Holding Esc on the Cardputer shows the quit coming, and MeshTerm leaves in time

The Cardputer Zero's launcher ends any app whose Esc is held: SIGTERM to
its process group at three seconds, SIGKILL three seconds after that
(cp0_esc_exit_policy.hpp in CardputerZero/launcher; M5's packaging guide
still describes an older Home-for-five-seconds rule). Its own hint never
reaches the panel while an app owns it, and MeshTerm took 3.4 s to exit,
so a held Esc ended in SIGKILL.

Now a tap of Esc is typed on its release, and a hold of one second
floats a "Hold Esc to quit" box whose bar fills over the two seconds
left. While it is up the app holds the device's transmit lock: nothing
new goes on the air, and a scoped channel send under way closes its
window first. Letting go gives the lock back and types nothing. Held to
the end, MeshTerm leaves the way Quit does, and the launcher's SIGTERM
joins that exit instead of interrupting it wherever the main thread
happened to be.

The exit itself fits: openhop-core's cleanup joined the radio's IRQ
thread, parked in an uninterruptible 30 s poll, for its full 2 s
timeout. The node drops that daemon thread from the books first. On the
device, under the real launcher, the process group now drains 1.3 s
after the SIGTERM, with no SIGKILL.

The emulator's window does the same on a held Esc, debounced for an X
server's release-press repeats.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-10-06 00:59:38 -04:00
1 parent 5d2c1908e8
commit 9d16e0722a
12 files changed
+1202 -21

No files matched your search

