forked from esperanc/Py5Script
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.html
More file actions
871 lines (753 loc) · 41.1 KB
/
runner.html
File metadata and controls
871 lines (753 loc) · 41.1 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
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Runner</title>
<link rel="stylesheet" href="https://pyscript.net/releases/2024.1.1/core.css">
<script type="module" src="https://pyscript.net/releases/2024.1.1/core.js"></script>
<script src="https://cdn.jsdelivr.net/npm/p5@1.11.11/lib/p5.min.js"></script>
<style>
body { margin: 0; padding: 0; overflow: hidden; }
main { display: flex; justify-content: center; align-items: center; height: 100vh; }
canvas { display: block; }
</style>
</head>
<body>
<script>
// Catch global JS errors (including PythonError from Pyodide)
window.addEventListener('error', function(event) {
let message = "";
if (event.error && event.error.message) {
message = event.error.message;
} else {
message = event.message || String(event);
}
// Ignore duplicate SyntaxErrors (handled by Python logic)
if (message && message.includes('SyntaxError:')) return;
const msg = { type: 'error', message: message };
window.parent.postMessage(msg, '*');
});
// Catch unhandled promise rejections (often used by async Pyodide)
window.addEventListener('unhandledrejection', function(event) {
const message = (event.reason ? event.reason.message || event.reason : "Unknown");
if (message && message.toString().includes('SyntaxError:')) return;
const msg = { type: 'error', message: "Unhandled Rejection: " + message };
window.parent.postMessage(msg, '*');
});
// Loopback message listener for standalone mode
window.addEventListener('message', (event) => {
if (window.parent === window) {
const data = event.data;
if (data && data.type === 'print') {
console.log(data.message);
} else if (data && data.type === 'error') {
if (data.filename) {
console.error(`${data.filename}:${data.line} - ${data.message}`);
} else {
console.error(data.message);
}
}
}
});
// Intercept console.error (used by p5.js for shader/internal errors)
(function() {
const originalError = console.error;
console.error = function(...args) {
originalError.apply(console, args);
// Convert args to string message
const message = args.map(arg => String(arg)).join(' ');
// Post to IDE
window.parent.postMessage({ type: 'error', message: message }, '*');
// Stop Sketch if it's running (prevents infinite error loops)
// We access the global P5 instance from the Python side if possible,
// but simpler to check the global variable directly if exposed to JS or just known.
// Logic: "P5" is defined in Python `globals()`, not necessarily window.
// BUT, we can try to stop p5 via the instance assigned to window.p5 if we can reach it.
// Actually, the instance is inside `sketch` function scope.
// However, `P5` is global in Python.
// Let's use a try-catch to call back into Python? Or just accept that `noLoop` might be hard to reach from here?
// Wait, we can't easily reach Python state from this JS block.
// BUT we can check `window.p5` which is the constructor. The instance?
// We don't have a global reference to the p5 instance in JS scope (it's in Python).
// Workaround: We can post a message that *Python* listens to? No.
// We can't easily stop it from here unless we exposed the instance to window.
// Let's rely on the user manually stopping?
// NO, user requested "stop the execution".
// Solution: In `sketch()` function (Python), we set `js.window.currentP5 = p`.
if (window.currentP5) {
try { window.currentP5.noLoop(); } catch(e){}
}
};
})();
</script>
<script type="py">
import js
import ast
import textwrap
import sys
import json
import base64
import asyncio
from pyodide.ffi import create_proxy, to_js
# Global P5 instance
P5 = None
# Expose global p5 class
p5 = js.p5
class StdoutCatcher:
def write(self, text):
msg = {"type": "print", "message": text}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
def flush(self):
pass
class StderrCatcher:
def write(self, text):
# Avoid Duplicate SyntaxError messages (handled explicitly by sketch logic)
if text.strip().startswith('SyntaxError:'):
return
msg = {"type": "error", "message": text}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
def flush(self):
pass
# Install Catchers globally immediately
sys.stdout = StdoutCatcher()
sys.stderr = StderrCatcher()
def camel_to_snake(name):
if name.isupper(): return name
import re
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
class P5Transformer(ast.NodeTransformer):
custom_aliases = {}
def __init__(self, user_defined, case_mode='both'):
# Use prototype to get properties since instance isn't created yet
self.p5_props = set(dir(js.p5.prototype))
# Add common instance properties that aren't on the prototype
self.p5_props.update([
'width', 'height', 'frameCount', 'mouseX', 'mouseY', 'pmouseX', 'pmouseY',
'mouseIsPressed', 'mouseButton', 'keyIsPressed', 'key', 'keyCode',
'pixels', 'touches', 'deltaTime', 'focused'
])
self.user_defined = user_defined
self.case_mode = case_mode
self.scope_stack = []
# Explicitly exclude 'print' and other builtins/globals
# 'label' is often leaked from p5.prototype (as part of internal DOM attributes?) causing confusion.
exclusions = {
'print', 'open', 'exit', 'quit', 'help', 'asset', 'label',
'map', 'set', 'filter', 'min', 'max', 'abs', 'round', 'pow', 'sum',
'random', 'shuffle', 'sort', 'reverse', 'append', 'splice', 'subset',
'join', 'split', 'shorten', 'concat'
}
self.p5_props -= exclusions
self.p5_props.add('drawingContext')
# Build Mapping: snake_case -> camelCase
# Only needed if case_mode is 'snake' or 'both'
self.snake_map = {}
if self.case_mode in ['snake', 'both']:
for prop in self.p5_props:
snake = camel_to_snake(prop)
# Ensure we don't map back to an excluded builtin (e.g. OPEN -> open)
if snake != prop and snake not in exclusions:
self.snake_map[snake] = prop
def resolve_p5_name(self, name):
# 0. Check Scope Stack (Local shadowing)
for scope in self.scope_stack:
if name in scope:
return None
# 0.1 Check custom aliases (e.g. set by hacks.py)
if name in self.custom_aliases:
return self.custom_aliases[name]
# 0.5. Check if already defined in globals (e.g. from hacks.py)
if name in globals():
return None
# 1. Check exact match (CamelCase)
if name in self.p5_props:
if self.case_mode in ['camel', 'both']:
return name
if self.case_mode == 'snake':
return None
# 2. Check snake_case match
if name in self.snake_map:
if self.case_mode in ['snake', 'both']:
return self.snake_map[name]
return None
def analyze_scope(self, node):
"""Collect local variables from a function body (args + assignments), recursively."""
local_vars = set()
# 1. Arguments are always local
for arg in node.args.args:
local_vars.add(arg.arg)
# 2. Recursive traversal for assignments
# We do NOT use generic_visit/NodeVisitor because we need manual control
# to STOP at nested scopes (FunctionDef, ClassDef, Lambda).
def visit_node_scope(n):
if isinstance(n, ast.Assign):
for target in n.targets:
add_target(target)
elif isinstance(n, ast.AnnAssign):
add_target(n.target)
elif isinstance(n, ast.For) or isinstance(n, ast.AsyncFor):
add_target(n.target)
for item in n.body: visit_node_scope(item)
for item in n.orelse: visit_node_scope(item)
elif isinstance(n, ast.With) or isinstance(n, ast.AsyncWith):
for item in n.items:
if item.optional_vars:
add_target(item.optional_vars)
for item in n.body: visit_node_scope(item)
elif isinstance(n, ast.NamedExpr): # walrus operator (a := 1)
add_target(n.target)
# Control Flow - Recurse but don't add vars directly
elif isinstance(n, (ast.If, ast.While, ast.Try)):
for field, value in ast.iter_fields(n):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
visit_node_scope(item)
elif isinstance(value, ast.AST):
visit_node_scope(value)
# Scopes - STOP recursion.
# Nested functions/classes create their own scope, so their locals aren't ours.
elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
return
# Statements - Recurse into lists of statements (like module body or if body)
elif hasattr(n, 'body') and isinstance(n.body, list):
for item in n.body:
visit_node_scope(item)
def add_target(target):
if isinstance(target, ast.Name):
local_vars.add(target.id)
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
add_target(elt)
# Start traversal from function body
for item in node.body:
visit_node_scope(item)
return local_vars
def visit_FunctionDef(self, node):
# Push new scope
local_names = self.analyze_scope(node)
self.scope_stack.append(local_names)
# Visit children (body)
self.generic_visit(node)
# Pop scope
self.scope_stack.pop()
return node
def visit_Call(self, node):
# We do generic_visit first to process arguments
self.generic_visit(node)
if isinstance(node.func, ast.Name):
name = node.func.id
if name == 'print': return node
if name not in self.user_defined:
target = self.resolve_p5_name(name)
if target:
node.func = ast.Attribute(
value=ast.Name(id='P5', ctx=ast.Load()),
attr=target,
ctx=ast.Load()
)
return node
def visit_Name(self, node):
if isinstance(node.ctx, ast.Load):
if node.id not in self.user_defined:
target = self.resolve_p5_name(node.id)
if target:
return ast.Attribute(
value=ast.Name(id='P5', ctx=ast.Load()),
attr=target,
ctx=ast.Load()
)
return node
async def entry_point():
# Standard file IO is sufficient in Pyodide
import os
import importlib.abc
import importlib.util
# Ensure stdout is still set
sys.stdout = StdoutCatcher()
# Parse URL params
params = js.URLSearchParams.new(js.window.location.search)
project_id = params.get('id')
case_mode = params.get('case') or 'both'
raw_window_name = js.window.name or ""
# Will be set to True if no project is loaded from localStorage or via IDE
is_standalone = False
if not project_id and not raw_window_name.strip():
is_standalone = True
# --- Custom Import Hook for Auto-Prefixing in Modules ---
class P5Importer(importlib.abc.MetaPathFinder, importlib.abc.Loader):
def __init__(self, mode):
self.mode = mode
def find_spec(self, fullname, path, target=None):
filename = fullname + ".py"
if os.path.exists(filename):
return importlib.util.spec_from_file_location(fullname, filename, loader=self)
if is_standalone:
try:
# Standalone mode: try synchronous fetch for dynamic imports
req = js.XMLHttpRequest.new()
req.open('GET', filename, False)
req.send(None)
if req.status == 200:
with open(filename, 'w') as f:
f.write(req.responseText)
return importlib.util.spec_from_file_location(fullname, filename, loader=self)
except Exception:
pass
return None
def create_module(self, spec):
return None
def exec_module(self, module):
with open(module.__file__, 'r') as f:
source = f.read()
try:
tree = ast.parse(source)
except Exception as e:
# Report SyntaxError in module
err_msg = f"{e.__class__.__name__}: {e}"
if isinstance(e, SyntaxError):
err_msg = f"{e.__class__.__name__}: {e.msg}"
line_num = getattr(e, 'lineno', 0)
msg = {"type": "error", "message": err_msg, "filename": module.__file__, "line": line_num}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
raise e
user_defined = set()
for node in tree.body:
if isinstance(node, ast.FunctionDef):
user_defined.add(node.name)
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
user_defined.add(target.id)
elif isinstance(target, ast.Tuple) or isinstance(target, ast.List):
for elt in target.elts:
if isinstance(elt, ast.Name):
user_defined.add(elt.id)
try:
transformer = P5Transformer(user_defined, self.mode)
new_tree = transformer.visit(tree)
ast.fix_missing_locations(new_tree)
code_obj = compile(new_tree, filename=module.__file__, mode="exec")
exec(code_obj, module.__dict__)
except Exception as e:
# Runtime error in module execution
import traceback
# We just propagate it, but the main loop's handler might catch "ImportError",
# so we want to be sure to report the inner detail if possible.
# Actually, posting here is safe.
tb_list = traceback.extract_tb(e.__traceback__)
line_num = 0
err_filename = module.__file__
if tb_list:
last_frame = tb_list[-1]
line_num = last_frame.lineno
err_filename = last_frame.filename
err_msg = f"{e.__class__.__name__}: {e}"
msg = {"type": "error", "message": err_msg, "filename": err_filename, "line": line_num}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
raise e
# Register Hook
sys.meta_path.insert(0, P5Importer(case_mode))
# --- Unified Project Hydration ---
# Parse Project ID from runner URL
params = js.URLSearchParams.new(js.window.location.search)
project_id = params.get('id')
hydrated_assets = {}
if not is_standalone:
try:
project_files_data = None
if project_id:
# --- Try IndexedDB first (new storage backend) ---
try:
idb_read = js.eval("""(function(pid) {
return new Promise(function(resolve) {
var req = indexedDB.open('py5script_db', 1);
req.onsuccess = function(e) {
var db = e.target.result;
if (!db.objectStoreNames.contains('files')) { resolve(null); return; }
var tx = db.transaction(['files'], 'readonly');
var gr = tx.objectStore('files').get(pid);
gr.onsuccess = function() { resolve(gr.result ? gr.result.files : null); };
gr.onerror = function() { resolve(null); };
};
req.onerror = function() { resolve(null); };
});
})""")
idb_files_js = await idb_read(project_id)
if idb_files_js:
project_files_data = json.loads(js.JSON.stringify(idb_files_js))
except Exception:
pass
# --- Fall back to localStorage (legacy) ---
if project_files_data is None:
ls_json = js.localStorage.getItem(f"project_{project_id}_files")
if ls_json:
project_files_data = json.loads(ls_json)
else:
# Very old single-project key
ls_json = js.localStorage.getItem('py5script_project')
if ls_json:
project_files_data = json.loads(ls_json)
if project_files_data:
for filename, content in project_files_data.items():
try:
if content.startswith('data:'):
# Binary asset — decode and write to Pyodide FS
if ',' in content:
_, headerless_data = content.split(',', 1)
binary_data = base64.b64decode(headerless_data)
with open(filename, 'wb') as f:
f.write(binary_data)
hydrated_assets[filename] = content
else:
# Text file (module, shader, …) — write and register as data URL
with open(filename, 'w') as f:
f.write(content)
b64_text = base64.b64encode(content.encode('utf-8')).decode('utf-8')
hydrated_assets[filename] = f"data:text/plain;base64,{b64_text}"
except Exception:
pass
except Exception:
pass
if is_standalone:
print("Running in Standalone Mode. Trying to fetch files dynamically via web server...")
try:
from pyodide.http import pyfetch
# Pre-fetch main sketch file so it's synchronously available when setup runs
try:
resp = await pyfetch('sketch.py')
if resp.ok:
with open('sketch.py', 'w') as f:
f.write(await resp.string())
except Exception:
pass
for cfg in ["requirements.txt", "js_modules.txt"]:
try:
resp = await pyfetch(cfg)
if resp.ok:
with open(cfg, "w") as f:
f.write(await resp.string())
except Exception:
pass
except Exception as e:
print("Error initiating standalone pyfetch:", e)
# -----------------------
# --- Package Installation (requirements.txt) ---
if os.path.exists("requirements.txt"):
try:
# Ensure micropip is available
try:
import micropip
except ImportError:
# Attempt to load micropip via Pyodide JS API wrapper
try:
import pyodide_js
await pyodide_js.loadPackage("micropip")
import micropip
except Exception as e:
print(f"Error loading micropip: {e}")
raise e
with open("requirements.txt", "r") as f:
packages = [line.strip() for line in f if line.strip() and not line.startswith('#')]
if packages:
print(f"Installing packages: {packages}...")
await micropip.install(packages)
print("Packages installed.")
except Exception as e:
print(f"Error installing packages: {e}")
# Post error but maybe continue
msg = {"type": "error", "message": f"Failed to install requirements: {e}", "filename": "requirements.txt", "line": 0}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
# ---------------------------------------------
# --- JavaScript Module Loading (js_modules.txt) ---
# Allows users to import ES modules by adding a js_modules.txt file.
# Format: one entry per line — url = alias
# Lines starting with # are comments. Example:
#
# # Tone.js audio synthesis
# https://cdn.jsdelivr.net/npm/tone@14/build/Tone.js = Tone
# https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.js = Chart
#
# Each alias becomes available as a global in the sketch.
if os.path.exists("js_modules.txt"):
try:
with open("js_modules.txt", "r") as f:
lines = f.readlines()
entries = []
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
url, _, alias = line.partition("=")
url = url.strip()
alias = alias.strip()
if url and alias:
entries.append((url, alias))
if entries:
print(f"Loading JS modules: {[a for _, a in entries]}...")
import builtins
for url, alias in entries:
try:
mod = await js.eval(f"import('{url}')")
globals()[alias] = mod
setattr(builtins, alias, mod)
print(f"JS module '{alias}' loaded from {url}")
except Exception as mod_e:
print(f"Error loading JS module '{alias}' from {url}: {mod_e}")
msg = {"type": "error", "message": f"Failed to load JS module '{alias}': {mod_e}", "filename": "js_modules.txt", "line": 0}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
except Exception as e:
print(f"Error reading js_modules.txt: {e}")
msg = {"type": "error", "message": f"Failed to read js_modules.txt: {e}", "filename": "js_modules.txt", "line": 0}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
# -------------------------------------------------
# Asset Helper (Explicit URL resolution)
def asset(filename):
"""
Returns the Data URL for a given asset filename if it exists.
Otherwise returns the filename itself (fallback).
Usage: p5.loadImage(asset('cat.png'))
"""
if filename in hydrated_assets:
return hydrated_assets[filename]
return filename
# Expose to global scope for user scripts
globals()['asset'] = asset
# Ensure open is builtins.open (defensive)
import builtins
globals()['open'] = builtins.open
# --- Pyodide / JS interop helpers (available everywhere, no import needed) ---
from pyodide.ffi import to_js as _to_js, create_proxy as _create_proxy
import js as _js_mod
def js_array(iterable):
"""Convert a Python list or tuple to a JavaScript Array."""
return _to_js(iterable)
def js_object(d):
"""Convert a Python dict to a plain JavaScript object."""
return _to_js(d, dict_converter=_js_mod.Object.fromEntries)
# Inject into globals AND builtins so imported modules get them too
for _name, _val in [
('to_js', _to_js),
('create_proxy', _create_proxy),
('js_array', js_array),
('js_object', js_object),
]:
globals()[_name] = _val
setattr(builtins, _name, _val)
# -------------------------------------------------------------------------
# --- Hacks Loading (hacks.py) ---
try:
from pyodide.http import pyfetch
url = f"hacks.py?t={js.Date.now()}"
resp = await pyfetch(url)
if resp.ok:
hacks_source = await resp.string()
if hacks_source.strip():
try:
hacks_tree = ast.parse(hacks_source)
user_defined_hacks = set()
for node in hacks_tree.body:
if isinstance(node, ast.FunctionDef):
user_defined_hacks.add(node.name)
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
user_defined_hacks.add(target.id)
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
if isinstance(elt, ast.Name):
user_defined_hacks.add(elt.id)
transformer = P5Transformer(user_defined_hacks, case_mode)
new_hacks_tree = transformer.visit(hacks_tree)
ast.fix_missing_locations(new_hacks_tree)
code_obj = compile(new_hacks_tree, filename="hacks.py", mode="exec")
exec(code_obj, globals())
except Exception as e:
err_msg = f"{e.__class__.__name__}: {e}"
if isinstance(e, SyntaxError):
err_msg = f"{e.__class__.__name__}: {e.msg}"
line_num = getattr(e, 'lineno', 0)
msg = {"type": "error", "message": err_msg, "filename": "hacks.py", "line": line_num}
js.window.parent.postMessage(_to_js(msg, dict_converter=js.Object.fromEntries), "*")
except Exception as e:
pass
# -------------------------------------------------------------------------
def sketch(p):
global P5
P5 = p
# Expose to JS for console.error interception
js.window.currentP5 = p
# Inject P5 into builtins so imported modules can access it as 'P5'
import builtins
builtins.P5 = p
builtins.p5 = js.p5 # Global p5 class available everywhere
# Intercept load functions to use Data URLs if available
# This fixes p5.loadImage() failing to fetch local files
def create_asset_loader(original_loader, loader_name):
def wrapper(*args, **kwargs):
new_args = []
for arg in args:
if isinstance(arg, str) and arg in hydrated_assets:
new_args.append(hydrated_assets[arg])
else:
new_args.append(arg)
return original_loader(*new_args, **kwargs)
return wrapper
# List of load functions to wrap
load_funcs = ['loadImage', 'loadJSON', 'loadStrings', 'loadTable', 'loadXML', 'loadBytes', 'loadModel', 'loadFont', 'loadSound', 'loadShader']
for name in load_funcs:
if hasattr(p, name):
original = getattr(p, name)
setattr(p, name, create_proxy(create_asset_loader(original, name)))
# 1. Get Code & Params
raw_source = js.window.name
source = textwrap.dedent(raw_source)
# Standalone Mode fallback
if not source.strip() and is_standalone:
try:
if os.path.exists("sketch.py"):
with open("sketch.py", "r") as f:
source = f.read()
except Exception:
pass
if not source.strip():
if is_standalone:
print("Error: Could not find sketch.py on paths. Source is empty!")
return
try:
tree = ast.parse(source)
except Exception as e:
# Captura erro de sintaxe
err_msg = f"{e.__class__.__name__}: {e}"
if isinstance(e, SyntaxError):
err_msg = f"{e.__class__.__name__}: {e.msg}"
line_num = getattr(e, 'lineno', 0)
msg = {"type": "error", "message": err_msg, "filename": "sketch.py", "line": line_num}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
return
# --- STATIC MODE ---
# Detect whether or not a setup function was included.
# If not, copy all the code to the body of a setup function automatically.
has_setup = False
for node in tree.body:
if isinstance(node, ast.FunctionDef) and node.name == 'setup':
has_setup = True
break
if not has_setup:
source = "def setup():\n" + textwrap.indent(source, " ")
try:
tree = ast.parse(source)
except Exception as e:
err_msg = f"{e.__class__.__name__}: {e}"
if isinstance(e, SyntaxError):
err_msg = f"{e.__class__.__name__}: {e.msg}"
line_num = getattr(e, 'lineno', 0)
if line_num > 0:
line_num -= 1
msg = {"type": "error", "message": err_msg, "filename": "sketch.py", "line": line_num}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
return
# -------------------
# Collect user definitions
user_defined = set()
for node in tree.body:
if isinstance(node, ast.FunctionDef):
user_defined.add(node.name)
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
user_defined.add(target.id)
# Tuple unpacking? (a, b) = ...
elif isinstance(target, ast.Tuple) or isinstance(target, ast.List):
for elt in target.elts:
if isinstance(elt, ast.Name):
user_defined.add(elt.id)
# 2. Transform AST
transformer = P5Transformer(user_defined, case_mode)
new_tree = transformer.visit(tree)
ast.fix_missing_locations(new_tree)
# 3. Compile and Execute
try:
code_obj = compile(new_tree, filename="sketch.py", mode="exec")
exec(code_obj, globals())
except Exception as e:
import traceback
import os
err_msg = f"{e.__class__.__name__}: {e}"
line_num = 0
err_filename = "sketch.py"
if isinstance(e, SyntaxError):
err_msg = f"{e.__class__.__name__}: {e.msg}"
line_num = e.lineno
err_filename = e.filename
else:
tb_list = traceback.extract_tb(e.__traceback__)
# Find the last frame that is in a user file or sketch.py
for frame in tb_list:
if frame.filename == "sketch.py" or os.path.exists(frame.filename):
err_filename = frame.filename
line_num = frame.lineno
if not has_setup and err_filename == "sketch.py" and line_num > 0:
line_num -= 1
msg = {"type": "error", "message": err_msg, "filename": err_filename, "line": line_num}
js.window.parent.postMessage(to_js(msg, dict_converter=js.Object.fromEntries), "*")
return
# 4. Connect to p5
# List of p5.js event functions to map
p5_events = [
'setup', 'draw', 'preload',
'mousePressed', 'mouseReleased', 'mouseClicked', 'mouseMoved', 'mouseDragged', 'doubleClicked', 'mouseWheel',
'keyPressed', 'keyReleased', 'keyTyped',
'touchStarted', 'touchMoved', 'touchEnded',
'deviceMoved', 'deviceTurned', 'deviceShaken',
'windowResized'
]
import inspect
import traceback
def safe_wrapper(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
traceback.print_exc()
# Stop the sketch loop on error
if P5:
P5.noLoop()
return wrapper
def create_arg_stripper(func):
return lambda *args: func()
for event in p5_events:
py_func = None
# 1. Check for standard camelCase (mousePressed)
if event in globals():
py_func = globals()[event]
# 2. Check for snake_case (mouse_pressed)
else:
snake_event = camel_to_snake(event)
if snake_event != event and snake_event in globals():
py_func = globals()[snake_event]
if py_func:
# Handle argument mismatch (e.g. mousePressed(e) vs mousePressed())
if callable(py_func):
try:
sig = inspect.signature(py_func)
params = sig.parameters
has_varargs = any(p.kind == p.VAR_POSITIONAL for p in params.values())
if not has_varargs and len(params) == 0:
# Wrap to discard arguments
py_func = create_arg_stripper(py_func)
except Exception as e:
pass
# Wrap in error handler
secure_func = safe_wrapper(py_func)
setattr(p, event, create_proxy(secure_func))
proxy = create_proxy(sketch)
js.window.p5.new(proxy)
import asyncio
asyncio.ensure_future(entry_point())
</script>
</body>
</html>