Holding Esc quits wherever MeshTerm can tell the key is held

Hold-to-quit was the Cardputer's alone. It is now MeshTerm's gesture
everywhere a key can be seen coming up, which a terminal never reports:

- The emulator's window, for either handheld, which reads its own keys
  as the Cardputer's panel does.
- A terminal's Esc, where the keyboard can be asked whether it is still
  down: GetAsyncKeyState on Windows, as the right-Ctrl rescue already
  asks, and EVIOCGKEY on Linux wherever the keyboard's event device
  opens (the PicoCalc, a uConsole, a user in `input`). It reads the key
  state only, no events.

An Esc arriving while its key is still down is held back as a hold:
delivered as it comes up, a box after a second, gone at three. The
keyboard's repeats are part of the hold, a key typed during it goes in
behind the Esc, and on a VT stream the last repeat, which prompt_toolkit
can parse after the key is up, is dropped rather than going back a
screen behind a box the reader just let go of. On macOS and over SSH Esc
is unchanged.

SIGTERM is a quit for the interactive menu on every platform now, not
only under the Cardputer's launcher: a system shutting down gets the
same clean exit, terminal and console font restored.

EVIOCGKEY checked on the Cardputer's arm64 kernel; the Lyra was offline.

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 01:20:53 -04:00
1 parent 9d16e0722a
commit b9585e9b59
12 files changed
+529 -91

No files matched your search

