omnipython-applibs 0.1.2__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.
Files changed (143) hide show
  1. appkit/__init__.py +52 -0
  2. appkit/__init__.pyi +17 -0
  3. appkit/data.py +149 -0
  4. appkit/data.pyi +25 -0
  5. appkit/foreground.py +357 -0
  6. appkit/foreground.pyi +45 -0
  7. appkit/home.py +19 -0
  8. appkit/home.pyi +8 -0
  9. appkit/hover.py +59 -0
  10. appkit/hover.pyi +13 -0
  11. appkit/index.py +199 -0
  12. appkit/index.pyi +30 -0
  13. appkit/launcher.py +1075 -0
  14. appkit/launcher.pyi +96 -0
  15. appkit/manifest.py +75 -0
  16. appkit/manifest.pyi +8 -0
  17. appkit/net.py +167 -0
  18. appkit/net.pyi +34 -0
  19. appkit/places.py +202 -0
  20. appkit/places.pyi +39 -0
  21. appkit/py.typed +0 -0
  22. appkit/scope.py +636 -0
  23. appkit/scope.pyi +110 -0
  24. appkit/shell.py +121 -0
  25. appkit/shell.pyi +32 -0
  26. appkit/worker.py +409 -0
  27. appkit/worker.pyi +83 -0
  28. controlkit/__init__.py +19 -0
  29. controlkit/__init__.pyi +10 -0
  30. controlkit/_draw.py +88 -0
  31. controlkit/_safe.py +29 -0
  32. controlkit/dotmatrix.py +101 -0
  33. controlkit/dotmatrix.pyi +23 -0
  34. controlkit/encoder.py +297 -0
  35. controlkit/encoder.pyi +55 -0
  36. controlkit/font5x7.py +22 -0
  37. controlkit/font5x7.pyi +11 -0
  38. controlkit/lamp_button.py +92 -0
  39. controlkit/lamp_button.pyi +40 -0
  40. controlkit/meter.py +86 -0
  41. controlkit/meter.pyi +30 -0
  42. controlkit/mock.py +116 -0
  43. controlkit/mock.pyi +35 -0
  44. controlkit/pad_grid.py +113 -0
  45. controlkit/pad_grid.pyi +41 -0
  46. controlkit/py.typed +0 -0
  47. controlkit/slider.py +185 -0
  48. controlkit/slider.pyi +49 -0
  49. controlkit/sprites.py +279 -0
  50. controlkit/sprites.pyi +22 -0
  51. controlkit/theme.py +120 -0
  52. controlkit/theme.pyi +15 -0
  53. deskkit/__init__.py +74 -0
  54. deskkit/__init__.pyi +18 -0
  55. deskkit/forecast.py +261 -0
  56. deskkit/forecast.pyi +40 -0
  57. deskkit/localtime.py +215 -0
  58. deskkit/localtime.pyi +33 -0
  59. deskkit/py.typed +0 -0
  60. deskkit/shell.py +113 -0
  61. deskkit/shell.pyi +33 -0
  62. omnipython_applibs-0.1.2.dist-info/METADATA +90 -0
  63. omnipython_applibs-0.1.2.dist-info/RECORD +143 -0
  64. omnipython_applibs-0.1.2.dist-info/WHEEL +5 -0
  65. omnipython_applibs-0.1.2.dist-info/licenses/LICENSE +21 -0
  66. omnipython_applibs-0.1.2.dist-info/top_level.txt +9 -0
  67. programkit/__init__.py +27 -0
  68. programkit/__init__.pyi +8 -0
  69. programkit/board.py +56 -0
  70. programkit/board.pyi +20 -0
  71. programkit/press.py +63 -0
  72. programkit/press.pyi +17 -0
  73. programkit/py.typed +0 -0
  74. programkit/rows.py +149 -0
  75. programkit/rows.pyi +34 -0
  76. sayso/__init__.py +109 -0
  77. sayso/__init__.pyi +124 -0
  78. sayso/auth.py +811 -0
  79. sayso/auth.pyi +102 -0
  80. sayso/client.py +1286 -0
  81. sayso/client.pyi +138 -0
  82. sayso/keepalive.py +371 -0
  83. sayso/keepalive.pyi +53 -0
  84. sayso/local.py +85 -0
  85. sayso/local.pyi +28 -0
  86. sayso/object_specs.py +706 -0
  87. sayso/object_specs.pyi +8 -0
  88. sayso/objects.py +411 -0
  89. sayso/objects.pyi +854 -0
  90. sayso/py.typed +0 -0
  91. sayso/schema_coverage.py +210 -0
  92. sayso/schema_coverage.pyi +13 -0
  93. sayso/transport.py +426 -0
  94. sayso/transport.pyi +47 -0
  95. songmodel/__init__.py +30 -0
  96. songmodel/__init__.pyi +9 -0
  97. songmodel/link.py +189 -0
  98. songmodel/link.pyi +53 -0
  99. songmodel/model.py +238 -0
  100. songmodel/model.pyi +40 -0
  101. songmodel/page.html +225 -0
  102. songmodel/page_data.py +236 -0
  103. songmodel/page_data.pyi +6 -0
  104. songmodel/py.typed +0 -0
  105. soundmodule/__init__.py +7 -0
  106. soundmodule/__init__.pyi +6 -0
  107. soundmodule/engine.py +1001 -0
  108. soundmodule/engine.pyi +196 -0
  109. soundmodule/names.py +298 -0
  110. soundmodule/names.pyi +30 -0
  111. soundmodule/pipes.py +105 -0
  112. soundmodule/pipes.pyi +31 -0
  113. soundmodule/py.typed +0 -0
  114. soundmodule/run.py +249 -0
  115. soundmodule/run.pyi +49 -0
  116. spectrum/__init__.py +72 -0
  117. spectrum/__init__.pyi +30 -0
  118. spectrum/analyzer.py +231 -0
  119. spectrum/analyzer.pyi +67 -0
  120. spectrum/fake_music.py +201 -0
  121. spectrum/fake_music.pyi +36 -0
  122. spectrum/pump_levels.py +126 -0
  123. spectrum/pump_levels.pyi +46 -0
  124. spectrum/py.typed +0 -0
  125. spectrum/spectrum_view.py +403 -0
  126. spectrum/spectrum_view.pyi +80 -0
  127. touchkit/__init__.py +4 -0
  128. touchkit/__init__.pyi +4 -0
  129. touchkit/cam.py +146 -0
  130. touchkit/cam.pyi +35 -0
  131. touchkit/clock.py +18 -0
  132. touchkit/clock.pyi +6 -0
  133. touchkit/ecp.py +134 -0
  134. touchkit/ecp.pyi +28 -0
  135. touchkit/net.py +347 -0
  136. touchkit/net.pyi +27 -0
  137. touchkit/py.typed +0 -0
  138. touchkit/settings.py +85 -0
  139. touchkit/settings.pyi +17 -0
  140. touchkit/shell.py +268 -0
  141. touchkit/shell.pyi +42 -0
  142. touchkit/ui.py +167 -0
  143. touchkit/ui.pyi +53 -0