+10
View File
@@ -755,6 +755,16 @@ branch on the platform per frame, and never `from meshterm.platforms import PLAT
`fontset.CARDPUTER_ZERO_CODEPOINTS`, named by `Platform.font` as the PicoCalc's is; the fold
derives everything from the platform's font (accents, emoji, the `?` net) and quantizes
colour only where `truecolor` is off.
- **A held Esc is the Cardputer's way out** (`services/hold_to_quit.py`, from the
launcher's own source): Esc down 3 s and the launcher SIGTERMs the app's process group,
SIGKILL 3 s later, letting go or not. So on that device (`EmulatedDevice.hold_to_quit`,
the window included) Esc is typed on its *release*; a 1 s hold floats
`holdquit.HoldQuitDialog`, whose bar runs out at 3 s, and engages the app's quiesce
(`TuiSession.set_quiesce`: the menu holds the transmit lock), given back if the reader
lets go. `TuiSession.leave` is the one exit that asks nothing — the hold running out and
the SIGTERM both take it, and a second one joins it. The whole exit must fit the
launcher's 3 s grace: 1.3 s measured with the Cap (2026-10-06), so don't add a slow step
to teardown.
- `meshterm specimen` prints the whole visual language through the real funnels — the
acceptance card on-device, a preview under `--platform picocalc-lyra` on the desktop.
- Dev loop: `meshterm --mock --platform picocalc-lyra` in a 53×40 window, or
+8 -3
View File
@@ -51,8 +51,12 @@ character on the screen itself and reads the keys directly.
- The row of function-key labels along the bottom of the screen, driven by **Fn+4** to
**Fn+8**, the keys that sit right under the display. **Shift** with them is a second set.
- M5Stack's Cap LoRa-1262 radio add-on (see [Radios](#radios)).
- Holding **Esc** for three seconds, which is how the launcher closes any app, closes
MeshTerm properly.
- Holding **Esc** to quit, which is how the launcher closes any app. After a second,
MeshTerm shows a box saying so, with a bar that fills over the next two seconds, and it
stops sending anything new over the radio while the box is up. Let go before the bar
fills and you're back where you were. Hold on, and MeshTerm saves everything and closes
in good time, before the launcher would force it. A quick press of **Esc** still goes
back a screen, as it does everywhere else.
**Not done:**
@@ -136,7 +140,8 @@ In the window, your keyboard's **F4** to **F8** stand in for **Fn+4** to **Fn+8*
holding **Shift** shows the second set. You can click the keys instead, either the ones
drawn under the screen or the coloured keys along its bottom row; hold **Shift** while you
click for the second set. **Ctrl+Shift+S** saves a screenshot at the screen's
real size. Closing the window quits MeshTerm.
real size. Closing the window quits MeshTerm, and so does holding **Esc** for three
seconds, as it does on the device.
## Radios
+24
View File
@@ -823,10 +823,34 @@ async def _serve( # noqa: PLR0913 - the library modules run_node imported, hand
except Exception as exc: # noqa: BLE001 - keep going: the radio still needs freeing
log.warning("shutdown step failed: %s", exc)
node.contacts.save_snapshot()
_forget_edge_threads(radio)
radio.cleanup()
return 0
def _forget_edge_threads(radio: Any) -> None:
"""Spare the radio's cleanup two seconds spent waiting on a thread that can't hear it.
The library watches the IRQ pin from a daemon thread parked in a 30-second ``poll``,
which its stop event cannot cut short, and ``cleanup()`` joins that thread for up to
two seconds before it closes the pins — so every shutdown waited the full two seconds
for nothing. On the Cardputer Zero that was 2.2 s of a 3.4 s exit, against the three
seconds the launcher allows between its SIGTERM and its SIGKILL (measured 2026-10-06).
The thread is a daemon and its line is the kernel's to release when the process ends,
so it is told to stop and then dropped from the manager's books, and cleanup closes the
pins without waiting on it. A library that keeps its threads somewhere else is left
alone: the cleanup is slower, not wrong.
"""
manager = getattr(radio, "_gpio_manager", None)
stops = getattr(manager, "_edge_stop_events", None)
threads = getattr(manager, "_edge_threads", None)
if not isinstance(stops, dict) or not isinstance(threads, dict):
return
for stop in stops.values():
stop.set()
threads.clear()
def apply_preamble(radio: Any, symbols: int) -> None:
"""Give a running radio a new preamble length, for both what it sends and what it hears.
+8 -1
View File
@@ -41,6 +41,10 @@ class EmulatedDevice:
shifted: The desktop's Shift+F-key as the key the device's keyboard sends instead.
The PicoCalc's keyboard sends F6–F10 for Shift+F1–F5; the Cardputer Zero's sends
a shifted F4–F8, which needs no translating.
hold_to_quit: Whether holding Esc quits, as the Cardputer Zero's launcher has it
(:mod:`~meshterm.services.hold_to_quit`): a tap is Esc on its release, a hold
raises the quit box. The PicoCalc's console has no such rule, and its Esc is
typed the moment it goes down.
"""
platform: Platform
@@ -49,6 +53,7 @@ class EmulatedDevice:
console: bool = False
lane_keys: tuple[tuple[str, int], ...] = ()
shifted: dict[str, str] = field(default_factory=dict)
hold_to_quit: bool = False
@property
def id(self) -> str:
@@ -75,12 +80,14 @@ class EmulatedDevice:
#: M5Stack's Cardputer Zero: a 320×170 panel MeshTerm draws itself, its lane on Fn+4…8 —
#: the five keys right under the panel, at the positions M5's drawing gives them.
#: the five keys right under the panel, at the positions M5's drawing gives them — and
#: Esc held for three seconds its launcher's way out of any app.
CARDPUTER_ZERO_DEVICE = EmulatedDevice(
platform=CARDPUTER_ZERO,
name="Cardputer Zero",
panel=(320, 170),
lane_keys=(("4", 48), ("5", 104), ("6", 160), ("7", 216), ("8", 272)),
hold_to_quit=True,
)
#: ClockworkPi's PicoCalc with a Luckfox Lyra core: a 320×320 panel the Linux console draws
+32 -4
View File
@@ -5,7 +5,10 @@ The launcher starts an app with the screen to itself and tells it where things a
``APPLAUNCH_LINUX_FBDEV_DEVICE`` names the panel's framebuffer and
``APPLAUNCH_LINUX_KEYBOARD_DEVICE`` its keyboard, which it shares rather than grabs — so the
app reads key events itself, while the launcher watches the same stream for a held Esc
(3 s, then SIGTERM to the app's process group). This front end follows that contract.
(3 s, then SIGTERM to the app's process group, and SIGKILL 3 s after that). This front end
follows that contract: Esc goes through :mod:`~meshterm.services.hold_to_quit`, which shows
the hold on the panel the launcher has stopped drawing, and the SIGTERM is taken as the
quit it is (:func:`_leave_on_sigterm`).
**Written ahead of the hardware** (2026-09-30), from M5's published sources: the
framebuffer and keyboard paths and the Esc policy from the launcher, the key codes from the
@@ -32,7 +35,7 @@ import threading
from collections.abc import Callable
from pathlib import Path
from ..services import modifier_watch
from ..services import hold_to_quit, modifier_watch
from .font import Font
from .keys import Key, encode
from .raster import Raster, rgb565
@@ -48,6 +51,9 @@ DEFAULT_KEYBOARD = "/dev/input/by-path/platform-3f804000.i2c-event"
_EVENT = struct.Struct("llHHi")
_EV_KEY = 0x01
#: ``KEY_ESC``: held, the launcher's way out (see :mod:`~meshterm.services.hold_to_quit`).
_ESC = 1
# Modifier key codes (linux/input-event-codes.h).
_SHIFT = {42, 54}
_CTRL = {29, 97}
@@ -228,6 +234,7 @@ class Device:
def _read_keys(self) -> None:
state = KeyState()
esc = hold_to_quit.EscKey(self._type)
with open(self._keyboard, "rb", buffering=0) as stream:
while not self._closing:
data = stream.read(_EVENT.size)
@@ -236,6 +243,13 @@ class Device:
_, _, kind, code, value = _EVENT.unpack(data)
if kind != _EV_KEY:
continue
if code == _ESC:
# Down and its repeats are one hold; a tap is typed as it comes up.
if value:
esc.down()
else:
esc.up()
continue
was_shifted = state.shift
key = state.event(code, value)
if state.shift != was_shifted:
@@ -243,12 +257,26 @@ class Device:
if key is not None:
sequence = encode(key)
if sequence:
esc.before()
self._type(sequence)
def _leave_on_sigterm() -> None:
"""Treat the launcher's SIGTERM (a held Esc) as an interrupt, so MeshTerm cleans up."""
signal.signal(signal.SIGTERM, signal.default_int_handler)
"""Take the launcher's SIGTERM — the end of a held Esc — as a quit, not an interrupt.
With the TUI running, MeshTerm leaves the way a held Esc does when its bar runs out
(:func:`~meshterm.services.hold_to_quit.terminate`): from its own event loop, between
two keys, once nothing is mid-transmission. One that lands on an exit already under way
— the bar ran out a moment before — joins it, where an interrupt raised wherever the
main thread happened to be used to cut the teardown short. Before the TUI starts there
is nothing to put away, and it stops as an interrupt would.
"""
def on_term(signum: int, frame: object) -> None:
if not hold_to_quit.terminate():
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, on_term)
def front_end():
+44 -4
View File
@@ -18,7 +18,8 @@ Shift it saw, so the window sends the shifted key itself (:func:`lane_press`). T
keys wear the lane's own fill, and take its Shift fill while Shift is down, as the chips
above them do (:func:`lane_fills`). Closing the window leaves MeshTerm at once, as ^Q
twice would. Ctrl+Shift+S saves the panel at its true size as a PNG in the working
directory.
directory. On a device whose launcher quits an app on a held Esc (the Cardputer Zero), Esc
held in the window does the same (:mod:`~meshterm.services.hold_to_quit`).
Tk runs on a thread of its own, the TUI on the main thread; the two meet only through the
terminal's lock, a flag saying a frame is ready, and the function that types.
@@ -32,7 +33,7 @@ import time
from collections.abc import Callable
from pathlib import Path
from ..services import modifier_watch
from ..services import hold_to_quit, modifier_watch
from ..ui.theme import MESH_THEME, MESH_THEME_16
from ..ui.tui.fkeys import LaneDeck
from .devices import EmulatedDevice
@@ -64,6 +65,11 @@ _NAMED = {
_SHIFTS = ("Shift_L", "Shift_R")
#: How long a released Esc waits to be sure it was let go. An X server repeats a held key
#: as a release and a press back to back, and the press arrives within this; a desktop
#: that repeats with presses alone never sends the release until the key is up.
_REPEAT_GAP_MS = 30
#: A drawn lane key's cap, and the ink of the digit printed on it.
_KEY_BODY = "#1d2025"
_KEY_DIGIT = "#eef1f4"
@@ -184,6 +190,9 @@ class EmulatorWindow:
self._fills = lane_fills(device)
self._shifted = False
self._pressed: int | None = None
self._esc = hold_to_quit.EscKey(type_text)
self._esc_down = False
self._esc_letting_go: str | None = None
self._ready = threading.Event()
self._ready.set()
self._closing = False
@@ -229,8 +238,9 @@ class EmulatorWindow:
root.bind("<KeyPress>", self._on_press)
root.bind("<KeyRelease>", self._on_release)
# A Shift let go in another window never reaches this one; leaving it held here
# would keep the lane and the drawn keys in the Shift bank.
root.bind("<FocusOut>", lambda _: self._set_shift(False))
# would keep the lane and the drawn keys in the Shift bank — and an Esc left held
# would quit three seconds later.
root.bind("<FocusOut>", self._on_focus_out)
root.protocol("WM_DELETE_WINDOW", self._on_close)
root.focus_force()
self._started.set()
@@ -302,6 +312,7 @@ class EmulatorWindow:
def _press_lane(self, slot: int, state: int) -> None:
data = lane_press(self._device, slot, shift=bool(state & _SHIFT_BIT))
if data:
self._esc.before()
self._type(data)
def _set_shift(self, down: bool) -> None:
@@ -334,6 +345,9 @@ class EmulatorWindow:
if event.keysym in _SHIFTS:
self._set_shift(True)
return
if event.keysym == "Escape" and self._device.hold_to_quit:
self._esc_pressed()
return
if event.keysym in ("S", "s") and event.state & _CTRL_BIT and event.state & _SHIFT_BIT:
self._save()
return
@@ -341,11 +355,37 @@ class EmulatorWindow:
if key is not None:
data = encode(self._device.translate(key))
if data:
self._esc.before()
self._type(data)
def _on_release(self, event) -> None:
if event.keysym in _SHIFTS:
self._set_shift(False)
elif event.keysym == "Escape" and self._esc_down:
root = self._tk[0]
self._esc_letting_go = root.after(_REPEAT_GAP_MS, self._esc_released)
def _on_focus_out(self, _event) -> None:
self._set_shift(False)
if self._esc_down:
self._esc_released()
def _esc_pressed(self) -> None:
"""Esc went down — or, straight after its release, the X server repeated it."""
if self._esc_letting_go is not None:
self._tk[0].after_cancel(self._esc_letting_go)
self._esc_letting_go = None
return
self._esc_down = True
self._esc.down()
def _esc_released(self) -> None:
"""Esc is up, and no repeat followed: the hold is over."""
if self._esc_letting_go is not None:
self._tk[0].after_cancel(self._esc_letting_go)
self._esc_letting_go = None
self._esc_down = False
self._esc.up()
def _on_close(self) -> None:
# ^Q asks; a second ^Q while it asks leaves at once.
+253
View File
@@ -0,0 +1,253 @@
# SPDX-License-Identifier: Apache-2.0
"""Hold Esc to quit: the Cardputer Zero launcher's way out of an app, and MeshTerm's half of it.
The launcher hands an app the panel and the keyboard but goes on reading the keyboard
itself, and a held Esc is its door out of whatever is running (``cp0_esc_exit_policy.hpp``
in CardputerZero/launcher, read 2026-10-06): Esc down for **three seconds** and it sends
SIGTERM to the app's process group; **three seconds** after that, SIGKILL, whether or not
Esc is still down. Letting go after the SIGTERM changes nothing. The launcher also raises a
hint at half a second, but only as a flag: its own drawing is paused while an app owns the
panel, so the hint never reaches the glass. The app is the only one who can show what is
about to happen, and it has to be gone before the SIGKILL. (M5's packaging guide still
describes an older rule — Home held five seconds, then SIGINT — that the code no longer
follows.)
MeshTerm meets it like this:
* **A tap is Esc.** Let go within :data:`DIALOG_S` and the TUI gets the one Esc it was, on
the release. It waits for the release because a press that went back a screen and then
quit would be two things for one gesture. Another key pressed while Esc is still down
sends the Esc first, so keys keep their order.
* **Held for a second, a box says so.** ``Hold Esc to quit``, with a bar that fills over
the two seconds left until :data:`QUIT_S`, the launcher's own deadline. While it is up,
MeshTerm stops *starting* things: it takes the transmit lock, so nothing new goes on the
air and a scoped channel send already under way finishes first (see
:mod:`~meshterm.core.transmit_lock`). Nothing is torn down.
* **Let go before the bar fills** and the box goes and the lock is given back. No Esc
arrives: the reader changed their mind about leaving, not about going back.
* **Hold it to the end** and MeshTerm leaves the way Quit does. The launcher's SIGTERM
arrives at the same moment and joins that exit rather than cutting into it
(:func:`terminate`).
The emulator's front ends know the key — the device's event stream, the window's key
events, the only two places MeshTerm sees a key go *up* — and the session knows the
screens, so this module is where they meet, as :mod:`~meshterm.services.modifier_watch` is
for Shift. A front end reports Esc going down and up; the session listens while it runs
and does the rest. With nothing listening (before the TUI starts, after it ends) a front
end types Esc at once, like any other key.
"""
from __future__ import annotations
import threading
import time
from collections.abc import Callable
from typing import Protocol
#: Seconds Esc is held before the box comes up. A tap is far shorter; a second is long
#: enough that the box never flashes up under a slow press.
DIALOG_S = 1.0
#: Seconds Esc is held before MeshTerm leaves: the launcher's own ``TERMINATE_DELAY_MS``,
#: when its SIGTERM lands anyway, so the bar runs out when the launcher says it does.
QUIT_S = 3.0
#: Seconds the launcher waits after its SIGTERM before it sends SIGKILL
#: (``KILL_GRACE_MS``). MeshTerm's whole exit has to fit in it.
GRACE_S = 3.0
#: What a terminal sends for Esc.
ESC = "\x1b"
class Listener(Protocol):
"""The running session's side: told when Esc goes down and up, and when to leave.
Every method is called from a thread that is not the session's (a front end's key
thread, or the main thread inside a signal handler), so each hands its work to the
session's loop and returns at once.
"""
def held(self, since: float) -> None:
"""Esc went down at ``since`` (``time.monotonic``) and is being watched."""
def released(self) -> None:
"""Esc came up."""
def terminate(self) -> None:
"""Leave now, the way a hold that ran its course does (SIGTERM)."""
_lock = threading.Lock()
_listener: Listener | None = None
#: When the Esc being held went down, or ``None`` while it is up (or nobody watches it).
_since: float | None = None
#: Whether the held Esc is still owed to the TUI as a press, not yet typed.
_owed = False
#: Whether the box has claimed the hold, so that letting go types nothing.
_claimed = False
#: Whether the app has begun to leave, so a SIGTERM has nothing left to ask for.
_leaving = False
def listen(listener: Listener) -> None:
"""Start watching held Esc keys for ``listener`` (the session, as it starts to run)."""
global _listener, _leaving
with _lock:
_listener = listener
_leaving = False
_forget()
def unlisten(listener: Listener) -> None:
"""Stop watching for ``listener``; a hold under way is forgotten."""
global _listener
with _lock:
if _listener is listener:
_listener = None
_forget()
def leaving() -> None:
"""Note that the app has begun to leave: a SIGTERM from now on joins that exit.
Kept until the next :func:`listen`, past the session's end, since the launcher's SIGTERM
can land while the app is already tearing down, and an interrupt there would cut the
teardown short.
"""
global _leaving
with _lock:
_leaving = True
def press(now: float | None = None) -> bool:
"""Esc went down, or repeated while held. Returns whether the hold is being watched.
Args:
now: When it went down (``time.monotonic``); now if not given.
Returns:
``True`` when the session is watching, so the front end must not type the Esc —
it is owed until :func:`release` or :func:`interrupt` says to type it. ``False``
when nothing is listening: type Esc now, as any key.
"""
global _since, _owed, _claimed
with _lock:
listener = _listener
if listener is None:
return False
if _since is not None:
return True # the keyboard's repeat: one hold, however long
_since = time.monotonic() if now is None else now
_owed, _claimed = True, False
since = _since
listener.held(since)
return True
def release() -> bool:
"""Esc came up. Returns whether to type it now: a tap, not yet typed or claimed."""
with _lock:
listener = _listener
if _since is None:
return False
tap = _owed and not _claimed
_forget()
if listener is not None:
listener.released()
return tap
def interrupt() -> bool:
"""Another key went down. Returns whether to type the held Esc ahead of it."""
global _owed
with _lock:
if _since is None or not _owed or _claimed:
return False
_owed = False
return True
def claim(since: float) -> bool:
"""The box asks for the hold that began at ``since``. ``True`` if it is still held.
Claimed, the hold is no longer a press: letting go types nothing. The session asks
:data:`DIALOG_S` after the press, and the answer settles a release arriving at the same
instant — exactly one of the two wins.
"""
global _claimed
with _lock:
if _since != since:
return False
_claimed = True
return True
def terminate() -> bool:
"""Ask the app to leave, as the launcher's SIGTERM does. ``False`` when nothing can.
Returns:
``True`` when a listening session was asked to leave, or the app is leaving already
(a second SIGTERM, or one landing on a quit under way); ``False`` when there is no
session to ask, and the caller should stop the process its own way.
"""
with _lock:
listener, already = _listener, _leaving
if already:
return True
if listener is None:
return False
listener.terminate()
return True
def _forget() -> None:
"""Drop the hold under way (call with the lock held)."""
global _since, _owed, _claimed
_since, _owed, _claimed = None, False, False
class EscKey:
"""A front end's Esc key, typed by the rules above.
The front end calls :meth:`down` and :meth:`up` as the key goes, and :meth:`before`
ahead of typing any other key; this types the Esc whenever, and only when, it is a
press — at once where nothing is watching, on the release for a tap.
"""
def __init__(self, type_text: Callable[[str], None]) -> None:
"""Type through ``type_text``, the front end's way into the TUI."""
self._type = type_text
def down(self) -> None:
"""Esc went down (or the keyboard repeated it)."""
if not press():
self._type(ESC)
def up(self) -> None:
"""Esc came up."""
if release():
self._type(ESC)
def before(self) -> None:
"""Another key is about to be typed: send an Esc still owed ahead of it."""
if interrupt():
self._type(ESC)
__all__ = [
"DIALOG_S",
"ESC",
"GRACE_S",
"QUIT_S",
"EscKey",
"Listener",
"claim",
"interrupt",
"leaving",
"listen",
"press",
"release",
"terminate",
"unlisten",
]
+25
View File
@@ -421,6 +421,8 @@ async def run_menu(ctx: AppContext) -> None:
ctx.ui = TuiUi(session)
# The one quit confirm, asked by the menu's Quit row and by the quit chord from anywhere.
session.set_quit_confirm(lambda: _confirm_quit(ctx, session))
# What a held Esc engages while its box is up, and the app keeps on its way out.
session.set_quiesce(lambda: _off_the_air(ctx))
async def main() -> None:
try:
@@ -450,6 +452,29 @@ async def run_menu(ctx: AppContext) -> None:
ctx.console.print("[muted]bye 73![/muted]")
@asynccontextmanager
async def _off_the_air(ctx: AppContext) -> AsyncIterator[None]:
"""Hold the connected device's transmit lock: nothing new starts going on the air.
The app's quiesce (:meth:`~meshterm.ui.tui.session.TuiSession.set_quiesce`), held while
a held Esc's box is up and kept on the way out. The lock is what every transmission
takes (:mod:`~meshterm.core.transmit_lock`), so taking it waits for one under way —
a scoped channel send closes its window and puts the session scope back first — and
then holds the rest up: a courier retry, a scheduled advert. Letting go of Esc gives it
back and they go ahead. With no device connected there is nothing to hold, and it never
connects one just to hold it.
Args:
ctx: The shared application context.
"""
lock = getattr(ctx._device, "transmit_lock", None)
if lock is None:
yield
return
async with lock.held():
yield
async def _can_unpair(ctx: AppContext) -> bool:
"""Whether the quit dialog should offer to drop the current device's OS pairing.
+237
View File
@@ -0,0 +1,237 @@
# SPDX-License-Identifier: Apache-2.0
"""The session's half of hold-Esc-to-quit: the box, its bar, and what holding it engages.
:mod:`~meshterm.services.hold_to_quit` says what the gesture is and why; this is what the
session does with it. :class:`EscHoldWatch` is the session's listener: told that Esc went
down, it waits out :data:`~meshterm.services.hold_to_quit.DIALOG_S`, claims the hold, floats
a :class:`HoldQuitDialog` over whatever is up — detached, the way the quit confirm floats,
so nothing under it stops — and engages the app's :class:`Quiet`; told that Esc came up, it
takes the box down and gives the quiet back. Held to
:data:`~meshterm.services.hold_to_quit.QUIT_S`, it leaves
(:meth:`~meshterm.ui.tui.session.TuiSession.leave`).
"""
from __future__ import annotations
import asyncio
import time
from collections.abc import Callable
from contextlib import AbstractAsyncContextManager
from typing import TYPE_CHECKING, Any
from rich.console import Group
from rich.text import Text
from ...persistence.logging import get_logger
from ...services import hold_to_quit
from ..braillechart import meter
from .render import render_lines
from .screen import Screen, ScrollScreen
if TYPE_CHECKING:
from .session import TuiSession
_log = get_logger()
#: Seconds between repaints while the bar fills. The bar gains a step every few hundredths
#: of a second, but a frame costs real time on a handheld, and ten a second reads as a
#: smooth fill while leaving most of a core to whatever the app is finishing up.
BAR_TICK_S = 0.1
#: The box's width, border included: the bar is the width of the text above it.
_WIDTH = 30
class Quiet:
"""The app's quiesce (:meth:`~meshterm.ui.tui.session.TuiSession.set_quiesce`), held.
Entered in a task of its own, since what it takes — the transmit lock — may have to
wait for a transmission to finish, and the box must not wait with it. Given back
(:meth:`release`) when the reader lets go of Esc. When the app leaves it is never given
back: it goes when the event loop is shut down, after the device has been disconnected,
so nothing starts transmitting while the app tears down.
"""
def __init__(self, enter: Callable[[], AbstractAsyncContextManager[Any]] | None) -> None:
"""Start entering ``enter`` (``None``: nothing to enter, engaged at once)."""
self._engaged = asyncio.Event()
self._released = asyncio.Event()
self._task = asyncio.ensure_future(self._hold(enter))
async def _hold(self, enter: Callable[[], AbstractAsyncContextManager[Any]] | None) -> None:
try:
if enter is None:
self._engaged.set()
await self._released.wait()
return
async with enter():
self._engaged.set()
await self._released.wait()
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 - a failed quiesce must not stop a quit
_log.warning("could not quiet the app before leaving: %s", exc)
finally:
# Never keep a leave waiting on a quiesce that failed or was cancelled.
self._engaged.set()
async def engaged(self, timeout: float) -> bool:
"""Wait up to ``timeout`` seconds for the quiesce to take hold; whether it did."""
try:
await asyncio.wait_for(self._engaged.wait(), timeout)
except asyncio.TimeoutError:
return False
return True
def release(self) -> None:
"""Give the quiesce back: what it held up goes ahead."""
self._released.set()
class HoldQuitDialog(Screen):
"""The box a held Esc raises: that MeshTerm is about to quit, and how soon.
The bar is the time left: it starts filling the moment the box appears and is full at
:data:`~meshterm.services.hold_to_quit.QUIT_S` from the press, when the app leaves —
and when, on the Cardputer Zero, the launcher sends its SIGTERM. No buttons, since the
only answer is in the reader's hand: keep holding, or let go. Modal, so no key reaches
the screen beneath while it is up.
"""
title = "Quit MeshTerm"
floating = True
modal = True
border_style = "warn"
footer_hint = "let go of Esc to stay"
def __init__(self, since: float, *, clock: Callable[[], float] = time.monotonic) -> None:
"""A box for the hold that began at ``since`` (``clock``'s time, ``time.monotonic``)."""
super().__init__()
self._starts = since + hold_to_quit.DIALOG_S
self._span = hold_to_quit.QUIT_S - hold_to_quit.DIALOG_S
self._clock = clock
@property
def picocalc_lyra_lane(self):
"""No lane: nothing on the keyboard but the Esc in the reader's hand does anything."""
from .fkeys import EMPTY_LANE
return EMPTY_LANE
@property
def dialog_width(self) -> int:
"""A small box: one line and a bar."""
return _WIDTH
@property
def fraction(self) -> float:
"""How full the bar is, ``0`` when the box appears to ``1`` when the app leaves."""
return min(1.0, max(0.0, (self._clock() - self._starts) / self._span))
def render_body(self, width: int) -> list[str]:
"""``Hold Esc to quit`` over the bar, which fills the line's width."""
bar = meter(self.fraction, width, style="warn", slim=True, track="track")
return render_lines(Group(Text("Hold Esc to quit", style="warn"), Text(""), bar), width)
def handle(self, action: str, data: str = "") -> None:
"""Swallow every key: the box answers to Esc being held or let go, and nothing else."""
return
class EscHoldWatch:
"""The session's :class:`~meshterm.services.hold_to_quit.Listener`.
Its three listener methods are called from other threads and only hand their work to
the session's loop; everything else here runs on the loop.
"""
def __init__(self, session: TuiSession, loop: asyncio.AbstractEventLoop) -> None:
"""Watch held Esc keys for ``session``, whose loop is ``loop``."""
self._session = session
self._loop = loop
self._raise: asyncio.TimerHandle | None = None
self._quit: asyncio.TimerHandle | None = None
self._ticker: asyncio.Future | None = None
#: The box while it is up, and the backdrop pushed under it when nothing was.
self._dialog: HoldQuitDialog | None = None
self._backdrop: Screen | None = None
# --- the listener (other threads) ------------------------------------------------
def held(self, since: float) -> None:
"""Esc went down at ``since``."""
self._call(self._on_held, since)
def released(self) -> None:
"""Esc came up."""
self._call(self._on_released)
def terminate(self) -> None:
"""Leave now (the launcher's SIGTERM)."""
self._call(self._session.leave)
def _call(self, work: Callable[..., None], *args: Any) -> None:
try:
self._loop.call_soon_threadsafe(work, *args)
except RuntimeError: # the loop has closed: the app is gone already
pass
# --- on the loop --------------------------------------------------------------------
def _on_held(self, since: float) -> None:
self._stand_down()
delay = since + hold_to_quit.DIALOG_S - time.monotonic()
self._raise = self._loop.call_later(max(0.0, delay), self._show, since)
def _show(self, since: float) -> None:
"""Raise the box, if the hold that asked for it is still held."""
self._raise = None
if self._session.leaving or not hold_to_quit.claim(since):
return
self._session.quiet()
dialog = self._dialog = HoldQuitDialog(since)
left = since + hold_to_quit.QUIT_S - time.monotonic()
self._quit = self._loop.call_later(max(0.0, left), self._session.leave)
# Pushed here and popped by :meth:`_stand_down`, the way the busy card is: the box
# answers to the key, not to a future, and a release landing in the same breath
# has nothing half-made to miss. On an empty stack (a tool between two screens) it
# gets a blank backdrop of its own, as the busy card does, never the menu: the menu
# may be pushed again under it by then, and popping it would take the menu away.
if self._session.top is None:
self._backdrop = ScrollScreen("", floating=False, footer_hint="")
self._session.push(self._backdrop)
self._session.push(dialog)
self._ticker = asyncio.ensure_future(self._fill(dialog))
async def _fill(self, dialog: HoldQuitDialog) -> None:
"""Repaint while the bar fills; the last repaint shows it full."""
while True:
await asyncio.sleep(BAR_TICK_S)
self._session.invalidate()
if dialog.fraction >= 1.0:
return
def _on_released(self) -> None:
if self._session.leaving:
return # the bar ran out: the app is on its way, and the launcher's SIGTERM too
self._stand_down()
self._session.unquiet()
def _stand_down(self) -> None:
"""Cancel the hold under way: its timers, its repaints, and its box."""
for timer in (self._raise, self._quit):
if timer is not None:
timer.cancel()
self._raise = self._quit = None
if self._ticker is not None:
self._ticker.cancel()
self._ticker = None
if self._dialog is not None:
self._session.pop(self._dialog)
self._dialog = None
if self._backdrop is not None:
self._session.pop(self._backdrop)
self._backdrop = None
__all__ = ["BAR_TICK_S", "EscHoldWatch", "HoldQuitDialog", "Quiet"]
+98 -9
View File
@@ -16,7 +16,7 @@ import asyncio
import os
import sys
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
from contextlib import asynccontextmanager, nullcontext, suppress
from contextlib import AbstractAsyncContextManager, asynccontextmanager, nullcontext, suppress
from typing import Any
from prompt_toolkit.application import Application
@@ -32,10 +32,12 @@ from rich.console import RenderableType
from rich.text import Text
from ...core import win32dll
from ...persistence.logging import get_logger
from ...platforms import get_platform
from ...services import modifier_watch
from ...services import hold_to_quit, modifier_watch
from . import colsnap, fastrender, fkeys, frame
from .emoji_width import ClusterTextControl
from .holdquit import EscHoldWatch, Quiet
from .overlay import BusyOverlay
from .progress import TuiProgress
from .prompt import (
@@ -354,6 +356,15 @@ def _color_depth() -> ColorDepth | None:
#: real nesting — a tool's list, an item's detail popup, and a confirm over that is only three.
_MAX_DIALOG_LAYERS = 8
#: How long :meth:`TuiSession.leave` waits for the app's quiesce to take hold — for a
#: transmission under way to finish — before it leaves anyway. On the Cardputer Zero the
#: whole exit has to fit the launcher's three seconds between SIGTERM and SIGKILL
#: (:data:`~meshterm.services.hold_to_quit.GRACE_S`), and the rest of it was measured at
#: about one second there (2026-10-06).
QUIESCE_WAIT_S = 1.0
_log = get_logger()
def _changed_rows(before: str, after: str) -> list[int] | None:
"""Which lines of a full-screen frame differ, or ``None`` when they can't be compared.
@@ -551,6 +562,12 @@ class TuiSession:
# what turns the next ^Q into the leaving itself.
self._quit_confirm: Callable[[], Awaitable[bool]] | None = None
self._quit_asking = False
# What the app does to stop starting things before it may have to leave (see
# :meth:`set_quiesce`), the quiesce while it is held, and whether the app is on its
# way out — the one-way flag :meth:`leave` raises.
self._quiesce: Callable[[], AbstractAsyncContextManager[Any]] | None = None
self._quiet: Quiet | None = None
self._leaving = False
# --- stack ---------------------------------------------------------------
@@ -700,6 +717,65 @@ class TuiSession:
if self._app is not None and self._app.is_running:
self._app.exit()
def set_quiesce(self, enter: Callable[[], AbstractAsyncContextManager[Any]] | None) -> None:
"""Declare how the app stops *starting* things, for when it may be about to leave.
Entered when a held Esc raises its box and left again if the reader lets go (see
:mod:`~meshterm.services.hold_to_quit`); entered on the way out by :meth:`leave`,
and then kept until the process ends. It must take nothing apart, since letting go
has to undo it: the app's own is to hold the device's transmit lock, so nothing new
goes on the air and a scoped channel send in flight closes its window first. The
app declares it, as it declares the quit confirm, because only the app has a
device.
Args:
enter: Makes the async context manager to hold, or ``None`` for nothing.
"""
self._quiesce = enter
@property
def leaving(self) -> bool:
"""Whether the app is on its way out (:meth:`leave`), which nothing calls back."""
return self._leaving
def quiet(self) -> Quiet:
"""Engage the app's quiesce (:meth:`set_quiesce`), or return the one already held."""
if self._quiet is None:
self._quiet = Quiet(self._quiesce)
return self._quiet
def unquiet(self) -> None:
"""Give the quiesce back — never once the app is leaving, which keeps it to the end."""
if self._quiet is not None and not self._leaving:
self._quiet.release()
self._quiet = None
def leave(self) -> None:
"""Leave the app now, without asking — once nothing is mid-transmission.
The end of a held Esc, and the launcher's SIGTERM: a decision already made, so
there is no confirm. It is the same exit as Quit (:meth:`run` unwinds the flow and
the app tears down) with one step first: the app's quiesce is engaged, so a scoped
channel send under way closes its window before the device goes. That wait is
bounded by :data:`QUIESCE_WAIT_S`, because on the Cardputer Zero the launcher's
SIGKILL follows its SIGTERM by three seconds whatever the app is doing.
Idempotent and one-way: a SIGTERM landing on a hold that just ran out is the same
exit, not a second one.
"""
if self._leaving:
return
self._leaving = True
hold_to_quit.leaving()
quiet = self.quiet()
async def go() -> None:
if not await quiet.engaged(QUIESCE_WAIT_S):
_log.warning("leaving with a transmission still under way")
self._exit_app()
self.run_detached(go())
def request_pop_all(self) -> bool:
"""Arm the unwind to the navigation root (the ^W key). Returns whether it fired.
@@ -1702,13 +1778,26 @@ class TuiSession:
def pre_run() -> None:
task["driver"] = asyncio.ensure_future(driver())
# Don't let prompt_toolkit install its own loop exception handler: on any stray
# background-task error it prints a traceback and a "Press ENTER to continue..."
# prompt straight over the full-screen UI. With it disabled, asyncio's default
# handler logs such errors to the ``asyncio`` logger instead, which is routed to the
# file log (see :func:`meshterm.persistence.logging.configure_logging`) and never
# touches the screen. Errors from ``main`` still propagate via ``driver``/``box``.
await self._app.run_async(pre_run=pre_run, set_exception_handler=False)
# A held Esc, where a front end can tell one (the emulator's), raises the quit box,
# and the launcher's SIGTERM leaves through here too: see services.hold_to_quit.
# Listening costs nothing where nobody reports a key going down.
watch = EscHoldWatch(self, asyncio.get_running_loop())
hold_to_quit.listen(watch)
try:
# Don't let prompt_toolkit install its own loop exception handler: on any stray
# background-task error it prints a traceback and a "Press ENTER to continue..."
# prompt straight over the full-screen UI. With it disabled, asyncio's default
# handler logs such errors to the ``asyncio`` logger instead, which is routed to
# the file log (see :func:`meshterm.persistence.logging.configure_logging`) and
# never touches the screen. Errors from ``main`` still propagate via
# ``driver``/``box``.
await self._app.run_async(pre_run=pre_run, set_exception_handler=False)
finally:
# Whichever door it left by, the app is tearing down from here on, and a
# SIGTERM arriving now must join that rather than interrupt it.
self._leaving = True
hold_to_quit.leaving()
hold_to_quit.unlisten(watch)
# The app can also exit from *under* the driver: the quit chords (^Q/^C) call
# ``Application.exit`` from their detached confirm, or straight from the key handler
# on the second press (see request_quit), so ``run_async`` returns while
+9
View File
@@ -1614,6 +1614,14 @@ def _diagnostics_source() -> str:
return markdown_source(report, when=datetime(2026, 9, 19, 17, 0))
def _quit_hold(cols: int, rows: int) -> Screen:
"""The box a held Esc raises, its bar half full: a second from the quit."""
from meshterm.services.hold_to_quit import DIALOG_S, QUIT_S
from meshterm.ui.tui.holdquit import HoldQuitDialog
return HoldQuitDialog(0.0, clock=lambda: (DIALOG_S + QUIT_S) / 2)
def _share_qr(cols: int, rows: int) -> Screen:
"""The share screen: a contact card's code and link on a bare frame (the widest QR)."""
from meshterm.ui.qr import QrScreen
@@ -1689,6 +1697,7 @@ _ENTRIES: list[_Entry] = [
_Entry("preferences-weekly-advert", _preferences_weekly_advert),
_Entry("cooldown_countdown", _cooldown_countdown),
_Entry("reconnect_reason", _reconnect_reason),
_Entry("quit_hold", _quit_hold),
_Entry("about_meshterm", _about_meshterm),
_Entry("about_author", _about_author),
_Entry("join_discord", _join_discord),
+454
View File
@@ -0,0 +1,454 @@
# SPDX-License-Identifier: Apache-2.0
"""Hold Esc to quit: the Cardputer Zero launcher's way out, and MeshTerm's half of it.
The gesture's rules (:mod:`meshterm.services.hold_to_quit`), the session's box and its
quiesce (:mod:`meshterm.ui.tui.holdquit`), the two front ends that see a key go up, the
launcher's SIGTERM, and the radio node's exit fitting inside the launcher's grace.
"""
from __future__ import annotations
import asyncio
import signal
import struct
import threading
import time
from contextlib import asynccontextmanager
import pytest
from prompt_toolkit.input.defaults import create_pipe_input
from prompt_toolkit.output import DummyOutput
from meshterm.core.radionode import _forget_edge_threads
from meshterm.core.transmit_lock import TransmitLock
from meshterm.emulator import framebuffer
from meshterm.emulator.devices import CARDPUTER_ZERO_DEVICE, PICOCALC_LYRA_DEVICE
from meshterm.emulator.window import EmulatorWindow
from meshterm.services import hold_to_quit
from meshterm.ui.tui import holdquit, session as session_mod
from meshterm.ui.tui.holdquit import HoldQuitDialog
from meshterm.ui.tui.screen import ScrollScreen
from meshterm.ui.tui.session import TuiSession
ESC = "\x1b"
class _Heard:
"""A listener that writes down what it was told."""
def __init__(self) -> None:
self.calls: list[tuple] = []
def held(self, since: float) -> None:
self.calls.append(("held", since))
def released(self) -> None:
self.calls.append(("released",))
def terminate(self) -> None:
self.calls.append(("terminate",))
@pytest.fixture(autouse=True)
def _nobody_listening():
"""Every test starts and ends with no listener and nothing held."""
hold_to_quit._listener = None
hold_to_quit._leaving = False
hold_to_quit._forget()
yield
hold_to_quit._listener = None
hold_to_quit._leaving = False
hold_to_quit._forget()
@pytest.fixture
def quick(monkeypatch):
"""The gesture's timings shrunk to test speed: box at 0.1 s, out at 0.3 s."""
monkeypatch.setattr(hold_to_quit, "DIALOG_S", 0.1)
monkeypatch.setattr(hold_to_quit, "QUIT_S", 0.3)
monkeypatch.setattr(holdquit, "BAR_TICK_S", 0.02)
# --- the rules --------------------------------------------------------------------------
def test_with_nobody_listening_esc_is_typed_as_it_goes_down() -> None:
"""Before the TUI runs (or on a device without the rule) Esc is any other key."""
typed: list[str] = []
esc = hold_to_quit.EscKey(typed.append)
esc.down()
esc.down() # the keyboard's repeat, as it always typed
esc.up()
assert typed == [ESC, ESC]
def test_a_tap_is_typed_on_its_release_and_a_repeat_is_part_of_the_hold() -> None:
heard = _Heard()
hold_to_quit.listen(heard)
typed: list[str] = []
esc = hold_to_quit.EscKey(typed.append)
esc.down()
esc.down()
assert typed == [], "a held Esc is owed, not typed"
assert [c[0] for c in heard.calls] == ["held"], "one hold, however often it repeats"
esc.up()
assert typed == [ESC]
assert heard.calls[-1] == ("released",)
def test_another_key_sends_the_held_esc_ahead_of_itself_once() -> None:
"""Keys keep their order: Esc, then the key pressed while Esc was still down."""
hold_to_quit.listen(_Heard())
typed: list[str] = []
esc = hold_to_quit.EscKey(typed.append)
esc.down()
esc.before()
typed.append("a")
esc.before()
typed.append("b")
esc.up()
assert typed == [ESC, "a", "b"]
def test_a_claimed_hold_types_nothing_when_let_go() -> None:
"""Once the box is up the reader is deciding about leaving, not about going back."""
heard = _Heard()
hold_to_quit.listen(heard)
assert hold_to_quit.press(now=5.0)
assert hold_to_quit.claim(5.0)
assert hold_to_quit.release() is False
def test_a_release_and_the_box_settle_on_exactly_one() -> None:
hold_to_quit.listen(_Heard())
hold_to_quit.press(now=1.0)
assert hold_to_quit.release() is True
assert hold_to_quit.claim(1.0) is False, "a box asking for a hold already let go"
hold_to_quit.press(now=2.0)
assert hold_to_quit.claim(1.0) is False, "a box asking for an earlier hold"
def test_sigterm_asks_the_listener_once_and_joins_an_exit_under_way() -> None:
assert hold_to_quit.terminate() is False, "nothing to ask: the caller stops its own way"
heard = _Heard()
hold_to_quit.listen(heard)
assert hold_to_quit.terminate() is True
assert heard.calls == [("terminate",)]
hold_to_quit.leaving()
hold_to_quit.unlisten(heard)
assert hold_to_quit.terminate() is True, "a SIGTERM landing on a teardown joins it"
assert heard.calls == [("terminate",)]
hold_to_quit.listen(heard)
assert hold_to_quit._leaving is False, "a new session starts with nothing leaving"
# --- the session ------------------------------------------------------------------------
class _Air:
"""A stand-in for the device's transmit lock, as the menu's quiesce holds it."""
def __init__(self) -> None:
self.lock = TransmitLock()
self.held = False
@asynccontextmanager
async def quiet(self):
async with self.lock.held():
self.held = True
try:
yield
finally:
self.held = False
def _running(inp, air: _Air | None = None) -> TuiSession:
session = TuiSession(input=inp, output=DummyOutput())
if air is not None:
session.set_quiesce(air.quiet)
return session
async def _until(condition, timeout: float = 2.0) -> None:
deadline = time.monotonic() + timeout
while not condition():
assert time.monotonic() < deadline, "timed out"
await asyncio.sleep(0.01)
async def test_a_tap_reaches_the_screen_as_esc(quick) -> None:
with create_pipe_input() as inp:
session = _running(inp)
esc = hold_to_quit.EscKey(inp.send_text)
results: list[object] = []
async def main() -> None:
async def tap() -> None:
await asyncio.sleep(0.02)
esc.down()
await asyncio.sleep(0.02)
esc.up()
asyncio.ensure_future(tap())
results.append(await session.run_screen(ScrollScreen("a page")))
await asyncio.wait_for(session.run(main()), timeout=5)
assert results == [None], "the page took the tap as its Esc and closed"
async def test_a_hold_raises_the_box_and_letting_go_undoes_it(quick) -> None:
with create_pipe_input() as inp:
air = _Air()
session = _running(inp, air)
esc = hold_to_quit.EscKey(inp.send_text)
page = ScrollScreen("a capture in progress")
async def main() -> None:
session.push(page)
esc.down()
await _until(lambda: isinstance(session.top, HoldQuitDialog))
await _until(lambda: air.held)
assert session.top.modal, "the box owns the keyboard"
esc.up()
await _until(lambda: session.top is page)
await _until(lambda: not air.held)
await asyncio.sleep(0.4) # past the point the hold would have quit
assert not session.leaving
assert page.future is None, "no Esc reached the page under the box"
session.pop(page)
await asyncio.wait_for(session.run(main()), timeout=5)
async def test_a_box_over_an_empty_stack_takes_its_backdrop_away_with_it(quick) -> None:
"""A tool between two screens: the box brings a blank page to float over, then goes."""
with create_pipe_input() as inp:
session = _running(inp)
esc = hold_to_quit.EscKey(inp.send_text)
async def main() -> None:
esc.down()
await _until(lambda: isinstance(session.top, HoldQuitDialog))
assert len(session._stack) == 2, "a backdrop under the box, so it draws as a box"
esc.up()
await _until(lambda: session.top is None)
await asyncio.wait_for(session.run(main()), timeout=5)
async def test_a_hold_to_the_end_leaves_and_keeps_the_air_quiet(quick) -> None:
with create_pipe_input() as inp:
air = _Air()
session = _running(inp, air)
esc = hold_to_quit.EscKey(inp.send_text)
torn_down: list[bool] = []
async def main() -> None:
try:
esc.down()
await session.run_screen(ScrollScreen("deep"))
finally:
torn_down.append(air.held)
started = time.monotonic()
await asyncio.wait_for(session.run(main()), timeout=5)
assert time.monotonic() - started >= hold_to_quit.QUIT_S - 0.05
assert torn_down == [True], "the teardown runs with nothing able to transmit"
assert session.leaving
esc.up() # letting go after the end changes nothing
async def test_sigterm_waits_for_a_transmission_under_way(quick) -> None:
"""A scoped channel send closes its window before the app goes."""
with create_pipe_input() as inp:
air = _Air()
session = _running(inp, air)
order: list[str] = []
async def transmission() -> None:
async with air.lock.held():
order.append("sending")
assert hold_to_quit.terminate()
await asyncio.sleep(0.15)
order.append("scope restored")
async def main() -> None:
try:
asyncio.ensure_future(transmission())
await session.run_screen(ScrollScreen("chat"))
finally:
order.append("teardown")
await asyncio.wait_for(session.run(main()), timeout=5)
assert order == ["sending", "scope restored", "teardown"]
async def test_a_quiesce_that_never_takes_hold_does_not_keep_the_app(quick, monkeypatch) -> None:
monkeypatch.setattr(session_mod, "QUIESCE_WAIT_S", 0.1)
with create_pipe_input() as inp:
air = _Air()
session = _running(inp, air)
async def wedged() -> None:
async with air.lock.held():
await asyncio.sleep(60)
async def main() -> None:
asyncio.ensure_future(wedged())
await asyncio.sleep(0)
hold_to_quit.terminate()
await session.run_screen(ScrollScreen("chat"))
await asyncio.wait_for(session.run(main()), timeout=5)
assert session.leaving
def test_the_box_s_bar_runs_from_its_appearance_to_the_quit() -> None:
now = [100.0]
dialog = HoldQuitDialog(100.0, clock=lambda: now[0])
assert dialog.fraction == 0.0
now[0] = 100.0 + hold_to_quit.DIALOG_S
assert dialog.fraction == 0.0
now[0] = 100.0 + (hold_to_quit.DIALOG_S + hold_to_quit.QUIT_S) / 2
assert dialog.fraction == pytest.approx(0.5)
now[0] = 100.0 + hold_to_quit.QUIT_S + 1
assert dialog.fraction == 1.0
assert dialog.fkey_lane is not None
dialog.handle("enter") # no key does anything to it
# --- the front ends ---------------------------------------------------------------------
def _events(path, *events: tuple[int, int]) -> None:
record = struct.Struct("llHHi")
path.write_bytes(b"".join(record.pack(0, 0, 1, code, value) for code, value in events))
def _reader(path, typed: list[str]):
device = object.__new__(framebuffer.Device)
device._keyboard = str(path)
device._closing = False
device._type = typed.append
return device
def test_the_device_types_a_tap_on_its_release_and_keys_after_it(tmp_path) -> None:
hold_to_quit.listen(_Heard())
path = tmp_path / "keyboard"
# Esc down, its repeat, A down while Esc is held, A up, Esc up.
_events(path, (1, 1), (1, 2), (30, 1), (30, 0), (1, 0))
typed: list[str] = []
_reader(path, typed)._read_keys()
assert typed == [ESC, "a"]
def test_the_device_types_esc_at_once_with_nobody_listening(tmp_path) -> None:
path = tmp_path / "keyboard"
_events(path, (1, 1), (1, 2), (1, 0))
typed: list[str] = []
_reader(path, typed)._read_keys()
assert typed == [ESC, ESC]
def test_the_launcher_s_sigterm_is_a_quit_or_an_interrupt() -> None:
before = signal.getsignal(signal.SIGTERM)
try:
framebuffer._leave_on_sigterm()
handler = signal.getsignal(signal.SIGTERM)
with pytest.raises(KeyboardInterrupt):
handler(signal.SIGTERM, None) # nothing running to leave
heard = _Heard()
hold_to_quit.listen(heard)
handler(signal.SIGTERM, None)
assert heard.calls == [("terminate",)]
finally:
signal.signal(signal.SIGTERM, before)
class _Root:
"""Tk's timer calls, run by hand."""
def __init__(self) -> None:
self.pending: dict[str, object] = {}
def after(self, _ms: int, work) -> str:
name = f"after#{len(self.pending)}"
self.pending[name] = work
return name
def after_cancel(self, name: str) -> None:
self.pending.pop(name, None)
def run(self) -> None:
for name in list(self.pending):
self.pending.pop(name)()
class _Event:
def __init__(self, keysym: str) -> None:
self.keysym, self.char, self.state = keysym, "", 0
def _window(device, typed: list[str]) -> tuple[EmulatorWindow, _Root]:
root = _Root()
window = object.__new__(EmulatorWindow)
window._device = device
window._tk = (root, None, None, None)
window._type = typed.append
window._esc = hold_to_quit.EscKey(typed.append)
window._esc_down = False
window._esc_letting_go = None
window._shifted = False
return window, root
def test_the_window_reads_an_x_server_s_repeat_as_one_hold(monkeypatch) -> None:
"""X repeats a held key as release-press pairs; only a release left alone lets go."""
monkeypatch.setattr(EmulatorWindow, "_set_shift", lambda self, down: None)
heard = _Heard()
hold_to_quit.listen(heard)
typed: list[str] = []
window, root = _window(CARDPUTER_ZERO_DEVICE, typed)
window._on_press(_Event("Escape"))
for _ in range(3):
window._on_release(_Event("Escape"))
window._on_press(_Event("Escape"))
assert root.pending == {}
assert [c[0] for c in heard.calls] == ["held"]
window._on_release(_Event("Escape"))
root.run()
assert typed == [ESC]
assert heard.calls[-1] == ("released",)
window._on_press(_Event("Escape"))
window._on_focus_out(None)
assert typed == [ESC, ESC], "an Esc still down as the window loses focus is let go"
def test_the_picocalc_window_types_esc_as_it_goes_down(monkeypatch) -> None:
hold_to_quit.listen(_Heard())
typed: list[str] = []
window, _ = _window(PICOCALC_LYRA_DEVICE, typed)
window._on_press(_Event("Escape"))
assert typed == [ESC]
# --- the radio node's exit --------------------------------------------------------------
def test_the_node_skips_the_wait_on_its_irq_thread() -> None:
"""The library joins a thread parked in a 30 s poll for 2 s; the node does not wait."""
class _Manager:
def __init__(self) -> None:
self._edge_stop_events = {23: threading.Event()}
self._edge_threads = {23: object()}
class _Radio:
_gpio_manager = _Manager()
radio = _Radio()
_forget_edge_threads(radio)
assert radio._gpio_manager._edge_stop_events[23].is_set()
assert radio._gpio_manager._edge_threads == {}
_forget_edge_threads(object()) # a library that keeps them elsewhere is left alone