From 45eacf3968559b4d633a52c4415f12db121e5cfb Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 1 Aug 2026 17:45:56 -0400 Subject: [PATCH] F-lane: coloured chips, plain-key priority, shift latch Rebuild the PicoCalc F-key lane per JP's spec: five fixed 9-cell chips (F1 DESCRI, "10" standing in for the overflow F10 label), gray fill on the plain F1-F5 bank and green while Shift's bank is showing, white text on both. DEFAULT_LANE moves to an adjacent-plain-key priority model: commit/leave take the easiest- to-reach F4/F5 with no Shift needed, jump-to-top/end take F1/F2 with paging as their Shift companions, and F3 stays the one lone slot a screen's own lane reaches for first. FPair's Shift half is now optional, so a lone slot renders blank in the shifted bank instead of forcing an unrelated opposite action onto it. Also bridges the on-device quirk where the MCU's F6-F10 translation can appear to release Shift an instant before the translated code lands, flipping the lane back mid-chord: modifier_watch now latches shift_down() true for a short grace window after any F6-F10 press resolves, on top of the raw watcher state. Co-Authored-By: Claude Haiku 4.5 --- meshterm/services/modifier_watch.py | 44 +++++++++++- meshterm/ui/theme.py | 11 +++ meshterm/ui/tui/fkeys.py | 105 +++++++++++++++++----------- meshterm/ui/tui/screen.py | 8 ++- meshterm/ui/tui/session.py | 8 ++- tests/test_modifier_watch.py | 41 +++++++++++ tests/test_picocalc_chrome.py | 22 +++--- 7 files changed, 186 insertions(+), 53 deletions(-) create mode 100644 tests/test_modifier_watch.py diff --git a/meshterm/services/modifier_watch.py b/meshterm/services/modifier_watch.py index c234321..484e5c2 100644 --- a/meshterm/services/modifier_watch.py +++ b/meshterm/services/modifier_watch.py @@ -6,6 +6,16 @@ the ``LSHIFT DOWN`` event arrives *before* the translated F-code (measured in P0 watcher reads the raw evdev stream and tracks whether a Shift key is physically held, so the footer lane can flip to the F6–F10 bank's labels while the user is mid-chord. +On-device use (JP, 2026-08-01) turned up a follow-on quirk: the lane can flip back to its +unshifted bank the instant an F6–F10 code lands, even with Shift still physically held — +consistent with the MCU's key-matrix scan releasing/re-asserting Shift around the chord +rather than holding it down continuously through the translation. :func:`note_shift_bank_key` +bridges that: the session calls it whenever an F6–F10 press actually resolves, and +:func:`shift_down` latches ``True`` for a short grace window after, so a momentary dip in +the raw signal can't flip the display mid-keystroke. The window is generous enough to +outlast the flicker without noticeably outlasting the actual key release — the lane still +self-corrects within one idle repaint (the 2 s picocalc tick) either way. + Strictly an experiment layered over a working static lane, and built to disappear: it only ever engages when the platform asks for it (``Platform.modifier_watch``), the input device exists, and it is readable (the deploy user is in the ``input`` group on the device) — an ssh @@ -19,6 +29,7 @@ from __future__ import annotations import struct import threading +import time from pathlib import Path from typing import Callable, Optional @@ -37,10 +48,39 @@ _SYS_INPUT = Path("/sys/class/input") _shift_down = False _thread: Optional[threading.Thread] = None +#: How long a resolved F6–F10 keycode keeps :func:`shift_down` latched ``True`` after the +#: raw signal drops — long enough to bridge the MCU's release/re-assert flicker around a +#: chord, short enough that letting Shift go for real still reads as released well within +#: one held keypress. See :func:`note_shift_bank_key`. +_SHIFT_BANK_GRACE_S = 0.6 + +_last_shift_bank_at: Optional[float] = None + def shift_down() -> bool: - """Whether a Shift key is physically held right now (``False`` when not watching).""" - return _shift_down + """Whether a Shift key is physically held right now (``False`` when not watching). + + Also ``True`` for :data:`_SHIFT_BANK_GRACE_S` after the last F6–F10 press resolved + (see :func:`note_shift_bank_key`), bridging a firmware quirk where the raw signal can + dip mid-chord even though Shift never actually came up. + """ + if _shift_down: + return True + return ( + _last_shift_bank_at is not None + and time.monotonic() - _last_shift_bank_at < _SHIFT_BANK_GRACE_S + ) + + +def note_shift_bank_key() -> None: + """Record that an F6–F10 keycode just resolved — proof Shift was physically down. + + The MCU only ever emits these codes while Shift is held, so their arrival is stronger + evidence than the watcher's own raw state (see the module docstring). Call this from + wherever an F-key press resolves against the Shift bank (:meth:`TuiSession._dispatch`). + """ + global _last_shift_bank_at + _last_shift_bank_at = time.monotonic() def _find_keyboard() -> Optional[Path]: diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index beb0065..0555793 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -105,6 +105,12 @@ MESH_THEME = Theme( "heat.cool": "#fb923c", "heat.cold": "#94a3b8", "heat.never": "#64748b", + # The PicoCalc F-key lane's chip fills (see ui.tui.fkeys): gray for the plain + # F1-F5 bank, green while the Shift watcher reports F6-F10. White text on both — + # defined here too so the style names resolve on every platform, even though + # only PicoCalc's footer_fkeys ever asks for them. + "fkey.chip": "bold #ffffff on #475569", + "fkey.chip.shift": "bold #ffffff on #16a34a", } ) @@ -233,6 +239,11 @@ MESH_THEME_16 = Theme( "heat.cool": "color(3)", "heat.cold": "color(7)", "heat.never": "color(8)", + # The F-key lane's chip fills: light-grey background (the palette's only "gray" + # addressable as a background — see _VT_SLOTS) for the plain bank, green for the + # Shift bank, white text on both. + "fkey.chip": "bold color(15) on color(7)", + "fkey.chip.shift": "bold color(15) on color(2)", } ) diff --git a/meshterm/ui/tui/fkeys.py b/meshterm/ui/tui/fkeys.py index 1dc9df0..fab788d 100644 --- a/meshterm/ui/tui/fkeys.py +++ b/meshterm/ui/tui/fkeys.py @@ -1,16 +1,19 @@ -"""The PicoCalc F-key lane: a fixed footer row mapping F1–F5 (and their opposites). +"""The PicoCalc F-key lane: a fixed footer row of five coloured chips, F1-F5. The PicoCalc keyboard has five dedicated function keys; its MCU translates Shift+F1..F5 -into plain F6–F10 keycodes (measured in P0), so "Shift+key = the opposite action" is -literal hardware behaviour and the app simply binds all ten. One footer row teaches both -banks: each slot shows its digit and primary label, and — while the optional modifier -watch reports Shift held — flips to the opposite bank's labels live. +into plain F6-F10 keycodes (measured in P0), so "Shift+key = the opposite action" is +literal hardware behaviour and the app simply binds all ten. By JP's spec +(2026-08-01), the five *plain* keys carry a screen's most-used actions — reachable with +no Shift at all — and the Shift bank (F6-F10) is overflow, consulted only when a screen +has more than five things worth a key. F4 and F5 sit closest to the thumbs and take the +highest-priority pair (e.g. commit/leave); F1/F2 take the next pair; F3 is the one lone, +unpaired slot a screen reaches for when it has a single extra action. A screen describes its lane as five :class:`FPair` slots (``None`` = unassigned); the session resolves a pressed F-key to the slot's action string and dispatches it through the normal action funnel, so screens gain F-key support without any key handling of -their own. The defaults duplicate the nav cluster (which sits on an Fn layer on this -keyboard) plus commit/leave — the pairs that mean something on every screen. +their own. An :class:`FPair` need not carry a Shift-bank action at all — a "lone" slot +(``opp_label=""``) simply renders blank in the shifted bank and F(n+5) does nothing. """ from __future__ import annotations @@ -20,76 +23,100 @@ from typing import Optional, Sequence from rich.text import Text +#: Every chip is exactly this many cells: a 2-cell key label, a space, a 6-cell +#: description. Five chips plus four 2-cell gaps sum to exactly 53 — the PicoCalc's +#: readable width — with nothing left over. +_CHIP_WIDTH = 9 +_DESC_WIDTH = 6 +_GAP = " " + @dataclass(frozen=True, slots=True) class FPair: - """One F-key slot: the primary action (Fn) and its opposite (F(n+5)). + """One F-key slot: the plain-key action and its optional Shift-bank companion. Attributes: - label: Hint text for the primary, ≤7 cells (the lane budgets 5 slots into 53). - action: The screen action the primary dispatches (``"home"``, ``"enter"``, …). - opp_label: Hint text for the opposite bank. - opp_action: The action the opposite dispatches. + label: Verb-phrase hint for the plain key, e.g. ``"Zoom +"`` — what the key + *does* on this screen, never the key's own name (``"PgUp"``). Clipped/padded + to 6 cells. + action: The screen action the plain key dispatches (``"home"``, ``"enter"``, …). + opp_label: Hint for the Shift-bank companion, or ``""`` for a lone slot with no + companion — the shifted bank then renders that chip blank and the + corresponding F(n+5) does nothing. + opp_action: The action the Shift-bank companion dispatches, or ``""``. """ label: str action: str - opp_label: str - opp_action: str + opp_label: str = "" + opp_action: str = "" #: A lane is five slots, F1..F5 left to right; ``None`` leaves a slot unassigned. Lane = Sequence[Optional[FPair]] -#: The screen-agnostic default lane. Top/End and the page pair mirror the nav cluster -#: (Fn-layered on the physical keyboard, so the dedicated F-keys earn their duplicate); -#: F5 commits and its opposite leaves — the one inversion every screen understands. +#: The screen-agnostic default lane, per JP's slot-priority spec: F4/F5 (the most +#: reachable pair) carry commit/leave — the one action every screen needs and needs +#: without Shift; F1/F2 (the next pair) carry the nav cluster's most common half (jump to +#: top/end), with the paging half riding their Shift bank since it is reached for less +#: often; F3 is the lone slot a screen's own :attr:`~meshterm.ui.tui.screen.Screen.fkey_lane` +#: override reaches for first. DEFAULT_LANE: tuple[Optional[FPair], ...] = ( - FPair("Top", "home", "End", "end"), - FPair("PgUp", "pageup", "PgDn", "pagedown"), + FPair("Top", "home", "PgUp", "pageup"), + FPair("End", "end", "PgDn", "pagedown"), None, - None, - FPair("OK", "enter", "Back", "escape"), + FPair("OK", "enter"), + FPair("Back", "escape"), ) def action_for(lane: Lane, number: int) -> Optional[str]: - """The action F-key ``number`` (1–10) resolves to on this lane, or ``None``. + """The action F-key ``number`` (1-10) resolves to on this lane, or ``None``. - F1–F5 take the slot's primary action, F6–F10 its opposite (the physical Shift bank). + F1-F5 take the slot's plain-key action, F6-F10 (the physical Shift bank) take its + companion — or resolve to nothing when the slot has none (a lone slot, or an + unassigned one). """ index = (number - 1) % 5 if index >= len(lane) or lane[index] is None: return None pair = lane[index] - return pair.opp_action if number > 5 else pair.action + if number > 5: + return pair.opp_action or None + return pair.action + + +def _chip(number: int, label: str) -> str: + """The exact 9-cell chip body: ``F1 Zoom +`` (``10`` stands in for ``F10``).""" + key = f"F{number}" if number < 10 else "10" + return f"{key} {label[:_DESC_WIDTH]:<{_DESC_WIDTH}}" def lane_text(lane: Lane, *, shifted: bool = False) -> Text: - """Render the lane as the fixed footer row: ``1 Top 2 PgUp ··· 5 OK``. + """Render the lane as five 9-cell chips: coloured fill, white text, 2-cell gaps. Args: lane: The five slots. - shifted: Show the opposite bank's digits and labels (the modifier watch saw - Shift go down); the static fallback always shows the primary bank. + shifted: Show the Shift-bank chips (F6-F10) in the green fill; the plain bank + (F1-F5) renders in the gray fill. Returns: - A one-line :class:`Text`, ≤53 cells with ≤7-cell labels. + A one-line :class:`Text`, exactly 53 cells: five 9-cell chips and four 2-cell + gaps. """ + fill = "fkey.chip.shift" if shifted else "fkey.chip" row = Text() for index in range(5): + if index: + row.append(_GAP) pair = lane[index] if index < len(lane) else None - if row.plain: - row.append(" ") number = index + 6 if shifted else index + 1 - if pair is None: - row.append(f"{number}", style="track") + label = (pair.opp_label if shifted else pair.label) if pair else "" + if not label: + # Unassigned (no slot, or a lone slot's empty Shift bank): the bare key + # number, unfilled — nothing to press here. + key = f"F{number}" if number < 10 else "10" + row.append(f"{key}{' ' * (_CHIP_WIDTH - len(key))}", style="muted") continue - label = pair.opp_label if shifted else pair.label - # The row's budget is exact at 53: five 9-cell slots and four 2-cell gaps. A - # label is clipped to its slot rather than pushing the lane over — and F10's - # two-digit key costs its own label a cell. - budget = 6 if number >= 10 else 7 - row.append(f"{number}", style="accent") - row.append(f" {label[:budget]}", style="muted") + row.append(_chip(number, label), style=fill) return row diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index 3d838b4..7d99df0 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -63,9 +63,11 @@ class Screen: def fkey_lane(self): """The screen's F-key lane (the PicoCalc footer; see :mod:`~meshterm.ui.tui.fkeys`). - Five slots, F1–F5 with their F6–F10 opposites (the physical Shift bank). The - default duplicates the nav cluster — Fn-layered on the PicoCalc keyboard — plus - commit/leave; a screen with richer verbs overrides this property. + Five slots, F1–F5, each with an optional F6–F10 Shift-bank companion. The + default puts commit/leave on the prime F4/F5 pair (no Shift needed), the nav + cluster's jump-to-top/end on F1/F2 with paging as their Shift companions, and + leaves F3 as the one lone slot — the first a screen with its own verbs reaches + for. A screen with richer needs overrides this property. """ from .fkeys import DEFAULT_LANE diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index ef9f748..cb181bc 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -1389,8 +1389,14 @@ class TuiSession: # normal screen action; an unassigned slot, or a platform without the lane, # drops the press here. if len(action) in (2, 3) and action[0] == "f" and action[1:].isdigit(): + number = int(action[1:]) + if number > 5: + # However this resolves, the code only exists because Shift was + # physically down for the MCU to emit it — latch the lane's shifted + # display against the release/re-assert flicker (see modifier_watch). + modifier_watch.note_shift_bank_key() top = self.top or self._base_screen() - resolved = fkeys.action_for(top.fkey_lane, int(action[1:])) if top else None + resolved = fkeys.action_for(top.fkey_lane, number) if top else None if resolved is None: return action = resolved diff --git a/tests/test_modifier_watch.py b/tests/test_modifier_watch.py new file mode 100644 index 0000000..2eefb7b --- /dev/null +++ b/tests/test_modifier_watch.py @@ -0,0 +1,41 @@ +"""The F-key lane's Shift-state watcher: the raw flag and the shift-bank latch.""" + +from __future__ import annotations + +from meshterm.services import modifier_watch + + +def _reset() -> None: + modifier_watch._shift_down = False + modifier_watch._last_shift_bank_at = None + + +def test_shift_down_reflects_the_raw_flag() -> None: + _reset() + try: + assert modifier_watch.shift_down() is False + modifier_watch._shift_down = True + assert modifier_watch.shift_down() is True + finally: + _reset() + + +def test_shift_bank_key_latches_over_the_release_flicker(monkeypatch) -> None: + """An F6-F10 press keeps the lane's shifted read for a grace window, even if the raw + watcher (wrongly, per the MCU quirk) reports Shift already back up.""" + _reset() + try: + clock = [100.0] + monkeypatch.setattr(modifier_watch.time, "monotonic", lambda: clock[0]) + + assert modifier_watch.shift_down() is False + modifier_watch.note_shift_bank_key() + assert modifier_watch.shift_down() is True # latched, raw flag never went true + + clock[0] += modifier_watch._SHIFT_BANK_GRACE_S - 0.05 + assert modifier_watch.shift_down() is True # still inside the grace window + + clock[0] += 0.1 + assert modifier_watch.shift_down() is False # grace lapsed, Shift really let go + finally: + _reset() diff --git a/tests/test_picocalc_chrome.py b/tests/test_picocalc_chrome.py index ab19c2b..f44c149 100644 --- a/tests/test_picocalc_chrome.py +++ b/tests/test_picocalc_chrome.py @@ -70,21 +70,27 @@ def test_picocalc_header_brands_the_app_not_the_device() -> None: def test_fkey_lane_resolution_and_banks() -> None: lane = DEFAULT_LANE - assert action_for(lane, 1) == "home" and action_for(lane, 6) == "end" - assert action_for(lane, 2) == "pageup" and action_for(lane, 7) == "pagedown" + # F4/F5 (commit/leave) are plain-key only — no Shift companion. + assert action_for(lane, 4) == "enter" and action_for(lane, 9) is None + assert action_for(lane, 5) == "escape" and action_for(lane, 10) is None + # F1/F2 carry the jump-to-top/end pair; paging rides their Shift bank. + assert action_for(lane, 1) == "home" and action_for(lane, 6) == "pageup" + assert action_for(lane, 2) == "end" and action_for(lane, 7) == "pagedown" + # F3 is the lone, unassigned slot a screen's own lane fills in. assert action_for(lane, 3) is None and action_for(lane, 8) is None - assert action_for(lane, 5) == "enter" and action_for(lane, 10) == "escape" def test_fkey_lane_text_fits_and_flips() -> None: primary = lane_text(DEFAULT_LANE) shifted = lane_text(DEFAULT_LANE, shifted=True) - assert cell_len(primary.plain) <= 53 and cell_len(shifted.plain) <= 53 - assert "1 Top" in primary.plain and "5 OK" in primary.plain - assert "6 End" in shifted.plain and "10 Back" in shifted.plain + assert cell_len(primary.plain) == 53 and cell_len(shifted.plain) == 53 + assert "F1 Top" in primary.plain and "F4 OK" in primary.plain and "F5 Back" in primary.plain + assert "F6 PgUp" in shifted.plain and "F7 PgDn" in shifted.plain + # F4/F5 have no Shift companion: their shifted chips (F9/F10) render unfilled. + assert "F9" in shifted.plain and "10" in shifted.plain wide = [FPair("Muchtoolonglabel", "a", "Muchtoolonglabel", "b")] * 5 - assert cell_len(lane_text(wide).plain) <= 53 # clipped to the slot budget - assert cell_len(lane_text(wide, shifted=True).plain) <= 53 + assert cell_len(lane_text(wide).plain) == 53 # clipped to the slot budget + assert cell_len(lane_text(wide, shifted=True).plain) == 53 def test_host_battery_reads_the_sysfs_supply(tmp_path, monkeypatch) -> None: