Debian Codegraph @

Platforms/emscripten/web_example_pyrepl_jspi/src.mjs

raw
1 // Much of this is adapted from here:
2 // https://github.com/mame/xterm-pty/blob/main/emscripten-pty.js
3 // Thanks to xterm-pty for making this possible!
4
5 import createEmscriptenModule from "./python.mjs";
6 import { openpty } from "https://unpkg.com/xterm-pty/index.mjs";
7 import "https://unpkg.com/@xterm/xterm/lib/xterm.js";
8
9 var term = new Terminal();
10 term.open(document.getElementById("terminal"));
11 const { master, slave: PTY } = openpty();
12 term.loadAddon(master);
13 globalThis.PTY = PTY;
14
15 async function setupStdlib(Module) {
16 const versionInt = Module.HEAPU32[Module._Py_Version >>> 2];
17 const major = (versionInt >>> 24) & 0xff;
18 const minor = (versionInt >>> 16) & 0xff;
19 // Prevent complaints about not finding exec-prefix by making a lib-dynload directory
20 Module.FS.mkdirTree(`/lib/python${major}.${minor}/lib-dynload/`);
21 const resp = await fetch(`python${major}.${minor}.zip`);
22 const stdlibBuffer = await resp.arrayBuffer();
23 Module.FS.writeFile(
24 `/lib/python${major}${minor}.zip`,
25 new Uint8Array(stdlibBuffer),
26 { canOwn: true },
27 );
28 }
29
30 const tty_ops = {
31 ioctl_tcgets: () => {
32 const termios = PTY.ioctl("TCGETS");
33 const data = {
34 c_iflag: termios.iflag,
35 c_oflag: termios.oflag,
36 c_cflag: termios.cflag,
37 c_lflag: termios.lflag,
38 c_cc: termios.cc,
39 };
40 return data;
41 },
42
43 ioctl_tcsets: (_tty, _optional_actions, data) => {
44 PTY.ioctl("TCSETS", {
45 iflag: data.c_iflag,
46 oflag: data.c_oflag,
47 cflag: data.c_cflag,
48 lflag: data.c_lflag,
49 cc: data.c_cc,
50 });
51 return 0;
52 },
53
54 ioctl_tiocgwinsz: () => PTY.ioctl("TIOCGWINSZ").reverse(),
55
56 get_char: () => {
57 throw new Error("Should not happen");
58 },
59 put_char: () => {
60 throw new Error("Should not happen");
61 },
62
63 fsync: () => {},
64 };
65
66 const POLLIN = 1;
67 const POLLOUT = 4;
68
69 const waitResult = {
70 READY: 0,
71 SIGNAL: 1,
72 TIMEOUT: 2,
73 };
74
75 function onReadable() {
76 var handle;
77 var promise = new Promise((resolve) => {
78 handle = PTY.onReadable(() => resolve(waitResult.READY));
79 });
80 return [promise, handle];
81 }
82
83 function onSignal() {
84 // TODO: signal handling
85 var handle = { dispose() {} };
86 var promise = new Promise((resolve) => {});
87 return [promise, handle];
88 }
89
90 function onTimeout(timeout) {
91 var id;
92 var promise = new Promise((resolve) => {
93 if (timeout > 0) {
94 id = setTimeout(resolve, timeout, waitResult.TIMEOUT);
95 }
96 });
97 var handle = {
98 dispose() {
99 if (id) {
100 clearTimeout(id);
101 }
102 },
103 };
104 return [promise, handle];
105 }
106
107 async function waitForReadable(timeout) {
108 let p1, p2, p3;
109 let h1, h2, h3;
110 try {
111 [p1, h1] = onReadable();
112 [p2, h2] = onTimeout(timeout);
113 [p3, h3] = onSignal();
114 return await Promise.race([p1, p2, p3]);
115 } finally {
116 h1.dispose();
117 h2.dispose();
118 h3.dispose();
119 }
120 }
121
122 const FIONREAD = 0x541b;
123
124 const tty_stream_ops = {
125 async readAsync(stream, buffer, offset, length, pos /* ignored */) {
126 let readBytes = PTY.read(length);
127 if (length && !readBytes.length) {
128 const status = await waitForReadable(-1);
129 if (status === waitResult.READY) {
130 readBytes = PTY.read(length);
131 } else {
132 throw new Error("Not implemented");
133 }
134 }
135 buffer.set(readBytes, offset);
136 return readBytes.length;
137 },
138
139 write: (stream, buffer, offset, length) => {
140 // Note: default `buffer` is for some reason `HEAP8` (signed), while we want unsigned `HEAPU8`.
141 buffer = new Uint8Array(
142 buffer.buffer,
143 buffer.byteOffset,
144 buffer.byteLength,
145 );
146 const toWrite = Array.from(buffer.subarray(offset, offset + length));
147 PTY.write(toWrite);
148 return length;
149 },
150
151 async pollAsync(stream, timeout) {
152 if (!PTY.readable && timeout) {
153 await waitForReadable(timeout);
154 }
155 return (PTY.readable ? POLLIN : 0) | (PTY.writable ? POLLOUT : 0);
156 },
157 ioctl(stream, request, varargs) {
158 if (request === FIONREAD) {
159 const res = PTY.fromLdiscToUpperBuffer.length;
160 Module.HEAPU32[varargs / 4] = res;
161 return 0;
162 }
163 throw new Error("Unimplemented ioctl request");
164 },
165 };
166
167 async function setupStdio(Module) {
168 Object.assign(Module.TTY.default_tty_ops, tty_ops);
169 Object.assign(Module.TTY.stream_ops, tty_stream_ops);
170 }
171
172 const emscriptenSettings = {
173 async preRun(Module) {
174 Module.addRunDependency("pre-run");
175 Module.ENV.TERM = "xterm-256color";
176 // Uncomment next line to turn on tracing (messages go to browser console).
177 // Module.ENV.PYREPL_TRACE = "1";
178
179 // Leak module so we can try to show traceback if we crash on startup
180 globalThis.Module = Module;
181 await Promise.all([setupStdlib(Module), setupStdio(Module)]);
182 Module.removeRunDependency("pre-run");
183 },
184 };
185
186 try {
187 await createEmscriptenModule(emscriptenSettings);
188 } catch (e) {
189 // Show JavaScript exception and traceback
190 console.warn(e);
191 // Show Python exception and traceback
192 Module.__Py_DumpTraceback(2, Module._PyGILState_GetThisThreadState());
193 process.exit(1);
194 }