-
Notifications
You must be signed in to change notification settings - Fork 0
/
run-console.js
318 lines (296 loc) · 10.3 KB
/
run-console.js
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
"use strict";
window.app = {};
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "run-code") {
console.log("run-code: ", message.data);
window.term.exec(message.data);
}
});
function sleep(s) {
return new Promise((resolve) => setTimeout(resolve, s));
}
async function restart() {
const body = $("body");
$(".terminal")[0].remove();
window.console_ready = initConsole();
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);
}
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;
}
}
async function initConsole() {
let indexURL = chrome.runtime.getURL("libs/");
const urlParams = new URLSearchParams(window.location.search);
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 🐍"
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();
term.resume();
$.terminal.syntax("python");
}
window.console_ready = initConsole();