omnipython-applibs 0.1.2.dev16__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- appkit/__init__.py +52 -0
- appkit/__init__.pyi +17 -0
- appkit/data.py +149 -0
- appkit/data.pyi +25 -0
- appkit/foreground.py +357 -0
- appkit/foreground.pyi +45 -0
- appkit/home.py +19 -0
- appkit/home.pyi +8 -0
- appkit/hover.py +59 -0
- appkit/hover.pyi +13 -0
- appkit/index.py +199 -0
- appkit/index.pyi +30 -0
- appkit/launcher.py +1075 -0
- appkit/launcher.pyi +96 -0
- appkit/manifest.py +75 -0
- appkit/manifest.pyi +8 -0
- appkit/net.py +167 -0
- appkit/net.pyi +34 -0
- appkit/places.py +202 -0
- appkit/places.pyi +39 -0
- appkit/py.typed +0 -0
- appkit/scope.py +636 -0
- appkit/scope.pyi +110 -0
- appkit/shell.py +121 -0
- appkit/shell.pyi +32 -0
- appkit/worker.py +409 -0
- appkit/worker.pyi +83 -0
- controlkit/__init__.py +19 -0
- controlkit/__init__.pyi +10 -0
- controlkit/_draw.py +88 -0
- controlkit/_safe.py +29 -0
- controlkit/dotmatrix.py +101 -0
- controlkit/dotmatrix.pyi +23 -0
- controlkit/encoder.py +297 -0
- controlkit/encoder.pyi +55 -0
- controlkit/font5x7.py +22 -0
- controlkit/font5x7.pyi +11 -0
- controlkit/lamp_button.py +92 -0
- controlkit/lamp_button.pyi +40 -0
- controlkit/meter.py +86 -0
- controlkit/meter.pyi +30 -0
- controlkit/mock.py +116 -0
- controlkit/mock.pyi +35 -0
- controlkit/pad_grid.py +113 -0
- controlkit/pad_grid.pyi +41 -0
- controlkit/py.typed +0 -0
- controlkit/slider.py +185 -0
- controlkit/slider.pyi +49 -0
- controlkit/sprites.py +279 -0
- controlkit/sprites.pyi +22 -0
- controlkit/theme.py +120 -0
- controlkit/theme.pyi +15 -0
- deskkit/__init__.py +74 -0
- deskkit/__init__.pyi +18 -0
- deskkit/forecast.py +261 -0
- deskkit/forecast.pyi +40 -0
- deskkit/localtime.py +215 -0
- deskkit/localtime.pyi +33 -0
- deskkit/py.typed +0 -0
- deskkit/shell.py +113 -0
- deskkit/shell.pyi +33 -0
- omnipython_applibs-0.1.2.dev16.dist-info/METADATA +90 -0
- omnipython_applibs-0.1.2.dev16.dist-info/RECORD +143 -0
- omnipython_applibs-0.1.2.dev16.dist-info/WHEEL +5 -0
- omnipython_applibs-0.1.2.dev16.dist-info/licenses/LICENSE +21 -0
- omnipython_applibs-0.1.2.dev16.dist-info/top_level.txt +9 -0
- programkit/__init__.py +27 -0
- programkit/__init__.pyi +8 -0
- programkit/board.py +56 -0
- programkit/board.pyi +20 -0
- programkit/press.py +63 -0
- programkit/press.pyi +17 -0
- programkit/py.typed +0 -0
- programkit/rows.py +149 -0
- programkit/rows.pyi +34 -0
- sayso/__init__.py +109 -0
- sayso/__init__.pyi +124 -0
- sayso/auth.py +811 -0
- sayso/auth.pyi +102 -0
- sayso/client.py +1286 -0
- sayso/client.pyi +138 -0
- sayso/keepalive.py +371 -0
- sayso/keepalive.pyi +53 -0
- sayso/local.py +85 -0
- sayso/local.pyi +28 -0
- sayso/object_specs.py +706 -0
- sayso/object_specs.pyi +8 -0
- sayso/objects.py +411 -0
- sayso/objects.pyi +854 -0
- sayso/py.typed +0 -0
- sayso/schema_coverage.py +210 -0
- sayso/schema_coverage.pyi +13 -0
- sayso/transport.py +426 -0
- sayso/transport.pyi +47 -0
- songmodel/__init__.py +30 -0
- songmodel/__init__.pyi +9 -0
- songmodel/link.py +189 -0
- songmodel/link.pyi +53 -0
- songmodel/model.py +238 -0
- songmodel/model.pyi +40 -0
- songmodel/page.html +225 -0
- songmodel/page_data.py +236 -0
- songmodel/page_data.pyi +6 -0
- songmodel/py.typed +0 -0
- soundmodule/__init__.py +7 -0
- soundmodule/__init__.pyi +6 -0
- soundmodule/engine.py +1001 -0
- soundmodule/engine.pyi +196 -0
- soundmodule/names.py +298 -0
- soundmodule/names.pyi +30 -0
- soundmodule/pipes.py +105 -0
- soundmodule/pipes.pyi +31 -0
- soundmodule/py.typed +0 -0
- soundmodule/run.py +249 -0
- soundmodule/run.pyi +49 -0
- spectrum/__init__.py +72 -0
- spectrum/__init__.pyi +30 -0
- spectrum/analyzer.py +231 -0
- spectrum/analyzer.pyi +67 -0
- spectrum/fake_music.py +201 -0
- spectrum/fake_music.pyi +36 -0
- spectrum/pump_levels.py +126 -0
- spectrum/pump_levels.pyi +46 -0
- spectrum/py.typed +0 -0
- spectrum/spectrum_view.py +403 -0
- spectrum/spectrum_view.pyi +80 -0
- touchkit/__init__.py +4 -0
- touchkit/__init__.pyi +4 -0
- touchkit/cam.py +146 -0
- touchkit/cam.pyi +35 -0
- touchkit/clock.py +18 -0
- touchkit/clock.pyi +6 -0
- touchkit/ecp.py +134 -0
- touchkit/ecp.pyi +28 -0
- touchkit/net.py +347 -0
- touchkit/net.pyi +27 -0
- touchkit/py.typed +0 -0
- touchkit/settings.py +85 -0
- touchkit/settings.pyi +17 -0
- touchkit/shell.py +268 -0
- touchkit/shell.pyi +42 -0
- touchkit/ui.py +167 -0
- touchkit/ui.pyi +53 -0
appkit/launcher.py
ADDED
|
@@ -0,0 +1,1075 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""Launcher: start switchable apps by name, and switch between them.
|
|
5
|
+
|
|
6
|
+
::
|
|
7
|
+
|
|
8
|
+
# main.py
|
|
9
|
+
from appkit.launcher import Launcher, run_pending_script
|
|
10
|
+
run_pending_script() # first: a plain script a switch asked for
|
|
11
|
+
|
|
12
|
+
import board_config
|
|
13
|
+
from appdev import App
|
|
14
|
+
|
|
15
|
+
launcher = Launcher(App(board_config), {
|
|
16
|
+
"face": "apps.face", # name -> module with main(scope)
|
|
17
|
+
"steps": "apps.steps",
|
|
18
|
+
}, home="face")
|
|
19
|
+
launcher.boot() # starts "face", or the app a restart asked for
|
|
20
|
+
|
|
21
|
+
# later, from a button, a gesture or the REPL:
|
|
22
|
+
launcher.switch("steps")
|
|
23
|
+
|
|
24
|
+
Each switch closes the old app's `AppScope <appkit.scope.AppScope>` (its
|
|
25
|
+
timers, subscriptions, devices, LVGL objects and modules) and starts the
|
|
26
|
+
new one in the same process. After the close it checks the heap: if free
|
|
27
|
+
memory or the largest free block has fallen below its threshold, or the old
|
|
28
|
+
app's ``close()`` raised or couldn't release something, it **restarts** the
|
|
29
|
+
program straight into the new app instead, so memory can't run out however
|
|
30
|
+
the apps behave. How it restarts depends on the host:
|
|
31
|
+
|
|
32
|
+
================== ========================== ===================================
|
|
33
|
+
Host The next app's name Restart
|
|
34
|
+
================== ========================== ===================================
|
|
35
|
+
ESP32 (MicroPython) ``machine.RTC().memory()`` ``machine.soft_reset()``, or
|
|
36
|
+
``machine.reset()`` from a callback;
|
|
37
|
+
main.py calls ``boot()`` again
|
|
38
|
+
CircuitPython a file, ``/data/.next_app`` ``supervisor.reload()``, or
|
|
39
|
+
``microcontroller.reset()`` from a
|
|
40
|
+
callback; code.py calls ``boot()``
|
|
41
|
+
again
|
|
42
|
+
Other boards a file, ``/data/.next_app`` the same as ESP32
|
|
43
|
+
Desktop MicroPython ``<data root>/.next_app`` exit with code 75; run the program
|
|
44
|
+
under ``python -m appkit.launcher``
|
|
45
|
+
to have it started again
|
|
46
|
+
CPython ``<data root>/.next_app`` ``os.execv`` of the same command
|
|
47
|
+
Browser (wasm) the page URL's ``?app=`` reload the page
|
|
48
|
+
================== ========================== ===================================
|
|
49
|
+
|
|
50
|
+
The file is in the data root (see ``appkit.data``), so it moves with
|
|
51
|
+
``data_root``. ``OMNIPYTHON_NEXT_APP`` overrides its path.
|
|
52
|
+
|
|
53
|
+
A plain script (`Launcher.add_script`, or ``"script"`` in an
|
|
54
|
+
``app.json``) builds its own ``App`` when imported, so it never runs in the
|
|
55
|
+
launcher's process: the launcher restarts the program into it, and
|
|
56
|
+
`run_pending_script`, first thing in ``main.py``, runs it and restarts
|
|
57
|
+
back to the home screen when it quits.
|
|
58
|
+
|
|
59
|
+
See appkit's README.md.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
import gc
|
|
63
|
+
import sys
|
|
64
|
+
|
|
65
|
+
import multimer
|
|
66
|
+
|
|
67
|
+
from . import data, foreground
|
|
68
|
+
from .data import DESKTOPS
|
|
69
|
+
from .scope import AppScope, _error, mem_free
|
|
70
|
+
|
|
71
|
+
#: The exit code a desktop MicroPython program uses to ask for a restart.
|
|
72
|
+
RESTART_EXIT_CODE = 75
|
|
73
|
+
|
|
74
|
+
#: The largest block the launcher's baseline measurement looks for, in bytes.
|
|
75
|
+
#: On an ESP32 with PSRAM the heap grows on demand, so an uncapped search
|
|
76
|
+
#: briefly takes nearly all of the PSRAM; a stale reference to that buffer on
|
|
77
|
+
#: the C stack can then keep it alive into the first app, which reads as a
|
|
78
|
+
#: heap already half gone.
|
|
79
|
+
PROBE_LIMIT = 1 << 20
|
|
80
|
+
|
|
81
|
+
MICROPYTHON = sys.implementation.name == "micropython"
|
|
82
|
+
|
|
83
|
+
#: Whether this host can read its heap, and so checks it after a close.
|
|
84
|
+
_HEAP = hasattr(gc, "mem_free")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _print_exc(exc):
|
|
88
|
+
pe = getattr(sys, "print_exception", None)
|
|
89
|
+
if pe is not None:
|
|
90
|
+
pe(exc)
|
|
91
|
+
else:
|
|
92
|
+
import traceback
|
|
93
|
+
|
|
94
|
+
traceback.print_exception(type(exc), exc, exc.__traceback__)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _say(msg):
|
|
98
|
+
print("appkit.launcher: " + msg)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def largest_free_block(limit=None):
|
|
102
|
+
"""The largest bytearray that can be allocated now, in bytes (to 64 B).
|
|
103
|
+
|
|
104
|
+
None where the heap can't be read (CPython). It finds the size by
|
|
105
|
+
trying allocations, so it costs a few collections: use it to measure,
|
|
106
|
+
not on every switch. *limit* caps the search.
|
|
107
|
+
"""
|
|
108
|
+
if not hasattr(gc, "mem_free"):
|
|
109
|
+
return None
|
|
110
|
+
gc.collect()
|
|
111
|
+
if limit is not None and _can_allocate(limit):
|
|
112
|
+
# The usual case on a big heap: one allocation instead of a search,
|
|
113
|
+
# which on an ESP32's PSRAM takes seconds.
|
|
114
|
+
gc.collect()
|
|
115
|
+
return limit
|
|
116
|
+
lo = 0
|
|
117
|
+
hi = gc.mem_free() if limit is None else min(limit, gc.mem_free())
|
|
118
|
+
while hi - lo > 64:
|
|
119
|
+
mid = ((lo + hi) // 2) & ~15
|
|
120
|
+
try:
|
|
121
|
+
b = bytearray(mid)
|
|
122
|
+
b = None
|
|
123
|
+
lo = mid
|
|
124
|
+
except MemoryError:
|
|
125
|
+
hi = mid
|
|
126
|
+
gc.collect()
|
|
127
|
+
return lo
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _can_allocate(n):
|
|
131
|
+
try:
|
|
132
|
+
b = bytearray(n)
|
|
133
|
+
b = None
|
|
134
|
+
return True
|
|
135
|
+
except MemoryError:
|
|
136
|
+
return False
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _can_gather(n, piece=PROBE_LIMIT):
|
|
140
|
+
"""True when *n* bytes can be allocated now, in pieces of *piece*.
|
|
141
|
+
|
|
142
|
+
Where the heap grows on demand (an ESP32's PSRAM), ``gc.mem_free()``
|
|
143
|
+
counts only what the heap holds now, so it can read low while there is
|
|
144
|
+
room to grow; this asks the allocator instead.
|
|
145
|
+
"""
|
|
146
|
+
pieces = []
|
|
147
|
+
got = 0
|
|
148
|
+
try:
|
|
149
|
+
while got < n:
|
|
150
|
+
k = min(piece, n - got)
|
|
151
|
+
pieces.append(bytearray(k))
|
|
152
|
+
got += k
|
|
153
|
+
return True
|
|
154
|
+
except MemoryError:
|
|
155
|
+
return False
|
|
156
|
+
finally:
|
|
157
|
+
pieces = None
|
|
158
|
+
gc.collect()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _import(modname):
|
|
162
|
+
mod = __import__(modname)
|
|
163
|
+
for part in modname.split(".")[1:]:
|
|
164
|
+
mod = getattr(mod, part)
|
|
165
|
+
return mod
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def lacks(needs):
|
|
169
|
+
"""Return the first of *needs* this interpreter doesn't have, or None.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
needs (list): What an app's ``app.json`` lists under ``"needs"``:
|
|
173
|
+
module names (``"audiomp3"``) and attributes of modules
|
|
174
|
+
(``"os.dupterm"``).
|
|
175
|
+
"""
|
|
176
|
+
for need in needs or ():
|
|
177
|
+
module, _, name = need.partition(".")
|
|
178
|
+
try:
|
|
179
|
+
found = __import__(module)
|
|
180
|
+
except ImportError:
|
|
181
|
+
return need
|
|
182
|
+
if name and not hasattr(found, name):
|
|
183
|
+
return need
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
#: What appkit writes to an apps folder that has no ``__init__.py``.
|
|
188
|
+
INIT_TEXT = "# The apps folder is a package: appkit imports each app in it as %s.<app>.\n"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _split_folder(folder):
|
|
192
|
+
"""``(parent, package)`` for an apps folder: ``("", "apps")`` for
|
|
193
|
+
``"apps"``, ``("/sd", "apps")`` for ``"/sd/apps"``."""
|
|
194
|
+
f = folder
|
|
195
|
+
while len(f) > 1 and f[-1] in "/\\":
|
|
196
|
+
f = f[:-1]
|
|
197
|
+
i = max(f.rfind("/"), f.rfind("\\"))
|
|
198
|
+
if i < 0:
|
|
199
|
+
return "", f
|
|
200
|
+
return (f[:i] if i > 0 else f[0]), f[i + 1 :]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _identifier(name):
|
|
204
|
+
if not name or name[0] in "0123456789":
|
|
205
|
+
return False
|
|
206
|
+
return all(c == "_" or "a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9" for c in name)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _ensure_init(folder, package):
|
|
210
|
+
"""Make *folder*'s ``__init__.py`` if it has none; OSError, saying what
|
|
211
|
+
to do, when it can't (a read-only filesystem). True when it made one."""
|
|
212
|
+
import os
|
|
213
|
+
|
|
214
|
+
path = folder + "/__init__.py"
|
|
215
|
+
try:
|
|
216
|
+
os.stat(path)
|
|
217
|
+
return False
|
|
218
|
+
except OSError:
|
|
219
|
+
pass
|
|
220
|
+
try:
|
|
221
|
+
with open(path, "w") as f:
|
|
222
|
+
f.write(INIT_TEXT % (package,))
|
|
223
|
+
except OSError as exc:
|
|
224
|
+
raise OSError(
|
|
225
|
+
"the apps folder %r has no __init__.py and appkit couldn't make one (%s): "
|
|
226
|
+
"add an empty %s/__init__.py, so its apps import as %s.<app>" % (folder, exc, folder, package)
|
|
227
|
+
)
|
|
228
|
+
_say("made %s, so the apps in %r import as %s.<app>" % (path, folder, package))
|
|
229
|
+
return True
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _read_folder(folder):
|
|
233
|
+
"""``[(entry, app.json contents, entry's folder), ...]`` for each app in
|
|
234
|
+
*folder*, sorted; None when *folder* doesn't exist."""
|
|
235
|
+
import json
|
|
236
|
+
import os
|
|
237
|
+
|
|
238
|
+
try:
|
|
239
|
+
entries = sorted(os.listdir(folder))
|
|
240
|
+
except OSError:
|
|
241
|
+
return None
|
|
242
|
+
out = []
|
|
243
|
+
for entry in entries:
|
|
244
|
+
where = folder + "/" + entry
|
|
245
|
+
try:
|
|
246
|
+
with open(where + "/app.json") as f:
|
|
247
|
+
info = json.load(f)
|
|
248
|
+
except OSError:
|
|
249
|
+
continue # not an app
|
|
250
|
+
out.append((entry, info, where))
|
|
251
|
+
return out
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
# -- where the next app's name is kept, per host ------------------------------
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def host():
|
|
258
|
+
"""Which restart path this interpreter takes: ``"board"``, ``"desktop"``
|
|
259
|
+
(desktop MicroPython), ``"cpython"``, ``"browser"`` or ``"circuitpython"``."""
|
|
260
|
+
plat = sys.platform
|
|
261
|
+
if plat in ("webassembly", "emscripten"):
|
|
262
|
+
return "browser"
|
|
263
|
+
name = sys.implementation.name
|
|
264
|
+
if name == "cpython":
|
|
265
|
+
return "cpython"
|
|
266
|
+
if plat in DESKTOPS:
|
|
267
|
+
return "desktop"
|
|
268
|
+
if name == "circuitpython":
|
|
269
|
+
return "circuitpython"
|
|
270
|
+
return "board"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _state_path():
|
|
274
|
+
path = data._getenv("OMNIPYTHON_NEXT_APP")
|
|
275
|
+
if path:
|
|
276
|
+
return path
|
|
277
|
+
root = data.root()
|
|
278
|
+
data.makedirs(root)
|
|
279
|
+
return data.join(root, ".next_app")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
_MAGIC = b"appkit:"
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _rtc():
|
|
286
|
+
try:
|
|
287
|
+
import machine
|
|
288
|
+
|
|
289
|
+
rtc = machine.RTC()
|
|
290
|
+
if not hasattr(rtc, "memory"):
|
|
291
|
+
return None
|
|
292
|
+
return rtc
|
|
293
|
+
except (ImportError, AttributeError, ValueError, OSError):
|
|
294
|
+
return None
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
#: How a pending script is told from a pending app: ``script:<module>``.
|
|
298
|
+
SCRIPT = "script:"
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def save_next(name, count=1, path=None):
|
|
302
|
+
"""Keep *name* (and how many restarts in a row led here) for the next boot.
|
|
303
|
+
|
|
304
|
+
*path* is a folder the next boot puts on ``sys.path`` first: a script's
|
|
305
|
+
own folder.
|
|
306
|
+
"""
|
|
307
|
+
text = "%s\n%d" % (name, count)
|
|
308
|
+
if path:
|
|
309
|
+
text += "\n" + path
|
|
310
|
+
h = host()
|
|
311
|
+
if h == "browser":
|
|
312
|
+
return # carried by the URL the restart navigates to
|
|
313
|
+
if h == "board":
|
|
314
|
+
rtc = _rtc()
|
|
315
|
+
if rtc is not None:
|
|
316
|
+
rtc.memory(_MAGIC + text.encode())
|
|
317
|
+
return
|
|
318
|
+
with open(_state_path(), "w") as f:
|
|
319
|
+
f.write(text)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def take_next():
|
|
323
|
+
"""The ``(name, count)`` a restart left for this boot, cleared once read, or None."""
|
|
324
|
+
rec = read_next(clear=True)
|
|
325
|
+
return None if rec is None else rec[:2]
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def read_next(clear=False):
|
|
329
|
+
"""The ``(name, count, path)`` a restart left for this boot, or None.
|
|
330
|
+
|
|
331
|
+
Cleared once read when *clear*; left for `Launcher.boot` otherwise.
|
|
332
|
+
"""
|
|
333
|
+
h = host()
|
|
334
|
+
text = None
|
|
335
|
+
if h == "browser":
|
|
336
|
+
return _browser_take(clear)
|
|
337
|
+
if h == "board":
|
|
338
|
+
rtc = _rtc()
|
|
339
|
+
if rtc is not None:
|
|
340
|
+
raw = bytes(rtc.memory())
|
|
341
|
+
if not raw.startswith(_MAGIC):
|
|
342
|
+
return None
|
|
343
|
+
if clear:
|
|
344
|
+
rtc.memory(b"")
|
|
345
|
+
text = raw[len(_MAGIC) :].decode()
|
|
346
|
+
if text is None:
|
|
347
|
+
import os
|
|
348
|
+
|
|
349
|
+
path = _state_path()
|
|
350
|
+
try:
|
|
351
|
+
with open(path) as f:
|
|
352
|
+
text = f.read()
|
|
353
|
+
except OSError:
|
|
354
|
+
return None
|
|
355
|
+
if clear:
|
|
356
|
+
try:
|
|
357
|
+
os.remove(path)
|
|
358
|
+
except OSError:
|
|
359
|
+
pass
|
|
360
|
+
parts = text.split("\n")
|
|
361
|
+
if not parts[0]:
|
|
362
|
+
return None
|
|
363
|
+
try:
|
|
364
|
+
count = int(parts[1]) if len(parts) > 1 else 1
|
|
365
|
+
except ValueError:
|
|
366
|
+
count = 1
|
|
367
|
+
return parts[0], count, (parts[2] if len(parts) > 2 and parts[2] else None)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _browser_params():
|
|
371
|
+
import js
|
|
372
|
+
|
|
373
|
+
return js, js.URLSearchParams.new(js.window.location.search)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _browser_take(clear=True):
|
|
377
|
+
js, params = _browser_params()
|
|
378
|
+
name = params.get("app")
|
|
379
|
+
if not name:
|
|
380
|
+
return None
|
|
381
|
+
try:
|
|
382
|
+
count = int(params.get("app_restarts") or 1)
|
|
383
|
+
except ValueError:
|
|
384
|
+
count = 1
|
|
385
|
+
path = params.get("app_path") or None
|
|
386
|
+
if clear:
|
|
387
|
+
params.delete("app")
|
|
388
|
+
params.delete("app_restarts")
|
|
389
|
+
params.delete("app_path")
|
|
390
|
+
loc = js.window.location
|
|
391
|
+
q = params.toString()
|
|
392
|
+
js.window.history.replaceState(None, "", loc.pathname + ("?" + q if q else "") + loc.hash)
|
|
393
|
+
return str(name), count, (str(path) if path else None)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
#: True while a launcher's scheduled start (`Launcher._resume`) runs.
|
|
397
|
+
_resuming = False
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _in_callback():
|
|
401
|
+
"""True while multimer is delivering timer callbacks, or a launcher's
|
|
402
|
+
scheduled start runs."""
|
|
403
|
+
return _resuming or bool(getattr(multimer._dispatch, "_in_deliver", False))
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def restart_into(name, count=1, path=None):
|
|
407
|
+
"""Restart the program straight into app *name*, the host's way.
|
|
408
|
+
|
|
409
|
+
With *name* None the program restarts with nothing pending, so it starts
|
|
410
|
+
as it does from cold: on its home screen. Doesn't return where the host
|
|
411
|
+
can restart (it exits, execs or resets). In a browser it returns after
|
|
412
|
+
asking for the reload: stop work and let the page go.
|
|
413
|
+
"""
|
|
414
|
+
h = host()
|
|
415
|
+
if h == "browser":
|
|
416
|
+
js, params = _browser_params()
|
|
417
|
+
for key in ("app", "app_restarts", "app_path"):
|
|
418
|
+
params.delete(key)
|
|
419
|
+
if name is not None:
|
|
420
|
+
params.set("app", name)
|
|
421
|
+
params.set("app_restarts", str(count))
|
|
422
|
+
if path:
|
|
423
|
+
params.set("app_path", path)
|
|
424
|
+
js.window.location.search = params.toString()
|
|
425
|
+
return
|
|
426
|
+
if name is not None:
|
|
427
|
+
save_next(name, count, path)
|
|
428
|
+
else:
|
|
429
|
+
try:
|
|
430
|
+
read_next(clear=True)
|
|
431
|
+
except Exception:
|
|
432
|
+
pass
|
|
433
|
+
if h == "board":
|
|
434
|
+
import machine
|
|
435
|
+
|
|
436
|
+
# soft_reset() raises SystemExit, which only reaches the REPL from
|
|
437
|
+
# top-level code. From a callback (a timer, a button, an LVGL event:
|
|
438
|
+
# how an app asks to switch) the scheduler that ran it catches the
|
|
439
|
+
# exception and the program carries on, so reset the chip instead;
|
|
440
|
+
# RTC memory survives that too.
|
|
441
|
+
if _in_callback():
|
|
442
|
+
machine.reset()
|
|
443
|
+
# A callback multimer didn't deliver (a pin IRQ, say) can't be told
|
|
444
|
+
# apart: if the soft reset is swallowed, this timer resets the chip.
|
|
445
|
+
# A real soft reset stops it with every other timer.
|
|
446
|
+
multimer.after(500, lambda t: machine.reset(), name="launcher.reset")
|
|
447
|
+
machine.soft_reset()
|
|
448
|
+
elif h == "circuitpython":
|
|
449
|
+
import microcontroller
|
|
450
|
+
import supervisor
|
|
451
|
+
|
|
452
|
+
# The same as a board's soft reset: reload() raises an exception that
|
|
453
|
+
# a callback's caller catches, so from a callback reset the chip; the
|
|
454
|
+
# file in /data survives either.
|
|
455
|
+
if _in_callback():
|
|
456
|
+
microcontroller.reset()
|
|
457
|
+
multimer.after(500, lambda t: microcontroller.reset(), name="launcher.reset")
|
|
458
|
+
supervisor.reload()
|
|
459
|
+
elif h == "desktop":
|
|
460
|
+
import os
|
|
461
|
+
|
|
462
|
+
if not (hasattr(os, "getenv") and os.getenv("OMNIPYTHON_SUPERVISED")):
|
|
463
|
+
sys.stderr.write(
|
|
464
|
+
"appkit.launcher: exiting so the program can restart%s; "
|
|
465
|
+
"run it under `python -m appkit.launcher <command>` to restart automatically\n"
|
|
466
|
+
% (
|
|
467
|
+
""
|
|
468
|
+
if name is None
|
|
469
|
+
else " into the script %r" % (name[len(SCRIPT) :],)
|
|
470
|
+
if name.startswith(SCRIPT)
|
|
471
|
+
else " into %r" % (name,)
|
|
472
|
+
)
|
|
473
|
+
)
|
|
474
|
+
# The exit code alone doesn't always get out: raised from a timer or
|
|
475
|
+
# an LVGL event (a click on the home screen) it can be caught on the
|
|
476
|
+
# way and the program ends with 0. So tell the supervisor in a file too.
|
|
477
|
+
flag = data._getenv("APPKIT_RESTART_FILE")
|
|
478
|
+
if flag:
|
|
479
|
+
try:
|
|
480
|
+
with open(flag, "w") as f:
|
|
481
|
+
f.write("restart")
|
|
482
|
+
except OSError:
|
|
483
|
+
pass
|
|
484
|
+
# Or multimer's exit hook keeps the program alive on its timers, or
|
|
485
|
+
# the foreground loop (appkit.serve) on its own, and the exit never
|
|
486
|
+
# happens.
|
|
487
|
+
foreground.stop()
|
|
488
|
+
multimer.stop_all()
|
|
489
|
+
multimer.keepalive(False)
|
|
490
|
+
sys.exit(RESTART_EXIT_CODE)
|
|
491
|
+
else:
|
|
492
|
+
import os
|
|
493
|
+
|
|
494
|
+
argv = getattr(sys, "orig_argv", None) or [sys.executable] + sys.argv
|
|
495
|
+
for stream in (sys.stdout, sys.stderr):
|
|
496
|
+
try:
|
|
497
|
+
stream.flush()
|
|
498
|
+
except Exception:
|
|
499
|
+
pass
|
|
500
|
+
os.execv(sys.executable, argv)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
# -- plain scripts --------------------------------------------------------------
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _app_done(app):
|
|
507
|
+
return app is None or app.quit_requested
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def run_pending_script(data_root=None):
|
|
511
|
+
"""Run the script a launcher restarted into, if there is one.
|
|
512
|
+
|
|
513
|
+
Call it first thing in ``main.py``, before anything opens the display or
|
|
514
|
+
builds an ``App`` (``appkit.run()`` does). With nothing pending it
|
|
515
|
+
returns False at once. With a script pending it imports the script,
|
|
516
|
+
waits until the ``App`` the script built has quit (a script may keep
|
|
517
|
+
running on its timers after its body ends), then restarts the program,
|
|
518
|
+
which comes back up on its home screen: it doesn't return. In a browser
|
|
519
|
+
it returns True once the restart is arranged; the caller should then do
|
|
520
|
+
nothing more.
|
|
521
|
+
|
|
522
|
+
*data_root* is the program's data root, where a desktop's restart file
|
|
523
|
+
is (see ``appkit.data``).
|
|
524
|
+
"""
|
|
525
|
+
if data_root is not None:
|
|
526
|
+
data.set_root(data_root)
|
|
527
|
+
try:
|
|
528
|
+
rec = read_next()
|
|
529
|
+
except Exception as exc:
|
|
530
|
+
_say("could not read the pending app: %s" % (exc,))
|
|
531
|
+
return False
|
|
532
|
+
if rec is None or not rec[0].startswith(SCRIPT):
|
|
533
|
+
return False
|
|
534
|
+
read_next(clear=True)
|
|
535
|
+
module = rec[0][len(SCRIPT) :]
|
|
536
|
+
path = rec[2]
|
|
537
|
+
if path and path not in sys.path:
|
|
538
|
+
sys.path.insert(0, path)
|
|
539
|
+
_say("running the script %r" % (module,))
|
|
540
|
+
app = None
|
|
541
|
+
try:
|
|
542
|
+
_import(module)
|
|
543
|
+
from appdev import App
|
|
544
|
+
|
|
545
|
+
app = App.current()
|
|
546
|
+
if not _app_done(app):
|
|
547
|
+
# What the script would have done itself had it called run().
|
|
548
|
+
app.run()
|
|
549
|
+
except SystemExit:
|
|
550
|
+
pass # the script's own way out
|
|
551
|
+
except Exception as exc:
|
|
552
|
+
_say("the script %r failed" % (module,))
|
|
553
|
+
_print_exc(exc)
|
|
554
|
+
if not _app_done(app):
|
|
555
|
+
# The host runs the loop (a browser page): restart when the script quits.
|
|
556
|
+
app.on_quit(lambda: restart_into(None))
|
|
557
|
+
return True
|
|
558
|
+
app = None
|
|
559
|
+
_say("the script %r has ended; restarting to the home screen" % (module,))
|
|
560
|
+
restart_into(None)
|
|
561
|
+
return True
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
# -- the launcher ---------------------------------------------------------------
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
class Launcher:
|
|
568
|
+
"""Owns the long-lived App, starts apps by name and switches between them.
|
|
569
|
+
|
|
570
|
+
*apps* maps a name to the module holding that app's ``main(scope)``
|
|
571
|
+
(``{"steps": "apps.steps"}``); `add` registers more. *home* is
|
|
572
|
+
started by `boot` when no restart is pending, and after an app
|
|
573
|
+
fails to start.
|
|
574
|
+
|
|
575
|
+
*min_free* and *min_block* are the heap thresholds in bytes, checked
|
|
576
|
+
after each close: free heap, and the largest block that can still be
|
|
577
|
+
allocated. Free heap under *min_free* is tried by allocating that much
|
|
578
|
+
in 1 MB pieces, since a heap that grows on demand reads low. Left as
|
|
579
|
+
None they are half the free heap and a quarter of the largest free
|
|
580
|
+
block (looked for up to ``PROBE_LIMIT``, 1 MB), measured when the
|
|
581
|
+
launcher first starts an app.
|
|
582
|
+
Hosts that can't read their heap (CPython) skip the check and rely on
|
|
583
|
+
``close()``'s own report. *max_restarts* bounds restarts in a row, so a
|
|
584
|
+
threshold the program can never meet doesn't restart it forever.
|
|
585
|
+
"""
|
|
586
|
+
|
|
587
|
+
def __init__(self, app=None, apps=None, *, home=None, shell=None, min_free=None, min_block=None, max_restarts=3):
|
|
588
|
+
if app is None:
|
|
589
|
+
from appdev import App
|
|
590
|
+
|
|
591
|
+
app = App.current() or App()
|
|
592
|
+
self.app = app
|
|
593
|
+
self._apps = {}
|
|
594
|
+
self._order = [] # names, in the order they were added
|
|
595
|
+
#: Script entries: name -> (module, folder to put on sys.path or None).
|
|
596
|
+
self._scripts = {}
|
|
597
|
+
for name in apps or ():
|
|
598
|
+
self.add(name, apps[name])
|
|
599
|
+
self.home = home
|
|
600
|
+
#: What's around an app (``appkit.Shell``): it gives each scope its
|
|
601
|
+
#: ``root`` before the app's ``main`` runs. None: the app makes its own.
|
|
602
|
+
self.shell = shell
|
|
603
|
+
#: Each scanned app's ``app.json``, by name.
|
|
604
|
+
self.info = {}
|
|
605
|
+
self.min_free = min_free
|
|
606
|
+
self.min_block = min_block
|
|
607
|
+
self.max_restarts = max_restarts
|
|
608
|
+
#: The running app's name and scope, or None.
|
|
609
|
+
self.current = None
|
|
610
|
+
self.scope = None
|
|
611
|
+
#: Restarts in a row that led to this process (0 on a cold start).
|
|
612
|
+
self.restarts = 0
|
|
613
|
+
self._streak = 0
|
|
614
|
+
#: In-process switches done by this process.
|
|
615
|
+
self.switches = 0
|
|
616
|
+
#: What the last close() couldn't release.
|
|
617
|
+
self.problems = []
|
|
618
|
+
#: Free heap and largest free block when the launcher started.
|
|
619
|
+
self.baseline = None
|
|
620
|
+
#: How the last switch went: ``(how, ms, free)`` with how one of
|
|
621
|
+
#: ``"start"``, ``"switch"``, ``"restart"``.
|
|
622
|
+
self.last = None
|
|
623
|
+
#: The app a `request` is waiting to switch to, or None.
|
|
624
|
+
self._pending = None
|
|
625
|
+
# The request timers and their callback are made here, so a request
|
|
626
|
+
# allocates nothing. Made while an app runs, they would land among its
|
|
627
|
+
# objects and, still alive when the heap is checked after its close,
|
|
628
|
+
# split the free space it left. Two, because a request made while one
|
|
629
|
+
# is firing (an app's main() switching on) can't re-arm that one.
|
|
630
|
+
self._request_timers = (
|
|
631
|
+
multimer.Timer(-1, name="launcher.switch"),
|
|
632
|
+
multimer.Timer(-1, name="launcher.switch"),
|
|
633
|
+
)
|
|
634
|
+
self._firing = None
|
|
635
|
+
self._on_request_cb = self._on_request
|
|
636
|
+
self._resume_cb = self._resume
|
|
637
|
+
#: ``(t0, reason, free)`` from closing an app for a request whose
|
|
638
|
+
#: heap check and start are still to come; see `_on_request`.
|
|
639
|
+
self._closed = None
|
|
640
|
+
self._restarting = False
|
|
641
|
+
|
|
642
|
+
# -- registry -------------------------------------------------------
|
|
643
|
+
|
|
644
|
+
def add(self, name, module=None):
|
|
645
|
+
"""Register app *name*, whose ``main(scope)`` is in *module* (default *name*)."""
|
|
646
|
+
self._scripts.pop(name, None)
|
|
647
|
+
self._register(name, module or name)
|
|
648
|
+
|
|
649
|
+
def _register(self, name, module):
|
|
650
|
+
if name not in self._apps:
|
|
651
|
+
self._order.append(name)
|
|
652
|
+
self._apps[name] = module
|
|
653
|
+
|
|
654
|
+
def add_script(self, name, module=None, path=None):
|
|
655
|
+
"""Register *name* as a plain script: *module* (default *name*) builds
|
|
656
|
+
its own ``App`` when imported, so it runs in a fresh process.
|
|
657
|
+
|
|
658
|
+
Switching to it restarts the program into the script; when the
|
|
659
|
+
script's ``App`` quits, the program restarts to the home screen.
|
|
660
|
+
*path* is a folder to put first on ``sys.path`` before the import.
|
|
661
|
+
"""
|
|
662
|
+
self._register(name, module or name)
|
|
663
|
+
self._scripts[name] = (module or name, path)
|
|
664
|
+
|
|
665
|
+
def is_script(self, name):
|
|
666
|
+
"""True when *name* is a plain script rather than an app."""
|
|
667
|
+
return name in self._scripts
|
|
668
|
+
|
|
669
|
+
def scan(self, folder="apps"):
|
|
670
|
+
"""Register every app in *folder*: each subfolder holding an ``app.json``.
|
|
671
|
+
|
|
672
|
+
The folder is a package, named for it, and each app is a module in
|
|
673
|
+
it: ``apps/clock`` is imported as ``apps.clock``, so an app can have
|
|
674
|
+
the name of any library without either hiding the other. The folder
|
|
675
|
+
needs an ``__init__.py``: when it has none, scan() makes one, or
|
|
676
|
+
raises ``OSError`` saying so where it can't (a read-only
|
|
677
|
+
filesystem). The folder's parent goes on the end of ``sys.path``.
|
|
678
|
+
|
|
679
|
+
An ``app.json`` with ``"script": "<module>"`` is a plain script (see
|
|
680
|
+
`add_script`), looked for in its own folder first. An app whose
|
|
681
|
+
``"needs"`` names something this interpreter lacks (see `lacks`) is
|
|
682
|
+
left out, with a line saying why, so a home screen never offers an
|
|
683
|
+
app that can't start: the REPL, which needs ``os.dupterm``, isn't on
|
|
684
|
+
CircuitPython's home screen. Where
|
|
685
|
+
*folder* doesn't exist (a build with the apps frozen in), the same
|
|
686
|
+
entries come from the generated module ``_appkit_apps``, with the
|
|
687
|
+
apps frozen as the package ``apps`` (see ``appkit.index``). Returns
|
|
688
|
+
the apps' ``app.json`` contents, by name.
|
|
689
|
+
"""
|
|
690
|
+
entries = _read_folder(folder)
|
|
691
|
+
if entries is None:
|
|
692
|
+
try:
|
|
693
|
+
index = _import("_appkit_apps")
|
|
694
|
+
except ImportError:
|
|
695
|
+
raise OSError("no apps: there is no folder %r and no _appkit_apps module" % (folder,))
|
|
696
|
+
package = getattr(index, "PACKAGE", "apps")
|
|
697
|
+
entries = [(entry, info, None) for entry, info in index.APPS]
|
|
698
|
+
else:
|
|
699
|
+
parent, package = _split_folder(folder)
|
|
700
|
+
if not _identifier(package):
|
|
701
|
+
raise ValueError("the apps folder %r can't be a package: name it like a module, as in apps" % (folder,))
|
|
702
|
+
if any(not info.get("script") for _, info, _ in entries):
|
|
703
|
+
_ensure_init(folder, package)
|
|
704
|
+
if parent not in sys.path:
|
|
705
|
+
sys.path.append(parent)
|
|
706
|
+
found = {}
|
|
707
|
+
for entry, info, path in entries:
|
|
708
|
+
name = info.get("name", entry)
|
|
709
|
+
missing = lacks(info.get("needs"))
|
|
710
|
+
if missing is not None:
|
|
711
|
+
_say("%s is left out: it needs %s, which %s doesn't have" % (name, missing, sys.implementation.name))
|
|
712
|
+
continue
|
|
713
|
+
script = info.get("script")
|
|
714
|
+
if script:
|
|
715
|
+
self.add_script(name, script, path)
|
|
716
|
+
else:
|
|
717
|
+
self.add(name, package + "." + entry)
|
|
718
|
+
found[name] = info
|
|
719
|
+
self.info.update(found)
|
|
720
|
+
return found
|
|
721
|
+
|
|
722
|
+
@property
|
|
723
|
+
def names(self):
|
|
724
|
+
"""Every app's and script's name, in the order they were added."""
|
|
725
|
+
return tuple(self._order)
|
|
726
|
+
|
|
727
|
+
# -- heap -----------------------------------------------------------
|
|
728
|
+
|
|
729
|
+
def _measure_baseline(self):
|
|
730
|
+
if self.baseline is not None:
|
|
731
|
+
return
|
|
732
|
+
free = mem_free()
|
|
733
|
+
block = largest_free_block(PROBE_LIMIT)
|
|
734
|
+
self.baseline = (free, block)
|
|
735
|
+
if free is not None:
|
|
736
|
+
if self.min_free is None:
|
|
737
|
+
self.min_free = free // 2
|
|
738
|
+
if self.min_block is None:
|
|
739
|
+
self.min_block = block // 4
|
|
740
|
+
|
|
741
|
+
def heap(self):
|
|
742
|
+
"""``(free, largest_free_block)`` now, or ``(None, None)`` on CPython."""
|
|
743
|
+
free = mem_free()
|
|
744
|
+
if free is None:
|
|
745
|
+
return None, None
|
|
746
|
+
return free, largest_free_block()
|
|
747
|
+
|
|
748
|
+
def _low(self, free):
|
|
749
|
+
if free is None:
|
|
750
|
+
return None
|
|
751
|
+
if self.min_free is not None and free < self.min_free and not _can_gather(self.min_free):
|
|
752
|
+
return "free heap %d B is below %d B" % (free, self.min_free)
|
|
753
|
+
if self.min_block and not _can_allocate(self.min_block):
|
|
754
|
+
return "no free block of %d B" % (self.min_block,)
|
|
755
|
+
return None
|
|
756
|
+
|
|
757
|
+
# -- starting and switching ---------------------------------------------
|
|
758
|
+
|
|
759
|
+
def boot(self, default=None):
|
|
760
|
+
"""Start the app a restart asked for, else *default*, else ``home``.
|
|
761
|
+
|
|
762
|
+
Call it once, where the program starts (``main.py`` on a board).
|
|
763
|
+
Returns the name of the app it started.
|
|
764
|
+
"""
|
|
765
|
+
pending = None
|
|
766
|
+
try:
|
|
767
|
+
pending = take_next()
|
|
768
|
+
except Exception as exc:
|
|
769
|
+
_say("could not read the pending app: %s" % (exc,))
|
|
770
|
+
if pending is not None and pending[0].startswith(SCRIPT):
|
|
771
|
+
_say(
|
|
772
|
+
"a script was pending (%r) and nothing ran it: call appkit.run_pending_script() "
|
|
773
|
+
"first thing in main.py" % (pending[0][len(SCRIPT) :],)
|
|
774
|
+
)
|
|
775
|
+
pending = None
|
|
776
|
+
if pending is not None and pending[0] in self._apps and pending[0] not in self._scripts:
|
|
777
|
+
name, self.restarts = pending
|
|
778
|
+
self._streak = self.restarts
|
|
779
|
+
_say("restarted into %r" % (name,))
|
|
780
|
+
else:
|
|
781
|
+
name = default or self.home
|
|
782
|
+
if name is None:
|
|
783
|
+
if not self._apps:
|
|
784
|
+
raise ValueError("no apps registered")
|
|
785
|
+
name = self.names[0]
|
|
786
|
+
self.switch(name)
|
|
787
|
+
return name
|
|
788
|
+
|
|
789
|
+
def start(self, name):
|
|
790
|
+
"""Start app *name*; the same as `switch`."""
|
|
791
|
+
self.switch(name)
|
|
792
|
+
|
|
793
|
+
def request(self, name):
|
|
794
|
+
"""Switch to *name* at the next safe point, after the current callback.
|
|
795
|
+
|
|
796
|
+
This is what an app calls (``scope.switch(name)``) from its own timer
|
|
797
|
+
or event callback, so it isn't closed while it is still running.
|
|
798
|
+
"""
|
|
799
|
+
if name not in self._apps:
|
|
800
|
+
raise ValueError("no app named %r" % (name,))
|
|
801
|
+
# Under a hold: a host that delivers between bytecodes could otherwise
|
|
802
|
+
# fire it before the name is stored.
|
|
803
|
+
with multimer.hold():
|
|
804
|
+
self._cancel_request()
|
|
805
|
+
self._pending = name
|
|
806
|
+
a, b = self._request_timers
|
|
807
|
+
t = b if self._firing is a else a
|
|
808
|
+
t.init(mode=multimer.Timer.ONE_SHOT, period=1, callback=self._on_request_cb)
|
|
809
|
+
|
|
810
|
+
def _on_request(self, timer):
|
|
811
|
+
name = self._pending
|
|
812
|
+
if name is None:
|
|
813
|
+
return
|
|
814
|
+
self._firing = timer
|
|
815
|
+
try:
|
|
816
|
+
if self.scope is not None and _HEAP and name not in self._scripts:
|
|
817
|
+
# Close the app now, and check the heap and start the next one
|
|
818
|
+
# once the calls that delivered this one have returned. Where
|
|
819
|
+
# an interpreter keeps a call's frame on the heap, those calls
|
|
820
|
+
# began while the old app ran, so their frames sit among its
|
|
821
|
+
# objects, and while they last they split the free space the
|
|
822
|
+
# check measures. The main loop's next turn has none of them
|
|
823
|
+
# below it; without the loop, a scheduled call has fewer.
|
|
824
|
+
t0 = multimer.ticks_ms()
|
|
825
|
+
self._closed = (t0,) + self._close_running()
|
|
826
|
+
if not foreground.next_turn(self._resume_cb, False):
|
|
827
|
+
try:
|
|
828
|
+
multimer.schedule(self._resume_cb, True)
|
|
829
|
+
except RuntimeError: # the scheduler's queue is full
|
|
830
|
+
self.request(name)
|
|
831
|
+
return
|
|
832
|
+
self.switch(name)
|
|
833
|
+
finally:
|
|
834
|
+
self._firing = None
|
|
835
|
+
|
|
836
|
+
def _resume(self, scheduled):
|
|
837
|
+
# The second half of a request `_on_request` began: the old app is
|
|
838
|
+
# closed, so check the heap and start the next one, unless a newer
|
|
839
|
+
# request's switch already has. *scheduled* is True from a scheduled
|
|
840
|
+
# call, which swallows a soft reset as a timer callback does.
|
|
841
|
+
global _resuming
|
|
842
|
+
name = self._pending
|
|
843
|
+
if name is None or self._closed is None:
|
|
844
|
+
return
|
|
845
|
+
_resuming = scheduled
|
|
846
|
+
try:
|
|
847
|
+
self.switch(name)
|
|
848
|
+
finally:
|
|
849
|
+
_resuming = False
|
|
850
|
+
|
|
851
|
+
def _cancel_request(self):
|
|
852
|
+
self._pending = None
|
|
853
|
+
for t in self._request_timers:
|
|
854
|
+
t.deinit()
|
|
855
|
+
|
|
856
|
+
def switch(self, name):
|
|
857
|
+
"""Close the running app and start app *name*.
|
|
858
|
+
|
|
859
|
+
In-process unless the heap check or the old app's close() says
|
|
860
|
+
otherwise; then the program restarts into *name* (see the module
|
|
861
|
+
docstring). Returns ``"start"``, ``"switch"`` or ``"restart"``
|
|
862
|
+
(the last only where a restart returns at all: a browser).
|
|
863
|
+
"""
|
|
864
|
+
if name not in self._apps:
|
|
865
|
+
raise ValueError("no app named %r" % (name,))
|
|
866
|
+
if self._restarting:
|
|
867
|
+
return "restart"
|
|
868
|
+
self._cancel_request()
|
|
869
|
+
if name in self._scripts:
|
|
870
|
+
return self._run_script(name)
|
|
871
|
+
closed = self._closed
|
|
872
|
+
self._closed = None
|
|
873
|
+
if closed is not None: # a request closed the app already
|
|
874
|
+
t0, reason, free = closed
|
|
875
|
+
how = "switch"
|
|
876
|
+
elif self.scope is not None:
|
|
877
|
+
t0 = multimer.ticks_ms()
|
|
878
|
+
reason, free = self._close_running()
|
|
879
|
+
how = "switch"
|
|
880
|
+
else:
|
|
881
|
+
t0 = multimer.ticks_ms()
|
|
882
|
+
reason = free = None
|
|
883
|
+
how = "start"
|
|
884
|
+
if free is None:
|
|
885
|
+
# Before the baseline: its probe allocates, and a buffer it leaves
|
|
886
|
+
# briefly reachable mustn't count against the first app.
|
|
887
|
+
free = mem_free()
|
|
888
|
+
self._measure_baseline()
|
|
889
|
+
if reason is None:
|
|
890
|
+
reason = self._low(free)
|
|
891
|
+
if reason is not None:
|
|
892
|
+
if self._restart(name, reason):
|
|
893
|
+
return "restart"
|
|
894
|
+
try:
|
|
895
|
+
self._start(name)
|
|
896
|
+
except MemoryError as exc:
|
|
897
|
+
if self._restart(name, "%s starting %r" % (type(exc).__name__, name)):
|
|
898
|
+
return "restart"
|
|
899
|
+
raise
|
|
900
|
+
except Exception as exc:
|
|
901
|
+
if self.home is None or name == self.home:
|
|
902
|
+
raise
|
|
903
|
+
_say("%r failed to start; starting %r" % (name, self.home))
|
|
904
|
+
_print_exc(exc)
|
|
905
|
+
self._start(self.home)
|
|
906
|
+
name = self.home
|
|
907
|
+
if reason is None:
|
|
908
|
+
self._streak = 0
|
|
909
|
+
if how == "switch":
|
|
910
|
+
self.switches += 1
|
|
911
|
+
self.last = (how, multimer.ticks_diff(multimer.ticks_ms(), t0), free)
|
|
912
|
+
return how
|
|
913
|
+
|
|
914
|
+
def _close_running(self):
|
|
915
|
+
"""Close the running app; return ``(reason to restart or None, free heap after)``."""
|
|
916
|
+
old = self.scope
|
|
917
|
+
self.scope = None
|
|
918
|
+
self.current = None
|
|
919
|
+
reason = None
|
|
920
|
+
try:
|
|
921
|
+
problems = old.close()
|
|
922
|
+
except Exception as exc:
|
|
923
|
+
problems = [_error("close() of %r raised" % (old.name,), exc)]
|
|
924
|
+
self.problems = list(problems)
|
|
925
|
+
if problems:
|
|
926
|
+
reason = "%r did not close cleanly: %s" % (old.name, problems[0])
|
|
927
|
+
# close() has just collected and read it.
|
|
928
|
+
return reason, getattr(old, "free_after_close", None)
|
|
929
|
+
|
|
930
|
+
def _run_script(self, name):
|
|
931
|
+
"""Close the running app and restart the program into script *name*."""
|
|
932
|
+
module, path = self._scripts[name]
|
|
933
|
+
self._closed = None
|
|
934
|
+
old = self.scope
|
|
935
|
+
self.scope = None
|
|
936
|
+
self.current = None
|
|
937
|
+
if old is not None:
|
|
938
|
+
try:
|
|
939
|
+
self.problems = list(old.close())
|
|
940
|
+
except Exception as exc:
|
|
941
|
+
self.problems = [_error("close() of %r raised" % (old.name,), exc)]
|
|
942
|
+
old = None
|
|
943
|
+
_say("restarting into the script %r" % (name,))
|
|
944
|
+
try:
|
|
945
|
+
self._restarting = True
|
|
946
|
+
restart_into(SCRIPT + module, 1, path)
|
|
947
|
+
except Exception as exc:
|
|
948
|
+
self._restarting = False
|
|
949
|
+
_say("could not restart into %r: %s" % (name, exc))
|
|
950
|
+
if self.home is None or self.home == name or self.home in self._scripts:
|
|
951
|
+
raise
|
|
952
|
+
self._start(self.home)
|
|
953
|
+
return "start"
|
|
954
|
+
self.last = ("restart", None, None)
|
|
955
|
+
return "restart"
|
|
956
|
+
|
|
957
|
+
def _restart(self, name, reason):
|
|
958
|
+
"""Restart into *name*; False (and carry on in-process) when that isn't allowed."""
|
|
959
|
+
if self._streak >= self.max_restarts:
|
|
960
|
+
_say("%s; not restarting (%d restarts in a row)" % (reason, self._streak))
|
|
961
|
+
return False
|
|
962
|
+
_say("%s; restarting into %r" % (reason, name))
|
|
963
|
+
try:
|
|
964
|
+
self._restarting = True
|
|
965
|
+
restart_into(name, self._streak + 1)
|
|
966
|
+
except Exception as exc:
|
|
967
|
+
self._restarting = False
|
|
968
|
+
_say("could not restart: %s" % (exc,))
|
|
969
|
+
return False
|
|
970
|
+
self.last = ("restart", None, None)
|
|
971
|
+
return True
|
|
972
|
+
|
|
973
|
+
def _start(self, name):
|
|
974
|
+
modname = self._apps[name]
|
|
975
|
+
scope = AppScope(self.app, name, modules=(modname,))
|
|
976
|
+
scope.launcher = self
|
|
977
|
+
self.scope = scope
|
|
978
|
+
self.current = name
|
|
979
|
+
try:
|
|
980
|
+
if self.shell is not None:
|
|
981
|
+
self.shell.prepare(scope)
|
|
982
|
+
main = _import(modname).main
|
|
983
|
+
# Its own timers wait until main() has finished building.
|
|
984
|
+
with multimer.hold():
|
|
985
|
+
main(scope)
|
|
986
|
+
except BaseException:
|
|
987
|
+
self.scope = None
|
|
988
|
+
self.current = None
|
|
989
|
+
main = None
|
|
990
|
+
scope.close()
|
|
991
|
+
raise
|
|
992
|
+
|
|
993
|
+
def stop(self):
|
|
994
|
+
"""Close the running app and cancel a pending switch."""
|
|
995
|
+
self._cancel_request()
|
|
996
|
+
self._closed = None
|
|
997
|
+
old = self.scope
|
|
998
|
+
self.scope = None
|
|
999
|
+
self.current = None
|
|
1000
|
+
if old is not None:
|
|
1001
|
+
self.problems = list(old.close())
|
|
1002
|
+
return self.problems
|
|
1003
|
+
|
|
1004
|
+
|
|
1005
|
+
# -- the restart command --------------------------------------------------------
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
_SAFE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./=:,+@%"
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
def _quote(arg):
|
|
1012
|
+
if arg and all(c in _SAFE for c in arg):
|
|
1013
|
+
return arg
|
|
1014
|
+
return "'" + arg.replace("'", "'\"'\"'") + "'"
|
|
1015
|
+
|
|
1016
|
+
|
|
1017
|
+
def _take_flag(path):
|
|
1018
|
+
import os
|
|
1019
|
+
|
|
1020
|
+
try:
|
|
1021
|
+
os.remove(path)
|
|
1022
|
+
return True
|
|
1023
|
+
except OSError:
|
|
1024
|
+
return False
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def supervise(cmd):
|
|
1028
|
+
"""Run *cmd*, and again each time it exits asking for a restart.
|
|
1029
|
+
|
|
1030
|
+
A restart is asked for by exit code 75, or by the file named in the
|
|
1031
|
+
child's ``APPKIT_RESTART_FILE`` (the exit code can be lost when the
|
|
1032
|
+
restart comes from inside a callback). Returns the exit code it finally
|
|
1033
|
+
ends with. The child sees ``OMNIPYTHON_SUPERVISED=1``.
|
|
1034
|
+
"""
|
|
1035
|
+
if not cmd:
|
|
1036
|
+
raise ValueError("no command to run")
|
|
1037
|
+
flag = _state_path() + ".restart"
|
|
1038
|
+
while True:
|
|
1039
|
+
_take_flag(flag) # a stale one from a run that died
|
|
1040
|
+
if MICROPYTHON:
|
|
1041
|
+
import os
|
|
1042
|
+
|
|
1043
|
+
status = os.system(
|
|
1044
|
+
"OMNIPYTHON_SUPERVISED=1 APPKIT_RESTART_FILE=%s " % _quote(flag) + " ".join(_quote(a) for a in cmd)
|
|
1045
|
+
)
|
|
1046
|
+
code = (status >> 8) & 0xFF if status & 0x7F == 0 else 128 + (status & 0x7F)
|
|
1047
|
+
else:
|
|
1048
|
+
import os
|
|
1049
|
+
import subprocess
|
|
1050
|
+
|
|
1051
|
+
env = dict(os.environ)
|
|
1052
|
+
env["OMNIPYTHON_SUPERVISED"] = "1"
|
|
1053
|
+
env["APPKIT_RESTART_FILE"] = flag
|
|
1054
|
+
code = subprocess.call(cmd, env=env)
|
|
1055
|
+
asked = _take_flag(flag)
|
|
1056
|
+
if code != RESTART_EXIT_CODE and not asked:
|
|
1057
|
+
return code
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def main(argv=None):
|
|
1061
|
+
"""``python -m appkit.launcher [--] <command>``: run a launcher program,
|
|
1062
|
+
restarting it whenever it asks."""
|
|
1063
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
1064
|
+
if argv and argv[0] == "--":
|
|
1065
|
+
argv = argv[1:]
|
|
1066
|
+
if not argv or argv[0] in ("-h", "--help"):
|
|
1067
|
+
print("usage: python -m appkit.launcher [--] <command ...>")
|
|
1068
|
+
print("Runs <command> and starts it again each time it exits with code %d," % RESTART_EXIT_CODE)
|
|
1069
|
+
print("which is how an appkit launcher program restarts into another app.")
|
|
1070
|
+
return 0 if argv else 2
|
|
1071
|
+
return supervise(argv)
|
|
1072
|
+
|
|
1073
|
+
|
|
1074
|
+
if __name__ == "__main__":
|
|
1075
|
+
sys.exit(main())
|