appkit/scope.py ADDED
@@ -0,0 +1,636 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """AppScope: what one switchable app made, and how to take it all back.
5
+
6
+ An app that can be switched out has to give back everything it made, or
7
+ its RAM stays behind. What keeps an app's memory alive after it has gone is
8
+ references: a timer or event callback pointing at its functions, a device it
9
+ registered, an LVGL screen, its entry in ``sys.modules``, anything it parked
10
+ in another module's global. An ``AppScope`` records what the app makes
11
+ through it, and `AppScope.close` undoes all of it.
12
+
13
+ ::
14
+
15
+ def main(scope):
16
+ @scope.every(1000)
17
+ def tick(timer):
18
+ ...
19
+
20
+ scope.on(events.KEYDOWN, on_key)
21
+ screen = scope.screen() # an LVGL screen, deleted at close
22
+
23
+ # later, usually from appkit.launcher:
24
+ problems = scope.close() # [] when everything was released
25
+
26
+ Shared services (the display, touch, the power chip) belong to the long-lived
27
+ ``App``; an app borrows them through ``scope.app`` and must not close them.
28
+ See appkit's README.md.
29
+ """
30
+
31
+ import gc
32
+ import sys
33
+
34
+ import multimer
35
+
36
+ try:
37
+ import weakref
38
+ except ImportError: # MicroPython: no weak references
39
+ weakref = None
40
+
41
+
42
+ #: Every scope not yet closed, oldest first.
43
+ _open = []
44
+
45
+
46
+ def open_scopes(app=None):
47
+ """The scopes not yet closed, oldest first; only *app*'s when given."""
48
+ return [s for s in _open if app is None or s.app is app]
49
+
50
+
51
+ #: What ``AppScope.store()`` hands out, by app name: kept for the whole run.
52
+ _stores = {}
53
+
54
+ #: Apps that close their open scopes when they quit.
55
+ _closing_at_quit = []
56
+
57
+
58
+ def _close_at_quit(app):
59
+ """Once per App: when it quits, close the scopes still open on it, so an
60
+ app's timers stop with the program."""
61
+ if any(a is app for a in _closing_at_quit):
62
+ return
63
+ on_quit = getattr(app, "on_quit", None)
64
+ if on_quit is None: # an appdev from before on_quit
65
+ return
66
+ _closing_at_quit.append(app)
67
+
68
+ def close_all():
69
+ for scope in open_scopes(app):
70
+ scope.close()
71
+ _closing_at_quit.remove(app)
72
+
73
+ on_quit(close_all)
74
+
75
+
76
+ def mem_free():
77
+ """Free GC heap in bytes after a collection, or None where it can't be read."""
78
+ fn = getattr(gc, "mem_free", None)
79
+ if fn is None:
80
+ return None
81
+ gc.collect()
82
+ return fn()
83
+
84
+
85
+ def _lvgl():
86
+ """The lvgl module when it is loaded and initialised, else None.
87
+
88
+ MicroPython and CircuitPython keep built-in modules out of
89
+ ``sys.modules``, so there an import (free for a built-in, an ImportError
90
+ without one) is the test.
91
+ """
92
+ lv = sys.modules.get("lvgl")
93
+ if lv is None and sys.implementation.name in ("micropython", "circuitpython"):
94
+ try:
95
+ import lvgl as lv
96
+ except ImportError:
97
+ return None
98
+ if lv is None:
99
+ return None
100
+ try:
101
+ if not lv.is_initialized():
102
+ return None
103
+ except AttributeError:
104
+ pass
105
+ return lv
106
+
107
+
108
+ def _error(what, exc):
109
+ return "%s: %s: %s" % (what, type(exc).__name__, exc)
110
+
111
+
112
+ def _same(a, b):
113
+ try:
114
+ return a is b or a == b
115
+ except Exception:
116
+ return a is b
117
+
118
+
119
+ def _check_probes(probes, problems):
120
+ """Collect, then report each module or main that is still referenced."""
121
+ gc.collect()
122
+ # A cycle that holds an object with a finalizer is freed by the
123
+ # collection after the one that finalised it (PEP 442), so give
124
+ # the probes one more before calling anything a leak.
125
+ if any(ref() is not None for label, ref in probes):
126
+ gc.collect()
127
+ for label, ref in probes:
128
+ if ref() is not None:
129
+ problems.append("%s still referenced after close: something kept a reference to the app" % label)
130
+
131
+
132
+ class AppScope:
133
+ """What one app made, through its scope; ``close()`` releases it.
134
+
135
+ It has the same ``every``, ``after``, ``on``, ``off``, ``register`` and
136
+ timer surface as ``App``, and records each thing it makes. Things made
137
+ straight on ``scope.app`` are shared and are not released by ``close()``.
138
+ """
139
+
140
+ def __init__(self, app, name=None, *, modules=()):
141
+ self.app = app
142
+ self.name = name
143
+ self.launcher = None
144
+ self._modules = list(modules)
145
+ self._timers = []
146
+ self._subs = [] # (event_type, callback)
147
+ self._dev_subs = [] # (device, callback)
148
+ self._devices = []
149
+ self._adopted = [] # (obj, closer)
150
+ self._screens = []
151
+ self._on_close = []
152
+ self._lv_base = None # (screen, [(parent, child_count), ...])
153
+ #: The LVGL object the app builds on, its ``(width, height)`` and its
154
+ #: ``(x, y, width, height)`` on the panel: set by the launcher's shell
155
+ #: before ``main`` runs, None without one.
156
+ self.root = None
157
+ self.size = None
158
+ self.rect = None
159
+ self._worker = None
160
+ self._data_dir = None
161
+ self._closed = False
162
+ self._closing = False
163
+ self.problems = []
164
+ #: Bytes the app still held after close() (MicroPython), or None.
165
+ self.retained = None
166
+ self.free_after_close = None
167
+ self._free_at_open = mem_free()
168
+ self._snapshot_lvgl()
169
+ _open.append(self)
170
+ _close_at_quit(app)
171
+
172
+ # -- passthrough to the shared App -----------------------------------
173
+
174
+ @property
175
+ def displays(self):
176
+ return self.app.displays
177
+
178
+ @property
179
+ def primary(self):
180
+ return self.app.primary
181
+
182
+ @property
183
+ def closed(self):
184
+ return self._closed
185
+
186
+ @property
187
+ def timers(self):
188
+ """This app's timers that are still armed."""
189
+ return tuple(t for t in self._timers if t.running)
190
+
191
+ # -- services -------------------------------------------------------
192
+
193
+ @property
194
+ def worker(self):
195
+ """The shared background thread, as this app sees it.
196
+
197
+ ``scope.worker.submit(work, done, key=None)`` runs ``work()`` in the
198
+ background and then ``done(value, error)`` on the main thread. What
199
+ the app queued and hasn't started is dropped when it closes. Where
200
+ there are no threads the work runs on a timer. See ``appkit.worker``.
201
+ """
202
+ w = self._worker
203
+ if w is None:
204
+ self._check_open()
205
+ from .worker import ScopedWorker, shared
206
+
207
+ w = self._worker = ScopedWorker(shared(), self)
208
+ return w
209
+
210
+ @worker.setter
211
+ def worker(self, value):
212
+ self._worker = value
213
+
214
+ @property
215
+ def data_dir(self):
216
+ """A folder for this app's own files, made on first use: ``<data
217
+ root>/<app>``. See ``appkit.data`` for where the data root is."""
218
+ d = self._data_dir
219
+ if d is None:
220
+ if not self.name:
221
+ raise ValueError("an unnamed scope has no data_dir")
222
+ from .data import app_dir
223
+
224
+ d = self._data_dir = app_dir(self.name)
225
+ return d
226
+
227
+ @data_dir.setter
228
+ def data_dir(self, value):
229
+ self._data_dir = value
230
+
231
+ def data_dir_of(self, name):
232
+ """App *name*'s folder, made on first use, as ``store(name)`` is its
233
+ dict: for an app that shows another's files (the camera's photos,
234
+ say). ``data_dir_of(scope.name)`` is ``scope.data_dir``."""
235
+ if name == self.name:
236
+ return self.data_dir
237
+ from .data import app_dir
238
+
239
+ return app_dir(name)
240
+
241
+ def store(self, name=None):
242
+ """A dict in RAM that outlives this app's close: its own, or app *name*'s.
243
+
244
+ For what an app wants back when it opens again in this run: a
245
+ position, a choice, the last answer from the network. It is never
246
+ written to flash; save what must survive a reboot in ``data_dir``.
247
+ Keep plain data in it (numbers, strings, lists, dicts): a function
248
+ or an object of the app's would keep the whole app in memory.
249
+ """
250
+ key = name if name is not None else self.name
251
+ d = _stores.get(key)
252
+ if d is None:
253
+ d = _stores[key] = {}
254
+ return d
255
+
256
+ def _check_open(self):
257
+ if self._closed or self._closing:
258
+ raise RuntimeError("scope %r is closed" % (self.name,))
259
+
260
+ # -- timers ---------------------------------------------------------
261
+
262
+ def every(self, ms=None, callback=None, *, period=None, name=None):
263
+ """A periodic ``multimer.Timer`` owned by this app (``App.every``'s shape)."""
264
+ from appdev.app import SERVICE_TICK_MS
265
+
266
+ if period is not None:
267
+ if callable(ms) and callback is None:
268
+ callback = ms
269
+ ms = period
270
+ if ms is None:
271
+ ms = SERVICE_TICK_MS
272
+ if callback is None:
273
+ if callable(ms):
274
+ callback = ms
275
+ ms = SERVICE_TICK_MS
276
+ else:
277
+ return lambda fn: self.every(ms, fn, name=name)
278
+ if not callable(callback):
279
+ raise ValueError("callback must be callable")
280
+ self._check_open()
281
+ tim = multimer.every(int(ms), callback, name=name)
282
+ self._timers.append(tim)
283
+ self.app._keep_alive()
284
+ return tim
285
+
286
+ def after(self, ms, callback=None, *, name=None):
287
+ """A one-shot ``multimer.Timer`` owned by this app."""
288
+ if callback is None:
289
+ return lambda fn: self.after(ms, fn, name=name)
290
+ if not callable(callback):
291
+ raise ValueError("callback must be callable")
292
+ self._check_open()
293
+ # Fired one-shots leave the list here, so a long-lived app that keeps
294
+ # scheduling them doesn't grow it.
295
+ self._timers = [t for t in self._timers if t.running]
296
+ tim = multimer.after(int(ms), callback, name=name)
297
+ self._timers.append(tim)
298
+ self.app._keep_alive()
299
+ return tim
300
+
301
+ def stop_timers(self):
302
+ """Cancel every timer this app made."""
303
+ timers = self._timers
304
+ self._timers = []
305
+ for t in timers:
306
+ try:
307
+ t.deinit()
308
+ except Exception as exc:
309
+ self.problems.append(_error("timer %r" % (t,), exc))
310
+
311
+ # -- events ---------------------------------------------------------
312
+
313
+ def on(self, event_type_or_list, callback=None):
314
+ """Subscribe to App events, as ``App.on``; dropped at close."""
315
+ if callback is None:
316
+ return lambda fn: self.on(event_type_or_list, fn)
317
+ if not callable(callback):
318
+ raise ValueError("callback must be callable")
319
+ self._check_open()
320
+ if isinstance(event_type_or_list, (list, tuple, set)):
321
+ for et in event_type_or_list:
322
+ self.on(et, callback)
323
+ return callback
324
+ self.app.on(event_type_or_list, callback)
325
+ self._subs.append((event_type_or_list, callback))
326
+ return callback
327
+
328
+ def off(self, event_type_or_list, callback):
329
+ """Unsubscribe, as ``App.off``."""
330
+ if isinstance(event_type_or_list, (list, tuple, set)):
331
+ for et in event_type_or_list:
332
+ self.off(et, callback)
333
+ return
334
+ self.app.off(event_type_or_list, callback)
335
+ self._subs = [s for s in self._subs if not (s[0] == event_type_or_list and s[1] is callback)]
336
+
337
+ def subscribe(self, device, callback, event_types=None):
338
+ """``device.subscribe(callback)`` on a shared device; unsubscribed at close."""
339
+ self._check_open()
340
+ device.subscribe(callback, event_types)
341
+ self._dev_subs.append((device, callback))
342
+ return callback
343
+
344
+ # -- devices --------------------------------------------------------
345
+
346
+ def register(self, dev):
347
+ """Register a device with the App, as ``App.register``; unregistered at close."""
348
+ self._check_open()
349
+ self.app.register(dev)
350
+ if dev not in self._devices:
351
+ self._devices.append(dev)
352
+ return dev
353
+
354
+ def unregister(self, dev):
355
+ self.app.unregister(dev)
356
+ if dev in self._devices:
357
+ self._devices.remove(dev)
358
+
359
+ # -- anything else --------------------------------------------------
360
+
361
+ def adopt(self, obj, close=None):
362
+ """Own *obj* until close: then ``close(obj)``, or its ``delete()``,
363
+ ``deinit()`` or ``close()``, whichever it has.
364
+
365
+ For LVGL objects and timers not on a scope screen, a ``machine.Pin``
366
+ IRQ, a socket, a file. Returns *obj*.
367
+ """
368
+ self._check_open()
369
+ self._adopted.append((obj, close))
370
+ return obj
371
+
372
+ def on_close(self, fn):
373
+ """Call ``fn()`` first thing in close(). Usable as a decorator."""
374
+ if not callable(fn):
375
+ raise ValueError("on_close needs a callable")
376
+ self._check_open()
377
+ self._on_close.append(fn)
378
+ return fn
379
+
380
+ def foreground(self, fn, *, steps=True):
381
+ """Have the program's main-thread loop call ``fn()`` over and over
382
+ until this app closes, or until ``foreground(None)``.
383
+
384
+ For work too heavy for a timer: a camera frame, an audio copy. *fn*
385
+ runs outside every timer callback. Where nothing runs the loop (see
386
+ ``appkit.serve()``), *fn* runs from a timer instead when it does one
387
+ step and returns; one that never returns (``steps=False``) waits for
388
+ the loop. Returns True when *fn* runs now, False when it waits. See
389
+ ``appkit.foreground``.
390
+ """
391
+ from . import foreground
392
+
393
+ if fn is not None:
394
+ self._check_open()
395
+ return foreground.set_function(self, fn, steps)
396
+
397
+ def switch(self, name):
398
+ """Ask the launcher to switch to app *name*, after this callback returns."""
399
+ if self.launcher is None:
400
+ raise RuntimeError("this scope has no launcher")
401
+ self.launcher.request(name)
402
+
403
+ # -- LVGL -----------------------------------------------------------
404
+
405
+ def screen(self, load=True):
406
+ """A new LVGL screen for this app, loaded unless ``load=False``.
407
+
408
+ Deleting a screen deletes everything on it, so an app that builds
409
+ its UI on its scope screen gives all of it back at close.
410
+ """
411
+ import lvgl as lv
412
+
413
+ self._check_open()
414
+ scr = lv.obj(None)
415
+ self._screens.append(scr)
416
+ if load:
417
+ lv.screen_load(scr)
418
+ return scr
419
+
420
+ def _snapshot_lvgl(self):
421
+ # Widgets an app adds to the screen that was showing when it started,
422
+ # or to the top and system layers, are its own: close() deletes the
423
+ # children those had gained.
424
+ lv = _lvgl()
425
+ if lv is None:
426
+ return
427
+ try:
428
+ if lv.display_get_default() is None:
429
+ return
430
+ base = lv.screen_active()
431
+ parents = []
432
+ for parent in (base, lv.layer_top(), lv.layer_sys()):
433
+ if parent is not None:
434
+ parents.append((parent, parent.get_child_count()))
435
+ self._lv_base = (base, parents)
436
+ except Exception:
437
+ self._lv_base = None
438
+
439
+ def _close_lvgl(self, problems):
440
+ lv = _lvgl() if (self._screens or self._lv_base) else None
441
+ if lv is None:
442
+ self._screens = []
443
+ self._lv_base = None
444
+ return
445
+ base = self._lv_base[0] if self._lv_base else None
446
+ try:
447
+ active = lv.screen_active()
448
+ if base is not None and any(_same(active, s) for s in self._screens):
449
+ lv.screen_load(base)
450
+ except Exception as exc:
451
+ problems.append(_error("lvgl screen_load", exc))
452
+ if self._lv_base:
453
+ for parent, count in self._lv_base[1]:
454
+ try:
455
+ n = parent.get_child_count()
456
+ for i in range(n - 1, count - 1, -1):
457
+ parent.get_child(i).delete()
458
+ except Exception as exc:
459
+ problems.append(_error("lvgl children", exc))
460
+ for scr in reversed(self._screens):
461
+ try:
462
+ scr.delete()
463
+ except Exception as exc:
464
+ problems.append(_error("lvgl screen", exc))
465
+ self._screens = []
466
+ self._lv_base = None
467
+
468
+ # -- close ----------------------------------------------------------
469
+
470
+ def close(self):
471
+ """Release everything this app made; return what couldn't be released.
472
+
473
+ In order: its foreground function (see `foreground`), the
474
+ ``on_close`` hooks, the worker jobs it queued, timers,
475
+ event subscriptions, devices, adopted objects, LVGL objects, then the
476
+ app's modules leave ``sys.modules`` and the heap is collected. Each step runs even when
477
+ an earlier one fails. Safe to call twice; the second call does
478
+ nothing and returns the same list.
479
+
480
+ The list holds one line per failure. On CPython it also names an app
481
+ module whose namespace is still reachable after close, which is a
482
+ leak: something kept a reference to the app.
483
+ """
484
+ if self._closed or self._closing:
485
+ return self.problems
486
+ self._closing = True
487
+ problems = self.problems
488
+ probes = []
489
+ busy = False
490
+ try:
491
+ # In a function of its own, so that none of its locals (the last
492
+ # callback a loop saw, say) is still holding the app while the
493
+ # probes below look for what is. Under a hold, so none of the
494
+ # app's timers runs in the middle of it: on hosts that deliver
495
+ # between bytecodes one otherwise can, and finds it half closed.
496
+ with multimer.hold():
497
+ probes, busy = self._release(problems)
498
+ finally:
499
+ if self in _open:
500
+ _open.remove(self)
501
+ self._closed = True
502
+ self._closing = False
503
+ if probes:
504
+ if busy:
505
+ # close() runs inside the app's own foreground function, so
506
+ # the call still holds the app's module: look once it returns.
507
+ from appkit import foreground
508
+
509
+ foreground.after_calls(_check_probes, probes, problems)
510
+ else:
511
+ _check_probes(probes, problems)
512
+ probes = None
513
+ # mem_free() collects first. Where it can't read the heap, collect
514
+ # anyway: close() always gives the memory back.
515
+ free = mem_free()
516
+ if free is None:
517
+ gc.collect()
518
+ #: Free heap just after close (MicroPython), or None.
519
+ self.free_after_close = free
520
+ if free is not None and self._free_at_open is not None:
521
+ self.retained = self._free_at_open - free
522
+ return problems
523
+
524
+ def _release(self, problems):
525
+ # Returns (probes, busy): busy when the app's foreground function is
526
+ # in a call now, so the probes must wait for it to return.
527
+ # First, so the loop stops calling the app's function.
528
+ fg = sys.modules.get("appkit.foreground") # loaded only if an app used it
529
+ busy = False
530
+ if fg is not None:
531
+ busy = fg.calling(self)
532
+ fg.clear(self)
533
+ fg = None
534
+ hooks = self._on_close
535
+ self._on_close = []
536
+ for fn in reversed(hooks):
537
+ try:
538
+ fn()
539
+ except Exception as exc:
540
+ problems.append(_error("on_close %r" % (fn,), exc))
541
+ w = self._worker
542
+ self._worker = None
543
+ if w is not None:
544
+ try:
545
+ w.cancel()
546
+ except Exception as exc:
547
+ problems.append(_error("worker cancel", exc))
548
+ w = None
549
+ self.stop_timers()
550
+ for et, cb in self._subs:
551
+ try:
552
+ self.app.off(et, cb)
553
+ except Exception as exc:
554
+ problems.append(_error("off %r" % (et,), exc))
555
+ self._subs = []
556
+ for dev, cb in self._dev_subs:
557
+ try:
558
+ dev.unsubscribe(cb)
559
+ except Exception as exc:
560
+ problems.append(_error("unsubscribe %r" % (dev,), exc))
561
+ self._dev_subs = []
562
+ for dev in self._devices:
563
+ try:
564
+ self.app.unregister(dev)
565
+ except Exception as exc:
566
+ problems.append(_error("unregister %r" % (dev,), exc))
567
+ self._devices = []
568
+ adopted = self._adopted
569
+ self._adopted = []
570
+ for obj, closer in reversed(adopted):
571
+ try:
572
+ if closer is not None:
573
+ closer(obj)
574
+ else:
575
+ for meth in ("delete", "deinit", "close"):
576
+ fn = getattr(obj, meth, None)
577
+ if callable(fn):
578
+ fn()
579
+ break
580
+ else:
581
+ if callable(obj):
582
+ obj()
583
+ except Exception as exc:
584
+ problems.append(_error("adopted %r" % (obj,), exc))
585
+ self._close_lvgl(problems)
586
+ return self._purge_modules(problems), busy
587
+
588
+ def _purge_modules(self, problems):
589
+ probes = []
590
+ if not self._modules:
591
+ return probes
592
+ names = []
593
+ for key in list(sys.modules):
594
+ for root in self._modules:
595
+ if key == root or key.startswith(root + "."):
596
+ names.append(key)
597
+ break
598
+ for key in names:
599
+ mod = sys.modules.pop(key, None)
600
+ if mod is None:
601
+ continue
602
+ if weakref is not None:
603
+ for label, obj in (("module %r" % key, mod), ("%s.main" % key, getattr(mod, "main", None))):
604
+ if obj is None:
605
+ continue
606
+ try:
607
+ probes.append((label, weakref.ref(obj)))
608
+ except TypeError:
609
+ pass
610
+ # A submodule is also an attribute of its parent package.
611
+ if "." in key:
612
+ parent_name, leaf = key.rsplit(".", 1)
613
+ parent = sys.modules.get(parent_name)
614
+ if parent is not None and getattr(parent, leaf, None) is mod:
615
+ try:
616
+ delattr(parent, leaf)
617
+ except Exception as exc:
618
+ problems.append(_error("unbind %s from %s" % (leaf, parent_name), exc))
619
+ mod = None
620
+ return probes
621
+
622
+ def __enter__(self):
623
+ return self
624
+
625
+ def __exit__(self, exc_type, exc, tb):
626
+ self.close()
627
+ return False
628
+
629
+ def __repr__(self):
630
+ return "AppScope(%r, timers=%d, subs=%d, devices=%d%s)" % (
631
+ self.name,
632
+ len(self._timers),
633
+ len(self._subs),
634
+ len(self._devices),
635
+ ", closed" if self._closed else "",
636
+ )