forked from pygame-web/pygbag
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mobile.tmpl
697 lines (519 loc) · 17.9 KB
/
mobile.tmpl
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
<html lang="en-us"><script src="{{cookiecutter.cdn}}pythons.js" type=module id="site" data-COLUMNS={{cookiecutter.COLUMNS}} data-LINES={{cookiecutter.LINES}} data-CONSOLE={{cookiecutter.CONSOLE}} data-python="python{{cookiecutter.PYBUILD}}" data-os="vtx,fs,snd,gui,fbdev" async defer>#<!--
print("""
Loading {{cookiecutter.title}} from {{cookiecutter.archive}}.apk
Pygbag Version : {{cookiecutter.version}}
Template Version : 0.8.5
Python : {{cookiecutter.PYBUILD}}
CDN URL : {{cookiecutter.cdn}}
Screen : {{cookiecutter.width}}x{{cookiecutter.height}}
Title : {{cookiecutter.title}}
Folder : {{cookiecutter.directory}}
Authors : {{cookiecutter.authors}}
SPDX-License-Identifier: {{cookiecutter.spdx}}
""")
import sys
import platform
import json
from pathlib import Path
# import pygbag.aio as asyncio
import aio
import aio.fetch
#if platform.window.location.host.find('localhost')>=0:
# aio.fetch.FS("""
#http://localhost:8000/pygbag/pygbag/support/
#. ~ .
#├── offline.png
#├── pygbag_app.py
#├── pygbag_fsm.py
#├── pygbag_host.py
#├── pygbag_ui.py
#└── pygbag_ux.py
#""")
import asyncio
import builtins
try:
re_entered
except:
builtins.re_entered = False
# do not rename, it has a special meaning for asyncio.run()
async def custom_site():
global app
await aio.fetch.preload(chdir=False, isolated=True)
sys.path.append('/tmp')
# TODO remove later
if re_entered:
platform.window.console.warn("54: @@@@@@@@@@@@@@@@ ERROR @@@@@@@@@@@@@@ ")
return
builtins.re_entered = True
import pygbag_app
import pygbag_ux as ux
#import pygbag_fsm
fsm = None #pygbag_fsm.build({})
app = pygbag_app
ui = app.ui
TTY = app.TTY
Tui = app.Tui
ux.dim({{cookiecutter.width}}, {{cookiecutter.height}})
platform.window.transfer.hidden = true
platform.window.canvas.style.visibility = "visible"
console = app.console.get()
platform.document.body.style.background = "#555555"
apk = "{{cookiecutter.archive}}.apk"
bundle = "{{cookiecutter.archive}}"
# the C or js loader could do that but be explicit.
appdir = Path(f"/data/data/{bundle}") # /data/data/{{cookiecutter.archive}}
appdir.mkdir() #parents=True, exist_ok=True)
# mount apk
cfg = {
"io": "url",
"type":"mount",
"mount" : {
"point" : appdir.as_posix(),
"path" : "/",
}
}
track = platform.window.MM.prepare(apk, json.dumps(cfg))
marginx = ux.x(.020) # 20%
marginy = ux.y(.045) # 45%
async def pv(track, prefix="", suffix="", decimals=1, length=70, fill="X", printEnd="\r"):
# Progress Bar Printing Function
def print_pg_bar(total, iteration):
if iteration > total:
iteration = total
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + "-" * (length - filledLength)
print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=printEnd)
# Update Progress Bar
while True:
if track.pos < 0:
raise IOError(404)
print_pg_bar(track.len or 100, track.pos or 0)
if str(track.avail) == "true":
break
await asyncio.sleep(0.02)
# Print New Line on Complete
print()
print('Downloading and mounting assets:')
# wait until zip mount + overlayfs is complete
#while not track.ready:
await pv(track)
#await asyncio.sleep(.1)
# preloader will change dir and prepend it to sys.path
# but do not run main.py yet.
assets = appdir / "assets"
# we need to fill __file__ that is not yet set
# as default exec mode is REPL from stdin
__import__(__name__).__file__ = (assets / "main.py").as_posix()
def ui_callback(pkg):
print(f"installing {pkg}")
while not Path(__file__).is_file():
print("mobile.tmpl: waiting for main")
await asyncio.sleep(.1)
# get all modules from guesswork or pep0722/0723
# preloading will change directory to assets dir and prepare imports.
with open(__file__,"r") as source:
await shell.preload_code(source.read(), loaderhome=appdir / "assets", hint=__file__)
# do wasm streaming compilation on all gathered .so
platform.explore(assets)
# wait preloading complete
# that includes images and wasm compilation of bundled modules
while platform.preloading>0:
platform.preloading = embed.preloading()
print(f"Assets to streaming-compile : {platform.preloading}")
await asyncio.sleep(.5)
print("mobile.tmpl: top level")
# test/wait user media interaction
print( platform.window.MM.UME )
if str(platform.window.MM.UME)!="true":
# now make a prompt
print("Ready to start !")
print("""
* Waiting for media user engagement : please click/touch page *
""")
while not platform.window.MM.UME:
await asyncio.sleep(.1)
# unlock async for main.py loop ( 2nd asyncio.run call )
embed.run()
loop = asyncio.get_event_loop()
# mypyc/hpy require modules.
print("mobile.tmpl: running 'main' as a module", __name__, __file__, os.getcwd(), sys.modules.get('main','ok'))
# get symbols of "main" for REPL "__main__"
import main
for k,v in vars(main).items():
if not k.startswith('_'):
globals()[k]=v
def console_display():
if len(ui.clog):
print()
while len(ui.clog):
l = ui.clog.pop(0)
print(l)
try:
platform.window.console.log(l)
except:
...
TTY.prompts.append(1)
# this tty is program normal flow
ui.goto_xy(1,1)
# so save is done here
ESC("7")
ui.goto_xy(1, app.TTY.LINES + app.TTY.CONSOLE)
print(">>> ", end=sys.__eot__)
try:
while not app.TTY.closed:
ESC("8")
while len(platform.frames):
frame = platform.frames.pop(0)
# should not be used at all or PTY context required
# if inspect.iscoroutinefunction(frame):
# await frame(timestamp=0.0)
# else:
frame(timestamp=0.0)
ESC("7")
await asyncio.sleep(app.sleep_delay)
if not PyConfig.interactive:
continue
# if (last_state != fsm.state):
# app.log(f"{last_state}=>{fsm.state}")
# last_state = fsm.state
with Tui() as out:
# lbuf = ctx()["io"][0]
# for z,x, row in lbuf:
# out( row, x=x, z=z )
# lbuf.clear()
# for z,x, row in bufs.values():
# out( row, x=x, z=z )
# bufs.clear()
# import io
# sio = io.StringIO()
# rich.print(rich.panel.Panel(get_panels(), width=55) , file=sio)
# sio.seek(0)
# out( sio.read(), x=10, z=2, filter = ui.filter_out )
out( f"{TTY.COLUMNS}x({TTY.LINES}+{TTY.CONSOLE}):{TTY.console}\
fsm={fsm and fsm.state} C={TTY.C} L={TTY.L}\
min/avg/max:{aio.load_min} {aio.load_avg} {aio.load_max}\
⏏︎ ■ ▶\
{TTY.last_event_type}({TTY.last_event_data})\
", x=1, y=TTY.LINES)
if TTY.event_type:
if TTY.event_type == "click":
act(TTY.event_data)
# async readline interface ( await input() )
if TTY.input():
pass
# console zone ( only when mouse hovering )
elif TTY.console:
# readline editing
# console prompt zone #todo pos cursor readline
ui.goto_xy(5, app.TTY.LINES + app.TTY.CONSOLE)
TTY.prompt()
# exec
if len(TTY.rl_complete):
aio.toplevel.handler.instance.buffer.append("\n".join(TTY.rl_complete))
TTY.rl_complete.clear()
await aio.toplevel.handler.instance.interact_step('>_> ')
# app loops only when not in console
else:
...
#frames.append( tetryscale.pygame.loop() )
# console zone ( display, always, force scroll by display on last line )
console_display()
except asyncio.exceptions.CancelledError:
print("Cancelled")
except KeyboardInterrupt:
print("KeyboardInterrupt")
finally:
TTY.set_raw(0)
print("killing tasks, FIXME restart REPL for WASM")
aio.exit_now(0)
platform.window.console.warn(" ************************************** ")
asyncio.run( custom_site() )
# BEGIN BLOCK
#
# now this is the html part you can (and should) customize
# It is not mandatory : pygame-script when it reads the first line (also called
# shebang ) of above code create absolute minimal widget set
# required for running with default rules
#
# do not alter that comment block it is separating python code from html code
# =============================================================================
# --></script><head><!--
//=============================================================================
//
//
//
//
//
//
//
{%- if cookiecutter.comment != "" -%}
{{cookiecutter.comment}}
{% endif %}
--><script type="application/javascript">
// END BLOCK
// this dict is available under PyConfig.config from __main__
config = {
xtermjs : "{{cookiecutter.xtermjs}}" ,
_sdl2 : "canvas",
user_canvas : 0,
user_canvas_managed : 0,
ume_block : {{cookiecutter.ume_block}},
can_close : {{cookiecutter.can_close}},
archive : "{{cookiecutter.archive}}",
gui_debug : 1.5,
cdn : "{{cookiecutter.cdn}}",
autorun : {{cookiecutter.autorun}},
PYBUILD : "{{cookiecutter.PYBUILD}}"
}
</script>
<title>{{cookiecutter.title}}</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="viewport" content="minimal-ui, width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1, user-scalable=no"">
<link rel="icon" type="image/png" href="favicon.png" sizes="16x16">
<style>
#status {
display: inline-block;
vertical-align: top;
margin-top: 20px;
margin-left: 30px;
font-weight: bold;
color: rgb(120, 120, 120);
}
#progress {
height: 20px;
width: 300px;
}
div.emscripten { text-align: center; }
div.emscripten_border { border: 1px solid black; }
div.thick_border { border: 4px solid black; }
/* the canvas *must not* have any border or padding, or mouse coords will be wrong */
/* average size of droid screen 470dp x 320dp */
canvas.emscripten {
border: 0px none;
background-color: transparent;
width: 100%;
height: 100%;
z-index: 5;
padding: 0;
margin: 0 auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
canvas.moved {
border: 0px none;
background-color: transparent;
width: 100%;
height: 100%;
z-index: 5;
padding: 0;
margin: 0 auto;
}
body {
font-family: arial;
margin: 0;
padding: none;
background-color: #1a1c1f;
}
.topright{
position:absolute;
top:0px;
right:0px;
}
.rightpane{
position:absolute;
left : 50%;
}
.bottomright {
position:absolute;
top: 70%;
right: 0px;
height: 30%;
}
.center {
display: flex;
align-items: center;
justify-content: center;
}
.framed{
position: relative;
top: 00px;
right: 0px;
border: 1px solid white;
}
</style>
</head>
<body id=body>
<div id="transfer" align=center>
<div class="emscripten" id="status">Downloading...</div>
<div class="emscripten">
<progress value="0" max="100" id="progress"></progress>
</div>
</div>
<canvas class="emscripten" id="canvas"
width="1px"
height="1px"
oncontextmenu="event.preventDefault()" tabindex=0>
</canvas>
<div id=html></div>
<div id=crt class=bottomright>
<div id=box class=emscripten_border hidden=true>
<canvas id=canvas3d class="emscripten"
width="512px"
height="512px"
oncontextmenu="event.preventDefault()">
</canvas>
<iframe id="dlhandler" class="framed" name="dlhandler"
width="470px" height="95%"
loading="lazy"
allowtransparency="true"
style="z-index: 10;"
style="background: #FFFFFF;"
frameborder="1"
allowfullscreen="true"
webkitallowfullscreen="true"
msallowfullscreen="true"
mozallowfullscreen="true"
sandbox="allow-same-origin allow-top-navigation allow-scripts allow-pointer-lock"
allow="autoplay; fullscreen *; geolocation; microphone; camera; midi; monetization; xr-spatial-tracking; gamepad; gyroscope; accelerometer; xr; cross-origin-isolated"
src="{{cookiecutter.cdn}}../../archives/lib/index.html"
scrolling="yes">
</iframe>
</div>
</div>
<div id="dlg" hidden>
<input type="file" id="dlg_multifile" multiple accept="image/*">
<label for="dlg_multifile">Select files</label>
</div>
<div id="pyconsole">
<div id="terminal" tabIndex=1 align="left"
ondrag="dragHandler(event);"
ondrop="dropHandler(event);"
ondragover="dragOverHandler(event);">
</div>
</div>
<script type="application/javascript">
var dragged = null;
function dragHandler(event) {
dragged = event.target;
}
function dropHandler(ev) {
// prevent default action (open as a link for some elements)
ev.preventDefault();
// Loop through the dropped items and log their data
filelist = []
for (const item of ev.dataTransfer.items) {
if (item.kind === "file") {
filelist.push(item.getAsFile())
continue;
}
//if (item.kind === "string" && item.type.match(/^text\/plain/)) {
//if (item.kind === "string" && item.type.match(/^text\/html/)) {
//if (item.kind === "string" && item.type.match(/^text\/uri-list/)) {
console.log('?',file.name, item.type )
}
console.log("dropHandler", filelist.length)
if (filelist.length)
transfer_uploads(filelist, true)
dragged = null;
}
function dragOverHandler(event) {
if (!dragged) {
dragged = event.target;
console.log("dragOverHandler", event.dataTransfer)
}
event.preventDefault();
}
async function custom_onload(debug_hidden) {
// this is called before anything python is loaded
// make your js customization here
console.log(__FILE__, "custom_onload")
pyconsole.hidden = debug_hidden
box.hidden = debug_hidden
}
var dlfcn_handle_id = 0
var dlfcn_handles = {}
var dlfcn_retval = {}
function dlvoid(hexstack) {
//const dlhandler = document.getElementById("dlhandler").contentWindow
//window.console.log(`dlhandler.postMessage("${hexstack}")`)
dlhandler.postMessage(hexstack, "*")
}
function * dlcall(callid, hexstack) {
//const dlhandler = document.getElementById("dlhandler").contentWindow
dlhandler.postMessage(hexstack, "*")
while (!dlfcn_retval[callid])
yield 0
yield dlfcn_retval[callid]
}
function * dlopen(lib) {
dlfcn_handle_id += 1
const linkid = lib + "_" + dlfcn_handle_id
// const dlhandler = document.getElementById("dlhandler").contentWindow
console.log("dlopen: opening :", linkid)
// wait for lazy iframe case
while (!dlfcn_handles["dlopen"])
yield 0
dlhandler.postMessage("dlopen:"+lib+":"+ linkid , "*")
while (!dlfcn_handles[linkid])
yield 0
yield linkid
}
function from_hex(h) {
var s = ''
for (var i = 0; i < h.length; i+=2) {
s += String.fromCharCode(parseInt(h.substr(i, 2), 16))
}
return decodeURIComponent(escape(s))
}
function rx(event) {
const rxmsg = ""+event.data
const origin = event.origin
var e = rxmsg.split(':')
const rt = e.shift()
if (rt == "dlopen") {
const serial = e.shift()
if (serial =="") {
const linkid = e.shift()
dlfcn_handles[linkid] = linkid
// call returned value
} else {
dlfcn_retval[serial] = from_hex(e.shift())
}
} else {
console.warn("bus(567)",rxmsg, origin)
}
if (origin) {
//console.log("forwarding",rxmsg)
}
}
window.addEventListener("message", rx, false);
function custom_prerun(){
// no python main and no (MEMFS + VFS) yet.
console.log(__FILE__, "custom_prerun")
}
function custom_postrun(){
// python main and no VFS filesystem yet.
console.log(__FILE__, "custom_postrun")
}
function debug() {
// allow to gain access to dev tools from js console
// but only on desktop. difficult to reach when in iframe
python.config.debug = true
custom_onload(false)
Module.PyRun_SimpleString("shell.uptime()")
window_resize()
}
// Hides mobile browser's address bar when page is done loading.
window.addEventListener('load', function(e) {
setTimeout(function() { window.scrollTo({left:0, top:1080, behaviour :"instant"}) }, 1);
}, false);
</script>
</body>
</html>