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.pyi ADDED
@@ -0,0 +1,110 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Everything an app makes through its scope, released when the app closes."""
5
+
6
+ import types
7
+ from collections.abc import Callable
8
+ from typing import Any, Protocol, TypeVar, overload
9
+
10
+ _F = TypeVar('_F', bound=Callable[..., Any])
11
+ _T = TypeVar('_T')
12
+
13
+ class _Timer(Protocol):
14
+ @property
15
+ def running(self) -> bool: ...
16
+ def deinit(self) -> None: ...
17
+
18
+ class _App(Protocol):
19
+ @property
20
+ def displays(self) -> Any: ...
21
+ @property
22
+ def primary(self) -> Any: ...
23
+ def on(self, event_type: Any, callback: Callable[..., Any]) -> Any: ...
24
+ def off(self, event_type: Any, callback: Callable[..., Any]) -> Any: ...
25
+ def register(self, dev: Any) -> Any: ...
26
+ def unregister(self, dev: Any) -> Any: ...
27
+
28
+ def open_scopes(app: _App | None = None) -> list[AppScope]:
29
+ """Every scope not yet closed, oldest first; only `app`'s when given."""
30
+ def mem_free() -> int | None:
31
+ """Free GC heap in bytes after a collection, or None where it can't be read."""
32
+
33
+ class AppScope:
34
+ """What one app made, through its scope; `close()` releases it."""
35
+
36
+ app: _App
37
+ name: str | None
38
+ launcher: Any
39
+ root: Any
40
+ size: tuple[int, int] | None
41
+ rect: tuple[int, int, int, int] | None
42
+ problems: list[str]
43
+ retained: int | None
44
+ free_after_close: int | None
45
+ def __init__(self, app: _App, name: str | None = None, *, modules: tuple[str, ...] | list[str] = ()) -> None: ...
46
+ @property
47
+ def displays(self) -> Any:
48
+ """The app's displays."""
49
+ @property
50
+ def primary(self) -> Any:
51
+ """The app's primary display."""
52
+ @property
53
+ def closed(self) -> bool: ...
54
+ @property
55
+ def timers(self) -> tuple[_Timer, ...]:
56
+ """This app's timers that are still armed."""
57
+ @property
58
+ def worker(self) -> Any:
59
+ """The shared background thread, as this app sees it."""
60
+ @worker.setter
61
+ def worker(self, value: Any) -> None: ...
62
+ @property
63
+ def data_dir(self) -> str:
64
+ """A folder for this app's own files, made on first use."""
65
+ @data_dir.setter
66
+ def data_dir(self, value: str | None) -> None: ...
67
+ def data_dir_of(self, name: str) -> str:
68
+ """App `name`'s folder, made on first use."""
69
+ def store(self, name: str | None = None) -> dict[str, Any]:
70
+ """A dict in RAM that outlives this app's close: its own, or app `name`'s."""
71
+ @overload
72
+ def every(self, ms: int | None, callback: Callable[[Any], Any], *, period: None = None, name: str | None = None) -> _Timer: ...
73
+ @overload
74
+ def every(self, ms: Callable[[Any], Any], callback: None = None, *, period: None = None, name: str | None = None) -> _Timer: ...
75
+ @overload
76
+ def every(self, ms: None = None, *, callback: Callable[[Any], Any], period: int | None = None, name: str | None = None) -> _Timer: ...
77
+ @overload
78
+ def every(self, ms: int | None = None, callback: None = None, *, period: None = None, name: str | None = None) -> Callable[[_F], _F]: ...
79
+ @overload
80
+ def after(self, ms: int, callback: Callable[[Any], Any], *, name: str | None = None) -> _Timer: ...
81
+ @overload
82
+ def after(self, ms: int, callback: None = None, *, name: str | None = None) -> Callable[[_F], _F]: ...
83
+ def stop_timers(self) -> None:
84
+ """Cancel every timer this app made."""
85
+ @overload
86
+ def on(self, event_type_or_list: Any, callback: _F) -> _F: ...
87
+ @overload
88
+ def on(self, event_type_or_list: Any, callback: None = None) -> Callable[[_F], _F]: ...
89
+ def off(self, event_type_or_list: Any, callback: Callable[..., Any]) -> None:
90
+ """Unsubscribe from App events."""
91
+ def subscribe(self, device: Any, callback: _F, event_types: Any = None) -> _F:
92
+ """`device.subscribe(callback)` on a shared device; unsubscribed at close."""
93
+ def register(self, dev: _T) -> _T:
94
+ """Register a device with the App; unregistered at close."""
95
+ def unregister(self, dev: Any) -> None:
96
+ """Unregister a device."""
97
+ def adopt(self, obj: _T, close: Callable[[_T], Any] | None = None) -> _T:
98
+ """Own `obj` until close: then `close(obj)`, or its `delete()`, `deinit()` or `close()`."""
99
+ def on_close(self, fn: _F) -> _F:
100
+ """Call `fn()` first thing in close(). Usable as a decorator."""
101
+ def foreground(self, fn: Callable[[], Any] | None, *, steps: bool = True) -> bool:
102
+ """Have the program's main-thread loop call `fn()` over and over until this app closes."""
103
+ def switch(self, name: str) -> None:
104
+ """Ask the launcher to switch to app `name`, after this callback returns."""
105
+ def screen(self, load: bool = True) -> Any:
106
+ """A new LVGL screen for this app, loaded unless `load` is False."""
107
+ def close(self) -> list[str]:
108
+ """Release everything this app made; return what couldn't be released."""
109
+ def __enter__(self) -> AppScope: ...
110
+ def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> bool: ...
appkit/shell.py ADDED
@@ -0,0 +1,121 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Shell: what's around an app, and what it hands each app's scope.
5
+
6
+ This one is the plainest: an app gets the whole screen, and a Home button
7
+ sits in the corner when there's a home screen to go back to. On a round
8
+ screen (`is_round`) the button is a circle with the Home icon, set in
9
+ from the top right along the diagonal so all of it is inside the circle. A board that
10
+ wants a header, its own look or its own buttons subclasses it: override
11
+ `Shell.make_root` to give apps a smaller area,
12
+ `Shell.make_home_button` for its own Home button, or
13
+ `Shell.prepare` to hand them other services.
14
+ """
15
+
16
+ import sys
17
+
18
+ import lvgl as lv
19
+ from iconkit import lvicons
20
+
21
+ from . import data, hover
22
+
23
+ #: How far a round screen's Home button keeps in from the circle's edge, in pixels.
24
+ ROUND_MARGIN = 4
25
+
26
+
27
+ def is_round():
28
+ """Whether the default display is a round panel.
29
+
30
+ The board's display driver says so with a ``round`` attribute; without
31
+ one, a GC9A01 is taken to be round, since the controller is made for
32
+ round panels. A screen that isn't square never is. It only looks at a
33
+ ``board_config`` something has already imported, so it imports nothing.
34
+ """
35
+ disp = lv.display_get_default()
36
+ if disp is None or disp.get_horizontal_resolution() != disp.get_vertical_resolution():
37
+ return False
38
+ board = sys.modules.get("board_config")
39
+ drv = getattr(board, "display_drv", None)
40
+ if drv is None:
41
+ return False
42
+ r = getattr(drv, "round", None)
43
+ if r is None:
44
+ r = type(drv).__name__.upper().startswith("GC9A01")
45
+ return bool(r)
46
+
47
+
48
+ def round_corner(size, d, margin=ROUND_MARGIN):
49
+ """Where a *d*-pixel circle goes at the top right of a round screen
50
+ *size* pixels across: ``(x, y)`` of its top left, on the diagonal, as
51
+ far out as it can go and stay *margin* pixels inside the edge."""
52
+ r = size // 2
53
+ off = int((r - margin - d / 2) * 0.7071) # along the diagonal, cos 45
54
+ return r + off - d // 2, r - off - d // 2
55
+
56
+
57
+ class Shell:
58
+ """*data_root* moves every app's ``data_dir``, and the launcher's
59
+ restart file, for the whole program (see ``appkit.data``)."""
60
+
61
+ def __init__(self, launcher, *, data_root=None):
62
+ self.launcher = launcher
63
+ self.home_button = None
64
+ if data_root is not None:
65
+ data.set_root(data_root)
66
+ hover.apply()
67
+ if launcher.home is not None:
68
+ # Made before any app starts, so no app's close() deletes it.
69
+ self.home_button = self.make_home_button()
70
+
71
+ def make_home_button(self):
72
+ """The Home button, made once when the shell is: an LVGL object that
73
+ switches to the home screen when clicked, or None for no button.
74
+
75
+ Override it for a button of your own look. Put it on
76
+ ``lv.layer_top()`` or ``lv.layer_sys()``, so it shows over every
77
+ app's screen; `prepare` hides it on the home screen itself.
78
+ """
79
+ launcher = self.launcher
80
+ b = lv.button(lv.layer_top())
81
+ if is_round():
82
+ # The corner is outside the circle: a round button on the diagonal.
83
+ size = lv.display_get_default().get_horizontal_resolution()
84
+ d = max(36, size // 6)
85
+ b.set_size(d, d)
86
+ b.set_style_radius(lv.RADIUS_CIRCLE, 0)
87
+ b.set_style_pad_all(0, 0)
88
+ lvicons.image(b, "home", 24).center()
89
+ b.set_pos(*round_corner(size, d))
90
+ else:
91
+ b.align(lv.ALIGN.TOP_RIGHT, -8, 8)
92
+ lv.label(b).set_text("Home")
93
+ b.add_event_cb(lambda e: launcher.request(launcher.home), lv.EVENT.CLICKED, None)
94
+ return b
95
+
96
+ def prepare(self, scope):
97
+ """Fill *scope* before the app's ``main`` runs: its ``root``, ``size``
98
+ and ``rect``. ``worker``, ``data_dir`` and ``store()`` have defaults
99
+ on every scope; a subclass may set others here."""
100
+ scope.root = self.make_root(scope)
101
+ self.measure(scope)
102
+ if self.home_button is not None:
103
+ if scope.name == self.launcher.home:
104
+ self.home_button.add_flag(lv.obj.FLAG.HIDDEN)
105
+ else:
106
+ self.home_button.remove_flag(lv.obj.FLAG.HIDDEN)
107
+
108
+ def make_root(self, scope):
109
+ """The LVGL object the app builds on: here, a screen of its own."""
110
+ return scope.screen()
111
+
112
+ def measure(self, scope):
113
+ """Set ``scope.size`` and ``scope.rect`` from ``scope.root``."""
114
+ root = scope.root
115
+ root.update_layout()
116
+ area = lv.area_t()
117
+ root.get_coords(area)
118
+ w = area.x2 - area.x1 + 1
119
+ h = area.y2 - area.y1 + 1
120
+ scope.size = (w, h)
121
+ scope.rect = (area.x1, area.y1, w, h)
appkit/shell.pyi ADDED
@@ -0,0 +1,32 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Shell: what's around an app, and what it hands each app's scope."""
5
+
6
+ from typing import Any
7
+
8
+ from . import data as data
9
+ from .launcher import Launcher
10
+ from .scope import AppScope
11
+
12
+ ROUND_MARGIN: int
13
+
14
+ def is_round() -> bool:
15
+ """Whether the default display is a round panel."""
16
+ def round_corner(size: int, d: int, margin: int = ...) -> tuple[int, int]:
17
+ """`(x, y)` of the top left of a `d`-pixel circle at the top right of a round screen `size` pixels across."""
18
+
19
+ class Shell:
20
+ """The plainest shell: apps get the whole screen, with a Home button in the corner."""
21
+
22
+ launcher: Launcher
23
+ home_button: Any
24
+ def __init__(self, launcher: Launcher, *, data_root: str | None = None) -> None: ...
25
+ def make_home_button(self) -> Any:
26
+ """The Home button, made once: an LVGL object, or None for no button."""
27
+ def prepare(self, scope: AppScope) -> None:
28
+ """Fill `scope` before the app's `main` runs: its `root`, `size` and `rect`."""
29
+ def make_root(self, scope: AppScope) -> Any:
30
+ """The LVGL object the app builds on: here, a screen of its own."""
31
+ def measure(self, scope: AppScope) -> None:
32
+ """Set `scope.size` and `scope.rect` from `scope.root`."""
appkit/worker.py ADDED
@@ -0,0 +1,409 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """One background thread for blocking calls, shared by every app.
5
+
6
+ An app hands it work through its scope and gets the answer back on the
7
+ main thread::
8
+
9
+ def main(scope):
10
+ def done(value, error):
11
+ label.set_text(str(error or value))
12
+
13
+ scope.worker.submit(lambda: fetch(url), done, key="fetch")
14
+
15
+ ``work()`` runs on the worker thread. ``done(value, error)`` runs later on
16
+ the main thread, at a safe point, with what ``work()`` returned or the
17
+ exception it raised. A second job with the same *key* replaces one still
18
+ waiting, so a burst of volume taps sends one request.
19
+
20
+ The thread outlives the apps: starting one per app would leak its stack,
21
+ which on a board is scarce internal RAM. When an app closes, what it queued
22
+ and hasn't started is dropped, and a job of its that finishes afterwards is
23
+ not delivered.
24
+
25
+ A job that uses something the app would otherwise close at once, such as an
26
+ mDNS server, passes ``release=``. ``release()`` runs once for that job: on
27
+ the thread after ``work()`` returns, even if the app has closed meanwhile,
28
+ or at once if the job is dropped before it starts. So the thing is never
29
+ torn down under a call that is still using it, and close doesn't wait for
30
+ the call.
31
+
32
+ Where there are no threads (the browser, CircuitPython on a board,
33
+ MicroPython's Windows port) a `TimerWorker` runs each job on a timer
34
+ instead, one per tick, so the screen still gets a turn between jobs.
35
+ """
36
+
37
+ import sys
38
+
39
+ import multimer
40
+
41
+ #: The worker thread's stack on a board, in bytes. A TLS handshake needs
42
+ #: about 20 KB; 12 KB overflowed.
43
+ STACK = 24 * 1024
44
+
45
+
46
+ def _gone(owner):
47
+ """True once *owner* (an app's scope) has closed or is closing."""
48
+ return bool(getattr(owner, "closed", False) or getattr(owner, "_closing", False))
49
+
50
+
51
+ def _report(exc):
52
+ print("appkit.worker: a done() failed: %r" % (exc,))
53
+ pe = getattr(sys, "print_exception", None)
54
+ if pe is not None:
55
+ pe(exc)
56
+
57
+
58
+ def _call_done(done, owner, value, error):
59
+ if _gone(owner):
60
+ return
61
+ try:
62
+ done(value, error)
63
+ except Exception as exc:
64
+ _report(exc)
65
+
66
+
67
+ def _call_release(release):
68
+ try:
69
+ release()
70
+ except Exception as exc:
71
+ print("appkit.worker: a release() failed: %r" % (exc,))
72
+
73
+
74
+ def _release_all(releases):
75
+ for release in releases:
76
+ _call_release(release)
77
+
78
+
79
+ def _check(work, done, release):
80
+ if not callable(work):
81
+ raise ValueError("work must be callable")
82
+ if done is not None and not callable(done):
83
+ raise ValueError("done must be callable")
84
+ if release is not None and not callable(release):
85
+ raise ValueError("release must be callable")
86
+
87
+
88
+ class _Lock:
89
+ """The job list's lock, which a callback can't wait on for ever.
90
+
91
+ A scheduled callback (a timer, a job's ``done()``) can run between two
92
+ bytecodes of a ``submit()`` on the same thread, with this lock held. If
93
+ it submits a job too, a plain lock would have it wait for its own thread.
94
+ Here it asks `mine` first, and hands a change to `later`, which makes it
95
+ once the outer call has let go.
96
+ """
97
+
98
+ def __init__(self):
99
+ import _thread
100
+
101
+ self._lock = _thread.allocate_lock()
102
+ self._owner = None
103
+ self._later = []
104
+
105
+ def mine(self):
106
+ """True when this thread holds the lock: the caller is a callback inside it."""
107
+ return self._owner is not None and self._owner == _ident()
108
+
109
+ def later(self, fn, *args):
110
+ """Call ``fn(*args)`` when the lock is let go."""
111
+ self._later.append((fn, args))
112
+
113
+ def __enter__(self):
114
+ self._lock.acquire()
115
+ self._owner = _ident()
116
+ return self
117
+
118
+ def __exit__(self, *exc):
119
+ self._owner = None
120
+ self._lock.release()
121
+ later = self._later
122
+ while later:
123
+ try:
124
+ fn, args = later.pop(0)
125
+ except IndexError: # another thread made the call
126
+ break
127
+ fn(*args)
128
+ return False
129
+
130
+
131
+ class _Base:
132
+ def __init__(self):
133
+ self._jobs = [] # [key, work, done, owner, release]
134
+ #: True while a job is running, whichever app's it is.
135
+ self.busy = False
136
+ self._key = None # the running job's key
137
+ #: Jobs run, and jobs whose work() raised.
138
+ self.ran = 0
139
+ self.errors = 0
140
+
141
+ def _queue(self, work, done, key, owner, release=None):
142
+ """Queue a job; returns the releases of any waiting jobs it replaced."""
143
+ _check(work, done, release)
144
+ dropped = []
145
+ if key is not None:
146
+ kept = []
147
+ for j in self._jobs:
148
+ if j[0] == key and j[3] is owner:
149
+ if j[4] is not None:
150
+ dropped.append(j[4])
151
+ else:
152
+ kept.append(j)
153
+ self._jobs = kept
154
+ self._jobs.append([key, work, done, owner, release])
155
+ return dropped
156
+
157
+ def _dropped(self, owner):
158
+ """Remove *owner*'s waiting jobs; returns their releases."""
159
+ dropped = [j[4] for j in self._jobs if j[3] is owner and j[4] is not None]
160
+ self._jobs = [j for j in self._jobs if j[3] is not owner]
161
+ return dropped
162
+
163
+ def _run(self, job):
164
+ key, work, done, owner, release = job
165
+ self._key = key
166
+ self.busy = True
167
+ value = error = None
168
+ try:
169
+ value = work()
170
+ except Exception as exc:
171
+ error = exc
172
+ self.errors += 1
173
+ self.busy = False
174
+ self._key = None
175
+ self.ran += 1
176
+ if release is not None:
177
+ _call_release(release)
178
+ return done, owner, value, error
179
+
180
+ def queued(self, owner=None):
181
+ """How many jobs are waiting; only *owner*'s when given."""
182
+ return len([j for j in self._jobs if owner is None or j[3] is owner])
183
+
184
+
185
+ class Worker(_Base):
186
+ """One background thread that runs jobs in the order they were submitted."""
187
+
188
+ def __init__(self, stack=None):
189
+ import _thread
190
+
191
+ _Base.__init__(self)
192
+ self._lock = _Lock()
193
+ self._thread = None # the thread's identity, once it is running
194
+ self._wake = _thread.allocate_lock()
195
+ self._wake.acquire()
196
+ if stack is None and _on_board():
197
+ stack = STACK
198
+ if stack:
199
+ try:
200
+ _thread.stack_size(stack)
201
+ except Exception:
202
+ pass
203
+ try:
204
+ _thread.start_new_thread(self._loop, ())
205
+ finally:
206
+ if stack:
207
+ try:
208
+ _thread.stack_size(0)
209
+ except Exception:
210
+ pass
211
+
212
+ def submit(self, work, done=None, key=None, owner=None, release=None):
213
+ """Run ``work()`` on the thread, then ``done(value, error)`` on the main thread."""
214
+ lock = self._lock
215
+ if lock.mine():
216
+ # A callback inside this thread's own submit() or cancel().
217
+ _check(work, done, release)
218
+ lock.later(self.submit, work, done, key, owner, release)
219
+ return
220
+ with lock:
221
+ dropped = self._queue(work, done, key, owner, release)
222
+ _release_all(dropped)
223
+ if self._wake.locked():
224
+ try:
225
+ self._wake.release()
226
+ except RuntimeError:
227
+ pass
228
+
229
+ def pending(self, key, owner=None):
230
+ """True while a job with *key* is waiting or running."""
231
+ if self._key is not None and self._key == key:
232
+ return True
233
+ lock = self._lock
234
+ if lock.mine():
235
+ # A callback inside this thread's own call: the list as it stands.
236
+ return any(j[0] == key and j[3] is owner for j in self._jobs)
237
+ with lock:
238
+ return any(j[0] == key and j[3] is owner for j in self._jobs)
239
+
240
+ def cancel(self, owner):
241
+ """Drop everything *owner* queued that hasn't started."""
242
+ lock = self._lock
243
+ if lock.mine():
244
+ lock.later(self.cancel, owner)
245
+ return
246
+ with lock:
247
+ dropped = self._dropped(owner)
248
+ _release_all(dropped)
249
+
250
+ def _loop(self):
251
+ self._thread = _ident()
252
+ while True:
253
+ job = None
254
+ with self._lock:
255
+ if self._jobs:
256
+ job = self._jobs.pop(0)
257
+ if job is None:
258
+ self._wake.acquire()
259
+ continue
260
+ done, owner, value, error = self._run(job)
261
+ job = None
262
+ if done is not None and not _gone(owner):
263
+ _deliver(done, owner, value, error, self._thread)
264
+ done = owner = value = error = None
265
+
266
+
267
+ def _ident():
268
+ import _thread
269
+
270
+ return _thread.get_ident()
271
+
272
+
273
+ def _deliver(done, owner, value, error, worker=None):
274
+ """Schedule ``done(value, error)`` for the main thread; *worker* is the worker thread's identity."""
275
+
276
+ def run(_):
277
+ if worker is not None and _ident() == worker:
278
+ # Where threads share one interpreter lock (an ESP32), a scheduled
279
+ # call runs on whichever thread looks for one next, and that can be
280
+ # the worker itself, in the middle of taking its next job with its
281
+ # lock held: a done() that submits a job then waits for that lock
282
+ # for ever, and nothing scheduled runs again. So from here the call
283
+ # is handed on, until the main thread is the one that finds it.
284
+ try:
285
+ multimer.schedule(run, None)
286
+ except RuntimeError:
287
+ print("appkit.worker: dropped a done(): the schedule queue stayed full")
288
+ return
289
+ _call_done(done, owner, value, error)
290
+
291
+ for _ in range(50):
292
+ try:
293
+ multimer.schedule(run, None)
294
+ return
295
+ except RuntimeError:
296
+ # The schedule queue is full; it drains fast.
297
+ import time
298
+
299
+ sleep_ms = getattr(time, "sleep_ms", None)
300
+ if sleep_ms is not None:
301
+ sleep_ms(10)
302
+ else:
303
+ time.sleep(0.01)
304
+ print("appkit.worker: dropped a done(): the schedule queue stayed full")
305
+
306
+
307
+ class TimerWorker(_Base):
308
+ """The worker where there are no threads: each job runs on a timer, on
309
+ the main thread, one per tick."""
310
+
311
+ def __init__(self):
312
+ _Base.__init__(self)
313
+ self._timer = None
314
+
315
+ def submit(self, work, done=None, key=None, owner=None, release=None):
316
+ """Run ``work()`` soon on a timer, then ``done(value, error)``."""
317
+ _release_all(self._queue(work, done, key, owner, release))
318
+ self._kick()
319
+
320
+ def pending(self, key, owner=None):
321
+ if self._key is not None and self._key == key:
322
+ return True
323
+ return any(j[0] == key and j[3] is owner for j in self._jobs)
324
+
325
+ def cancel(self, owner):
326
+ _release_all(self._dropped(owner))
327
+
328
+ def _kick(self):
329
+ t = self._timer
330
+ if t is None or not t.running:
331
+ self._timer = multimer.after(1, self._step, name="appkit.worker")
332
+
333
+ def _step(self, timer):
334
+ self._timer = None
335
+ if not self._jobs:
336
+ return
337
+ job = self._jobs.pop(0)
338
+ done, owner, value, error = self._run(job)
339
+ job = None
340
+ if done is not None:
341
+ _call_done(done, owner, value, error)
342
+ done = owner = value = error = None
343
+ if self._jobs:
344
+ self._kick()
345
+
346
+
347
+ class ScopedWorker:
348
+ """The shared worker as one app sees it: its jobs are its scope's, and
349
+ are dropped when the scope closes. This is ``scope.worker``."""
350
+
351
+ def __init__(self, worker, owner):
352
+ self.worker = worker
353
+ self.owner = owner
354
+
355
+ @property
356
+ def busy(self):
357
+ """True while the shared thread is running a job, this app's or
358
+ another's: say, before closing a connection a job may be using."""
359
+ return self.worker.busy
360
+
361
+ def submit(self, work, done=None, key=None, release=None):
362
+ """Run ``work()`` in the background, then ``done(value, error)`` on the main thread.
363
+
364
+ ``release()``, if given, runs once for this job after ``work()`` returns,
365
+ even if the app has closed by then, and at once if the job is dropped
366
+ before it starts. Use it to let go of what ``work()`` uses.
367
+ """
368
+ if _gone(self.owner):
369
+ raise RuntimeError("scope %r is closed" % (getattr(self.owner, "name", None),))
370
+ self.worker.submit(work, done, key=key, owner=self.owner, release=release)
371
+
372
+ def pending(self, key):
373
+ """True while this app's job with *key* is waiting or running."""
374
+ return self.worker.pending(key, self.owner)
375
+
376
+ def queued(self):
377
+ """How many of this app's jobs are waiting."""
378
+ return self.worker.queued(self.owner)
379
+
380
+ def cancel(self):
381
+ """Drop every job this app queued that hasn't started."""
382
+ self.worker.cancel(self.owner)
383
+
384
+
385
+ def _on_board():
386
+ from .data import desktop
387
+
388
+ return not desktop()
389
+
390
+
391
+ def threads():
392
+ """True where this interpreter can start a thread."""
393
+ try:
394
+ import _thread # noqa: F401
395
+ except ImportError:
396
+ return False
397
+ return True
398
+
399
+
400
+ _shared = None
401
+
402
+
403
+ def shared():
404
+ """The program's one worker, started on first use: a `Worker`
405
+ where there are threads, a `TimerWorker` where there aren't."""
406
+ global _shared
407
+ if _shared is None:
408
+ _shared = Worker() if threads() else TimerWorker()
409
+ return _shared