Debian Codegraph @

Platforms/emscripten/web_example/index.html

raw
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta name="author" content="Katie Bell, Adam Hartz">
8 <meta name="description" content="Simple REPL for Python WASM">
9 <title>wasm-python terminal</title>
10 <link
11 rel="stylesheet"
12 href="https://unpkg.com/[email protected]/css/xterm.css"
13 crossorigin
14 integrity="sha384-4eEEn/eZgVHkElpKAzzPx/Kow/dTSgFk1BNe+uHdjHa+NkZJDh5Vqkq31+y7Eycd"
15 >
16 <style>
17 body {
18 font-family: arial;
19 max-width: 800px;
20 margin: 0 auto;
21 }
22 #editor {
23 padding: 5px;
24 border: 1px solid black;
25 width: 100%;
26 height: 300px;
27 }
28 #info {
29 padding-top: 20px;
30 }
31 .error {
32 border: 1px solid red;
33 background-color: #ffd9d9;
34 padding: 5px;
35 margin-top: 20px;
36 }
37 .button-container {
38 display: flex;
39 justify-content: end;
40 height: 50px;
41 align-items: center;
42 gap: 10px;
43 }
44 button {
45 padding: 6px 18px;
46 }
47 </style>
48 <script
49 src="https://unpkg.com/[email protected]/lib/xterm.js"
50 crossorigin
51 integrity="sha384-yYdNmem1ioP5Onm7RpXutin5A8TimLheLNQ6tnMi01/ZpxXdAwIm2t4fJMx1Djs+"
52 ></script>
53 <script
54 src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.43.1/ace.js"
55 crossorigin
56 integrity="sha512-kmA5vhcxOkZI0ReiKJMGNb8/KKbgbExIlnt6aXuPtl86AgHBEi6OHHOz2wsTazBDGZKxe7fmiE+pIuZJQks4+A=="
57 ></script>
58 <script type="module">
59 const _magic_ctrlc_string = "__WASM_REPL_CTRLC_" + (Date.now()) + "__";
60 class WorkerManager {
61 constructor(
62 workerURL,
63 standardIO,
64 readyCallBack,
65 finishedCallback,
66 ) {
67 this.workerURL = workerURL;
68 this.worker = null;
69 this.standardIO = standardIO;
70 this.readyCallBack = readyCallBack;
71 this.finishedCallback = finishedCallback;
72
73 this.initialiseWorker();
74 }
75
76 async initialiseWorker() {
77 if (!this.worker) {
78 this.worker = new Worker(this.workerURL, {
79 type: "module",
80 });
81 this.worker.addEventListener(
82 "message",
83 this.handleMessageFromWorker,
84 );
85 }
86 }
87
88 async run(options) {
89 this.worker.postMessage({
90 type: "run",
91 args: options.args || [],
92 files: options.files || {},
93 });
94 }
95
96 reset() {
97 if (this.worker) {
98 this.worker.terminate();
99 this.worker = null;
100 }
101 this.standardIO.message("Worker process terminated.");
102 this.initialiseWorker();
103 }
104
105 handleStdinData(inputValue) {
106 if (this.stdinbuffer && this.stdinbufferInt) {
107 let startingIndex = 1;
108 if (this.stdinbufferInt[0] > 0) {
109 startingIndex = this.stdinbufferInt[0];
110 }
111 const data = new TextEncoder().encode(inputValue);
112 data.forEach((value, index) => {
113 this.stdinbufferInt[startingIndex + index] = value;
114 });
115
116 this.stdinbufferInt[0] =
117 startingIndex + data.length - 1;
118 Atomics.notify(this.stdinbufferInt, 0, 1);
119 }
120 }
121
122 handleMessageFromWorker = (event) => {
123 const type = event.data.type;
124 if (type === "ready") {
125 this.readyCallBack();
126 } else if (type === "stdout") {
127 this.standardIO.stdout(event.data.stdout);
128 } else if (type === "stderr") {
129 this.standardIO.stderr(event.data.stderr);
130 } else if (type === "stdin") {
131 // Leave it to the terminal to decide whether to chunk it into lines
132 // or send characters depending on the use case.
133 this.stdinbuffer = event.data.buffer;
134 this.stdinbufferInt = new Int32Array(this.stdinbuffer);
135 this.standardIO.stdin().then((inputValue) => {
136 this.handleStdinData(inputValue);
137 });
138 } else if (type === "finished") {
139 this.standardIO.message(
140 `Exited with status: ${event.data.returnCode}`,
141 );
142 this.finishedCallback();
143 }
144 };
145 }
146
147 class WasmTerminal {
148 constructor() {
149 try {
150 this.history = JSON.parse(sessionStorage.getItem('__python_wasm_repl.history'));
151 this.historyBuffer = this.history.slice();
152 } catch(e) {
153 this.history = [];
154 this.historyBuffer = [];
155 }
156 this.reset();
157
158 this.xterm = new Terminal({
159 scrollback: 10000,
160 fontSize: 14,
161 theme: { background: "#1a1c1f" },
162 cols: 100,
163 });
164
165 this.xterm.onKey((keyEvent) => {
166 // Fix for iOS Keyboard Jumping on space
167 if (keyEvent.key === " ") {
168 keyEvent.domEvent.preventDefault();
169 }
170 });
171
172 this.xterm.onData(this.handleTermData);
173 }
174
175 reset() {
176 this.inputBuffer = new BufferQueue();
177 this.input = "";
178 this.resolveInput = null;
179 this.activeInput = false;
180 this.inputStartCursor = null;
181
182 this.cursorPosition = 0;
183 this.historyIndex = -1;
184 this.beforeHistoryNav = "";
185 }
186
187 open(container) {
188 this.xterm.open(container);
189 }
190
191 handleTermData = (data) => {
192 const ord = data.charCodeAt(0);
193 data = data.replace(/\r(?!\n)/g, "\n"); // Convert lone CRs to LF
194
195 // Handle pasted data
196 if (data.length > 1 && data.includes("\n")) {
197 let alreadyWrittenChars = 0;
198 // If line already had data on it, merge pasted data with it
199 if (this.input != "") {
200 this.inputBuffer.addData(this.input);
201 alreadyWrittenChars = this.input.length;
202 this.input = "";
203 }
204 this.inputBuffer.addData(data);
205 // If input is active, write the first line
206 if (this.activeInput) {
207 let line = this.inputBuffer.nextLine();
208 this.writeLine(line.slice(alreadyWrittenChars));
209 this.resolveInput(line);
210 this.activeInput = false;
211 }
212 // When input isn't active, add to line buffer
213 } else if (!this.activeInput) {
214 // Skip non-printable characters
215 if (!(ord === 0x1b || ord == 0x7f || ord < 32)) {
216 this.inputBuffer.addData(data);
217 }
218 // TODO: Handle more escape sequences?
219 } else if (ord === 0x1b) {
220 // Handle special characters
221 switch (data.slice(1)) {
222 case "[A": // up
223 this.historyBack();
224 break;
225 case "[B": // down
226 this.historyForward();
227 break;
228 case "[C": // right
229 this.cursorRight();
230 break;
231 case "[D": // left
232 this.cursorLeft();
233 break;
234 case "[H": // home key
235 this.cursorHome(true);
236 break;
237 case "[F": // end key
238 this.cursorEnd(true);
239 break;
240 case "[3~": // delete key
241 this.deleteAtCursor();
242 break;
243 default:
244 break;
245 }
246 } else if (ord < 32 || ord === 0x7f) {
247 switch (data) {
248 case "\x0c": // CTRL+L
249 this.clear();
250 break;
251 case "\n": // ENTER
252 case "\x0a": // CTRL+J
253 case "\x0d": // CTRL+M
254 this.resolveInput(
255 this.input + this.writeLine("\n"),
256 );
257 this.input = "";
258 this.cursorPosition = 0;
259 this.activeInput = false;
260 break;
261 case "\x03": // CTRL+C
262 this.input = "";
263 this.cursorPosition = 0;
264 this.historyIndex = -1;
265 this.resolveInput(_magic_ctrlc_string + "\n");
266 break;
267 case "\x09": // TAB
268 this.handleTab();
269 break;
270 case "\x7F": // BACKSPACE
271 case "\x08": // CTRL+H
272 this.handleCursorErase(true);
273 break;
274 case "\x04": // CTRL+D
275 // Send empty input
276 if (this.input === "") {
277 this.resolveInput("");
278 this.cursorPosition = 0;
279 this.activeInput = false;
280 }
281 }
282 } else {
283 this.handleCursorInsert(data);
284 this.updateHistory();
285 }
286 };
287
288 clearLine() {
289 this.xterm.write("\x1b[K");
290 }
291
292 writeLine(line) {
293 this.xterm.write(line.slice(0, -1));
294 this.xterm.write("\r\n");
295 return line;
296 }
297
298 handleCursorInsert(data) {
299 const trailing = this.input.slice(this.cursorPosition);
300 this.input =
301 this.input.slice(0, this.cursorPosition) +
302 data +
303 trailing;
304 this.cursorPosition += data.length;
305 this.xterm.write(data);
306 if (trailing.length !== 0) {
307 this.xterm.write(trailing);
308 this.xterm.write("\x1b[" + trailing.length + "D");
309 }
310 this.updateHistory();
311 }
312
313 handleTab() {
314 // handle tabs: from the current position, add spaces until
315 // this.cursorPosition is a multiple of 4.
316 const prefix = this.input.slice(0, this.cursorPosition);
317 const suffix = this.input.slice(this.cursorPosition);
318 const count = 4 - (this.cursorPosition % 4);
319 const toAdd = " ".repeat(count);
320 this.input = prefix + toAdd + suffix;
321 this.cursorHome(false);
322 this.clearLine();
323 this.xterm.write(this.input);
324 if (suffix) {
325 this.xterm.write("\x1b[" + suffix.length + "D");
326 }
327 this.cursorPosition += count;
328 this.updateHistory();
329 }
330
331 handleCursorErase() {
332 // Don't delete past the start of input
333 if (
334 this.xterm.buffer.active.cursorX <=
335 this.inputStartCursor
336 ) {
337 return;
338 }
339 const trailing = this.input.slice(this.cursorPosition);
340 this.input =
341 this.input.slice(0, this.cursorPosition - 1) + trailing;
342 this.cursorLeft();
343 this.clearLine();
344 if (trailing.length !== 0) {
345 this.xterm.write(trailing);
346 this.xterm.write("\x1b[" + trailing.length + "D");
347 }
348 this.updateHistory();
349 }
350
351 deleteAtCursor() {
352 if (this.cursorPosition < this.input.length) {
353 const trailing = this.input.slice(
354 this.cursorPosition + 1,
355 );
356 this.input =
357 this.input.slice(0, this.cursorPosition) + trailing;
358 this.clearLine();
359 if (trailing.length !== 0) {
360 this.xterm.write(trailing);
361 this.xterm.write("\x1b[" + trailing.length + "D");
362 }
363 this.updateHistory();
364 }
365 }
366
367 cursorRight() {
368 if (this.cursorPosition < this.input.length) {
369 this.cursorPosition += 1;
370 this.xterm.write("\x1b[C");
371 }
372 }
373
374 cursorLeft() {
375 if (this.cursorPosition > 0) {
376 this.cursorPosition -= 1;
377 this.xterm.write("\x1b[D");
378 }
379 }
380
381 cursorHome(updatePosition) {
382 if (this.cursorPosition > 0) {
383 this.xterm.write("\x1b[" + this.cursorPosition + "D");
384 if (updatePosition) {
385 this.cursorPosition = 0;
386 }
387 }
388 }
389
390 cursorEnd() {
391 if (this.cursorPosition < this.input.length) {
392 this.xterm.write(
393 "\x1b[" +
394 (this.input.length - this.cursorPosition) +
395 "C",
396 );
397 this.cursorPosition = this.input.length;
398 }
399 }
400
401 updateHistory() {
402 if (this.historyIndex !== -1) {
403 this.historyBuffer[this.historyIndex] = this.input;
404 } else {
405 this.beforeHistoryNav = this.input;
406 }
407 }
408
409 historyBack() {
410 if (this.history.length === 0) {
411 return;
412 } else if (this.historyIndex === -1) {
413 // we're not currently navigating the history; store
414 // the current command and then look at the end of our
415 // history buffer
416 this.beforeHistoryNav = this.input;
417 this.historyIndex = this.history.length - 1;
418 } else if (this.historyIndex > 0) {
419 this.historyIndex -= 1;
420 }
421 this.input = this.historyBuffer[this.historyIndex];
422 this.cursorHome(false);
423 this.clearLine();
424 this.xterm.write(this.input);
425 this.cursorPosition = this.input.length;
426 }
427
428 historyForward() {
429 if (this.history.length === 0 || this.historyIndex === -1) {
430 // we're not currently navigating the history; NOP.
431 return;
432 } else if (this.historyIndex < this.history.length - 1) {
433 this.historyIndex += 1;
434 this.input = this.historyBuffer[this.historyIndex];
435 } else if (this.historyIndex == this.history.length - 1) {
436 // we're coming back from the last history value; reset
437 // the input to whatever it was when we started going
438 // through the history
439 this.input = this.beforeHistoryNav;
440 this.historyIndex = -1;
441 }
442 this.cursorHome(false);
443 this.clearLine();
444 this.xterm.write(this.input);
445 this.cursorPosition = this.input.length;
446 }
447
448 prompt = async () => {
449 this.activeInput = true;
450 // Hack to allow stdout/stderr to finish before we figure out where input starts
451 setTimeout(() => {
452 this.inputStartCursor =
453 this.xterm.buffer.active.cursorX;
454 }, 1);
455 // If line buffer has a line ready, send it immediately
456 if (this.inputBuffer.hasLineReady()) {
457 return new Promise((resolve, reject) => {
458 resolve(
459 this.writeLine(this.inputBuffer.nextLine()),
460 );
461 this.activeInput = false;
462 });
463 // If line buffer has an incomplete line, use it for the active line
464 } else if (this.inputBuffer.lastLineIsIncomplete()) {
465 // Hack to ensure cursor input start doesn't end up after user input
466 setTimeout(() => {
467 this.handleCursorInsert(
468 this.inputBuffer.nextLine()
469 );
470 }, 1);
471 }
472 return new Promise((resolve, reject) => {
473 this.resolveInput = (value) => {
474 if (
475 value.replace(/\s/g, "").length != 0 &&
476 value != _magic_ctrlc_string + "\n"
477 ) {
478 if (this.historyIndex !== -1) {
479 this.historyBuffer[this.historyIndex] =
480 this.history[this.historyIndex];
481 }
482 this.history.push(value.slice(0, -1));
483 this.historyBuffer.push(value.slice(0, -1));
484 this.historyIndex = -1;
485 this.cursorPosition = 0;
486 try {
487 sessionStorage.setItem('__python_wasm_repl.history', JSON.stringify(this.history));
488 } catch(e) {
489 }
490 }
491 resolve(value);
492 };
493 });
494 };
495
496 clear() {
497 this.xterm.clear();
498 }
499
500 print(charCode) {
501 let array = [charCode];
502 if (charCode == 10) {
503 array = [13, 10]; // Replace \n with \r\n
504 }
505 this.xterm.write(new Uint8Array(array));
506 }
507 }
508
509 class BufferQueue {
510 constructor(xterm) {
511 this.buffer = [];
512 }
513
514 isEmpty() {
515 return this.buffer.length == 0;
516 }
517
518 lastLineIsIncomplete() {
519 return (
520 !this.isEmpty() &&
521 !this.buffer[this.buffer.length - 1].endsWith("\n")
522 );
523 }
524
525 hasLineReady() {
526 return !this.isEmpty() && this.buffer[0].endsWith("\n");
527 }
528
529 addData(data) {
530 let lines = data.match(/.*(\n|$)/g);
531 if (this.lastLineIsIncomplete()) {
532 this.buffer[this.buffer.length - 1] += lines.shift();
533 }
534 for (let line of lines) {
535 this.buffer.push(line);
536 }
537 }
538
539 nextLine() {
540 return this.buffer.shift();
541 }
542 }
543
544 const runButton = document.getElementById("run");
545 const replButton = document.getElementById("repl");
546 const stopButton = document.getElementById("stop");
547 const clearButton = document.getElementById("clear");
548
549 window.onload = () => {
550 const terminal = new WasmTerminal();
551 terminal.open(document.getElementById("terminal"));
552
553 const stdio = {
554 stdout: (charCode) => {
555 terminal.print(charCode);
556 },
557 stderr: (charCode) => {
558 terminal.print(charCode);
559 },
560 stdin: async () => {
561 return await terminal.prompt();
562 },
563 message: (text) => {
564 terminal.writeLine(`\r\n${text}\r\n`);
565 },
566 };
567
568 const programRunning = (isRunning) => {
569 if (isRunning) {
570 replButton.setAttribute("disabled", true);
571 runButton.setAttribute("disabled", true);
572 stopButton.removeAttribute("disabled");
573 } else {
574 replButton.removeAttribute("disabled");
575 runButton.removeAttribute("disabled");
576 stopButton.setAttribute("disabled", true);
577 }
578 };
579
580 runButton.addEventListener("click", (e) => {
581 terminal.clear();
582 terminal.reset(); // reset the history
583 programRunning(true);
584 const code = editor.getValue();
585 pythonWorkerManager.run({
586 args: ["main.py"],
587 files: { "main.py": code },
588 });
589 });
590
591 replButton.addEventListener("click", (e) => {
592 terminal.clear();
593 terminal.reset(); // reset the history
594 const REPL = `
595 class WASMREPLKeyboardInterrupt(KeyboardInterrupt):
596 pass
597
598 import sys
599 import code
600 import builtins
601
602 def _interrupt_aware_input(prompt=''):
603 line = builtins.input(prompt)
604 if line.strip() == "${_magic_ctrlc_string}":
605 raise KeyboardInterrupt()
606 return line
607
608 cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
609 banner = f'Python {sys.version} on {sys.platform}\\n{cprt}'
610
611 code.interact(banner=banner, readfunc=_interrupt_aware_input, exitmsg='')
612 `;
613 programRunning(true);
614 pythonWorkerManager.run({ args: ["-c", REPL], files: {} });
615 });
616
617 stopButton.addEventListener("click", (e) => {
618 programRunning(false);
619 pythonWorkerManager.reset();
620 });
621
622 clearButton.addEventListener("click", (e) => {
623 terminal.clear();
624 });
625
626 const readyCallback = () => {
627 replButton.removeAttribute("disabled");
628 runButton.removeAttribute("disabled");
629 clearButton.removeAttribute("disabled");
630 };
631
632 const finishedCallback = () => {
633 programRunning(false);
634 pythonWorkerManager.reset();
635 };
636
637 const pythonWorkerManager = new WorkerManager(
638 "./python.worker.mjs",
639 stdio,
640 readyCallback,
641 finishedCallback,
642 );
643 };
644 var editor;
645 document.addEventListener("DOMContentLoaded", () => {
646 editor = ace.edit("editor");
647 editor.session.setMode("ace/mode/python");
648 });
649 </script>
650 </head>
651 <body>
652 <div id="repldemo">
653 <h1>Simple REPL for Python WASM</h1>
654 <div id="editor">print('Welcome to WASM!')</div>
655 <div class="button-container">
656 <button id="run" disabled>Run code</button>
657 <button id="repl" disabled>Start REPL</button>
658 <button id="stop" disabled>Stop</button>
659 <button id="clear" disabled>Clear</button>
660 </div>
661 <div id="terminal"></div>
662 <div id="info">
663 The simple REPL provides a limited Python experience in the
664 browser.
665 <a
666 href="https://github.com/python/cpython/blob/main/Platforms/emscripten/README.md"
667 >
668 Platforms/emscripten/README.md
669 </a>
670 contains a list of known limitations and issues. Networking,
671 subprocesses, and threading are not available.
672 </div>
673 </div>
674 <div id="buffererror" class="error" style="display: none">
675 <p>
676 <code>SharedArrayBuffer</code>, which is required for this demo,
677 is not available in your browser environment. One common cause
678 of this failure is loading <code>index.html</code> directly in
679 your browser instead of using <code>server.py</code> as
680 described in
681 <a
682 href="https://github.com/python/cpython/blob/main/Platforms/emscripten/README.md#the-web-example"
683 >
684 Platforms/emscripten/README.md
685 </a>.
686 </p>
687 <p>
688 For more details about security requirements for
689 <code>SharedArrayBuffer</code>, see
690 <a
691 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements"
692 >this MDN page</a
693 >.
694 </p>
695 <script>
696 if (typeof SharedArrayBuffer === 'undefined') {
697 document.getElementById('repldemo').style.display = 'none';
698 document.getElementById('buffererror').style.display = 'block';
699 }
700 </script>
701 </div>
702 </body>
703 </html>