forked from pygame-web/pygbag
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pythons.html
222 lines (161 loc) · 6.32 KB
/
pythons.html
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
<html><head><meta charset="utf-8"></head><script src="pythons.js" type=module id="site" data-os="fs,vtx,gui" async defer>#<!--
import sys
import platform
import asyncio
from pathlib import Path
#print(json.dumps(PyConfig, sort_keys=True, indent=4))
# ok
# import packaging, pyparsing, cycler, kiwisolver, PIL, dateutil, pytz, numpy, matplotlib
# screen pixels (real, hardware)
WIDTH=1024
HEIGHT=600
# reference/idealized screen pixels
REFX = 1980
REFY = 1080
def u(real, ref, v):
if abs(v)<0.9999999:
result = int( (float(real)/100.0) * (v*1000))
if v<0:
return real-result
return result
return int( (real/ref) * v )
def ux(*argv):
global WIDTH, REFX
acc = 0
for v in argv:
acc += u(WIDTH, REFX, v)
return acc
def uy(*argv):
global HEIGHT, REFY
acc = 0
for v in argv:
acc += u(HEIGHT, REFY, v)
return acc
if sys.platform in ("emscripten","wasi",):
platform.window.python.is_ready = True
log = platform.console
try:
platform.document.body.style.background = "#7f7f7f"
import pygame
screen = pygame.display.set_mode([ux(.100),uy(.100)], pygame.SRCALPHA, 32)
screen.set_colorkey( (0,0,0,0), pygame.RLEACCEL )
screen.fill( (0,0,0,0) )
except Exception as _:
pygame = False
sys.print_exception(_)
log.error("cannot load pygame and clear canvas")
async def custom_site():
global PyConfig, con
# reset term
# shell.reset()
class VFS:
from pathlib import Path
script = Path(PyConfig.run_filename) # or sys.argv[0]
if script.suffix.lower() == ".py":
print("Loading:", script )
await TopLevel_async_handler.start_toplevel(platform.shell, console=True)
#wants = "packaging, pyparsing, cycler, kiwisolver, PIL, dateutil, pytz, numpy".split(', ')
wants = ["numpy"]
if 0:
if await TopLevel_async_handler.async_imports(*wants):
import numpy
if 0:
await asyncio.sleep(1)
if await TopLevel_async_handler.async_imports("matplotlib"):
import matplotlib
if 0:
import sys
from urllib.parse import urlencode
import asyncio
import json
class Fetch:
"""
WASM compatible request handler
auto-detects emscripten environment and sends requests using JavaScript Fetch API
"""
GET = 'GET'
POST = 'POST'
_js_code = ""
_init = False
def __init__(self):
self.is_web = True if sys.platform == 'emscripten' else False
if not self._init:
self.init()
self.debug = True
self.result = None
if not self.is_web:
try:
import requests
self.requests = requests
except ImportError:
pass
def init(self):
self.is_web = sys.platform in ('emscripten','wasi')
# jscode is already in pygbag loader
@staticmethod
def read_file(file):
# synchronous reading of file intended for evaluating on initialization
# use async functions during runtime
with open(file, 'r') as f:
data = f.read()
return data
@staticmethod
def print(*args, default=True):
try:
for i in args:
platform.window.console.log(i)
except AttributeError:
pass
except Exception as e:
return e
if default:
print(*args)
async def get(self, url, params=None, doseq=False):
# await asyncio.sleep(5)
if params is None:
params = {}
if self.is_web:
query_string = urlencode(params, doseq=doseq)
await asyncio.sleep(0)
content = await platform.jsiter(platform.window.Fetch.GET(url + "?" + query_string))
if self.debug:
self.print(content)
self.result = content
else:
self.result = self.requests.get(url, params).text
return self.result
# def get(self, url, params=None, doseq=False):
# return await self._get(url, params, doseq)
async def post(self, url, data=None):
if data is None:
data = {}
if self.is_web:
await asyncio.sleep(0)
content = await platform.jsiter(platform.window.Fetch.POST(url, json.dumps(data)))
if self.debug:
self.print(content)
self.result = content
else:
self.result = self.requests.post(url, data).text
return self.result
# def post(self, url, data=None):
# return await self._post(url, data)
if not pygame:
return
rng = 10 # resolution of progress bar
slot = ux(.060)/rng # 60%
async def compose(delay=0):
import asyncio
global screen
pygame.display.update()
platform.window.chromakey(None, *screen.get_colorkey(), 40)
await asyncio.sleep(delay)
for i in range(rng):
marginx = ux(.020) # 20%
marginy = uy(.045) # 45%
pygame.draw.rect(screen,(10,10,10),( marginx-ux(10), marginy-uy(10), (rng*slot)+ux(20), uy(110) ) )
pygame.draw.rect(screen,(0,255,0), ( marginx, marginy, (1+i)*slot, uy(90)) )
await compose(1)
#embed.prompt()
asyncio.run(custom_site())
# --></script></html>