+14 -10
View File
@@ -164,6 +164,16 @@ deliberately, one at a time, and say why in the code.
the question up is the leaving — one key pressed twice, as ^Q is.
`test_navigation` walks every string literal in the package to keep them out of the rest
of the UI.
- **Holding Esc quits**, from anywhere, wherever MeshTerm can tell a key is held
(`services/hold_to_quit.py`): a front end that reads its own keys (the emulator, both
devices), or a probe that asks the keyboard whether a terminal's Esc is still down
(`esc_probe`: `GetAsyncKeyState` on Windows, `EVIOCGKEY` on a readable Linux keyboard).
There Esc acts 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 SIGTERM (`leave_on_sigterm`, the menu's on
every platform) both take it, and a second joins it. macOS and SSH can't see a release,
so there Esc is unchanged.
- **Esc at the main menu does nothing** but peel a typed filter: the menu is the bottom of
the stack, so Esc-mashing up to it settles there. Leaving is the Quit row or ^Q, both
behind the confirm. ^W arms **every frame on the stack**, not just the
@@ -755,16 +765,10 @@ 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.
- **The Cardputer's exit must fit its launcher's grace.** A held Esc there is the
launcher's own way out (SIGTERM at 3 s, SIGKILL 3 s later, letting go or not), which is
where hold-to-quit's timing comes from (see **Navigation**). MeshTerm's whole exit was
measured at 1.3 s 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
+3 -2
View File
@@ -533,8 +533,9 @@ radio behind it, drawing braille charts and node glyphs cleanly — no empty tof
the bottom you should see the **F-key lane**: five labelled chips instead of the footer hint
line a desktop terminal shows.
Have a look around. **Esc** backs out of any screen, and **Quit** on the main menu leaves
the app.
Have a look around. **Esc** backs out of any screen. To leave the app, choose **Quit** on
the main menu, or hold **Esc** for three seconds from any screen. After a second a box
shows a bar filling up, and letting go before it fills keeps you where you were.
Then look at the whole visual language on one card:
+22
View File
@@ -71,3 +71,25 @@ pages close it.
| **👤 About the author** | The person behind MeshTerm, on the mesh and off it. | `meshterm about-author` |
| **🔗 Join Discord** | The community server: one invite link, and a QR of it for a phone to read. | `meshterm discord` |
| **💰 Support MeshTerm** | What keeps MeshTerm going, and the ways — paid and unpaid — to help it along. | `meshterm support` |
## Leaving MeshTerm
**Quit** at the bottom of the main menu leaves, after asking. **Ctrl+Q** asks the same
question from any screen, and pressing it again while the question is up leaves at once.
You can also hold **Esc**. After a second, a box says *Hold Esc to quit*, with a bar that
fills over the next two seconds. When it's full, MeshTerm closes, the same way Quit closes
it. Let go before then and you're back where you were. While the box is up, MeshTerm
doesn't start sending anything new over the radio, so a message that's going out finishes
first. A quick press of **Esc** still goes back a screen, as always.
Holding Esc only works where MeshTerm can tell that a key is being held down, and a
terminal never says when a key comes back up. These can tell:
- Windows.
- Linux, where you can read your keyboard's input device. That includes the PicoCalc, and
a uConsole or any other Linux computer where your user is in the `input` group.
- The Cardputer Zero, and the [emulator](../devices/cardputer-zero.md#trying-it-in-the-emulator)
window for either handheld.
On a Mac, or over SSH, Esc works as it always did.
+5
View File
@@ -363,6 +363,11 @@ def main_callback(
# them whole, so it is the one that claims the directory. One-shot subcommands are
# brief and mostly read; blocking `meshterm contacts` because a menu is open in
# another window would be an obstacle rather than a guard.
# A SIGTERM (the Cardputer launcher's end of a held Esc, a system shutting down)
# leaves the menu the way Quit does, instead of stopping it wherever it stood.
from .services import hold_to_quit
hold_to_quit.leave_on_sigterm()
try:
with hold_instance_lock(settings.config_dir):
asyncio.run(_drive(run_menu(app_ctx), app_ctx))
+1 -8
View File
@@ -41,10 +41,6 @@ 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
@@ -53,7 +49,6 @@ 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:
@@ -80,14 +75,12 @@ 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 — and
#: Esc held for three seconds its launcher's way out of any app.
#: the five keys right under the panel, at the positions M5's drawing gives them.
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
+4 -21
View File
@@ -8,7 +8,7 @@ app reads key events itself, while the launcher watches the same stream for a he
(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`).
quit it is (:func:`~meshterm.services.hold_to_quit.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
@@ -29,7 +29,6 @@ from __future__ import annotations
import mmap
import os
import signal
import struct
import threading
from collections.abc import Callable
@@ -261,24 +260,6 @@ class Device:
self._type(sequence)
def _leave_on_sigterm() -> None:
"""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():
"""The device as a :data:`~.run.FrontEndFactory`, from the launcher's environment."""
from .font import find_font
@@ -286,7 +267,9 @@ def front_end():
font = find_font()
framebuffer = os.environ.get(FB_ENV) or "/dev/fb0"
keyboard = os.environ.get(KEYBOARD_ENV) or DEFAULT_KEYBOARD
_leave_on_sigterm()
# From here, not only from the CLI: the launcher's SIGTERM can land while MeshTerm is
# still importing, and there it should stop as an interrupt rather than unhandled.
hold_to_quit.leave_on_sigterm()
def build(terminal: Terminal, lock: threading.Lock, type_text: Callable[[str], None]):
return Device(
+4 -3
View File
@@ -18,8 +18,9 @@ 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. 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`).
directory. Esc held in the window quits, as it does on either device
(:mod:`~meshterm.services.hold_to_quit`): the window sees a key come up, as a terminal
never does.
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.
@@ -345,7 +346,7 @@ class EmulatorWindow:
if event.keysym in _SHIFTS:
self._set_shift(True)
return
if event.keysym == "Escape" and self._device.hold_to_quit:
if event.keysym == "Escape":
self._esc_pressed()
return
if event.keysym in ("S", "s") and event.state & _CTRL_BIT and event.state & _SHIFT_BIT:
+157 -33
View File
@@ -1,55 +1,65 @@
# 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.
"""Hold Esc to quit: MeshTerm's way out from any screen, wherever it can tell a key is held.
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.
* **A tap is Esc.** Let go within :data:`DIALOG_S` and the screen 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.
the two seconds left until :data:`QUIT_S`. 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`).
* **Hold it to the end** and MeshTerm leaves the way Quit does, without asking.
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.
**Where it works is where a key can be seen going up**, which a terminal never reports.
The emulator's front ends read the keys themselves (the Cardputer Zero's event stream, the
window's key events), so they own the Esc: they report it going down and up and type it
only when it is a press (:class:`EscKey`). For a terminal's Esc, two systems answer "is Esc
down right now?" — Windows (``GetAsyncKeyState``) and Linux where the keyboard's event
device can be opened (``EVIOCGKEY``: the PicoCalc, a uConsole, any machine whose user is
in ``input``) — and the session holds back an Esc that arrives still down (:func:`esc_probe`,
:class:`~meshterm.ui.tui.holdquit.WatchedEsc`). Elsewhere — macOS, and any session over
SSH, whose keyboard is on another machine — Esc is what it always was.
**Why three seconds:** it is the Cardputer Zero's own rule. Its launcher goes on reading
the keyboard while an app runs, 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. Its own hint never reaches the panel, since its
drawing is paused while an app owns it, so 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 took the launcher's timing for every platform; on the Cardputer the
launcher's SIGTERM arrives as the bar runs out and joins that exit rather than cutting
into it (:func:`terminate`, :func:`leave_on_sigterm`).
The session knows the screens and a front end or a probe knows the key, so this module is
where they meet, as :mod:`~meshterm.services.modifier_watch` is for Shift. The session
listens while it runs; 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 os
import signal
import sys
import threading
import time
from collections.abc import Callable
from pathlib import Path
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.
#: Seconds Esc is held before MeshTerm leaves: the Cardputer Zero launcher's own
#: ``TERMINATE_DELAY_MS``, when its SIGTERM lands anyway, so there the bar runs out when
#: the launcher says it does, and everywhere else the gesture is the same one.
QUIT_S = 3.0
#: Seconds the launcher waits after its SIGTERM before it sends SIGKILL
@@ -201,6 +211,117 @@ def terminate() -> bool:
return True
def holding() -> bool:
"""Whether an Esc is being held and watched right now."""
with _lock:
return _since is not None
def leave_on_sigterm() -> None:
"""Take SIGTERM as a quit: the end of a held Esc on the Cardputer, a shutdown anywhere.
With the TUI running, MeshTerm leaves the way a held Esc does when its bar runs out
(:func:`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 would cut the teardown short. Before the TUI starts there is nothing to put away,
and it stops as an interrupt would. Off the main thread (MeshTerm run inside another
program) it leaves the handler to whoever owns that thread, as Python requires.
"""
def on_term(signum: int, frame: object) -> None:
if not terminate():
raise KeyboardInterrupt
if threading.current_thread() is threading.main_thread():
signal.signal(signal.SIGTERM, on_term)
# --- asking the keyboard ------------------------------------------------------------------
#: Windows' virtual-key code for Esc.
_VK_ESCAPE = 0x1B
#: Linux's key code for Esc (``KEY_ESC``), and ``EVIOCGKEY(96)``: which keys an event device
#: holds down right now, one bit each. 96 bytes cover every key code there is (``KEY_MAX``
#: is 0x2ff); the request's number is the generic ``_IOC`` encoding, ARM's and x86's both.
_KEY_ESC = 1
_EVIOCGKEY = (2 << 30) | (96 << 16) | (ord("E") << 8) | 0x18
_SYS_INPUT = Path("/sys/class/input")
_DEV_INPUT = Path("/dev/input")
def esc_probe() -> Callable[[], bool] | None:
"""A way to ask whether Esc is physically down right now, or ``None`` where there is none.
For a terminal's Esc, which arrives with no word of when it comes up: the session asks
when one arrives, and while the answer is yes the Esc is a hold (see
:class:`~meshterm.ui.tui.holdquit.WatchedEsc`). Windows answers for the keyboard in front
of it (``GetAsyncKeyState``, as the right-Ctrl rescue already asks); Linux, for every
keyboard whose event device this user can open (``EVIOCGKEY``, which reads the key
state and no events). Nothing on macOS, which keeps a key's state behind a permission
prompt. A probe that fails answers no, and Esc is an ordinary key again.
"""
if sys.platform == "win32":
return _windows_probe()
if sys.platform.startswith("linux"):
return _evdev_probe()
return None
def _windows_probe() -> Callable[[], bool] | None:
try:
from ..core import win32dll
user32 = win32dll.user32()
except Exception: # noqa: BLE001 - no probe is an ordinary Esc, not an error
return None
def down() -> bool:
try:
return bool(user32.GetAsyncKeyState(_VK_ESCAPE) & 0x8000)
except Exception: # noqa: BLE001 - a failed probe answers no
return False
return down
def _evdev_probe(root: Path = _SYS_INPUT, dev: Path = _DEV_INPUT) -> Callable[[], bool] | None:
"""Every keyboard with an Esc key whose event device opens, asked through ``EVIOCGKEY``."""
try:
import fcntl
except ImportError:
return None
devices: list[int] = []
for entry in sorted(root.glob("event*")):
try:
words = (entry / "device" / "capabilities" / "key").read_text().split()
except OSError:
continue
# The key bitmap's words run highest first; KEY_ESC is a bit of the last one.
if not words or not int(words[-1], 16) & (1 << _KEY_ESC):
continue
flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_CLOEXEC", 0)
try:
devices.append(os.open(dev / entry.name, flags))
except OSError:
continue
if not devices:
return None
def down() -> bool:
state = bytearray(96)
for fd in devices:
try:
fcntl.ioctl(fd, _EVIOCGKEY, state)
except OSError:
continue
if state[_KEY_ESC // 8] & (1 << _KEY_ESC % 8):
return True
return False
return down
def _forget() -> None:
"""Drop the hold under way (call with the lock held)."""
global _since, _owed, _claimed
@@ -243,7 +364,10 @@ __all__ = [
"EscKey",
"Listener",
"claim",
"esc_probe",
"holding",
"interrupt",
"leave_on_sigterm",
"leaving",
"listen",
"press",
+6
View File
@@ -28,6 +28,7 @@ from .. import __version__
from ..context import AppContext
from ..persistence.logging import get_logger
from ..platforms import get_platform
from ..services import hold_to_quit
from ..tools import all_tools
from .braillechart import activity_peak, activity_sparkline
from .menus import (
@@ -423,6 +424,11 @@ async def run_menu(ctx: AppContext) -> None:
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))
# Where a terminal delivers the keys, the keyboard is asked whether an Esc is still
# held, so holding it quits there too. The emulator reads its keys itself, and its
# machine's keyboard is not the device's.
if not get_platform().own_display:
session.set_esc_probe(hold_to_quit.esc_probe())
async def main() -> None:
try:
+92 -5
View File
@@ -4,16 +4,21 @@
: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
a :class:`HoldQuitDialog` over whatever is up, 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`).
Who says Esc went down and up depends on who has the keys. A front end that reads them
itself (the emulator's) says so directly. Where a terminal delivers them, :class:`WatchedEsc`
asks the keyboard whether an arriving Esc is still down, and if it is, holds it back and
watches it until it comes up.
"""
from __future__ import annotations
import asyncio
import sys
import time
from collections.abc import Callable
from contextlib import AbstractAsyncContextManager
@@ -234,4 +239,86 @@ class EscHoldWatch:
self._backdrop = None
__all__ = ["BAR_TICK_S", "EscHoldWatch", "HoldQuitDialog", "Quiet"]
#: Whether a terminal's keys arrive as a VT byte stream, whose last Esc can be parsed after
#: the key is up: everywhere but Windows, where prompt_toolkit reads the console's events.
VT_INPUT = sys.platform != "win32"
#: Seconds between looks at the keyboard while a terminal's Esc is held. A tap is let go
#: well within a tenth of a second of this, and the probes cost next to nothing to ask.
POLL_S = 0.03
class WatchedEsc:
"""A terminal's Esc, with the keyboard asked whether it is still held.
Where no front end owns the keys, Esc arrives through the terminal like any other key,
and the terminal never says when it comes up. The keyboard does
(:func:`~meshterm.services.hold_to_quit.esc_probe`). So an Esc that arrives while the
key is still down is held back, and the hold reported and watched, the same hold an
owning front end reports: let go at once and it is delivered, a second's hold raises
the box, and the keyboard's repeats are part of the hold.
Through a VT stream a lone Esc byte reaches the screen only once prompt_toolkit has
waited to be sure it starts no sequence (``ttimeoutlen``), so a tap is usually let go
before it arrives and is never held back at all; and the last repeat of a hold can
arrive *after* the key is up. Repeats arriving that late are swallowed for as long as
that wait lasts, rather than going back a screen behind a box the reader just let go of.
"""
def __init__(self, session: TuiSession, down: Callable[[], bool]) -> None:
"""Hold back ``session``'s Esc while ``down()`` says the key is still held."""
self._session = session
self._down = down
self._watching: asyncio.Future | None = None
self._repeats = 0
self._late_until = 0.0
self._delivering = False
def take(self) -> bool:
"""An Esc arrived. Returns whether it is held back as part of a hold."""
if self._delivering:
return False
if self._watching is not None:
self._repeats += 1
return True # the keyboard repeating a held key
if time.monotonic() < self._late_until:
return True # a repeat of the hold just let go, parsed late
if not self._down() or not hold_to_quit.press():
return False # let go already, or nothing listening
self._repeats = 0
self._watching = asyncio.ensure_future(self._until_let_go())
return True
def ahead(self) -> None:
"""Another key arrived: deliver an Esc still held back first, so keys keep order."""
if self._watching is not None and hold_to_quit.interrupt():
self._deliver()
async def _until_let_go(self) -> None:
while self._down():
await asyncio.sleep(POLL_S)
self._watching = None
tap = hold_to_quit.release()
if self._repeats and VT_INPUT:
app = getattr(self._session, "_app", None)
self._late_until = time.monotonic() + getattr(app, "ttimeoutlen", 0.5) + POLL_S
if tap:
self._deliver()
def _deliver(self) -> None:
self._delivering = True
try:
self._session._dispatch("escape")
finally:
self._delivering = False
__all__ = [
"BAR_TICK_S",
"POLL_S",
"VT_INPUT",
"EscHoldWatch",
"HoldQuitDialog",
"Quiet",
"WatchedEsc",
]
+29 -1
View File
@@ -37,7 +37,7 @@ from ...platforms import get_platform
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 .holdquit import EscHoldWatch, Quiet, WatchedEsc
from .overlay import BusyOverlay
from .progress import TuiProgress
from .prompt import (
@@ -568,6 +568,9 @@ class TuiSession:
self._quiesce: Callable[[], AbstractAsyncContextManager[Any]] | None = None
self._quiet: Quiet | None = None
self._leaving = False
# A terminal's Esc, held back while the keyboard says it is still down — where
# something can say so (see :meth:`set_esc_probe`).
self._watched_esc: WatchedEsc | None = None
# --- stack ---------------------------------------------------------------
@@ -733,6 +736,21 @@ class TuiSession:
"""
self._quiesce = enter
def set_esc_probe(self, down: Callable[[], bool] | None) -> None:
"""Declare how to ask whether Esc is physically down, for a terminal's Esc.
With one, an Esc that arrives while its key is still down is held back and watched
as a hold (:class:`~meshterm.ui.tui.holdquit.WatchedEsc`): the hold-to-quit gesture
where a terminal, which never reports a key coming up, delivers the keys. The app
declares it, because only the app knows the keys are this machine's own — not a
front end's that reads them itself (the emulator's), not another machine's over SSH.
Args:
down: Answers whether Esc is down right now
(:func:`~meshterm.services.hold_to_quit.esc_probe`), or ``None``.
"""
self._watched_esc = None if down is None else WatchedEsc(self, down)
@property
def leaving(self) -> bool:
"""Whether the app is on its way out (:meth:`leave`), which nothing calls back."""
@@ -2230,6 +2248,16 @@ class TuiSession:
action = _CTRL_CHORDS[action]
elif action == "text" and data.lower() in _CTRL_LETTER_CHORDS and _right_ctrl_down():
action, data = _CTRL_LETTER_CHORDS[data.lower()], ""
# A terminal's Esc still held down is a hold, not yet a press; any other key goes
# behind an Esc held back, so keys keep their order (see set_esc_probe).
watched = self._watched_esc
if watched is not None:
if action == "escape":
if watched.take():
self.invalidate()
return
else:
watched.ahead()
if action == "to_menu":
# Pop every frame at once (^W). Refused over a dialog or work in flight; see
# request_pop_all. The repaint below is still wanted either way — a refusal
+192 -8
View File
@@ -1,9 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
"""Hold Esc to quit: the Cardputer Zero launcher's way out, and MeshTerm's half of it.
"""Hold Esc to quit, wherever MeshTerm can tell a key is held.
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.
quiesce (:mod:`meshterm.ui.tui.holdquit`), the two front ends that see a key go up, a
terminal's Esc watched through the keyboard, SIGTERM, and the radio node's exit fitting
inside the Cardputer launcher's grace.
"""
from __future__ import annotations
@@ -11,8 +12,10 @@ from __future__ import annotations
import asyncio
import signal
import struct
import sys
import threading
import time
import types
from contextlib import asynccontextmanager
import pytest
@@ -25,7 +28,8 @@ 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 import holdquit
from meshterm.ui.tui import 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
@@ -83,6 +87,7 @@ def test_with_nobody_listening_esc_is_typed_as_it_goes_down() -> None:
def test_a_tap_is_typed_on_its_release_and_a_repeat_is_part_of_the_hold() -> None:
"""A tap is owed until it comes up, and the keyboard's repeats are one hold."""
heard = _Heard()
hold_to_quit.listen(heard)
typed: list[str] = []
@@ -120,6 +125,7 @@ def test_a_claimed_hold_types_nothing_when_let_go() -> None:
def test_a_release_and_the_box_settle_on_exactly_one() -> None:
"""A release and the box asking for the same hold: exactly one of them wins."""
hold_to_quit.listen(_Heard())
hold_to_quit.press(now=1.0)
assert hold_to_quit.release() is True
@@ -129,6 +135,7 @@ def test_a_release_and_the_box_settle_on_exactly_one() -> None:
def test_sigterm_asks_the_listener_once_and_joins_an_exit_under_way() -> None:
"""SIGTERM asks a running session to leave, and joins an exit already under way."""
assert hold_to_quit.terminate() is False, "nothing to ask: the caller stops its own way"
heard = _Heard()
hold_to_quit.listen(heard)
@@ -177,6 +184,7 @@ async def _until(condition, timeout: float = 2.0) -> None:
async def test_a_tap_reaches_the_screen_as_esc(quick) -> None:
"""A tap reaches the screen as the Esc it was."""
with create_pipe_input() as inp:
session = _running(inp)
esc = hold_to_quit.EscKey(inp.send_text)
@@ -197,6 +205,7 @@ async def test_a_tap_reaches_the_screen_as_esc(quick) -> None:
async def test_a_hold_raises_the_box_and_letting_go_undoes_it(quick) -> None:
"""A second's hold raises the box and quiets the air; letting go undoes both."""
with create_pipe_input() as inp:
air = _Air()
session = _running(inp, air)
@@ -237,6 +246,7 @@ async def test_a_box_over_an_empty_stack_takes_its_backdrop_away_with_it(quick)
async def test_a_hold_to_the_end_leaves_and_keeps_the_air_quiet(quick) -> None:
"""Held to the end, the app leaves with nothing able to transmit."""
with create_pipe_input() as inp:
air = _Air()
session = _running(inp, air)
@@ -284,6 +294,7 @@ async def test_sigterm_waits_for_a_transmission_under_way(quick) -> None:
async def test_a_quiesce_that_never_takes_hold_does_not_keep_the_app(quick, monkeypatch) -> None:
"""A transmission that never ends cannot keep the app from leaving."""
monkeypatch.setattr(session_mod, "QUIESCE_WAIT_S", 0.1)
with create_pipe_input() as inp:
air = _Air()
@@ -304,6 +315,7 @@ async def test_a_quiesce_that_never_takes_hold_does_not_keep_the_app(quick, monk
def test_the_box_s_bar_runs_from_its_appearance_to_the_quit() -> None:
"""The bar is empty as the box appears and full when the app leaves."""
now = [100.0]
dialog = HoldQuitDialog(100.0, clock=lambda: now[0])
assert dialog.fraction == 0.0
@@ -317,6 +329,171 @@ def test_the_box_s_bar_runs_from_its_appearance_to_the_quit() -> None:
dialog.handle("enter") # no key does anything to it
# --- a terminal's Esc, watched through the keyboard -------------------------------------
class _Keyboard:
"""Esc's physical state, as a probe reports it."""
def __init__(self) -> None:
self.esc = False
def down(self) -> bool:
return self.esc
def _watched(inp, keyboard: _Keyboard, air: _Air | None = None) -> TuiSession:
session = _running(inp, air)
session.set_esc_probe(keyboard.down)
return session
class _Keys(ScrollScreen):
"""A page that writes down every key it is handed."""
def __init__(self) -> None:
super().__init__("a page")
self.got: list[str] = []
def handle(self, action: str, data: str = "") -> None:
self.got.append(data or action)
async def test_a_terminal_s_esc_already_let_go_is_an_esc_at_once(quick) -> None:
"""A terminal's Esc whose key is already up is an ordinary Esc."""
with create_pipe_input() as inp:
keyboard = _Keyboard()
session = _watched(inp, keyboard)
page = _Keys()
async def main() -> None:
session.push(page)
session._dispatch("escape")
assert page.got == ["escape"]
session.pop(page)
await asyncio.wait_for(session.run(main()), timeout=5)
async def test_a_terminal_s_esc_still_down_is_held_until_it_comes_up(quick) -> None:
"""A terminal's Esc still down is held back and delivered once it comes up."""
with create_pipe_input() as inp:
keyboard = _Keyboard()
session = _watched(inp, keyboard)
page = _Keys()
async def main() -> None:
session.push(page)
keyboard.esc = True
session._dispatch("escape")
session._dispatch("escape") # the keyboard's repeat
assert page.got == []
keyboard.esc = False
await _until(lambda: page.got == ["escape"])
await asyncio.sleep(0.05)
assert page.got == ["escape"], "one press, however often it repeated"
session.pop(page)
await asyncio.wait_for(session.run(main()), timeout=5)
async def test_a_key_typed_during_a_terminal_s_hold_follows_the_esc(quick) -> None:
"""A key typed while a terminal's Esc is held goes in behind the Esc."""
with create_pipe_input() as inp:
keyboard = _Keyboard()
session = _watched(inp, keyboard)
page = _Keys()
async def main() -> None:
session.push(page)
keyboard.esc = True
session._dispatch("escape")
session._dispatch("text", "a")
assert page.got == ["escape", "a"]
keyboard.esc = False
await asyncio.sleep(0.1)
assert page.got == ["escape", "a"]
session.pop(page)
await asyncio.wait_for(session.run(main()), timeout=5)
@pytest.mark.parametrize(("vt", "late"), [(True, []), (False, ["escape"])])
async def test_a_terminal_s_held_esc_raises_the_box_and_a_late_repeat_is_dropped(
quick, monkeypatch, vt: bool, late: list[str]
) -> None:
"""A VT stream's last repeat can be parsed after the key is up; Windows' never is."""
monkeypatch.setattr(holdquit, "VT_INPUT", vt)
with create_pipe_input() as inp:
keyboard = _Keyboard()
air = _Air()
session = _watched(inp, keyboard, air)
page = _Keys()
async def main() -> None:
session.push(page)
keyboard.esc = True
session._dispatch("escape")
await _until(lambda: isinstance(session.top, HoldQuitDialog))
await _until(lambda: air.held)
session._dispatch("escape") # a repeat, under the box
keyboard.esc = False
await _until(lambda: session.top is page)
await _until(lambda: not air.held)
session._dispatch("escape") # a VT stream's last repeat, or a fresh press
assert page.got == late, "letting go of a hold goes back nowhere"
session.pop(page)
await asyncio.wait_for(session.run(main()), timeout=5)
async def test_a_terminal_s_esc_held_to_the_end_leaves(quick) -> None:
"""A terminal's Esc held to the end leaves, as an owned one does."""
with create_pipe_input() as inp:
keyboard = _Keyboard()
session = _watched(inp, keyboard)
async def main() -> None:
keyboard.esc = True
session._dispatch("escape")
await session.run_screen(ScrollScreen("deep"))
await asyncio.wait_for(session.run(main()), timeout=5)
assert session.leaving
def test_an_evdev_probe_asks_every_keyboard_with_an_esc_key(tmp_path, monkeypatch) -> None:
"""Only devices whose key bitmap has KEY_ESC are opened; the state comes from EVIOCGKEY."""
sysfs, dev = tmp_path / "sys", tmp_path / "dev"
dev.mkdir()
for name, words in (("event0", "0"), ("event1", "e 0 0 fffffffffffffffe"), ("event2", "10")):
caps = sysfs / name / "device" / "capabilities"
caps.mkdir(parents=True)
(caps / "key").write_text(words + "\n")
(dev / name).write_bytes(b"")
asked: list[int] = []
held = {"esc": False}
def ioctl(fd: int, request: int, state: bytearray) -> None:
assert request == hold_to_quit._EVIOCGKEY
asked.append(fd)
state[0] = 0b10 if held["esc"] else 0
monkeypatch.setitem(sys.modules, "fcntl", types.SimpleNamespace(ioctl=ioctl))
down = hold_to_quit._evdev_probe(sysfs, dev)
assert down is not None
assert down() is False
assert len(asked) == 1, "event0 and event2 have no Esc key and were never opened"
held["esc"] = True
assert down() is True
def test_no_keyboard_that_opens_means_no_probe(tmp_path, monkeypatch) -> None:
"""With no keyboard to open there is no probe, and Esc is ordinary."""
monkeypatch.setitem(sys.modules, "fcntl", types.SimpleNamespace(ioctl=None))
assert hold_to_quit._evdev_probe(tmp_path / "sys", tmp_path / "dev") is None
# --- the front ends ---------------------------------------------------------------------
@@ -334,6 +511,7 @@ def _reader(path, typed: list[str]):
def test_the_device_types_a_tap_on_its_release_and_keys_after_it(tmp_path) -> None:
"""The device's key reader types a tap on release, ahead of a key pressed during it."""
hold_to_quit.listen(_Heard())
path = tmp_path / "keyboard"
# Esc down, its repeat, A down while Esc is held, A up, Esc up.
@@ -344,6 +522,7 @@ def test_the_device_types_a_tap_on_its_release_and_keys_after_it(tmp_path) -> No
def test_the_device_types_esc_at_once_with_nobody_listening(tmp_path) -> None:
"""With nothing listening the device's Esc and its repeats are typed at once."""
path = tmp_path / "keyboard"
_events(path, (1, 1), (1, 2), (1, 0))
typed: list[str] = []
@@ -351,10 +530,11 @@ def test_the_device_types_esc_at_once_with_nobody_listening(tmp_path) -> None:
assert typed == [ESC, ESC]
def test_the_launcher_s_sigterm_is_a_quit_or_an_interrupt() -> None:
def test_sigterm_is_a_quit_or_an_interrupt() -> None:
"""SIGTERM is a quit while the TUI runs, and an interrupt before it does."""
before = signal.getsignal(signal.SIGTERM)
try:
framebuffer._leave_on_sigterm()
hold_to_quit.leave_on_sigterm()
handler = signal.getsignal(signal.SIGTERM)
with pytest.raises(KeyboardInterrupt):
handler(signal.SIGTERM, None) # nothing running to leave
@@ -425,11 +605,15 @@ def test_the_window_reads_an_x_server_s_repeat_as_one_hold(monkeypatch) -> 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:
def test_the_picocalc_window_holds_esc_too() -> None:
"""The gesture is MeshTerm's, not one launcher's: every emulated device takes it."""
hold_to_quit.listen(_Heard())
typed: list[str] = []
window, _ = _window(PICOCALC_LYRA_DEVICE, typed)
window, root = _window(PICOCALC_LYRA_DEVICE, typed)
window._on_press(_Event("Escape"))
assert typed == [], "held, not yet a press"
window._on_release(_Event("Escape"))
root.run()
assert typed == [ESC]