-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython.js
More file actions
70 lines (61 loc) · 2.06 KB
/
python.js
File metadata and controls
70 lines (61 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const defaultPyodideUrl = "https://cdn.jsdelivr.net/pyodide/v0.29.4/full/pyodide.js";
let _apps = {};
let _documentUrl = document.URL;
// This method is called from Dart on backend.connect()
// dartOnMessage is called on backend.onMessage
// it accepts "data" of type JSUint8Array
globalThis.jsConnect = async function(appId, args, dartOnMessage) {
let app = {
"dartOnMessage": dartOnMessage
};
console.log(`Starting up Python worker: ${appId}, args: ${args}`);
_apps[appId] = app;
app.worker = new Worker("python-worker.js");
var error;
app.worker.onmessage = (event) => {
if (typeof event.data === "string") {
if (event.data != "initialized") {
error = event.data;
}
app.onPythonInitialized();
} else {
app.dartOnMessage(event.data);
}
};
let pythonInitialized = new Promise((resolveCallback) => app.onPythonInitialized = resolveCallback);
// initialize worker
app.worker.postMessage({
pyodideUrl: flet.noCdn ? flet.pyodideUrl : defaultPyodideUrl,
args: args,
documentUrl: _documentUrl,
appPackageUrl: flet.appPackageUrl,
micropipIncludePre: flet.micropipIncludePre,
pythonModuleName: flet.pythonModuleName
});
await pythonInitialized;
if (error) {
console.log("Python worker init error:", error);
throw error;
} else {
console.log(`Python worker initialized: ${appId}`);
}
}
// Called from Dart on backend.send
// data is a message serialized to JSUint8Array
globalThis.jsSend = async function(appId, data) {
if (appId in _apps) {
const app = _apps[appId];
app.worker.postMessage(data);
}
}
// Called from Dart on channel.disconnect
globalThis.jsDisconnect = async function(appId) {
if (appId in _apps) {
console.log(`Terminating Python worker: ${appId}`);
const app = _apps[appId];
delete _apps[appId];
app.worker.terminate();
app.worker.onmessage = null;
app.worker.onerror = null;
}
}