-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
692 lines (638 loc) · 25.8 KB
/
index.html
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdn.jsdelivr.net/npm/jquery"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/jquery.terminal.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/unix_formatting.min.js"></script>
<script src="https://lib.imjoy.io/imjoy-loader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.terminal/js/prism.js"></script>
<script src="https://unpkg.com/[email protected]/components/prism-python.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/css/jquery.terminal.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism.css" rel="stylesheet" />
<!-- add icon -->
<link rel="icon" href="https://imjoy.io//static/icons/favicon-32x32.png" />
<!-- add title -->
<title>web-python-console</title>
<style>
:root {
--size: 1.4;
--font: Consolas;
}
.terminal {
--size: 1.5;
--color: rgba(255, 255, 255, 0.8);
}
.noblink {
--animation: terminal-none;
}
body {
background-color: black;
}
#loading {
display: inline-block;
width: 50px;
height: 50px;
position: fixed;
top: 50%;
left: 50%;
border: 3px solid rgba(172, 237, 255, 0.5);
border-radius: 50%;
border-top-color: #fff;
animation: spin 1s ease-in-out infinite;
-webkit-animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to {
-webkit-transform: rotate(360deg);
}
}
@-webkit-keyframes spin {
to {
-webkit-transform: rotate(360deg);
}
}
#menu-container {
position: absolute;
top: 3px;
right: 3px;
z-index: 100;
}
.window {
z-index: 101 !important;
min-height: 220px !important;
}
</style>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-ETFXPV2DFP"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-ETFXPV2DFP');
</script>
</head>
<body>
<div id="loading"></div>
<div id="menu-container"></div>
<div id="window-container" style="height:0px;"></div>
<script>
"use strict";
window.app = {};
function sleep(s) {
return new Promise((resolve) => setTimeout(resolve, s));
}
async function setupImJoyApp() {
const app = await loadImJoyBasicApp({
name: "web-python-console",
process_url_query: true,
show_window_title: false,
show_progress_bar: true,
show_empty_window: true,
menu_style: { position: "absolute", right: 0, top: "2px" },
window_style: {},
main_container: null,
menu_container: "menu-container",
window_manager_container: "window-container",
expose_api: true,
imjoy_api: {
async getConsole(caller, config) {
return createApi();
}
},
});
const imjoy_api = app.imjoy.api;
window.app.imjoy = imjoy_api;
const console = await createApi();
window.app.console = console;
// if you want to let users to load new plugins, add a menu item
app.addMenuItem({
label: "➕ Load Plugin",
callback() {
const uri = prompt(
`Please type a ImJoy plugin URL`,
"https://github.com/imjoy-team/imjoy-plugins/blob/master/repository/ImageAnnotator.imjoy.html"
);
if (uri) app.loadPlugin(uri);
},
});
app.addMenuItem({
label: "📝 Edit Code",
async callback() {
let plugin = null;
app.loadedPlugins.forEach((p) => {
if (p.config.name === "PyEditor") {
plugin = p;
}
});
if (!plugin) {
plugin = await app.loadPlugin(
"https://nanguage.github.io/web-python-console/python-editor.imjoy.html"
);
}
await app.runPlugin(plugin);
}
});
app.addMenuItem({
label: "📂 Mount Local Folder",
async callback() {
const mountPoint = prompt(
`Please type a mount point`,
"/mount_dir"
);
if (mountPoint) {
await mountNativeFs(mountPoint);
await imjoy_api.showMessage(`Mounted at ${mountPoint}`);
}
}
})
app.addMenuItem({
// restart
label: "🔄 Restart",
async callback() {
await restart();
},
})
return app;
}
async function restart() {
const body = $("body");
$(".terminal")[0].remove();
window.console_ready = initConsole(false);
await window.console_ready;
}
async function mountNativeFs(mountPoint = "/mount_dir") {
const pyodide = window.pyodide;
const dirHandle = await showDirectoryPicker();
if ((await dirHandle.queryPermission({ mode: "readwrite" })) !== "granted") {
if (
(await dirHandle.requestPermission({ mode: "readwrite" })) !== "granted"
) {
throw Error("Unable to read and write directory");
}
}
const nativefs = await pyodide.mountNativeFS(mountPoint, dirHandle);
}
async function createApi() {
function setup() {
console.log("web-python-console is ready.")
}
function echo(msg) {
const term = window.term;
term.echo(msg);
}
async function exec(code, show_code = true) {
const term = window.term;
code = code.replaceAll("\r\n", "\n");
await term.exec(code, !show_code);
}
function clear() {
const term = window.term;
term.clear();
}
async function getConsoleContent() {
const term = window.term;
const output = term.get_output();
return output;
}
function getVariable(name) {
const pyodide = window.pyodide;
const value = pyodide.globals.get(name);
const res = toImjoyObj(value);
return res;
}
function setVariable(name, value) {
const pyodide = window.pyodide;
const res = toPyObj(value);
pyodide.globals.set(name, res);
}
function mount_native_fs(mount_point = "/mount_dir") {
return mountNativeFs(mount_point);
}
async function consoleReady() {
await window.console_ready;
}
return {
_rintf: true,
setup: setup,
echo: echo,
exec: exec,
clear: clear,
restart: restart,
get_variable: getVariable,
set_variable: setVariable,
get_content: getConsoleContent,
mount_native_fs: mount_native_fs,
ready: consoleReady,
}
}
async function initImJoy() {
// start as an plugin
if (window.self !== window.top) {
const imjoyRPC = await loadImJoyRPC();
const imjoy_api = await imjoyRPC.setupRPC({ name: "web-python-console" });
window.app.imjoy = imjoy_api;
const console = await createApi();
window.app.console = console;
await imjoy_api.export(console)
} else {
// start as an standalone app
await setupImJoyApp();
}
}
function updateButtonLabel() {
$(".fa-home").map((_, el) => {
el.innerHTML = "Home";
});
$(".fa-arrow-left").map((_, el) => {
el.innerHTML = "Back";
});
$(".fa-arrow-right").map((_, el) => {
el.innerHTML = "Forward";
});
$(".fa-arrows").map((_, el) => {
el.innerHTML = "Pan";
});
$(".fa-search-plus").map((_, el) => {
el.innerHTML = "Zoom";
});
}
function toBool(value, default_value = false) {
if (value === undefined || value === null) return default_value;
if (typeof value === "boolean") return value;
if (typeof value === "number") return value !== 0;
if (typeof value === "string") {
switch (value.toLowerCase().trim()) {
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": case null: return false;
default: return Boolean(value);
}
}
}
function toDigits(i, digits) {
return i.toString().padStart(digits, "0");
}
async function runFile(url, showCode = true) {
const term = window.term;
const response = await fetch(url);
let text = await response.text();
text = text.replaceAll("\r\n", "\n");
text = "\n" + text;
const p = term.exec(text, !showCode);
await p;
}
function toJs(value) {
if (value instanceof pyodide.ffi.PyProxy) {
if (value instanceof pyodide.ffi.PyDict) {
let map = value.toJs();
const obj = {};
for (const [key, value] of map) {
obj[key] = toJs(value);
}
return obj;
} else {
return value.toJs();
}
} else {
return value;
}
}
class ImjoyApiWrapper {
constructor(imjoy_api) {
this.imjoy_api = imjoy_api;
Object.assign(this, imjoy_api);
this.getWindow = this.getWindowOveride;
this.createWindow = this.createWindowOveride;
this.loadPlugin = this.loadPluginOveride;
this.getPlugin = this.getPluginOveride;
}
async getWindowOveride(config) {
const window = await this.imjoy_api.getWindow(config);
const windowWrapper = new PluginWrapper(window);
return windowWrapper;
}
async createWindowOveride(config) {
const window = await this.imjoy_api.createWindow(config);
const windowWrapper = new PluginWrapper(window);
return windowWrapper;
}
async loadPluginOveride(config) {
const plugin = await this.imjoy_api.loadPlugin(config);
const pluginWrapper = new PluginWrapper(plugin);
return pluginWrapper;
}
async getPluginOveride(config) {
const plugin = await this.imjoy_api.getPlugin(config);
const pluginWrapper = new PluginWrapper(plugin);
return pluginWrapper;
}
async restart() {
await restart();
}
async insertHtml(htmlSrc, width = "100%", height = "400px") {
const term = window.term;
const encoded = encodeURIComponent(htmlSrc);
const iframe = document.createElement("iframe");
iframe.src = 'data:text/html;charset=utf-8,' + encoded;
iframe.style.width = width;
iframe.style.height = height;
iframe.style.resize = 'both'
iframe.style.overflow = 'auto'
term.echo(iframe);
}
async mountNativeFs(mountPoint = "/mount_dir") {
await mountNativeFs(mountPoint);
}
async openEditor() {
const plugin = await this.imjoy_api.loadPlugin(
"https://nanguage.github.io/web-python-console/python-editor.imjoy.html"
);
await plugin.run();
}
}
function toImjoyObj(obj) {
const pyodide = window.pyodide;
const imjoy_encode = pyodide.globals.get("imjoy_encode");
const res = toJs(imjoy_encode(obj));
return res;
}
function toPyObj(obj) {
const pyodide = window.pyodide;
const imjoy_decode = pyodide.globals.get("imjoy_decode");
const res = imjoy_decode(pyodide.toPy(obj));
return res;
}
class PluginWrapper {
constructor(plugin) {
Object.keys(plugin).forEach(key => {
if (typeof plugin[key] === 'function') {
this[key] = (...args) => {
const processedArgs = args.map(arg => toImjoyObj(arg));
const res = plugin[key](...processedArgs);
if (res instanceof Promise) {
return res.then(r => toPyObj(r));
} else {
return toPyObj(res);
}
};
} else {
this[key] = plugin[key];
}
});
}
}
async function initConsole(initIj = true) {
let indexURL = "https://cdn.jsdelivr.net/pyodide/v0.24.1/full/";
const urlParams = new URLSearchParams(window.location.search);
const buildParam = urlParams.get("build");
if (buildParam) {
if (["full", "debug", "pyc"].includes(buildParam)) {
indexURL = indexURL.replace(
"/full/",
"/" + urlParams.get("build") + "/",
);
} else {
console.warn(
'Invalid URL parameter: build="' +
buildParam +
'". Using default "full".',
);
}
}
const { loadPyodide } = await import(indexURL + "pyodide.mjs");
// to facilitate debugging
globalThis.loadPyodide = loadPyodide;
let term;
globalThis.pyodide = await loadPyodide({
stdin: () => {
let result = prompt();
echo(result);
return result;
},
});
let namespace = pyodide.globals.get("dict")();
pyodide.runPython(
`
import sys
from pyodide.ffi import to_js
from pyodide.console import PyodideConsole, repr_shorten, BANNER
import __main__
BANNER = "Welcome to the Pyodide terminal emulator 🐍\\nSupport control through ImJoy API.\\nSee https://github.com/Nanguage/imjoy-web-python-console for detail.\\n" + BANNER
pyconsole = PyodideConsole(__main__.__dict__)
import builtins
async def await_fut(fut):
res = await fut
if res is not None:
builtins._ = res
return to_js([res], depth=1)
def clear_console():
pyconsole.buffer = []
`,
{ globals: namespace },
);
let repr_shorten = namespace.get("repr_shorten");
let banner = namespace.get("BANNER");
let await_fut = namespace.get("await_fut");
let pyconsole = namespace.get("pyconsole");
let clear_console = namespace.get("clear_console");
const echo = (msg, ...opts) =>
term.echo(
msg
.replaceAll("]]", "]]")
.replaceAll("[[", "[["),
...opts,
);
namespace.destroy();
let ps1 = ">>> ",
ps2 = "... ";
async function lock() {
let resolve;
let ready = term.ready;
term.ready = new Promise((res) => (resolve = res));
await ready;
return resolve;
}
async function interpreter(command) {
let unlock = await lock();
term.pause();
// multiline should be split (useful when pasting)
let counter = 0;
const lines = command.split("\n");
for (const c of lines) {
counter++;
const escaped = c.replaceAll(/\u00a0/g, " ");
let fut = pyconsole.push(escaped);
term.set_prompt(fut.syntax_check === "incomplete" ? ps2 : ps1);
switch (fut.syntax_check) {
case "syntax-error":
term.error(fut.formatted_error.trimEnd());
continue;
case "incomplete":
continue;
case "complete":
break;
default:
throw new Error(`Unexpected type ${ty}`);
}
// In JavaScript, await automatically also awaits any results of
// awaits, so if an async function returns a future, it will await
// the inner future too. This is not what we want so we
// temporarily put it into a list to protect it.
let wrapped = await_fut(fut);
// complete case, get result / error and print it.
try {
const mplShow = escaped.includes("plt.show()");
let mplTarget = null;
if (mplShow) {
term.echo();
const outputs = $(".terminal-output")[0].children
mplTarget = outputs[outputs.length - 1]
document.pyodideMplTarget = mplTarget
}
// Real execution happens here.
let [value] = await wrapped;
if (mplShow) {
if (mplTarget) {
mplTarget.children[0].style.display = "none";
if (mplTarget.children.length > 1) {
mplTarget.children[1].removeAttribute("id")
}
}
updateButtonLabel();
}
if (value !== undefined) {
echo(
repr_shorten.callKwargs(value, {
separator: "\n<long output truncated>\n",
}),
);
}
if (value instanceof pyodide.ffi.PyProxy) {
value.destroy();
}
} catch (e) {
if (e.constructor.name === "PythonError") {
const message = fut.formatted_error || e.message;
let msg = "";
if (lines.length > 1) {
// print the error position in multiline mode
const limit = 3;
const maxDigits = (counter + limit).toString().length;
msg += `Error occred at line ${counter}:\n`;
msg += "----------------------------------------\n"
let i = 0;
for (const line of lines) {
i++;
if (i === counter) {
msg += toDigits(i, maxDigits) + ": " + line + " <-- Error here!" + "\n";
} else if ((i >= counter - limit) && (i <= counter + limit)) {
msg += toDigits(i, maxDigits) + ": " + line + "\n";
}
}
msg += "----------------------------------------\n"
}
msg += message.trimEnd();
term.error(msg);
break;
} else {
throw e;
}
} finally {
fut.destroy();
wrapped.destroy();
}
}
term.resume();
await sleep(10);
unlock();
}
term = $("body").terminal(interpreter, {
greetings: banner,
prompt: ps1,
completionEscape: false,
completion: function (command, callback) {
callback(pyconsole.complete(command).toJs()[0]);
},
keymap: {
"CTRL+C": async function (event, original) {
clear_console();
term.enter();
echo("KeyboardInterrupt");
term.set_command("");
term.set_prompt(ps1);
},
TAB: (event, original) => {
const command = term.before_cursor();
// Disable completion for whitespaces.
if (command.trim() === "") {
term.insert("\t");
return false;
}
return original(event);
},
},
});
window.term = term;
pyconsole.stdout_callback = (s) => echo(s, { newline: false });
pyconsole.stderr_callback = (s) => {
term.error(s.trimEnd());
};
term.ready = Promise.resolve();
pyodide._api.on_fatal = async (e) => {
if (e.name === "Exit") {
term.error(e);
term.error("Pyodide exited and can no longer be used.");
} else {
term.error(
"Pyodide has suffered a fatal error. Please report this to the Pyodide maintainers.",
);
term.error("The cause of the fatal error was:");
term.error(e);
term.error("Look in the browser console for more details.");
}
await term.ready;
term.pause();
await sleep(15);
term.pause();
};
const searchParams = new URLSearchParams(window.location.search);
if (searchParams.has("noblink")) {
$(".cmd-cursor").addClass("noblink");
}
document.pyodideMplTarget = $(".terminal-wrapper")[0]
term.echo("--- Initializing ---")
term.pause();
if (initIj) {
await initImJoy();
}
term.resume();
const installRpc = toBool(searchParams.get("install_rpc"), true);
if (installRpc) {
await term.exec("import micropip; await micropip.install('imjoy-rpc')", true)
const currentUrl = new URL(window.location.href);
const libUrl = currentUrl.origin + currentUrl.pathname + "/imjoy_encode.py";
await runFile(libUrl, false)
pyodide.globals.set("api", new ImjoyApiWrapper(window.app.imjoy));
}
const showCode = toBool(urlParams.get("show_code"), true);
const code = urlParams.get("code");
if (code) {
term.echo("--- Running code ---")
$.terminal.syntax('python')
await term.exec(code, !showCode);
} else {
const file = urlParams.get("file");
if (file) {
term.echo(`--- Running ${file} ---`)
$.terminal.syntax('python')
await runFile(file, showCode);
} else {
$.terminal.syntax('python')
}
}
}
window.console_ready = initConsole();
</script>
</body>
</html>