From d6d49df0a2920b42ae54d636ef1f2c15e23d8f40 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 6 Oct 2026 04:17:05 -0400 Subject: [PATCH] Docstrings and comments of meshterm/ui/tui are in ASD-STE100 The same rewrite as for the core package. A navigation entry is now "a screen on the stack", the visible part of a page is its viewport, and the visible rows of a ListWindow are its list window. Two statements now agree with the theme: the selected chip style is a grey fill. Co-Authored-By: Claude Opus 5.5 (1M context) --- meshterm/ui/tui/__init__.py | 32 +- meshterm/ui/tui/colsnap.py | 338 +++--- meshterm/ui/tui/emoji_width.py | 421 ++++---- meshterm/ui/tui/fastrender.py | 166 +-- meshterm/ui/tui/fkeys.py | 373 +++---- meshterm/ui/tui/frame.py | 739 ++++++------- meshterm/ui/tui/holdquit.py | 158 +-- meshterm/ui/tui/overlay.py | 105 +- meshterm/ui/tui/progress.py | 91 +- meshterm/ui/tui/prompt.py | 528 +++++----- meshterm/ui/tui/render.py | 323 +++--- meshterm/ui/tui/screen.py | 894 ++++++++-------- meshterm/ui/tui/select.py | 1003 +++++++++--------- meshterm/ui/tui/session.py | 1784 +++++++++++++++++--------------- meshterm/ui/tui/spinner.py | 57 +- 15 files changed, 3720 insertions(+), 3292 deletions(-) diff --git a/meshterm/ui/tui/__init__.py b/meshterm/ui/tui/__init__.py index fdd14a9..b283d04 100644 --- a/meshterm/ui/tui/__init__.py +++ b/meshterm/ui/tui/__init__.py @@ -1,22 +1,28 @@ # SPDX-License-Identifier: Apache-2.0 -"""A small, centralized, reusable full-screen text-UI library. +"""A small, central, reusable library for a full-screen text UI. -Built on prompt_toolkit (for the terminal, input, and resize handling) and Rich (for all -content rendering), this package gives the interactive app a consistent, bounded, layered -UI: screens never overflow the terminal, long content scrolls, going deeper stacks dialogs -over a dimmed parent, and Esc always dismisses the current layer. +The package uses prompt_toolkit for the terminal, the input, and the resize events, and +Rich to render all the content. It gives the interactive app a UI that is consistent, +bounded, and in layers: -Navigation is a strict stack: one push per screen entered, one pop per Esc, and the screen -object survives the whole visit so its cursor, sort and filter are still there when a -sub-screen closes (:meth:`~meshterm.ui.tui.session.TuiSession.stay`). The one shortcut past -it is ^W, which unwinds every frame at once by raising +- A screen never becomes larger than the terminal. +- Long content scrolls. +- When the user goes deeper, each dialog is put over its dimmed parent. +- The Esc key always closes the current layer. + +Navigation is a strict stack. Each screen that the user enters is one push, and each Esc is +one pop. The screen object stays for the whole visit. Thus its highlight, its sort, and its +filter are still there when a screen above it closes +(:meth:`~meshterm.ui.tui.session.TuiSession.stay`). The only shortcut past the stack is ^W. +It unwinds all the screens on the stack at one time, because it raises :class:`~meshterm.ui.tui.screen.PopToMenu` through them. Public API: - - :class:`~meshterm.ui.tui.session.TuiSession` — the running session and prompt helpers. - - :class:`~meshterm.ui.tui.select.Choice` / :class:`~meshterm.ui.tui.select.Separator` - — items for ``session.select``. - - Screen classes for advanced/custom layers. + - :class:`~meshterm.ui.tui.session.TuiSession`: the running session and the prompt + helpers. + - :class:`~meshterm.ui.tui.select.Choice` / :class:`~meshterm.ui.tui.select.Separator`: + the items for ``session.select``. + - The screen classes, for advanced or custom layers. """ from __future__ import annotations diff --git a/meshterm/ui/tui/colsnap.py b/meshterm/ui/tui/colsnap.py index 9217281..51bbc42 100644 --- a/meshterm/ui/tui/colsnap.py +++ b/meshterm/ui/tui/colsnap.py @@ -1,83 +1,90 @@ # SPDX-License-Identifier: Apache-2.0 -"""Pin a written row's columns to the terminal's own grid, so no glyph can shift it. +"""Pin the columns of a written row to the grid of the terminal, so that no glyph can shift it. -:mod:`~meshterm.ui.tui.emoji_width` answers *how many cells does this glyph take*. This -module answers the question that actually decides whether a row lines up: **which column does -the next glyph land in?** +:mod:`~meshterm.ui.tui.emoji_width` answers the question "how many cells does this glyph +use?". This module answers the question that decides if a row is aligned: **in which column +does the next glyph start?** -A row reaches the terminal as one run of characters, and the terminal advances its own cursor -by its own idea of each glyph's width. Where that idea differs from ours by a cell, -*everything after that glyph* is drawn a column out — the lanes to its right shift, the values -under a heading stop being under it, and the panel's right border notches in one short of the -frame. One emoji in one node's name, and the row it sits on is the only row in the list that -does not line up. +A row goes to the terminal as one sequence of characters. The terminal moves its own cursor +forward by the width that it thinks each glyph has. If that width is different from our width +by one cell, all the text after that glyph is drawn one column out of position. The lanes to +its right shift, the values under a heading are no longer under it, and the right border of +the panel moves in, one cell short of the edge of the frame. Thus one emoji in the name of one +node makes its row the only row in the list that is not aligned. -**That disagreement cannot be measured away**, which is the part worth being plain about. -Whether a font draws a given emoji in one cell or two is the font's business rather than the -codepoint's; there is no table that is right on every terminal; and no escape sequence reports -a renderer's width back to the program, because on a split terminal the component that tracks -the cursor and the component that paints the glyph are different programs that disagree with -each other (a cursor probe reads the PTY, not the painter). Curating exceptions one confirmed -glyph at a time — which is what the app used to do — lines up the rows somebody has already -looked at, and leaves every name that arrives off the air, written by a stranger and carrying -whatever they felt like typing, exactly as broken as it was. A contact list is the worst case -in the app for precisely that reason: its content is the one thing on screen that nobody can -put on a list in advance. +**A measurement cannot remove that difference**, and it is important to say this clearly. The +font decides if it draws a given emoji in one cell or in two cells. The code point does not +decide it. No table is correct on all terminals. Also, no escape sequence tells the program +the width that the renderer used. On a split terminal, the component that tracks the cursor +and the component that draws the glyph are different programs, and they do not agree with +each other (a cursor probe reads the PTY, not the component that draws). The app once kept a +list of exceptions, and added to it one confirmed glyph at a time. That method aligned the +rows that a person had already examined. But each name that arrives over the radio stayed as +broken as before, because a stranger wrote it, with any characters that they wanted to type. +For this reason, a contact list is the worst case in the app: its content is the only thing +on the screen that nobody can put on a list before it arrives. -So this module stops asking the terminal to agree. After any glyph whose drawn width is not -certain, the row carries an **absolute column address** — ``CSI n G``, naming the one-based -column the app measured that glyph into — so the terminal's answer to *where am I* is replaced -with ours before the next glyph is drawn. The cursor is re-pinned to the app's own grid at -every point where a disagreement could have started, and a mismeasured glyph can no longer -move anything but itself: +Thus this module does not ask the terminal to agree. After each glyph whose drawn width is not +certain, the row has an **absolute column address**. This address is ``CSI n G``, and it names +the one-based column that the app measured for that glyph. Thus our answer to the question +"where am I?" replaces the answer of the terminal before the next glyph is drawn. The cursor +gets a new pin to the grid of the app at each point where a difference could start. Thus a +glyph with an incorrect measurement can move only itself: -* Drawn **narrower** than we reserved, it leaves a blank cell after it. The cells a glyph is - reserved are erased in its own colours before it is drawn (``CSI n X``), so that cell is - blank in the right background: never a character left over from the last frame, and never a - hole in the fill of a chip. -* Drawn **wider**, its overhang is written over by whatever the next column holds. +* If the glyph is drawn **narrower** than the cells that we reserved, it leaves a blank cell + after it. Before the glyph is drawn, its reserved cells are erased in its own colours + (``CSI n X``). Thus that cell is blank, with the correct background. It never shows a + character from the last frame, and it never makes a hole in the fill of a chip. +* If the glyph is drawn **wider**, the content of the next column is written over the part + of the glyph that extends past its cells. -Both are one cell of cosmetic damage inside the glyph's own lane, where a shift was a whole row -of it, and the second never happens in practice: :mod:`~meshterm.ui.tui.emoji_width` reserves -every glyph that may be drawn as an emoji two cells, the most a single glyph draws. Pinning holds -the lanes after a glyph wherever the terminal puts it; the reservation is what makes the text -beside it line up from row to row as well, since a pin can only land where the glyph was measured. +In both cases, the damage is one cell, only cosmetic, and in the lane of the glyph. A shift +damaged a full row. The second case does not occur in practice: +:mod:`~meshterm.ui.tui.emoji_width` reserves two cells for each glyph that a terminal may draw +as an emoji, and two cells is the maximum for one glyph. The pin keeps the lanes after a glyph +in position, at any width that the terminal gives to the glyph. The reservation also keeps the +text next to the glyph aligned from row to row, because a pin can only go to the column where +the glyph was measured. -**What is certain.** Pinning after a glyph that did not need it is harmless (it addresses the -column the cursor is already in) but it is not free: five bytes on the wire and a cluster walk -in Python, and MeshTerm draws some non-ASCII glyphs by the thousand — a map is a canvas of -braille, every frame is box drawing, a path ribbon is half blocks and chevrons. So -:data:`_TEXT_GLYPHS` lists the ranges this app draws in bulk whose one-cell *text* width both -authorities already agree on, and :func:`snap_row` pins after everything else. A row holding -nothing outside that list is handed back untouched, which is nearly every row of nearly every -screen; the walk is paid only where an emoji actually is. +**What is certain.** A pin after a glyph that did not need it does no damage, because it +addresses the column that the cursor is already in. But it has a cost: five bytes on the +wire, and a walk through the clusters in Python. MeshTerm draws some non-ASCII glyphs in +thousands: a map is a canvas of braille, each frame has box drawing, and a path ribbon is half +blocks and chevrons. Thus :data:`_TEXT_GLYPHS` lists the ranges that this app draws in large +quantities and for which the two authorities already agree on a one-cell text width. +:func:`snap_row` pins after all other glyphs. A row that has nothing outside that list is +returned unchanged, and that is almost each row of almost each screen. Thus the cost of the +walk occurs only where an emoji is. -Getting an entry in that list wrong costs exactly what today costs anyway — one glyph's row — -so the list is a performance claim and never the thing correctness rests on. That is the whole -point of the inversion: the exception sets this replaced had to be *complete* to keep the app -aligned, and this one only has to be *cheap*. +If an entry in that list is wrong, the cost is the same cost that the app had before: the row +of that one glyph. Thus the list is a claim about performance, and correct alignment never +depends on it. This is the purpose of the inversion. The exception sets that this module +replaced had to be complete to keep the app aligned. This list must only be cheap. -**Two writers, two spellings of the same pin.** A frame reaches the terminal one of two ways, -and each knows something different about where its cursor is: +**Two writers, two forms of the same pin.** A frame goes to the terminal in one of two ways, +and each way knows a different thing about the position of its cursor: -* :mod:`~meshterm.ui.tui.fastrender` writes a plain full-screen frame itself, each changed row - as one run from column 0. It knows every column absolutely, so :func:`snap_row` spells the - pin as an absolute address, ``CSI n G``. -* Anything prompt_toolkit lays out — a floating dialog, and the backdrop it repaints — goes out - through its differential renderer, which never knows a column absolutely: it steps a cursor - of its own by relative moves and adds each character's measured width as it writes. So - :class:`PinnedOutput` spells the pin *relative to the glyph itself* — save the cursor, draw - the glyph, restore, step forward exactly the width the renderer is about to add. The - terminal's cursor then lands where the renderer's arithmetic says it is, after every glyph, - and a relative move computed from that arithmetic is a correct move. Nothing is tracked, so - nothing can drift out of step with the renderer's own bookkeeping. +* :mod:`~meshterm.ui.tui.fastrender` writes a plain full-screen frame itself. It writes each + changed row as one sequence from column 0. It knows the absolute position of each column, + thus :func:`snap_row` writes the pin as an absolute address, ``CSI n G``. +* All that prompt_toolkit lays out (a floating dialog, and the backdrop that it draws again) + goes out through its differential renderer. That renderer never knows the absolute + position of a column. It moves a cursor of its own with relative moves, and it adds the + measured width of each character when it writes the character. Thus :class:`PinnedOutput` + writes the pin relative to the glyph itself: save the cursor, draw the glyph, restore the + cursor, and then move forward by exactly the width that the renderer will add. After each + glyph, the cursor of the terminal then goes to the position that the arithmetic of the + renderer gives. Thus a relative move that comes from that arithmetic is a correct move. + Nothing is tracked, thus nothing can go out of step with the count that the renderer + keeps. -A platform that never draws a glyph outside its own font has nothing to pin, and pins nothing: -the PicoCalc folds every emoji away before it reaches the console, and every glyph it does draw -is one :mod:`~meshterm.ui.fontset` has verified on the device. +A platform that never draws a glyph outside its own font has nothing to pin, and it pins +nothing. The PicoCalc folds each emoji away before the emoji gets to the console. Each glyph +that the PicoCalc draws is a glyph that :mod:`~meshterm.ui.fontset` checked on the handheld. -The escape hatch is ``MESHTERM_COLUMN_SNAP=0``: this is terminal geometry, read once at session -build, not a choice anybody makes about how the app behaves. +To turn the pins off, set ``MESHTERM_COLUMN_SNAP=0``. This value is about the geometry of the +terminal, and MeshTerm reads it one time, when it builds the session. It is not a choice about +the behaviour of the app. """ from __future__ import annotations @@ -93,111 +100,123 @@ from rich.cells import cell_len from ...platforms import get_platform from .emoji_width import clusters -#: The glyph ranges MeshTerm draws in bulk whose single-cell width both width authorities -#: already agree on, so a row made only of them needs no pinning at all. Each entry is an -#: inclusive ``(first, last)`` pair; a single glyph names itself twice. +#: The glyph ranges that MeshTerm draws in large quantities, and for which the two width +#: authorities already agree on a width of one cell. Thus a row that has only these glyphs +#: gets no pin. Each entry is an inclusive ``(first, last)`` pair. A single glyph gives its +#: own value two times. #: -#: These are *text* glyphs — outside Emoji_Presentation, carrying no variation selector — which -#: is the class the emoji-width module's hardest-won lesson is about: ``U+1F6E3`` and -#: ``U+1F578`` measure one cell by both authorities because the font draws them as one-cell -#: text, and forcing either to two pulled a row's border in. Everything else non-ASCII — every -#: pictograph, every flag, every joined sequence, every fullwidth character, and anything nobody -#: has ever looked at — falls outside this list and gets pinned. +#: These are text glyphs: they are outside Emoji_Presentation, and they have no variation +#: selector. The most difficult lesson of the emoji-width module is about this class. +#: ``U+1F6E3`` and ``U+1F578`` measure one cell for the two authorities, because the font +#: draws them as one-cell text. When the app forced one of them to two cells, the border of +#: its row moved in. All the other non-ASCII glyphs are outside this list and get a pin: each +#: pictograph, each flag, each joined sequence, each fullwidth character, and each glyph that +#: nobody has examined. _TEXT_GLYPHS: tuple[tuple[str, str], ...] = ( - ("\x00", "\x7f"), # ASCII: every letter, digit and escape byte in a composed row + ("\x00", "\x7f"), # ASCII: each letter, digit, and escape byte in a composed row (" ", "ſ"), # Latin-1 + Latin Extended-A: an accented name, °, ·, ± ("‐", "‧"), # General Punctuation: – — ‘ ’ “ ” • … - ("←", "↓"), # ← ↑ → ↓, the arrow atoms every footer hint leads with - ("─", "╿"), # Box Drawing: every panel border and every rule - ("▀", "▟"), # Block Elements: the path line's half blocks, the splash art + ("←", "↓"), # ← ↑ → ↓: the arrow atoms at the start of each footer hint + ("─", "╿"), # Box Drawing: each panel border and each rule + ("▀", "▟"), # Block Elements: the half blocks of the path line, and the splash art ("■", "■"), # ■ room server ("▲", "▲"), # ▲ repeater - ("▸", "▸"), # ▸ a row's own marker + ("▸", "▸"), # ▸ the marker of a row ("◉", "◉"), # ◉ sensor - ("○", "●"), # ○ unknown through ● node, and the rings between them + ("○", "●"), # from ○ unknown to ● node, and the rings between them ("★", "★"), # ★ you ("✓", "✓"), # ✓ ok ("✗", "✗"), # ✗ err - ("❯", "❯"), # ❯ the cursor - ("⠀", "⣿"), # Braille: every chart, and the whole map canvas - ("", ""), # the powerline chevrons a path ribbon's seams are drawn from + ("❯", "❯"), # ❯ the glyph that points to the highlight + ("⠀", "⣿"), # Braille: each chart, and all of the map canvas + ("", ""), # the powerline chevrons that make the seams of a path ribbon ) -#: Matches the first glyph in a row that is *not* one of :data:`_TEXT_GLYPHS` — the probe that -#: decides whether a row needs walking at all. A negated class of the ranges above, so the test -#: is one C-speed scan of the row instead of a Python loop over its cells. +#: Matches the first glyph in a row that is not in :data:`_TEXT_GLYPHS`. This test decides if a +#: walk through the row is necessary. It is a negated class of the ranges above. Thus the test +#: is one scan of the row at C speed, instead of a Python loop over its cells. _UNPINNED = re.compile("[^" + "".join(f"{low}-{high}" for low, high in _TEXT_GLYPHS) + "]") -#: One escape sequence: a CSI (which is everything a composed row actually carries — the -#: theme's SGR colour runs), an OSC string, or a bare two-character escape. Matched so it can -#: be copied through *without* advancing the column: a style change occupies no cell, and -#: counting one would pin every glyph after it to the wrong column. +#: One escape sequence: a CSI, an OSC string, or a bare two-character escape. A composed row +#: has only CSI sequences (the SGR colour runs of the theme). The pattern matches an escape +#: sequence so that the walk can copy it without a move to the next column. A style change +#: uses no cell. If the walk counts it, each glyph after it gets a pin to the wrong column. _ESCAPE = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?|[@-Z\\-_])") -#: Pinned rows, keyed by the row as composed. Scrolling a list rewrites the same few rows over -#: and over — the highlighted one, and the one the highlight just left — so the walk is paid -#: once per distinct row rather than once per paint. +#: The pinned rows, with the composed row as the ``dict`` key. When a list scrolls, the same +#: few rows are written again many times: the row of the highlight, and the row that the +#: highlight left. Thus the walk occurs one time for each different row, instead of one time +#: for each paint. _CACHE: OrderedDict[str, str] = OrderedDict() -#: Rows the cache holds before evicting the least recently used. +#: The number of rows that the cache holds. After that number, the cache removes the least +#: recently used row. _CACHE_MAX = 1024 -#: DECSC and DECRC: save the cursor, and return to it. What :class:`PinnedOutput` brackets a -#: glyph with, so the step after it is measured from where the glyph *started* rather than from -#: wherever the terminal's own width table left the cursor. Both also save and restore the -#: current colour, which is harmless here: nothing changes it between the two. +#: DECSC and DECRC: save the cursor, and go back to it. :class:`PinnedOutput` puts these two +#: sequences before and after a glyph. Thus the step after the glyph is measured from the +#: start of the glyph, instead of from the position where the width table of the terminal put +#: the cursor. The two sequences also save and restore the current colour. This does no damage +#: here, because nothing changes the colour between the two sequences. _SAVE = "\x1b7" _RESTORE = "\x1b8" def _erase(width: int) -> str: - """ECH: blank ``width`` cells from the cursor in the current colours, without moving it. + """ECH: blank ``width`` cells at the cursor, in the current colours, with no cursor move. - Written in front of a glyph reserved more than one cell, so every cell of its reservation is - painted by this frame whatever the font does with the glyph: the background a chip or a - highlighted row filled it with, rather than whatever the terminal last held there. + MeshTerm writes this sequence before a glyph that has more than one reserved cell. Thus + this frame draws each reserved cell, whatever the font does with the glyph. Each cell gets + the background that a chip or a highlighted row gave it, instead of the last content of + the terminal at that position. """ return f"\x1b[{width}X" def enabled() -> bool: - """Whether written glyphs are pinned to the columns the app measured them into. + """Whether the app pins the written glyphs to the columns that it measured for them. - On wherever the platform draws emoji, with ``MESHTERM_COLUMN_SNAP=0`` to turn it off for one - run — the escape hatch a terminal that mishandles the pins would need, and the switch that - shows what the alignment looks like without them. Off on a platform that draws no emoji at - all, where every glyph is one the platform's own font has already verified. Read at session - build, like its neighbours. + The pins are on wherever the platform draws emoji. Set ``MESHTERM_COLUMN_SNAP=0`` to turn + them off for one run. A terminal that handles the pins incorrectly must have this way out. + This value also shows how the alignment looks without the pins. The pins are off on a + platform that draws no emoji, because there each glyph is in the platform's own font, and + that font is already checked. The value is read when MeshTerm builds the session, the same + as the values of its neighbours. """ return os.environ.get("MESHTERM_COLUMN_SNAP") != "0" and get_platform().emoji def _pinned(cluster: str) -> bool: - """Whether ``cluster`` needs an absolute column address written after it. + """Whether ``cluster`` must have an absolute column address after it. - True for anything the app cannot be sure the terminal draws at the width it measured: every - multi-codepoint glyph (a flag, a joined sequence, an emoji carrying a variation selector or - a skin tone — the forms :func:`~meshterm.ui.tui.emoji_width.clusters` gathers), and every - lone codepoint outside :data:`_TEXT_GLYPHS`. + True for each glyph when the app is not sure that the terminal draws it at the measured + width: + + - each glyph with more than one code point: a flag, a joined sequence, or an emoji with a + variation selector or a skin tone. :func:`~meshterm.ui.tui.emoji_width.clusters` + collects these forms. + - each lone code point outside :data:`_TEXT_GLYPHS`. """ return len(cluster) > 1 or bool(_UNPINNED.match(cluster)) def snap_row(row: str) -> str: - """``row`` with an absolute column address after every glyph that could be mismeasured. + """``row`` with an absolute column address after each glyph that can have a wrong width. - The row is taken to start in **column 0**, which is what - :mod:`~meshterm.ui.tui.fastrender` guarantees: it addresses the row, then writes it whole. + The function assumes that the row starts in **column 0**. + :mod:`~meshterm.ui.tui.fastrender` makes sure of this: it addresses the row, then writes + all of it. - A row holding only :data:`_TEXT_GLYPHS` comes back unchanged and untouched — one scan, no - walk, no allocation — because that is nearly every row the app draws. + A row that has only :data:`_TEXT_GLYPHS` is returned as it is, with no change: one scan, + no walk, and no allocation. The reason is that almost each row that the app draws is such + a row. Args: - row: One composed terminal row: text with the theme's escape sequences in it, already - sliced to the terminal's width. + row: One composed terminal row. It is text with the escape sequences of the theme in + it, and it is already cut to the width of the terminal. Returns: - The row, with ``CSI n G`` inserted wherever the cursor has to be re-pinned. + The row, with ``CSI n G`` at each position where the cursor must get a new pin. """ if _UNPINNED.search(row) is None: return row @@ -213,15 +232,16 @@ def snap_row(row: str) -> str: def _snapped(row: str) -> str: - """Walk ``row`` glyph by glyph, tracking the column, and pin where :func:`_pinned` says. + """Walk ``row`` glyph by glyph, track the column, and pin where :func:`_pinned` says. - The address is written **lazily** — held over until something drawable actually follows it — - so a row that ends on an emoji (a chat line, very often) pays nothing for an address nothing - would have used, and a style change between two glyphs stays where the theme put it. + The address is written **lazily**: the walk holds it until a glyph that it can draw + follows it. Thus a row that ends with an emoji (often a chat line) has no cost for an + address that nothing uses. Also, a style change between two glyphs stays where the + theme put it. """ parts: list[str] = [] column = 0 - owed = -1 # the column a held-over address names, or -1 when none is owed + owed = -1 # the column that a held address names, or -1 when no address is owed position = 0 for escape in _ESCAPE.finditer(row): column, owed = _pin_text(row[position : escape.start()], parts, column, owed) @@ -232,16 +252,18 @@ def _snapped(row: str) -> str: def _pin_text(text: str, parts: list[str], column: int, owed: int) -> tuple[int, int]: - """Append one escape-free stretch of ``text`` to ``parts``, pinned glyph by glyph. + """Append one part of ``text`` that has no escape sequence to ``parts``, with pins. + + The pins are added glyph by glyph. Args: - text: The stretch to append, with no escape sequence in it. - parts: The row being built, appended to in place. - column: The column this stretch starts in. - owed: The column a held-over address names, or ``-1`` for none. + text: The part to append. It has no escape sequence in it. + parts: The row that the walk builds. This function appends to it in place. + column: The column in which this part starts. + owed: The column that a held address names, or ``-1`` for none. Returns: - The column the stretch ends in, and the address it ends owing. + The column in which the part ends, and the address that it still owes at its end. """ for cluster in clusters(text): if owed >= 0: @@ -259,12 +281,12 @@ def _pin_text(text: str, parts: list[str], column: int, owed: int) -> tuple[int, def _lone_pinned_glyph(data: str) -> bool: - """Whether ``data`` is exactly one glyph, and one :func:`_pinned` says needs pinning. + """Whether ``data`` is exactly one glyph, and a glyph that :func:`_pinned` says to pin. - What prompt_toolkit's renderer writes is one screen cell's content at a time — a character, - or a whole sequence it was handed as one (see - :class:`~meshterm.ui.tui.emoji_width.ClusterTextControl`) — so that is the only shape pinned. - Anything longer is not a cell, and passes through as it came. + The renderer of prompt_toolkit writes the content of one screen cell at a time: a + character, or a full sequence that it got as one item (refer to + :class:`~meshterm.ui.tui.emoji_width.ClusterTextControl`). Thus that shape is the only + shape that gets a pin. Longer data is not a cell, and it goes through with no change. """ if len(data) == 1: return bool(_UNPINNED.match(data)) @@ -274,19 +296,20 @@ def _lone_pinned_glyph(data: str) -> bool: class PinnedOutput: - """A prompt_toolkit ``Output`` proxy that pins every uncertain glyph it is asked to write. + """A prompt_toolkit ``Output`` proxy that pins each uncertain glyph that it must write. - prompt_toolkit's renderer writes a screen cell with ``write`` and then adds that cell's - measured width to a cursor it keeps for itself; every later move on the row is computed - from that cursor, relatively. Where the terminal draws the glyph at another width, the two - cursors part company and every move after it lands a column out. This proxy closes the gap - at the one moment it opens: a glyph :func:`_pinned` cannot vouch for is written between a - cursor save and a restore, and followed by a forward step of exactly the width the renderer - is about to add — so the terminal's cursor is back in step before the renderer's next move. + The renderer of prompt_toolkit writes a screen cell with ``write``. Then it adds the + measured width of that cell to a cursor that it keeps for itself. Each later move on the + row is a relative move from that cursor. If the terminal draws the glyph at a different + width, the two cursors separate, and each move after that glyph goes one column out of + position. This proxy closes the gap at the moment when the gap opens. It writes each glyph + that :func:`_pinned` cannot guarantee between a save and a restore of the cursor. Then it + adds a forward step of exactly the width that the renderer will add. Thus the cursor of + the terminal is in step again before the next move of the renderer. - Everything else — ``write_raw``, the cursor moves, the size, the attributes — forwards to the - wrapped output untouched, and so does ``write`` for anything that is not a lone uncertain - glyph, which is almost every call it gets. + All the other calls go to the wrapped output with no change: ``write_raw``, the cursor + moves, the size, and the attributes. ``write`` also goes through with no change when its + data is not a lone uncertain glyph, and that is almost each call that it gets. """ def __init__(self, inner: Any) -> None: @@ -294,23 +317,24 @@ class PinnedOutput: self._inner = inner def write(self, data: str) -> None: - """Write ``data``, pinning the cursor after it when it is a glyph worth pinning.""" + """Write ``data``. If it is a glyph that must get a pin, pin the cursor after it.""" inner = self._inner if data.isascii() or not _lone_pinned_glyph(data): inner.write(data) return width = get_cwidth(data) - # The renderer skips the cells after a wide glyph as the glyph's own and never writes - # them, so erasing them first is what keeps a glyph drawn narrower from leaving the - # last frame's character in the cell it did not cover. + # The renderer thinks that the cells after a wide glyph are part of the glyph, and it + # never writes them. Thus this code erases them first. Then a glyph that is drawn + # narrower does not leave the character of the last frame in the cell that it did not + # cover. inner.write_raw(_SAVE + _erase(width) if width > 1 else _SAVE) inner.write(data) - # A forward step of zero is read as a step of one, so a glyph that measures nothing - # (a stranded joiner) just returns to where it started. + # The terminal reads a forward step of zero as a step of one. Thus, after a glyph that + # has a width of zero (a stranded joiner), the cursor only goes back to its start. inner.write_raw(f"{_RESTORE}\x1b[{width}C" if width else _RESTORE) def __getattr__(self, name: str) -> Any: - """Forward every other attribute and method straight to the wrapped output.""" + """Forward each other attribute and method directly to the wrapped output.""" return getattr(self._inner, name) diff --git a/meshterm/ui/tui/emoji_width.py b/meshterm/ui/tui/emoji_width.py index 540904f..33cfb01 100644 --- a/meshterm/ui/tui/emoji_width.py +++ b/meshterm/ui/tui/emoji_width.py @@ -1,72 +1,81 @@ # SPDX-License-Identifier: Apache-2.0 -"""How wide a glyph is: one rule everywhere, and two cells wherever nobody can know. +"""The width of a glyph: one rule in all places, and two cells where nobody can know. -Emoji column width is not standardized, and it cannot be discovered. Whether a terminal draws a -given emoji in one cell or two is decided by its font, glyph by glyph, with no rule behind the -split: the same terminal draws ``👋`` in one cell and ``📡`` in two, ``☀️`` in one and ``🛩️`` in -two. No escape sequence reports a renderer's width back to the program, and a cursor probe does -not help: on a split terminal (VS Code, Windows Terminal) the component that tracks the cursor and -the component that paints the glyph are different programs that disagree with each other, and a -probe can only ask the first. +The width of an emoji in cells is not standardized, and a program cannot find it. The font of a +terminal decides if the terminal draws an emoji in one cell or in two. The font decides for each +glyph, and no rule is behind the split. Thus the same terminal draws ``👋`` in one cell and +``📡`` in two,``☀️`` in one and ``🛩️`` in two. No escape +sequence reports the width of a renderer back to the program. A cursor probe does not help +either. On a split terminal (VS Code, Windows Terminal), the component that tracks the cursor +and the component that paints the glyph are different programs that do not agree with each +other, and a probe can only ask the first. -This module used to answer that with a probe and two hand-curated exception sets — glyphs -confirmed, one at a time, to be drawn narrower or wider than the tables said. That lined up every -row somebody had already looked at and none of the rows nobody had, and a contact's name arrives -off the air, written by a stranger, carrying whatever they typed. The sets were retired for that -reason, along with the probe that decided when to apply them. +This module once answered that problem with a probe and two exception sets, curated by hand: +glyphs that somebody confirmed, one at a time, that the terminal drew narrower or wider than the +tables said. That lined up each row that somebody had already examined, and none of the rows that +nobody had examined. But the name of a contact comes over the radio, written by a stranger, and +it has whatever the stranger typed. For that reason we retired the sets, and also the probe that +decided when to apply them. -**What replaced them is two halves, and neither needs to know what the font does.** +**Two halves replaced them. Neither half has to know what the font does.** -* **Placement** belongs to :mod:`~meshterm.ui.tui.colsnap`: every glyph whose drawn width is - uncertain is written with its column pinned, so whatever width the terminal gives it, the - glyphs after it land in the columns the app measured. -* **Measurement** belongs here: every glyph that *may* be drawn as an emoji is reserved **two - cells**, the most a single glyph ever draws. Pinned into two cells, a glyph the font draws in two - fills them exactly, and one it draws in one leaves a blank beside it — never an overwrite, never - a shift. That is what lines up the text *after* an emoji from row to row, which pinning alone - cannot do: it pins to the measured column, and the measurement was the thing that varied. +* **Placement** belongs to :mod:`~meshterm.ui.tui.colsnap`. Each glyph whose drawn width is not + certain is written with its column pinned. Thus, whatever width the terminal gives it, the + glyphs after it go to the columns that the app measured. +* **Measurement** belongs here. Each glyph that may be drawn as an emoji is reserved **two + cells**, the maximum that one glyph ever draws. When the glyph is pinned into two cells, a glyph + that the font draws in two cells fills them exactly. A glyph that the font draws in one cell + leaves a blank next to it: never an overwrite, never a shift. This is what lines up the text + after an emoji from row to row. The pin alone cannot do that, because it pins to the measured + column, and the measurement was the thing that changed. -**"May be drawn as an emoji"** is read off Unicode, never off a font: +**"May be drawn as an emoji"** comes from Unicode, never from a font: * A glyph built from several codepoints: a variation-selector sequence (``☀️``), a ZWJ sequence (``👨‍👩‍👧``), a keycap (``1️⃣``), a flag's pair of Regional Indicators (``🇨🇦``). -* A lone codepoint Unicode marks as an emoji with *text* presentation by default (``☀``, ``✈``, - ``❤``) — the set a variation selector promotes to two, which Rich ships as ``narrow_to_wide`` — - and a lone Regional Indicator. A font draws either kind either way. -* An emoji whose default presentation is already emoji (``📡``, ``👋``) measures two in both - width authorities as it stands, and is left to them. +* A lone codepoint that Unicode marks as an emoji with text presentation by default (``☀``, + ``✈``, ``❤``). This is the set that a variation selector promotes to two cells, which Rich + ships as ``narrow_to_wide``. Also a lone Regional Indicator. A font can draw each of these two + kinds at one cell or at two. +* An emoji whose default presentation is already emoji (``📡``, ``👋``) measures two cells in + both width authorities without a change. This module leaves it to them. -**Two exceptions, both measured at their one cell.** Rich's own single-cell ranges (``©``, ``▶``, -box drawing) are measured by a fast path that never consults a patch, so everything else has to -agree with it. And :data:`_APP_TEXT_MARKS` is the handful of text-default emoji MeshTerm draws -*itself*, as one-cell marks in its own lexicon (``⚠``, ``↕``, ``🗑``). Those are a closed -vocabulary, not content: every glyph in the list is drawn by the app, the app is what checks them -(``meshterm specimen``), and a test holds every such glyph in the source to the list. +**Two exceptions, both measured at their one cell.** A fast path measures the single-cell ranges +of Rich itself (``©``, ``▶``, box drawing), and that path never examines a patch. Thus all the +other parts must agree with it. Also, :data:`_APP_TEXT_MARKS` is the small set of text-default +emoji that MeshTerm draws itself, as one-cell marks in its own lexicon (``⚠``, ``↕``, ``🗑``). +These marks are a closed vocabulary, not content. The app draws each glyph in the list, the app +checks them (``meshterm specimen``), and a test makes sure that each such glyph in the source is +in the list. -**One rule, every authority.** Rich measures in three places — a whole string, a single character, -and the grapheme spans it crops and wraps by — and prompt_toolkit in a fourth. :func:`install` -patches all four from the same rule (:func:`_glyph_width`) at once, and they must never differ: -Rich's segment splitter walks a string a codepoint at a time until a whole-string width meets the -cut it was asked for, and a character measured one inside a string measured two is a cut that walk -never meets. +**One rule, all authorities.** Rich measures in three places: a whole string, a single character, +and the grapheme spans by which it crops and wraps. prompt_toolkit measures in a fourth place. +:func:`install` patches all four from the same rule (:func:`_glyph_width`) at the same time, and +they must never be different. The segment splitter of Rich walks a string one codepoint at a +time, until a whole-string width meets the cut that the caller asked for. If a character measures +one cell alone but two cells in a string, the walk never meets that cut. -**Delivery.** prompt_toolkit lays out one codepoint at a time, and folds a zero-width codepoint into -the cell before it while keeping that cell's place, so a mark measured one and followed by a -selector would become a two-cell glyph in a one-cell slot. :class:`ClusterTextControl` hands every -multi-codepoint glyph to it as a single fragment instead, laid out and written as the one glyph it -is. +**Delivery.** prompt_toolkit lays out one codepoint at a time. It folds a zero-width codepoint +into the cell before it, but it keeps the place of that cell. Thus a mark measured at one cell and +followed by a selector becomes a two-cell glyph in a one-cell slot. Instead, +:class:`ClusterTextControl` gives each multi-codepoint glyph to prompt_toolkit as a single +fragment, which is laid out and written as the one glyph that it is. -**Where it applies.** :func:`install` runs once, when the full-screen app starts on a platform that -draws emoji, before its first frame. Nothing else installs it. Tests, piped output and the command -line keep the stock tables, because nothing pins their output: a glyph reserved two cells and drawn -in one, with no pin after it, pulls the rest of its row a column in. +**Where it applies.** :func:`install` runs one time, before the first frame, when the full-screen +app starts on a platform that draws emoji. Nothing else installs it. Tests, piped output, and the +command line keep the stock tables, because nothing pins their output. There, a glyph that is +reserved two cells but drawn in one, with no pin after it, pulls the rest of its row one cell to +the left. -Two jobs beside the measuring belong here, because they are the same question asked of the same -glyphs. **Where a string may be cut** (:func:`cut_cells`, over :func:`clusters`): a lane that -truncates a name a codepoint at a time cuts through the middle of a glyph, and the pieces that -leaves — a stranded joiner, half a flag — are nothing a terminal draws as measured. And **what may -be drawn at all** (:func:`drawable`): an advert name is written by a stranger and can carry a -newline or an escape, which no width can make safe. +Two more jobs belong here, next to the measurement, because they ask the same question of the +same glyphs: + +* **Where a string can be cut** (:func:`cut_cells`, over :func:`clusters`). A lane that truncates + a name one codepoint at a time cuts through the middle of a glyph. The pieces that this cut + leaves (a stranded joiner, half a flag) are not things that a terminal draws at the measured + width. +* **What can be drawn at all** (:func:`drawable`). A stranger writes the name in an advert, and + the name can have a newline or an escape in it. No width can make these characters safe. """ from __future__ import annotations @@ -79,7 +88,7 @@ from functools import lru_cache from prompt_toolkit.layout.controls import FormattedTextControl from rich.cells import cell_len -#: The zero-width joiner: the tell that the codepoints it sits between are **one glyph** +#: The zero-width joiner: the sign that the codepoints on each side of it are **one glyph** #: (``🤷‍♂️``, ``👨‍👩‍👧``), which a terminal draws in the width of the sequence's base. _ZWJ = "\u200d" @@ -90,32 +99,34 @@ _VS16 = "\ufe0f" #: between them) into one keycap glyph: ``1️⃣``. _KEYCAP = "\u20e3" -#: The five Fitzpatrick skin-tone modifiers (U+1F3FB–U+1F3FF). One following an emoji base -#: *recolours* that glyph rather than drawing one of its own — ``👍🏽`` is a thumb, not a thumb -#: beside a swatch — so it occupies no cell. Rich's table says zero; wcwidth says two. +#: The five Fitzpatrick skin-tone modifiers (U+1F3FB to U+1F3FF). A modifier after an emoji +#: base changes the colour of that glyph, and does not draw a glyph of its own. +#: Thus ``👍🏽`` is a thumb, not a thumb next to a swatch, and the modifier +#: occupies no cell. Rich's table says zero, and wcwidth says two. _MODIFIERS = frozenset(chr(cp) for cp in range(0x1F3FB, 0x1F400)) -#: What may trail a base inside one glyph with no joiner in front of it: its variation selector, -#: its skin tone, and a keycap's enclosing mark. A joined run gathers these after its base and -#: after every component. +#: What can follow a base in one glyph without a joiner before it: its variation selector, its +#: skin tone, and the enclosing mark of a keycap. A joined run collects these after its base and +#: after each component. _EXTENDERS = frozenset((_VS16, _KEYCAP, *_MODIFIERS)) -#: Unicode general categories holding nothing a terminal can draw: control characters -#: (``Cc``), the format and bidi-control block (``Cf``), surrogates (``Cs``), and the line -#: and paragraph separators (``Zl``/``Zp``). See :func:`drawable`, which folds them to a -#: space — and keeps the one ``Cf`` codepoint that matters, the zero-width joiner. +#: The Unicode general categories that hold nothing that a terminal can draw: control +#: characters (``Cc``), the format and bidi-control block (``Cf``), surrogates (``Cs``), and +#: the line and paragraph separators (``Zl``/``Zp``). Refer to :func:`drawable`, which folds +#: them to a space. It keeps the one ``Cf`` codepoint that matters: the zero-width joiner. _UNDRAWABLE = frozenset(("Cc", "Cf", "Cs", "Zl", "Zp")) -#: The text-default emoji MeshTerm draws *itself*, as one-cell marks in its own lexicon, and so -#: measures at one cell rather than reserving two. Each is a glyph the app has put on screen -#: deliberately and checks through ``meshterm specimen``, not one that arrived in somebody's -#: name, so its width is a fact about the app's own vocabulary rather than a guess about a font. +#: The text-default emoji that MeshTerm draws itself, as one-cell marks in its own lexicon. +#: Thus MeshTerm measures them at one cell, and does not reserve two. Each one is a glyph that +#: the app put on the screen on purpose and checks through ``meshterm specimen``. It is not a +#: glyph that came in the name of somebody. Thus its width is a fact about the vocabulary of the +#: app, not a guess about a font. #: -#: The list is closed by a test, not by care: every text-default emoji in the package's source -#: must be named here, so a new mark cannot slip into the reserve-two rule unnoticed. A glyph -#: that is not here is reserved two cells, which costs a blank beside it and never a misaligned -#: row — which is why this is a list that may be short, where the sets it replaced had to be -#: complete. +#: A test closes the list, not care: each text-default emoji in the source of the package must +#: be named here. Thus a new mark cannot go into the reserve-two rule without notice. A glyph +#: that is not here is reserved two cells. This costs a blank next to the glyph, and never a row +#: that is not aligned. For this reason, this list can be short, but the sets that it replaced +#: had to be complete. _APP_TEXT_MARKS = frozenset( ( "⚠", # ⚠ the warning mark @@ -130,49 +141,50 @@ _APP_TEXT_MARKS = frozenset( ) ) -#: Set once :func:`install` has run, so repeated calls are cheap no-ops. +#: Set when :func:`install` has run, so that later calls are cheap no-ops. _INSTALLED = False -#: Whether the width authorities have been redirected through this module. Gates -#: :class:`ClusterTextControl`: handing prompt_toolkit a multi-codepoint glyph as one character is -#: only right once something measures that character as one glyph, so the delivery and the -#: measurement are switched on together or not at all. +#: Whether the width authorities were redirected through this module. It gates +#: :class:`ClusterTextControl`. To give prompt_toolkit a multi-codepoint glyph as one character +#: is correct only when something measures that character as one glyph. Thus the delivery and +#: the measurement are switched on together, or not at all. _CLUSTERS = False def _is_regional_indicator(char: str) -> bool: - """Whether ``char`` is a single Regional Indicator Symbol — a country flag's building block. + """Whether ``char`` is a single Regional Indicator Symbol (one part of a country flag). - The two-letter flags (``🇨🇦``, ``🇺🇸``) are a grapheme pair drawn from this block - (U+1F1E6–U+1F1FF). The pair is one glyph; either half alone is a letter-like glyph a font - may draw at either width. It is a whole category, never a per-country entry: the indicators - are shared across flags (``🇨🇦`` and ``🇨🇳`` both start with ``C``). + The two-letter flags (``🇨🇦``, ``🇺🇸``) are a grapheme pair from this block + (U+1F1E6 to U+1F1FF). The pair is one glyph. Each half alone is a glyph like a letter, which + a font can draw at either width. The test is for the whole category, never for each country, + because the flags share the indicators (``🇨🇦`` and ``🇨🇳`` both start with ``C``). """ return len(char) == 1 and 0x1F1E6 <= ord(char) <= 0x1F1FF def _joins(char: str) -> bool: - """Whether a zero-width joiner in front of ``char`` really joins it to the glyph before. + """Whether a zero-width joiner before ``char`` truly joins it to the glyph before the joiner. - Every component an emoji ZWJ sequence joins is a pictograph — ``♂``, ``☠``, ``❤``, ``💻``, - all at U+2000 and above — so that is the test. What it rules out is a **stranded** joiner. - A MeshCore advert name is cut at a byte limit, and a name that ended on a joined emoji - (``That's So Fetch 🏴‍☠️``) arrives cut just past the joiner, followed by whatever the row - puts after the name: a space of lane padding, the next lane. Folding that character into the - flag would take its cell from it while the terminal still drew it. It also leaves the joiners - of the scripts that use them between letters (the Indic conjuncts, below U+2000) as the - letters they are. + Each component that an emoji ZWJ sequence joins is a pictograph (``♂``, ``☠``, ``❤``, + ``💻``, all at U+2000 and above), so that is the test. The test excludes a **stranded** + joiner. MeshCore cuts the name in an advert at a byte limit. A name that ended on a joined emoji + (``That's So Fetch 🏴‍☠️``) arrives cut directly after the joiner, followed by whatever the row + puts after the name: a space of lane padding, or the next lane. If that character is folded + into the flag, it loses its cell, but the terminal still draws it. The test also + leaves the joiners of the scripts that use them between letters (the Indic conjuncts, below + U+2000) as the letters that they are. """ return char >= "\u2000" and not char.isspace() @lru_cache(maxsize=1) def _reserved() -> frozenset[str]: - """Every lone codepoint that is reserved two cells, read off Unicode once. + """All the lone codepoints that are reserved two cells, read from Unicode one time. - The text-default emoji Rich's own table lists (``narrow_to_wide``, the codepoints a variation - selector promotes), less the ones measured by Rich's single-cell fast path and the app's own - marks (see the module docstring for both), plus the Regional Indicators. + The set starts with the text-default emoji that the table of Rich itself lists + (``narrow_to_wide``, the codepoints that a variation selector promotes). It removes the + codepoints that the single-cell fast path of Rich measures, and the marks of the app itself + (refer to the module docstring for both). Then it adds the Regional Indicators. """ from rich._unicode_data import load from rich.cells import _SINGLE_CELLS @@ -187,20 +199,21 @@ def _reserved() -> frozenset[str]: @lru_cache(maxsize=1) def _probe() -> re.Pattern[str]: - """Matches the first codepoint in a string that could make :func:`_glyph_width` differ. + """Matches the first codepoint in a string that can make :func:`_glyph_width` different. - A string with none of these measures exactly as the stock tables say, so it is handed to - them untouched — one C-speed scan instead of a cluster walk, which is nearly every string. + A string with none of these codepoints measures exactly as the stock tables say. Thus the + string goes to them with no change: one scan at C speed instead of a cluster walk. Nearly + every string takes this path. """ chars = {_ZWJ, _VS16, _KEYCAP, *_MODIFIERS, *_reserved()} return re.compile("[" + "".join(re.escape(char) for char in sorted(chars)) + "]") def _override(char: str) -> int | None: - """What this module says a lone codepoint measures, or ``None`` to take the stock answer. + """The width that this module gives a lone codepoint, or ``None`` for the stock answer. A skin tone takes no cell (wcwidth gives it two). A reserved codepoint (:func:`_reserved`) - takes two. Everything else is the stock table's business. + takes two. For all other codepoints, the stock table decides. """ if char in _MODIFIERS: return 0 @@ -210,19 +223,20 @@ def _override(char: str) -> int | None: def _glyph_width(glyph: str, stock: Callable[[str], int]) -> int: - """The cells one glyph is reserved — the single rule every width authority is patched with. + """The cells that one glyph is reserved: the one rule that patches each width authority. - A glyph built from several codepoints that carries a joiner, a variation selector or a keycap, - or is a flag's indicator pair, is reserved two. Anything else is its base codepoint: a skin tone - rides along with its base, so a toned emoji measures what the emoji does, and a letter wearing a - stray modifier stays a letter. + A glyph is reserved two cells if it is built from several codepoints and has a joiner, a + variation selector, or a keycap. A glyph that is the indicator pair of a flag is also reserved + two. All other glyphs measure as their base codepoint. A skin tone goes with its base, so an + emoji with a tone measures the same as the emoji. A letter with a stray modifier stays a + letter. Args: glyph: One glyph, as :func:`clusters` splits it. - stock: The stock width of a single codepoint, in the authority being patched. + stock: The stock width of a single codepoint, in the authority that is patched. Returns: - The glyph's width in cells. + The width of the glyph in cells. """ base = glyph[0] if len(glyph) > 1 and ( @@ -234,18 +248,18 @@ def _glyph_width(glyph: str, stock: Callable[[str], int]) -> int: def clusters(text: str) -> Iterator[str]: - """Split ``text`` into the glyphs the terminal actually draws, never inside one. + """Split ``text`` into the glyphs that the terminal draws, never in the middle of one. - The same run :func:`_join_clusters` gathers out of a laid-out line, read off a plain - string instead: a base, whatever extends it (:data:`_EXTENDERS` — a variation selector, a - skin tone, a keycap's enclosing mark), then any number of *joiner + component + extenders* - groups, plus the Regional Indicator **pair** a country flag is drawn from. A joiner that - joins nothing (:func:`_joins`) is a cluster of its own, because it is not part of the glyph - before it. + A cluster is the same run that :func:`_join_clusters` collects from a laid-out line, but + read from a plain string. It is a base, then what extends it (:data:`_EXTENDERS`: a + variation selector, a skin tone, the enclosing mark of a keycap), then any number of + *joiner + component + extenders* groups. A cluster is also the Regional Indicator **pair** + from which a country flag is drawn. A joiner that joins nothing (:func:`_joins`) is a + cluster of its own, because it is not part of the glyph before it. - The unit a lane has to cut on and a width is measured by: a cut through the middle of a - glyph leaves pieces that are nothing a terminal draws as measured — a lone Regional - Indicator drawn as a letter, a skin tone with no base, or a stranded joiner. See + A lane must cut on this unit, and a width is measured by it. A cut through the middle of a + glyph leaves pieces that a terminal does not draw at the measured width: a lone Regional + Indicator drawn as a letter, a skin tone with no base, or a stranded joiner. Refer to :func:`cut_cells`. """ index = 0 @@ -261,33 +275,34 @@ def clusters(text: str) -> Iterator[str]: while index < count and text[index] in _EXTENDERS: index += 1 while index + 1 < count and text[index] == _ZWJ and _joins(text[index + 1]): - index += 2 # the joiner and the codepoint it joins + index += 2 # the joiner and the codepoint that it joins while index < count and text[index] in _EXTENDERS: index += 1 yield text[start:index] def cut_cells(text: str, width: int) -> str: - """The longest prefix of ``text`` that fits ``width`` cells, cut **between** glyphs. + """The longest prefix of ``text`` that fits in ``width`` cells, cut **between** glyphs. - What a fixed lane needs when a name outruns it (:func:`~meshterm.ui.menus.fit_cells`), - and the reason it cannot simply walk the string a character at a time: a MeshCore name - is written by whoever owns the radio, so it arrives carrying whatever emoji they typed, - and a codepoint-by-codepoint cut lands inside one about as often as not. Cutting + A fixed lane needs this prefix when a name is longer than the lane + (:func:`~meshterm.ui.menus.fit_cells`). The lane cannot walk the string one character at a + time, for this reason: the owner of the radio writes a MeshCore name, so the name comes + with whatever emoji the owner typed. A cut at each codepoint lands in the middle of an + emoji approximately as often as not. A cut of ``"👨‍👩‍👧"`` after its first joiner leaves a stranded joiner at the end of the lane, and - cutting a flag in half leaves a lone Regional Indicator, which is a letter rather than half - a flag. + a cut of a flag in half leaves a lone Regional Indicator, which is a letter, not half a + flag. - So the prefix is built out of whole :func:`clusters`, and a trailing joiner — stranded - by the cut itself, or already stranded in the name — is dropped rather than left beside - whatever the caller appends. + Thus the prefix is made of whole :func:`clusters`. A trailing joiner is removed, and not + left next to the text that the caller adds after it. The cut itself can strand the + joiner, or the joiner can be already stranded in the name. Args: text: The text to cut. - width: The most cells the result may occupy. + width: The maximum number of cells that the result can occupy. Returns: - A prefix measuring at most ``width`` cells, with every glyph in it whole. + A prefix that measures at most ``width`` cells, with each glyph in it whole. """ kept: list[str] = [] used = 0 @@ -303,20 +318,20 @@ def cut_cells(text: str, width: int) -> str: def drawable(text: str) -> str: - """``text`` with every codepoint a terminal cannot *draw* folded to a space. + """``text`` with each codepoint that a terminal cannot draw folded to a space. - A name comes off the air from a stranger's radio, and nothing on the way in promises it - holds only characters. A newline in one ends the row mid-lane; an ``ESC`` starts an - escape sequence in the middle of a screen the app composed; a bidi override (``U+202E``) - reverses everything drawn after it. None of them is a width question at all — they are - text that must not reach the terminal, so a lane folds them to the one character that is - always safe. + A name comes over the radio from the node of a stranger, and nothing on the way in + promises that it holds only characters that a terminal can draw. A newline in a name ends + the row in the middle of a lane. An ``ESC`` starts an escape sequence in the middle of a + screen that the app composed. A bidi override (``U+202E``) reverses all that is drawn + after it. None of these is a question of width. They are text that must not get to the + terminal, so a lane folds them to the one character that is always safe. Folded: control characters, the format and bidi-control block, surrogates, and the line - and paragraph separators. **Kept:** the zero-width joiner, which is format-class too and - is the tell that holds an emoji sequence together, along with every mark and modifier a - glyph is built from. Private-use codepoints are kept as well — that block is where a - Nerd Font keeps the powerline glyphs the path line is drawn with. + and paragraph separators. **Kept:** the zero-width joiner, which is also in the format + class and is the sign that holds an emoji sequence together. Also kept: each mark and + modifier from which a glyph is built. Private-use codepoints are also kept, because a + Nerd Font keeps in that block the powerline glyphs with which the path line is drawn. """ return "".join( " " if char != _ZWJ and unicodedata.category(char) in _UNDRAWABLE else char for char in text @@ -324,15 +339,17 @@ def drawable(text: str) -> str: def install() -> None: - """Patch every width authority with the reserve-two rule, once, before the first frame. + """Patch each width authority with the reserve-two rule, one time, before the first frame. - Rich's whole-string width, its single-character width (in both modules that read it) and its - grapheme spans, and prompt_toolkit's width cache, all from :func:`_glyph_width` — see the - module docstring for why all four and why at once. Each patch hands a string with nothing - reservable in it straight to the stock code it replaced, so the common case pays one scan. + The patches are: the whole-string width of Rich, its single-character width (in both + modules that read it), its grapheme spans, and the width cache of prompt_toolkit. All of + them use :func:`_glyph_width`. The module docstring gives the reason for all four, and for + the patch of all four at the same time. Each patch gives a string with nothing reservable in + it directly to the stock code that it replaced. Thus the common case pays for one scan. - Safe to call more than once; only the first call does anything. Called from the menu loop on - a platform that draws emoji; see the module docstring for why nothing else calls it. + It is safe to call this function more than one time. Only the first call does something. + The menu loop calls it on a platform that draws emoji. The module docstring gives the + reason why nothing else calls it. """ global _INSTALLED, _CLUSTERS if _INSTALLED: @@ -376,8 +393,8 @@ def install() -> None: end = index + len(glyph) width = _glyph_width(glyph, lambda char: stock_size(char, unicode_version)) if width == 0 and spans: - # Zero-width pieces belong to the glyph before them, as Rich's own splitter has it, - # so a crop never lands between a letter and its mark. + # Zero-width pieces belong to the glyph before them, as in the splitter of Rich + # itself. Thus a crop never lands between a letter and its mark. start, _end, size = spans[-1] spans[-1] = (start, end, size) else: @@ -387,7 +404,7 @@ def install() -> None: return spans, total class _ReservingCache(type(ptu._CHAR_SIZES_CACHE)): # type: ignore[misc] - """prompt_toolkit's width cache, answering from :func:`_glyph_width`.""" + """The width cache of prompt_toolkit, which gets its answers from :func:`_glyph_width`.""" def __missing__(self, string: str) -> int: if len(string) == 1: @@ -399,8 +416,9 @@ def install() -> None: if probe.search(string) is None: return super().__missing__(string) total = sum(_glyph_width(glyph, self.__getitem__) for glyph in clusters(string)) - # A whole line holding an emoji is cheap to recompute, and would otherwise slip past - # the base class's rotation of long strings and grow the cache without bound. + # A whole line that holds an emoji is cheap to compute again. If a long line is + # cached here, it goes past the rotation of long strings in the base class, and the + # cache grows without limit. if len(string) <= self.LONG_STRING_MIN_LEN: self[string] = total return total @@ -412,26 +430,27 @@ def install() -> None: cells.cached_cell_len.cache_clear() ptu._CHAR_SIZES_CACHE = _ReservingCache() _CLUSTERS = True - # The measurement just changed under every renderable, so anything rasterized before - # (nothing, in the normal boot order — but never trust that) is stale. + # The measurement changed under each renderable. Thus all that was rasterized before is + # stale. (In the normal boot order, nothing was rasterized before, but never trust that.) _ANSI_CACHE.clear() class _Cluster(str): """A multi-codepoint glyph that must reach the screen buffer as **one** character. - prompt_toolkit builds its screen a codepoint at a time — ``for c in text`` in - ``Window._copy_body`` — and gives each one its own cell-occupying ``Char``. A glyph measured - correctly at two cells is therefore still laid out as its parts: a shrug followed by a male - sign, a flag as two letters, a warning mark with a selector folded into a slot one cell wide. - Iterating a cluster yields the whole glyph instead, so that loop makes a single ``Char`` of it: - one width in prompt_toolkit's arithmetic, every codepoint written to the terminal back to back, - and one composed glyph on the screen. + prompt_toolkit builds its screen buffer one codepoint at a time (``for c in text`` in + ``Window._copy_body``), and gives each codepoint its own ``Char``, which occupies a cell. + Thus a glyph that is correctly measured at two cells is still laid out as its parts: a shrug + followed by a male sign, a flag as two letters, a warning mark with a selector folded into a + slot one cell wide. An iteration over a cluster yields the whole glyph instead, so that loop + makes a single ``Char`` of it. The result is one width in the arithmetic of prompt_toolkit, + each codepoint written to the terminal one after the other, and one composed glyph on the + terminal. - It is a ``str`` subclass rather than a wrapper because it has to survive as ordinary text - through everything else prompt_toolkit does with a fragment — joining, slicing, comparing. - ``str`` methods return plain ``str``, so the marking is lost on the first ``split``; that is - why :class:`ClusterTextControl` applies it to the finished lines and nothing earlier. + It is a ``str`` subclass instead of a wrapper, because it must stay ordinary text through + all the other things that prompt_toolkit does with a fragment: join, slice, and compare. + ``str`` methods return plain ``str``, so the first ``split`` loses the mark. For this + reason, :class:`ClusterTextControl` applies the mark to the finished lines, and not earlier. """ __slots__ = () @@ -440,28 +459,31 @@ class _Cluster(str): yield str(self) -#: Codepoints whose presence in a laid-out line means some glyph on it is built from several. +#: If one of these codepoints is in a laid-out line, a glyph on that line is built from several. _JOINERS = frozenset((_ZWJ, *_EXTENDERS)) def _join_clusters(line: list) -> list: """Merge each multi-codepoint glyph in one screen line into a single :class:`_Cluster` fragment. - The line arrives one codepoint per fragment (that is what - :class:`~prompt_toolkit.formatted_text.ANSI` produces), so a glyph built from several is a run - to be gathered, the same run :func:`clusters` reads off a plain string: a base and whatever - extends it, a flag's indicator pair, and any number of *joiner + component + extenders* groups. + The line arrives with one codepoint in each fragment (that is what + :class:`~prompt_toolkit.formatted_text.ANSI` produces). Thus a glyph built from several + codepoints is a run to collect. It is the same run that :func:`clusters` reads from a plain + string: a base and what extends it, the indicator pair of a flag, and any number of + *joiner + component + extenders* groups. - Every such glyph is merged, a lone selector pair and a toned emoji included. prompt_toolkit - would fold those into the cell before them on its own, but it keeps that cell's place while it - does, so a mark measured one cell and followed by a selector would become a two-cell glyph in a - one-cell slot. And the renderer's writes are what :class:`~meshterm.ui.tui.colsnap.PinnedOutput` - pins: a pin between the two halves of a flag is a cursor move between them, after which a - terminal no longer joins them into one glyph at all. + Each such glyph is merged, also a lone selector pair and an emoji with a tone. Without the + merge, prompt_toolkit folds those into the cell before them itself, but while it does, it + keeps the place of that cell. Thus a mark measured at one cell and followed by a selector + becomes a two-cell glyph in a one-cell slot. Also, + :class:`~meshterm.ui.tui.colsnap.PinnedOutput` pins the writes of the renderer. A pin + between the two halves of a flag is a cursor move between them, and after that move, a + terminal no longer joins them into one glyph. - A joiner with no pictograph after it (see :func:`_joins`) is not part of any glyph, and keeps - its fragment. The whole line is handed back unchanged when nothing on it could start or extend - such a glyph, which is almost every line; the scan runs only when a control's content changes. + A joiner with no pictograph after it (refer to :func:`_joins`) is not part of a glyph, and + keeps its fragment. When nothing on the line can start or extend such a glyph, the whole + line is returned with no change. That is true of almost every line. The scan runs only when + the content of a control changes. """ if not any(item[1] in _JOINERS or _is_regional_indicator(item[1]) for item in line): return line @@ -481,7 +503,7 @@ def _join_clusters(line: list) -> list: while end < count and line[end][1] in _EXTENDERS: end += 1 while end + 1 < count and line[end][1] == _ZWJ and _joins(line[end + 1][1]): - end += 2 # the joiner and the codepoint it joins + end += 2 # the joiner and the codepoint that it joins while end < count and line[end][1] in _EXTENDERS: end += 1 if end - index > 1: @@ -496,28 +518,29 @@ def _join_clusters(line: list) -> list: class ClusterTextControl(FormattedTextControl): """A :class:`~prompt_toolkit.layout.controls.FormattedTextControl` that keeps glyphs whole. - The control is the last place a screen's text is still arranged in lines and still ours to - touch, which is exactly what merging a glyph needs: ``split_lines`` runs before this point and - returns plain ``str`` parts, so a :class:`_Cluster` marked any earlier would not survive to be - laid out. Everything downstream — the width lookup, the wrapping, the screen buffer — reads the - merged lines. + The control is the last place where the text of a screen is still in lines, and where we + can still change it. A merge of a glyph needs exactly that. ``split_lines`` runs before + this point and returns plain ``str`` parts, so a :class:`_Cluster` marked earlier does not + stay until the layout. All the steps after this point (the width lookup, the wrapping, the + screen buffer) read the merged lines. - Merging is gated on :func:`install` having run, because handing prompt_toolkit a glyph as one - character is only right once its cache measures that character as one glyph. Off that path - (a test, a platform that draws no emoji) this is its base class exactly. + The merge is gated on :func:`install`: it occurs only after that function has run. To give + prompt_toolkit a glyph as one character is correct only when its cache measures that + character as one glyph. Off that path (a test, a platform that draws no emoji), this class + is exactly its base class. """ def create_content(self, width: int, height: int | None): # type: ignore[override] - """The base class's content, with each line's multi-codepoint glyphs joined into one. + """The content of the base class, with the multi-codepoint glyphs of each line joined. - The joining is wrapped around the returned object's line lookup and memoised - behind it, because prompt_toolkit hands back the same content object paint after - paint — walking every line of every frame would cost far more than it saves. + The join is wrapped around the line lookup of the returned object, and cached behind + it. prompt_toolkit returns the same content object paint after paint, and a walk over + each line of each frame costs much more than it saves. """ content = super().create_content(width, height) - # The base class caches its ``UIContent`` per (fragments, width, cursor), so the same - # object comes back paint after paint: wrap its line lookup once, and memoise the merge - # behind it, rather than re-walking every line of every frame. + # The base class caches its ``UIContent`` for each (fragments, width, cursor), so the + # same object comes back paint after paint. Thus wrap its line lookup one time, and + # cache the merge behind it, instead of a new walk over each line of each frame. if _CLUSTERS and not getattr(content, "_clusters_merged", False): content._clusters_merged = True # type: ignore[attr-defined] source = content.get_line diff --git a/meshterm/ui/tui/fastrender.py b/meshterm/ui/tui/fastrender.py index ad96c2b..be8dfd7 100644 --- a/meshterm/ui/tui/fastrender.py +++ b/meshterm/ui/tui/fastrender.py @@ -1,41 +1,46 @@ # SPDX-License-Identifier: Apache-2.0 -"""Write an already-composed frame straight to the terminal, one changed row at a time. +"""Write an already composed frame directly to the terminal, one changed row at a time. -MeshTerm composes every frame itself: :func:`~meshterm.ui.tui.frame.compose_base` returns -a finished ANSI string, exactly one line per terminal row, already sliced to the viewport -and already folded to the platform's glyph set. prompt_toolkit's own renderer then takes -that string and does a full round trip with it — parses the ANSI back into style/text -fragments, writes every one of the ~1400 cells into a fresh grid of ``Char`` objects, -diffs that grid against the previous frame's grid, and re-emits ANSI for the cells that -moved. +MeshTerm composes each frame itself. :func:`~meshterm.ui.tui.frame.compose_base` returns a +finished ANSI string, with exactly one line for each terminal row. The string is already +cut to the viewport, and already folded to the glyph set of the platform. +The renderer of prompt_toolkit then takes that string and does a full round trip with it: -That round trip is the single largest cost in a keystroke on the PicoCalc, and it is paid -in full on *every* paint — a measured 70-125 ms whether the frame changed by one row, by -all of them, or not at all (the 2 s header tick recomposes an identical frame and still -pays it). Since we already know the frame as rows of text, the same pixels can be reached -by comparing this frame's rows against the last frame's rows and rewriting only the ones -that differ: ~0.1 ms, and a smaller write besides. +* it parses the ANSI back into style and text fragments, +* it writes each of the approximately 1400 cells into a new grid of ``Char`` objects, +* it compares that grid with the grid of the previous frame, and +* it writes ANSI again for the cells that changed. -The bypass is deliberately narrow. It runs only when the frame is a plain full-screen -composition — one base screen, no floating dialog and no busy overlay — because those are -laid out by prompt_toolkit's float containers rather than by us, and compositing them here -would mean re-implementing that placement. Anything else falls straight through to the -stock renderer, which stays the authority: :meth:`FastRenderer.render` is an accelerator -for the common case, never a second implementation of the whole layout engine. +That round trip is the largest cost of a key press on the PicoCalc. MeshTerm pays all of +it on each paint: a measured 70-125 ms, when the frame changed by one row, by all rows, or +not at all. (The header tick every 2 s composes an identical frame again, and still pays +the full cost.) We already know the frame as rows of text. Thus the same pixels are +possible with less work: compare the rows of this frame with the rows of the last frame, +and write again only the rows that are different. That takes approximately 0.1 ms, and the +write is also smaller. -Three details make the row diff safe rather than merely fast: +The bypass is narrow on purpose. It runs only when the frame is a plain full-screen +composition: one base screen, with no floating dialog and no busy overlay. The float +containers of prompt_toolkit lay out the dialog and the overlay, not MeshTerm. If we +composite them here, we must implement that placement again. All other frames go +directly to the stock renderer, which stays the authority. :meth:`FastRenderer.render` +makes the common case faster. It is never a second implementation of the whole layout +engine. -* **A row is rewritten whole, from column 0.** Stepping down to a row returns the terminal - to a true column 0 whatever happened on the row above, so a glyph drawn at a width we did - not measure can never throw off the rows below it — the same guarantee - :meth:`~meshterm.ui.tui.session.TuiSession._emit` relies on, reached here for free rather - than by a scrub pass. -* **Every column of that row is pinned to the grid the app measured** - (:func:`~meshterm.ui.tui.colsnap.snap_row`), which is what keeps the drift from mattering - *within* the row either. This is the only place in the app where a row's bytes are still - ours on their way to the terminal, so it is the only place that correction can be made. -* **Each row is cleared before it is drawn, never after**, so no style leaks in from the row - above, a row that got shorter leaves no tail behind, and a row that fills the terminal +Three details make the row diff safe, not only fast: + +* **A row is written again whole, from column 0.** When the cursor steps down to a row, + the terminal goes back to a true column 0, whatever occurred on the row above. Thus a + glyph that the terminal draws at a width that we did not measure can never move the rows + below it. :meth:`~meshterm.ui.tui.session.TuiSession._emit` relies on the same + guarantee. Here the guarantee comes at no cost, without a scrub pass. +* **Each cell of that row is pinned to the grid that the app measured** + (:func:`~meshterm.ui.tui.colsnap.snap_row`). This pin keeps the drift from having an + effect in the row too. This is the only place in the app where the bytes of a row are + still ours on their way to the terminal. Thus it is the only place where that correction + is possible. +* **Each row is cleared before it is drawn, never after.** Thus no style comes in from the + row above, a row that became shorter leaves no tail, and a row that fills the terminal exactly keeps its last cell. """ @@ -50,20 +55,22 @@ from . import colsnap def _as_is(row: str) -> str: - """The unpinned write path: a row goes out exactly as it was composed.""" + """The write path with no pin: a row goes out exactly as it was composed.""" return row def enabled() -> bool: """Whether the direct row writer is active. - On by default — it is 2-3x on every navigation keystroke and its output is verified - byte-identical against the stock renderer by reading the console back. The escape - hatch, for a terminal that ever disagrees, is the ``fast_render`` preference; - ``MESHTERM_FASTRENDER=0``/``=1`` overrules it for one run without editing anything. + The writer is on by default. It makes each navigation key press 2-3x faster. Its output + was checked against the stock renderer with a read back of the console, and the bytes + are identical. If a terminal does not agree with the writer, the ``fast_render`` + preference turns it off. ``MESHTERM_FASTRENDER=0``/``=1`` overrides that preference + for one run, without an edit to anything. - Read at session build, so a change made on the Preferences page takes hold at the - next launch — which is what that preference's description promises. + The value is read when the session is built. Thus a change on the Preferences page has + an effect at the next start of the app. The description of that preference promises + this behaviour. """ from ...core.preferences import current as current_preferences @@ -74,56 +81,59 @@ def enabled() -> bool: class FastRenderer(Renderer): - """A :class:`~prompt_toolkit.renderer.Renderer` that short-circuits simple frames. + """A :class:`~prompt_toolkit.renderer.Renderer` that takes a short path for simple frames. Args: - frame_source: Returns the composed full-screen frame as one ANSI string (rows - joined by newlines), or ``None`` when this paint is not a plain base frame - and must go through prompt_toolkit's layout instead. + frame_source: A function that returns the composed full-screen frame as one ANSI + string (rows joined by newlines). It returns ``None`` when this paint is not a + plain base frame and must go through the layout of prompt_toolkit instead. """ def __init__(self, *args, frame_source: Callable[[], str | None], **kwargs) -> None: - """Wrap the stock renderer, starting with no remembered frame. + """Wrap the stock renderer, with no remembered frame at the start. - With nothing to compare against, the first paint is always a full one; the - ``frame_source`` argument is described in the class docstring above. + There is nothing to compare with, thus the first paint is always a full paint. The + class docstring above describes the ``frame_source`` argument. """ super().__init__(*args, **kwargs) self._frame_source = frame_source - #: How a row is pinned to the app's column grid on its way out — resolved once here, - #: because the escape hatch is a property of the terminal this session is talking to - #: and not of any one paint. Identity when it is off, so the write path never branches. + #: How a row is pinned to the column grid of the app on its way out. It is resolved + #: one time here, because the switch that turns the pin off is a property of the + #: terminal of this session, not of one paint. When the pin is off, this is the + #: identity function, so the write path never branches. self._pin: Callable[[str], str] = colsnap.snap_row if colsnap.enabled() else _as_is self._prev_rows: list[str] | None = None self._prev_size: tuple[int, int] | None = None - #: Paints answered here vs handed to the stock renderer — read by the bench. + #: The paints that this class does itself, and the paints that it gives to the stock + #: renderer. The bench reads these counts. self.fast_paints = 0 self.slow_paints = 0 def reset(self, _scroll: bool = False, leave_alternate_screen: bool = True) -> None: - """Forget the last frame along with prompt_toolkit's own render state.""" + """Forget the last frame, and also the render state of prompt_toolkit.""" self._prev_rows = None super().reset(_scroll=_scroll, leave_alternate_screen=leave_alternate_screen) def erase(self, leave_alternate_screen: bool = True) -> None: - """The screen is being cleared out from under us — the next paint must be full.""" + """The terminal is cleared under our record of it, so the next paint must be full.""" self._prev_rows = None super().erase(leave_alternate_screen=leave_alternate_screen) def render(self, app, layout, is_done: bool = False) -> None: # noqa: ANN001 - """Paint the frame, taking the row-diff path when this frame is a plain one.""" + """Paint the frame. Use the row-diff path when this frame is a plain frame.""" text = None if is_done else self._frame_source() if text is None: - # A dialog, the busy overlay, or the closing paint: prompt_toolkit lays those - # out, so it must also own the diff — its grid is the only record of what is - # on screen, and it is about to be rebuilt from scratch anyway. + # A dialog, the busy overlay, or the closing paint: prompt_toolkit lays these + # out, so it must also own the diff. Its grid is the only record of what is on + # the terminal, and prompt_toolkit will build that grid again from the start in + # any case. self._prev_rows = None self.slow_paints += 1 super().render(app, layout, is_done) return output = self.output - pending = False # whether the terminal setup below has queued anything to flush + pending = False # whether the terminal setup below queued anything to flush if self.full_screen and not self._in_alternate_screen: self._in_alternate_screen = True output.enter_alternate_screen() @@ -141,13 +151,13 @@ class FastRenderer(Renderer): dims = (size.rows, size.columns) rows = text.split("\n")[: size.rows] - # A resize invalidates both records of the screen: ours and prompt_toolkit's. + # A resize makes both records of the terminal wrong: ours and that of prompt_toolkit. full = self._prev_rows is None or self._prev_size != dims if not full and not pending and rows == self._prev_rows: - # The app repaints on a timer to keep the header's pulse moving, and most of - # those frames come back identical. Writing nothing at all is not merely cheaper - # than writing the rows again — it leaves the panel's damage region empty, so - # the display never flushes and the SPI bus stays quiet. + # The app paints on a timer to keep the pulse of the header in motion, and most + # of those frames are identical. To write nothing is not only cheaper than to + # write the rows again. It also keeps the damage region of the display empty. + # Thus the display never flushes, and the SPI bus stays quiet. self._last_size = size self.fast_paints += 1 return @@ -164,29 +174,33 @@ class FastRenderer(Renderer): for i, row in enumerate(rows): if not full and i < len(prev) and prev[i] == row: continue - # Stepping down a row with CRLF returns the terminal to a true column 0 - # whatever happened on the row above, and costs three bytes less than a - # cursor address; only a real jump pays for one. + # A step down one row with CRLF sets the terminal back to a true column 0, + # whatever occurred on the row above. It also costs three bytes less than a + # cursor address. Only a real jump uses a cursor address. write("\r\n" if i == last + 1 else f"\x1b[{i + 1};1H") - # Erase *before* drawing, never after. A row that fills the terminal exactly - # leaves the cursor in the last column with wrap pending, and an erase-to-end - # there wipes the very character just written (the row's last cell went - # missing on the PicoCalc's 53-column console). Clearing first also drops the - # tail of a row that got shorter, which is what the erase was for. + # Erase before the row is drawn, never after. A row that fills the terminal + # exactly leaves the cursor in the last cell, with a wrap pending. An erase to + # the end there removes the character that was just written. (The last cell of + # the row went missing on the console of the PicoCalc, which is 53 cells wide.) + # An erase first also removes the tail of a row that became shorter, which is + # the purpose of the erase. write("\x1b[0m\x1b[K") - # Pinned, not merely written: an emoji in a node's name is drawn at whatever width - # this font gives it, and the lanes after it belong to the app's grid either way. + # Pinned, not only written: the terminal draws an emoji in the name of a node at + # the width that this font gives it. But the lanes after the emoji stay on the + # grid of the app in all cases. write(self._pin(row)) last = i - # Park the cursor out of the text. The app hides it, but a terminal that ignores - # that should not leave it blinking in the middle of a row. + # Move the cursor out of the text. The app hides the cursor, but a terminal can + # ignore that. Such a terminal must not leave the cursor to blink in the middle of + # a row. write(f"\x1b[{len(rows)};1H") output.flush() self._prev_rows = rows self._prev_size = dims self._last_size = size - # prompt_toolkit's grid no longer describes the screen — if a later paint falls - # back to it, it must redraw everything rather than diff against a stale record. + # The grid of prompt_toolkit no longer describes the terminal. If a later paint + # goes back to that grid, it must draw everything again, instead of a diff against + # an old record. self._last_screen = None self.fast_paints += 1 diff --git a/meshterm/ui/tui/fkeys.py b/meshterm/ui/tui/fkeys.py index 33836dc..058f930 100644 --- a/meshterm/ui/tui/fkeys.py +++ b/meshterm/ui/tui/fkeys.py @@ -1,66 +1,81 @@ # SPDX-License-Identifier: Apache-2.0 -"""The F-key lane: a handheld's fixed footer row of coloured chips, one per function key. +"""The F-key lane: a handheld's fixed footer row of coloured chips, one for each function key. -**Each platform deals its own lane** (JP, 2026-09-30). What a lane *is* — slots of -:class:`FPair`, dimmed or live, stripped from a dialog's hint — is shared; everything that -belongs to one keyboard is a :class:`LaneDeck`, named by ``Platform.lane_deck``: which -keycodes drive the slots, where the chips sit on the row, how they are drawn, and which of -a screen's lane definitions it reads. A screen states its lane per deck — -``Screen.picocalc_lyra_lane``, ``Screen.cardputer_zero_lane`` — and the Cardputer's follows the -PicoCalc's until a screen says otherwise. Both decks having five slots is a coincidence of -two keyboards, not a rule, and nothing here assumes it: a deck's slot count is its keys. +**Each platform has its own lane** (JP, 2026-09-30). The parts of the lane concept are +shared: the :class:`FPair` slots, the dim and live states, and the removal of lane atoms +from the hint of a dialog. All that belongs to one keyboard is a :class:`LaneDeck`, named +by ``Platform.lane_deck``: -The rest of this docstring is the PicoCalc deck's design, which the Cardputer's deals for -now. 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. +* which keycodes drive the slots, +* where the chips are on the row, +* how the chips are drawn, and +* which of the lane definitions of a screen the deck reads. -By JP's spec (2026-08-01): a lane slot is for functionality that would otherwise be -*hard to reach* — not a shortcut to a key that is already close at hand. Enter and Esc -sit right on the keyboard and are already the easiest keys to hit, so they never occupy -a slot. Paging has no physical key at all, so a screen that scrolls earns it the prime -F4/F5 pair. Ctrl+letter chords (Ctrl+P for message paths, Ctrl+arrows for a sort column, -…) are fiddly to hold on this keyboard, so a screen promotes its own onto the free -F1-F3 bank. The five *plain* keys carry a screen's most-used, otherwise-awkward actions -— reachable with no Shift at all — and the Shift bank (F6-F10) holds each slot's -*opposite number*, not unrelated overflow. A lane can, and does, differ from screen to -screen. +A screen gives its lane for each deck (``Screen.picocalc_lyra_lane``, +``Screen.cardputer_zero_lane``). The Cardputer's lane follows the PicoCalc's lane until a +screen gives a different one. Both decks have five slots, but that is a coincidence of two +keyboards, not a rule, and nothing here assumes it: the slot count of a deck is the number +of its keys. -**Second-grade keys ride their own pair's Shift half** (JP, 2026-08-08). Home and End -*are* on this keyboard, so jumping to either end of a body was never the unreachable -thing paging is — it only ever wanted a chip for consistency with the pager it belongs -to. So it rides that pager: Shift+F5 (``F10``) is Top because F5 is Page ↑, Shift+F4 -(``F9``) is Bottom because F4 is Page ↓. One axis, one pair of slots, the jump sitting -behind the page on the very same key. That leaves **F1-F3 free on every screen** for the -verbs a screen actually has to offer, which is where the interesting work goes. +The rest of this docstring is the design of the PicoCalc deck, and the Cardputer's deck +uses the same design for now. The PicoCalc keyboard has five dedicated function keys. Its +MCU translates Shift+F1..F5 into plain F6-F10 keycodes (measured in P0). Thus +"Shift+key = the opposite action" is literal hardware behaviour, and the app binds all ten +keys. -**A chip names an action, never a key** (JP, 2026-08-07). ``PgUp``, ``End`` and their -kin are the names of keys this keyboard doesn't even have; what the slot is for is the -thing it does *here* — ``Page ↑`` through a body, ``Latest`` on a transcript, ``Reset`` -on the map, whose Home key refits the view and whose paging keys zoom. A screen that -repurposes a shared action relabels it; a screen the action means nothing on leaves the -slot **empty** rather than filling the lane out. Empty and dim are different claims: -empty says *not a thing here* (Retry in a channel, where nothing is ever acknowledged), -dim says *a thing here, just not right now* (Retry in a direct chat with everything -delivered). +By JP's spec (2026-08-01), a lane slot is for a function that is otherwise hard to reach. +It is not a shortcut to a keyboard key that is already easy to reach. Enter and Esc are +directly on the keyboard, and they are already the easiest keyboard keys to press. Thus +they never use a slot. Paging has no physical keyboard key, so a screen that scrolls gets +the best pair, F4/F5, for it. Ctrl+letter chords (Ctrl+P for message paths, Ctrl+arrows +for a sort column, …) are difficult to hold on this keyboard. Thus a screen moves its own +chords onto the free F1-F3 bank. -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. 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. +The five plain keys have the actions of a screen that are used most and are otherwise +difficult to reach. The user can reach them with no Shift. The Shift bank (F6-F10) holds +the *opposite number* of each slot, not unrelated overflow. A lane can be different on +each screen, and it is. -**A slot never advertises a key that would do nothing.** The lane is the PicoCalc's whole -footer — it stands in for the hint line the other platform draws, and that line has always -dropped an atom whose key is inert (see :attr:`~meshterm.ui.tui.screen.Screen.content_overflows`). -So a screen rebuilds its lane each paint and clears :attr:`FPair.enabled` / -:attr:`FPair.opp_enabled` on whatever is out of reach right now: the chat's *Paths* with -no message picked, its *Retry* with nothing unacknowledged, the shared nav slots on a -screen with nothing to move (:func:`default_lane`). A dimmed slot keeps its label — muted, -unfilled, like an unassigned slot — so the key still reads as *what it would do*, it just -plainly isn't live. The dimming is presentational: the screen's own ``handle`` stays the -authority on what an action does (it no-ops), so a lane built from one-paint-stale metrics -can never swallow a key that would have worked. +**Second-grade keys go on the Shift half of their own pair** (JP, 2026-08-08). Home and +End are on this keyboard, so a jump to an end of a body was never hard to reach, as paging +is. The jump got a chip only to be consistent with the pager that it belongs to. Thus the +jump goes on that pager: Shift+F5 (``F10``) is Top because F5 is Page ↑, and Shift+F4 +(``F9``) is Bottom because F4 is Page ↓. One axis uses one pair of slots, and the jump is +behind the page on the same keyboard key. Thus **F1-F3 stay free on each screen** for the +verbs that the screen has to offer, which is where the interesting work goes. + +**A chip names an action, never a keyboard key** (JP, 2026-08-07). ``PgUp``, ``End``, and +similar names are the names of keyboard keys that this keyboard does not have. The slot is +for what it does on this screen: ``Page ↑`` through a body, ``Latest`` on a transcript, +``Reset`` on the map. (On the map, the Home key fits the viewport again, and the paging +keys zoom.) A screen that uses a shared action for a different purpose gives it a new +label. A screen on which the action has no meaning leaves the slot **empty**, and does not +fill the lane. + +Empty and dim are different claims. Empty says "not a thing here" (Retry in a channel, +where nothing is ever acknowledged). Dim says "a thing here, but not now" (Retry in a +direct chat where all messages are delivered). + +A screen gives its lane as five :class:`FPair` slots (``None`` = unassigned). The session +resolves a pressed F-key to the action string of the slot, and dispatches it through the +normal action funnel. Thus screens get F-key support with no key handling of their own. +An :class:`FPair` does not have to have a Shift-bank action. A "lone" slot +(``opp_label=""``) renders blank in the shifted bank, and F(n+5) does nothing. + +**A slot never advertises a keyboard key that does nothing.** The lane is the full footer +of the PicoCalc. It replaces the hint line that the other platform draws, and that line +always removed an atom whose keyboard key does nothing (refer to +:attr:`~meshterm.ui.tui.screen.Screen.content_overflows`). Thus a screen builds its lane +again at each paint. It clears :attr:`FPair.enabled` / :attr:`FPair.opp_enabled` on each +action that is not available now: the chat's *Paths* when no message is picked, its +*Retry* when no message is unacknowledged, and the shared nav slots on a screen with +nothing to move (:func:`default_lane`). + +A dim slot keeps its label (muted and with no fill, as an unassigned slot). Thus the +keyboard key still shows what it will do, but it is clearly not live. The dimming is only +presentational. The screen's own ``handle`` stays the authority on what an action does +(it does nothing). Thus a lane that was built from metrics one paint old can never +block a key press that works. """ from __future__ import annotations @@ -80,20 +95,21 @@ _DESC_WIDTH = 6 @dataclass(frozen=True, slots=True) class FPair: - """One F-key slot: the plain-key action and its optional Shift-bank companion. + """One F-key slot: the action of the plain key, and its optional Shift-bank companion. Attributes: - 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 ``""``. - enabled: Whether the plain key's action is available *right now*. ``False`` draws - the chip dimmed — label kept, fill dropped — rather than pretending (see the - module docstring). + label: A verb-phrase hint for the plain key, for example ``"Zoom +"``: what the + keyboard key does on this screen, never the name of the keyboard key + (``"PgUp"``). Clipped or padded to 6 cells. + action: The screen action that the plain key dispatches (``"home"``, ``"enter"``, + …). + opp_label: The hint for the Shift-bank companion, or ``""`` for a lone slot with + no companion. Then the shifted bank renders that chip blank, and the related + F(n+5) does nothing. + opp_action: The action that the Shift-bank companion dispatches, or ``""``. + enabled: Whether the action of the plain key is available now. ``False`` draws + the chip dim (the label stays, and the fill is removed), and does not pretend + (refer to the module docstring). opp_enabled: The same, for the Shift-bank companion. """ @@ -105,25 +121,27 @@ class FPair: opp_enabled: bool = True -#: A lane is five slots, F1..F5 left to right; ``None`` leaves a slot unassigned. +#: A lane is five slots, F1..F5 from left to right. ``None`` leaves a slot unassigned. Lane = Sequence[FPair | None] -#: The default lane, in the vocabulary of a screen that is one scrolling body: move -#: through it a page at a time (F4/F5), or — behind Shift, on those same two keys — jump -#: to the end each pager heads for (F9/F10). No Enter or Esc slot: both keys sit right on -#: the keyboard already. F1-F3 stay free for the screen's own verbs; a screen that has -#: none leaves them blank rather than filling the lane out. A screen whose body is not one -#: scrolling column says so in its own words (see :class:`ChatScreen`, ``MapScreen``). +#: The default lane, in the vocabulary of a screen that is one body that scrolls. Move +#: through the body one page at a time (F4/F5), or jump to the end that each pager goes to +#: (F9/F10, behind Shift, on the same two keyboard keys). There is no Enter or Esc slot, +#: because both keyboard keys are already directly on the keyboard. F1-F3 stay free for +#: the verbs of the screen. A screen that has no verbs leaves them blank, and does not +#: fill the lane. A screen whose body is not one column that scrolls gives its lane in its +#: own words (refer to :class:`ChatScreen`, ``MapScreen``). #: -#: **A directional pair rises toward its outer key** (JP, 2026-08-08): wherever two -#: adjacent chips are opposite ends of one axis, the *up · in · more* end takes the slot -#: nearer the lane's own edge. On the right-hand F4/F5 pair that is F5 — the pager here, -#: the map's zoom, ``Zoom -`` then ``Zoom +``, a rocker — and on a left-hand F1/F2 pair it -#: is F1, so a select list reads ``Sect ↑`` then ``Sect ↓``: ergonomically the hand -#: anchors on the lane's edge and rocks inward, whichever side the pair lives on. A slot's -#: own Shift companion follows the same rule *along its slot*: the jump behind ``Page ↑`` -#: is the one Page ↑ is heading for, so F10 is Top and F9 Bottom. A screen relabelling a -#: pair keeps its order (a chat's ``Latest``/``Oldest``). +#: **A directional pair rises toward its outer key** (JP, 2026-08-08). When two adjacent +#: chips are opposite ends of one axis, the *up · in · more* end takes the slot that is +#: nearer to the edge of the lane. On the right-hand F4/F5 pair, that is F5: the pager +#: here, or the map's zoom (``Zoom -`` then ``Zoom +``, a rocker). On a left-hand F1/F2 +#: pair, it is F1, so a select list reads ``Sect ↑`` then ``Sect ↓``. The reason is +#: ergonomic: the hand stays on the edge of the lane and rocks inward, on the side of the +#: pair. +#: The Shift companion of a slot follows the same rule along its slot: the jump behind +#: ``Page ↑`` is the end that Page ↑ goes to, so F10 is Top and F9 is Bottom. A screen +#: that gives a pair new labels keeps its order (a chat's ``Latest``/``Oldest``). DEFAULT_LANE: tuple[FPair | None, ...] = ( None, None, @@ -132,28 +150,28 @@ DEFAULT_LANE: tuple[FPair | None, ...] = ( FPair("Page ↑", "pageup", "Top", "home"), ) -#: The lane of a screen with no lane at all: a confirm dialog, a busy spinner, a text -#: prompt. Nothing there pages or jumps, so the shared pager is not dim-but-real, it is -#: simply *not a thing here* — the distinction the module docstring draws — and every slot -#: renders as a bare, unfilled key number. +#: The lane of a screen with no lane: a confirm dialog, a busy spinner, a text prompt. +#: Nothing there pages or jumps. Thus the shared pager is not "dim but real". It is "not a +#: thing here", which is the difference that the module docstring explains. Each slot +#: renders as a bare key number with no fill. EMPTY_LANE: tuple[FPair | None, ...] = (None, None, None, None, None) def default_lane(*, nav: bool = True) -> tuple[FPair | None, ...]: - """:data:`DEFAULT_LANE`, with its pager slots dimmed unless ``nav``. + """:data:`DEFAULT_LANE`, with its pager slots dim unless ``nav``. - Both shared slots *move* something — the page, and the jump behind it — so on a screen - with nothing to move (a body that fits its viewport, a transcript with no messages) - both banks are inert and say so. Screens that repurpose the nav actions for something - always live (the map's zoom) build from :data:`DEFAULT_LANE` instead, relabelling as - they go. + Both shared slots move something: the page, and the jump behind it. Thus on a screen + with nothing to move (a body that fits in its visible area, a transcript with no + messages), both banks do nothing and show it. Screens that use the nav actions for + something that is always live (the map's zoom) build from :data:`DEFAULT_LANE` + instead, and give new labels. Args: - nav: Whether the nav keys would do anything on this paint — typically + nav: Whether the nav keys can do something on this paint. This is usually :attr:`~meshterm.ui.tui.screen.Screen.content_overflows`. Returns: - The five slots, ready for a screen to overwrite the ones it claims. + The five slots, ready for a screen to overwrite the slots that it claims. """ if nav: return DEFAULT_LANE @@ -165,25 +183,27 @@ def default_lane(*, nav: bool = True) -> tuple[FPair | None, ...]: @dataclass(frozen=True, slots=True) class LaneDeck: - """One platform's F-key lane: the keys that drive it, where it draws, whose lanes it reads. + """One platform's F-key lane: its keyboard keys, where it draws, and whose lanes it reads. - The slots are left to right, and every per-slot tuple here has one entry per slot. + The slots are from left to right, and each per-slot tuple here has one entry for each + slot. Attributes: name: What ``Platform.lane_deck`` calls this deck. - keys: The F-key number each slot's plain key arrives as. - shift_keys: The F-key number each slot's Shift companion arrives as. - captions: How each slot's plain key is named on the row: leading a captioned - chip, and standing alone, muted, in a slot with nothing assigned. + keys: The F-key number that the plain key of each slot arrives as. + shift_keys: The F-key number that the Shift companion of each slot arrives as. + captions: How the row names the plain key of each slot. The caption starts a + captioned chip, and it stands alone, muted, in a slot with nothing assigned. shift_captions: The same, for the Shift bank. - columns: The column each chip starts at. - chip_width: Cells per chip. - captioned: Whether a live chip leads with its key's caption (``F1 Zoom +``) or - is its label alone, centred — for a keyboard whose key sits right under the - chip, where naming it again only costs the label cells. + columns: The column at which each chip starts. + chip_width: The number of cells in each chip. + captioned: Whether a live chip starts with the caption of its keyboard key + (``F1 Zoom +``), or is only its label, at the centre. The second form is for + a keyboard whose keyboard key is directly under the chip. There, the name of + the keyboard key again only uses cells of the label. fill: The theme style of a live chip in the plain bank. - shift_fill: The same, while the Shift watcher reports Shift held. - read_lane: Reads a screen's lane for this deck. + shift_fill: The same, while the Shift watcher reports that Shift is held. + read_lane: Reads the lane of a screen for this deck. """ name: str @@ -203,14 +223,15 @@ class LaneDeck: return number in self.shift_keys def action_for(self, lane: Lane, number: int) -> str | None: - """The action F-key ``number`` resolves to on this lane, or ``None``. + """The action that F-key ``number`` resolves to on this lane, or ``None``. - A plain key takes its slot's action, a Shift-bank key its companion — or nothing, - where the slot has none (a lone slot, or an unassigned one), and where the key is - not one of this deck's at all. A *dimmed* slot still resolves: dimming is how the - lane draws an action the screen would no-op anyway, and resolving it regardless - keeps a lane built from stale metrics from ever swallowing a key that works (see - the module docstring). + A plain key takes the action of its slot, and a Shift-bank key takes the action of + its companion. The result is ``None`` where the slot has no action (a lone slot, or + an unassigned slot), and where the keyboard key is not a key of this deck. A dim + slot still resolves. Dimming is how the lane draws an action on which the screen + does nothing anyway. Because the action resolves in all cases, a lane that was + built from stale metrics can never block a key press that works (refer to the + module docstring). """ if number in self.keys: index, shifted = self.keys.index(number), False @@ -229,12 +250,12 @@ class LaneDeck: """Render the lane as this deck's chips: coloured fill, white text, each at its column. Args: - lane: The slots; any past this deck's last are not drawn. - shifted: Show the Shift bank, in :attr:`shift_fill`; the plain bank renders + lane: The slots. The slots after the last slot of this deck are not drawn. + shifted: Show the Shift bank, in :attr:`shift_fill`. The plain bank renders in :attr:`fill`. Returns: - A one-line :class:`Text`, ending with the last chip. + A one-line :class:`Text` that ends with the last chip. """ fill = self.shift_fill if shifted else self.fill captions = self.shift_captions if shifted else self.captions @@ -244,15 +265,15 @@ class LaneDeck: pair = lane[index] if index < len(lane) else None 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 - # caption, unfilled — nothing to press here. + # Unassigned (no slot, or the empty Shift bank of a lone slot): the bare + # key caption with no fill. There is nothing to press here. row.append(self._body(captions[index]), style="muted") continue live = pair.opp_enabled if shifted else pair.enabled body = f"{captions[index]} {label[:_DESC_WIDTH]:<{_DESC_WIDTH}}" - # A dimmed slot drops the fill and keeps the label, landing in the same muted - # "nothing to press" class as an unassigned one — while still saying what the - # key is for once it becomes available. + # A dim slot removes the fill and keeps the label. Thus it is in the same muted + # "nothing to press" class as an unassigned slot. But it still says what the + # keyboard key is for, when the action becomes available. row.append( self._body(body if self.captioned else label[:_DESC_WIDTH]), style=fill if live else "muted", @@ -267,9 +288,9 @@ class LaneDeck: #: The PicoCalc's five dedicated function keys. Its keyboard MCU sends Shift+F1..F5 as -#: plain F6-F10, so the Shift bank is keys of its own. Every chip is a 2-cell key caption, -#: a space and a 6-cell label; five chips and four 2-cell gaps sum to exactly 53, the -#: console's width, with nothing left over. +#: plain F6-F10, so the Shift bank has keyboard keys of its own. Each chip is a 2-cell key +#: caption, a space, and a 6-cell label. Five chips and four 2-cell gaps add up to exactly +#: 53, the width of the console, with nothing left over. PICOCALC_LYRA_DECK = LaneDeck( name="picocalc-lyra", keys=(1, 2, 3, 4, 5), @@ -284,15 +305,16 @@ PICOCALC_LYRA_DECK = LaneDeck( read_lane=attrgetter("picocalc_lyra_lane"), ) -#: The Cardputer Zero's number keys 4-8, which sit right under the display: Fn+4..8 are -#: F4-F8, never the bare digits, since a digit must stay a digit on a screen that takes -#: typing (JP, 2026-09-30). The keyboard driver sends Shift as a key of its own, and the -#: emulator encodes Shift+Fn+4..8 the way xterm encodes Shift+F4..F8, which -#: prompt_toolkit reads as F16-F20 — so a desktop terminal with ``--platform cardputer-zero`` -#: drives the same bank. The chips are laid out exactly as the PicoCalc's — the key's -#: caption leading a 6-cell label, nine cells a chip, two between (JP, 2026-09-30) — and -#: the Shift bank keeps the same captions, since it is the same keys with Shift held; its -#: blue fill is what says so. It reads the PicoCalc's lanes for now (see +#: The Cardputer Zero's number keys 4-8, which are directly under the display. Fn+4..8 are +#: F4-F8, never the bare digits, because a digit must stay a digit on a screen that takes +#: typing (JP, 2026-09-30). The keyboard driver sends Shift as a key of its own. The +#: emulator encodes Shift+Fn+4..8 as xterm encodes Shift+F4..F8, which prompt_toolkit +#: reads as F16-F20. Thus a desktop terminal with ``--platform cardputer-zero`` drives the +#: same bank. The chips have exactly the same layout as the PicoCalc's: the caption of the +#: keyboard key before a 6-cell label, nine cells for each chip, and two cells between +#: chips (JP, 2026-09-30). The Shift bank keeps the same captions, because it is the same +#: keyboard keys with Shift held. Its blue fill shows that Shift is held. For now, the +#: deck reads the lanes of the PicoCalc (refer to #: :meth:`~meshterm.ui.tui.screen.Screen.cardputer_zero_lane`). CARDPUTER_ZERO_DECK = LaneDeck( name="cardputer-zero", @@ -308,7 +330,7 @@ CARDPUTER_ZERO_DECK = LaneDeck( read_lane=attrgetter("cardputer_zero_lane"), ) -#: Every deck, by the name ``Platform.lane_deck`` gives it. +#: All the decks, by the name that ``Platform.lane_deck`` gives each one. DECKS: dict[str, LaneDeck] = {deck.name: deck for deck in (PICOCALC_LYRA_DECK, CARDPUTER_ZERO_DECK)} _DECK: LaneDeck | None = None @@ -321,16 +343,16 @@ def active_deck() -> LaneDeck | None: @on_platform def _bind(platform: Platform) -> None: - """Deal the platform's deck (see :attr:`~meshterm.platforms.Platform.lane_deck`).""" + """Set the deck of the platform (refer to :attr:`~meshterm.platforms.Platform.lane_deck`).""" global _DECK _DECK = DECKS[platform.lane_deck] if platform.lane_deck else None -#: The screen action each key notation in a footer hint dispatches — the vocabulary the -#: hint line and the lane have in common, and the only place the two can say the same -#: thing twice. Arrows, Enter, Esc and the letter chords are absent deliberately: no lane -#: slot ever claims them (Enter and Esc are barred outright), so an atom naming one can -#: never be a duplicate of a chip. +#: The screen action that each key notation in a footer hint dispatches. This is the +#: vocabulary that the hint line and the lane have in common, and the only place where the +#: two can say the same thing two times. Arrows, Enter, Esc, and the letter chords are not +#: here, on purpose. No lane slot ever claims them (Enter and Esc can never have a slot). +#: Thus an atom that names one of them can never be a duplicate of a chip. _HINT_KEY_ACTIONS: dict[str, str] = { "PgUp": "pageup", "PgDn": "pagedown", @@ -343,25 +365,30 @@ _HINT_KEY_ACTIONS: dict[str, str] = { "Tab": "tab", } -#: Marks a word as *some* key notation even where it isn't one this module can map: a -#: chord (``^Y``), a shifted key (``⇧Tab``), or a bare glyph key (``⌫``). An atom whose -#: verb half carries one of these names more than the keys it opened with, so it is never -#: dropped on the strength of the ones it did name (the map's ``Home/^Y region/you``). +#: Marks a word as a key notation of some type, also where this module cannot map it: a +#: chord (``^Y``), a shifted key (``⇧Tab``), or a bare glyph key (``⌫``). If the verb half +#: of an atom has one of these marks, the atom names more than the keys at its start. Thus +#: the atom is never removed because of the keys that it did name (the map's +#: ``Home/^Y region/you``). _KEYISH = ("^", "⇧", "⌫", "↑", "↓", "←", "→") def _hint_keys(atom: str) -> tuple[str, ...]: - """The key notations ``atom`` opens with, or ``()`` where it names something else too. + """The key notations that ``atom`` opens with, or ``()`` if it also names something else. - A hint atom is *keys then verb* — ``PgUp/PgDn scroll``, ``Home/End ends`` — so the - keys are the leading run of words whose every ``/``-separated part this module knows. - The run stops at the verb, and the answer is empty (meaning "keep this atom") both - when the atom opens with a key we can't map (``↑↓ PgUp/PgDn scroll`` documents the - arrows too) and when anything after the run still looks like a key notation - (:data:`_KEYISH`) — dropping such an atom would take an unrepresented key with it. + A hint atom is keys, then a verb: ``PgUp/PgDn scroll``, ``Home/End ends``. Thus the + keys are the leading run of words in which this module knows each ``/``-separated part. + The run stops at the verb. The answer is empty (which means "keep this atom") in two + cases: + + * when the atom opens with a key that we cannot map (``↑↓ PgUp/PgDn scroll`` also + documents the arrows), and + * when a word after the run still looks like a key notation (:data:`_KEYISH`). + + If such an atom is removed, it takes away a key that the lane does not represent. """ keys: list[str] = [] - verb = False # past the leading key run: everything from here is the atom's verb half + verb = False # after the leading key run: all words from here are the verb half for word in atom.split(): parts = word.split("/") mappable = all(part in _HINT_KEY_ACTIONS for part in parts) @@ -370,36 +397,36 @@ def _hint_keys(atom: str) -> tuple[str, ...]: continue verb = True if mappable or any(mark in word for mark in _KEYISH): - return () # a second key rides in the verb half — the atom says more than these + return () # a second key is in the verb half. The atom says more than these keys. return tuple(keys) def strip_lane_atoms(hint: str, lane: Lane) -> str: - """``hint`` with every atom the lane already advertises removed. + """``hint`` with each atom that the lane already advertises removed. - Where both a hint line and the lane are drawn at once — a floating dialog on the - PicoCalc, whose box carries the hint in its border while the frame's footer row below - carries *its* lane — an atom whose keys are all chips is the same statement twice, in - two notations, and the cells are the dialog's to spend on what the lane doesn't say. - An atom survives unless **every** key it names is a slot's action: a lane covering - only half of ``Home/End ends`` leaves the whole atom standing rather than telling half - a truth. + Sometimes a hint line and the lane are drawn at the same time: for example, a floating + dialog on the PicoCalc. Its box has the hint in its border, while the footer row of + the frame below it has the lane of the frame. Then an atom whose keys are all chips is + the same statement two times, in two notations. The dialog can use those cells for + what the lane does not say. An atom stays unless **each** key that it names is the + action of a slot. If a lane covers only half of ``Home/End ends``, the full atom + stays, and does not tell half of a truth. - Dimmed slots count as covering. A dim chip keeps its label and means *a thing here, - just not right now* (see the module docstring) — the reader has been told where the - action lives either way, which is all the hint atom was for. + Dim slots also cover their keys. A dim chip keeps its label and means "a thing here, + but not now" (refer to the module docstring). In both cases, the user knows where the + action is, and that was the only purpose of the hint atom. - Runs per paint, never once at construction: a screen rewrites its hint as its content - changes (the packet viewer drops to a bare ``Esc close`` on a single packet) and reads - its lane fresh on every frame, so the overlap between the two is a property of *this* - paint. + This function runs at each paint, never one time at construction. A screen writes its + hint again when its content changes (on a single packet, the packet viewer changes to + a bare ``Esc close``). It also reads its lane again on each frame. Thus the overlap + between the two is a property of this paint. Args: - hint: The screen's footer hint, in the standard ``a · b · Esc x`` grammar. - lane: The lane drawn on the same frame. + hint: The footer hint of the screen, in the standard ``a · b · Esc x`` grammar. + lane: The lane that is drawn on the same frame. Returns: - The kept atoms, rejoined in order; ``""`` when the lane says all of it. + The atoms that stay, joined again in order. ``""`` when the lane says all of it. """ covered = { action diff --git a/meshterm/ui/tui/frame.py b/meshterm/ui/tui/frame.py index a85bf77..645ba58 100644 --- a/meshterm/ui/tui/frame.py +++ b/meshterm/ui/tui/frame.py @@ -1,9 +1,10 @@ # SPDX-License-Identifier: Apache-2.0 -"""Composition helpers: turn a screen + terminal size into a bounded, framed ANSI view. +"""Composition helpers: change a screen and a terminal size into a bounded ANSI frame. -The session owns input and the screen stack; this module owns *layout* — slicing a screen's -body to a scroll viewport, wrapping it in a titled panel, and assembling the persistent -header and footer so the whole view fits the terminal exactly (never overflowing it). +The session owns the input and the screen stack. This module owns the layout. It slices the +body of a screen to its viewport, wraps it in a panel with a title, and assembles the +persistent header and footer. Thus the whole frame fits the terminal exactly, and never goes +past it. """ from __future__ import annotations @@ -24,36 +25,38 @@ from . import fkeys from .render import crop_cells, render_lines, render_to_ansi from .screen import Screen -#: How many times :func:`_visible_slice` re-settles the scroll against the rows a screen -#: pins above it. Each pin costs a content row, so gaining one can push the highlighted row -#: back out of view and call for another nudge; two or three passes always reach a fixed -#: point at the pin counts screens actually use (a column header and a section heading). +#: How many times :func:`_visible_slice` settles the scroll again against the rows that a +#: screen pins above it. Each pin costs a content row. Thus one more pin can push the +#: highlighted row out of the viewport again, and make another small move necessary. +#: Two or three passes always get to a fixed point with the pin counts that screens use (a +#: column header and a section heading). _PIN_SETTLE_PASSES = 3 -#: Rows the splash may shear off the *top* of the wordmark when the terminal is too short -#: to hold the whole block. Both marks are drawn as a globe standing over the lettering, and -#: the globe is decoration: on a short screen the box below it — the device list, the PIN -#: prompt — is what the user came for. Cropping from the top keeps the lettering and its -#: copyright sitting exactly where they were, so the mark thins rather than moves. The art's -#: own height bounds this, so a mark drawn without a globe is never sheared into its letters. +#: The rows that the splash can cut off the top of the wordmark when the terminal is too +#: short for the whole block. Both marks show a globe above the lettering, and the globe is +#: decoration. On a short terminal, the box below it (the device list, the PIN prompt) is +#: what the user came for. A crop from the top keeps the lettering and its copyright exactly +#: where they were, so the mark becomes thinner and does not move. The height of the art +#: itself limits this crop, so a mark with no globe is never cut into its letters. _BANNER_CROP_ROWS = 9 def _window_start( scroll: int, total: int, viewport: int, pinned: int, cursor: int | None = None ) -> int: - """The body line the visible window starts at, given ``pinned`` reserved top rows. + """The body line at which the viewport starts, with ``pinned`` reserved top rows. - Normally the scroll offset itself. Scrolled fully to the bottom, the reserved rows must - not cost the *last* body lines (a chat's input row would vanish exactly when the - transcript fills the screen), so the window slides down by as many rows as are pinned — - the lines it drops are at the top, right under the pins, where they are stale. + Usually this is the scroll offset itself. When the page is scrolled fully to the + bottom, the reserved rows must not cost the last body lines. (If they do, the input row + of a chat disappears exactly when the transcript fills the screen.) Thus the viewport + slides down by the number of pinned rows. The lines that it removes are at the top, + directly under the pins, where they are stale. - Except the ``cursor``'s, which is never stale: the slide stops at the highlighted line. - A reader walking ↑ back up a list that is still scrolled to its bottom reaches the - window's top line with the scroll yet to move, and a slide past that line hid the very - row they had just stepped onto. Where the two cannot share the window the highlight - keeps its row and the last line waits below the ``↓`` marker. + The exception is the line of the ``cursor``, which is never stale: the slide stops at + the highlighted line. A user who walks ↑ back up a list that is still scrolled to its + bottom gets to the top line of the viewport before the scroll moves. A slide past that + line hid the row that the user stepped onto a moment before. When the two cannot share the + viewport, the highlight keeps its row, and the last line waits below the ``↓`` marker. """ cap = max(1, viewport - pinned) if scroll >= total - viewport and total > cap: @@ -63,9 +66,10 @@ def _window_start( def _cursor_side(cursor: int | None, start: int, rows: int) -> int: - """Where a window of ``rows`` lines from ``start`` leaves ``cursor``: 0 in it, -1 above, +1 below. + """Where a viewport of ``rows`` lines from ``start`` puts ``cursor``: 0 in, -1 above, +1 below. - No highlight at all counts as in view — there is nothing to bring back. + If there is no highlight, the result is 0 (in the viewport): there is nothing to bring + back. """ if cursor is None or start <= cursor < start + rows: return 0 @@ -73,34 +77,37 @@ def _cursor_side(cursor: int | None, start: int, rows: int) -> int: def _visible_slice(screen: Screen, lines: list[str], viewport: int) -> tuple[list[str], bool, bool]: - """Clamp the screen's scroll and return the visible lines plus clip flags. + """Clamp the scroll of the screen, and return the visible lines and the clip flags. - Keeps the screen's cursor line in view (for select/text screens) and clamps the scroll - offset to the content, then pads the slice to exactly ``viewport`` rows so the panel - always fills its allotted height. Any sticky rows the screen offers (a grouped list's - section heading that has scrolled off, over a table's column header — see - :meth:`Screen.sticky_rows`) are pinned to the top rows: each reserves one row, so the - cursor is kept within the remaining ``viewport - pinned`` and the bottom clamp is relaxed - by as many so the final content row can still reach the last visible line. + The function keeps the line of the highlight visible (for select and text screens), and + clamps the scroll offset to the content. Then it pads the slice to exactly ``viewport`` + rows, so that the panel always fills its height. The screen can offer sticky rows (refer + to :meth:`Screen.sticky_rows`): for example, the section heading of a grouped list that + scrolled off, above the column header of a table. These rows are pinned to the top rows, + and each one reserves one row. Thus the highlight is kept in the remaining + ``viewport - pinned`` rows, and the bottom clamp is relaxed by the same number, so that + the last content row can still get to the last visible line. Args: - screen: The screen being rendered (its ``scroll`` is adjusted in place). - lines: The screen's full, unclipped body lines. - viewport: The visible body height in rows. + screen: The screen to render (its ``scroll`` is changed in place). + lines: All the body lines of the screen, not clipped. + viewport: The height of the visible body in rows. Returns: A tuple of (padded visible lines, more-above, more-below). """ total = len(lines) - # Record the body height and viewport so the screen's shared scroll helpers can page by a - # screenful and clamp to the content (see :meth:`Screen.note_metrics`). + # Record the body height and the viewport, so that the shared scroll helpers of the + # screen can page by one screen height and clamp to the content (refer to + # :meth:`Screen.note_metrics`). screen.note_metrics(total, viewport) cursor = screen.cursor_line() - # Edge scroll: the arrows pressed since the last paint get their verdict first — one - # that left the highlight where it was scrolls the page instead (Screen.note_highlight). - # A page scrolled past its highlight leaves it where it is, off screen if need be, until - # a key brings it back (see Screen.edge_scroll) — so only a page that isn't - # edge-scrolled has its highlight followed. + # Edge scroll: first, find the result of the arrow keys pressed since the last paint. An + # arrow key that did not move the highlight scrolls the page instead + # (Screen.note_highlight). A page scrolled past its highlight leaves the highlight where + # it is, off the screen if necessary, until a key brings it back (refer to + # Screen.edge_scroll). Thus the frame follows the highlight only on a page that is not + # edge-scrolled. screen.note_highlight(cursor, lines) follow = None if screen.edge_scrolled else cursor @@ -112,11 +119,12 @@ def _visible_slice(screen: Screen, lines: list[str], viewport: int) -> tuple[lis scroll = follow - viewport + 1 scroll = max(0, min(scroll, max(0, total - viewport))) - # Each pinned row takes a top row, leaving that many fewer for content: nudge the scroll - # down if the cursor would fall in the reserved rows, then re-ask — moving can change - # which heading governs (crossing a section boundary pins another, or none), and a pin - # gained that way reserves one more row, which can call for a further nudge. Settles - # within _PIN_SETTLE_PASSES, since a screen pins at most a column header and a heading. + # Each pinned row takes a top row, and the content gets that many fewer rows. Move the + # scroll down a little if the highlight falls in the reserved rows, then ask again. A move + # can change which heading applies (when the move crosses a section boundary, it pins a + # different heading, or none). A pin that the move adds reserves one more row, which can + # make another small move necessary. The loop settles within _PIN_SETTLE_PASSES, because + # a screen pins at most a column header and a heading. pinned = screen.sticky_rows(scroll) if scroll > 0 else [] for _ in range(_PIN_SETTLE_PASSES): cap = max(1, viewport - len(pinned)) @@ -130,10 +138,11 @@ def _visible_slice(screen: Screen, lines: list[str], viewport: int) -> tuple[lis if pinned: start = _window_start(scroll, total, viewport, len(pinned), follow) if start != scroll: - # The window slid down off the scroll offset, so the pins must describe the row - # it now *starts* at — otherwise a section heading among the dropped lines would - # simply vanish instead of being pinned. Re-ask, then re-settle the start against - # however many rows that reserves (never unpinning: the slide depends on it). + # The viewport slid down from the scroll offset, so the pins must describe the row + # at which it now starts. If not, a section heading in the removed lines + # disappears, and is not pinned. Ask again, then settle the start again against + # the number of rows that this reserves (never remove the pins: the slide + # depends on them). pinned = screen.sticky_rows(start) or pinned start = _window_start(scroll, total, viewport, len(pinned), follow) cap = max(1, viewport - len(pinned)) @@ -152,17 +161,18 @@ def _visible_slice(screen: Screen, lines: list[str], viewport: int) -> tuple[lis def _breathing_room(body_len: int, budget: int) -> int: - """Rows of blank vertical padding a content-sized box should draw inside its borders. + """The rows of blank vertical padding that a box of content size draws in its borders. - Every popup box (:func:`compose_dialog` floats and the :func:`compose_startup` splash - boxes alike) aerates its layout with a blank row above and below the body whenever that - doesn't cost visible content; on a terminal too short for both, the content wins and the - box sits flush. Full-screen panels (:func:`compose_base`) deliberately skip this — they - hold dense content and would only waste rows. + Each dialog box (the :func:`compose_dialog` floats, and also the :func:`compose_startup` + splash boxes) adds a blank row above and below the body, when this costs no visible + content. On a terminal that is too short for both, the content has priority and the box + has no padding. Full-screen panels (:func:`compose_base`) do not use this padding, on + purpose. They hold dense content, and the padding only uses rows to no purpose. Args: - body_len: The body's full height in rows. - budget: Rows the box may spend between its borders — on body and padding alike. + body_len: The full height of the body in rows. + budget: The rows that the box can use between its borders, for the body and for + the padding. Returns: The vertical padding (1 or 0) to pass to the panel. @@ -179,28 +189,27 @@ def _panel_box( caption: str = "", flush: bool = False, ) -> Panel: - """Wrap already-sliced body lines in a titled, scroll-aware panel. + """Wrap body lines that are already sliced in a panel with a title and scroll arrows. - The bottom rule carries up to two things, and they share one subtitle rather than - fighting over the line. The clip arrows sit centred as they always have. A - ``caption`` — a screen's :attr:`~meshterm.ui.tui.screen.Screen.bottom_caption`, which - today means the map's OpenStreetMap credit — is **right-justified**, so it lands as - ``──── © OpenStreetMap ─╯``: one rule cell before the corner, the mirror of the way - the title sits in the top rule, and not one cell of the body given up for it. Where - both are wanted the caption joins the arrows in the same run and the run moves right, - because the arrows are the half a reader is looking *for* and the caption is the half - that must simply be present — dropping either would be the frame deciding something - neither screen asked it to. + The bottom rule can carry two things, and they share one subtitle instead of a fight for + the line. The clip arrows are centred, as always. A ``caption`` is **right-justified**. + (The caption is the :attr:`~meshterm.ui.tui.screen.Screen.bottom_caption` of a screen. + Today, that is only the OpenStreetMap credit of the map.) Thus it shows as + ``──── © OpenStreetMap ─╯``: one rule cell before the corner, the mirror of the title in + the top rule, and the body gives up no cell for it. When both are necessary, the caption + joins the arrows in the same run, and the run moves right. The user looks for the + arrows, and the caption must only be present. If the frame removes one of them, the + frame decides something that no screen asked for. Args: title: The screen's heading (empty for none). - visible: The viewport's ANSI lines, already sliced and padded to height. + visible: The ANSI lines of the viewport, already sliced and padded to height. more_above: Whether content continues above the slice. more_below: Whether content continues below the slice. - border: Border style name (``"accent"`` for the focused screen). - caption: A short muted credit for the bottom rule's right end (empty for none). - flush: Drop the one-column padding inside each side border, for a body that fills - the frame (see :attr:`~meshterm.ui.tui.screen.Screen.flush`). + border: The name of the border style (``"accent"`` for the focused screen). + caption: A short muted credit for the right end of the bottom rule (empty for none). + flush: Remove the one-cell padding inside each side border, for a body that fills + the frame (refer to :attr:`~meshterm.ui.tui.screen.Screen.flush`). Returns: A Rich :class:`Panel` of exactly ``len(visible) + 2`` rows. @@ -223,48 +232,51 @@ def _panel_box( def panel_inset(flush: bool) -> int: - """Columns the bordered base frame takes from the body's width. + """The cells that the base frame with a border takes from the width of the body. - Its two side borders, plus the padding column inside each unless the screen is - :attr:`~meshterm.ui.tui.screen.Screen.flush`. One definition, because the session sizes - a screen against this frame before the frame is drawn (``base_body_size``). + These are its two side borders, plus the padding cell inside each border, unless the + screen is :attr:`~meshterm.ui.tui.screen.Screen.flush`. There is one definition, because + the session sizes a screen against this frame before the frame is drawn + (``base_body_size``). """ return 2 if flush else 4 -#: The last framed base composition: ``(content key, rendered lines)``. Re-parsing the -#: sliced body (``Text.from_ansi``) and re-rendering it through the Panel is the priciest -#: part of a repaint (~8 ms on a full frame), and the idle tick recomposes an unchanged -#: screen every second — only the header above it moves. One slot suffices: there is only -#: ever one base screen per paint, and any content change (a keystroke, a scroll, new -#: rows) simply misses and re-renders. +#: The last base composition with a border: ``(content key, rendered lines)``. To parse +#: the sliced body again (``Text.from_ansi``) and render it again through the Panel is the +#: most costly part of a paint (approximately 8 ms on a full frame). The idle tick composes +#: an unchanged screen again each second, and only the header above it moves. One slot is +#: sufficient: there is only one base screen for each paint. Each change of content (a key +#: press, a scroll, new rows) misses the cache and renders again. _BASE_BOX_CACHE: tuple[tuple, list[str]] | None = None -#: The screen's own way out, lifted off the end of its footer hint. The grammar is -#: mandated — "navigation keys, then action keys, **Esc last**" — so the last atom is the -#: Esc clause wherever a screen has one, and its verb is the true one for that surface -#: (``back`` on a screen, ``keep`` in a value picker). The main menu is the one screen -#: whose way out is not Esc, which is inert there: its hint ends on ``^Q quit?`` instead, -#: until a typed filter puts ``Esc clear`` after it. +#: The way out of the screen, taken from the end of its footer hint. The grammar is a rule: +#: "navigation keys, then action keys, **Esc last**". Thus the last atom is the Esc clause +#: when a screen has one, and its verb is the correct verb for that surface (``back`` on a +#: screen, ``keep`` in a value picker). The main menu is the one screen whose way out is not +#: Esc, because Esc does nothing there. Its hint ends on ``^Q quit?`` instead, until a typed +#: filter puts ``Esc clear`` after it. _WAY_OUT_ATOM = re.compile(r"(?:^|·\s*)(Esc\s+\S+|\^[A-Z]\s+quit\??)\s*$") -#: Rule cells the title keeps on each side before the bar gives the Esc hint back. Below -#: this the title is being crowded, which is the one thing the hint must not do. +#: The rule cells that the title keeps on each side before the bar removes the Esc hint. +#: With fewer cells, the hint crowds the title, and that is the one thing that the hint must +#: not do. _MIN_RULE = 2 def fitted_title(screen: Screen, room: int) -> str: - """The heading to draw in ``room`` cells: the full title, or its short form where it won't fit. + """The heading for ``room`` cells: the title, or its short form if the title is too long. - A title that states figures (``Contacts · 198 known + 123 archived``) would otherwise be - cut by the rule it sits in, and the cut takes the end — the last figure. A screen that - declares a :attr:`~meshterm.ui.tui.screen.Screen.short_title` gets that instead, the same - atoms said tighter; one with none keeps its title and the frame's usual clipping. + If not, the rule cuts a title that states figures (``Contacts · 198 known + 123 + archived``), and the cut removes the end: the last figure. A screen that declares a + :attr:`~meshterm.ui.tui.screen.Screen.short_title` gets that short title instead, with + the same atoms in fewer cells. A screen with no short title keeps its title and the usual + clipping of the frame. Args: screen: The screen whose heading is drawn. - room: Cells the heading may take, not counting the space either side of it. + room: The cells that the heading can take, without the space on each side of it. """ if screen.short_title and cell_len(screen.title) > room: return screen.short_title @@ -272,7 +284,7 @@ def fitted_title(screen: Screen, room: int) -> str: def _way_out(hint: str) -> str: - """The way-out atom a screen's footer hint ends on (``Esc …``, ``^Q quit?``), or ``""``.""" + """The way-out atom at the end of a footer hint (``Esc …``, ``^Q quit?``), or ``""``.""" found = _WAY_OUT_ATOM.search(hint or "") return found.group(1) if found else "" @@ -284,75 +296,77 @@ def _title_bar( more_below: bool, status: Text | None = None, ) -> Text: - """The borderless frame's one-row title bar: clip arrows, a centered title, the way out. + """The one-row title bar of a borderless frame: clip arrows, a centred title, the way out. - The Panel border's whole vocabulary — where you are (title) and whether the body - continues (the ``↑↓ more`` subtitle) — compressed into a single row so the body wins - back three rows and four columns on the PicoCalc. Shape: - ``↑↓ ──── Title ─────── Esc back``, echoing - :func:`~meshterm.ui.menus.section_heading`'s heading language. + The bar puts the whole vocabulary of the Panel border in a single row: where you are + (the title), and if the body continues (the ``↑↓ more`` subtitle). Thus the body gets + back three rows and four cells of width on the PicoCalc. The shape is + ``↑↓ ──── Title ─────── Esc back``, which repeats the heading language of + :func:`~meshterm.ui.menus.section_heading`. - **The clip arrows lead the row, and both are always drawn** (JP, 2026-08-31). A pair - that appeared and vanished — and, half-shown, left a blank cell standing in for the - arrow that wasn't there — made the reader compare the row against a memory of itself - to learn something the row could simply state. So the pair is fixed furniture at the - left edge, where the eye starts, and **colour** carries the reading: an arrow whose - direction has more takes the border's own ``accent``, so it reads as part of the - frame; one with nothing that way drops to ``muted``. That is the same live/dim - language the F-key lane draws one row below (a dim chip keeps its label and loses its - fill), and the two are the platform's only two indicators. + **The clip arrows are at the start of the row, and the bar always draws both** (JP, + 2026-08-31). A pair that appeared and disappeared made the user compare the row with a + memory of it, to learn something that the row can state directly. (When only one arrow + showed, a blank cell stood in for the other.) Thus the pair is fixed at the left edge, + where the eye starts, and **colour** gives the information. An arrow whose direction + has more content takes the ``accent`` of the border, so it looks like part of the + frame. An arrow with nothing in its direction becomes ``muted``. This is the same + live/dim language that the F-key lane draws one row below (a dim chip keeps its label + and loses its fill). The two are the only indicators of the platform. - The title is centered in the rule between the arrows and the tail, exactly as Rich's - ``Panel`` centers its own ``title`` — the desktop's bordered frame this one stands in - for. The rule itself takes ``border_style`` (``"accent"``) directly, the same bold - weight a real border draws in, rather than :func:`~meshterm.ui.theme.hint_style`'s - muted variant, which is for auxiliary text riding *alongside* a border (the Esc atom - below, a footer hint on the other platform). + The title is centred in the rule between the arrows and the tail, exactly as the Rich + ``Panel`` centres its own ``title``. (That panel is the frame with a border on the + desktop, which this bar replaces.) The rule itself takes ``border_style`` + (``"accent"``) directly: the same bold weight that a real border has. It does not take + the muted variant of :func:`~meshterm.ui.theme.hint_style`, which is for secondary text + next to a border (the Esc atom below, a footer hint on the other platform). - The bar's tail carries **the way out** (JP, 2026-08-30). This platform has no footer - hint line — the F-key lane stands where it would be, and the lane advertises only what - its five slots do — so nothing on the screen said that Esc leaves, which is the one key - every screen answers to and the reason no screen spends a row on a *Back* item. The - verb is the screen's own (:func:`_way_out` lifts the atom off its footer hint, so a - value picker says ``keep``, and the main menu, where Esc is inert, says ``^Q quit?``); - a screen whose hint names no way out gets nothing. Compact by construction: where a - long title would be crowded, the atom drops to its bare key and then out - altogether — the title is what the reader came for, and the arrows are two cells - nothing else can spend. + The tail of the bar carries **the way out** (JP, 2026-08-30). This platform has no + footer hint line. The F-key lane is in its place, and the lane shows only what its five + slots do. Thus nothing on the screen said that Esc leaves. But Esc is the one key that + all screens answer to, and it is the reason why no screen uses a row for a *Back* item. + The verb comes from the screen (:func:`_way_out` takes the atom from its footer hint). + Thus a value picker says ``keep``, and the main menu, where Esc does nothing, says + ``^Q quit?``. A screen whose hint names no way out gets nothing. - Where the platform has **no header row** (the Cardputer, JP 2026-10-03), the header's - atoms arrive as ``status`` and are pinned to the bar's right end, after the way out: - ``↑↓ ── Title ──── Esc back ● 3 ⣷ 87%``. That is the top-right corner the badges and - battery always had, one row up, and every screen gets the header's row back. The status - gives way to nothing — an unread count and a dying battery are what it exists to say — - so the way out sheds first, as it does for a long title, and a title too long even then - is cut short on an ellipsis rather than pushing the status off the end of the row. + The design keeps the bar compact. When a long title has too little space, the atom + becomes only its key, then disappears. The title is what the user came for, and the + arrows are two cells that nothing else can use. + + When the platform has **no header row** (the Cardputer, JP 2026-10-03), the atoms of + the header arrive as ``status``. They are pinned to the right end of the bar, after the + way out: ``↑↓ ── Title ──── Esc back ● 3 ⣷ 87%``. That is the top-right corner that the + badges and the battery always had, one row higher, and each screen gets the header row + back. The status gives way to nothing, because it exists to tell an unread count and a + battery that is almost empty. Thus the way out goes first, as it does for a long title. + If the title is still too long, it is cut with an ellipsis, and does not push the + status off the end of the row. Args: screen: The screen whose heading the bar carries. - cols: Bar width in cells. + cols: The width of the bar in cells. more_above: Whether the body continues above the viewport. more_below: Whether the body continues below it. - status: The header's atoms, for a platform without a header row; ``None`` (or + status: The atoms of the header, for a platform without a header row. ``None`` (or empty: nothing unread, no pack) draws the bar exactly as it is with a header. """ border = "accent" - head_span = 3 # the arrow pair, plus the space parting it from the rule + head_span = 3 # the arrow pair, plus the space between it and the rule status = status if status is not None and status.cell_len else None - stat_span = status.cell_len + 1 if status else 0 # the space in front of the status - # The short form is chosen against the bar with no Esc tail at all: the title is what - # the reader came for, so the tail gives way to it before it gives way to the tail. + stat_span = status.cell_len + 1 if status else 0 # the space before the status + # The short form is chosen against the bar with no Esc tail: the title is what the user + # came for. Thus the tail gives way to the title before the title gives way to the tail. title = fitted_title(screen, cols - head_span - stat_span - 2 - 2 * _MIN_RULE) - label_w = cell_len(title) + 2 if title else 0 # a space either side + label_w = cell_len(title) + 2 if title else 0 # a space on each side atom = _way_out(screen.footer_hint) for esc in (atom, atom.split()[0] if atom else "", ""): - tail_span = cell_len(esc) + 1 if esc else 0 # the space in front of the tail + tail_span = cell_len(esc) + 1 if esc else 0 # the space before the tail if not esc or cols - head_span - tail_span - stat_span - label_w >= 2 * _MIN_RULE: break rule_span = max(0, cols - head_span - tail_span - stat_span) heading = screen.bar_title(title, title_style(border)) if title else Text() if status and label_w > rule_span - 2: - # A rule cell either side, and whatever is left for the title; the status stays. + # One rule cell on each side, and the remaining cells for the title. The status stays. heading.truncate(max(1, rule_span - 4), overflow="ellipsis") label_w = heading.cell_len + 2 @@ -380,14 +394,14 @@ def _title_bar( def header_lines(header: Text, cols: int) -> list[str]: - """The header's rows above the frame: its one line, or none where it has no row. + """The header rows above the panel: its one line, or none where it has no row. - The header is a single status line, cropped to one row so a narrow terminal never wraps - it onto a second (which would push the panel down and misreport its height). A platform - without a header row (:attr:`~meshterm.platforms.Platform.header_row`) draws none here — - the title bar carries the header's atoms instead (see :func:`_title_bar`) — and this is - the one place that says so, for :func:`compose_base` and for the session sizing a body - against it alike. + The header is a single status line, cropped to one row, so that a narrow terminal never + wraps it onto a second row. (A second row pushes the panel down and gives a wrong height + for it.) A platform without a header row (:attr:`~meshterm.platforms.Platform.header_row`) + draws no header here. The title bar carries the atoms of the header instead (refer to + :func:`_title_bar`). This function is the one place that says so, for + :func:`compose_base` and also for the session when it sizes a body against it. """ if not get_platform().header_row: return [] @@ -402,23 +416,25 @@ def compose_base( rows: int, footer_lane: Callable[[], RenderableType] | None = None, ) -> str: - """Compose the full-screen ANSI view: header, the base screen's panel, and a footer. + """Compose the full-screen ANSI frame: the header, the base screen's panel, and a footer. Args: - header: The persistent header (banner + live status) — a row of its own, or, on a - platform without a header row, the title bar's right end (see + header: The persistent header (banner and live status). It is a row of its own, or + the right end of the title bar on a platform without a header row (refer to :func:`header_lines`). - base: The screen filling the background (the deepest non-floating layer). - footer_hint: The active screen's key hint, shown at the very bottom. + base: The screen that fills the background (the deepest layer that does not + float). + footer_hint: The key hint of the active screen, shown at the bottom. cols: Terminal width. rows: Terminal height. - footer_lane: Builds the footer row (the PicoCalc F-key lane) that replaces the - hint string when the platform runs fixed F-key hints. Called *after* the body - renders, since a lane dims its slots from the screen's scroll metrics — which - this paint has only just recorded (see :func:`~meshterm.ui.tui.fkeys.default_lane`). + footer_lane: A function that builds the footer row (the PicoCalc F-key lane). That + row replaces the hint string when the platform uses fixed F-key hints. It is + called after the body renders, because a lane dims its slots from the scroll + metrics of the screen. This paint records these metrics only a moment before + (refer to :func:`~meshterm.ui.tui.fkeys.default_lane`). Returns: - An ANSI string of exactly ``rows`` lines, each within ``cols`` columns. + An ANSI string of exactly ``rows`` lines, each not wider than ``cols`` cells. """ global _BASE_BOX_CACHE platform = get_platform() @@ -426,30 +442,30 @@ def compose_base( header_h = len(head) def footer_row() -> RenderableType: - """The bottom line: the platform's F-key lane, else the muted hint string.""" + """The bottom line: the F-key lane of the platform, or else the muted hint string.""" if footer_lane is not None: return footer_lane() return Text.from_markup(f"[muted]{footer_hint}[/muted]") if platform.frame_border: viewport = max(1, rows - header_h - 1 - 2) # minus footer(1) and panel border(2) - # Record the viewport *before* the body renders, so a screen that windows a - # list inside itself (see :class:`~meshterm.ui.tui.screen.ListWindow`) can size - # its chrome to the frame it is about to be sliced into. + # Record the viewport before the body renders. Thus a screen with a list window + # (refer to :class:`~meshterm.ui.tui.screen.ListWindow`) can size its chrome to the + # frame into which it will be sliced. base.note_viewport(viewport) body_lines = base.render_body(cols - panel_inset(base.flush)) visible, more_above, more_below = _visible_slice(base, body_lines, viewport) - # The panel wrap is a pure function of what's between its borders: memoize it so - # the repaints that change nothing below the header (the 1 Hz tick) skip the - # ANSI re-parse and Panel re-render. A dynamic footer (the F-key lane, which can - # flip with the physical Shift key alone) has no place in the key, so it renders - # uncached — that combination doesn't arise: the lane belongs to the borderless - # platform below. - # The caption belongs in the key like the title does: the map's credit collapses on - # a keystroke that need not change a single body line, and a memo without it would - # keep serving the rule the reader has already grown out of. + # The panel wrap is a pure function of what is between its borders. Thus cache it, + # so that the paints that change nothing below the header (the 1 Hz tick) do not + # parse the ANSI again and do not render the Panel again. A dynamic footer (the F-key + # lane, which can change with only the physical Shift key) has no place in the key, + # so it renders without the cache. But that combination does not occur: the lane + # belongs to the borderless platform below. + # The caption belongs in the key, as the title does. The credit of the map becomes + # short on a key press that does not have to change a body line. If the cache does + # not have the caption, it continues to return the old rule after that key press. caption = base.bottom_caption - # Rich sets the padded title into the rule's inner ``cols - 4`` cells. + # Rich sets the padded title into the inner ``cols - 4`` cells of the rule. title = fitted_title(base, cols - 4 - 2) flush = base.flush key = (cols, rows, title, caption, flush, footer_hint, more_above, more_below, *visible) @@ -461,8 +477,8 @@ def compose_base( if footer_lane is None: _BASE_BOX_CACHE = (key, body) else: - # Borderless chrome: a one-row title bar instead of the Panel's border and - # padding — the body wins the full terminal width and one extra row. + # Chrome with no border: a one-row title bar instead of the border and padding of + # the Panel. The body gets the full terminal width and one more row. viewport = max(1, rows - header_h - 1 - 1) # minus footer(1) and title bar(1) base.note_viewport(viewport) body_lines = base.render_body(cols) @@ -475,7 +491,8 @@ def compose_base( + render_lines(footer_row(), cols, no_wrap=True) ) lines = head + body - # Guarantee we never exceed the terminal height (pt would otherwise clip unpredictably). + # Make sure that the frame is never taller than the terminal. If it is taller, pt clips it + # in a way that we cannot predict. if len(lines) > rows: lines = lines[:rows] else: @@ -484,12 +501,12 @@ def compose_base( def _ansi_width(line: str) -> int: - """Return the display width of an ANSI line, ignoring its trailing padding.""" + """Return the width in cells of an ANSI line, without its trailing padding.""" return cell_len(Text.from_ansi(line).plain.rstrip()) def _center(lines: list[str], cols: int) -> list[str]: - """Left-pad each ANSI line so the block is horizontally centered within ``cols``.""" + """Pad each ANSI line on the left, so that the block is centred horizontally in ``cols``.""" out: list[str] = [] for line in lines: pad = max(0, (cols - cell_len(Text.from_ansi(line).plain)) // 2) @@ -498,15 +515,15 @@ def _center(lines: list[str], cols: int) -> list[str]: def _banner_lines(banner: Sequence[str], cols: int) -> list[str]: - """Center the wordmark rows (already-coloured ANSI) as one left-aligned block. + """Centre the wordmark rows (ANSI that already has colour) as one left-aligned block. - Each row is padded to the block's widest display width first, so the shared left margin - keeps the art internally aligned rather than centering every row on its own axis. + First, each row is padded to the widest width of the block. Thus the shared left margin + keeps the art aligned in itself, and each row is not centred on its own axis. - The rows are art, not renderables, so they never pass through - :func:`~meshterm.ui.tui.render.render_to_ansi` — the fold is applied here instead, and - the wordmark's truecolour lands on the palette slots the art was drawn against rather - than on whatever the console's own downsample picks. + The rows are art, not renderables, so they never go through + :func:`~meshterm.ui.tui.render.render_to_ansi`. Thus the fold is applied here instead. + The truecolour of the wordmark then goes to the palette slots for which the art was + drawn, not to the slots that the downsample of the console selects. """ if not banner: return [] @@ -516,28 +533,29 @@ def _banner_lines(banner: Sequence[str], cols: int) -> list[str]: return _center(padded, cols) -#: The wordmark as the splash last drew it: ``(banner, cols)`` and what that came to. One -#: slot, because there is one splash and one terminal size at a time. +#: The wordmark as the splash last drew it: ``(banner, cols)`` and the result. One slot, +#: because there is one splash and one terminal size at a time. _BANNER_CACHE: tuple[tuple, tuple[list[str], int]] | None = None def _fitted_banner(banner: Sequence[str], cols: int) -> tuple[list[str], int]: - """The wordmark drawn at ``cols`` — fitted, folded and centred — and the art's width. + """The wordmark drawn at ``cols`` (fitted, folded, and centred), and the width of the art. - Fitting the mark is the dearest thing the splash draws: a mark wider than the terminal - sends :func:`~meshterm.ui.logo.load_logo` back to the disk for every size until one - fits, each one parsed and measured, and then every row is decoded again to centre it. - None of that moves from one paint to the next, and the splash paints on every keystroke - and every idle tick. Done fresh each time it was nine-tenths of a splash frame at - 53×26, which on the PicoCalc put a visible wait behind every ↑↓ on the device list. + To fit the mark is the most costly thing that the splash draws. If a mark is wider than + the terminal, :func:`~meshterm.ui.logo.load_logo` goes back to the disk for each size + until one fits. It parses and measures each one, and then each row is decoded again to + centre it. None of that changes from one paint to the next, and the splash paints on + each key press and each idle tick. When this was done again each time, it took + nine-tenths of a splash frame at 53×26. On the PicoCalc, that caused a visible wait + after each ↑↓ on the device list. Args: - banner: The wordmark rows the screen names (usually the full-size mark). + banner: The wordmark rows that the screen names (usually the full-size mark). cols: Terminal width. Returns: - The centred rows to draw — shared with the memo, so never mutate them — and the - display width of the mark actually chosen, for hanging the footnote off its edge. + The centred rows to draw, and the width in cells of the mark that was chosen, to + align the footnote with its edge. The cache shares the rows, so never change them. """ global _BANNER_CACHE key = (tuple(banner), cols) @@ -552,30 +570,31 @@ def _fitted_banner(banner: Sequence[str], cols: int) -> tuple[list[str], int]: def fit_hint(hint: str, width: int, *, shed_first: Sequence[str] = ()) -> str: - """Drop ``·`` atoms from a footer hint, right to left, until it fits ``width``. + """Remove ``·`` atoms from a footer hint, from right to left, until it fits ``width``. - The chromeless splash has one row of border for its hint and a box no wider than the - terminal less its gutter — 47 cells on the PicoCalc — while the hint itself grows as the - highlight moves onto a row with more keys to offer. Cutting the line at the edge takes - the *end* of it, and the end is ``Esc``: the one atom that must survive, being the only - way out. So atoms are dropped instead, from the right and never the last one, which - spends the cells on the keys nearest the front of the sentence — the ones that move and - commit — and gives up the optional ones a screen advertises elsewhere. + The chromeless splash has one border row for its hint, and a box that is not wider than + the terminal minus its gutter (47 cells on the PicoCalc). But the hint grows when the + highlight moves onto a row with more keys to offer. A cut of the line at the edge + removes its end, and the end is ``Esc``: the one atom that must stay, because it is the + only way out. Thus the function removes atoms instead, from the right, and never the + last one. The cells then go to the keys nearest the front of the sentence (the keys that + move and commit). The function gives up the optional atoms, which a screen shows in + other places. - ``shed_first`` overrides that order for atoms whose key the reader would find anyway. A - scroll atom is the example: ←→ are the keys already named by the leading move atom, so - trying them costs nothing and teaches the rest, while a bare-letter shortcut is - unguessable and has nowhere else to be advertised on a chromeless splash. Given the - choice between those two, the sentence keeps the letter. + ``shed_first`` overrides that order for atoms whose key the user finds without the hint. + A scroll atom is the example. The leading move atom already names the ←→ keys, so a try + of these keys costs nothing and shows the rest. But nobody can guess a bare-letter + shortcut, and a chromeless splash has no other place to show it. Between those two, the + sentence keeps the letter. Args: hint: The composed hint sentence. - width: Cells available. - shed_first: Atoms to drop before any others, in the order given. + width: The cells that are available. + shed_first: The atoms to remove before all others, in the given order. Returns: - The hint, or as much of its head plus its final atom as fits (ellipsized only if - even those cannot). + The hint, or as much of its start as fits, plus its last atom. If even those do not + fit, the result is cut with an ellipsis. """ if cell_len(hint) <= width: return hint @@ -586,7 +605,7 @@ def fit_hint(hint: str, width: int, *, shed_first: Sequence[str] = ()) -> str: if spare in atoms: atoms.remove(spare) while len(atoms) > 2 and cell_len(" · ".join(atoms)) > width: - del atoms[-2] # the last atom is Esc's; drop what sits in front of it + del atoms[-2] # the last atom is the Esc atom: remove the atom before it fitted = " · ".join(atoms) if cell_len(fitted) <= width: return fitted @@ -594,58 +613,62 @@ def fit_hint(hint: str, width: int, *, shed_first: Sequence[str] = ()) -> str: def compose_startup(screen: Screen, cols: int, rows: int) -> str: - """Compose a chromeless splash: a centered wordmark above a content-sized panel. + """Compose a chromeless splash: a centred wordmark above a panel of content size. - Unlike :func:`compose_base`, this draws no header or footer status bars and does not - stretch the panel across the terminal — the box is sized to its own content (the device - list) and the whole block is centered on screen. Used for the startup device picker. + This function draws no header or footer status bars, and it does not stretch the panel + across the terminal, as :func:`compose_base` does. The box has the size of its own + content (the device list), and the whole block is centred on the terminal. The startup + device picker uses it. Args: - screen: The chromeless base screen (its ``banner`` supplies the wordmark). + screen: The chromeless base screen (its ``banner`` gives the wordmark). cols: Terminal width. rows: Terminal height. Returns: - An ANSI string of exactly ``rows`` lines, each within ``cols`` columns. + An ANSI string of exactly ``rows`` lines, each not wider than ``cols`` cells. """ - # A screen names its wordmark; the width to draw it at is only known here, so this is - # where the size is chosen — a narrow terminal gets a narrow mark rather than a torn one. - # ``logo_w`` is the chosen mark's own width, so the footnote below can hang off its right - # edge (the wordmark is centered as one block, so every row shares one left margin). + # A screen names its wordmark. Only this function knows the width at which to draw it, + # so the size is chosen here. A narrow terminal gets a narrow mark, not a torn one. + # ``logo_w`` is the width of the chosen mark, so that the footnote below can align with + # its right edge (the wordmark is centred as one block, so all rows share one left + # margin). banner, logo_w = _fitted_banner(screen.banner or (), cols) banner_h = len(banner) gap = 1 if banner else 0 # the blank line under the banner logo_right = max(0, (cols - logo_w) // 2) + logo_w - # Size the box to its widest real row (probe at a generous width, then measure), never - # wider than the terminal and never narrower than the title/hint it must show. + # Size the box to its widest real row (a trial render at a generous width, then a + # measure). It is never wider than the terminal, and never narrower than the title or the + # hint that it must show. probe = max(10, min(cols - 6, 100)) probe_lines = screen.render_body(probe) measured = max((_ansi_width(line) for line in probe_lines), default=10) - # Size to the fullest the footer can get, not this frame's — a screen whose hint grows - # as the highlight moves (a select's per-row "Del remove") reports that width here, so - # the box is reserved for it up front and never widens mid-navigation. + # Size to the widest footer possible, not to the footer of this frame. A screen whose + # hint grows as the highlight moves (the "Del remove" of a select list on some rows) + # gives that width here. Thus the box has space for it from the start, and never + # becomes wider during navigation. sizing_footer = getattr(screen, "sizing_footer_hint", screen.footer_hint) inner_w = max(measured, cell_len(screen.title), cell_len(sizing_footer)) inner_w = max(10, min(inner_w, cols - 6)) - # The hint is fitted to the box rather than cut off by it (see :func:`fit_hint`). + # The hint is fitted to the box, instead of cut by it (refer to :func:`fit_hint`). hint_text = fit_hint( screen.footer_hint, inner_w, shed_first=getattr(screen, "spare_hint_atoms", ()) ) - # The probe render is the answer whenever it was already made at the width we settled - # on — the common case, since a body narrower than the probe *is* what set inner_w. - # The splash repaints on every tick while the device list sits there, and rendering - # the same body twice was a measured third of that paint on the PicoCalc. + # The trial render is the answer when it was already made at the width that we chose. + # That is the usual case, because a body narrower than the trial width is what set + # inner_w. The splash paints on each tick while the device list is visible. A second + # render of the same body was a measured third of that paint on the PicoCalc. body_lines = probe_lines if inner_w == probe else screen.render_body(inner_w) - footnote_h = 1 if screen.footnote else 0 # the note sits directly under the logo + footnote_h = 1 if screen.footnote else 0 # the note is directly under the logo - # A terminal too short for the whole block gives rows back in a fixed order, cheapest - # first: the blank line under the mark (breathing room, and nothing else), then the top - # of the mark itself — the globe over the lettering, up to _BANNER_CROP_ROWS of it. The - # lettering and its copyright are the part that says what this is, so they are the part - # that never moves: the mark thins from above while the box below keeps its rows. Past - # that the block is simply taller than the screen and the trailing clip still applies. + # A terminal too short for the whole block gives back rows in a fixed order, the least + # costly first. First, the blank line under the mark (it is only space). Then the top of + # the mark itself: the globe above the lettering, up to _BANNER_CROP_ROWS of it. The + # lettering and its copyright tell what this is, so they never move. The mark becomes + # thinner from above, and the box below keeps its rows. After that, the block is taller + # than the terminal, and the trailing clip still applies. short = banner_h + footnote_h + gap + len(body_lines) + 2 - rows if short > 0 and gap: gap = 0 @@ -655,14 +678,16 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str: banner_h = len(banner) # Pin the banner to a fixed vertical anchor that depends only on the terminal height and - # the banner's own (constant) height, so the wordmark never moves as the box below it - # swaps contents between splash states (device list → spinner → message). The box hangs - # from just under the banner and only *it* grows or shrinks; the logo stays put. The - # anchor sits at 2/5 of the terminal rather than the midline so the block reads centered - # once the device list has populated (the box only ever grows downward); the brief small - # states sit slightly high, the conventional optical placement for dialogs. + # the (constant) height of the banner. Thus the wordmark never moves when the box below + # it changes contents between splash states (device list → spinner → message). The box + # hangs from directly under the banner, and only the box grows or shrinks. The logo + # stays where it is. The anchor is at 2/5 of the terminal, not at the midline, so that + # the block looks centred when the device list has its rows (the box only grows + # downward). The short states, which are small, are a little high: the usual optical + # placement for dialogs. top = max(0, rows * 2 // 5 - banner_h - gap) - # Rows left for the box below the fixed banner block: the panel border is 2 rows. + # The rows that remain for the box below the fixed banner block. The panel border is + # 2 rows. below = rows - top - banner_h - footnote_h - gap budget = below - 2 vpad = _breathing_room(len(body_lines), budget) @@ -685,8 +710,9 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str: ) panel_lines = _center(render_lines(panel, inner_w + 4), cols) - # A small muted line (e.g. a copyright notice) sits immediately under the logo, its right - # edge hung off the logo's right edge so the two read as one signed block. + # A small muted line (for example a copyright notice) is immediately under the logo. Its + # right edge aligns with the right edge of the logo, so that the two look like one signed + # block. footnote_lines: list[str] = [] if screen.footnote: note = Text.from_markup(f"[muted]{screen.footnote}[/muted]") @@ -706,13 +732,13 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str: def compose_bare(screen: Screen, cols: int, rows: int) -> str: """Compose a bare frame: the screen's body on blank rows, and nothing else. - No header, no footer, no title bar, no box, no wordmark — the frame - :attr:`~meshterm.ui.tui.screen.Screen.bare` asks for. The body is drawn at the - terminal's full width (the screen lays its own rows out across it) and sits a little - above true centre when it is shorter than the frame, the optical placement everything - else here anchors to. A body taller than the frame is windowed from the top and - scrolls, so a code that does not fit is at least whole while the reader is at the top - of it, with the URL under it a page down. + There is no header, no footer, no title bar, no box, and no wordmark: this is the frame + that :attr:`~meshterm.ui.tui.screen.Screen.bare` asks for. The body is drawn at the full + width of the terminal (the screen lays out its own rows across it). When the body is + shorter than the frame, it is a little above the true centre: the optical placement that + all other parts of this module use. A body taller than the frame shows from its top in + the viewport, and scrolls. Thus a QR code that does not fit is at least whole while the + user is at its top, and the URL is under it, one page down. Args: screen: The bare base screen. @@ -720,15 +746,15 @@ def compose_bare(screen: Screen, cols: int, rows: int) -> str: rows: Terminal height. Returns: - An ANSI string of exactly ``rows`` lines, each within ``cols`` columns. + An ANSI string of exactly ``rows`` lines, each not wider than ``cols`` cells. """ - # The height is known here and nowhere else, and a bare screen may size its body - # to it (the share screen fits its code to the rows), so it is noted *before* the - # body is asked for rather than after, the way the framed composers record it. + # Only this function knows the height, and a bare screen can size its body to it (the + # share screen fits its code to the rows). Thus the height is recorded before the body + # is requested, not after, as the composers with a frame also do. screen.note_viewport(rows) body_lines = screen.render_body(cols) while body_lines and not _ansi_width(body_lines[-1]): - body_lines.pop() # a trailing blank row would push the block off its anchor + body_lines.pop() # a trailing blank row pushes the block off its anchor visible, _more_above, _more_below = _visible_slice(screen, body_lines, rows) top = max(0, (rows - len(body_lines)) * 2 // 5) lines = [""] * top + visible[: rows - top] @@ -737,69 +763,72 @@ def compose_bare(screen: Screen, cols: int, rows: int) -> str: def _dialog_layout(screen: Screen, cols: int, rows: int) -> tuple[int, int, int, list[str]]: """Size a floating dialog: ``(outer_width, vpad, viewport, body_lines)``.""" - # Most dialogs stretch to a generous cap; a screen may instead request a natural width - # (a short confirm sized to its content), still bounded to the terminal. A grow-only - # screen's natural width ratchets like its height, so the box never narrows either. - # What the cap leaves behind is the backdrop gutter the box floats over, and how many - # columns that is worth is the platform's call (see Platform.dialog_margin). + # Most dialogs stretch to a generous limit. A screen can request a natural width instead + # (a short confirm sized to its content), still limited to the terminal. The natural + # width of a grow-only screen ratchets like its height, so the box also never becomes + # narrower. The cells that the limit leaves are the backdrop gutter over which the box + # floats. The platform decides how many cells that is (refer to Platform.dialog_margin). cap = min(cols - get_platform().dialog_margin, 100) natural = getattr(screen, "dialog_width", None) max_w = cap if natural is None else max(24, min(cap, screen.ratchet_width(natural))) - # Rows the box may spend between its borders — on body lines and breathing room alike: - # the frame less the two borders and the rows it leaves to the frame around it (the - # header, the footer, and on a tall enough frame a row of air each side — see - # Platform.dialog_row_margin). + # The rows that the box can use between its borders, for body lines and for padding: + # the frame minus the two borders and the rows that it leaves to the frame around it + # (the header, the footer, and a blank row on each side when the frame is tall enough). + # Refer to Platform.dialog_row_margin. budget = max(3, rows - 2 - get_platform().dialog_row_margin) - # Record the budget as the provisional viewport before the body renders, so a - # dialog that windows a list inside itself (the path composer) can size to what - # it may spend; the slice records the real, body-sized viewport afterwards. + # Record the budget as the temporary viewport before the body renders. Thus a dialog + # with a list window (the path composer) can size to what it can use. After that, the + # slice records the real viewport, sized to the body. screen.note_viewport(budget) body_lines = screen.render_body(max_w - 4) - # A grow-only screen (the packet viewer paging between packets) sizes to the tallest - # body it has shown, not this one, so a shorter body keeps the larger box instead of - # re-centring smaller — the frame blank-pads the slack. The breathing room is taken - # from that ratcheted height, so the box stays put as the body shrinks below it. + # A grow-only screen (the packet viewer, when it pages between packets) sizes to the + # tallest body that it has shown, not to this body. Thus a shorter body keeps the larger + # box, and the box does not become smaller and centred again. The frame pads the extra + # rows with blanks. The padding comes from that ratcheted height, so the box stays where + # it is when the body becomes shorter than it. body_h = screen.ratchet_viewport(max(1, len(body_lines))) vpad = _breathing_room(body_h, budget) viewport = min(budget - 2 * vpad, body_h) return max_w, vpad, viewport, body_lines -#: Memoized dialog compositions, keyed by everything the box is a function of. Dialogs -#: stack (a confirm over a picker over a menu), and each layer recomposes on every -#: repaint of the frame beneath it, so a single slot would thrash — a handful covers the -#: deepest realistic stack, LRU-evicted as dialogs change. +#: Cached dialog compositions, with a key of all that the box is a function of. Dialogs +#: stack (a confirm over a picker over a menu), and each layer composes again on each paint +#: of the frame below it. Thus one slot is not sufficient, because it thrashes. A small +#: number covers the deepest realistic stack. When dialogs change, the cache removes the +#: entry that was used least recently. _DIALOG_CACHE: OrderedDict[tuple, str] = OrderedDict() -#: Dialog compositions the memo keeps. +#: The number of dialog compositions that the cache keeps. _DIALOG_CACHE_MAX = 12 def _dialog_hint(screen: Screen) -> str: - """The hint a floating dialog's own border carries — often none at all. + """The hint that the border of a floating dialog carries. Often there is no hint. - A dialog is drawn over a frame that already has a footer row, and *what that row is* - decides whether the box needs to speak at all: + A dialog is drawn over a frame that already has a footer row. The type of that row + decides if the box must show a hint: - - Where the footer is the **hint line** (the desktop), it draws the top screen's hint - — this dialog's — in full, on the row every screen's keys have always been read - from. A subtitle repeating it was the same sentence twice on one frame, once in the - border and once at the bottom of the terminal (JP, 2026-08-31), so the border says - nothing and the box leaves the reader's eye on the one place hints live. - - Where the footer is the **F-key lane** (the PicoCalc), there is no hint line at all - and the lane speaks only for its five chips, so the border is the only thing that - can name Enter, Esc or the arrows — it keeps the hint. What the lane *does* say it - says already, one row below: :func:`~meshterm.ui.tui.fkeys.strip_lane_atoms` lifts - out the atoms whose every key is a chip on that row. + - When the footer is the **hint line** (the desktop), the footer draws the hint of the + top screen (this dialog) in full. It is on the row where the user always reads the + keys of each screen. A subtitle that repeated it put the same sentence two times in + one frame: one time in the border, and one time at the bottom of the terminal + (JP, 2026-08-31). Thus the border says nothing, and the user looks at the one place + where the hints are. + - When the footer is the **F-key lane** (the PicoCalc), there is no hint line, and the + lane shows only its five chips. Thus the border is the only place that can name + Enter, Esc, or the arrow keys, and it keeps the hint. The lane already shows its own + atoms, one row below: :func:`~meshterm.ui.tui.fkeys.strip_lane_atoms` removes the + atoms whose keys are all chips on that row. - Resolved on each paint rather than folded into a screen's hint once, because both - halves move: a screen rewrites its hint as its content changes (the packet viewer - drops to a bare ``Esc close`` on a single packet) and its lane is read fresh every - frame. + The hint is resolved on each paint, instead of one time in the hint of a screen, + because both halves change. A screen writes its hint again when its content changes + (the packet viewer changes to only ``Esc close`` on a single packet), and its lane is + read again for each frame. - The chromeless startup splash is not this case and never passes through here — it has - no footer row of any kind, so :func:`compose_startup` keeps drawing the hint in its - own panel's subtitle on both platforms. + The chromeless startup splash is not this case, and never comes here. It has no footer + row of any type, so :func:`compose_startup` continues to draw the hint in the subtitle + of its own panel on both platforms. """ if not get_platform().footer_fkeys: return "" @@ -807,12 +836,12 @@ def _dialog_hint(screen: Screen) -> str: def _dialog_subtitle(hint: str, more_above: bool, more_below: bool, border: str) -> str | None: - """A floating box's bottom-border legend: the clip arrows, the hint, or both. + """The legend on the bottom border of a floating box: the clip arrows, the hint, or both. - With no hint to carry (the desktop — see :func:`_dialog_hint`) the arrows keep the - base frame's own wording, ``↑↓ more``, exactly as :func:`_panel_box` labels them: a - border that has fallen silent still says the one thing every border here says, in the - vocabulary the frame around it uses. + When there is no hint to carry (the desktop: refer to :func:`_dialog_hint`), the arrows + keep the words of the base frame, ``↑↓ more``, exactly as :func:`_panel_box` labels + them. A border with no hint still says the one thing that all borders here say, in the + vocabulary of the frame around it. """ arrow = "" if more_above or more_below: @@ -824,7 +853,7 @@ def _dialog_subtitle(hint: str, more_above: bool, more_below: bool, border: str) def compose_dialog(screen: Screen, cols: int, rows: int) -> str: - """Compose a centered dialog panel for a floating screen, bounded to the terminal. + """Compose a centred dialog panel for a floating screen, limited to the terminal. Args: screen: The floating (top) screen. @@ -832,13 +861,13 @@ def compose_dialog(screen: Screen, cols: int, rows: int) -> str: rows: Terminal height. Returns: - An ANSI string sized to the dialog's content (never larger than the terminal). + An ANSI string sized to the content of the dialog (never larger than the terminal). """ max_w, vpad, viewport, body_lines = _dialog_layout(screen, cols, rows) visible, more_above, more_below = _visible_slice(screen, body_lines, viewport) border = getattr(screen, "border_style", "accent") - # The resolved hint, not the screen's own: it is what the border actually draws, and - # it moves with the lane below as well as with the screen's hint (see _dialog_hint). + # The resolved hint, not the hint of the screen: it is what the border draws. It changes + # with the lane below, and also with the hint of the screen (refer to _dialog_hint). hint = _dialog_hint(screen) key = ( max_w, @@ -871,19 +900,19 @@ def compose_dialog(screen: Screen, cols: int, rows: int) -> str: return out -#: Memoized composited rows, keyed by everything the merge is a function of: the base row -#: under the box, the box's own line, and where it sits. A dialog repaints with almost every -#: row identical to the last paint (only the highlight moved, or nothing did but the header's -#: pulse), and each unchanged row then costs a dict hit instead of two ANSI parses, two cell -#: crops and a render. +#: Cached composited rows, with a key of all that the merge is a function of: the base row +#: under the box, the line of the box itself, and its position. When a dialog paints, almost +#: each row is identical to the last paint (only the highlight moved, or only the pulse of +#: the header). Each unchanged row then costs a dict hit, instead of two ANSI parses, two +#: cell crops, and a render. _OVERLAY_CACHE: OrderedDict[tuple, str] = OrderedDict() -#: Composited rows the memo holds — a few dialogs' worth of rows. +#: The number of composited rows that the cache holds: the rows of a few dialogs. _OVERLAY_CACHE_MAX = 256 def _overlay_row(base_row: str, box_line: str, left: int, cols: int) -> str: - """Lay one box line over one base row at cell ``left``, keeping both sides' styling.""" + """Put one box line over one base row at cell ``left``, and keep the styles of both.""" key = (base_row, box_line, left, cols) cached = _OVERLAY_CACHE.get(key) if cached is not None: @@ -892,8 +921,8 @@ def _overlay_row(base_row: str, box_line: str, left: int, cols: int) -> str: under = Text.from_ansi(base_row) over = Text.from_ansi(box_line) merged = crop_cells(under, 0, left) - # A base row shorter than the box's left edge (a blank line under a wide dialog) still - # has to hold the box out at its true column, so pad the gap rather than closing it. + # A base row shorter than the left edge of the box (a blank line under a wide dialog) + # must still hold the box at its true column. Thus pad the gap, and do not close it. merged.append(" " * max(0, left - merged.cell_len)) merged.append_text(over) tail_at = left + over.cell_len @@ -909,32 +938,35 @@ def _overlay_row(base_row: str, box_line: str, left: int, cols: int) -> str: def composite_float(base_rows: list[str], box: str, cols: int, rows: int) -> list[str]: - """Lay a dialog box over the full-screen rows beneath it, centred, and return the result. + """Put a dialog box over the full-screen rows below it, centred, and return the result. - The floating layers are normally placed by prompt_toolkit's ``FloatContainer``, which is - why a frame carrying one used to fall through to prompt_toolkit's renderer whole — and - pay its full grid rebuild and diff (70-125 ms on the PicoCalc) on every keystroke in - every dialog. There is nothing to that placement we cannot do here: an unanchored float - with no size of its own is centred on the frame, horizontally at its widest line and - vertically at its line count, clipped to the terminal. Doing it ourselves keeps dialogs + Usually, the ``FloatContainer`` of prompt_toolkit places the floating layers. For that + reason, a frame with a float once went whole to the renderer of prompt_toolkit. It then + paid the full grid rebuild and diff (70-125 ms on the PicoCalc) on each key press in + each dialog. But this function can do all of that placement. A float with no anchor and + no size of its own is centred on the frame: horizontally by its widest line, and + vertically by its line count, clipped to the terminal. When we do it here, dialogs stay on the row-diff path with the rest of the app. Args: - base_rows: The frame beneath, one ANSI string per terminal row. - box: The composed dialog, its rows joined by newlines (see :func:`compose_dialog`). + base_rows: The frame below, one ANSI string for each terminal row. + box: The composed dialog, its rows joined by newlines (refer to + :func:`compose_dialog`). cols: Terminal width. rows: Terminal height. - A box that lands on the borderless frame's **title bar** takes the whole row: the - cells either side of it are blanked instead of letting the bar show through. Every - other row's gutter is the backdrop the box floats over, and reads as one; a bar cut by a - box is fragments of chrome — the base's clip arrows, the last letters of its way out, - and, where the bar carries the header's atoms (the Cardputer, whose tall dialogs draw - over the bar), the tail of a battery gauge, where a stray ``7%`` reads as a reading. + A box that lands on the **title bar** of a borderless frame takes the whole row. The + cells on each side of it are blank, and the bar does not show through. On all other + rows, the gutter is the backdrop below the floating box, and looks like a backdrop. But + a bar that a box cuts is only fragments of chrome: the clip arrows of the base, the last + letters of its way out, and the tail of a battery gauge. (The bar carries the atoms of + the header on the Cardputer, whose tall dialogs draw over the bar.) There, a stray + ``7%`` looks like a battery level. Returns: - A new list of rows with the box merged in. Rows the box doesn't reach are passed - through untouched — the same strings, so the row diff skips them for free. + A new list of rows, with the box merged in. The rows that the box does not reach go + through with no change. They are the same strings, so the row diff skips them at no + cost. """ lines = box.split("\n") width = max((cell_len(Text.from_ansi(line).plain) for line in lines), default=0) @@ -949,19 +981,20 @@ def composite_float(base_rows: list[str], box: str, cols: int, rows: int) -> lis return out -#: The row the borderless frame's title bar sits on — under the header's one line, or -#: the top row where the platform has no header row — or ``None`` on a bordered frame, -#: whose top rule is the panel's own and has no fragments to leave (bound in :func:`_bind`). +#: The row of the title bar of a borderless frame: under the one line of the header, or the +#: top row when the platform has no header row. It is ``None`` on a frame with a border, +#: because its top rule belongs to the panel and leaves no fragments (bound in +#: :func:`_bind`). _BAR_ROW: int | None = None @on_platform def _bind(platform: Platform) -> None: - """Drop the composition memos on a platform switch — their output bakes the theme in. + """Clear the composition caches on a platform switch: their output contains the theme. - Also binds where the title bar sits (:data:`_BAR_ROW`), which only the platform decides. - Registered at module bottom so the immediate first run (see - :func:`~meshterm.platforms.on_platform`) finds every cache already defined. + It also binds the row of the title bar (:data:`_BAR_ROW`), which only the platform + decides. It is registered at the bottom of the module, so that the immediate first run + (refer to :func:`~meshterm.platforms.on_platform`) finds each cache already defined. """ global _BASE_BOX_CACHE, _BANNER_CACHE, _BAR_ROW _BAR_ROW = None if platform.frame_border else int(platform.header_row) diff --git a/meshterm/ui/tui/holdquit.py b/meshterm/ui/tui/holdquit.py index c0a07e8..d954279 100644 --- a/meshterm/ui/tui/holdquit.py +++ b/meshterm/ui/tui/holdquit.py @@ -1,18 +1,25 @@ # SPDX-License-Identifier: Apache-2.0 -"""The session's half of hold-Esc-to-quit: the box, its bar, and what holding it engages. +"""The part of hold-Esc-to-quit that the session does: the dialog, its bar, and the quiesce. -: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, 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 +:mod:`~meshterm.services.hold_to_quit` tells what the gesture is and why it exists. This +module tells what the session does with it. :class:`EscHoldWatch` is the listener of the +session. When it is told that the Esc key went down, it does these steps: + +- It waits for :data:`~meshterm.services.hold_to_quit.DIALOG_S`. +- It claims the hold. +- It floats a :class:`HoldQuitDialog` over the screen that is up. Thus nothing under the + dialog stops. +- It engages the quiesce of the app (:class:`Quiet`). + +When it is told that the Esc key came up, it closes the dialog and releases the quiesce. +If the key is held until :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. +The source of the down and up events of the Esc key depends on what reads the keys. A +front end that reads the keys itself (the front end of the emulator) reports them directly. +When a terminal delivers the keys, :class:`WatchedEsc` asks the keyboard if an Esc that +arrives is still down. If it is, :class:`WatchedEsc` holds it back and watches it until the +key comes up. """ from __future__ import annotations @@ -38,27 +45,28 @@ if TYPE_CHECKING: _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. +#: Seconds between two paints while the bar fills. The bar gets one more step after a few +#: hundredths of a second. But a frame costs real time on a handheld. Ten paints each +#: second look like a smooth fill, and most of a core stays free for the work that the app +#: must finish. BAR_TICK_S = 0.1 -#: The box's width, border included: the bar is the width of the text above it. +#: The width of the dialog, with its border: the bar has the width of the text above it. _WIDTH = 30 class Quiet: - """The app's quiesce (:meth:`~meshterm.ui.tui.session.TuiSession.set_quiesce`), held. + """The quiesce of the app (: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. + The quiesce is entered in its own task, because the thing that it takes (the transmit + lock) may have to wait until a transmission finishes, and the dialog must not wait with + it. The quiesce is released (:meth:`release`) when the user releases the Esc key. When + the app leaves, it is never released. It stops when the event loop shuts down, after + the device is disconnected. Thus no transmission starts while the app shuts down. """ def __init__(self, enter: Callable[[], AbstractAsyncContextManager[Any]] | None) -> None: - """Start entering ``enter`` (``None``: nothing to enter, engaged at once).""" + """Start to enter ``enter`` (``None``: there is nothing to enter, so engage at once).""" self._engaged = asyncio.Event() self._released = asyncio.Event() self._task = asyncio.ensure_future(self._hold(enter)) @@ -77,11 +85,11 @@ class Quiet: 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. + # A leave must never wait for 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.""" + """Wait up to ``timeout`` seconds for the quiesce to engage. Return whether it did.""" try: await asyncio.wait_for(self._engaged.wait(), timeout) except asyncio.TimeoutError: @@ -89,18 +97,19 @@ class Quiet: return True def release(self) -> None: - """Give the quiesce back: what it held up goes ahead.""" + """Release the quiesce: the work that it held back continues.""" self._released.set() class HoldQuitDialog(Screen): - """The box a held Esc raises: that MeshTerm is about to quit, and how soon. + """The dialog that a held Esc key opens: MeshTerm will quit soon, and it shows when. - 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. + The bar shows the time that remains. It starts to fill when the dialog appears. It is + full at :data:`~meshterm.services.hold_to_quit.QUIT_S` after the key press. At that + time, the app leaves, and on the Cardputer Zero, the launcher sends its SIGTERM. The + dialog has no buttons, because the only answer is in the hand of the user: hold the + key, or release it. The dialog is modal, so no key press gets to the screen below it + while it is up. """ title = "Quit MeshTerm" @@ -110,7 +119,7 @@ class HoldQuitDialog(Screen): 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``).""" + """A dialog for the hold that started at ``since``, in ``clock`` time (monotonic).""" super().__init__() self._starts = since + hold_to_quit.DIALOG_S self._span = hold_to_quit.QUIT_S - hold_to_quit.DIALOG_S @@ -118,7 +127,7 @@ class HoldQuitDialog(Screen): @property def picocalc_lyra_lane(self): - """No lane: nothing on the keyboard but the Esc in the reader's hand does anything.""" + """No lane: no keyboard key has an effect, except the Esc key that the user holds.""" from .fkeys import EMPTY_LANE return EMPTY_LANE @@ -130,24 +139,24 @@ class HoldQuitDialog(Screen): @property def fraction(self) -> float: - """How full the bar is, ``0`` when the box appears to ``1`` when the app leaves.""" + """How full the bar is: ``0`` when the dialog 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.""" + """``Hold Esc to quit`` above the bar. The bar fills the width of the line.""" 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.""" + """Ignore all keys: the dialog responds only to a hold or a release of the Esc key.""" return class EscHoldWatch: - """The session's :class:`~meshterm.services.hold_to_quit.Listener`. + """The :class:`~meshterm.services.hold_to_quit.Listener` of the session. - 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. + Other threads call its three listener methods. These methods only give their work to + the loop of the session. All the other code here runs on the loop. """ def __init__(self, session: TuiSession, loop: asyncio.AbstractEventLoop) -> None: @@ -157,7 +166,7 @@ class EscHoldWatch: 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. + #: The dialog while it is up, and the backdrop pushed under it when no screen was up. self._dialog: HoldQuitDialog | None = None self._backdrop: Screen | None = None @@ -178,7 +187,7 @@ class EscHoldWatch: 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 + except RuntimeError: # the loop is closed: the app has already stopped pass # --- on the loop -------------------------------------------------------------------- @@ -189,7 +198,7 @@ class EscHoldWatch: 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.""" + """Open the dialog, if the hold that asked for it continues.""" self._raise = None if self._session.leaving or not hold_to_quit.claim(since): return @@ -197,11 +206,12 @@ class EscHoldWatch: 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. + # This method pushes the dialog and :meth:`_stand_down` pops it, the same as the busy + # card. The dialog responds to the key, not to a future. Thus a release that arrives + # at the same moment cannot miss a dialog that is only half made. On an empty stack + # (a tool between two screens), the dialog gets its own blank backdrop, as the busy + # card does. It never uses the menu as its backdrop: by that time, the menu may be + # pushed again under the dialog, and a pop of the backdrop then removes the menu. if self._session.top is None: self._backdrop = ScrollScreen("", floating=False, footer_hint="") self._session.push(self._backdrop) @@ -209,7 +219,7 @@ class EscHoldWatch: 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.""" + """Request a paint while the bar fills. The last paint shows the full bar.""" while True: await asyncio.sleep(BAR_TICK_S) self._session.invalidate() @@ -218,12 +228,12 @@ class EscHoldWatch: 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 + return # the bar is full: the app leaves, and the launcher's SIGTERM comes too self._stand_down() self._session.unquiet() def _stand_down(self) -> None: - """Cancel the hold under way: its timers, its repaints, and its box.""" + """Cancel the hold that is in progress: its timers, its paints, and its dialog.""" for timer in (self._raise, self._quit): if timer is not None: timer.cancel() @@ -239,34 +249,40 @@ class EscHoldWatch: self._backdrop = None -#: 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. +#: Whether the keys of a terminal arrive as a VT byte stream. In such a stream, the last Esc +#: can be parsed after the key is up. This is true on all platforms except Windows, where +#: prompt_toolkit reads the events of the console. 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. +#: Seconds between two probes of the keyboard while the Esc key of a terminal is held. At +#: this interval, MeshTerm finds the release of a tap well within a tenth of a second. Each +#: probe costs almost nothing. POLL_S = 0.03 class WatchedEsc: - """A terminal's Esc, with the keyboard asked whether it is still held. + """The Esc key of a terminal, with a probe that asks the keyboard if 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. + When no front end owns the keys, the Esc key arrives through the terminal like all + other keys, and the terminal never tells when the key comes up. The keyboard tells it + (:func:`~meshterm.services.hold_to_quit.esc_probe`). Thus an Esc that arrives while the + key is still down is held back. Then the hold is reported and watched, the same as a + hold that a front end with its own keys reports: - 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. + - If the user releases the key at once, the Esc is delivered. + - A hold of one second opens the dialog. + - The repeats of the keyboard are part of the hold. + + Through a VT stream, a lone Esc byte gets to the screen only after prompt_toolkit waits + to be sure that it starts no sequence (``ttimeoutlen``). Thus the user usually releases + a tap before it arrives, and the tap is never held back. Also, the last repeat of a hold + can arrive after the key is up. Repeats that arrive this late are ignored for the length + of that wait. Thus a late repeat does not leave the screen under a dialog that the user + just released. """ def __init__(self, session: TuiSession, down: Callable[[], bool]) -> None: - """Hold back ``session``'s Esc while ``down()`` says the key is still held.""" + """Hold back the Esc of ``session`` while ``down()`` tells that the key is still held.""" self._session = session self._down = down self._watching: asyncio.Future | None = None @@ -280,17 +296,17 @@ class WatchedEsc: return False if self._watching is not None: self._repeats += 1 - return True # the keyboard repeating a held key + return True # the keyboard repeats a held key if time.monotonic() < self._late_until: - return True # a repeat of the hold just let go, parsed late + return True # a repeat of the hold that just ended, parsed late if not self._down() or not hold_to_quit.press(): - return False # let go already, or nothing listening + return False # the key is already up, or nothing listens 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.""" + """Another key arrived: first deliver a held-back Esc, so that the keys stay in order.""" if self._watching is not None and hold_to_quit.interrupt(): self._deliver() diff --git a/meshterm/ui/tui/overlay.py b/meshterm/ui/tui/overlay.py index c27c4cd..4724515 100644 --- a/meshterm/ui/tui/overlay.py +++ b/meshterm/ui/tui/overlay.py @@ -1,23 +1,24 @@ # SPDX-License-Identifier: Apache-2.0 -"""The busy skeleton: a titled card floated between screens while a load runs. +"""The busy skeleton: a card with a title that floats between screens while a load runs. A :class:`BusyOverlay` is the model behind :meth:`~meshterm.ui.tui.session.TuiSession. -busy_overlay` — a small *skeleton card* standing in for a screen the device is still -fetching: a title and the one-cell working :class:`~meshterm.ui.tui.spinner.Spinner` -beside a caption. Unlike a :class:`~meshterm.ui.tui.screen.Screen` it is *not* part of the -screen stack: the session draws it as the top-most float, so it hovers over the gap between -screens that a slow device operation (Bluetooth most of all) opens — the caller shows it -while the fetch runs and drops it when that fetch returns. +busy_overlay`. It is a small *skeleton card* that stands in for a screen whose data +MeshTerm still reads from the device. It has a title, and the one-cell working +:class:`~meshterm.ui.tui.spinner.Spinner` next to a caption. The card is not part of the +screen stack, as a :class:`~meshterm.ui.tui.screen.Screen` is. The session draws it as the +top-most float. Thus it floats over the gap between screens that a slow device operation +opens (Bluetooth most of all). The caller shows the card while the read runs, and removes +it when that read returns. -Rather than pop in, it stays fully black for a short *hold* and then *fades in from black* -over its next fraction of a second (see :attr:`brightness`): an operation that finishes within -the hold shows nothing at all, and a longer one eases up out of the black rather than appearing -suddenly — so the card never flashes and never pops in. +The card does not appear suddenly. It stays fully black for a short *hold*, then it fades +in from black during the next fraction of a second (refer to :attr:`brightness`). An +operation that finishes during the hold shows nothing. During a longer operation, the card +comes up slowly out of the black. Thus the card never flashes and never appears suddenly. -The spinning chip is the whole animation, and says everything the card has to say: the app is -working. It once shared the card with a scanning-light LED bar (JP, 2026-08-29) — eighteen -cells of travelling red that drew the eye harder than the words did, for a screen the reader -is only ever passing through. +The chip of the spinner is the whole animation, and it tells all that the card must tell: +the app is working. The card once also had an LED bar with a scanning light +(JP, 2026-08-29): eighteen cells of red that moved across the bar. That bar pulled the eye +more strongly than the words did, on a screen that the user only passes through. """ from __future__ import annotations @@ -30,27 +31,32 @@ from rich.text import Text from .render import render_to_ansi from .spinner import Spinner -#: The title line's colour (the theme's ``title.accent``, as hex so the fade can dim it). +#: The colour of the title line (the theme's ``title.accent``, in hex so that the fade can +#: dim it). _TITLE_COLOR = "bold #a5b4fc" -#: The working chip's colour (the theme's ``accent`` — the same beloved one-cell spinner). +#: The colour of the working chip (the theme's ``accent``). The chip has the same one-cell +#: spinner as the other dialogs. _CHIP_COLOR = "bold #818cf8" -#: The caption colour (the theme's ``muted``, as a hex so it can be dimmed for the fade). +#: The colour of the caption (the theme's ``muted``, in hex so that the fade can dim it). _CAPTION_COLOR = "#94a3b8" class BusyOverlay: - """A skeleton card (title, working chip + caption) drawn as the session's top-most float. + """A skeleton card (a title, the working chip, and a caption): the top-most float. Attributes: - spinner: The animated one-cell :class:`~meshterm.ui.tui.spinner.Spinner` — the same - working chip used inline elsewhere — sitting beside the caption. - title: An optional heading for the screen being fetched (empty for a bare card). - message: An optional caption drawn beside the chip (e.g. "reading from …"). - started_at: The monotonic time the card was created, from which the hold + fade run. - hold: Seconds the card stays fully black before the fade begins. - fade: The fade-in duration in seconds, after the hold. + spinner: The animated one-cell :class:`~meshterm.ui.tui.spinner.Spinner` next to + the caption. It is the same working chip that other places use inline. + title: An optional heading for the screen whose data is still read (empty for a + bare card). + message: An optional caption next to the chip (for example "reading from …"). + started_at: The monotonic time at which the card was created. The hold and the + fade count from this time. + hold: The time in seconds for which the card stays fully black before the fade + starts. + fade: The duration of the fade-in in seconds, after the hold. """ def __init__( @@ -64,11 +70,12 @@ class BusyOverlay: """Create a busy skeleton card. Args: - message: A short caption drawn beside the working chip (empty for a bare card). - title: An optional heading naming the screen being fetched. - hold: Seconds to stay fully black before fading in, so an operation that finishes - this fast shows nothing at all. - fade: Seconds over which the card then brightens from black to full colour. + message: A short caption next to the working chip (empty for a bare card). + title: An optional heading that names the screen whose data is still read. + hold: The time in seconds for which the card stays fully black before it fades + in. Thus an operation that finishes in this time shows nothing. + fade: The time in seconds in which the card then becomes brighter, from black + to full colour. """ self.spinner = Spinner() self.title = title @@ -79,11 +86,11 @@ class BusyOverlay: @property def brightness(self) -> float: - """The current fade level in ``[0, 1]``: 0 through the :attr:`hold`, then easing to 1. + """The current fade level in ``[0, 1]``: 0 during the :attr:`hold`, then a soft rise to 1. - Stays exactly 0 for the first :attr:`hold` seconds (nothing paints), then a smoothstep - easing over :attr:`fade` gives a gentle glow up out of the black rather than a linear - ramp. + The level stays exactly 0 for the first :attr:`hold` seconds (nothing paints). Then a + smoothstep curve over :attr:`fade` gives a gentle glow up out of the black, instead of + a linear ramp. """ elapsed = time.monotonic() - self.started_at - self.hold if elapsed <= 0: @@ -94,15 +101,17 @@ class BusyOverlay: return t * t * (3 - 2 * t) # smoothstep def tick(self) -> None: - """Advance the working chip one frame — the card's only animation.""" + """Move the working chip forward one animation step (the only animation of the card).""" self.spinner.tick() def restart(self) -> None: - """Restart the intro from scratch: rewind the fade ramp and the chip to their starts. + """Start the intro again: set the fade ramp and the chip back to their start. - Called each time the card is (re)exposed — its first appearance and every time it comes - back after a prompt covered it — so the black hold and fade-in play fresh every display - rather than the card snapping back at full brightness mid-way through an operation. + This method is called each time that the card becomes visible: at its first + appearance, and each time that it comes back after a prompt covered it. Thus the black + hold and the fade-in play again from the start each time that the card shows. If this + method is not called, the card comes back at full brightness in the middle of an + operation. """ self.started_at = time.monotonic() self.spinner.reset() @@ -110,12 +119,13 @@ class BusyOverlay: def render(self) -> str: """Render the skeleton card as a centred ANSI block, at the current fade level. - The title and the chip + caption line are each padded to a common width and joined - into one multi-line :class:`~rich.text.Text`, so the session's content-sized float - centres a clean rectangle over the gap between screens. + The title line, and the line with the chip and the caption, are padded to the same + width. Then they are joined into one :class:`~rich.text.Text` of more than one line. + Thus the float of the session, which has the size of its content, centres a clean + rectangle over the gap between screens. Returns: - An ANSI string of the card's rows. + An ANSI string with the rows of the card. """ level = self.brightness lines: list[Text] = [] @@ -132,7 +142,7 @@ class BusyOverlay: def _center_text(text: Text, width: int) -> Text: - """Return ``text`` padded with spaces so it is centred within ``width`` cells.""" + """Return ``text`` with spaces added so that it is centred in ``width`` cells.""" pad = max(0, width - cell_len(text.plain)) left = pad // 2 out = Text(" " * left) @@ -144,8 +154,9 @@ def _center_text(text: Text, width: int) -> Text: def dim_color(style: str, factor: float) -> str: """Scale a Rich hex-colour style toward black by ``factor`` (0 = black, 1 = unchanged). - Only the ``#rrggbb`` token is scaled; any attribute words (e.g. ``bold``) are preserved. - A style without a hex colour is returned untouched, as is any ``factor >= 1``. + Only the ``#rrggbb`` token is scaled. The attribute words (for example ``bold``) stay as + they are. A style without a hex colour is returned with no change. The style is also + returned with no change when ``factor >= 1``. Args: style: A Rich style such as ``"#38bdf8"`` or ``"bold #ecfeff"``. diff --git a/meshterm/ui/tui/progress.py b/meshterm/ui/tui/progress.py index e41fe67..e393a4f 100644 --- a/meshterm/ui/tui/progress.py +++ b/meshterm/ui/tui/progress.py @@ -1,10 +1,12 @@ # SPDX-License-Identifier: Apache-2.0 -"""A progress screen whose handle mimics the slice of ``rich.progress`` the tools use. +"""A progress screen whose handle copies the part of ``rich.progress`` that the tools use. -Trace and TX-optimize sweeps drive progress with ``add_task`` / ``advance`` / ``update`` on a -Rich ``Progress`` in CLI mode. In the TUI the same calls update a bounded, centered progress -dialog instead, so tool code stays identical across both front-ends (see -:meth:`meshterm.ui.surface.PlainUi.progress` vs :meth:`~meshterm.ui.surface.TuiUi.progress`). +In CLI mode, the trace sweep and the TX-optimize sweep show their progress with +``add_task`` / ``advance`` / ``update`` on a Rich ``Progress``. In the TUI, the same calls +change a progress dialog instead. The dialog has a limited size and is at the centre of +the screen. Thus the tool code is the same for the two front ends (refer to +:meth:`meshterm.ui.surface.PlainUi.progress` and +:meth:`~meshterm.ui.surface.TuiUi.progress`). """ from __future__ import annotations @@ -36,15 +38,15 @@ class _Task: class ProgressScreen(Screen): - """A non-interactive dialog showing one or more running progress bars.""" + """A non-interactive dialog that shows one or more progress bars of work that runs.""" footer_hint = "working…" floating = True - modal = True # work in flight owns the keyboard; ^W must not unwind out from under it + modal = True # the work owns the keyboard. ^W must not unwind the stack while it runs. @property def picocalc_lyra_lane(self): - """No lane: the dialog is non-interactive, so no key does anything to it.""" + """No lane: the dialog is non-interactive, so no keyboard key has an effect on it.""" from .fkeys import EMPTY_LANE return EMPTY_LANE @@ -55,25 +57,28 @@ class ProgressScreen(Screen): self.title = title self._tasks: dict[int, _Task] = {} self._next = 0 - #: The one-cell working chip, spun by an animation timer (see :class:`TuiProgress`). - #: It is the liveness signal every row carries so a slow task — a trace that only - #: advances once, at the very end — reads as *working* rather than frozen while it - #: waits, which a static meter alone cannot show. + #: The working chip, one cell wide. An animation timer turns it (refer to + #: :class:`TuiProgress`). Each row has this chip as its sign of activity. Thus a slow + #: task (a trace that advances only one time, at the end) looks active, not frozen, + #: while it waits. A static meter alone cannot show this. self.spinner = Spinner() def tick(self) -> None: - """Advance the working chip one frame (called from the dialog's animation timer).""" + """Advance the working chip by one animation step. + + The animation timer of the dialog calls this method. + """ self.spinner.tick() def add_task(self, description: str, total: float | None = None) -> int: - """Add a task and return its id (mirrors ``rich.progress.Progress.add_task``).""" + """Add a task and return its id (the same as ``rich.progress.Progress.add_task``).""" task_id = self._next self._next += 1 self._tasks[task_id] = _Task(description=description, total=total) return task_id def advance(self, task_id: int, amount: float = 1.0) -> None: - """Advance a task's completed count (mirrors ``Progress.advance``).""" + """Increase the completed count of a task (the same as ``Progress.advance``).""" self._tasks[task_id].completed += amount def update( @@ -84,7 +89,7 @@ class ProgressScreen(Screen): completed: float | None = None, total: float | None = None, ) -> None: - """Update a task's fields (mirrors the ``Progress.update`` kwargs used).""" + """Change the fields of a task (the ``Progress.update`` arguments that the tools use).""" task = self._tasks[task_id] if description is not None: task.description = description @@ -96,14 +101,18 @@ class ProgressScreen(Screen): def render_body(self, width: int) -> list[str]: """Render each task as ``chip description [meter] m/n``. - Every row leads with the animated working :attr:`spinner` chip — the app's one-cell - indicator — so the row is visibly alive whatever the bar is doing; it flips to a - green ``✓`` once the task completes. When a total is known, the bar is the app's - braille :func:`~meshterm.ui.braillechart.meter` — the one way MeshTerm draws a - proportion — a slim gauge filling a visible ``track`` and turning ``ok`` green at - full. A task with no known total (nothing to divide by) shows no bar at all — a dead, - never-moving track reads as broken — and leans on the spinning chip beside its running - count to signal progress. + Each row starts with the animated working chip (:attr:`spinner`), which is the + one-cell indicator of the app. Thus the row shows that it is active, whatever the bar + does. When the task completes, the chip changes to a green ``✓``. + + When the total is known, the bar is the braille + :func:`~meshterm.ui.braillechart.meter` of the app, which is the only way that + MeshTerm draws a proportion. It is a slim gauge that fills a visible ``track``, and + it changes to the ``ok`` green when it is full. + + A task with no known total (there is nothing to divide by) shows no bar, because a + track that never moves looks broken. Instead, the animated chip next to the current + count shows the progress. """ bar_width = max(10, min(40, width - 26)) table = Table.grid(padding=(0, 1)) @@ -124,7 +133,7 @@ class ProgressScreen(Screen): counts = f"{int(task.completed)}/{int(task.total)}" else: done = False - bar = Text("") # indeterminate: the chip carries the liveness, not a dead track + bar = Text("") # no total. The chip shows the activity, not a static track. counts = str(int(task.completed)) chip = Text("✓", style="ok") if done else self.spinner.text("brand") table.add_row( @@ -134,18 +143,19 @@ class ProgressScreen(Screen): return render_lines(Group(body), width) def handle(self, action: str, data: str = "") -> None: - """Swallow all keys: progress advances with the work, not the keyboard.""" + """Ignore all keyboard keys: the progress advances with the work, not the keyboard.""" return @dataclass class TuiProgress: - """Context manager yielding a :class:`ProgressScreen` handle, pushed for its lifetime. + """A context manager that yields a :class:`ProgressScreen` handle and keeps it pushed. - Presents the same ``with ... as progress:`` shape as ``make_progress`` so tools need - only swap the factory. Entering pushes the dialog and starts an animation timer that - keeps its working chip spinning; the ``add_task`` / ``advance`` / ``update`` methods - mutate it and repaint; exiting cancels the timer and pops it. + It has the same ``with ... as progress:`` form as ``make_progress``. Thus a tool must + change only the factory. On entry, the context manager pushes the dialog and starts an + animation timer that keeps the working chip in motion. The ``add_task`` / ``advance`` / + ``update`` methods change the dialog and request a paint. On exit, the context manager + cancels the timer and pops the dialog. """ session: TuiSession @@ -157,14 +167,14 @@ class TuiProgress: def __enter__(self) -> ProgressScreen: """Push the progress dialog and start its animation timer.""" self._screen = ProgressScreen(self.title) - # Wrap add_task/advance/update so each repaints the session automatically. + # Wrap add_task/advance/update, so that each call requests a paint of the session. for name in ("add_task", "advance", "update"): setattr(self._screen, name, self._wrap(getattr(self._screen, name))) self.session.push(self._screen) - # The task mutates the dialog only when it advances, which can be seconds apart (a - # trace advances just once, at the end). Without a heartbeat the chip would sit frozen - # between those beats and read as broken, so spin it on a timer, exactly as the busy - # splash does, for the dialog's whole lifetime. + # The task changes the dialog only when it advances, and the advances can be seconds + # apart (a trace advances only one time, at the end). Without a timer, the chip stays + # frozen between the advances and looks broken. Thus a timer turns the chip for the + # full life of the dialog, in the same way as the busy splash. self._ticker = asyncio.ensure_future(self._animate()) return self._screen @@ -176,19 +186,20 @@ class TuiProgress: self.session.pop(self._screen) async def _animate(self) -> None: - """Advance the dialog's working chip and repaint every :attr:`interval` seconds.""" + """Advance the working chip and request a paint, each :attr:`interval` seconds.""" try: while True: await asyncio.sleep(self.interval) self._screen.tick() self.session.invalidate() except asyncio.CancelledError: - # Swallow the cancellation so the task finishes cleanly on its final loop cycle - # rather than being torn down while pending (a screen-corrupting loop warning). + # Catch the cancellation and ignore it, so that the task ends cleanly on its last + # loop cycle. If the loop destroys the task while it is pending, the loop shows a + # warning, and the warning corrupts the screen. pass def _wrap(self, method): # type: ignore[no-untyped-def] - """Wrap a mutating method so it repaints the session after running.""" + """Wrap a method that changes the dialog, so that it requests a paint after it runs.""" def wrapped(*args, **kwargs): # type: ignore[no-untyped-def] result = method(*args, **kwargs) diff --git a/meshterm/ui/tui/prompt.py b/meshterm/ui/tui/prompt.py index 329f0eb..ece6456 100644 --- a/meshterm/ui/tui/prompt.py +++ b/meshterm/ui/tui/prompt.py @@ -1,9 +1,10 @@ # SPDX-License-Identifier: Apache-2.0 -"""Input screens: text, confirm, and autocomplete — the ``questionary`` replacements. +"""Input screens: text, confirm, and autocomplete. They replace ``questionary``. -These reimplement the small slice of ``questionary`` the app uses (a validated line editor, -a yes/no toggle, and a free-text field with suggestions) as uniform TUI screens, so every -prompt shares the framework's look, layering, resize, and Esc-to-cancel behavior. +These screens implement again the small part of ``questionary`` that the app uses: a line +editor with validation, a yes/no toggle, and a free-text field with suggestions. They are +uniform TUI screens. Thus each prompt has the same look, layering, resize, and +Esc-to-cancel behaviour as the rest of the framework. """ from __future__ import annotations @@ -23,29 +24,31 @@ from .spinner import Spinner if TYPE_CHECKING: from .fkeys import FPair -#: A validator returns ``True`` when the input is acceptable, or an error message to show. +#: A validator returns ``True`` when the input is acceptable. Otherwise, it returns an error +#: message to show. Validator = Callable[[str], "bool | str"] -#: MeshCore's LoRa payload caps a direct message at 150 UTF-8 bytes and an (unscoped) -#: channel broadcast at 130; past the cap the companion silently drops the packet. Every -#: compose bar that feeds one of those sends — the chat input, the courier's message entry — -#: counts bytes against these and blocks over the limit rather than losing the packet. +#: The LoRa payload of MeshCore limits a direct message to 150 UTF-8 bytes, and an +#: (unscoped) channel broadcast to 130 bytes. Past the limit, the companion discards the +#: packet and gives no error. Each compose bar that feeds one of those sends (the chat input, +#: the message entry of the courier) counts bytes against these limits. Over the limit, it +#: blocks the send, instead of a lost packet. DM_BYTE_LIMIT = 150 CHANNEL_BYTE_LIMIT = 130 -#: Byte-counter thresholds (bytes *remaining*) at which its colour escalates, plus the two -#: mid-band hues. The theme's ``warn``/``err`` sit too close together (an amber that reads -#: orange, then red), so the counter names a truer yellow and orange directly to keep the -#: green→yellow→orange→red fuel gauge visibly stepped. +#: The thresholds of the byte counter (in bytes that remain) at which its colour goes up one +#: step, and the two colours of the middle band. The theme's ``warn`` and ``err`` are too close +#: together (an amber that looks orange, then red). Thus the counter names a truer yellow and +#: orange directly, so that the green→yellow→orange→red fuel gauge has visible steps. _BYTES_TIGHT, _BYTES_LOW = 20, 10 _BYTES_YELLOW = "bold #fde047" _BYTES_ORANGE = "bold #ff9500" def byte_style(remaining: int) -> str: - """Map bytes remaining to the counter's escalating colour (green→yellow→orange→red).""" + """Map the bytes that remain to the colour of the counter (green→yellow→orange→red).""" if remaining <= 0: - return "err" # at or over the limit — the send is blocked + return "err" # at or over the limit: the send is blocked if remaining <= _BYTES_LOW: return _BYTES_ORANGE if remaining <= _BYTES_TIGHT: @@ -54,12 +57,13 @@ def byte_style(remaining: int) -> str: def byte_counter(used: int, limit: int) -> Text: - """The inline ``used/limit`` budget; only ``used`` is coloured by how much is left. + """The inline ``used/limit`` budget. Only ``used`` gets a colour, from how much is left. - Green with room to spare, yellow within :data:`_BYTES_TIGHT` bytes, orange within - :data:`_BYTES_LOW`, and red once the limit is met or exceeded — so the number reads as a - fuel gauge while the ``/limit`` suffix stays muted (it never changes). The shared gauge - the chat compose bar and the courier's message field both draw. + The colour is green when there is space to spare, yellow within :data:`_BYTES_TIGHT` + bytes, orange within :data:`_BYTES_LOW`, and red when the text is at or over the limit. + Thus the number is a fuel gauge, and the ``/limit`` suffix stays muted (it never + changes). The chat compose bar and the message field of the courier both draw this + shared gauge. """ counter = Text() counter.append(str(used), style=byte_style(limit - used)) @@ -68,13 +72,14 @@ def byte_counter(used: int, limit: int) -> Text: def _center(content: Text, width: int) -> Text: - """Center ``content`` in ``width`` with plain padding on both sides. + """Centre ``content`` in ``width``, with plain padding on the two sides. - Used instead of ``Text(justify="center")`` for lines that hold a reverse-video button - chip: Rich strips a styled span's *trailing* whitespace when it sits directly against - justify padding, which would shave the right edge off the chip (``" Quit"`` instead of - ``" Quit "``) and leave the label hugging the left of the fill. Padding manually keeps - a real segment after the chip, so its trailing cells survive and the fill stays symmetric. + Use this function instead of ``Text(justify="center")`` for lines that hold a + reverse-video button chip. When a styled span is directly against justify padding, Rich + removes the trailing whitespace of the span. That removes the right edge of the chip + (``" Quit"`` instead of ``" Quit "``), and the label then stays at the left of the + fill. Padding added by hand keeps a real segment after the chip. Thus the trailing cells + of the chip stay, and the fill stays symmetric. """ pad = max(0, width - content.cell_len) left = pad // 2 @@ -85,39 +90,40 @@ def _center(content: Text, width: int) -> Text: class LineEditor: - """A minimal single-line text editor (insert, delete, and cursor movement). + """A small single-line text editor (insert, delete, and cursor movement). - Shared by :class:`TextScreen` and :class:`AutocompleteScreen`. Tracks the text and the - cursor position; rendering shows the cursor as a reverse-video cell. + :class:`TextScreen` and :class:`AutocompleteScreen` share it. It tracks the text and the + cursor position. The render shows the cursor as a reverse-video cell. """ def __init__(self, initial: str = "", *, max_length: int | None = None) -> None: """Start the editor with ``initial`` text and the cursor at its end. Args: - initial: The starting buffer contents. - max_length: Optional hard cap on the number of characters; further insertions are - dropped (or a paste truncated to fit). ``None`` leaves the length unbounded. + initial: The contents of the buffer at the start. + max_length: An optional hard limit on the number of characters. More insertions + are ignored (or a paste is truncated to fit). ``None`` leaves the length + without a limit. """ self.text = initial self.cursor = len(initial) self._max_length = max_length def edit(self, action: str, data: str = "") -> bool: - """Apply an editing action, returning ``True`` if it changed the buffer/cursor. + """Apply an edit action. Return ``True`` if it changed the buffer or the cursor. Args: action: The normalized key action. - data: The character to insert when ``action`` is ``text`` — or the whole run - pasted when ``action`` is ``paste``. + data: The character to insert when ``action`` is ``text``, or the whole pasted + run when ``action`` is ``paste``. Returns: - ``True`` if the action was an editing action handled here. + ``True`` if the action was an edit action that this method handled. """ if action == "paste": - # A paste arrives as one multi-character run. A single-line field can't hold - # newlines or control characters, so fold them to spaces, then insert the run - # exactly like typed text (the max-length trim below still applies). + # A paste arrives as one multi-character run. A single-line field cannot hold + # newlines or control characters, so fold them to spaces. Then insert the run + # exactly as typed text (the max-length trim below still applies). data = "".join(ch if ch.isprintable() else " " for ch in data) if not data: return False @@ -126,8 +132,8 @@ class LineEditor: if self._max_length is not None: room = self._max_length - len(self.text) if room <= 0: - return False # at capacity — swallow the key without changing the buffer - data = data[:room] # a multi-char paste fills only the remaining slots + return False # full: ignore the key, and do not change the buffer + data = data[:room] # a multi-character paste fills only the slots that remain self.text = self.text[: self.cursor] + data + self.text[self.cursor :] self.cursor += len(data) elif action == "backspace" and self.cursor > 0: @@ -152,11 +158,12 @@ class LineEditor: return True def _word_left(self, pos: int) -> int: - """Index of the start of the word at/left of ``pos`` (the previous word if already there). + """Index of the word start at or left of ``pos`` (the previous word if already there). - Skips any whitespace immediately left of the cursor, then the run of word characters, so - from mid-word it lands on that word's first character and from a word start it steps back - to the previous word — the usual Ctrl+Left behavior of a text editor. + It skips the whitespace immediately left of the cursor, then the run of word characters. + Thus from the middle of a word, it lands on the first character of that word. From a + word start, it steps back to the previous word. This is the usual Ctrl+Left behaviour + of a text editor. """ i = pos while i > 0 and self.text[i - 1].isspace(): @@ -168,8 +175,8 @@ class LineEditor: def _word_right(self, pos: int) -> int: """Index of the start of the next word after ``pos`` (or the line end if none remains). - Skips the current run of word characters, then the whitespace after it, landing on the - first character of the following word — the usual Ctrl+Right behavior. + It skips the current run of word characters, then the whitespace after it. Thus it + lands on the first character of the next word. This is the usual Ctrl+Right behaviour. """ n = len(self.text) i = pos @@ -186,12 +193,13 @@ class LineEditor: Args: mask: When ``True``, replace each character with a bullet (password entry). - overflow_at: Character index at which the text spills past a byte budget; that - character and everything after it are shown in the error style so the user - can see exactly what to trim. ``None`` (the default) styles the line plainly. - slots: When set, render exactly this many fixed positions (a masked PIN field): - typed positions show a bullet, still-blank ones a muted centre dot. Takes - precedence over ``mask``/``overflow_at``. + overflow_at: The character index at which the text goes past a byte budget. That + character and all characters after it show in the error style, so that the + user can see exactly what to cut. ``None`` (the default) gives the line a + plain style. + slots: When set, render exactly this number of fixed positions (a masked PIN + field). A typed position shows a bullet, and a blank position shows a muted + centre dot. This argument has priority over ``mask`` and ``overflow_at``. """ if slots is not None: return self._render_slots(slots) @@ -210,9 +218,10 @@ class LineEditor: def _render_slots(self, slots: int) -> Text: """Render a fixed-width masked field: filled bullets and centred dots for blanks. - Used for PIN entry — each of ``slots`` positions shows a bullet (``•``) once typed and - a muted centre dot (``·``) while still blank, spaced apart so the field reads as a row - of PIN boxes rather than a growing line. The cursor position is drawn reverse-video. + The PIN entry uses this method. Each of the ``slots`` positions shows a bullet (``•``) + after it is typed, and a muted centre dot (``·``) while it is blank. Spaces separate + the positions, so that the field looks like a row of PIN boxes, not a line that grows. + The cursor position is drawn in reverse video. """ filled = len(self.text) text = Text("› ", style="accent") @@ -230,33 +239,33 @@ class LineEditor: class _KeylessDialog(Screen): - """A dialog with no F-key lane, because it has nothing a lane could carry. + """A dialog with no F-key lane, because it has nothing that a lane can carry. - Every prompt in this module is answered with Enter, Esc, the arrows, and typing — - keys that sit right under the reader's hands on both platforms. None of them scroll, - so the shared pager (which the base :class:`~meshterm.ui.tui.screen.Screen` hands out) - would name two keys that do nothing here. The lane's standing rule is to leave a slot - **empty** rather than dim when the action is not a thing on this screen *at all* — - dim is for a thing that just isn't available this paint — so these dialogs draw the - bare key numbers (see :mod:`~meshterm.ui.tui.fkeys`). + The user answers each prompt in this module with Enter, Esc, the arrow keys, and typed + text. These keyboard keys are directly under the hands of the user on both platforms. + None of these prompts scroll. Thus the shared pager (which the base + :class:`~meshterm.ui.tui.screen.Screen` gives by default) names two keys that do nothing + here. The rule of the lane is: leave a slot **empty**, not dim, when the action + does not exist on this screen. Dim is for an action that is not available for this paint + only. Thus these dialogs draw only the key numbers (refer to :mod:`~meshterm.ui.tui.fkeys`). - Every one of them is also :attr:`~meshterm.ui.tui.screen.Screen.modal`: a prompt is an - unanswered question, so the pop-all key (^W) declines to unwind past it and the reader - answers or Escs out first. + Each of these dialogs is also :attr:`~meshterm.ui.tui.screen.Screen.modal`. A prompt is a + question with no answer yet, so the pop-all key (^W) does not unwind past it. The user + answers it first, or leaves it with the Esc key. """ modal = True @property def picocalc_lyra_lane(self): - """No slots: nothing on a prompt pages, jumps, or needs promoting off a chord.""" + """No slots. On a prompt, nothing pages or jumps, and no chord must have a chip.""" from .fkeys import EMPTY_LANE return EMPTY_LANE class TextScreen(_KeylessDialog): - """A validated single-line text prompt. Resolves with the string, or CANCEL on Esc.""" + """A validated single-line text prompt. It resolves with the string, or CANCEL on Esc.""" def __init__( self, @@ -273,20 +282,21 @@ class TextScreen(_KeylessDialog): """Build a text prompt. Args: - title: Short heading shown in the dialog's border. - prompt: The question/instruction shown inside the box, above the field. Keep - the ``title`` short and put the detail here, so the popup reads like the - button dialogs (a prompt above its controls) rather than a lone field. + title: A short heading in the border of the dialog. + prompt: The question or instruction in the box, above the field. Keep the + ``title`` short and put the detail here. Thus the dialog looks like the + button dialogs (a prompt above its controls), not like a lone field. default: Prefilled text. - validate: Optional validator run on Enter; a returned string is shown as an - error and blocks submission. - help_text: Optional muted hint shown under the field. + validate: An optional validator that runs on Enter. If it returns a string, the + string shows as an error and the submission is blocked. + help_text: An optional muted hint under the field. password: When ``True``, mask the entered text. - byte_limit: When set, the field carries the shared UTF-8 byte gauge - (:func:`byte_counter`) pinned bottom-right and blocks submission once the - text exceeds it — for a field that feeds a size-capped packet (a direct - message, a courier entry). Left ``None`` for an unbounded field. - footer_hint: Footer key hint. + byte_limit: When set, the field has the shared UTF-8 byte gauge + (:func:`byte_counter`) pinned at the bottom right. The field blocks the + submission when the text is longer than the limit. Use it for a field that + feeds a packet with a size limit (a direct message, a courier entry). Keep + ``None`` for a field with no limit. + footer_hint: The key hint in the footer. """ super().__init__() self.title = title @@ -301,14 +311,16 @@ class TextScreen(_KeylessDialog): @property def dialog_width(self) -> int: - """Natural outer width so the frame sizes the box to its content (see ButtonDialog). + """Natural outer width: the frame sizes the box to its content (refer to ButtonDialog). - The widest of the prompt, title, hint, footer, and the field's current text, plus a - comfortable field minimum — so a short prompt is a tidy box, not a banner stretched - across the terminal. The compositor still caps this to the width available. + The width is the widest of these: the prompt, the title, the hint, the footer, and the + current text of the field, plus a comfortable minimum for the field. Thus a short + prompt is a tidy box, not a banner across the terminal. The compositor still limits + this width to the width that is available. """ - # A byte gauge rides the field's right edge, so the field lane needs room for the - # text, its cursor, and the counter ("150/150" ≈ 8 cells) without them colliding. + # A byte gauge sits at the right edge of the field. Thus the field lane must have space + # for the text, its cursor, and the counter ("150/150" ≈ 8 cells), so that they do not + # collide. field_slack = 12 if self._byte_limit is not None else 4 inner = max( cell_len(self._prompt), @@ -316,24 +328,24 @@ class TextScreen(_KeylessDialog): cell_len(self._help), cell_len(self.footer_hint), cell_len(self._editor.text) + field_slack, - 36, # a comfortable minimum so a short field isn't a cramped sliver + 36, # a comfortable minimum, so that a short field is not too narrow ) - return inner + 8 # panel padding + border, plus horizontal breathing room + return inner + 8 # panel padding + border, plus horizontal space to spare def _used_bytes(self) -> int: - """UTF-8 byte length of the field — what counts against ``byte_limit``.""" + """The UTF-8 byte length of the field: the value that counts against ``byte_limit``.""" return len(self._editor.text.encode("utf-8")) def render_body(self, width: int) -> list[str]: - """Render the optional prompt, the field (+ byte gauge), help, and any error.""" + """Render the optional prompt, the field (and its byte gauge), the help, and an error.""" parts: list[RenderableType] = [] if self._prompt: parts.append(Text(self._prompt)) parts.append(Text("")) field = self._editor.render(mask=self._password) if self._byte_limit is not None: - # The gauge pins to the field's right edge — a steady fuel gauge in the corner, - # exactly as the chat compose bar draws it (both via ``byte_counter``). + # The gauge pins to the right edge of the field: a steady fuel gauge in the corner, + # exactly as the chat compose bar draws it (both through ``byte_counter``). field = right_aligned_tail( field, byte_counter(self._used_bytes(), self._byte_limit), width ) @@ -368,34 +380,35 @@ class TextScreen(_KeylessDialog): class PinDialog(_KeylessDialog): - """A startup popup that collects a Bluetooth pairing PIN, re-asking on a rejected code. + """A startup dialog that gets a Bluetooth pairing PIN, and asks again after a rejected code. - Shown by the device picker when a chosen companion answers the scan but refuses the GATT - connection until it is bonded. It presents a masked field centered in its own bordered box - under the wordmark — the same chromeless-splash presentation as the picker and its spinner - — so it reads as one more step of the startup flow rather than a context switch. + The device picker shows it when a selected companion answers the scan, but refuses the + GATT connection until it is bonded. It shows a masked field, centred in its own box with a + border, under the wordmark. This is the same chromeless-splash presentation as the picker + and its spinner. Thus the dialog looks like one more step of the startup flow, not like a + change of context. - It only *collects* a PIN; verifying it means actually opening the BLE connection, which the - picker does. So a rejected code isn't detected here — the picker catches the authentication - failure and re-opens this dialog with ``error`` set, which is why the field starts empty each - time. Resolves with the entered PIN, or :data:`CANCEL` on Esc (the user gave up — the picker - returns them to the device list). + It only gets a PIN. To check the PIN, MeshTerm must open the BLE connection, and the + picker does that. Thus this dialog does not find a rejected code. The picker catches the + authentication failure and opens this dialog again with ``error`` set. For this reason, + the field is empty each time. It resolves with the entered PIN, or with :data:`CANCEL` on + Esc (the user stopped, and the picker returns the user to the device list). """ footer_hint = "Enter connect · Esc cancel" - #: MeshCore pairing PINs are a fixed six digits, so the field is capped at six characters - #: and drawn as six slots (typed digits as bullets, blanks as centre dots). + #: A MeshCore pairing PIN has exactly six digits. Thus the field is limited to six + #: characters, and drawn as six slots (typed digits as bullets, blanks as centre dots). PIN_LENGTH = 6 def __init__(self, device_name: str, *, error: str = "", help_text: str = "") -> None: """Build the PIN dialog. Args: - device_name: The companion's display name, woven into the prompt. - error: A message shown in the error style — set by the picker on a re-ask after a - rejected PIN; empty on the first ask. - help_text: A muted hint under the field (e.g. where to read the code). + device_name: The display name of the companion, which the prompt includes. + error: A message in the error style. The picker sets it when it asks again after + a rejected PIN. It is empty on the first ask. + help_text: A muted hint under the field (for example, where to read the code). """ super().__init__() self.title = "Bluetooth PIN required" @@ -421,7 +434,7 @@ class PinDialog(_KeylessDialog): """Edit the field, submit a non-empty PIN on Enter, or cancel on Esc.""" if action == "enter": pin = self._editor.text.strip() - if not pin: # an empty PIN can't be right — nudge rather than pointlessly retry + if not pin: # an empty PIN cannot be correct: tell the user, not a useless retry self._error = "Enter the PIN, or press Esc to cancel." return self.resolve(pin) @@ -439,18 +452,18 @@ class ConfirmScreen(_KeylessDialog): title: str, *, default: bool = True, - # The ButtonDialog hint verbatim: a yes/no prompt is a button row like any other, - # and the row is what differs, not the keys. The y/n accelerators stay unwritten — - # the Yes/No labels are their own hint, and naming them cost the Esc verb its - # cells inside a PicoCalc-width box. + # The ButtonDialog hint, word for word: a yes/no prompt is a button row like all + # others. The row is what is different, not the keys. The hint does not name the y/n + # accelerators. The Yes/No labels are their own hint, and when the hint named them, + # the Esc verb lost its cells in a box of PicoCalc width. footer_hint: str = "←→ choose · Enter select · Esc cancel", ) -> None: """Build a confirm prompt. Args: title: The yes/no question. - default: The initially highlighted answer. - footer_hint: Footer key hint. + default: The answer that has the highlight at the start. + footer_hint: The key hint in the footer. """ super().__init__() self.title = title @@ -459,7 +472,7 @@ class ConfirmScreen(_KeylessDialog): @property def dialog_width(self) -> int: - """Natural outer width so the box hugs the question rather than stretching wide.""" + """Natural outer width, so that the box fits the question and does not become wide.""" inner = max( cell_len(self.title), cell_len(self.footer_hint), @@ -488,13 +501,14 @@ class ConfirmScreen(_KeylessDialog): class ButtonDialog(_KeylessDialog): - """A centered dialog: a prompt above a row of side-by-side buttons. + """A centred dialog: a prompt above a row of buttons, side by side. - A reusable choose-one prompt. The buttons sit in a row; ←/→ (or Tab) move the highlight, - Enter commits the highlighted button, and Esc cancels. Optional single-key shortcuts - commit a button instantly (e.g. ``y``/``n``, self-hinted by ``Yes``/``No`` labels). The - highlight and border colours are parametrised so a caller can theme it (a destructive - action in red, say). Resolves with the chosen button's value, or CANCEL on Esc. + A prompt that can be used again, to select one item. The buttons are in a row. ←/→ (or + Tab) move the highlight, Enter commits the highlighted button, and Esc cancels. Optional + single-key shortcuts commit a button immediately (for example ``y``/``n``, which the + ``Yes``/``No`` labels hint themselves). The highlight and border colours are parameters, + so that a caller can theme the dialog (for example, a destructive action in red). It + resolves with the value of the selected button, or CANCEL on Esc. """ def __init__( @@ -515,24 +529,28 @@ class ButtonDialog(_KeylessDialog): """Build a button dialog. Args: - prompt: The question shown above the buttons. A plain string is styled with - ``prompt_style``; a pre-styled (possibly multi-line) :class:`Text` is - rendered as-is, so a caller can float richly-marked output — e.g. the - message dialog's "[ok]✓[/ok] …" outcome lines — without losing colour. + prompt: The question above the buttons. A plain string gets the style + ``prompt_style``. A :class:`Text` that already has its styles (possibly on + more than one line) is rendered as it is. Thus a caller can float output with + rich marks, and the colour is not lost. An example is the outcome lines + "[ok]✓[/ok] …" of the message dialog. buttons: ``(label, value)`` pairs laid out left to right. - title: Optional dialog heading. - default: Index of the initially highlighted button. - keys: Optional map of a lowercase shortcut character to the value it commits - immediately (bypassing the highlight), e.g. ``{"y": True, "n": False}``. - footer_hint: Footer key hint (hints Enter and Esc, as the other dialogs do). - prompt_style: Rich style for the question (e.g. ``"warn"`` for a cautionary - action); empty for the default foreground. - button_style: Rich style for the highlighted button. - button_idle_style: Rich style for the un-highlighted buttons. - border_style: Rich style for the dialog border (read by the frame compositor). - lane: An F-key lane for the one question that has a chip worth offering — the - quit confirm's, whose F3 is the chip that asked it, pressed again (see - ``menu._confirm_quit``). ``None`` keeps a prompt's empty lane. + title: An optional heading for the dialog. + default: The index of the button that has the highlight at the start. + keys: An optional map from a lowercase shortcut character to the value that it + commits immediately (without the highlight), for example + ``{"y": True, "n": False}``. + footer_hint: The key hint in the footer (it names Enter and Esc, as the other + dialogs do). + prompt_style: The Rich style for the question (for example ``"warn"`` for an + action with a risk). Empty for the default foreground. + button_style: The Rich style for the highlighted button. + button_idle_style: The Rich style for the buttons without the highlight. + border_style: The Rich style for the border of the dialog (the frame + compositor reads it). + lane: An F-key lane for the one question that has a chip to offer: the quit + confirm. Its F3 is the chip that asked the question, pressed again (refer to + ``menu._confirm_quit``). ``None`` keeps the empty lane of a prompt. """ super().__init__() self._lane = tuple(lane) if lane is not None else None @@ -548,12 +566,12 @@ class ButtonDialog(_KeylessDialog): self._button_idle_style = button_idle_style def _prompt_lines(self) -> list[Text]: - """The prompt as one styled :class:`Text` per line. + """The prompt as one styled :class:`Text` for each line. - A plain-string prompt becomes a single line in ``prompt_style``; a :class:`Text` - prompt keeps its own spans and is split on newlines so each line can be centered - independently (centering the block as a whole would skew every line to the - longest one's margin). + A plain-string prompt becomes a single line in ``prompt_style``. A :class:`Text` + prompt keeps its own spans, and is split on newlines, so that each line can be + centred alone. (If the block is centred as a whole, each line moves to the margin of + the longest line.) """ if isinstance(self._prompt, Text): return list(self._prompt.split("\n")) or [Text("")] @@ -561,27 +579,27 @@ class ButtonDialog(_KeylessDialog): @property def picocalc_lyra_lane(self): - """The caller's lane where one was given, else a prompt's empty one. + """The lane of the caller when the caller gave one, or else the empty lane of a prompt. - The per-deck definition, as every screen's is; the Cardputer's deck follows it. + This is the definition for one deck, as on all screens. The Cardputer deck follows it. """ return self._lane if self._lane is not None else super().picocalc_lyra_lane @property def _button_row_width(self) -> int: - """Display width of the button row (`` Label `` cells joined by 4-space gaps).""" + """The width in cells of the button row (`` Label `` chips joined by 4-space gaps).""" cells = sum(cell_len(label) + 4 for label, _ in self._buttons) gaps = 4 * max(0, len(self._buttons) - 1) return cells + gaps @property def dialog_width(self) -> int: - """Natural outer width so the frame sizes the box to its content, not the terminal. + """Natural outer width: the frame sizes the box to its content, not to the terminal. - The widest of the prompt lines, button row, title, and footer hint, plus a - comfortable margin and the border — so a short confirm reads as a tidy box rather - than a banner stretched across the screen. The compositor still caps this to the - terminal. + The width is the widest of these: the prompt lines, the button row, the title, and + the footer hint. Then a comfortable margin and the border are added. Thus a short + confirm is a tidy box, not a banner across the terminal. The compositor still limits + this width to the terminal. """ inner = max( max(line.cell_len for line in self._prompt_lines()), @@ -589,10 +607,10 @@ class ButtonDialog(_KeylessDialog): cell_len(self.title), cell_len(self.footer_hint), ) - return inner + 12 # panel padding + border, plus horizontal breathing room + return inner + 12 # panel padding + border, plus horizontal space to spare def render_body(self, width: int) -> list[str]: - """Render the prompt line(s) centered above a centered row of buttons.""" + """Render the prompt lines, centred above a centred row of buttons.""" row = Text() for i, (label, _value) in enumerate(self._buttons): if i: @@ -605,14 +623,14 @@ class ButtonDialog(_KeylessDialog): def handle(self, action: str, data: str = "") -> None: """Move the highlight, commit on Enter or a shortcut key, or cancel on Esc.""" if action in ("left", "right") and self._buttons: - # ←→ clamp, like every other cursor the app steers with a directional pair — - # a highlight that leaps end to end is the one move that reads as the screen - # changing rather than as one step. + # ←→ clamp, like all other highlights that the app moves with a directional pair. + # A highlight that jumps from one end to the other is the one move that looks like + # a change of the screen, instead of one step. step = -1 if action == "left" else 1 self._index = max(0, min(len(self._buttons) - 1, self._index + step)) elif action == "tab" and self._buttons: - # Tab is the exception the rule allows: a forward-only key with no reverse of - # its own, so it cycles or it dead-ends on the last chip. + # Tab is the exception that the rule permits: a forward-only key with no reverse + # key of its own. Thus it cycles, or else it stops on the last chip with no way on. self._index = (self._index + 1) % len(self._buttons) elif action == "text" and data.lower() in self._keys: self.resolve(self._keys[data.lower()]) @@ -623,44 +641,45 @@ class ButtonDialog(_KeylessDialog): class CountdownDialog(_KeylessDialog): - """A wait you can watch, and back out of: the seconds left, over one Cancel chip. + """A wait that you can watch and leave: the seconds that remain, above one Cancel chip. - Shown while a cooldown holds a transmission back (see - :func:`meshterm.ui.cooldown.wait_for_cooldown`). The point is that a wait long enough - to notice should say *why* it is waiting and leave a way out — a frozen screen says - neither, and on a radio app it reads as a lost connection rather than as courtesy. + It shows while a cooldown holds back a transmission (refer to + :func:`meshterm.ui.cooldown.wait_for_cooldown`). A wait that is long enough to notice + must tell why it waits, and must give a way out. A frozen screen tells neither. On a + radio app, a frozen screen looks like a lost connection, not like courtesy. - It resolves itself: the caller ticks it down with :meth:`set_remaining` and the dialog - resolves ``True`` the moment the clock reaches zero. Esc — or Enter on its Cancel chip - — resolves CANCEL instead, and the caller abandons whatever was waiting. + The dialog resolves itself. The caller counts it down with :meth:`set_remaining`, and + the dialog resolves ``True`` when the clock gets to zero. Esc (or Enter on its Cancel + chip) resolves CANCEL instead, and the caller abandons the thing that waited. - One chip, not two: there is nothing to choose between, only something to abandon, so - it takes the lone-button hint shape (no ``←→``) with Cancel as its verb. + One chip, not two: there is nothing to select between, only something to abandon. Thus + the dialog uses the lone-button hint shape (no ``←→``), with Cancel as its verb. """ def __init__(self, action: str, remaining: float, *, reason: str = "") -> None: """Build a countdown over one Cancel chip. Args: - action: What is waiting, named as the thing that will happen ("Flood advert"). - remaining: Seconds left when the dialog opens. - reason: One muted line under the clock saying why the wait exists; empty for - no line at all. + action: The thing that waits, named as the thing that will occur + ("Flood advert"). + remaining: The seconds that remain when the dialog opens. + reason: One muted line under the clock that tells why the wait is necessary. + Empty for no line. """ super().__init__() self.title = action - # Both keys do the one thing this dialog offers, so they share an atom rather - # than each claiming "cancel" in turn (the hint line's shared-key rule). + # Both keys do the one thing that this dialog offers. Thus they share an atom, + # instead of one atom each that says "cancel" (the shared-key rule of the hint line). self.footer_hint = "Enter/Esc cancel" self.border_style = "warn" self._remaining = max(0.0, remaining) self._reason = reason def set_remaining(self, remaining: float) -> None: - """Update the clock, resolving the dialog once it reaches zero. + """Set the clock, and resolve the dialog when the clock gets to zero. - Resolving twice is harmless — :meth:`~meshterm.ui.tui.screen.Screen.resolve` drops - a second result — so the tick never has to know whether Esc beat it to it. + To resolve two times causes no problem: :meth:`~meshterm.ui.tui.screen.Screen.resolve` + ignores a second result. Thus the tick never has to know if Esc came first. """ self._remaining = max(0.0, remaining) if self._remaining <= 0: @@ -668,11 +687,12 @@ class CountdownDialog(_KeylessDialog): @property def dialog_width(self) -> int: - """Natural outer width, sized for the widest line it will ever draw. + """Natural outer width, sized for the widest line that the dialog will ever draw. - Measured against the *opening* clock rather than the current one, so the box does - not shrink a cell as the seconds tick from 10 to 9 — a dialog that resizes while - you read it is harder to read than a slightly wide one. + The width is measured against the clock at the opening, not the current clock. Thus + the box does not become one cell narrower when the seconds go from 10 to 9. A dialog + that changes size while you read it is harder to read than a dialog that is a little + wide. """ inner = max( cell_len(self.title), @@ -681,20 +701,20 @@ class CountdownDialog(_KeylessDialog): cell_len(self._reason), len(" Cancel "), ) - return inner + 12 # panel padding + border, plus breathing room (see ButtonDialog) + return inner + 12 # panel padding + border, plus space to spare (refer to ButtonDialog) @staticmethod def _clock_text(remaining: float) -> str: - """The clock line: whole seconds, counted the way a person would say them.""" - seconds = max(0, int(remaining + 0.999)) # 0.2s left still reads as "1s" + """The clock line: whole seconds, counted as a person says them.""" + seconds = max(0, int(remaining + 0.999)) # 0.2s left still shows as "1s" return f"Ready in {seconds}s" def render_body(self, width: int) -> list[str]: - """Draw the clock and its reason centered above a centered Cancel chip. + """Draw the clock and its reason, centred above a centred Cancel chip. - Centered line by line, the way :class:`ButtonDialog` and :class:`ProgressDialog` - draw theirs: a chip is a chip wherever it appears, and one shoved against the left - border read as an afterthought beside its siblings' centered rows. + Each line is centred alone, as :class:`ButtonDialog` and :class:`ProgressDialog` draw + their lines. A chip is a chip in all places. A chip against the left border looked + like a late addition, next to the centred rows of the other dialogs. """ parts: list[Text] = [_center(Text(self._clock_text(self._remaining), style="warn"), width)] if self._reason: @@ -710,15 +730,16 @@ class CountdownDialog(_KeylessDialog): class TypedConfirmDialog(_KeylessDialog): - """A destructive-action gate: the user must type a confirmation word to proceed. + """A gate for a destructive action: the user must type a confirmation word to continue. - A centered, error-themed dialog for the actions a stray Enter must never be able to - trigger (factory reset, identity overwrite). It shows the warning, then a field the - user has to type the exact confirmation word into; Enter commits only when the field - matches (anything else shows a nudge and keeps the dialog up), and Esc always backs - out. Matching is case-insensitive so a forgotten CapsLock doesn't read as hesitation — - the friction is having to *type the word*, not its case. Resolves ``True`` on a match, - or :data:`~meshterm.ui.tui.screen.CANCEL` on Esc (never ``False``). + A centred dialog with the error theme, for the actions that a stray Enter must never + start (factory reset, identity overwrite). It shows the warning, then a field in which + the user must type the exact confirmation word. Enter commits only when the field + matches. All other text shows a short message and keeps the dialog open. Esc always + leaves. The match ignores case, so that a forgotten CapsLock does not look like + hesitation. The effort that the dialog asks for is to type the word, not its case. It + resolves ``True`` on a match, or :data:`~meshterm.ui.tui.screen.CANCEL` on Esc (never + ``False``). """ border_style = "err" @@ -728,9 +749,9 @@ class TypedConfirmDialog(_KeylessDialog): """Build the typed-confirmation dialog. Args: - warning: The consequence, spelled out (e.g. "This erases ALL data …"). - word: The word the user must type to confirm (e.g. ``"RESET"``). - title: Dialog heading. + warning: The result, in full words (for example "This erases ALL data …"). + word: The word that the user must type to confirm (for example ``"RESET"``). + title: The heading of the dialog. """ super().__init__() self.title = title @@ -741,22 +762,22 @@ class TypedConfirmDialog(_KeylessDialog): @property def dialog_width(self) -> int: - """Natural outer width so the frame sizes the box to its content (see ButtonDialog).""" + """Natural outer width: the frame sizes the box to its content (refer to ButtonDialog).""" inner = max( cell_len(self._warning), cell_len(self.title), cell_len(self.footer_hint), cell_len(self._ask), ) - return min(inner, 72) + 12 # panel padding + border, plus breathing room + return min(inner, 72) + 12 # panel padding + border, plus space to spare @property def _ask(self) -> str: - """The instruction line naming the word to type.""" + """The instruction line that names the word to type.""" return f"Type {self._word} to confirm:" def render_body(self, width: int) -> list[str]: - """Render the warning, the instruction, the typed field, and any mismatch nudge.""" + """Render the warning, the instruction, the typed field, and a mismatch message.""" parts: list[RenderableType] = [ Text(self._warning, style="err"), Text(""), @@ -783,25 +804,28 @@ class TypedConfirmDialog(_KeylessDialog): class ReconnectDialog(_KeylessDialog): - """A centered dialog shown when the companion link drops mid-session. + """A centred dialog that shows when the link to the companion goes down during a session. - An animated spinner and message sit above a single ``Abort`` button. Unlike the other - dialogs there is nothing to *choose*: the app watches for the device to return and - dismisses this screen itself (resolving its future) the moment the reconnect succeeds, so - the user's only action is to give up and abort. Only Enter resolves ``"quit"``; Esc is - deliberately inert, so an idle habit of pressing Esc can't drop the session while a replug - may be a second away. The button uses the shared ``selected`` highlight style (the theme's - cyan) — the same fill as the quit-confirmation dialog — so every popup dialog reads alike. - The animation is the reusable :class:`~meshterm.ui.tui.spinner.Spinner`, advanced by - :meth:`tick` from the session's animation timer. + An animated spinner and a message are above a single ``Abort`` button. In this dialog, + there is nothing to select, as there is in the other dialogs. The app watches for the + device to come back, and closes this dialog itself (it resolves its future) when the + reconnect is successful. Thus the only action of the user is to stop and abort. - Once the device is back but the reconnect keeps failing, the reason sits under the - spinner line (:meth:`set_detail`) — a port another program took while we waited, a - pairing that went stale — since a spinner alone would wait on it forever. + Only Enter resolves ``"quit"``. Esc does nothing, on purpose: a user who presses Esc + from habit cannot lose the session while a replug may be only one second away. The + button uses the shared ``selected`` chip style (a grey fill), the same fill as + the quit-confirmation dialog. Thus all dialogs look the same. The animation is the + reusable :class:`~meshterm.ui.tui.spinner.Spinner`, which :meth:`tick` moves forward + from the animation timer of the session. + + When the device is back but the reconnect continues to fail, the reason shows under the + spinner line (:meth:`set_detail`). For example, another program took the port while we + waited, or a pairing became stale. Without the reason, a spinner alone waits on the + problem forever. """ - #: The widest a reason runs before it wraps: a sentence or two at a reading measure, - #: rather than a box stretched to the terminal's edges to hold it on one line. + #: The maximum width of a reason before it wraps: one or two sentences at a width that is + #: easy to read, instead of a box as wide as the terminal that holds it on one line. DETAIL_MEASURE = 56 def __init__( @@ -816,11 +840,12 @@ class ReconnectDialog(_KeylessDialog): """Build the reconnect dialog. Args: - message: The line shown beside the spinner (e.g. "Waiting for your device…"). - title: Dialog heading. - footer_hint: Footer key hint (only Abort is offered). - prompt_style: Rich style for the message (``"warn"`` for the cautionary tone). - border_style: Rich style for the dialog border (read by the frame compositor). + message: The line next to the spinner (for example "Waiting for your device…"). + title: The heading of the dialog. + footer_hint: The key hint in the footer (only Abort is offered). + prompt_style: The Rich style for the message (``"warn"`` for a tone of caution). + border_style: The Rich style for the border of the dialog (the frame + compositor reads it). """ super().__init__() self.title = title @@ -833,7 +858,7 @@ class ReconnectDialog(_KeylessDialog): @property def dialog_width(self) -> int: - """Natural outer width so the frame sizes the box to its content (see ButtonDialog).""" + """Natural outer width: the frame sizes the box to its content (refer to ButtonDialog).""" detail = 0 if self._detail is not None: widest = max(cell_len(line.plain) for line in self._detail.split("\n")) @@ -845,27 +870,27 @@ class ReconnectDialog(_KeylessDialog): len(" Abort "), detail, ) - return inner + 12 # panel padding + border, plus horizontal breathing room + return inner + 12 # panel padding + border, plus horizontal space to spare @property def message(self) -> str: - """The line shown beside the spinner.""" + """The line next to the spinner.""" return self._message def set_message(self, message: str) -> None: - """Replace the line shown beside the spinner (e.g. to note a stalled retry).""" + """Replace the line next to the spinner (for example, to tell of a stalled retry).""" self._message = message def set_detail(self, detail: Text | None) -> None: - """Show why the reconnect keeps failing, under the spinner line; ``None`` clears it.""" + """Show why the reconnect continues to fail, under the spinner line. ``None`` clears it.""" self._detail = detail def tick(self) -> None: - """Advance the spinner to its next frame (driven by the session's animation timer).""" + """Move the spinner to its next animation step (the session's animation timer calls it).""" self._spinner.tick() def render_body(self, width: int) -> list[str]: - """Render the spinner and message, then any reason, centered above an Abort button.""" + """Render the spinner and the message, then a reason, centred above an Abort button.""" line = self._spinner.text() line.append(" ") line.append(self._message, style=self._prompt_style) @@ -873,8 +898,8 @@ class ReconnectDialog(_KeylessDialog): row.append(" Abort ", style="selected") parts: list[Text] = [_center(line, width)] if self._detail is not None: - # Wrapped and centred line by line; it holds no chip, so Rich's own centring - # is safe here (see _center for the one case it isn't). + # Wrapped and centred line by line. It holds no chip, so the centring of Rich + # itself is safe here (refer to _center for the one case where it is not safe). detail = self._detail.copy() detail.justify = "center" parts += [Text(""), detail] @@ -882,7 +907,7 @@ class ReconnectDialog(_KeylessDialog): return render_lines(Group(*parts), width) def handle(self, action: str, data: str = "") -> None: - """Abort only on Enter; ignore everything else, Esc included (the app auto-dismisses).""" + """Abort only on Enter. Ignore all other keys, also Esc (the app closes the dialog).""" if action == "enter": self.resolve("quit") @@ -890,14 +915,15 @@ class ReconnectDialog(_KeylessDialog): class AutocompleteScreen(_KeylessDialog): """A free-text field with a live suggestion list (``questionary.autocomplete``). - The user may type any value; matching suggestions appear below and can be highlighted - with the arrows and accepted into the field with Tab. Enter commits the typed text - (after validation). Resolves with the string, or CANCEL on Esc. + The user can type any value. The suggestions that match appear below the field. The + user can move the highlight to one of them with the arrow keys, and accept it into the + field with Tab. Enter commits the typed text (after validation). It resolves with the + string, or CANCEL on Esc. """ - #: Cap the suggestion list so it never dominates the dialog. + #: The limit of the suggestion list, so that the list never fills most of the dialog. MAX_SUGGESTIONS = 8 - #: Home and End move the field's caret, so edge scroll leaves them alone. + #: Home and End move the caret of the field, so edge scroll does not take them. home_end_jumps = False def __init__( @@ -913,12 +939,12 @@ class AutocompleteScreen(_KeylessDialog): """Build an autocomplete prompt. Args: - title: Short heading shown in the dialog's border. - choices: Suggestion strings to match against. - prompt: The instruction shown inside the box, above the field. + title: A short heading in the border of the dialog. + choices: The suggestion strings to match against. + prompt: The instruction in the box, above the field. default: Prefilled text. - validate: Optional validator run on Enter. - footer_hint: Footer key hint. + validate: An optional validator that runs on Enter. + footer_hint: The key hint in the footer. """ super().__init__() self.title = title @@ -933,7 +959,7 @@ class AutocompleteScreen(_KeylessDialog): @property def dialog_width(self) -> int: - """Natural outer width so the box fits its prompt/suggestions, not the whole screen.""" + """Natural outer width: the box fits its prompt and suggestions, not the whole terminal.""" widths = [ cell_len(self._prompt), cell_len(self.title), @@ -945,7 +971,7 @@ class AutocompleteScreen(_KeylessDialog): return max(widths) + 8 def _suggestions(self) -> list[str]: - """Return suggestions matching the current text, capped for display.""" + """Return the suggestions that match the current text, up to the maximum that shows.""" needle = self._editor.text.lower() if not needle: matches = list(self._choices) @@ -956,8 +982,8 @@ class AutocompleteScreen(_KeylessDialog): def render_body(self, width: int) -> list[str]: """Render the optional prompt, the field, the matching suggestions, and any error. - The suggestions are drawn a row at a time so the highlighted one's body line is - known (see :meth:`cursor_line`). + The suggestions are drawn one row at a time, so that the body line of the + highlighted suggestion is known (refer to :meth:`cursor_line`). """ parts: list[RenderableType] = [] if self._prompt: @@ -980,11 +1006,11 @@ class AutocompleteScreen(_KeylessDialog): return lines def cursor_line(self) -> int | None: - """The highlighted suggestion's body line, kept in view on a box too short for all.""" + """The body line of the highlighted suggestion, kept visible in a box too short for all.""" return self._cursor def handle(self, action: str, data: str = "") -> None: - """Edit the field, move/accept suggestions, submit on Enter, or cancel on Esc.""" + """Edit the field, move or accept suggestions, submit on Enter, or cancel on Esc.""" suggestions = self._suggestions() if action == "up": self._sugg = max(0, self._sugg - 1) if suggestions else 0 diff --git a/meshterm/ui/tui/render.py b/meshterm/ui/tui/render.py index 574a4c5..9330923 100644 --- a/meshterm/ui/tui/render.py +++ b/meshterm/ui/tui/render.py @@ -1,13 +1,14 @@ # SPDX-License-Identifier: Apache-2.0 -"""The single Rich-to-prompt_toolkit bridge. +"""The only bridge from Rich to prompt_toolkit. -The TUI keeps rendering in Rich (all existing tables, panels, and text widgets are reused -verbatim) and lets prompt_toolkit own the terminal, input, and resize events. This module -is the seam between the two: it renders any Rich renderable to an ANSI string at a chosen -width, which prompt_toolkit then draws via :class:`prompt_toolkit.formatted_text.ANSI`. +The TUI keeps its rendering in Rich (all the existing tables, panels, and text widgets are +used again exactly as they are). It lets prompt_toolkit own the terminal, the input, and +the resize events. This module is the seam between the two. It renders any Rich +renderable to an ANSI string at a chosen width. Then prompt_toolkit draws that string +through :class:`prompt_toolkit.formatted_text.ANSI`. -Because rendering is redone at the *current* width on every repaint, content reflows -automatically when the terminal is resized. +Each paint renders again at the current width. Thus the content wraps to the new width +automatically when the terminal changes size. """ from __future__ import annotations @@ -24,43 +25,48 @@ from ...platforms import Platform, on_platform from ..pathline import PATH_INK from ..theme import active_theme, fold_text, is_identity_style -#: Cache one headless render console per width. Consoles are cheap but repaint happens on -#: every keystroke and on the live-monitor timer, so caching avoids needless churn. Keyed -#: by width because a console's width is fixed at construction; emptied whenever the -#: platform switches, since the theme and colour system are baked in at construction. +#: A cache of one headless render console for each width. Consoles are cheap, but a paint +#: occurs at each key press and at each tick of the live-monitor timer. Thus the cache +#: prevents work that is not necessary. The cache key is the width, because the width of a +#: console is fixed at construction. The cache is cleared each time that the platform +#: changes, because the theme and the colour system are fixed at construction. _CONSOLES: dict[int, Console] = {} -#: The colour depth the rasterizer emits at — bound per platform. ``"standard"`` on the -#: 16-slot console: the theme's ``color(N)`` styles pass through as exact slot indices, -#: and any stray truecolor (a node hue, a map feature) is downsampled by Rich to the -#: nearest conventional slot — which the palette deliberately keeps hue-aligned (see -#: ``theme._VT_SLOTS``), so even strays land in their own colour family. +#: The colour depth that the rasterizer writes at, bound for each platform. On the +#: 16-slot console it is ``"standard"``. The ``color(N)`` styles of the theme go through +#: as exact slot indices. Rich downsamples any stray truecolour (a node hue, a map +#: feature) to the nearest standard slot. The palette keeps each slot aligned with its hue +#: on purpose (refer to ``theme._VT_SLOTS``), so even a stray colour lands in its own +#: colour family. _COLOR_SYSTEM = "truecolor" -#: Memoized ANSI per (content, width) for the *describable* renderables — a ``str`` or a -#: :class:`Text`, whose rendering is a pure function of their plain text, spans, and flags. -#: The TUI recomposes the whole frame on every keystroke and on the idle tick, and the -#: list-family screens rasterize row by row through :func:`render_to_ansi`; between two -#: paints almost every row is byte-identical, so this cache turns the per-row console -#: render (~0.15 ms each) into a dict hit. Tables, panels and groups have no cheap content -#: key and skip the cache (their callers memoize at their own level where it matters). +#: A cache of the ANSI for each (content, width), for the renderables that can be +#: described: a ``str`` or a :class:`Text`, whose rendering is a pure function of their +#: plain text, spans, and flags. The TUI composes the full frame again at each key press +#: and at the idle tick. The screens of the list family rasterize row by row through +#: :func:`render_to_ansi`. Between two paints, almost every row is byte-identical. Thus +#: this cache changes the console render of each row (approximately 0.15 ms each) into a +#: dict hit. Tables, panels, and groups have no cheap content key and skip the cache. +#: (Their callers cache at their own level where it is important.) _ANSI_CACHE: OrderedDict[tuple, str] = OrderedDict() -#: Entries the ANSI cache holds before evicting least-recently-used ones. Sized for a few -#: screenfuls of distinct rows (a busy list, its filtered variants, a dialog over it) at -#: well under ~2 MB; small enough that even the PicoCalc carries it without noticing. +#: The number of entries that the ANSI cache holds before it evicts the least recently +#: used entries. The size is for a few screens of different rows (a busy list, its +#: filtered variants, a dialog over it), at much less than 2 MB. It is small enough that +#: even the PicoCalc holds it with no problem. _ANSI_CACHE_MAX = 4096 -#: Generation stamp folded into every cache key. A platform switch swaps the theme and -#: colour system baked into the render consoles, so it bumps the generation instead of -#: trusting eviction — a stale entry can then never be *read*, even mid-eviction. +#: The generation stamp in each cache key. A platform switch changes the theme and the +#: colour system that are fixed in the render consoles. Thus the switch increments the +#: generation, and does not trust eviction. Then a stale entry can never be read, even in +#: the middle of an eviction. _CACHE_GEN = 0 @on_platform def _bind(platform: Platform) -> None: - """Re-bind the rasterizer's colour depth and drop stale consoles on a switch.""" + """Bind the colour depth of the rasterizer again, and remove stale consoles, on a switch.""" global _COLOR_SYSTEM, _CACHE_GEN _COLOR_SYSTEM = "truecolor" if platform.truecolor else "standard" _CONSOLES.clear() @@ -69,13 +75,13 @@ def _bind(platform: Platform) -> None: def _cache_key(renderable: RenderableType, width: int, no_wrap: bool) -> tuple | None: - """A content key for a cacheable renderable, or ``None`` when it has no cheap one. + """A content key for a renderable that can be cached, or ``None`` if it has no cheap key. - A ``str`` *is* its own content (markup included). A :class:`Text` renders as a pure - function of its plain text, span list, base style, and wrap flags — everything the - key captures (span styles via ``str``, which :class:`~rich.style.Style` memoizes). - Anything else — a table, a group, a panel — would need a deep walk to describe, so it - reports ``None`` and renders uncached. + A ``str`` is its own content (markup included). A :class:`Text` renders as a pure + function of its plain text, span list, base style, and wrap flags, and the key holds + all of these (the span styles through ``str``, which :class:`~rich.style.Style` + caches). To describe any other renderable (a table, a group, a panel), a deep walk is + necessary. Thus it reports ``None`` and renders without the cache. """ if isinstance(renderable, str): return ("s", renderable, width, no_wrap, _CACHE_GEN) @@ -97,13 +103,13 @@ def _cache_key(renderable: RenderableType, width: int, no_wrap: bool) -> tuple | def _console(width: int) -> Console: - """Return a themed, headless console that emits ANSI at the given width. + """Return a themed, headless console that writes ANSI at the given width. Args: - width: Target render width in columns. + width: The target render width, in cells. Returns: - A cached :class:`rich.console.Console` writing to an internal buffer. + A cached :class:`rich.console.Console` that writes to an internal buffer. """ console = _CONSOLES.get(width) if console is None: @@ -113,11 +119,11 @@ def _console(width: int) -> Console: file=StringIO(), force_terminal=True, color_system=_COLOR_SYSTEM, - # This console is a rasterizer, not terminal output: its ANSI is re-parsed - # by prompt_toolkit, and the TUI's hues are semantics (node identity, - # recency heat), not decoration. So a NO_COLOR environment must not strip - # them here — the scripted CLI's real console (theme.build_console) is the - # one that honours NO_COLOR. + # This console is a rasterizer, not terminal output. prompt_toolkit parses its + # ANSI again, and the hues of the TUI are semantics (node identity, recency + # heat), not decoration. Thus a NO_COLOR environment must not remove them + # here. The real console of the scripted CLI (theme.build_console) is the + # console that obeys NO_COLOR. no_color=False, highlight=False, soft_wrap=False, @@ -127,41 +133,43 @@ def _console(width: int) -> Console: def _whiten_identities(renderable: RenderableType) -> RenderableType: - """On the cursor row, a node's name is drawn in the highlight's white, not its hue. + """On the highlight, the name of a node is drawn in the highlight's white, not its hue. - A node's name is always coloured by its key, so a column of them reads as a column of - identities — but the row the ``❯`` points at is answering a different question, and a - keyed hue on it competes with the very highlight that says "this one". So the row that - declares itself the cursor (its *base* style is ``cursor``, which is how every list and - every screen drawing its own rows marks it) has its identity spans folded to that same - white, and the row reads as one thing. + The name of a node is always coloured by its key, so a column of names reads as a + column of identities. But the row that ``❯`` points to answers a different question, + and a keyed hue on it competes with the highlight that says "this one". Thus the row + that declares itself the highlight has its identity spans folded to that same white, + and the row reads as one thing. (Its base style is ``cursor``. That is how each list, + and each screen that draws its own rows, marks the highlight.) - Only :func:`~meshterm.ui.theme.is_identity_style` hues fold. Everything else on the row - is untouched — the heard-age heat, an SNR reading, a red badge, a path line's chip - fills, the grey of a node no key could place — because none of those are the identity - the highlight is standing in for. + Only :func:`~meshterm.ui.theme.is_identity_style` hues fold. Nothing else on the row + changes: the heat of the heard age, an SNR reading, a red badge, the chip fills of a + path line, the grey of a node that no key could place. None of these is the identity + that the highlight stands in for. - **A path line is spared**, wherever it sits on the row. There the hue is not decoration - on a name: it is what tells one hop from the next, and what a route graph drawn above - the row is cross-referenced by — its labels are a marker and one byte of hash, and the - colour is what says *which node*. So a picked route kept its hops' colours in chip form - (the fills were never in this vocabulary) and lost them in arrow form, which is every - path line on the PicoCalc and on any terminal without the powerline glyphs (JP, - 2026-08-30). The widget stamps its own extent with - :data:`~meshterm.ui.pathline.PATH_INK` and the stamp arrives here as a span over the - hops (``Text.append_text`` keeps a child's base style as one), so the route is spared - by name rather than by each screen remembering to ask. + **A path line keeps its hues**, at any position on the row. There the hue is not + decoration on a name. It tells one hop from the next, and a route graph drawn above + the row is cross-referenced by it. The labels of that graph are a marker and one byte + of hash, and the colour is what says which node. Earlier, a picked route kept the + colours of its hops in chip form (the fills were never in this vocabulary), but lost + them in arrow form (JP, 2026-08-30). Arrow form is each path line on the PicoCalc, and + on each terminal without the powerline glyphs. - Done here because this is where a row *is* a row: one boundary every screen's rows - already leave through, rather than a rule each of them has to remember. Callers hand us - read-only :class:`Text` (the ANSI cache keys on their content), so the rewrite is on a - copy. + The widget stamps its own extent with :data:`~meshterm.ui.pathline.PATH_INK`. The + stamp arrives here as a span over the hops (``Text.append_text`` keeps the base style + of a child as one span). Thus the fold skips the route by its name, and no screen has + to remember to ask. + + This is done here because here a row is a row: one boundary that the rows of each + screen already go through, instead of a rule that each screen has to remember. Callers + give read-only :class:`Text` (the ANSI cache uses their content as its key), so the + change is done on a copy. Args: - renderable: Whatever is about to be rendered. + renderable: The renderable that is about to be rendered. Returns: - The renderable, or a cursor row's copy with its name hues turned white. + The renderable, or a copy of a highlight row with its name hues changed to white. """ if not isinstance(renderable, Text) or str(renderable.style) != "cursor": return renderable @@ -180,18 +188,18 @@ def _whiten_identities(renderable: RenderableType) -> RenderableType: def _within(span: Span, runs: list[tuple[int, int]]) -> bool: - """Does ``span`` lie inside one of ``runs`` — a hop inside a marked path line?""" + """Whether ``span`` is inside one of ``runs``: a hop inside a marked path line.""" return any(start <= span.start and span.end <= end for start, end in runs) def render_to_ansi(renderable: RenderableType, width: int, *, no_wrap: bool = False) -> str: - """Render a Rich renderable to an ANSI string at ``width`` columns. + """Render a Rich renderable to an ANSI string at ``width`` cells. Args: renderable: Any Rich renderable (table, panel, text, group, markup string). - width: Target width in columns; content wraps/pads to it. - no_wrap: When ``True``, keep the content on a single line — show what fits and - crop the overflow (with an ellipsis) instead of wrapping onto more rows. + width: The target width in cells. The content wraps or pads to it. + no_wrap: When ``True``, keep the content on a single line: show what fits, and + crop the overflow (with an ellipsis). Do not wrap it onto more lines. Returns: The rendered output as an ANSI-escaped string, without a trailing newline. @@ -210,10 +218,11 @@ def render_to_ansi(renderable: RenderableType, width: int, *, no_wrap: bool = Fa console.print(renderable, end="", no_wrap=True, overflow="ellipsis", crop=True) else: console.print(renderable, end="") - # THE render boundary: every visible string in the TUI leaves through here, so this - # one call is what makes the PicoCalc glyph contract hold app-wide (identity on the - # regular platform). Widths were measured on the pre-fold text; the fold preserves - # cell counts (wide emoji become glyph + pad), so the layout above survives it. + # The only render boundary: each visible string in the TUI goes out through here. Thus + # this one call makes the PicoCalc glyph contract true in all of the app (on the + # regular platform, the fold changes nothing). The widths were measured on the text + # before the fold. The fold keeps the cell counts (a wide emoji becomes a glyph and a + # pad), so the layout above stays correct after it. out = fold_text(capture.get()) if key is not None: _ANSI_CACHE[key] = out @@ -223,20 +232,20 @@ def render_to_ansi(renderable: RenderableType, width: int, *, no_wrap: bool = Fa def render_lines(renderable: RenderableType, width: int, *, no_wrap: bool = False) -> list[str]: - """Render a Rich renderable to a list of ANSI lines at ``width`` columns. + """Render a Rich renderable to a list of ANSI lines at ``width`` cells. - Each returned line is an independently styled ANSI string, so the caller can slice a - vertical viewport (for scrolling) without splitting escape sequences. + Each line that is returned is an ANSI string with its own styles. Thus the caller can + slice a vertical range of lines (to scroll), and no escape sequence is split. Args: renderable: Any Rich renderable. - width: Target width in columns. - no_wrap: When ``True``, keep the content to a single cropped line (see + width: The target width in cells. + no_wrap: When ``True``, keep the content to a single cropped line (refer to :func:`render_to_ansi`). Returns: - The rendered lines, newline-free. A trailing empty line (from the final newline) - is dropped so line counts match visible rows. + The rendered lines, with no newlines. A trailing empty line (from the last + newline) is removed, so that the line count matches the visible lines. """ ansi = render_to_ansi(renderable, width, no_wrap=no_wrap) lines = ansi.split("\n") @@ -246,23 +255,25 @@ def render_lines(renderable: RenderableType, width: int, *, no_wrap: bool = Fals def query_line(query: str, width: int) -> str: - """The live find/filter query echoed as one body line: ``/hub``, warn-styled. + """The live find or filter query, shown as one body line: ``/hub``, in the warn style. - THE way a find-as-you-type screen shows what has been typed. Every such screen draws - this same line above whatever the query narrows — the select list above its rows, the - path composer above its suggestions, the map above its canvas, the walk above its link - list — so the text you are typing is always in the same shape, in the same place, in - the one colour nothing else in a body uses. + The only way that a find-as-you-type screen shows what the user typed. Each such + screen draws this same line above the content that the query narrows: the select list + above its rows, the path composer above its suggestions, the map above its canvas, and + the walk above its link list. Thus the text that the user types always has the same + shape, in the same place, in the one colour that nothing else in a body uses. - The map and the walk *also* echo the query in their footer hint, with its editing keys - beside it. That line is not drawn on a platform whose footer is the F-key lane (see - :attr:`~meshterm.platforms.Platform.footer_fkeys`), which is exactly why those two - call this: without it, the query would be invisible on the device while you typed it. - They gate the call on that flag rather than drawing the line twice on the desktop. + The map and the walk also show the query in their footer hint, with the keys that edit + it next to it. That line is not drawn on a platform whose footer is the F-key lane + (refer to :attr:`~meshterm.platforms.Platform.footer_fkeys`). That is why those two + screens call this function: without it, the query is not visible on the handheld + while the user types it. They call it only when that flag is set, so that the desktop + does not draw the line two times. Args: - query: The current query (callers only call this when it is non-empty). - width: Inner content width in columns. + query: The current query (callers call this function only when the query is not + empty). + width: The inner content width, in cells. Returns: One rendered ANSI line. @@ -271,16 +282,18 @@ def query_line(query: str, width: int) -> str: def query_text(query: str) -> Text: - """The same echo as a styled run, for a surface that lays the row out itself. + """The same echo as a styled run, for a surface that does the layout of the row itself. - :func:`query_line` is the whole line and the usual call; this is the run inside it, - wanted where something else shares the row. The map is the one such caller: its credit - is pinned to the row's right end (see :mod:`meshterm.ui.attribution`), so the query has - to arrive croppable rather than already rendered to the full width. Both go through - this one constructor, so the shape and the ``warn`` colour cannot drift apart. + :func:`query_line` is the full line and the usual call. This function is the run in + that line, for a place where something else shares the row. The map is the only such + caller. Its credit is pinned to the right end of the row (refer to + :mod:`meshterm.ui.attribution`). Thus the query must arrive in a form that can be + cropped, not already rendered to the full width. Both functions use this one + constructor, so the shape and the ``warn`` colour cannot become different. Args: - query: The current query (callers only call this when it is non-empty). + query: The current query (callers call this function only when the query is not + empty). Returns: The echo, ``warn`` and ``no_wrap``. @@ -289,18 +302,19 @@ def query_text(query: str) -> Text: def right_aligned_tail(body: Text, tail: Text, width: int) -> Text: - """Lay ``body`` out with ``tail`` pinned to the right edge of its last line. + """Lay out ``body`` with ``tail`` pinned to the right edge of its last line. - ``body`` wraps at ``width`` as usual; ``tail`` — a short status such as the chat - compose bar's byte counter — is right-aligned on ``body``'s final wrapped line when - it still fits there (after at least one blank cell), otherwise on a new line of its - own, also right-aligned. So the tail reads as a steady gauge in the corner rather - than trailing the cursor and wrapping along with the text. + ``body`` wraps at ``width`` as usual. ``tail`` is a short status, for example the byte + counter of the chat compose bar. It is right-aligned on the last wrapped line of + ``body`` when it still fits there (after at least one blank cell). If not, it goes on + a new line of its own, also right-aligned. Thus the tail reads as a steady gauge in + the corner, and does not follow the cursor and wrap with the text. Args: - body: The wrappable leading content (e.g. the input line, cursor block included). + body: The leading content that can wrap (for example, the input line, with the + cursor block). tail: The short run to pin to the right edge. - width: Total render width in columns. + width: The total render width, in cells. Returns: A single :class:`Text` with embedded newlines, ready for :func:`render_lines`. @@ -326,21 +340,21 @@ def right_aligned_tail(body: Text, tail: Text, width: int) -> Text: def crop_cells(text: Text, start: int, width: int) -> Text: - """Cut a single-line styled Text to the cell window ``[start, start + width)``. + """Cut a single-line styled Text to the cell range ``[start, start + width)``. - The horizontal-scroll primitive: a row wider than its lane is shown ``width`` - cells at a time, shifted ``start`` cells in, styling preserved. Boundaries are - measured in display cells, so a double-width glyph straddling either edge is - dropped (replaced by a pad space on the left) rather than half-shown. + The primitive for horizontal scroll: a row that is wider than its lane shows ``width`` + cells at a time, moved ``start`` cells in, with its styles kept. The boundaries are + measured in cells. Thus a double-width glyph that crosses either edge is removed (and + replaced by a pad space on the left), and is not shown as a half. Args: text: The styled line to crop (treated as a single line). - start: Cells to skip from the left (clamped at 0). - width: Cells the window spans. + start: The cells to skip from the left (clamped at 0). + width: The cells that the range spans. Returns: - A new :class:`Text` at most ``width`` cells wide, ``no_wrap`` set so the - caller can drop it straight into a row. + A new :class:`Text` that is at most ``width`` cells wide, with ``no_wrap`` set so + that the caller can put it directly into a row. """ start = max(0, start) plain = text.plain @@ -352,8 +366,8 @@ def crop_cells(text: Text, start: int, width: int) -> Text: for i, ch in enumerate(plain): w = cell_len(ch) if acc + w > start: - # This character crosses the cut: keep it when it starts exactly at - # the boundary, else drop it and pad for its protruding half. + # This character crosses the cut. Keep it when it starts exactly at the + # boundary. If not, remove it, and pad for the half that sticks out. index, pad = (i, 0) if acc == start else (i + 1, acc + w - start) break acc += w @@ -372,45 +386,50 @@ def render_hanging( whole: Sequence[tuple[int, int]] = (), gutter: int = 0, ) -> list[str]: - """Render ``prefix + body`` at ``width``, wrapping the body with a hanging indent. + """Render ``prefix + body`` at ``width``, and wrap the body with a hanging indent. - The first visual line carries ``prefix`` followed by the body; every wrapped - continuation line is padded by ``indent`` columns so it aligns under the body rather - than falling back to column zero. Used by the chat transcript so a wrapped message - lines up with its own first line instead of with the timestamp gutter. + The first visual line has ``prefix``, then the body. Each wrapped continuation line is + padded by ``indent`` cells, so that it aligns under the body and does not go back to + column zero. The chat transcript uses this function, so that a wrapped message aligns + with its own first line and not with the timestamp gutter. - ``whole`` names runs of the body that must not be cut where the screen can hold them — - a URL, which a terminal can only open, and a reader only copy, while it sits on one - line. A run that fits the hanging lane needs nothing: the wrap already moves a word - to the next line rather than splitting it. One that outruns the lane but not the - screen steps out of the block onto a line of its own, starting at ``gutter`` (or as - far right of it as still fits); the body resumes under its indent after it, unless - what follows is short enough to finish the run's own line. Only a run wider than the - whole screen is folded, as before, since no line could hold it. + ``whole`` names runs of the body that must not be cut where the screen can hold them. + A URL is such a run: a terminal can open it, and a user can copy it, only while it is + on one line. For a run that fits the hanging lane, nothing is necessary, because the + wrap already moves a word to the next line and does not split it. A run that is wider than the + lane, but not wider than the screen, steps out of the block onto a line of its own. It + starts at ``gutter``, or as far to the right of the gutter as still fits. After it, + the body continues under its indent, unless the text that follows is short enough to + finish the line of the run. Only a run wider than the full screen is folded, as + before, because no line can hold it. Args: - prefix: The leading run (e.g. a pointer + timestamp) shown once, on the first line. - body: The wrappable message text; styling (mentions, glyphs) is preserved. - width: Total render width in columns. - indent: Columns to indent continuation lines by (typically ``prefix.cell_len``). - whole: ``(start, end)`` offsets into ``body.plain`` of runs to keep on one line. - gutter: The column a run too wide for the lane starts at, when it can. + prefix: The leading run (for example, a pointer and a timestamp), shown one time, + on the first line. + body: The message text that can wrap. Its styles (mentions, glyphs) are kept. + width: The total render width, in cells. + indent: The cells by which to indent continuation lines (usually + ``prefix.cell_len``). + whole: ``(start, end)`` offsets into ``body.plain`` of the runs to keep on one + line. + gutter: The column at which a run that is too wide for the lane starts, when it + can. Returns: - The rendered lines, newline-free. + The rendered lines, with no newlines. """ width = max(1, width) console = _console(width) avail = max(1, width - indent) plain = body.plain - # The runs that need the step out: wider than the lane, no wider than the screen. + # The runs that must step out: wider than the lane, but not wider than the screen. out = [ (start, end) for start, end in sorted(whole) if avail < cell_len(plain[start:end]) <= width ] - rows: list[tuple[int, Text]] = [] # (left pad, line); the first row's pad is the prefix + rows: list[tuple[int, Text]] = [] # (left pad, line). The pad of the first row is the prefix. def hang(start: int, end: int) -> None: - """Wrap ``body[start:end]`` under the indent, trimming the seams beside a run.""" + """Wrap ``body[start:end]`` under the indent, and trim the seams next to a run.""" if out: while start < end and plain[start].isspace() and start: start += 1 @@ -418,7 +437,7 @@ def render_hanging( end -= 1 lines = list(body[start:end].wrap(console, avail)) if end > start else [] if not rows and not lines: - lines = [Text("")] # the prefix's line, even when the body opens on a run + lines = [Text("")] # the line of the prefix, also when the body starts with a run rows.extend((indent, line) for line in lines) pos = 0 @@ -429,8 +448,8 @@ def render_hanging( length = cell_len(plain[start:end]) pad = gutter if length + gutter <= width else width - length line = body[start:end] - # What follows up to the next run joins this line when it fits whole: a delivery - # mark or an SNR left alone on a line of its own reads as a stray. + # The text up to the next run joins this line when all of it fits. A delivery mark + # or an SNR alone on a line of its own reads as a stray. upto = out[i + 1][0] if i + 1 < len(out) else len(plain) tail = plain[end:upto].rstrip() if tail and "\n" not in tail and pad + length + cell_len(tail) <= width: diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index cc4a016..bf23ca1 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -1,14 +1,15 @@ # SPDX-License-Identifier: Apache-2.0 -"""The screen abstraction: one layer in the TUI's window stack. +"""The screen abstraction: one layer in the screen stack of the TUI. -A :class:`Screen` knows how to render its body (as Rich, converted to ANSI lines by -:mod:`~meshterm.ui.tui.render`) and how to react to normalized key *actions* dispatched by -the :class:`~meshterm.ui.tui.session.TuiSession`. Screens never touch prompt_toolkit or the -terminal directly, so they stay small, uniform, and testable. +A :class:`Screen` knows how to render its body (as Rich, which +:mod:`~meshterm.ui.tui.render` changes into ANSI lines). It also knows how to respond to +the normalized key *actions* that the :class:`~meshterm.ui.tui.session.TuiSession` +dispatches to it. A screen never uses prompt_toolkit or the terminal directly. Thus the +screens stay small, uniform, and easy to test. -Interactive screens (select, text, confirm) resolve an :class:`asyncio.Future` when the user -commits or cancels; the session awaits that future and then pops the screen, giving the -push/await/pop model behind ``await session.select(...)`` and friends. +An interactive screen (select, text, confirm) resolves an :class:`asyncio.Future` when the +user commits or cancels. The session awaits that future and then pops the screen. This is +the push/await/pop model of ``await session.select(...)`` and the related calls. """ from __future__ import annotations @@ -25,100 +26,110 @@ from rich.text import Text from .render import render_hanging, render_lines from .spinner import Spinner -#: Sentinel a screen resolves with when the user presses Esc to cancel, distinct from a -#: legitimately selected ``None`` value. +#: The sentinel that a screen resolves with when the user presses Esc to cancel. It is +#: different from a ``None`` value that the user selected. CANCEL = object() -#: Sentinel the session resolves the top screen's future with when the pop-all key is -#: pressed (^W). It is never a legitimate result: every navigation boundary that sees it -#: turns it straight into :class:`PopToMenu`, so no caller ever has to test for it. +#: The sentinel that the session resolves the future of the top screen with, when the user +#: presses the pop-all key (^W). It is never a valid result: each navigation boundary that +#: gets it changes it immediately into :class:`PopToMenu`. Thus a caller never has to test +#: for it. POP_ALL = object() -#: Edge scroll's keys (see :meth:`Screen.edge_scroll`): the arrows and the way each steps, -#: the jumps to either end, and the keys besides the arrow pointing at it that bring an -#: off-screen highlight back into view before doing anything — the keys that act on it. +#: The keys of the edge scroll (refer to :meth:`Screen.edge_scroll`). They are the arrows +#: and the direction of each step, the jumps to the two ends, and the keys that act on the +#: highlight. When the highlight is off the screen, a key of this last group (and the arrow +#: that points at the highlight) first makes the highlight visible again, before it does +#: anything. _EDGE_STEPS = {"up": -1, "down": 1} _EDGE_ENDS = {"home": -1, "ctrl_home": -1, "end": 1, "ctrl_end": 1} _SNAP_BACK_ACTIONS = frozenset({"enter", "delete"}) class PopToMenu(BaseException): - """Raised through every awaiting navigation frame to unwind to the main menu. + """Raised through each navigation call that awaits a screen, to unwind to the main menu. - The whole realized path is a stack of pending ``await`` expressions — a screen's caller - awaiting its result, that caller's caller awaiting *it* — so the one way to leave every - frame at once is to raise through them all. Each frame pops its own screen in a ``finally`` on - the way out, which is exactly the strict single-pop discipline applied N times: no - screen is ever dropped without its owner unwinding. + The full path that the user opened is a stack of pending ``await`` expressions. The + caller of a screen awaits its result, and the caller of that caller awaits the caller in + turn. Thus the only way to leave all the screens on the stack at the same time is to + raise through all of these expressions. On the way out, each caller pops its own screen + in a ``finally``. This is the strict rule of one pop for each push, applied N times: a + screen is never removed unless its owner unwinds. - It derives from :class:`BaseException`, not :class:`Exception`, for the same reason - :class:`asyncio.CancelledError` does: the app is full of ``except Exception`` guards - that stop a misbehaving tool from taking down the menu - (:func:`~meshterm.ui.menu._run_selection` is the widest), and an unwind must pass - through them rather than be swallowed and reported as a tool failure. ``finally`` - blocks still run, so nothing leaks. + It derives from :class:`BaseException`, not :class:`Exception`, for the same reason as + :class:`asyncio.CancelledError`. The app has many ``except Exception`` guards. These + guards stop a tool that has a fault before it can stop the menu + (:func:`~meshterm.ui.menu._run_selection` has the widest guard). An unwind must go + through these guards. They must not catch it and report it as a failure of a tool. + ``finally`` blocks still run, so nothing leaks. - Caught in exactly one place — the main menu loop, which is the unwind's destination. + Only one place catches it: the main menu loop, where the unwind ends. """ class Screen: - """Base class for every TUI layer. + """Base class for each TUI layer. Attributes: - title: Heading shown at the top of the screen/dialog. - short_title: The abbreviated heading the frame draws instead of :attr:`title` where - the full one would not fit the rule it sits in (see - :func:`~meshterm.ui.tui.frame.fitted_title`) — the same atoms said tighter, so a - narrow frame still carries every figure rather than a title cut off mid-word. - Empty (the default) means the title has no shorter form. - footer_hint: One-line key hint shown in the footer. - scroll: Current vertical scroll offset into the body's rendered lines. - future: Resolved with the screen's result (or :data:`CANCEL`) when it commits. - floating: Whether the session should draw this screen as a centered dialog over - the dimmed screen beneath it (deeper layers float; the base does not). - modal: Whether this layer is a *dialog* — a prompt or a running operation that - owns the keyboard until it is answered or finishes. Distinct from - :attr:`floating`, which is only about how the layer is drawn: an ordinary - select list floats as a box and is not modal, while a progress dialog is - modal and a full-frame busy splash is modal without floating at all. The - pop-all key (^W) refuses to fire while a modal layer is on top, so an unwind - can never blow past an unanswered question or yank the stack out from under - work in flight. - grow_only: Whether a floating dialog may only ever grow. Its box is sized to the - tallest body — and, for a natural-width dialog, the widest — it has shown, not - the current one, so a screen whose content swings as it changes (the packet - viewer paging between packets, the path composer's shifting suggestions) keeps - a steady, centred box — blank-padded when the current body is shorter — instead - of resizing on every change. - chrome: Whether, as the base screen, this layer is wrapped in the session's - persistent header/footer frame. A startup splash sets this ``False`` so the - session instead centers it under the :attr:`banner` with no status bars. - bare: Whether, as the base screen, this layer is the *whole frame*: its body on - blank rows with no header, no footer, no title bar, no box and no wordmark — - for a screen that is one thing a camera or a reader looks at (the share - screen's QR code, see :func:`~meshterm.ui.qr.share_screen`). Nothing is - advertised on it: Esc leaves, and Esc is on every keyboard. Read before - :attr:`chrome`; a bare screen is never floating. - banner: Block-glyph art (one string per row) drawn, centered, above a chromeless - base screen. Ignored while ``chrome`` is ``True``. - footnote: A short line drawn muted and centered *below* a chromeless base screen's - box (e.g. a copyright notice). Ignored while ``chrome`` is ``True``. - bottom_caption: A short credit or label set into the **bottom border rule**, - right-justified, the way :attr:`title` sits in the top one — for something - that belongs to the framed picture rather than to any row inside it. The map's - OpenStreetMap credit is the reason it exists (see - :mod:`meshterm.ui.attribution`): a bordered frame already draws that rule, so - a caption in it costs the body nothing at all. Read fresh every paint, so a - screen may change it as its state changes. Drawn only where the platform's - frame *has* a bottom rule — the borderless one has none, and a screen wanting - a mark there puts it in its own body instead. - flush: Whether, as the base screen in a bordered frame, the body runs right up to - the panel's side borders instead of sitting one blank column in from each. The - padding is air between a border and a row of *text*; a picture that fills the - frame (the map) has no text edge to keep off the border, and those two columns - are drawing it would otherwise give up for nothing (JP, 2026-10-01). Moot where - the platform's frame has no border — the body is the full width there already. + title: The heading at the top of the screen or the dialog. + short_title: The short heading that the frame draws instead of :attr:`title` when + the full heading does not fit in its rule (refer to + :func:`~meshterm.ui.tui.frame.fitted_title`). It has the same atoms in fewer + cells. Thus a narrow frame still shows each figure, instead of a title that is + cut in the middle of a word. Empty (the default) means that the title has no + shorter form. + footer_hint: The key hint of one line in the footer. + scroll: The current vertical scroll offset in the rendered lines of the body. + future: Resolved with the result of the screen (or :data:`CANCEL`) when the screen + commits. + floating: Whether the session draws this screen as a dialog at the centre, over the + dimmed screen below it (deeper layers float, the base layer does not). + modal: Whether this layer owns the keyboard. A modal layer is a prompt, or an + operation in progress, that owns the keyboard until the user answers it or it + finishes. This is different from :attr:`floating`, which is only about how the + layer is drawn. A usual select list floats as a box and is not modal. A + progress dialog is modal. A full-frame busy splash is modal and does not float. + The pop-all key (^W) does not operate while a modal layer is on top. Thus an + unwind can never go past a question that has no answer, or remove the stack + from under work in progress. + grow_only: Whether a floating dialog can only grow. The size of its box is the + size of the tallest body that it showed (and, for a dialog with a natural + width, the widest), not of the current body. Thus a screen whose content + changes size (the packet viewer when it pages between packets, the suggestions + of the path composer, which move) keeps a steady box at the centre, instead of + a box that changes size at each change. Blank lines fill the box when the + current body is shorter. + chrome: Whether this layer, as the base screen, is wrapped in the persistent header + and footer frame of the session. A startup splash sets this attribute to + ``False``. Then the session puts the splash at the centre, under the + :attr:`banner`, with no status bars. + bare: Whether this layer, as the base screen, is the full frame: its body on blank + rows, with no header, no footer, no title bar, no box, and no wordmark. It is + for a screen that shows one thing for a camera or a user to look at (the QR + code of the share screen, refer to :func:`~meshterm.ui.qr.share_screen`). The + screen shows no keys: Esc leaves, and each keyboard has an Esc key. This + attribute is read before :attr:`chrome`. A bare screen never floats. + banner: Block-glyph art (one string for each line), drawn at the centre above a + base screen that has no chrome. Ignored while ``chrome`` is ``True``. + footnote: A short line, drawn muted and at the centre, below the box of a base + screen that has no chrome (for example, a copyright notice). Ignored while + ``chrome`` is ``True``. + bottom_caption: A short credit or label, set right-justified into the **bottom + border rule**, in the same way as :attr:`title` is in the top rule. It is for + something that belongs to the picture in the frame, not to a row in it. The + OpenStreetMap credit of the map is the reason that it exists (refer to + :mod:`meshterm.ui.attribution`). A frame with a border already draws that + rule, so a caption in it takes no space from the body. It is read again at + each paint, so a screen can change it when its state changes. It is drawn only + where the frame of the platform has a bottom rule. The borderless frame has + none, and a screen that wants a mark there puts it in its own body instead. + flush: Whether the body of this base screen, in a frame with a border, goes all the + way to the side borders of the panel, instead of one blank cell in from each + border. The padding is space between a border and a line of text. A picture + that fills the frame (the map) has no text edge to keep away from the border. + Without this attribute, the picture loses those two cells of drawing for no + reason (JP, 2026-10-01). It has no effect where the frame of the platform has + no border, because the body already has the full width there. """ title: str = "" @@ -133,25 +144,27 @@ class Screen: bare: bool = False banner: Sequence[str] | None = None footnote: str | None = None - #: Whether the page edge-scrolls (see :meth:`edge_scroll`). On for every screen, and - #: nothing to do on one whose page has no highlight (:meth:`cursor_line` ``None``). Off - #: only where the line :meth:`cursor_line` keeps in view is not a highlight the arrows - #: walk — the remote CLI's prompt, whose ↑↓ recall history the way a shell's do. + #: Whether the page has edge scroll (refer to :meth:`edge_scroll`). It is on for each + #: screen. It does nothing on a screen whose page has no highlight (:meth:`cursor_line` + #: is ``None``). It is off only where the line that :meth:`cursor_line` keeps visible is + #: not a highlight that the arrows move: the prompt of the remote CLI, whose ↑↓ recall + #: the history, as in a shell. edge_scrolls: bool = True - #: Whether Home and End take the page to its very top and bottom once the screen has - #: handled them (see :meth:`edge_scroll`) — a list's Home and End jump its highlight to - #: the first and last row, and the page follows to its ends. Off where they move a text - #: caret instead — the chat's compose line, a prompt's field. + #: Whether Home and End move the page to its top and its bottom after the screen handles + #: them (refer to :meth:`edge_scroll`). In a list, Home and End move the highlight to the + #: first and the last row, and the page follows to its ends. It is off where these keys + #: move a text caret instead: the compose line of the chat, the field of a prompt. home_end_jumps: bool = True @property def fkey_lane(self): - """The screen's F-key lane on the active platform (see :mod:`~meshterm.ui.tui.fkeys`). + """The F-key lane of the screen on the active platform. - Each handheld deals its own: this reads whichever of the screen's lane definitions - the platform's deck names (:attr:`picocalc_lyra_lane`, :attr:`cardputer_zero_lane`). A - platform with no lane — the desktop, whose footer is the hint line — gets an empty - one. Override the per-deck definitions, never this. + Refer to :mod:`~meshterm.ui.tui.fkeys`. Each handheld has its own lane. This + property reads the lane definition of the screen that the deck of the platform + names (:attr:`picocalc_lyra_lane`, :attr:`cardputer_zero_lane`). A platform with no + lane (the desktop, whose footer is the hint line) gets an empty lane. Override the + definitions for each deck, never this property. """ from .fkeys import EMPTY_LANE, active_deck @@ -160,81 +173,90 @@ class Screen: @property def cardputer_zero_lane(self): - """The screen's lane on the Cardputer Zero: the PicoCalc's, for now. + """The lane of the screen on the Cardputer Zero: for now, the lane of the PicoCalc. - JP, 2026-09-30: the Cardputer deals the same entries as the PicoCalc until decided - otherwise — its Page Up/Down are real keys, but Fn+L/M is an awkward reach. Both - having five slots is a coincidence of two keyboards, so this is the one place the - two are tied; a screen whose Cardputer lane should differ overrides this. + JP decided on 2026-09-30 that the Cardputer deals the same entries as the PicoCalc, + until a new decision. Its Page Up/Down are real keys, but Fn+L/M is hard to reach. + That the two keyboards both have five slots is a coincidence. Thus this property is + the only place that ties the two lanes together. A screen whose Cardputer lane must + be different overrides this property. """ return self.picocalc_lyra_lane @property def picocalc_lyra_lane(self): - """The screen's lane on the PicoCalc (see :mod:`~meshterm.ui.tui.fkeys`). + """The lane of the screen on the PicoCalc (refer to :mod:`~meshterm.ui.tui.fkeys`). - Five slots, F1–F5, each with an optional F6–F10 Shift-bank companion. A slot is - for functionality that is otherwise hard to reach — Enter/Esc never appear, since - both keys are already close at hand. The default puts paging (no physical key at - all) on the prime F4/F5 pair and the jump-to-top/end pair behind Shift on those - same two keys, since Home and End *are* on this keyboard and only ever wanted a - chip for consistency with the pager they belong to. F1–F3 are left free: they are - where a screen's own verbs go, and a screen with none leaves them blank. A screen - overrides this property for its own verbs; the lane may differ screen to screen. + The lane has five slots, F1–F5. Each slot can have a companion F6–F10 in the Shift + bank. A slot is for a function that is otherwise hard to reach. Enter and Esc never + appear, because these two keys are already easy to reach. - Read fresh every paint, so an override dims the slots whose action would do - nothing right now rather than advertising a dead key — the lane's standing rule - (see :mod:`~meshterm.ui.tui.fkeys`). Screens whose nav keys only scroll gate the - shared slots on :attr:`content_overflows`; this base can't assume that much, - since a nav key elsewhere moves a cursor, a pick, or the map's zoom. + The default puts paging (which has no physical key) on the main F4/F5 pair. It puts + the pair that jumps to the top and the end behind Shift on the same two keys. Home + and End are on this keyboard, and they got a chip only for consistency with the + pager that they belong to. F1–F3 stay free: a screen puts its own verbs there, and a + screen with no verbs leaves them blank. A screen overrides this property for its own + verbs, so the lane can be different on each screen. + + The lane is read again at each paint. Thus an override can dim each slot whose + action has no effect at that time, instead of showing a key that does nothing. This + is the permanent rule of the lane (refer to :mod:`~meshterm.ui.tui.fkeys`). A screen + whose navigation keys only scroll controls the shared slots with + :attr:`content_overflows`. This base class cannot assume as much, because on other + screens a navigation key moves a highlight, a selection, or the zoom of the map. """ from .fkeys import DEFAULT_LANE return DEFAULT_LANE def bar_title(self, title: str, style: str) -> Text: - """The heading as the borderless title bar draws it: ``title`` in the bar's ``style``. + """The heading as the borderless title bar draws it: ``title`` in the bar ``style``. - ``title`` is whichever form the bar chose (:func:`~meshterm.ui.tui.frame.fitted_title`). - A heading that is a *mark* rather than words keeps the mark's own colours by - overriding this — the main menu's wordmark, on a frame with no header row to carry - it (see :attr:`~meshterm.platforms.Platform.header_row`). + ``title`` is the form that the bar chose (:func:`~meshterm.ui.tui.frame.fitted_title`). + A heading that is art instead of words overrides this method to keep the colours of + the art. An example is the wordmark of the main menu, on a frame that has no header + row for it (refer to :attr:`~meshterm.platforms.Platform.header_row`). """ return Text(title, style=style) def __init__(self) -> None: - """Initialize scroll state and the (later-assigned) result future.""" + """Initialize the scroll state and the result future (assigned later).""" self.scroll = 0 self.future: asyncio.Future | None = None - # (body-line index, rendered ANSI lines) for each section landmark eligible to be - # pinned to the top rows once it scrolls off. A block is usually one line — a section - # heading, a day divider — but may carry the rows that belong with it (a heading and - # the description under it), which pin together as they scroll off, in order. A screen - # that wants sticky headers rebuilds this list while rendering its body (see - # :meth:`sticky_block`); the default is no landmarks. + # (body-line index, rendered ANSI lines) for each section landmark that can pin to + # the top lines after it scrolls off. A block is usually one line (a section heading, + # a day divider). But it can also hold the lines that belong with it (a heading and + # the description under it). These lines pin together, in order, as they scroll + # off. A screen that wants sticky headers builds this list again while it renders + # its body (refer to :meth:`sticky_block`). The default is no landmarks. self._sticky_headers: list[tuple[int, list[str]]] = [] - # The one header that pins for the *whole* list rather than for its section — a - # table's column header, which means nothing scrolled off (see :meth:`sticky_rows`). - # Recorded the same way, as (body-line index, rendered line); ``None`` for none. + # The only header that pins for the full list instead of for its section: the + # column header of a table, which has no meaning after it scrolls off (refer to + # :meth:`sticky_rows`). It is kept in the same form, as (body-line index, rendered + # line). ``None`` if there is none. self._pinned_header: tuple[int, str] | None = None - # The last render's body height and viewport, recorded by the frame (:meth:`note_metrics`) - # so the shared scroll helpers can page by a screenful of the *current* terminal and - # clamp to the content without every caller threading the sizes through. + # The body height and the viewport of the last render. The frame records them here + # (:meth:`note_metrics`). Thus the shared scroll helpers can page by one viewport of + # the current terminal and clamp to the content, and each caller does not have to + # pass the sizes through. self._scroll_total = 1 self._scroll_viewport = 1 - # A grow-only screen's high-water body height and natural width: the tallest and - # widest it has rendered into a dialog, so its box can be held at that size once - # reached (see :meth:`ratchet_viewport` / :meth:`ratchet_width`). Zero until the - # first paint; irrelevant while not :attr:`grow_only`. + # The maximum body height and natural width of a grow-only screen: the tallest and + # the widest that it rendered into a dialog. Thus its box can stay at that size after + # it gets there (refer to :meth:`ratchet_viewport` / :meth:`ratchet_width`). Zero + # until the first paint. Not used while :attr:`grow_only` is false. self._viewport_floor = 0 self._width_floor = 0 - # Edge scroll (see :meth:`edge_scroll`): whether ↑↓ have scrolled the window past the - # highlight, so the frame has stopped pulling it into view; the arrows handed to - # :meth:`handle` since the last paint, net, awaiting that paint's verdict; the - # highlight as the last paint drew it, ``(body line, drawn line)``, which the verdict - # compares against; and which side of the window the last paint left it on (0 in - # view, -1 above, +1 below), which decides the snap-back. The last two are the - # frame's to record (:meth:`note_highlight`, :meth:`note_cursor_side`). + # Edge scroll (refer to :meth:`edge_scroll`). These attributes are: + # - whether ↑↓ scrolled the viewport past the highlight, so that the frame no longer + # moves the viewport to keep the highlight visible, + # - the net arrows given to :meth:`handle` since the last paint, which wait for the + # verdict of that paint, + # - the highlight as the last paint drew it, ``(body line, drawn line)``, which the + # verdict compares with, + # - the side of the viewport where the last paint left the highlight (0 visible, -1 + # above, +1 below), which decides the snap-back. + # The frame records the last two (:meth:`note_highlight`, :meth:`note_cursor_side`). self._edge_scrolled = False self._edge_steps = 0 self._highlight_mark: tuple[int, str] | None = None @@ -243,23 +265,25 @@ class Screen: # --- rendering ----------------------------------------------------------- def render_body(self, width: int) -> list[str]: - """Return the body's ANSI lines at ``width`` columns (unclipped). + """Return the ANSI lines of the body at ``width`` cells (not clipped). Args: - width: Inner content width in columns. + width: The inner content width in cells. Returns: - One ANSI string per body line; the session slices these to the viewport. + One ANSI string for each body line. The session slices these lines to the + viewport. """ raise NotImplementedError def ratchet_viewport(self, body_h: int) -> int: - """The body height a :attr:`grow_only` dialog is sized to: its running maximum. + """The body height that sets the size of a :attr:`grow_only` dialog: its maximum so far. - The frame calls this each paint with the current body's height. A grow-only - screen returns the tallest height it has yet shown — so its box never shrinks, - and the frame blank-pads a now-shorter body to fill it — while an ordinary - screen returns the height unchanged and is sized to each body as it comes. + The frame calls this method at each paint with the height of the current body. A + grow-only screen returns the tallest height that it showed until now. Thus its box + never becomes smaller, and the frame adds blank lines to a body that is now shorter, + to fill the box. A usual screen returns the height without a change, and its size + follows each body when it comes. """ if not self.grow_only: return body_h @@ -267,12 +291,13 @@ class Screen: return self._viewport_floor def ratchet_width(self, natural: int) -> int: - """The natural width a :attr:`grow_only` dialog is sized to: its running maximum. + """The natural width that sets the size of a :attr:`grow_only` dialog: its maximum. - The width-side twin of :meth:`ratchet_viewport`, applied by the frame to a - dialog's requested ``dialog_width`` before the terminal cap — so a grow-only - box holds its widest extent as its content narrows, but a shrinking terminal - still clips it. Full-cap dialogs (no ``dialog_width``) never reach here. + This method is the twin of :meth:`ratchet_viewport`, for the width. The frame + applies it to the ``dialog_width`` that a dialog requests, before the terminal + limit. Thus a grow-only box keeps its widest size when its content becomes narrower, + but a terminal that becomes smaller still clips it. A dialog at the full limit (with + no ``dialog_width``) never gets here. """ if not self.grow_only: return natural @@ -280,75 +305,84 @@ class Screen: return self._width_floor def cursor_line(self) -> int | None: - """Return a body line that must stay visible, or ``None`` for free scrolling. + """Return a body line that must stay visible, or ``None`` for free scroll. - Selection/text screens return the active row so the session can keep it in view; - plain scroll screens return ``None``. Naming the highlight's line here is also all a - screen does to edge-scroll (see :meth:`edge_scroll`): the frame reads its edges off - the page, so no screen says where they are. + A selection screen or a text screen returns the active row, so that the session can + keep it visible. A plain scroll screen returns ``None``. To name the line of the + highlight here is also all that a screen does for edge scroll (refer to + :meth:`edge_scroll`). The frame reads the edges from the page, so no screen tells + where they are. """ return None def consume_edge_scrub(self) -> int: - """Right-edge columns the session should force-repaint on the next paint (0 = none). + """The cells at the right edge that the session must write again at the next paint. - The default is 0 — no screen needs this. A screen whose body can emit glyphs the - terminal renders at an unexpected width (the map's braille) overrides this to have the - session redraw just the smeared edge cells, which prompt_toolkit's differential paint - would otherwise never rewrite (see :class:`~meshterm.ui.map_screen.MapScreen`). + The value is a number of cells (0 = none). The default is 0, because this is not + necessary for a usual screen. A screen whose body can contain glyphs that the + terminal renders at an unexpected width (the braille of the map) overrides this + method. Then the session draws again only the corrupted cells at the edge. Without + this method, the differential paint of prompt_toolkit never writes these cells + again (refer to :class:`~meshterm.ui.map_screen.MapScreen`). """ return 0 def sticky_block(self, scroll: int) -> list[str]: - """The already-rendered body lines to pin as ``scroll`` moves past a section landmark. + """The rendered body lines to pin when ``scroll`` moves past a section landmark. - Lets a grouped list keep its current section overhead after the section's own rows have - scrolled off — a select screen's ``Channels``/``Direct`` divider, the Trophy case's - discipline heading *and the description under it*, the chat transcript's - ``── Wed Jul 8 ──`` day divider. ``scroll`` is the offset the body is about to be - sliced at; the returned lines are drawn as top rows, under any whole-list header pinned - over them (:meth:`sticky_rows` composes them for the frame). + With these lines, a grouped list keeps its current section at the top after the rows + of the section scrolled off. Examples are the ``Channels``/``Direct`` divider of a + select screen, the discipline heading of the Trophy case together with the + description under it, and the ``── Wed Jul 8 ──`` day divider of the chat + transcript. ``scroll`` is the offset at which the body will be sliced. The returned + lines are drawn as the top lines, under the header of the full list if one is pinned + above them (:meth:`sticky_rows` composes them for the frame). - The shared rule: among the blocks a screen recorded in :attr:`_sticky_headers` while - rendering, find the last one starting at or above ``scroll`` (the one *governing* the - top visible row) and pin exactly the rows of it that ``scroll`` has passed. So a block - hands its rows over one at a time as they leave — the heading pins while its - description is still the top content row, and the two pin together once both are gone — - and the pinned rows always continue seamlessly into the body below. A screen opts in - simply by populating :attr:`_sticky_headers`; the empty default means no pinning. + The shared rule: from the blocks that a screen recorded in :attr:`_sticky_headers` + while it rendered, find the last block that starts at or above ``scroll``. This + block *governs* the top visible line. Pin exactly the lines of this block that + ``scroll`` passed. Thus a block gives its lines one at a time as they leave. The + heading pins while its description is still the top content line, and the two pin + together after both are gone. The pinned lines always continue smoothly into the + body below. A screen opts in only by filling :attr:`_sticky_headers`. The empty + default means no pins. - A block never takes more than half the viewport: the rows are given up from the *end*, - so the heading — the row that says which section this is — is the last thing dropped on - a short terminal. + A block never takes more than half the viewport. The lines are removed from the end. + Thus, on a short terminal, the heading (the line that tells which section this is) + is the last line to be removed. """ governing: tuple[int, list[str]] | None = None for entry in self._sticky_headers: if entry[0] <= scroll: governing = entry else: - break # blocks are recorded in body order; nothing past here can govern + break # blocks are in body order, so no later block can govern if governing is None: - return [] # no landmark above the top visible row + return [] # no landmark above the top visible line at, rows = governing keep = max(1, self._scroll_viewport // 2) return rows[: min(scroll - at, keep)] def sticky_rows(self, scroll: int) -> list[str]: - """Every already-rendered line to pin above the body sliced at ``scroll``. + """All the rendered lines to pin above the body, when the body is sliced at ``scroll``. - What the frame actually draws, top-down: the whole-list header from - :attr:`_pinned_header` (a table's column header — the lane names, which mean the - same everywhere in the list) once it has scrolled off, then the governing section - block from :meth:`sticky_block`. A screen with only section headings pins one - line; a grouped table pins both, so a scrolled row can still be read off its lanes - *and* placed in its group. + The frame draws these lines, from the top down: + + - The header of the full list from :attr:`_pinned_header`, after it scrolls off. + This is the column header of a table: the lane names, which have the same meaning + in all the list. + - Then the section block that governs, from :meth:`sticky_block`. + + A screen with only section headings pins one line. A grouped table pins both. Thus + the user can still read a scrolled row by its lanes, and also find its group. Args: - scroll: The offset the body is about to be sliced at. + scroll: The offset at which the body will be sliced. Returns: - The lines to pin, in draw order (empty for nothing to pin). Each one costs the - body a row, so the frame reserves exactly as many as come back. + The lines to pin, in draw order (empty if there is nothing to pin). Each line + takes one line from the body, so the frame keeps exactly as many lines as it + gets. """ rows: list[str] = [] if self._pinned_header is not None and self._pinned_header[0] < scroll: @@ -359,7 +393,7 @@ class Screen: # --- input --------------------------------------------------------------- def handle(self, action: str, data: str = "") -> None: - """React to a normalized key action from the session. + """Respond to a normalized key action from the session. Args: action: One of ``up``, ``down``, ``pageup``, ``pagedown``, ``home``, ``end``, @@ -377,46 +411,48 @@ class Screen: # --- edge scroll --------------------------------------------------------- def edge_scroll(self, action: str) -> bool: - """Edge scroll and the snap-back: take ``action`` here, before :meth:`handle` sees it. + """Edge scroll and the snap-back: take ``action`` here, before :meth:`handle` gets it. - **Edge scroll** (JP, 2026-10-04) is how every page with a highlight scrolls: where - the highlight can go no further, an arrow scrolls the page a line instead, so - whatever sits above the first selectable row or below the last — a node's vitals, a - list's lead-in, a closing note — can always be brought into view. The frame stops - pulling the highlight into view while the page is edge-scrolled, so it may scroll - off screen; that is deliberate. **Home** and **End** go the same way: the screen - takes them as ever (a list's highlight jumps to its first or last row), and the - page goes to its very top or bottom. + **Edge scroll** (JP, 2026-10-04) is how each page with a highlight scrolls. Where + the highlight cannot go further, an arrow scrolls the page by one line instead. Thus + the user can always make visible the lines above the first selectable row or below + the last row (the vitals of a node, the lead-in of a list, a closing note). While + the page is edge-scrolled, the frame does not move the viewport to keep the + highlight visible, so the highlight can scroll off the screen. This is intentional. + **Home** and **End** work in the same way: the screen handles them as usual (the + highlight of a list jumps to its first or last row), and the page goes to its top + or its bottom. - **The snap-back**: while the highlight is off screen, a key that would move it toward - the window or act on it — the arrow pointing at it, Enter, Delete — first brings it - back into view, jumping if it has to, and does nothing else. Nothing is run that - cannot be seen. + **The snap-back**: while the highlight is off the screen, a key that moves it toward + the viewport or acts on it (the arrow that points at it, Enter, Delete) first brings + it back into the viewport, with a jump if necessary, and does nothing more. Nothing + runs that the user cannot see. - **No screen says where its edges are** (JP, 2026-10-04: one rule, inherited, never - a gate written screen by screen). An arrow goes to :meth:`handle` like any key, and - the next paint reads the answer off the page (:meth:`note_highlight`): a highlight - that moved is followed as ever, and one that did not was at its edge, so the page - takes the line instead. All a screen supplies is its highlight's line, through - :meth:`cursor_line` — which keeping the highlight in view asked of it already. + **No screen tells where its edges are** (JP, 2026-10-04: one rule, inherited, never + a gate written screen by screen). An arrow goes to :meth:`handle` like all keys, and + the next paint reads the answer from the page (:meth:`note_highlight`). The frame + follows a highlight that moved, as usual. A highlight that did not move was at its + edge, so the page takes the line instead. A screen gives only the line of its + highlight, through :meth:`cursor_line`. The screen already gives that line so that + the frame can keep the highlight visible. - Any other key ends the edge scroll before :meth:`handle` sees it (a typed filter, a - tab switch, a page key), so the frame follows the highlight again from there; an - arrow that turns out to be at the edge re-arms it at the paint. + Any other key ends the edge scroll before :meth:`handle` gets it (a typed filter, a + tab change, a page key). Thus the frame follows the highlight again from there. An + arrow that is found at the edge arms the edge scroll again at the paint. Returns: - Whether the key was taken here; the session passes it to :meth:`handle` only - when it wasn't. + Whether the key was taken here. The session gives the key to :meth:`handle` + only when it was not taken. """ if not self.edge_scrolls or self._highlight_mark is None: - return False # no highlight on the page: every key is the screen's own + return False # no highlight on the page: each key belongs to the screen step = _EDGE_STEPS.get(action) if ( self._edge_scrolled and self._cursor_side and (step == self._cursor_side or action in _SNAP_BACK_ACTIONS) ): - self._edge_scrolled = False # the snap-back: this press only brings it home + self._edge_scrolled = False # snap-back: this press only brings the highlight back self._edge_steps = 0 return True if action in _EDGE_ENDS and self.home_end_jumps: @@ -426,7 +462,7 @@ class Screen: if _EDGE_ENDS[action] < 0: self.scroll_to_top() else: - self.scroll = self._scroll_total # the frame clamps it to the last screenful + self.scroll = self._scroll_total # the frame clamps it to the last full viewport return True if step is not None: self._edge_steps += step # the paint finds whether it moved the highlight @@ -434,20 +470,22 @@ class Screen: return False def note_highlight(self, cursor: int | None, lines: Sequence[str]) -> None: - """Record the highlight as this paint draws it, and judge the arrows pressed since. + """Record the highlight as this paint draws it, and judge the arrows that came before. - The frame calls this each paint, before it decides where the page sits: ``cursor`` - is :meth:`cursor_line` and ``lines`` the body just rendered. Every arrow since the - last paint went to :meth:`handle` (see :meth:`edge_scroll`), and each either moved - the highlight or found it at its edge. The page says which: a highlight on the same - body line, *drawn the same*, moved nothing, so the page scrolls those lines instead - and the frame stops following. Comparing the drawn line rather than only its index - is what tells a highlight that stayed put from one in a list that scrolls in its own - window (see :class:`ListWindow`), where it holds one line while the rows pass under - it. + The frame calls this method at each paint, before it decides the position of the + page. ``cursor`` is :meth:`cursor_line`, and ``lines`` is the body that was just + rendered. Each arrow since the last paint went to :meth:`handle` (refer to + :meth:`edge_scroll`). Each arrow moved the highlight, or found it at its edge. The + page tells which: a highlight on the same body line, drawn in the same way, did not + move. Thus the page scrolls those lines instead, and the frame stops to follow the + highlight. The comparison of the drawn line, not only of its index, tells a + highlight that did not move from a highlight in a list window (refer to + :class:`ListWindow`). There, the highlight stays on one line while the rows go past + under it. - Arrows pressed faster than the screen paints are judged together, so a held arrow - that reaches the last row part-way through a batch scrolls from the next one on. + Arrows that are pressed faster than the screen paints are judged together. Thus a + held arrow that gets to the last row in the middle of a batch scrolls from the next + batch on. """ mark = None if self.edge_scrolls and cursor is not None and 0 <= cursor < len(lines): @@ -466,17 +504,18 @@ class Screen: return self._edge_scrolled def note_cursor_side(self, side: int) -> None: - """Record where the last paint left the highlight: 0 in view, -1 above, +1 below. + """Record where the last paint left the highlight: 0 visible, -1 above, +1 below. - The frame calls this; it decides the snap-back (see :meth:`edge_scroll`). + The frame calls this method. The value decides the snap-back (refer to + :meth:`edge_scroll`). """ self._cursor_side = side def resolve(self, value: Any) -> None: - """Resolve this screen's future, committing ``value`` (or :data:`CANCEL`). + """Resolve the future of this screen, and commit ``value`` (or :data:`CANCEL`). Args: - value: The result to hand back to the awaiting caller. + value: The result to return to the caller that awaits it. """ if self.future is not None and not self.future.done(): self.future.set_result(value) @@ -484,76 +523,79 @@ class Screen: # --- scrolling helpers (shared) ------------------------------------------ def note_metrics(self, total: int, viewport: int) -> None: - """Record the last render's body height and viewport (the frame calls this each paint). + """Record the body height and the viewport of the last render. - The shared scroll/section jumps below size themselves from these, so a PageDown moves - by a screenful of the current terminal rather than a fixed constant, and the top/bottom - clamps track the real content height without the caller passing the sizes in. + The frame calls this method at each paint. The shared scroll jumps and section jumps + below get their sizes from these values. Thus a PageDown moves by one viewport of + the current terminal, not by a fixed constant. Also, the top and bottom clamps + follow the real content height, and the caller does not have to give the sizes. """ self._scroll_total = max(1, total) self._scroll_viewport = max(1, viewport) def note_viewport(self, viewport: int) -> None: - """Record just the viewport height (for callers that don't know the body total).""" + """Record only the viewport height (for callers that do not know the body total).""" self._scroll_viewport = max(1, viewport) @property def _page_step(self) -> int: - """Lines a PageUp/PageDown moves: a screenful, bar one row kept for continuity.""" + """The lines that PageUp/PageDown move: the viewport, less one line for continuity.""" return max(1, self._scroll_viewport - 1) @property def content_overflows(self) -> bool: - """Whether the last-rendered body is taller than its viewport — i.e. it can scroll. + """Whether the last rendered body is taller than its viewport: that is, it can scroll. - The reusable gate for the app-wide rule that a footer only advertises a key that - would do something: a screen whose body fits has nothing to scroll, so it drops its - ``↑↓ PgUp/PgDn scroll`` atom (see :attr:`DashboardScreen.footer_hint`). Reads the - metrics the frame recorded on the *previous* paint (:meth:`note_metrics`), so it is - honest one frame after a resize — the frame repaints again immediately. + This is the reusable condition for the rule of the app that a footer shows only a + key that does something. A screen whose body fits has nothing to scroll, so it + removes its ``↑↓ PgUp/PgDn scroll`` atom (refer to + :attr:`DashboardScreen.footer_hint`). It reads the metrics that the frame recorded + at the previous paint (:meth:`note_metrics`). Thus it becomes correct one frame + after a resize, but the frame paints again immediately. """ return self._scroll_total > self._scroll_viewport def scroll_by(self, delta: int, total: int, viewport: int) -> None: - """Adjust :attr:`scroll` by ``delta`` lines, clamped to the given content bounds.""" + """Change :attr:`scroll` by ``delta`` lines, clamped to the given content bounds.""" self.scroll = _clamp_scroll(self.scroll + delta, total, viewport) def scroll_lines(self, delta: int) -> None: - """Scroll by ``delta`` lines, clamped to the last-recorded content bounds.""" + """Scroll by ``delta`` lines, clamped to the content bounds that were noted last.""" self.scroll = _clamp_scroll(self.scroll + delta, self._scroll_total, self._scroll_viewport) def scroll_pages(self, pages: int) -> None: - """Scroll by ``pages`` screenfuls (negative scrolls up).""" + """Scroll by ``pages`` page steps (a negative number scrolls up).""" self.scroll_lines(pages * self._page_step) def scroll_to_top(self) -> None: - """Jump the view to the first line.""" + """Scroll to the first line.""" self.scroll = 0 def scroll_to_bottom(self) -> None: - """Jump the view to the last screenful.""" + """Scroll to the end, so that the last line is at the bottom.""" self.scroll = max(0, self._scroll_total - self._scroll_viewport) def scroll_to_section_start(self) -> None: - """Move to the top of the section holding the top visible line. + """Scroll to the top of the section that holds the top visible line. - Sections are delimited by the recorded :attr:`_sticky_headers` (a select list's group - dividers, the chat transcript's day dividers). If that heading is already the top line, - move to the *previous* section instead — so repeated presses walk up section by section, - the way a text editor's paragraph jump does. Falls back to the very top with no sections. + The stored :attr:`_sticky_headers` mark the limits of the sections (the group + dividers of a select list, the day dividers of the chat transcript). If that heading + is already the top line, scroll to the previous section instead. Thus more presses + go up one section at a time, as the paragraph jump of a text editor does. If there + are no sections, scroll to the top. """ offsets = [idx for idx, _ in self._sticky_headers] governing = max((o for o in offsets if o <= self.scroll), default=None) if governing is None: target = 0 elif governing < self.scroll: - target = governing # up to the top of the section we're inside + target = governing # up to the top of the current section else: target = max((o for o in offsets if o < self.scroll), default=0) self.scroll = _clamp_scroll(target, self._scroll_total, self._scroll_viewport) def scroll_to_next_section(self) -> None: - """Move to the start of the next section below the top visible line (else the bottom).""" + """Scroll to the start of the next section below the top visible line (or the bottom).""" offsets = [idx for idx, _ in self._sticky_headers] nxt = min((o for o in offsets if o > self.scroll), default=None) target = nxt if nxt is not None else self._scroll_total @@ -561,46 +603,49 @@ class Screen: class LazyLines(_SequenceABC): - """A body's ANSI lines, each rendered the first time something actually reads it. + """The ANSI lines of a body, each rendered the first time that something reads it. - A screen renders its body *whole* and the frame then slices a viewport out of it — so a - 141-contact list rasterizes 150 rows to show the twenty that fit, on every keystroke and - on every idle tick. The lines outside the slice are never looked at; they are built and + A screen renders its full body, and then the frame slices a viewport out of it. Thus a + list of 141 contacts renders 150 rows to show the twenty that fit, at each key press and + at each idle tick. Nothing reads the lines outside the slice. They are built and then thrown away. - This is the same list, deferred. A screen hands over one entry per body line — either the - finished string (for the few lines it had to render anyway: separators, headings, the - query echo) or a callable that will render it — and only the entries the frame indexes - are ever called. It is a plain :class:`~collections.abc.Sequence`, so ``len()``, slicing, - iteration and ``==`` against a list all behave exactly as the list it replaces; a slice - materializes to a real list of strings, which is what the frame goes on to pad and frame. + This class is the same list, deferred. A screen gives one entry for each body line. The + entry is the finished string (for the few lines that the screen had to render in any + case: separators, headings, the query echo) or a callable that will render the line. + Only the entries that the frame indexes are called. It is a plain + :class:`~collections.abc.Sequence`. Thus ``len()``, slices, iteration, and ``==`` + against a list all behave exactly as the list that it replaces. A slice becomes a real + list of strings, which the frame then pads and puts in its frame. - Two properties make it safe to substitute: + Two properties make it safe as a replacement: - * **The line count is exact and immediate.** Deferring the *drawing* of a row never - defers *how many rows there are* — the screen counts them while it plans — so the - scroll clamp, the ``↑↓ more`` markers and the sticky-header offsets are unchanged. - * **A line is rendered at most once.** Results are memoized per index, so the frame - re-reading a row (a pinned header, a re-settled slice) costs nothing extra. + * **The line count is exact and immediate.** When the drawing of a row is deferred, + the number of rows is never deferred, because the screen counts the rows while it + plans. Thus the scroll clamp, the ``↑↓ more`` markers, and the sticky-header offsets + do not change. + * **A line is rendered a maximum of one time.** The results are cached for each index. + Thus, when the frame reads a row again (a pinned header, a slice that settled again), + it costs nothing more. - A row's content is resolved inside its callable, which means a :class:`Choice` with a - live callable title is resolved only while it is on screen — the same rows a person can - actually see changing. + The content of a row is resolved in its callable. Thus a :class:`Choice` with a live + callable title is resolved only while it is on the screen: the same rows that a person + can see change. """ __slots__ = ("_entries", "_drawn") def __init__(self, entries: list[str | Callable[[], str]]) -> None: - """Wrap one entry per body line: a rendered string, or a callable rendering it.""" + """Wrap one entry for each body line: a rendered string, or a callable that renders it.""" self._entries = entries self._drawn: dict[int, str] = {} def __len__(self) -> int: - """The body's height in lines — known without rendering any of them.""" + """The height of the body in lines. It is known without a render of any line.""" return len(self._entries) def __getitem__(self, index): # type: ignore[no-untyped-def] - """Return line ``index`` (or a real list of lines for a slice), rendering on demand.""" + """Return line ``index`` (or a real list of lines for a slice), rendered on demand.""" if isinstance(index, slice): return [self[i] for i in range(*index.indices(len(self._entries)))] if index < 0: @@ -615,76 +660,78 @@ class LazyLines(_SequenceABC): return line def __eq__(self, other: object) -> bool: - """Compare equal to the plain list of lines this stands in for.""" + """Compare equal to the plain list of lines that this object replaces.""" if isinstance(other, (LazyLines, list)): return list(self) == list(other) return NotImplemented def __repr__(self) -> str: - """Describe the height and how much of it has actually been drawn.""" + """Describe the height, and how many lines are drawn.""" return f"LazyLines({len(self._entries)} lines, {len(self._drawn)} drawn)" class ListWindow: - """Scroll state for a list that scrolls *inside* a fixed screen. + """The scroll state of a list that scrolls inside a fixed screen. - The app-wide windowed-list pattern (established by the mesh walk's link list): the - screen sizes its fixed chrome — headings, charts, action rows — to the frame's - viewport (see :meth:`Screen.note_viewport`; the frame records it before - ``render_body`` runs) and hands the leftover rows here; only the list's rows - scroll within them. Faint ``↑ n more`` / ``↓ n more`` markers (see - :meth:`marker`) take the window's edge rows exactly when rows are hidden on - that side, and the settled content capacity is remembered as :attr:`page`, the - stride a PgUp/PgDn should move by. + This is the list-window pattern of the app (first used by the link list of the mesh + walk). The screen fits its fixed chrome (headings, charts, action rows) to the + viewport of the frame (refer to :meth:`Screen.note_viewport`: the frame records it + before ``render_body`` runs). Then the screen gives the remaining lines to this class, + and only the rows of the list scroll in them. Faint ``↑ n more`` / ``↓ n more`` markers + (refer to :meth:`marker`) take the edge lines of the list window exactly when rows are + hidden on that side. The content capacity, after it settles, is kept as :attr:`page`: + the step that PgUp/PgDn must move by. - A highlight over such a list **clamps at both ends rather than wrapping** (as - :class:`~meshterm.ui.tui.select.SelectScreen` does, and for the same reason, sharper - here): the window follows the highlight, so a ↓ off the last row would not - merely move the pointer — it would haul the whole window back to the head, flipping - the edge markers as it went, which reads as the screen changing under the reader - rather than as one step. Held-down arrows settle at an end instead (JP, 2026-09-04). - Each screen owns its own cursor, so this is a rule its ``handle`` keeps, not something - this class can enforce. + A highlight over such a list **clamps at both ends and does not wrap** (as + :class:`~meshterm.ui.tui.select.SelectScreen` does, for the same reason, which is + stronger here). The list window follows the highlight. Thus, if a ↓ off the last row + rolls over, it does more than move the pointer. It pulls the full list window back to + the start, and changes the edge markers as it goes. To the user, this looks like a change of the + screen under them, not like one step. Held-down arrows stop at an end instead (JP, + 2026-09-04). Each screen owns its own highlight, so its ``handle`` keeps this rule. + This class cannot enforce it. - **A window is for a list the highlight walks**, which is why :meth:`fit` and - :meth:`fit_blocks` take the highlight with no default. Every row a window hides must be - one the arrows can reach by walking onto it, since the window follows the highlight. - Rows nothing ever highlights (a log, a results table) belong to the page instead, - where the frame scrolls them and edge scroll (:meth:`Screen.edge_scroll`) reaches them. - Windowed privately, they made the page exactly as tall as the screen, so the frame - saw nothing to scroll: ↓ on the last row did nothing while a ``↓ n more`` sat under it - (the trace screen's results, JP 2026-10-04). ``None`` is still a highlight argument, - for a list whose rows the highlight has just left for another part of the same screen. + **A list window is for a list that the highlight moves through.** For this reason, + :meth:`fit` and :meth:`fit_blocks` take the highlight with no default. Each row that a + list window hides must be a row that the arrows can reach when the highlight moves onto + it, because the list window follows the highlight. Rows that nothing highlights (a log, + a results table) belong to the page instead. There, the frame scrolls them, and edge + scroll (:meth:`Screen.edge_scroll`) reaches them. When such rows were in a private list + window, they made the page exactly as tall as the screen. Thus the frame found nothing + to scroll: ↓ on the last row did nothing while a ``↓ n more`` was under it (the results + of the trace screen, JP 2026-10-04). ``None`` is still a highlight argument, for a list + whose rows the highlight just left for another part of the same screen. Attributes: - top: First list row the window shows (clamped by :meth:`fit` each paint). - page: Rows the window carried on the last :meth:`fit` — the paging stride. + top: The first list row that the list window shows (:meth:`fit` clamps it at each + paint). + page: The rows that the list window held at the last :meth:`fit`: the paging step. """ def __init__(self) -> None: - """Start at the top with a conservative pre-first-paint stride.""" + """Start at the top, with a safe paging step for the time before the first paint.""" self.top = 0 self.page = 6 def fit(self, n: int, win: int, index: int | None) -> tuple[int, int]: - """Settle the window over ``n`` rows into ``win`` lines: ``(top, count)``. + """Settle the list window over ``n`` rows in ``win`` lines: ``(top, count)``. - The edge markers eat the window's boundary rows exactly when rows hide - beyond them, so the content capacity shifts as the window slides; a few - passes settle top, capacity, and the highlight clamp together. + The edge markers take the boundary lines of the list window exactly when rows are + hidden past them. Thus the content capacity changes when the list window slides. A + few passes settle the top, the capacity, and the highlight clamp together. Args: - n: Total list rows. - win: Lines the window may spend — on content and markers alike. + n: The total number of list rows. + win: The lines that the list window can use, for content and for markers. index: The highlighted row, which must stay visible, or ``None`` while the - highlight is elsewhere on the screen (``top`` is then just clamped). - Required: a window over rows no highlight walks hides them from the - arrows (see the class docstring). + highlight is in another part of the screen (then ``top`` is only clamped). + Necessary: a list window over rows that no highlight moves through hides + them from the arrows (refer to the class docstring). Returns: - The first visible row and how many rows to draw. Rows hidden above - number ``top``; below, ``n - top - count`` — each side non-zero exactly - when its marker row should be drawn. + The first visible row and how many rows to draw. ``top`` rows are hidden above, + and ``n - top - count`` rows below. Each side is non-zero exactly when its + marker line must be drawn. """ if n <= win: self.top = 0 @@ -707,20 +754,20 @@ class ListWindow: return top, count def fit_blocks(self, heights: list[int], win: int, index: int | None) -> tuple[int, int]: - """Settle the window over variable-height rows: ``(top, count)`` blocks to draw. + """Settle the list window over rows of different heights: ``(top, count)`` blocks. - The hanging-wrap sibling of :meth:`fit`, for a list whose rows are *blocks* of - rendered lines — a route row and the muted facts under it, a wrapped path line — - rather than one line each. A block is never split across the window's edge, the - faint edge markers eat a window line exactly when rows hide beyond them, and the - highlighted block is walked into view. + This is the sibling of :meth:`fit` for hanging wraps: a list whose rows are blocks + of rendered lines (a route row and the muted facts under it, a wrapped path line), + not one line each. A block is never split across the edge of the list window. The + faint edge markers take a line of the list window exactly when rows are hidden past + them. The list window moves step by step until the highlighted block is visible. Args: - heights: Rendered line count per list row. - win: Lines the window may spend — on content and markers alike. + heights: The rendered line count of each list row. + win: The lines that the list window can use, for content and for markers. index: The highlighted row, which must stay visible, or ``None`` while the - highlight is elsewhere on the screen (``top`` is then just clamped). - Required, as for :meth:`fit`. + highlight is in another part of the screen (then ``top`` is only clamped). + Necessary, as for :meth:`fit`. Returns: The first visible row and how many rows to draw, as :meth:`fit` returns them. @@ -736,26 +783,27 @@ class ListWindow: while True: above = 1 if top > 0 else 0 count = _fill(heights, top, win - above) - if top + count < n: # rows hide below: the marker takes one of the lines + if top + count < n: # rows are hidden below: the marker takes one of the lines count = max(1, _fill(heights, top, win - above - 1)) if index is None or index < top + count: break - top += 1 # walk the window down until the cursor's row is inside + top += 1 # move the list window down until the highlighted row is in it self.top = top self.page = max(1, count) return top, count def to_end(self) -> None: - """Slide the window to the list's tail on the next :meth:`fit`. + """Slide the list window to the end of the list at the next :meth:`fit`. - The overshoot is deliberate — the caller rarely knows the list length at - keypress time, and :meth:`fit` clamps to the last windowful either way. + The value is too large on purpose. The caller seldom knows the list length at the + time of the key press, and :meth:`fit` clamps to the last full list window in all + cases. """ self.top = 10**9 @staticmethod def marker(hidden: int, direction: str) -> Text: - """The faint edge row counting rows hidden ``"above"`` or ``"below"``.""" + """The faint edge line that counts the rows hidden ``"above"`` or ``"below"``.""" arrow = "↑" if direction == "above" else "↓" return Text(f" {arrow} {hidden} more", style="faint") @@ -773,12 +821,12 @@ def _fill(heights: list[int], top: int, budget: int) -> int: def _clamp_scroll(scroll: int, total: int, viewport: int) -> int: - """Clamp a scroll offset to the valid range for the content and viewport. + """Clamp a scroll offset to the valid range for the content and the viewport. Args: - scroll: Proposed offset. - total: Total line count. - viewport: Visible height in lines. + scroll: The proposed offset. + total: The total line count. + viewport: The height of the viewport in lines. Returns: The offset clamped to ``0 .. max(0, total - viewport)``. @@ -787,21 +835,21 @@ def _clamp_scroll(scroll: int, total: int, viewport: int) -> int: class ScrollScreen(Screen): - """A read-only screen that shows a Rich renderable in a scrollable viewport. + """A read-only screen that shows a Rich renderable in a viewport that scrolls. - Used for tool result windows and any long list. Content taller than the viewport scrolls - with the arrows / PageUp / PageDown (a screenful) / Home / End (or Ctrl+Home / Ctrl+End); - Esc dismisses it. Result windows carry no sections, so Ctrl+PageUp/PageDown just reach the - top/bottom. + It is used for the result screens of tools and for all long lists. Content that is + taller than the viewport scrolls with the arrows, PageUp / PageDown (one viewport), and + Home / End (or Ctrl+Home / Ctrl+End). Esc closes it. Result screens have no sections, so + Ctrl+PageUp/PageDown only go to the top or the bottom. """ @property def picocalc_lyra_lane(self): - """The shared lane, its nav slots dimmed when the content already fits. + """The shared lane, with its navigation slots dimmed when the content already fits. - Every nav key here scrolls and nothing else, so a result window short enough to - read whole has four inert slots — the same gate the footer hint uses on the other - platform (:attr:`Screen.content_overflows`). + Each navigation key here only scrolls. Thus a result screen that is short enough to + read in full has four slots that do nothing. The footer hint on the other platform + uses the same condition (:attr:`Screen.content_overflows`). """ from .fkeys import default_lane @@ -815,14 +863,15 @@ class ScrollScreen(Screen): footer_hint: str | None = None, floating: bool = True, ) -> None: - """Wrap a renderable in a dismissable, scrollable screen. + """Wrap a renderable in a screen that the user can scroll and close. Args: - renderable: The Rich content to display. - title: Heading for the screen/dialog. - footer_hint: Footer key hint, or ``None`` to derive it (see - :attr:`footer_hint`). - floating: Whether to draw as a centered dialog over the parent. + renderable: The Rich content to show. + title: The heading of the screen or the dialog. + footer_hint: The footer key hint, or ``None`` to make it from the state of the + screen (refer to :attr:`footer_hint`). + floating: Whether to draw the screen as a dialog at the centre, over the parent + screen. """ super().__init__() self._renderable = renderable @@ -832,14 +881,14 @@ class ScrollScreen(Screen): @property def footer_hint(self) -> str: # type: ignore[override] - """The footer keys — whatever the caller passed, or the honest default. + """The footer keys: the hint that the caller gave, or the correct default. - A read-only body has only two keys to name, the pager and Esc, so the hint can - be derived rather than spelled out at each call site — and derived, it keeps the - standing rule that a footer never advertises a key that would do nothing: the - scroll atom appears only while the body is actually taller than its viewport - (:attr:`Screen.content_overflows`). The Esc verb follows the surface the standards - assign it: a floating read-only view *closes*, a full screen goes *back*. + A read-only body has only two keys to name: the pager and Esc. Thus the hint can be + made from the state of the screen, instead of written at each call site. A hint + made in this way keeps the permanent rule that a footer never shows a key that does + nothing. The scroll atom appears only while the body is taller than its viewport + (:attr:`Screen.content_overflows`). The Esc verb follows the surface, as the + standards say: a floating read-only dialog closes, and a full screen goes back. """ if self._footer_hint is not None: return self._footer_hint @@ -847,25 +896,26 @@ class ScrollScreen(Screen): return f"↑↓ PgUp/PgDn scroll · {verb}" if self.content_overflows else verb def replace_content(self, renderable: RenderableType) -> None: - """Swap the body in place, keeping the reader where they were. + """Replace the body in place, and keep the user at the same position. - The select list's :meth:`~meshterm.ui.tui.select.SelectScreen.replace_items` for a - read-only body: the same page with something in it changed — a value uncovered, a - figure refreshed — is still the page the reader was part-way down, so the scroll - offset stands. (It is clamped on the next scroll anyway, so a body that did change - height cannot strand the viewport past its end.) Rebuild the screen instead when - what is on it is genuinely a different subject. + This is the :meth:`~meshterm.ui.tui.select.SelectScreen.replace_items` of the + select list, for a read-only body. When something on a page changes (a value that + is now shown, a figure that is refreshed), it is still the page that the user was + part of the way down. Thus the scroll offset stays. (The next scroll clamps the + offset in any case. Thus a body whose height changed cannot leave the viewport past + its end.) Build the screen again instead when its content is really a different + subject. """ self._renderable = renderable def render_body(self, width: int) -> list[str]: - """Render the wrapped content to ANSI lines and remember the total count.""" + """Render the wrapped content to ANSI lines, and keep the total count.""" lines = render_lines(self._renderable, width) self._scroll_total = max(1, len(lines)) return lines def handle(self, action: str, data: str = "") -> None: - """Scroll the viewport (by line, page, or to an edge) or dismiss the screen.""" + """Scroll the viewport (by line, by page, or to an edge), or close the screen.""" if action == "up": self.scroll_lines(-1) elif action == "down": @@ -887,46 +937,50 @@ class ScrollScreen(Screen): class BusyScreen(Screen): - """A non-interactive splash body: an animated spinner beside a message. + """A non-interactive splash body: an animated spinner next to a message. - Used to keep the startup splash on screen — its wordmark and box unchanged — while a - short async task runs (e.g. smoke-testing a chosen companion device). It set as a - chromeless base so it redraws the same centered-under-the-wordmark splash, only swapping - the box's contents. It resolves nothing and ignores every key; the session pops it when - the awaited task completes. The animation itself is the reusable - :class:`~meshterm.ui.tui.spinner.Spinner`. + It keeps the startup splash on the screen, with no change to its wordmark and its box, + while a short async task runs (for example, a smoke test of a companion that the user + chose). It is set as a base without chrome. Thus it draws again the same splash at the + centre under the wordmark, and changes only the contents of the box. It resolves nothing + and ignores all keys. The session pops it when the awaited task completes. The animation + itself is the reusable :class:`~meshterm.ui.tui.spinner.Spinner`. """ footer_hint = "working…" floating = False - modal = True # work in flight owns the keyboard; ^W must not unwind out from under it + modal = True # the work owns the keyboard. ^W must not unwind the stack while it runs. @property def picocalc_lyra_lane(self): - """No lane at all: this screen swallows every key, so none of them do anything.""" + """No lane: this screen ignores all keys, so no key has an effect.""" from .fkeys import EMPTY_LANE return EMPTY_LANE def __init__(self, message: str, *, title: str = "") -> None: - """Start a busy splash showing ``message`` under an optional ``title``.""" + """Start a busy splash that shows ``message`` under an optional ``title``.""" super().__init__() self.title = title self._message = message self._spinner = Spinner() def tick(self) -> None: - """Advance the spinner to its next frame (driven by the session's animation timer).""" + """Advance the spinner to its next animation step. + + The animation timer of the session calls this method. + """ self._spinner.tick() def render_body(self, width: int) -> list[str]: - """Render the current spinner frame followed by the message, its lines hanging. + """Render the current animation step of the spinner, then the message. - A caption may carry line feeds — what it is doing on one line, how far along on the - next — and every line after the first, like any line too long for the box, hangs - under the caption's text rather than under the spinner: the wrapped-row rule every - labelled block follows. Left to wrap on its own, a caption that ends in a running - count dropped the count's last letter alone onto a line at column zero. + A caption can contain line feeds: what the task does on one line, and its progress + on the next line. Each line after the first hangs under the text of the caption, + not under the spinner. The same is true for each line that is too long for the box. + This is the rule for wrapped rows that each labelled block follows. When the caption + wrapped without this rule, a caption that ended in a count moved the last letter of + the count alone onto a line, at the left edge. """ first, *more = self._message.split("\n") prefix = self._spinner.text() @@ -938,50 +992,52 @@ class BusyScreen(Screen): return lines def handle(self, action: str, data: str = "") -> None: - """Swallow all keys: the splash dismisses itself when the task finishes.""" + """Ignore all keys: the splash closes itself when the task finishes.""" return class BusyDialog(BusyScreen): - """A busy splash drawn as a box over the screen it interrupts. + """A busy splash, drawn as a box over the screen that it interrupts. - :class:`BusyScreen`'s twin, for work started *from* a screen rather than instead of one: - same spinner, same caption, same swallow-everything :meth:`~BusyScreen.handle` — but - ``floating``, so the hub that started the work stays visible beneath it as a backdrop - instead of being replaced. + It is the twin of :class:`BusyScreen`, for work that starts from a screen, not instead + of a screen. It has the same spinner, the same caption, and the same + :meth:`~BusyScreen.handle` that ignores all keys. But it is ``floating``. Thus the hub + that started the work stays visible below it as a backdrop, and is not replaced. - Modal by inheritance, and that is the half that matters. A hub screen kept on the stack - with ``session.stay`` is *armed the whole time* (see - :meth:`~meshterm.ui.tui.session.Visit._arm`), so while it sits there waiting for a slow - device write every key a reader presses still reaches it: letters land in its live filter - and Esc resolves it, to be handed back the instant the work finishes. A modal screen on - top is what stops that — the key reaches this dialog and dies here. + It is modal because it inherits from :class:`BusyScreen`, and this is the important + part. A hub screen that ``session.stay`` keeps on the stack is armed all the time (refer + to :meth:`~meshterm.ui.tui.session.Visit._arm`). Thus, while the hub waits for a slow + write to the device, each key that the user presses still gets to it. Letters go into + its live filter, and Esc resolves it, and that result is returned at the moment that + the work finishes. A modal screen on top stops this: the key gets to this dialog and + stops here. - :meth:`~meshterm.ui.tui.session.TuiSession.busy_overlay` cannot do the job: it is not a - screen, so it is never consulted for a keypress, and it paints only when the stack is - empty — over a pushed hub it draws nothing at all. + :meth:`~meshterm.ui.tui.session.TuiSession.busy_overlay` cannot do this job. It is not + a screen, so it never gets a key press. It paints only when the stack is empty, so over + a pushed hub it draws nothing. """ floating = True @property def dialog_width(self) -> int: - """Hug the caption rather than stretching to the dialog cap. + """Fit the box to the caption, instead of to the maximum width of a dialog. - A spinner and four words have no business in a 94-cell box. The compositor still - caps this to the terminal (see :func:`~meshterm.ui.tui.frame._dialog_layout`), and - the width ratchets, so a caption that grows mid-batch never makes the box shrink - back and jitter. + A spinner and four words must not be in a box of 94 cells. The compositor still + limits this width to the terminal (refer to + :func:`~meshterm.ui.tui.frame._dialog_layout`). The width also ratchets (it only + grows). Thus a caption that becomes longer during a batch never makes the box + smaller again, and the box does not jitter. """ widest = max(cell_len(line) for line in self._message.split("\n")) return widest + 8 # spinner, its two spaces, and the padded border @property def message(self) -> str: - """The caption beside the spinner; a line feed starts a line hung under its text.""" + """The caption next to the spinner. A line feed starts a line that hangs under its text.""" return self._message @message.setter def message(self, text: str) -> None: - """Retitle the card mid-batch (a sequence of writes reporting which one it is on).""" + """Change the caption during a batch (a sequence of writes that tells which one runs).""" self._message = text diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index 18f9fee..3fe9f08 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -1,10 +1,10 @@ # SPDX-License-Identifier: Apache-2.0 """The selectable-list screen: the reusable replacement for ``questionary.select``. -A :class:`SelectScreen` shows grouped, arrow-navigable choices with type-to-filter, bounded -to the viewport and scrolled to keep the highlighted row visible. Choice values are -arbitrary objects, so the same screen drives the main menu (tool names), the device picker -(device objects), and the config editor (setting keys). +A :class:`SelectScreen` shows grouped choices that the arrows move through, with +type-to-filter. The list is limited to the viewport, and it scrolls to keep the highlighted +row visible. A choice value can be any object. Thus the same screen operates the main menu +(tool names), the device picker (device objects), and the config editor (setting keys). """ from __future__ import annotations @@ -25,14 +25,15 @@ from .screen import LazyLines, Screen def _wants_width(fn: Callable) -> bool: """Whether a callable :attr:`Choice.title` takes the render width. - A title callable with at least one *required* positional parameter is the width-aware - form; one with none (including defaults-only signatures) stays the zero-argument - live-repaint form. Decided from the signature once at construction — never by trying - the call, so a ``TypeError`` raised *inside* a title can't be mistaken for arity. + A title callable with one or more required positional parameters is the width-aware + form. A title callable with none (also a signature with only defaults) is the + zero-argument form, which is called again at each paint. The signature decides this one + time, at construction. A trial call never decides it, so that a ``TypeError`` raised in + a title is not mistaken for a wrong arity. """ try: parameters = inspect.signature(fn).parameters.values() - except (TypeError, ValueError): # a builtin without an introspectable signature + except (TypeError, ValueError): # a builtin with a signature that cannot be examined return False return any( p.default is p.empty and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) @@ -45,48 +46,53 @@ class Choice: """One selectable row. Attributes: - title: Text shown for the row — a plain string or a Rich :class:`~rich.text.Text` - (for a coloured segment such as an unread badge). Either may instead be a - zero-argument callable resolved fresh on every repaint, so a row can track state - that changes while the list is open — or a callable taking the **render width** - (one required positional argument), the :class:`Separator` power extended to - rows: a route-bearing row can then middle-elide itself to the terminal - (``PathLine.ellipsized``) instead of being amputated at the right edge. - value: Value returned when the row is chosen. - deletable: Whether pressing Delete on this row asks to remove it. When set, Delete - resolves the list with a :class:`DeleteRequest` wrapping this row's value instead - of choosing it, so the caller can run a remove flow and re-open the list. Off by - default, so an ordinary list ignores Delete. - detail: An optional second line, drawn hanging under ``title`` at the pointer's - indent — context that doesn't belong in the selectable line itself (a route's - weakest SNR/sample count/provenance tag, say). Never scrolls or wraps; it - ellipsizes on its own if too wide. ``None`` (the default) draws nothing, so an - ordinary row stays exactly one line. May be a zero-argument callable like - ``title``. - hscroll_from: Cells at the *head* of the row that stay pinned while ``←→`` scroll - everything to their right (``hscroll`` lists only; ``0``, the default, slides - the whole line). For a row that is fixed lanes followed by one long run — the - Trophy case's rank/date/score columns in front of the walk — the lanes are the - reader's place in the list, and sliding them off to read the walk costs the row - its identity and gains nothing (the columns are the part that already fits). - Set it to the cell width of that fixed block, measured from the row itself, so - the scroll rides only the run that overflows. Setting it at all also *turns the - list's scrolling on* (see :class:`SelectScreen`): a head block is only meaningful - as the part that stays put, so a row that pins one is a row built to scroll, - wherever the builder's list ends up being shown. - fitted: The width-aware title *is* the row at any width, not a cut of a longer one: - its lanes are fixed and only a trailing chart gives cells back (the Channels - list's activity sparkline, which drops its oldest buckets to fit). The - highlighted row of an ``hscroll`` list then draws that fitted form too, instead - of keeping its natural one for ←→ to slide over — nothing past the edge of such a - row is worth sliding to, and a highlight that flipped the row back to a cut-off - chart would undo the fit on exactly the row being read. - pans: The row is a line of a *table* that ←→ pan as one: every panning row and - panning column header (:attr:`Separator.pans`) slides by the same shift, so the - lanes stay under their labels however far the reader has panned, and the shift - survives ↑↓ rather than snapping back on each new row. Declaring it turns the - list's panning on, the way :attr:`hscroll_from` turns scrolling on; rows that - don't pan (an action row under the table) stay put. See :class:`SelectScreen`. + title: The text of the row: a plain string or a Rich :class:`~rich.text.Text` (for + a coloured segment such as an unread badge). Instead, each of them can be a + zero-argument callable, resolved again at each paint. Thus a row can follow a + state that changes while the list is open. It can also be a callable that takes + the **render width** (one required positional argument). This is the ability of + :class:`Separator`, extended to rows. Thus a row with a route can elide its + middle to fit the terminal (``PathLine.ellipsized``), instead of a cut at the + right edge. + value: The value that is returned when the user chooses the row. + deletable: Whether a press of Delete on this row asks to remove the row. When it is + set, Delete resolves the list with a :class:`DeleteRequest` that wraps the value + of this row, instead of a choice of the row. Thus the caller can run a remove + flow and open the list again. It is off by default, so a usual list ignores + Delete. + detail: An optional second line, drawn under ``title`` at the indent of the + pointer. It gives context that does not belong in the selectable line itself + (for example, the weakest SNR, the sample count, or the provenance tag of a + route). It never scrolls or wraps. If it is too wide, it ellipsizes itself. + ``None`` (the default) draws nothing, so a usual row stays exactly one line. It + can be a zero-argument callable, as ``title`` can. + hscroll_from: The cells at the head of the row that stay pinned while ``←→`` + scroll all the text to their right (only in ``hscroll`` lists. With ``0``, the + default, the full line slides). Some rows are fixed lanes, then one long run: + for example, the rank, date, and score columns of the Trophy case, in front of + the walk. The lanes tell the user where the row is in the list. If they slide + off when the user reads the walk, the row loses its identity, and nothing is + gained (the columns are the part that already fits). Set it to the cell width + of that fixed block, measured from the row itself. Thus the scroll moves only + the run that overflows. A value other than 0 also turns on the scroll of the + list (refer to :class:`SelectScreen`). A head block has a meaning only as the + part that does not move. Thus a row that pins one is a row made to scroll, on + whichever screen its list is shown. + fitted: The width-aware title is the full row at each width, not a cut of a longer + row. Its lanes are fixed, and only a chart at the end gives cells back (the + activity sparkline of the Channels list, which removes its oldest buckets to + fit). Then the highlighted row of an ``hscroll`` list also draws that fitted + form, instead of its natural form for ←→ to slide over. Past the edge of such a + row, there is nothing that is worth a slide. Also, if the highlight changes the + row back to a chart that is cut off, the fit is lost on the row that the user + reads. + pans: The row is a line of a table that ←→ pan as one unit. Each row and each + column header that pans (:attr:`Separator.pans`) slides by the same shift. Thus + the lanes stay under their labels, however far the user panned. The shift also + stays when ↑↓ move, and does not go back to zero on each new row. A row that + declares it turns on the pan of the list, in the same way as + :attr:`hscroll_from` turns on the scroll. Rows that do not pan (an action row + under the table) do not move. Refer to :class:`SelectScreen`. """ title: str | Text | Callable[[], str | Text] | Callable[[int], str | Text] @@ -98,48 +104,49 @@ class Choice: pans: bool = False def __post_init__(self) -> None: - """Read the title callable's arity once, so no paint has to ask again.""" - # The callable form's arity, read once — see _wants_width. + """Read the arity of the title callable one time, so that no paint must ask again.""" + # The arity of the callable form, read one time. Refer to _wants_width. self._title_wants_width = callable(self.title) and _wants_width(self.title) def text(self, width: int) -> str | Text: - """The row's content at ``width`` cells, resolving either callable form.""" + """The content of the row at ``width`` cells. This method resolves the callable forms.""" if not callable(self.title): return self.title return self.title(width) if self._title_wants_width else self.title() @property def label(self) -> str | Text: - """The row's *natural* (unbounded) text — what filtering and measuring read.""" + """The natural (unbounded) text of the row. The filter and the measurements read it.""" return self.text(_UNBOUNDED) def scroll_text(self, width: int) -> str | Text: - """What this row draws, and ←→ slide, as the highlighted row of an ``hscroll`` list. + """What this row draws (and ←→ slide) as the highlighted row of an ``hscroll`` list. - Its natural form, so the whole line can be slid along — or, for a row whose fitted - form is complete (:attr:`fitted`), that form at ``width``, which by construction - leaves nothing to slide. The drawing, the slide's clamp, and the footer's ←→ atom - all read this one answer, so none of them can disagree about whether the row moves. + It is the natural form, so that the full line can slide. For a row whose fitted + form is complete (:attr:`fitted`), it is that form at ``width``, which by design + leaves nothing to slide. The drawing, the clamp of the slide, and the ←→ atom of the + footer all read this one answer. Thus they cannot disagree about whether the row + moves. """ return self.text(width) if self.fitted else self.label @property def detail_label(self) -> str | Text | None: - """The row's current detail line, resolving a callable on each read.""" + """The current detail line of the row. A callable is resolved at each read.""" return self.detail() if callable(self.detail) else self.detail @dataclass class DeleteRequest: - """A request, raised from a select list, to remove the highlighted row. + """A request from a select list to remove the highlighted row. - Pressing Delete on a :class:`Choice` marked ``deletable`` resolves the select with this - wrapper rather than the row's value itself, so the caller can tell "the user wants to - remove this" apart from "the user chose this" — typically running a confirm-then-forget - flow and re-opening the list. + A press of Delete on a :class:`Choice` marked ``deletable`` resolves the select with + this wrapper, instead of with the value of the row itself. Thus the caller can tell "the + user wants to remove this" from "the user chose this". The caller usually runs a flow + that confirms, then forgets, and then opens the list again. Attributes: - value: The :attr:`Choice.value` of the row the user asked to remove. + value: The :attr:`Choice.value` of the row that the user asked to remove. """ value: Any @@ -147,17 +154,18 @@ class DeleteRequest: @dataclass class KeyRequest: - """A shortcut key pressed on a select list, with the row it was pressed on. + """A shortcut key pressed on a select list, with the row that it was pressed on. The sibling of :class:`DeleteRequest`, for a list that declares its own bare-key - shortcuts (see :class:`SelectScreen`'s ``keys``): the list resolves with this rather - than with a row's value, so the caller can tell "the user pressed *this key*" apart - from "the user chose this row" and act accordingly before re-opening the list. + shortcuts (refer to the ``keys`` argument of :class:`SelectScreen`). The list resolves + with this request instead of with the value of a row. Thus the caller can tell "the user + pressed this key" from "the user chose this row", and act on it before it opens the + list again. Attributes: - action: The token the pressed key was declared for. - value: The :attr:`Choice.value` of the highlighted row, or ``None`` where the list - had no rows to highlight. A screen-wide shortcut simply ignores it. + action: The token that the pressed key was declared for. + value: The :attr:`Choice.value` of the highlighted row, or ``None`` if the list + had no rows to highlight. A shortcut for the full screen ignores it. """ action: Any @@ -165,17 +173,17 @@ class KeyRequest: def _plain(label: str | Text) -> str: - """The plain-text form of a row label, for filtering (a :class:`Text` keeps its ``plain``).""" + """The plain-text form of a row label, for the filter (a :class:`Text` gives its ``plain``).""" return label.plain if isinstance(label, Text) else label def splice_hint(base: str, segment: str) -> str: - """Insert ``segment`` into a footer hint just before its trailing ``Esc`` clause. + """Insert ``segment`` into a footer hint, immediately before its last ``Esc`` clause. - Keeps the hint grammar's "Esc last" rule when a per-row hint (e.g. ``Del remove`` on a - deletable row) is added while the cursor sits on it: the segment lands as its own ``·`` - atom right before the final ``· Esc …``, rather than after it. A hint with no ``Esc`` - clause simply gains the segment at the end. + This keeps the "Esc last" rule of the hint grammar when a hint for one row (for + example, ``Del remove`` on a deletable row) is added while the highlight is on that + row. The segment goes in as its own ``·`` atom immediately before the last + ``· Esc …``, not after it. A hint with no ``Esc`` clause gets the segment at the end. """ marker = " · Esc" idx = base.rfind(marker) @@ -185,15 +193,15 @@ def splice_hint(base: str, segment: str) -> str: def _esc_verb(base: str, verb: str) -> str: - """Rewrite a footer hint's trailing ``Esc`` clause to ``Esc ``. + """Change the last ``Esc`` clause of a footer hint to ``Esc ``. - Esc's verb is fixed per surface (``back``, ``cancel``, ``keep`` …) — except while a - find-as-you-type filter is standing, where the press peels the filter instead of - leaving, and the line has to say so. The map and the mesh walk have always spelled that - ``Esc clear``; this is the same swap for a list, which keeps the rest of its atoms - rather than giving the whole line over to the query. + The verb of Esc is fixed for each surface (``back``, ``cancel``, ``keep``, and others). + The exception is while a find-as-you-type filter stands. Then the press clears the + filter instead of a leave, and the line must tell this. The map and the mesh walk + always wrote this as ``Esc clear``. This function does the same change for a list. The + list keeps its other atoms, and does not give all the line to the query. - A hint with no ``Esc`` clause is returned unchanged: there is nothing being claimed to + A hint with no ``Esc`` clause is returned without a change: it makes no claim to correct. """ marker = " · Esc " @@ -204,11 +212,12 @@ def _esc_verb(base: str, verb: str) -> str: def _insert_atom(base: str, atom: str, index: int = 1) -> str: - """Insert ``atom`` as the ``index``-th ` · `-separated atom of a footer hint. + """Insert ``atom`` as atom number ``index`` of a footer hint (atoms between ` · `). - Surfaces a conditional *navigation* atom (the ←→ per-row scroll) right after the - leading move atom, keeping the hint's navigation-then-actions-then-``Esc`` shape — where - :func:`splice_hint` instead places an *action* atom just before the trailing ``Esc``. + This function adds a conditional navigation atom (the ←→ scroll of one row) + immediately after the first move atom. Thus the hint keeps its form: navigation, then + actions, then ``Esc``. :func:`splice_hint`, by contrast, puts an action atom + immediately before the last ``Esc``. """ parts = base.split(" · ") parts.insert(min(index, len(parts)), atom) @@ -220,36 +229,38 @@ class Separator: """A non-selectable row between choices. Attributes: - title: The row's text — a plain string drawn uniformly in :attr:`style`, or a Rich - :class:`~rich.text.Text` carrying its own spans (for a column header that lights - just its active sort column, say), rendered as-authored with ``style`` ignored. - It may instead be a callable taking the **render width** and returning either - — unlike :attr:`Choice.title`'s zero-argument callable — so a column header can - size its labels to the terminal it is being drawn on (see - :func:`~meshterm.ui.menus.column_header`). - style: Theme style a *string* title is drawn in. Section headings pass ``"heading"`` - so they read as landmarks; the default ``"muted"`` fits the - structural rows (blank spacers, column-header lines, inline notes). A ``Text`` - title styles itself, so this is unused for one. - pinned: Whether this row stays on screen for the *whole* list once scrolled past, - above any section heading pinned under it — for a column header, whose lane - names mean the same in every section (see - :meth:`~meshterm.ui.tui.screen.Screen.sticky_rows`). Off by default: an - ordinary separator only pins while its own section is on screen. At most one - row per list should set it; the last one recorded wins. - heading: Whether this row is a *section landmark*: it re-pins to the top row while - its own section is scrolled through, and it delimits the Ctrl+PageUp/PageDown - section jumps. Off by default, because most separators label nothing below them - — a blank spacer, an empty-state note, a discipline's wrapped description — and - pinning one of those overhead would say nothing while costing a content row (and - would shadow the heading it sits under). Set through - :func:`~meshterm.ui.menus.section_heading`, or by hand on a column header that - *is* its block's only landmark. - pans: The column header of a table that ←→ pan as one (see :attr:`Choice.pans`): - drawn in its fullest form and slid with the rows under it, so each label stays - over its lane. It is laid out like a row — its first two cells are the pointer - column, which stays put while the rest slides — which is how - :func:`~meshterm.ui.menus.column_header` already indents it. + title: The text of the row: a plain string, drawn all in :attr:`style`, or a Rich + :class:`~rich.text.Text` with its own spans (for example, a column header that + marks only its active sort column). A ``Text`` is rendered as written, and + ``style`` is ignored. Instead, it can be a callable that takes the **render + width** and returns one of the two. This is different from the zero-argument + callable of :attr:`Choice.title`. Thus a column header can fit its labels to the + terminal that draws it (refer to :func:`~meshterm.ui.menus.column_header`). + style: The theme style for a title that is a string. Section headings give + ``"heading"``, so that they look like landmarks. The default ``"muted"`` fits + the structural rows (blank spacers, column-header lines, inline notes). A + ``Text`` title has its own style, so this attribute is not used for it. + pinned: Whether this row stays on the screen for the full list after it scrolls + past, above each section heading that pins under it. It is for a column header, + whose lane names have the same meaning in each section (refer to + :meth:`~meshterm.ui.tui.screen.Screen.sticky_rows`). It is off by default: a + usual separator pins only while its own section is on the screen. A maximum of + one row in each list must set it. If more rows set it, the last row that is + recorded wins. + heading: Whether this row is a *section landmark*. A landmark pins again to the top + line while the user scrolls through its section. It also marks the limits of + the section jumps of Ctrl+PageUp/PageDown. It is off by default, because most + separators label nothing below them: a blank spacer, an empty-state note, the + wrapped description of a discipline. If one of these pins at the top, it tells + nothing, it takes a content line, and it hides the heading above it. It is set + through :func:`~meshterm.ui.menus.section_heading`, or by + hand on a column header that is the only landmark of its block. + pans: The column header of a table that ←→ pan as one unit (refer to + :attr:`Choice.pans`). It is drawn in its fullest form, and it slides with the + rows under it. Thus each label stays above its lane. Its layout is the same as a + row: its first two cells are the pointer column, which does not move while the + rest slides. :func:`~meshterm.ui.menus.column_header` already indents it in this + way. """ title: str | Text | Callable[[int], str | Text] @@ -259,32 +270,33 @@ class Separator: pans: bool = False def text(self, width: int) -> str | Text: - """The row's content at ``width`` cells, resolving a width-aware title.""" + """The content of the row at ``width`` cells. This method resolves a width-aware title.""" return self.title(width) if callable(self.title) else self.title Item = "Choice | Separator" -#: The width handed to a width-aware :class:`Separator` or :class:`Choice` when a -#: *natural* width is being measured rather than a real terminal one -#: (:attr:`SelectScreen.dialog_width`, :attr:`Choice.label`) — wide enough that a -#: self-fitting column header or self-eliding row returns its fullest form. +#: The width given to a width-aware :class:`Separator` or :class:`Choice` when the code +#: measures a natural width, not the width of a real terminal +#: (:attr:`SelectScreen.dialog_width`, :attr:`Choice.label`). It is wide enough that a +#: column header that fits itself, or a row that elides itself, returns its fullest form. _UNBOUNDED = 10_000 -#: Cells a choice row's pointer (``❯ `` / `` ``) takes — the column a panning header keeps -#: still too, so its labels slide in step with the rows (see :attr:`Separator.pans`). +#: The cells that the pointer of a choice row (``❯ `` / `` ``) takes. A header that pans +#: also keeps this column still, so that its labels slide in step with the rows (refer to +#: :attr:`Separator.pans`). _POINTER = 2 def _pans(items: list) -> bool: - """Whether any of ``items`` is a table row or header that ←→ pan (see :attr:`Choice.pans`).""" + """Whether one of ``items`` is a table row or a header that pans (:attr:`Choice.pans`).""" return any(getattr(item, "pans", False) for item in items) -#: The navigation actions that move the highlight to another row, so an ``hscroll`` list -#: drops the current row's horizontal shift (each row scrolls on its own — see -#: :meth:`SelectScreen.handle`). The filter edits reset it in their own branches. A panning -#: list keeps its shift: the table is what moved, not the row. +#: The navigation actions that move the highlight to another row. Thus an ``hscroll`` list +#: removes the horizontal shift of the current row (each row scrolls by itself, refer to +#: :meth:`SelectScreen.handle`). The filter edits reset the shift in their own branches. A +#: list that pans keeps its shift, because the table moved, not the row. _HSHIFT_RESET_ACTIONS = frozenset( { "up", @@ -304,40 +316,42 @@ _HSHIFT_RESET_ACTIONS = frozenset( class SelectScreen(Screen): """A grouped, filterable, single-choice list. - Resolves with the chosen :class:`Choice` value, or :data:`~meshterm.ui.tui.screen.CANCEL` - if the user presses Esc. + Resolves with the value of the chosen :class:`Choice`, or with + :data:`~meshterm.ui.tui.screen.CANCEL` if the user presses Esc. """ - #: Cells one ←/→ press shifts an h-scrolling list by (see the ``hscroll`` flag). + #: The number of cells that one ←/→ press shifts an ``hscroll`` list (refer to ``hscroll``). _HSCROLL_STEP = 8 @property def picocalc_lyra_lane(self): - """The shared pager, the section jumps on F1/F2, and row deletion on F3. + """The shared pager, the section jumps on F1/F2, and the delete of a row on F3. - Ctrl+PageUp/PageDown step the highlight heading by heading — and on the PicoCalc - they are the one binding in the app that is *physically unreachable*: paging has - no key there to hold Ctrl over. So a grouped list promotes them onto the lane, - keeping the shared handedness — a pair rises toward its outer key, so on this - left-edge pair *up* takes F1 (see :data:`~meshterm.ui.tui.fkeys.DEFAULT_LANE`). + Ctrl+PageUp/PageDown move the highlight from one heading to the next. On the + PicoCalc, they are the only binding in the app that the user cannot physically + press: there is no paging key to hold Ctrl over. Thus a grouped list puts them on + the lane. It keeps the shared handedness: a pair rises toward its outer key, so on + this pair at the left edge, up takes F1 (refer to + :data:`~meshterm.ui.tui.fkeys.DEFAULT_LANE`). - Their two gates say different things, per the lane's empty-versus-dim rule. A list - that has no headings *at all* leaves both slots blank: sections aren't a thing - here. A grouped list whose live filter has narrowed the rows down to a single - surviving section keeps its labels and dims them — the sections are still a thing, - they just have nowhere to jump right now. + Their two conditions tell different things, by the empty-or-dim rule of the lane. A + list that has no headings leaves the two slots blank, because sections do not exist + here. A grouped list whose live filter shows rows from only one section keeps the + labels and dims them. The sections still exist, but there is no place to jump to at + this time. - ``Delete`` is the same claim as the footer's per-row delete atom, on a platform - that draws no footer: only a list that hands out :attr:`Choice.deletable` rows at - all shows the slot, and it lights exactly on the rows the key would act on. The - chip says ``Delete`` on every such list rather than echoing each one's own hint - phrasing, because six cells hold the key's verb and not the object it removes — - which the highlighted row is already naming. + ``Delete`` makes the same claim as the delete atom of the footer for each row, on a + platform that draws no footer. Only a list that has :attr:`Choice.deletable` rows + shows the slot, and the slot is enabled only on the rows that the key acts on. The + chip shows ``Delete`` on each such list, instead of the hint text of each list. The + reason is that six cells hold the verb of the key, not the object that it removes, + and the highlighted row already names that object. """ from .fkeys import FPair, default_lane - # One pass over the displayed rows for the whole lane: this runs every paint on - # the platform that draws it, and `_rows()` re-filters the item list each call. + # One pass over the shown rows for the full lane: this code runs at each paint on + # the platform that draws the lane, and `_rows()` filters the item list again at each + # call. rows = self._rows() lane = list(default_lane(nav=len(self._choices(rows)) > 1)) if len(self._all_section_starts()) >= 2: @@ -368,82 +382,87 @@ class SelectScreen(Screen): """Build a select screen. Args: - title: Short heading shown in the border. - items: A list of :class:`Choice` and :class:`Separator` in display order. - prompt: An optional instruction shown inside the box, above the list — so a - floating select reads like the other dialogs (a prompt above its controls). - default: A choice value to pre-highlight, if present. - footer_hint: Footer key hint; defaults to one that mentions type-to-filter only - when ``filterable`` (a fixed list shouldn't advertise a filter it ignores). - delete_hint: A key-hint atom (e.g. ``"Del remove"``) surfaced in the footer only - while the highlighted row is :attr:`Choice.deletable` — so the removal key - advertises itself exactly when it would act, and stays hidden on rows it can't - touch. Empty (the default) leaves the footer fixed. - filterable: Whether typing narrows the list. Off for short, fixed lists (e.g. - the startup device picker) where type-to-filter would only get in the way. - hscroll: Whether ←/→ horizontally scroll the *highlighted* row so an over-long - line can be read to its end (the Watchtower's alert log). ``None`` (the - default) lets the rows decide: one that pins a head block - (:attr:`Choice.hscroll_from`) turns scrolling on, and without one the rows - simply ellipsize at the right edge and ←/→ stay inert. ``False`` keeps it off - whatever the rows declare — the editor pages (Device config, repeater admin), - whose Actions rows pin heads but whose lanes are meant to end at the edge - rather than slide. Only a row that - actually overflows the width scrolls; a short row (and every separator or - column header) stays put, and the shift resets to the start whenever the - highlight moves to another row or the filter is edited — each row scrolls - on its own, independently of the rest of the screen. A row may hold a head - block out of the scroll (:attr:`Choice.hscroll_from`), so only its - overflowing run slides; whichever edges the line then continues past wear a - :func:`~meshterm.ui.pathline.cut_mark`. A list whose rows *pan* - (:attr:`Choice.pans`) scrolls differently, and takes precedence: ←→ slide - the whole table — its column header and every panning row by one shared - shift, clamped to the widest of them — and the shift stays put as the - highlight moves. - hscroll_hint: The footer atom surfaced (as the second ` · ` atom, right after - the move atom) while ``hscroll`` is on and the highlighted row overflows — - so ←→ advertises itself exactly when it would do something. Ignored when - ``hscroll`` is off. - keys: Bare-key shortcuts this list answers, mapping the character pressed to a - token naming what it means — the idiom - :meth:`~meshterm.ui.tui.session.TuiSession.button_dialog` already uses for a - dialog's y/n accelerators. The list resolves with a :class:`KeyRequest` - carrying the token and the highlighted row's value, so the caller can act - and re-open. **Only honoured on a non-filterable list**, where a bare letter - has nothing else to do: on a filtering list every letter belongs to the - query, and a shortcut stealing one would be a key that silently stops the - reader typing a name. - key_hint: What those shortcuts are called in the footer, asked of the *highlighted - row's value* on every paint and spliced in just before the trailing ``Esc`` - clause. Return one ` · `-joined run of atoms, or ``""`` for a row none of the - shortcuts would touch — the same rule ``delete_hint`` follows, and for the - same reason: the footer must never name a key that would do nothing where the - reader is standing. The policy lives with the caller because only it knows - which rows its keys mean anything on. + title: The short heading in the border. + items: A list of :class:`Choice` and :class:`Separator`, in the order to show. + prompt: An optional instruction in the box, above the list. Thus a floating + select looks like the other dialogs (a prompt above its controls). + default: A choice value to highlight at the start, if it is present. + footer_hint: The footer key hint. The default hint mentions type-to-filter only + when ``filterable`` is true (a fixed list must not show a filter that it + ignores). + delete_hint: A key-hint atom (for example, ``"Del remove"``) that the footer + shows only while the highlighted row is :attr:`Choice.deletable`. Thus the + hint shows the remove key exactly when the key acts, and hides it on rows + that the key cannot change. Empty (the default) keeps the footer fixed. + filterable: Whether typed text narrows the list. It is off for short, fixed lists + (for example, the device picker at startup), where type-to-filter only causes + problems. + hscroll: Whether ←/→ scroll the highlighted row horizontally, so that the user can + read a long line to its end (the alert log of the Watchtower). ``None`` (the + default) lets the rows decide. A row that pins a head block + (:attr:`Choice.hscroll_from`) turns the scroll on. Without one, the rows + ellipsize at the right edge, and ←/→ do nothing. ``False`` keeps the scroll + off, whatever the rows declare. This is for the editor pages (Device config, + repeater admin), whose Actions rows pin heads, but whose lanes must end at + the edge and not slide. Only a row that is wider than the width scrolls. A + short row (and each separator or column header) does not move. The shift + goes back to the start when the highlight moves to another row or when the + filter changes: each row scrolls by itself, independently of the rest of the + screen. A row can keep a head block out of the scroll + (:attr:`Choice.hscroll_from`), so only its run that overflows slides. Each + edge past which the line continues then shows a + :func:`~meshterm.ui.pathline.cut_mark`. A list whose rows pan + (:attr:`Choice.pans`) scrolls in a different way, and this way has priority. + ←→ slide the full table: its column header and each row that pans move by + one shared shift, clamped to the widest of them. The shift does not change + when the highlight moves. + hscroll_hint: The footer atom that the footer shows (as the second ` · ` atom, + immediately after the move atom) while ``hscroll`` is on and the highlighted + row overflows. Thus the hint shows ←→ exactly when these keys do something. + Ignored when ``hscroll`` is off. + keys: The bare-key shortcuts that this list answers. Each maps the pressed + character to a token that names what it means. + :meth:`~meshterm.ui.tui.session.TuiSession.button_dialog` already uses this + idiom for the y/n accelerators of a dialog. The list resolves with a + :class:`KeyRequest` that holds the token and the value of the highlighted + row. Thus the caller can act and open the list again. **Only a list that is + not filterable obeys them**, because there a bare letter has no other + function. On a list with a filter, each letter belongs to the query. A + shortcut that takes a letter is a key that stops the user, without a sign, + when the user types a name. + key_hint: The names of those shortcuts in the footer. At each paint, the screen + calls it with the value of the highlighted row, and inserts the result + immediately before the last ``Esc`` clause. Return one run of atoms joined + by ` · `, or ``""`` for a row that no shortcut changes. ``delete_hint`` + follows the same rule, for the same reason: the footer must never name a key + that does nothing on the row where the user is. The caller keeps this + policy, because only the caller knows on which rows its keys have a meaning. """ super().__init__() self.title = title - # A row that pins a head block (:attr:`Choice.hscroll_from`) is a row built to - # scroll — the head is only meaningful as "the part that stays put" — so declaring - # one turns the list's scrolling on without the builder having to reach the screen - # it will be shown in. That is what makes every label+description list - # (:func:`~meshterm.ui.menus.menu_rows`, the main menu) scroll its description - # wherever it is opened, ``ctx.ui.select`` included — unless the list itself has - # said ``hscroll=False``, which the rows cannot overrule. + # A row that pins a head block (:attr:`Choice.hscroll_from`) is a row made to + # scroll, because the head has a meaning only as "the part that stays put". Thus a + # row that declares one turns on the scroll of the list, and the builder does not + # have to reach the screen that will show it. Because of this, each + # label+description list (:func:`~meshterm.ui.menus.menu_rows`, the main menu) + # scrolls its description wherever it is opened, also through ``ctx.ui.select``. + # The exception is a list that itself says ``hscroll=False``. The rows cannot + # override that. self._hscroll_auto = hscroll is None self._hscroll = bool(hscroll) or ( self._hscroll_auto and any(getattr(item, "hscroll_from", 0) > 0 for item in items) ) self._hscroll_hint = hscroll_hint - # A row built as a line of a table turns panning on, as a pinned head turns on - # scrolling (see Choice.pans); it is read off the rows each time they change. + # A row made as a line of a table turns on the pan, as a pinned head turns on the + # scroll (refer to Choice.pans). The value is read from the rows each time they + # change. self._pan = _pans(items) - # Shortcuts are the non-filterable list's compensation for having no filter: the - # letters are free, so a list may spend them (see the ``keys`` argument). + # Shortcuts compensate a list that is not filterable for its missing filter. The + # letters are free, so the list can use them (refer to the ``keys`` argument). self._keys: dict[str, Any] = {} if filterable else dict(keys or {}) self._key_hint = key_hint self._hshift = 0 - self._last_width = 0 # the last render width, for the footer's overflow probe + self._last_width = 0 # the last render width, for the overflow check of the footer if footer_hint is None: footer_hint = ( "↑↓ move · type to filter · Enter select · Esc back" @@ -456,12 +475,12 @@ class SelectScreen(Screen): self._filterable = filterable self._items = items self._filter = "" - # Index into the currently-selectable (filtered) choices. + # The index in the choices that can be selected now (after the filter). self._index = 0 self._highlight(default) def _highlight(self, default: Any) -> None: - """Land the highlight on the choice whose value is ``default`` (first row otherwise).""" + """Put the highlight on the choice whose value is ``default`` (or else on the first row).""" self._index = 0 if default is None: return @@ -471,22 +490,27 @@ class SelectScreen(Screen): return def turn_page(self, items: list, *, title: str, prompt: str = "", default: Any = None) -> None: - """Show a *different* list in the same box — a stepped dialog's next page, or its last. + """Show a different list in the same box: the next or previous page of a stepped dialog. - The other way a list's rows change under a reader, and the opposite claim from - :meth:`replace_items`: that one refreshes the *same* list (its rows are data that - moved), so the filter and the highlight ride along. A page turned is a new question - — pick the node to tune, now pick where to measure — so nothing rides along: the - query typed to find a row on the last page would narrow this one to nothing it was - meant for, the scroll starts at the top, and the highlight lands on ``default`` (a - page turned *back* to offers its previous answer, exactly as a step of - :func:`~meshterm.ui.menus.run_steps` does) or on the first row. + This is the other way that the rows of a list change while the user looks at them. + It makes the opposite claim to :meth:`replace_items`. That method refreshes the same + list (its rows are data that moved), so the filter and the highlight stay. A new + page is a new question (select the node to tune, then select where to measure), so + nothing stays: + + - The query that the user typed to find a row on the previous page is cleared. If it + stays on this page, it narrows the list to rows that it was not meant for. + - The scroll starts at the top. + - The highlight goes to ``default`` or to the first row. (A page that the user turns + back to offers its previous answer, exactly as a step of + :func:`~meshterm.ui.menus.run_steps` does.) Args: - items: The new page's rows, in display order. - title: The new heading — the one place the reader sees which step this is. + items: The rows of the new page, in the order to show. + title: The new heading. It is the only place where the user sees which step this + is. prompt: The instruction above the rows, or ``""`` for none. - default: The choice value to highlight, if present. + default: The choice value to highlight, if it is present. """ self._items = items if self._hscroll_auto: @@ -502,27 +526,28 @@ class SelectScreen(Screen): def replace_items( self, items: list, *, title: str | None = None, prompt: str | None = None ) -> None: - """Swap the list's rows (and optionally its title) in place, keeping the reader's place. + """Replace the rows (and the title, if given) in place, and keep the place of the user. - The counterpart to :meth:`~meshterm.ui.tui.session.TuiSession.stay` for a list whose - *content* is data: an editor's rows carrying a staged ``current → new`` value, a - title counting what is staged, a queue that just lost the message it sent. Those - lists used to be rebuilt as a whole new screen every round, which threw away the - typed filter and left the cursor to be approximated by a ``default=`` restore. + This is the counterpart of :meth:`~meshterm.ui.tui.session.TuiSession.stay` for a + list whose content is data: the rows of an editor with a staged ``current → new`` + value, a title that counts what is staged, a queue that just lost the message that + it sent. Before, these lists were built again as a new screen at each round. That + removed the typed filter, and only a ``default=`` restore put the highlight back at + an approximate place. - The place is kept by *value*, not by index: the highlight lands back on the row it - was on wherever that row moved to, and falls back to the same position in the list - (clamped) when the row is gone entirely — which is what a reader expects after - deleting the row they were sitting on. The filter and the horizontal shift ride - along; the shift resets when the highlighted row changes, exactly as it does when - the highlight is moved by hand. + The place is kept by value, not by index. The highlight goes back to the row that it + was on, wherever that row moved to. If the row is gone, the highlight goes to the + same position in the list (clamped). A user expects this after the user deletes the + row that the highlight was on. The filter and the horizontal shift stay. The shift + goes back to the start when the highlighted row changes, exactly as when the user + moves the highlight. Args: - items: The new rows, in display order. - title: A new heading, or ``None`` to keep the current one. - prompt: A new instruction/summary line above the rows, or ``None`` to keep the - current one — the channel detail's vital signs, which age and count unread - alongside the rows they head. + items: The new rows, in the order to show. + title: A new heading, or ``None`` to keep the current heading. + prompt: A new instruction or summary line above the rows, or ``None`` to keep + the current line. An example is the vital signs of the channel detail, + which age and count unread messages next to the rows below them. """ current = self._current_choice() was = current.value if current is not None else None @@ -542,16 +567,16 @@ class SelectScreen(Screen): if index is None: index = max(0, min(position, len(selectable) - 1)) if not self._pan: - self._hshift = 0 # a different row is highlighted now; a pan is the table's + self._hshift = 0 # another row is highlighted now. A pan belongs to the table. self._index = index # --- filtering ----------------------------------------------------------- def _rows(self) -> list: - """Return the items to display given the active filter. + """Return the items to show with the active filter. - Without a filter, groups and headings show as authored. With a filter, only the - matching choices are shown — but every separator stays, so the list keeps its + Without a filter, groups and headings show as written. With a filter, only the + choices that match are shown. But each separator stays, so the list keeps its section landmarks (and column headers) while it narrows. """ needle = self._filter.strip().lower() @@ -564,25 +589,26 @@ class SelectScreen(Screen): ] def _choices(self, rows: list | None = None) -> list: - """Return just the selectable choices among ``rows`` (or the current rows).""" + """Return only the selectable choices in ``rows`` (or in the current rows).""" rows = self._rows() if rows is None else rows return [it for it in rows if isinstance(it, Choice)] def _section_starts(self, rows: list | None = None) -> list[int]: - """Choice indices that begin a section — the first choice after each run of separators. + """The choice indices that start a section: the first choice after each run of separators. - Drives Ctrl+PageUp/PageDown section jumps. Computed over the *displayed* rows by - default, so the jumps keep working while a filter narrows the list (the headings - stay — see :meth:`_rows` — and empty sections simply yield no stop). + The section jumps of Ctrl+PageUp/PageDown use them. By default, they are calculated + from the shown rows. Thus the jumps continue to work while a filter narrows the + list (the headings stay, refer to :meth:`_rows`, and an empty section gives no + stop). Args: - rows: The rows to read the sections off, or ``None`` for the displayed ones. - :meth:`_all_section_starts` passes the unfiltered items instead, to ask - the structural question rather than the live one. + rows: The rows to read the sections from, or ``None`` for the shown rows. + :meth:`_all_section_starts` gives the unfiltered items instead, to ask the + structural question instead of the live question. """ starts: list[int] = [] idx = 0 - fresh = True # the next choice opens a section (top of the list, or just past a heading) + fresh = True # the next choice starts a section (top of the list, or after a heading) for item in self._rows() if rows is None else rows: if isinstance(item, Separator): fresh = True @@ -594,20 +620,21 @@ class SelectScreen(Screen): return starts def _all_section_starts(self) -> list[int]: - """The section starts of the *unfiltered* list — whether this list has sections at all. + """The section starts of the unfiltered list: they tell if this list has sections. - The F-key lane needs both questions answered separately (see :attr:`picocalc_lyra_lane`): - a flat list never offers a section jump, while a grouped one whose filter has - collapsed it to one section offers it again the moment the filter is edited. + The F-key lane must have the answers to the two questions separately (refer to + :attr:`picocalc_lyra_lane`). A flat list never offers a section jump. A grouped list + whose filter shows only one section offers the jump again when the filter changes. """ return self._section_starts(self._items) def _jump_section(self, direction: int) -> None: - """Move the highlight to the next section (``+1``) or the current/previous one (``-1``). + """Move the highlight to the next section (``+1``), or the current or previous one (``-1``). - Mirrors the scroll-based section jump of read-only screens, but in choice space: down - lands on the first choice of the following section; up lands on the first choice of the - section we're in, or the previous section's when already at a section start. + It is the same as the section jump of the read-only screens, which scrolls, but it + moves through the choices. Down goes to the first choice of the next section. Up + goes to the first choice of the current section, or to the first choice of the + previous section when the highlight is already at the start of a section. """ starts = self._section_starts() if not starts: @@ -626,7 +653,7 @@ class SelectScreen(Screen): self._index = at_or_before[-2] if len(at_or_before) >= 2 else 0 def _current_choice(self) -> Choice | None: - """The choice the highlight currently sits on, or ``None`` when the list is empty.""" + """The choice that the highlight is on now, or ``None`` when the list is empty.""" choices = self._choices() if not choices: return None @@ -634,21 +661,22 @@ class SelectScreen(Screen): @property def footer_hint(self) -> str: - """The footer key hint, gaining dynamic atoms only where their keys would act. + """The footer key hint, with dynamic atoms only where their keys act. - Two conditional atoms fold in exactly where they apply, so the bottom border never - advertises a key that would do nothing: + Conditional atoms go in exactly where they apply. Thus the bottom border never + shows a key that does nothing: - * the :attr:`_delete_hint` atom, spliced just before the trailing ``Esc`` clause - (see :func:`splice_hint`) while the highlighted row is :attr:`Choice.deletable`; - * whatever ``key_hint`` names for the highlighted row's value — the shortcut keys - (``keys``) that would act on *it*, spliced the same way; - * the :attr:`_hscroll_hint` atom (``hscroll`` lists only), inserted right after the - move atom (see :func:`_insert_atom`) while the highlighted row overflows the width - — a short row scrolls nowhere, so ←→ stays hidden on it. + * The :attr:`_delete_hint` atom, inserted immediately before the last ``Esc`` + clause (refer to :func:`splice_hint`), while the highlighted row is + :attr:`Choice.deletable`. + * The names that ``key_hint`` gives for the value of the highlighted row: the + shortcut keys (``keys``) that act on that row, inserted in the same way. + * The :attr:`_hscroll_hint` atom (only in ``hscroll`` lists), inserted immediately + after the move atom (refer to :func:`_insert_atom`), while the highlighted row + is wider than the width. A short row cannot scroll, so ←→ stays hidden on it. - And the trailing ``Esc`` clause turns into ``Esc clear`` while a filter is typed, - because that is what the press does then (see :meth:`handle`). + Also, the last ``Esc`` clause changes to ``Esc clear`` while a filter is typed, + because the press then clears the filter (refer to :meth:`handle`). """ base = self._footer_base current = self._current_choice() @@ -665,17 +693,17 @@ class SelectScreen(Screen): return base def _selected_overflows(self) -> bool: - """Whether the highlighted row's label is too wide for the last render width. + """Whether the label of the highlighted row is too wide for the last render width. - The gate for both the ←→ scroll and its footer atom: a row that fits has nothing to - scroll. Measured against the row's content area (the width less the 2-cell pointer), - using the width the last :meth:`render_body` saw (``0`` before the first paint, so - nothing reads as overflowing until a real width is known). Asked of - :meth:`_max_hshift` rather than of the raw label width, so a row that pins a head - block (:attr:`Choice.hscroll_from`) is judged on the run that would actually move — - the marks a scrolled row spends cells on included. A panning list asks the same of - the whole table rather than of one row, since ←→ move the table wherever the - highlight is standing. + This is the condition for the ←→ scroll and for its footer atom: a row that fits + has nothing to scroll. The label is measured against the content area of the row + (the width less the pointer of 2 cells), at the width of the last + :meth:`render_body` (``0`` before the first paint, so nothing overflows until a + real width is known). The question goes to :meth:`_max_hshift`, not to the raw + label width. Thus a row that pins a head block (:attr:`Choice.hscroll_from`) is + measured by the run that moves, with the cells for the marks of a scrolled row. A + list that pans asks the same question of the full table instead of one row, + because ←→ move the table wherever the highlight is. """ if self._pan and self._last_width > 0: return self._pan_limit(self._last_width) > 0 @@ -694,12 +722,12 @@ class SelectScreen(Screen): @property def sizing_footer_hint(self) -> str: - """The fullest the footer can get, for stable box sizing (see :attr:`footer_hint`). + """The longest form of the footer, for a stable box size (refer to :attr:`footer_hint`). - The delete-hint atom is always folded in here, so a compositor that sizes a box to - the footer width (the startup splash's :func:`~meshterm.ui.tui.frame.compose_startup`) - reserves room for it up front — the box then never widens the moment the highlight - lands on a deletable row. + The delete-hint atom is always in it. Thus a compositor that sets the size of a box + from the width of the footer (:func:`~meshterm.ui.tui.frame.compose_startup` of the + startup splash) keeps space for the atom from the start. Then the box never becomes + wider when the highlight goes onto a deletable row. """ if self._delete_hint: return splice_hint(self._footer_base, self._delete_hint) @@ -709,16 +737,17 @@ class SelectScreen(Screen): @property def dialog_width(self) -> int: - """Natural outer width so a floating select hugs its widest row, not the terminal. + """The natural outer width, so that a floating select fits its widest row, not the terminal. - The widest of the prompt, title, footer, and every row (with room for the pointer), - so a short menu is a tidy popup rather than a full-width banner. The compositor still - caps this to the space available, and this is only read for a *floating* select — the - full-screen base menu is laid out by ``compose_base`` and ignores it. The footer is - measured at its fullest — with the delete-hint atom folded in — so a deletable row - surfacing that hint never widens the box mid-navigation. A width-aware separator is - measured at its fullest too (see :data:`_UNBOUNDED`): the box asks for room for the - whole header, and the header only abbreviates once the *terminal* caps the box. + It is the widest of the prompt, the title, the footer, and each row (with space for + the pointer). Thus a short menu is a small dialog, not a banner of full width. The + compositor still limits this width to the available space. Only a floating select + reads it: ``compose_base`` sets the layout of the full-screen base menu and ignores + it. The footer is measured at its longest, with the delete-hint atom in it. Thus a + deletable row that shows that hint never makes the box wider during navigation. A + width-aware separator is also measured at its fullest (refer to + :data:`_UNBOUNDED`). The box asks for space for the full header, and the header + becomes shorter only when the terminal limits the box. """ footer = ( splice_hint(self._footer_base, self._delete_hint) @@ -727,23 +756,23 @@ class SelectScreen(Screen): ) widths = [cell_len(self.title), cell_len(footer), cell_len(self._prompt)] for item in self._items: - label = item.text(_UNBOUNDED) # both row kinds measure at their fullest form + label = item.text(_UNBOUNDED) # the two types of row measure at their fullest form widths.append(cell_len(_plain(label)) + 2) # + the "❯ " / " " pointer column if isinstance(item, Choice) and item.detail_label is not None: widths.append(cell_len(_plain(item.detail_label)) + 2) # same hanging indent return max(widths, default=20) + 8 def render_body(self, width: int) -> list[str]: - """Plan the body's lines, drawing the rows the viewport actually shows. + """Plan the lines of the body, and draw only the rows that the viewport shows. - Walks every row to lay the body out — how many lines it takes, where the highlight - landed, which separators are sticky landmarks — because the frame's scroll clamp and - pinning need all of that exactly. But a *choice* row's own rasterizing is handed over - as a callable rather than done here (see - :class:`~meshterm.ui.tui.screen.LazyLines`): a list of 141 contacts laid out 150 rows - tall only ever shows the twenty that fit, so the other hundred and thirty were built - and discarded on every keystroke and every idle tick. Separators are rendered on the - spot — they are few, and their lines are the ones :meth:`sticky_rows` pins *outside* + The method goes through each row to make the layout of the body: how many lines the + body takes, where the highlight is, and which separators are sticky landmarks. The + scroll clamp and the pins of the frame must have all of this, exactly. But the + render of a choice row is given as a callable, and is not done here (refer to + :class:`~meshterm.ui.tui.screen.LazyLines`). A list of 141 contacts, 150 rows tall, + shows only the twenty rows that fit. Before, the other hundred and thirty rows were + built and thrown away at each key press and at each idle tick. Separators are + rendered immediately: they are few, and :meth:`sticky_rows` pins their lines outside the slice. """ rows = self._rows() @@ -751,13 +780,15 @@ class SelectScreen(Screen): self._index = max(0, min(self._index, len(choices) - 1)) if choices else 0 selected = choices[self._index] if choices else None - # Horizontal scroll rides only the *highlighted* row, and only as far as its own - # tail: → stops once that row's end is in view, and a short (or unselected) row - # can't shift at all. Measured fresh each paint — a callable title may have changed - # width — against the row's content area (width less the 2-cell pointer). + # The horizontal scroll moves only the highlighted row, and only as far as its own + # end: → stops when the end of that row is visible, and a short (or not selected) + # row cannot shift. It is measured again at each paint, because a callable title + # can change its width. It is measured against the content area of the row (the + # width less the pointer of 2 cells). self._last_width = width if self._pan: - # A panning list slides the table as one, as far as its widest line's tail. + # A list that pans slides the table as one unit, as far as the end of its + # widest line. self._hshift = max(0, min(self._hshift, self._pan_limit(width))) elif self._hscroll and self._hshift: avail = max(1, width - 2) @@ -767,45 +798,50 @@ class SelectScreen(Screen): 0, min(self._hshift, self._max_hshift(sel_len, anchor, max(1, width - 2))) ) - # One entry per body line: a finished string, or a callable that draws it when the - # frame asks. Positions are exact either way, which is all the layout below reads. + # One entry for each body line: a finished string, or a callable that draws the line + # when the frame asks. The positions are exact in the two cases, and the layout below + # reads only the positions. lines: list[str | Callable[[], str]] = [] - # A prompt (when set) sits above the list, offsetting every row below it. Every index - # recorded below — the cursor line, the sticky headers — is read off ``len(lines)``, - # which already counts the prompt's lines, so none of them adds the offset again. + # A prompt (when set) is above the list, and moves each row below it down. Each index + # recorded below (the line of the highlight, the sticky headers) comes from + # ``len(lines)``, which already counts the lines of the prompt. Thus no index adds + # the offset again. if self._prompt: lines.extend(render_lines(Text(self._prompt), width)) lines.append("") - # Record each section heading (a Separator that says it is one) as a sticky block, so - # one that scrolls off is re-pinned to the top rows by the base Screen.sticky_block — - # and a pinned separator (a column header) as the whole-list header pinned above it. - # A heading's block runs on through the separators that *immediately* follow it, before - # the section's first row: prose written there is the section's preamble (the Trophy - # case's "what this discipline scores"), so it belongs overhead with the heading rather - # than scrolling away from the rows it explains. Everything else — blank spacers, - # empty-state notes under a section that has rows, a stray line between choices — is - # the landmark of nothing and stays out of the running, so the rows pinned overhead - # are always the section that governs. Separators survive filtering (see _rows), so - # the pinning keeps working while the list narrows. + # Record each section heading (a Separator that says that it is one) as a sticky + # block. Thus, when one scrolls off, the base Screen.sticky_block pins it again to the + # top lines. Also record a pinned separator (a column header) as the header of the + # full list, pinned above it. The block of a heading continues through the separators + # that follow it immediately, before the first row of the section. Prose there is the + # preamble of the section (the "what this discipline scores" of the Trophy case). + # Thus it belongs at the top with the heading, and does not scroll away from the rows + # that it explains. All the other separators (blank spacers, empty-state notes under + # a section that has rows, a stray line between choices) are the landmark of + # nothing, and are not candidates. Thus the lines pinned at the top are always from + # the section that governs. Separators stay when the filter applies (refer to + # _rows), so the pins continue to work while the list narrows. self._sticky_headers = [] self._pinned_header = None - block: list[str] | None = None # the heading block still taking rows, if any + block: list[str] | None = None # the heading block that still takes lines, if any if self._filter: lines.append(query_line(self._filter, width)) - # A row's detail line (see Choice.detail) can make it two lines tall, so the cursor - # is tracked inline as rows are drawn rather than derived from the row index. + # The detail line of a row (refer to Choice.detail) can make the row two lines tall. + # Thus the code follows the line of the highlight while it draws the rows, and does + # not calculate it from the row index. cursor_at: int | None = None for item in rows: if isinstance(item, Separator): - # A Text title carries its own spans (a two-colour column header); a plain - # string is drawn uniformly in the separator's style. A separator h-scrolls - # only as a panning table's column header — the per-row shift rides the - # highlighted choice row alone. + # A Text title has its own spans (a column header with two colours). A plain + # string is drawn all in the style of the separator. A separator scrolls + # horizontally only as the column header of a table that pans. The shift for + # each row moves only the highlighted choice row. title = item.text(_UNBOUNDED if item.pans and self._pan else width) content = title if isinstance(title, Text) else Text(title, style=item.style) if item.pans and self._pan: - # Its fullest form, slid with the rows, its pointer column held still: - # one line however wide, since its labels must stay over their lanes. + # Its fullest form, slid with the rows, with its pointer column held + # still. It is one line, however wide, because its labels must stay above + # their lanes. slid = self._scroll_window(content, _POINTER, width) drawn = [render_to_ansi(slid, width, no_wrap=True)] if item.pinned: @@ -814,57 +850,59 @@ class SelectScreen(Screen): block = list(drawn) self._sticky_headers.append((len(lines), block)) elif item.pinned: - # A pinned header is drawn *outside* the body slice and is exactly one - # row tall, so it crops like a row rather than wrapping — a column - # header too wide for the terminal ellipsizes instead of stealing a - # second reserved row from the content. + # A pinned header is drawn outside the body slice and is exactly one + # line tall. Thus it crops like a row and does not wrap. A column header + # that is too wide for the terminal ellipsizes, and does not take a + # second reserved line from the content. drawn = [render_to_ansi(content, width, no_wrap=True)] - # A whole-list header stands outside the section run too: it pins above - # the section headings rather than taking a turn among them, and so is - # no section boundary for the Ctrl+PageUp/PageDown jumps either. + # A header for the full list is also outside the sequence of sections. + # It pins above the section headings, and does not take a turn among + # them. Thus it is also not a section boundary for the + # Ctrl+PageUp/PageDown jumps. self._pinned_header = (len(lines), drawn[0]) else: - # A prose separator (a note above a startup list) may wrap; each row it - # takes is its own body line, so the viewport still counts them all — and - # every one of them joins the block, wrapped continuations included. + # A prose separator (a note above a startup list) can wrap. Each line that + # it takes is its own body line, so the viewport still counts all of + # them. Also, each of them joins the block, the wrapped lines too. drawn = render_lines(content, width) if item.heading: block = list(drawn) self._sticky_headers.append((len(lines), block)) elif block is not None: - block.extend(drawn) # the heading's preamble, pinned with it + block.extend(drawn) # the preamble of the heading, pinned with it lines.extend(drawn) continue - block = None # a row closes the heading's block; prose past here is its own + block = None # a row ends the heading block. Prose after it is not in the block. is_sel = item is selected if is_sel: cursor_at = len(lines) lines.append(self._row_drawer(item, is_sel, width)) - # Resolved here, not in the drawer: whether the row is one line tall or two is - # part of the layout, so a callable detail is read while planning — and its one - # resolved value is what the drawer below renders, never a second call. + # Resolved here, not in the drawer. Whether the row is one line tall or two is + # part of the layout, so a callable detail is read during the plan. The drawer + # below renders this one resolved value, and never calls the callable again. detail = item.detail_label if isinstance(item, Choice) else None if detail is not None and _plain(detail): lines.append(self._detail_drawer(detail, width)) if not choices: - # With no row to highlight the empty state holds its place: kept in view, and - # the page still edge-scrolls past it to whatever sits above and below. + # With no row to highlight, the empty state takes its place: it is kept visible, + # and the page still has edge scroll past it, to the lines above and below it. cursor_at = len(lines) lines.append(render_to_ansi(Text("no matches", style="muted"), width)) - # Remember where the highlighted row landed so the session can keep it in view. + # Keep the line of the highlighted row, so that the session can keep it visible. self._cursor = cursor_at return LazyLines(lines) def _row_drawer(self, item: Choice, is_sel: bool, width: int) -> Callable[[], str]: - """A callable that rasterizes one choice row — run only if the row is on screen.""" + """A callable that renders one choice row. It runs only if the row is on the screen.""" def draw() -> str: - # A width-aware title fits itself to the row's content area (the width less - # the 2-cell pointer). The exception is the highlighted row of an ``hscroll`` + # A width-aware title fits itself to the content area of the row (the width less + # the pointer of 2 cells). The exception is the highlighted row of an ``hscroll`` # list, which keeps its natural form: ←→ slide the full line, and a row that - # pre-elided itself would have nothing left to slide over — unless the row - # declares its fitted form complete (``Choice.fitted``). A panning table's rows - # all keep their natural form, highlighted or not: the pan slides every one. + # elided itself before has nothing to slide. But a row can declare that its + # fitted form is complete (``Choice.fitted``). All the rows of a table that pans + # keep their natural form, highlighted or not, because the pan slides each of + # them. panned = self._pan and item.pans if panned or (self._hscroll and not self._pan and is_sel): label = item.scroll_text(max(1, width - 2)) @@ -872,22 +910,24 @@ class SelectScreen(Screen): label = item.text(max(1, width - 2)) pointer = "❯ " if is_sel else " " style = "cursor" if is_sel else "" - # A Text label carries its own spans (e.g. a red badge); keep them and lay the - # row's base style underneath, so the highlight tints the row while the badge - # keeps its colour. A plain string is styled uniformly as before. + # A Text label has its own spans (for example, a red badge). Keep them, and put the + # base style of the row under them. Thus the highlight tints the row, and the + # badge keeps its colour. A plain string gets one style for all its text, as + # before. text = Text(pointer, style=style) label_text = label if isinstance(label, Text) else Text(label) if panned or (self._hscroll and not self._pan and self._hshift and is_sel): - # Only the label slides — the 2-cell pointer stays pinned. Per-row scrolling - # moves the highlighted row alone; a pan moves every row of the table, and - # draws its cut marks at the shift of 0 too, where a line runs off the edge. + # Only the label slides. The pointer of 2 cells stays pinned. The scroll for + # each row moves only the highlighted row. A pan moves each row of the table, + # and also draws its cut marks at a shift of 0, where a line goes past the + # edge. label_text = self._scroll_window(label_text, item.hscroll_from, max(1, width - 2)) text.append_text(label_text) text.style = style text.no_wrap = True - # Cut rather than truncate, so a row carrying a path line (a trophy walk, a - # probe candidate) breaks its chip off on the crack while every ordinary row - # still ends in the ellipsis — ``cut_to`` decides that from the row itself. + # Cut, do not truncate. Thus a row with a path line (a trophy walk, a probe + # candidate) breaks its chip off on the crack, and each usual row still ends in + # the ellipsis. ``cut_to`` decides this from the row itself. text = cut_to(text, width) text.no_wrap = True return render_to_ansi(text, width) @@ -895,44 +935,45 @@ class SelectScreen(Screen): return draw def _max_hshift(self, label_cells: int, anchor: int, avail: int) -> int: - """How far ←→ may slide a row of ``label_cells`` whose head holds ``anchor`` cells. + """How far ←→ can slide a row of ``label_cells`` whose head holds ``anchor`` cells. - The stop is the first whole :attr:`_HSCROLL_STEP` that brings the run's tail inside - the lane — not the exact cell that flushes it right. A scrolled row has given up a - cell to its left :func:`~meshterm.ui.pathline.cut_mark`, so its last window spans one - less than the lane; stopping short of a whole step would leave the *right* mark drawn - at the far end, promising a remainder ←→ can no longer reach. (Both hand-rolled - windowed path rows — the node page's routes, the Message paths lanes — clamp the - same way.) + The stop is the first whole :attr:`_HSCROLL_STEP` that brings the end of the run + into the lane, not the exact cell that puts the end at the right edge. A scrolled + row gave one cell to its left :func:`~meshterm.ui.pathline.cut_mark`. Thus its last + visible slice is one cell shorter than the lane. If the slide stops before a whole + step, the right mark stays drawn at the far end, and promises more text that ←→ can + no longer reach. (The two path rows that cut their own visible slice by + hand, the routes of the node page and the lanes of Message paths, clamp in the same + way.) """ lane = max(1, avail - max(0, anchor)) run = max(0, label_cells - max(0, anchor)) if run <= lane: - return 0 # the whole run is in view unscrolled: nothing to slide to + return 0 # the full run is visible without a scroll: nothing to slide to steps = -(-max(0, run - (lane - 1)) // self._HSCROLL_STEP) return steps * self._HSCROLL_STEP def _pan_limit(self, width: int) -> int: - """How far ←→ may pan this list's table at ``width``: to its widest line's tail. + """How far ←→ can pan the table of this list at ``width``: to the end of its widest line. - Every panning line is measured on the same terms — a row in the content area after - its pointer, a column header over the whole width with its pointer column held — so - the two measure the same table and agree on where it ends. + Each line that pans is measured in the same way: a row in the content area after + its pointer, and a column header over the full width with its pointer column held. + Thus the two measure the same table and agree on where it ends. - The stop is the exact shift that brings the widest line's tail to the edge, not the - whole :attr:`_HSCROLL_STEP` past it that :meth:`_max_hshift` takes for one row. Here - every line moves, so a whole-step stop would leave the entire table ending short of - the edge — and a box sized to its content (the startup splash) would shrink under the - reader on the last press, shedding hint atoms as it went. At the exact stop the - widest line meets the edge with no right-hand mark: its first hidden cell is past - its own end. + The stop is the exact shift that brings the end of the widest line to the edge. It + is not the whole :attr:`_HSCROLL_STEP` past it that :meth:`_max_hshift` takes for + one row. Here each line moves. Thus a stop at a whole step makes the full table end + before the edge. Also, a box with the size of its content (the startup splash) then + becomes smaller under the user at the last press, and removes hint atoms as it + becomes smaller. At the exact stop, the widest line touches the edge with no mark at + the right: its first hidden cell is after its own end. """ avail = max(1, width - _POINTER) def tail(cells: int, anchor: int, room: int) -> int: lane = max(1, room - anchor) run = max(0, cells - anchor) - return 0 if run <= lane else run - (lane - 1) # the left mark costs a cell + return 0 if run <= lane else run - (lane - 1) # the left mark takes a cell limit = 0 for item in self._rows(): @@ -947,21 +988,22 @@ class SelectScreen(Screen): return limit def _scroll_window(self, label: Text, anchor: int, avail: int) -> Text: - """The highlighted row's label with its head pinned and its run slid ``_hshift`` in. + """The label of the highlighted row: head pinned, run slid in by ``_hshift``. - The first ``anchor`` cells are drawn whole and never move — a row that declares them - (:attr:`Choice.hscroll_from`) is columns-then-content, and the columns are what tells - the reader which row they are on. Everything past them is the scrolling run, shown a - lane at a time, with the edge it continues past on each side wearing - :func:`~meshterm.ui.pathline.cut_mark` — a chip broken off in its own fill where the - run is a path drawn in chips, the faint ``…`` where it isn't. Those marks are chrome - *inside* the lane rather than extra width, so each costs the window a cell and the - crop is measured only once both are known; else the run would draw a cell past the - row. With ``anchor`` at ``0`` (the default) the whole line is the run, which is the - behaviour every hscroll list had before rows could pin a head. + The first ``anchor`` cells are drawn in full and never move. A row that declares + them (:attr:`Choice.hscroll_from`) has columns, then content, and the columns tell + the user which row the highlight is on. All the text after them is the run that + scrolls, shown one lane at a time. On each side where the run continues past the + edge, the edge shows :func:`~meshterm.ui.pathline.cut_mark`: a chip broken off in its + own fill where the run is a path drawn in chips, or the faint ``…`` where it is not. + These marks are chrome in the lane, not more width. Thus each mark takes a cell from + the visible slice, and the crop is measured only when the two marks are known. If + the crop is measured before, the run draws one cell past the row. With ``anchor`` at + ``0`` (the default), the full line is the run. This is the behaviour that each + hscroll list had before rows could pin a head. """ head = crop_cells(label, 0, anchor) if anchor > 0 else Text() - anchor = head.cell_len # a head wider than the label itself keeps only what is there + anchor = head.cell_len # a head wider than the label keeps only the cells that exist run = max(0, label.cell_len - anchor) shift = self._hshift left = 1 if shift else 0 @@ -979,10 +1021,10 @@ class SelectScreen(Screen): @staticmethod def _detail_drawer(detail: str | Text, width: int) -> Callable[[], str]: - """A callable that rasterizes a row's already-resolved detail line, on demand. + """A callable that renders the detail line of a row (already resolved), on demand. - Hangs under the row at the pointer's own indent — never scrolls or wraps, just - ellipsizes on its own if it's too wide to fit. + The line hangs under the row, at the indent of the pointer. It never scrolls or + wraps. It ellipsizes itself if it is too wide to fit. """ def draw() -> str: @@ -1003,18 +1045,18 @@ class SelectScreen(Screen): # --- input --------------------------------------------------------------- def handle(self, action: str, data: str = "") -> None: - """Move the highlight, edit the filter, or commit/cancel the selection.""" + """Move the highlight, edit the filter, or commit or cancel the selection.""" choices = self._choices() if self._hscroll and not self._pan and action in _HSHIFT_RESET_ACTIONS: - self._hshift = 0 # moving off a row abandons its scroll — each row scrolls alone + self._hshift = 0 # a move off a row resets its scroll. Each row scrolls by itself. if action == "up": if choices: - # Both ends clamp; nothing in the app rolls a highlight over. A ↓ off the - # last row would haul the window back to the head and flip the edge - # markers with it, which reads as the screen changing under the reader - # rather than as one step — and across a grouped list's section headings - # it reads as a jump rather than as continuing to scroll. Held-down arrows - # settle at an end instead. + # Both ends clamp. Nothing in the app rolls a highlight over. If a ↓ off the + # last row rolls over, it pulls the viewport back to the start and changes + # the edge markers with it. To the user, this looks like a change of the screen + # under them, not like one step. Across the section headings of a grouped + # list, it looks like a jump, not like a scroll that continues. Held-down + # arrows stop at an end instead. self._index = max(0, self._index - 1) elif action == "down": if choices: @@ -1024,9 +1066,9 @@ class SelectScreen(Screen): elif action == "pagedown": self._index = min(len(choices) - 1, self._index + self._page_step) if choices else 0 elif action in ("home", "ctrl_home"): - # The jump goes to the very top of the *page*, not just the first choice: the - # rows above it (a heading, its preamble, a lead-in note) scroll back into - # view too, rather than staying folded behind their pinned stand-ins. + # The jump goes to the top of the page, not only to the first choice. The lines + # above it (a heading, its preamble, a lead-in note) also scroll back onto the + # screen, and do not stay hidden behind their pinned copies. self._index = 0 self.scroll_to_top() elif action in ("end", "ctrl_end"): @@ -1039,18 +1081,19 @@ class SelectScreen(Screen): if choices: self.resolve(choices[self._index].value) elif action == "delete": - # Delete asks to remove the highlighted row, but only where the row opted in - # (e.g. a remembered network device in the picker); elsewhere it's inert. + # Delete asks to remove the highlighted row, but only where the row opted in (for + # example, a remembered network device in the picker). On other rows, it does + # nothing. if choices and choices[self._index].deletable: self.resolve(DeleteRequest(choices[self._index].value)) elif action == "left" and (self._hscroll or self._pan): self._hshift = max(0, self._hshift - self._HSCROLL_STEP) elif action == "right" and (self._hscroll or self._pan): - self._hshift += self._HSCROLL_STEP # clamped at render, to the row's or table's tail + self._hshift += self._HSCROLL_STEP # clamped at render to the end of the row or table elif action == "escape": - # A typed filter is the most recent thing the reader entered, so Esc peels that - # before it leaves — the map and the mesh walk's rule, now every filtering - # screen's. Leaving a narrowed list is the second Esc. + # A typed filter is the most recent thing that the user entered. Thus Esc clears + # it before Esc leaves. This was the rule of the map and the mesh walk, and now it + # is the rule of each screen with a filter. The second Esc leaves a narrowed list. if self._filterable and self._filter: self._filter = "" self._index = 0 @@ -1062,15 +1105,16 @@ class SelectScreen(Screen): self._index = 0 self._hshift = 0 elif action == "text" and data in self._keys: - # A declared shortcut resolves the list with what was pressed and where the - # highlight was standing; only a non-filterable list can declare any. + # A declared shortcut resolves the list with the pressed key and the row of the + # highlight. Only a list that is not filterable can declare shortcuts. self.resolve( KeyRequest(self._keys[data], choices[self._index].value if choices else None) ) elif action == "text" and self._filterable and data.isprintable(): - # A leading space is ignored (the filter never begins with whitespace); a - # trailing one is dropped when matching (see _rows), so spaces count only - # mid-query — inside a multi-word name like "Homestead R&D". + # A space at the start is ignored (the filter never starts with whitespace). A + # space at the end is removed when the filter matches (refer to _rows). Thus + # spaces count only in the middle of the query, in a name of more than one word + # such as "Homestead R&D". if not data.isspace() or self._filter: self._filter += data self._index = 0 @@ -1078,30 +1122,32 @@ class SelectScreen(Screen): class ReorderScreen(Screen): - """A list whose rows the user rearranges in place with the arrow keys. + """A list whose rows the user puts in a new order in place, with the arrow keys. - Move the cursor with ↑/↓; press Enter on a row to *grab* it, then ↑/↓ carry it up and - down the list; press Enter again to *drop* it. Below the list sit the action rows, - following the config editor's pattern: once the order has actually changed, an - ok-tinted *Apply* joins an err-tinted *Back — discard*; while it is untouched there - are no action rows at all, because Esc already leaves. Enter on Apply commits, - resolving with the final order as a list of the original row indices (so ``[2, 0, 1]`` - means "the row that started third is now first"); Enter on Back — like Esc anywhere — - resolves :data:`CANCEL` so the caller keeps the original order. + Move the highlight with ↑/↓. Press Enter on a row to "grab" it. Then ↑/↓ move it up and + down the list. Press Enter again to "drop" it. + + The action rows are below the list, in the same pattern as the config editor. When the + order has changed, an "Apply" row in the ``ok`` tint and a "Back — discard" row in the + ``err`` tint appear. While the order has no change, there are no action rows, because + Esc already leaves. Enter on Apply commits. It resolves with the final order as a list + of the original row indices (thus ``[2, 0, 1]`` means "the row that started third is + now first"). Enter on Back, like Esc on all screens, resolves :data:`CANCEL`, so the + caller keeps the original order. """ - #: Action-row sentinels (kept distinct from list positions, which are ints). + #: Sentinels for the action rows (different from list positions, which are ints). _APPLY = "apply" _BACK = "back" - #: Footer hints for both grab states — dialog_width sizes to the longer one, so the - #: box never resizes when a grab starts. + #: The footer hints for the two grab states. ``dialog_width`` uses the longer one, so the + #: box never changes size when a grab starts. _HINT_IDLE = "↑↓ move · Enter grab / select · Esc cancel" _HINT_GRABBED = "↑↓ move row · Enter drop · Esc cancel" @property def picocalc_lyra_lane(self): - """No lane: the whole screen is ↑↓ and Enter, three keys already on the keyboard.""" + """No lane: the full screen uses ↑↓ and Enter, three keys that are on the keyboard.""" from .fkeys import EMPTY_LANE return EMPTY_LANE @@ -1110,29 +1156,30 @@ class ReorderScreen(Screen): """Build a reorder screen. Args: - title: Heading shown above the list. + title: The heading above the list. labels: The row labels, in their current order. """ super().__init__() self.title = title self._labels = list(labels) - # order[position] == the label's original index; a moved row carries its index along. + # order[position] == the original index of the label. A moved row keeps its index. self._order = list(range(len(labels))) self._index = 0 self._grabbed = False @property def footer_hint(self) -> str: # type: ignore[override] - """Key hint, phrased for whether a row is currently grabbed.""" + """The key hint, with words that depend on whether a row is grabbed now.""" return self._HINT_GRABBED if self._grabbed else self._HINT_IDLE @property def dialog_width(self) -> int: - """Natural outer width so a floating reorder hugs its widest row (see SelectScreen). + """The natural outer width, so that a floating reorder box fits its widest row. - Sized for the fullest the box can get — both footer hints and the dirty-state - action rows — so it never widens mid-interaction when a grab starts or Apply - appears. The compositor still caps this to the terminal. + Refer to SelectScreen. The size is for the largest form of the box: the two footer + hints and the action rows of the changed state. Thus the box never becomes wider + during the interaction, when a grab starts or when Apply appears. The compositor + still limits this width to the terminal. """ widths = [cell_len(self.title), cell_len(self._HINT_IDLE), cell_len(self._HINT_GRABBED)] rows = self._labels + [label.plain for _key, label in self._dirty_actions()] @@ -1140,28 +1187,28 @@ class ReorderScreen(Screen): return max(widths, default=20) + 8 def _dirty(self) -> bool: - """Whether the rows have actually left their original order.""" + """Whether the rows are no longer in their original order.""" return self._order != list(range(len(self._order))) @staticmethod def _dirty_actions() -> list[tuple[str, Text]]: - """The full exit group shown once the order has changed (also sizes dialog_width).""" + """The full exit group, shown after the order changes (it also sets dialog_width).""" return [ (ReorderScreen._APPLY, Text.assemble(("✓ ", "ok"), "Apply new order")), (ReorderScreen._BACK, Text.assemble(("✗ ", "err"), "Back — discard changes")), ] def _actions(self) -> list[tuple[str, Text]]: - """The action rows below the list, matching the config editor's exit group. + """The action rows below the list, the same as the exit group of the config editor. - An untouched order offers none: Esc leaves, and a row saying so was retired - app-wide. A changed one offers the pair, because Apply has no key of its own and - its counterpart names what leaving costs. + An order with no change offers no rows: Esc leaves, and we removed the row that told + this from all the app. A changed order offers the pair, because Apply has no key of + its own, and its counterpart tells what a leave costs. """ return self._dirty_actions() if self._dirty() else [] def render_body(self, width: int) -> list[str]: - """Render the rows, a blank spacer, then the action group, marking the cursor.""" + """Render the rows, a blank spacer, then the action group, and mark the highlight.""" n = len(self._order) lines: list[str] = [] for pos, orig in enumerate(self._order): @@ -1182,29 +1229,29 @@ class ReorderScreen(Screen): lines.append("") for i, (_key, label) in enumerate(actions): if n + i == self._index: - # The cursor row takes the highlight like the list rows above it, - # trading the ✓/✗ tint for the highlight. + # The highlighted action row gets the ``cursor`` style, as the list rows + # above it do. It loses the ✓/✗ tint for this style. text = Text("❯ " + label.plain, style="cursor", no_wrap=True) else: text = Text(" ", no_wrap=True) text.append_text(label) text.truncate(width, overflow="ellipsis") lines.append(render_to_ansi(text, width)) - # The spacer line offsets every action row by one on screen. + # The spacer line moves each action row down by one line on the screen. self._cursor = self._index if self._index < n else self._index + 1 return lines def cursor_line(self) -> int | None: - """Return the body line index of the cursor row, so the session keeps it in view.""" + """Return the body line index of the highlight, so that the session keeps it visible.""" return getattr(self, "_cursor", None) def handle(self, action: str, data: str = "") -> None: - """Move the cursor, carry a grabbed row, grab/drop, run an action, or cancel on Esc.""" + """Move the highlight or a grabbed row, grab or drop, run an action, or cancel on Esc.""" n = len(self._order) actions = self._actions() total = n + len(actions) - # A change undone while the cursor sat on an action row would strand it past the - # end; clamp before anything reads it. + # If a change is undone while the highlight is on an action row, the highlight is + # past the end. Clamp it before anything reads it. self._index = min(self._index, max(0, total - 1)) if action == "up": if self._grabbed and self._index > 0: @@ -1214,9 +1261,9 @@ class ReorderScreen(Screen): ) self._index -= 1 elif not self._grabbed and total: - # Clamps like every other row cursor, and like the grabbed one just above: + # Clamp, as each other row highlight does, and as the grabbed row above does: # the same two keys must not mean "stop at the end" in one mode and "leap - # to the other end" in the other. + # to the other end" in the other mode. self._index = max(0, self._index - 1) elif action == "down": if self._grabbed and self._index < n - 1: @@ -1228,9 +1275,9 @@ class ReorderScreen(Screen): elif not self._grabbed and total: self._index = min(total - 1, self._index + 1) elif action in ("home", "ctrl_home") and not self._grabbed and total: - # Home and End jump to the first row and the last, as on every list, and edge - # scroll takes the page to its ends with them. A grabbed row is carried a step - # at a time only, so they leave it where it is. + # Home and End jump to the first row and the last, as on each list, and the edge + # scroll moves the page to its ends with them. A grabbed row moves only one step + # at a time, so these keys do not move it. self._index = 0 elif action in ("end", "ctrl_end") and not self._grabbed and total: self._index = total - 1 diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index aa03f0b..e2bc6cc 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -1,13 +1,17 @@ # SPDX-License-Identifier: Apache-2.0 -"""The persistent full-screen session: the heart of the TUI library. +"""The persistent full-screen session: the central part of the TUI library. A :class:`TuiSession` owns one prompt_toolkit :class:`Application`, a stack of -:class:`~meshterm.ui.tui.screen.Screen` layers, and the persistent header/footer frame. It -translates prompt_toolkit key events into normalized *actions* dispatched to the top screen, -composes the current view (bounded to the terminal, reflowing on resize) via -:mod:`~meshterm.ui.tui.frame`, and exposes ``async`` helpers (``select``/``text``/ -``confirm``/``autocomplete``/``scroll``/``progress``) that push a screen, await its result, -and pop it — the push/await/pop model behind every prompt. +:class:`~meshterm.ui.tui.screen.Screen` layers, and the persistent header and footer. It +does these tasks: + +- It changes the prompt_toolkit key events into normalized *actions*, and it sends each + action to the top screen. +- It composes the current frame through :mod:`~meshterm.ui.tui.frame`. The frame stays in + the limits of the terminal, and its content flows again when the terminal changes size. +- It gives ``async`` helpers (``select``/``text``/``confirm``/``autocomplete``/``scroll``/ + ``progress``). Each helper pushes a screen, awaits its result, and pops it. This push, + await, and pop model is behind each prompt. """ from __future__ import annotations @@ -53,42 +57,53 @@ from .screen import CANCEL, POP_ALL, BusyDialog, BusyScreen, PopToMenu, Screen, from .select import Choice, ReorderScreen, SelectScreen, Separator from .spinner import spinner_interval -#: Every Ctrl-letter chord the app binds, keyed by the bare lowercase letter — the single -#: source of truth for both halves of a chord's life: the ``Keys.Control*`` bindings folded -#: into :data:`_KEY_ACTIONS` below, and the right-Ctrl rescue in :meth:`TuiSession._dispatch` -#: (see :func:`_right_ctrl_down`), which promotes the bare letter a layout-claimed right Ctrl -#: delivers as *text* back into the chord. Add a chord here and both Ctrl keys reach it — no -#: second edit, no chord that works on one side of the keyboard only. ``quit`` and -#: ``paste_clipboard`` are the session's own (answered in ``_dispatch``); the rest are actions -#: forwarded to the top screen. A bare letter only reaches text while the right Ctrl is held -#: when the layout has no third-level glyph for that key (i.e. it really is the chord) — a -#: genuine third-level character arrives as some *other* glyph and never matches this table. -#: ``m``/``i``/``h`` are not free: prompt_toolkit spells Enter, Tab and Backspace as -#: ``Keys.ControlM``/``ControlI``/``ControlH``, so claiming them here would rebind those keys. -#: A chord's letter is the mnemonic of the *action*, not of one screen's word for it — -#: ``locate`` is ^Y for **you** (JP, 2026-08-09), the same key on the map and in the mesh -#: walk, because what it names on both is our own node; it was ^U until 2026-10-01, when U -#: went to ``url_code`` — a chat message's links as QR codes. +#: Each Ctrl-letter chord that the app binds, indexed by the bare lowercase letter. This +#: table is the single source of truth for the two halves of the life of a chord: #: -#: Two of these are app-wide rather than a screen's: ``to_menu`` (^W) unwinds the whole -#: navigation stack back to the main menu, and ``quit`` (^Q, alongside the older ^C) asks -#: to leave the app from anywhere — a second press while it asks is the leaving (see -#: :meth:`TuiSession.request_quit`). Neither is advertised in a footer hint or an F-key -#: chip — the lane has three free slots per screen and a global verb would claim one on -#: every screen forever (JP, 2026-08-30) — save ``^Q quit?`` on the main menu's own hint, -#: where Esc is inert and the reader looks for the way out (issue #22). ^W was -#: picked for the close-this-whole-thing reflex; both were verified deliverable on the -#: Canadian Multilingual layout (^W ``U+0017``, ^Q ``U+0011``) and neither is eaten by the -#: terminal — prompt_toolkit's raw mode clears ``IXON``/``IXOFF``, so ^Q is not XON here. +#: - the ``Keys.Control*`` bindings, which are folded into :data:`_KEY_ACTIONS` below. +#: - the right-Ctrl rescue in :meth:`TuiSession._dispatch` (refer to +#: :func:`_right_ctrl_down`). When a keyboard layout claims the right Ctrl key, that key +#: sends a bare letter as text. The rescue changes that letter back into the chord. +#: +#: Add a chord here, and the two Ctrl keys get it. A second edit is not necessary, and no +#: chord works on only one side of the keyboard. ``quit`` and ``paste_clipboard`` belong to +#: the session (``_dispatch`` answers them). The other entries are actions that the session +#: sends to the top screen. While the right Ctrl key is held, a bare letter gets to the text +#: only when the layout has no third-level glyph for that key (that is, when the key press is +#: the chord). A real third-level character arrives as a different glyph, and it never +#: matches this table. +#: ``m``/``i``/``h`` are not free: prompt_toolkit spells Enter, Tab, and Backspace as +#: ``Keys.ControlM``/``ControlI``/``ControlH``. If this table claims them, it binds those +#: keys again. +#: The letter of a chord is the mnemonic of the action, not of the word that one screen uses +#: for it. ``locate`` is ^Y for **you** (JP, 2026-08-09). It is the same keyboard key on the +#: map and in the mesh walk, because on both it names our node. It was ^U until 2026-10-01. +#: Then U went to ``url_code``: the links of a chat message as QR codes. +#: +#: Two of these chords are for the full app, not for one screen: +#: +#: - ``to_menu`` (^W) unwinds the full navigation stack back to the main menu. +#: - ``quit`` (^Q, and also the older ^C) asks to quit the app from any screen. A second +#: press while the question is open quits (refer to :meth:`TuiSession.request_quit`). +#: +#: No footer hint and no F-key chip shows these two chords. The F-key lane has three free +#: slots for each screen, and a chip for a global verb uses one slot on each screen permanently +#: (JP, 2026-08-30). The only exception is ``^Q quit?`` in the hint of the main menu. There +#: the Esc key does nothing, and the user looks for the way out (issue #22). We chose ^W +#: because users press it by reflex to close everything. On the Canadian Multilingual layout, +#: we checked that the keyboard sends the two chords (^W ``U+0017``, ^Q ``U+0011``), and the +#: terminal does not consume either of them. The raw mode of prompt_toolkit clears +#: ``IXON``/``IXOFF``, so ^Q is not XON here. _CTRL_LETTER_CHORDS: dict[str, str] = { "c": "quit", - # ^L logs in to the room a room view is open on. + # ^L logs in to the room that a room screen shows. "l": "login", "p": "paths", "q": "quit", "r": "retry", - # ^S is XOFF's key, and safe here for the same reason ^Q is not XON (see above): raw - # mode clears IXON/IXOFF, so the terminal never eats it to freeze the screen. + # ^S is the XOFF key. It is safe here for the same reason that ^Q is not XON (refer to + # the text above): the raw mode clears IXON/IXOFF. Thus the terminal never takes it to + # freeze the screen. "s": "reveal", "u": "url_code", "v": "paste_clipboard", @@ -96,7 +111,7 @@ _CTRL_LETTER_CHORDS: dict[str, str] = { "y": "locate", } -#: Maps prompt_toolkit keys to the normalized action names screens understand. +#: Maps the prompt_toolkit keys to the normalized action names that the screens understand. _KEY_ACTIONS: dict[Any, str] = { Keys.Up: "up", Keys.Down: "down", @@ -119,39 +134,42 @@ _KEY_ACTIONS: dict[Any, str] = { Keys.ControlUp: "ctrl_up", Keys.ControlDown: "ctrl_down", Keys.Enter: "enter", - # Ctrl+Enter, as far as a terminal can spell it. There is no such keycode: Enter *is* - # ^M, so a console that doesn't do modifyOtherKeys has nothing left to modify and - # sends plain CR. What most do send is LF — prompt_toolkit's ``ControlJ`` — which is - # otherwise unbound here (an unprintable char, dropped by ``_typed``), so claiming it - # costs nothing and wins on the terminals that offer it. The right-Ctrl rescue below - # covers the rest through _CTRL_CHORDS, and on a console that spells neither, the - # F-lane chip is the affordance (which is the platform where that is already true). + # Ctrl+Enter, as well as a terminal can spell it. No such keycode exists: Enter is ^M. + # Thus a console without modifyOtherKeys has nothing more to modify, and it sends a + # plain CR. Most consoles send LF (``ControlJ`` in prompt_toolkit). LF has no other + # binding here (it is an unprintable character, and ``_typed`` removes it). Thus this + # binding costs nothing, and it works on the terminals that send LF. The right-Ctrl + # rescue below covers the other cases through _CTRL_CHORDS. On a console that spells + # neither, the chip on the F-key lane is the affordance (that is already true on the + # platform of that console). Keys.ControlJ: "ctrl_enter", Keys.Escape: "escape", Keys.Backspace: "backspace", Keys.Delete: "delete", Keys.Tab: "tab", Keys.BackTab: "shift_tab", - # The function keys, for a handheld's F-key lane. All of them, since which keycodes - # drive the lane is the platform's deck's business, not this table's: the PicoCalc's - # MCU sends its Shift bank as F6–F10, the Cardputer's emulator sends Shift+F4..F8 - # as xterm does, which prompt_toolkit reads as F16–F20. The session resolves them - # against the top screen's lane in _dispatch; a key the deck doesn't use, or a - # platform without a lane, resolves to nothing and falls away. Alt+Fn is the kernel's - # VT switch on the PicoCalc and must never be bound. + # The function keys, for the F-key lane of a handheld. This table binds all of them, + # because the deck of the platform decides which keycodes drive the lane, not this + # table. The MCU of the PicoCalc sends its Shift bank as F6–F10. The emulator of the + # Cardputer sends Shift+F4..F8 the same as xterm, and prompt_toolkit reads them as + # F16–F20. In _dispatch, the session resolves them against the lane of the top screen. + # A key that the deck does not use, or a key on a platform without a lane, resolves to + # nothing and is ignored. On the PicoCalc, Alt+Fn is the VT switch of the kernel, and + # it must never have a binding. **{getattr(Keys, f"F{n}"): f"f{n}" for n in range(1, 25)}, - # The Ctrl-letter chords, generated from the one table above so a chord can never be - # bound without its right-Ctrl rescue (or rescued into an action nothing binds). + # The Ctrl-letter chords, made from the one table above. Thus a chord can never have a + # binding without its right-Ctrl rescue (or a rescue into an action that nothing binds). **{ getattr(Keys, f"Control{letter.upper()}"): action for letter, action in _CTRL_LETTER_CHORDS.items() }, } -#: The plain actions that have a Ctrl-chord sibling, for the right-Ctrl rescue in -#: :meth:`TuiSession._dispatch` (see :func:`_right_ctrl_down`). Navigation keys, plus -#: ``enter`` — the one key a terminal cannot reliably spell chorded (see ``Keys.ControlJ`` -#: above), so the rescue is not a fallback there but the surer of the two paths. +#: The plain actions that have a related Ctrl chord, for the right-Ctrl rescue in +#: :meth:`TuiSession._dispatch` (refer to :func:`_right_ctrl_down`). These are the +#: navigation keys, and also ``enter``. A terminal cannot reliably spell ``enter`` as a chord +#: (refer to ``Keys.ControlJ`` above). Thus, for ``enter``, the rescue is not a fallback: it +#: is the more reliable of the two ways. _CTRL_CHORDS: dict[str, str] = { "up": "ctrl_up", "down": "ctrl_down", @@ -166,35 +184,37 @@ _CTRL_CHORDS: dict[str, str] = { def _right_ctrl_down() -> bool: - """Whether the right Ctrl key is physically held right now (Windows; ``False`` elsewhere). + """Whether the right Ctrl key is physically held now (Windows, ``False`` on other systems). - The rescue behind right-Ctrl chords. Keyboard layouts that claim the right Ctrl key as a - character-group modifier — the Canadian Multilingual Standard uses it to reach a third - character level — can deliver a right-Ctrl'd arrow to the console as a *bare* arrow, no - ctrl flag left for prompt_toolkit to map, so only the left Ctrl ever steered a sortable - list. This probes the physical key state (``GetAsyncKeyState``) instead of trusting the - stripped event modifiers: if an arrow reached our dispatch, our terminal had focus, so a - right Ctrl held at that instant is the user chording it. Non-Windows platforms report - ``False`` — a VT terminal encodes the ctrl modifier side-agnostically itself, and there - is no per-side key state to consult anyway. + This function is the rescue behind the right-Ctrl chords. Some keyboard layouts claim the + right Ctrl key as a modifier for a character group. (The Canadian Multilingual Standard + uses it to get to a third character level.) These layouts can send an arrow with the + right Ctrl key to the console as a bare arrow. Then no Ctrl flag stays for prompt_toolkit + to map, so only the left Ctrl key could control a sortable list. This function probes the + physical state of the key (``GetAsyncKeyState``). It does not trust the event modifiers, + because the layout removed them. If an arrow got to our dispatch, our terminal had the + focus. Thus a right Ctrl key that is held at that instant is a chord that the user makes. + The platforms other than Windows report ``False``. A VT terminal itself encodes the Ctrl + modifier the same for the two sides, and there is no key state for each side to examine. """ if sys.platform != "win32": return False try: return bool(win32dll.user32().GetAsyncKeyState(0xA3) & 0x8000) # VK_RCONTROL - except Exception: # noqa: BLE001 - a failed probe just leaves the plain action + except Exception: # noqa: BLE001 - if the probe fails, the plain action stays return False def _read_clipboard() -> str: - """Best-effort read of the OS clipboard's Unicode text (Windows; ``""`` elsewhere). + """Try to read the Unicode text of the OS clipboard (Windows, ``""`` on other systems). - The fallback behind Ctrl-V on a terminal that delivers the key literally rather than as a - bracketed paste (see :meth:`TuiSession._dispatch`): it pulls the clipboard's text - straight from the Win32 API. Every failure — a non-Windows platform, an empty or - non-text clipboard, a clipboard busy elsewhere we couldn't open — collapses to ``""``, so - the paste simply does nothing rather than raising into the key handler. Pointer-returning - calls declare a ``c_void_p`` result so a 64-bit handle isn't truncated to an int. + This function is the fallback behind Ctrl-V on a terminal that sends the key as it is, + instead of as a bracketed paste (refer to :meth:`TuiSession._dispatch`). It gets the text + of the clipboard directly from the Win32 API. Each failure gives ``""``: a platform that + is not Windows, an empty clipboard, a clipboard without text, or a clipboard that another + program uses, so that we could not open it. Thus the paste does nothing, and no exception + goes into the key handler. The calls that return a pointer declare a ``c_void_p`` result, + so that a 64-bit handle is not truncated to an int. """ if sys.platform != "win32": return "" @@ -202,8 +222,8 @@ def _read_clipboard() -> str: import ctypes CF_UNICODETEXT = 13 - # Private handles; the argtypes below would otherwise be declared on objects - # every library in the process shares. See meshterm.core.win32dll. + # Private handles. Without them, the argtypes below are declared on objects that all + # the libraries in the process share. Refer to meshterm.core.win32dll. user32 = win32dll.user32() kernel32 = win32dll.kernel32() user32.GetClipboardData.restype = ctypes.c_void_p @@ -226,36 +246,43 @@ def _read_clipboard() -> str: kernel32.GlobalUnlock(handle) finally: user32.CloseClipboard() - except Exception: # noqa: BLE001 - a clipboard hiccup must never break a keypress + except Exception: # noqa: BLE001 - a small clipboard problem must never break a key press return "" def _reclaim_last_column() -> bool | None: - """Whether to reclaim the terminal's final column — or ``None``, to ask the terminal. + """Whether to use the last column of the terminal, or ``None`` to ask the terminal. - prompt_toolkit's Windows console output reports the window one column narrower than it - really is, on purpose (see :func:`_probe_hides_last_column`), so the frame is drawn to - ``columns - 1`` and the true last column sits unused — visibly selectable to the right of - the border. When this is on, :class:`_WidthExtendedOutput` tells both the renderer and - the frame compositor the window is one column wider, and that final column gets drawn. + The Windows console output of prompt_toolkit reports the window as one column narrower + than it is. It does this on purpose (refer to :func:`_probe_hides_last_column`). Thus the + frame is drawn to ``columns - 1``, and the real last column is not used. The user can see + that column at the right of the border, and can select it. When this value is on, + :class:`_WidthExtendedOutput` tells the renderer and the frame compositor that the window + is one column wider. Then that last column is drawn. - It is *correct* only where the probe hid the column. Everywhere else the extra column - falls off the real screen, and since prompt_toolkit draws with autowrap off, each row's - phantom last cell is written over the real one before it: whatever sits flush right - loses its final character. On Linux that cut the header's battery gauge, so a full pack's - bare ``100`` read ``10`` and 99% read ``9%``. Hence the default is a question rather than - an answer: ``None`` means "reclaim if, and only if, the output this session draws on is - one whose probe hides the column", decided once that output exists. + This is correct only where the probe hid the column. In all other cases, the extra column + is outside the real screen. prompt_toolkit draws with autowrap off, so the phantom last + cell of each row is written over the real cell before it. Thus the text at the right edge + loses its last character. On Linux, this cut the battery gauge of the header: a full + battery showed ``10`` instead of ``100``, and 99% showed ``9%``. Thus the default is a + question, not an answer. ``None`` means "reclaim if, and only if, the output this session + draws on is one whose probe hides the column". The session decides this when that output + exists. - Three sources, in confidence order, because the person at the keyboard can see the - column and the code can only infer it: ``MESHTERM_FULL_WIDTH=0``/``=1`` for a one-off, - then the ``full_width`` preference (``yes``/``no``; ``auto`` — the default — steps - aside), then the platform, which answers ``False`` outright where its console is exact - (:data:`~meshterm.platforms.PICOCALC_LYRA`) and otherwise leaves it to the terminal. + Three sources give the answer, in the order of confidence, because the user at the + keyboard can see the column and the code can only infer it: - Read fresh on every call (never cached at import time) so it reflects whichever platform - :func:`~meshterm.platforms.set_platform` installed for this process — see that module's - docstring for why a cached/imported copy of the platform would go stale. + 1. ``MESHTERM_FULL_WIDTH=0``/``=1``, for one run. + 2. The ``full_width`` preference (``yes``/``no``). ``auto``, the default, gives no + answer. + 3. The platform. It answers ``False`` where its console is exact + (:data:`~meshterm.platforms.PICOCALC_LYRA`). In the other cases, it lets the terminal + decide. + + The function reads the values again at each call (never at import time, into a cache). + Thus it agrees with the platform that :func:`~meshterm.platforms.set_platform` installed + for this process. Refer to the docstring of that module for the reason why a cached or + imported copy of the platform becomes old. """ from ...core.preferences import current as current_preferences @@ -269,17 +296,18 @@ def _reclaim_last_column() -> bool | None: def _probe_hides_last_column(output: Any) -> bool: - """Whether prompt_toolkit sizes ``output`` one column narrower than its window. + """Whether prompt_toolkit gives ``output`` a width one column narrower than its window. - True of its Windows console output and nothing else. ``Win32Output.get_size`` takes the - visible width as ``srWindow.Right - srWindow.Left`` (an inclusive span, so one short) and - then caps it below the buffer's right margin — "windows will wrap otherwise" — and - ``Windows10_Output`` and ``ConEmuOutput`` both hand their size to the ``Win32Output`` - they hold. A POSIX terminal's ``Vt100_Output`` reads ``TIOCGWINSZ``, which is exact, so - there is nothing there to reclaim. + True for its Windows console output, and for no other output. ``Win32Output.get_size`` + takes the visible width as ``srWindow.Right - srWindow.Left``. This is an inclusive span, + so it is one column short. Then the function limits the width to less than the right + margin of the buffer ("windows will wrap otherwise"). ``Windows10_Output`` and + ``ConEmuOutput`` both use the size of the ``Win32Output`` that they hold. The + ``Vt100_Output`` of a POSIX terminal reads ``TIOCGWINSZ``, which is exact. Thus there is + no column to reclaim there. """ if sys.platform != "win32": - return False # prompt_toolkit's win32 module asserts the platform on import + return False # the win32 module of prompt_toolkit asserts the platform on import from prompt_toolkit.output.win32 import Win32Output return isinstance(output, Win32Output) or isinstance( @@ -287,48 +315,55 @@ def _probe_hides_last_column(output: Any) -> bool: ) -#: What each ``color_depth`` preference value asks for. ``auto`` is deliberately absent: it -#: is the one answer that is not a depth, and :func:`_color_depth` resolves it separately. +#: The depth for each value of the ``color_depth`` preference. ``auto`` is not in the table +#: on purpose: it is the only value that is not a depth, and :func:`_color_depth` resolves it +#: separately. _DEPTH_BY_NAME = { "truecolor": ColorDepth.DEPTH_24_BIT, "256": ColorDepth.DEPTH_8_BIT, "16": ColorDepth.DEPTH_4_BIT, } -#: What ``COLORTERM`` says on a terminal that means it about 24-bit colour. There is no -#: in-band way to ask — a terminal that cannot do truecolor answers a truecolor SGR by -#: quietly approximating it, which looks from here exactly like one that can — so this -#: convention, which every truecolor terminal follows, is the whole of the evidence. +#: The ``COLORTERM`` values of a terminal that tells the truth about 24-bit colour. There is +#: no in-band way to ask. A terminal without truecolor answers a truecolor SGR with an +#: approximation, and it does not tell us. From here, that looks exactly the same as a +#: terminal with truecolor. Thus this convention, which each truecolor terminal follows, is +#: all the evidence. _TRUECOLOR_COLORTERM = frozenset({"truecolor", "24bit"}) def _color_depth() -> ColorDepth | None: - """How many colours to send this terminal, or ``None`` to keep prompt_toolkit's verdict. + """How many colours to send to this terminal, or ``None`` to keep the prompt_toolkit verdict. - prompt_toolkit picks a depth per *output class*, and its two classes disagree: - ``Windows10_Output`` returns ``TRUE_COLOR`` outright, while ``Vt100_Output`` returns - ``DEPTH_8_BIT`` for every ``TERM`` but ``linux`` and a dumb terminal. So the same build - of MeshTerm, drawing the same theme, is 24-bit on Windows and 256 colours on macOS and - Linux — and it is quantized *silently*, which is why this went unnoticed: the app looks - fine, just flatter. It costs exactly what this palette is made of. The seven ``heat.*`` - steps and the per-node hue wheel (:func:`~meshterm.ui.theme.node_style`) are close - pastels chosen to be told apart; snapped to the 216-colour cube, neighbours collide and - identities stop being distinguishable by hue. ``COLORTERM`` is not consulted by - prompt_toolkit at all — only ``PROMPT_TOOLKIT_COLOR_DEPTH`` is — so a terminal - announcing truecolor in the conventional way is still handed 256. + prompt_toolkit chooses a depth for each *output class*, and its two classes do not agree. + ``Windows10_Output`` returns ``TRUE_COLOR`` directly. ``Vt100_Output`` returns + ``DEPTH_8_BIT`` for each ``TERM`` except ``linux`` and a dumb terminal. Thus the same + build of MeshTerm, with the same theme, has 24-bit colour on Windows and 256 colours on + macOS and Linux. The quantization is silent, and for this reason nobody saw it: the app + looks correct, only flatter. But the quantization damages exactly the thing that this + palette is made of. The seven ``heat.*`` steps and the hue wheel for the nodes + (:func:`~meshterm.ui.theme.node_style`) are pastels that are near each other, and we + chose them so that the user can tell them apart. In the 216-colour cube, neighbours become + the same colour, and the user cannot tell the identities apart by hue. prompt_toolkit + does not read ``COLORTERM``. It reads only ``PROMPT_TOOLKIT_COLOR_DEPTH``. Thus a + terminal that announces truecolor in the usual way still gets 256 colours. - Three sources, in confidence order, the same shape as :func:`_reclaim_last_column`: - ``MESHTERM_COLOR_DEPTH`` for a one-off, then the ``color_depth`` preference, then a - reading of the environment. + Three sources give the answer, in the order of confidence, the same as in + :func:`_reclaim_last_column`: - The reading only ever *raises* the verdict, never lowers it. A terminal we cannot get a - positive claim from returns ``None`` and keeps precisely the depth it had, so a host - this function has never heard of cannot be made worse by it — which matters more than - being right everywhere, because the failure mode of guessing 24-bit at a terminal - without it is not a duller palette but no colour at all. + 1. ``MESHTERM_COLOR_DEPTH``, for one run. + 2. The ``color_depth`` preference. + 3. A reading of the environment. + + The reading only increases the verdict. It never decreases it. If a terminal does not + give a positive claim, the function returns ``None``, and the terminal keeps exactly the + depth that it had. Thus this function cannot make a host worse when it does not know that + host. This is more important than a correct answer everywhere. If the function guesses + 24-bit for a terminal without 24-bit colour, the result is not a duller palette: it is no + colour at all. Returns: - The depth to force, or ``None`` to leave prompt_toolkit's own default in place. + The depth to force, or ``None`` to keep the default of prompt_toolkit. """ from ...core.preferences import current as current_preferences @@ -338,42 +373,43 @@ def _color_depth() -> ColorDepth | None: return _DEPTH_BY_NAME[preferred] if preferred != "auto": return None - # A 16-slot console is already right and has no truecolor to claim: the theme addresses - # its palette by index (see theme._VT_SLOTS), and promoting the depth would send RGB to - # a screen with sixteen colours to put it in. + # A 16-slot console is already correct, and it has no truecolor to claim. The theme + # addresses its palette by index (refer to theme._VT_SLOTS). If the function increases + # the depth, it sends RGB to a screen that has only sixteen colours for it. if not get_platform().truecolor: return None if os.environ.get("COLORTERM", "").strip().lower() in _TRUECOLOR_COLORTERM: return ColorDepth.DEPTH_24_BIT - # terminfo's own spelling for a direct-colour entry (``xterm-direct``, ``*-direct16m``). + # The terminfo spelling for a direct-colour entry (``xterm-direct``, ``*-direct16m``). if os.environ.get("TERM", "").endswith(("-direct", "-direct16m")): return ColorDepth.DEPTH_24_BIT return None -#: How many stacked dialog layers the layout can float over the background at once. A fixed -#: pool of centered-box floats (see :meth:`TuiSession._build_app`), sized well past the deepest -#: real nesting — a tool's list, an item's detail popup, and a confirm over that is only three. +#: The maximum number of dialog layers that the layout can float over the background at one +#: time. It is a fixed pool of floats, each one a centred box (refer to +#: :meth:`TuiSession._build_app`). The pool is much larger than the deepest real nesting: the +#: list of a tool, a detail dialog for an item, and a confirm over it are 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). +#: How long :meth:`TuiSession.leave` waits for the quiesce of the app to start (that is, for +#: a transmission in progress to finish). After this time, the method continues all the same. +#: On the Cardputer Zero, the full exit must fit in the three seconds that the launcher gives +#: between SIGTERM and SIGKILL (:data:`~meshterm.services.hold_to_quit.GRACE_S`). The rest of +#: the exit took approximately one second there (measured on 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. + """Which lines of a full-screen frame are different, or ``None`` if a comparison fails. - Both frames are composed one line per terminal row (see - :func:`~meshterm.ui.tui.frame.compose_base`), so a line index *is* a row index — the - mapping :meth:`TuiSession._scrub_rows` needs. A differing line count means the frame's - height moved (a resize, a splash giving way to the framed layout) and no such mapping - holds; the caller falls back to repainting everything. + The two frames are composed with one line for each terminal row (refer to + :func:`~meshterm.ui.tui.frame.compose_base`). Thus a line index is also a row index, and + :meth:`TuiSession._scrub_rows` uses this mapping. If the line counts are different, the + height of the frame changed (a resize, or a splash that gives its place to the framed + layout), and this mapping is not true. Then the caller does a full paint. """ old, new = before.split("\n"), after.split("\n") if len(old) != len(new): @@ -382,27 +418,28 @@ def _changed_rows(before: str, after: str) -> list[int] | None: def _has_wide_glyph(text: str) -> bool: - """Whether ``text`` holds a glyph prompt_toolkit reserves two cells for. + """Whether ``text`` has a glyph for which prompt_toolkit reserves two cells. - A width-2 glyph is where the terminal and the renderer can disagree: an emoji (``👋``) - that the terminal draws in a *single* cell is the common case here — pt reserves two, - the terminal advances one, and from that point the row's cursor model is off. Node-type - marks (``▲●■``) and chart braille are width-1 everywhere, so they never trip this. The - ``>= 0x1100`` guard skips the ASCII/Latin bulk of a frame before the width lookup, which - matters because this runs over the whole composed frame on every repaint. + The terminal and the renderer can disagree about a width-2 glyph. The usual case here is + an emoji (``👋``) that the terminal draws in one cell. pt reserves two cells, the + terminal moves forward one cell, and after that point the cursor model of the row is + incorrect. The node-type marks (``▲●■``) and the braille of a chart have a width of 1 + everywhere, so they never cause a ``True`` result. The ``>= 0x1100`` guard skips the + ASCII and Latin characters, which are most of a frame, before the width lookup. This is + important, because this function examines the full composed frame at each paint. - On a platform that folds its frames to a fixed font the answer is ``False`` by - construction — that font is a 512-glyph set with no wide glyph in it, so nothing a - composed frame can contain would return ``True``. Answering from the platform instead - of the text skips a per-character scan of the entire frame on every repaint, and with - it the scrub machinery that a ``True`` would arm, leaving the cheap differential paint - permanently in play. + On a platform that folds its frames to a fixed font, the answer is always ``False``. + That font is a set of 512 glyphs with no wide glyph in it. Thus nothing that a composed + frame can contain can return ``True``. The function answers from the platform instead of + from the text. Thus it skips a scan of each character of the full frame at each paint. + It also skips the scrub machinery that a ``True`` result arms, so the cheap differential + paint always stays in use. - The fold is the guarantee, not the icon table: a terminal that merely can't draw - *emoji* (the classic Windows console — see :func:`meshterm.ui.termfont.emoji_support`) - still renders the rest of the BMP, and a contact named in CJK is two cells wide there - like anywhere else. Reading ``emoji`` here instead would have skipped the scan on a - frame that genuinely needed it, and smeared the row. + The fold gives this guarantee, not the icon table. A terminal that cannot draw emoji (the + classic Windows console, refer to :func:`meshterm.ui.termfont.emoji_support`) still + renders the rest of the BMP. A contact with a CJK name is two cells wide there, the same + as everywhere else. If this function reads ``emoji`` instead, it skips the scan on a frame + that must have it, and leaves stray characters in the row. """ if get_platform().font: return False @@ -410,13 +447,14 @@ def _has_wide_glyph(text: str) -> bool: class _WidthExtendedOutput: - """A prompt_toolkit ``Output`` proxy that reports one extra terminal column. + """A prompt_toolkit ``Output`` proxy that reports one more terminal column. - Wraps the real output and forwards everything untouched *except* :meth:`get_size`, which - adds a column. Because the whole render pipeline — prompt_toolkit's differential renderer - and MeshTerm's own frame compositor (via :meth:`TuiSession._size`) — keys off - ``output.get_size()``, this single override makes both use the reclaimed column in - lock-step. See :func:`_reclaim_last_column` for when this is right (and when it isn't). + The proxy wraps the real output, and forwards all calls to it with no change, except + :meth:`get_size`, which adds a column. The full render pipeline uses + ``output.get_size()``: the differential renderer of prompt_toolkit, and the frame + compositor of MeshTerm (through :meth:`TuiSession._size`). Thus this one override makes + the two use the reclaimed column together. Refer to :func:`_reclaim_last_column` for when + this is correct (and when it is not). """ def __init__(self, inner: Any) -> None: @@ -424,28 +462,29 @@ class _WidthExtendedOutput: self._inner = inner def get_size(self) -> Size: - """The wrapped size with one column added, so the last column is claimed.""" + """The wrapped size with one more column, so that the last column is used.""" size = self._inner.get_size() return Size(rows=size.rows, columns=size.columns + 1) def __getattr__(self, name: str) -> Any: - """Forward every other attribute/method straight to the wrapped output.""" + """Forward each other attribute or method directly to the wrapped output.""" return getattr(self._inner, name) def _message_border(message: Text | str) -> str: - """Pick a message dialog's border style from the strongest tone in the text. + """Choose the border style of a message dialog from the strongest tone in the text. - Outcome notes carry their severity as theme spans (``[err]``, ``[warn]``, ``[ok]``), - so the dialog frame can echo it: an error message gets the ``err`` border, a warning - (e.g. "device rebooting") the cautionary one, and anything else — successes included — - the standard accent. A plain string carries no spans and always reads as neutral. + A note about a result has its severity as theme spans (``[err]``, ``[warn]``, ``[ok]``). + Thus the border of the dialog can show the same severity. An error message gets the + ``err`` border. A warning (for example "device rebooting") gets the caution border. All + the other messages, also the success messages, get the standard accent. A plain string + has no spans, and it is always neutral. Args: - message: The dialog's message, styled or plain. + message: The message of the dialog, with styles or plain. Returns: - The Rich style name for the dialog border. + The Rich style name for the border of the dialog. """ if isinstance(message, Text): styles = {str(span.style) for span in message.spans} @@ -457,45 +496,48 @@ def _message_border(message: Text | str) -> str: class Visit: - """One screen's stay on the stack, handed out by :meth:`TuiSession.stay`. + """The stay of one screen on the stack, which :meth:`TuiSession.stay` returns. - Holds nothing but the session and the screen; :meth:`result` arms a fresh future on that - screen and awaits it, leaving the screen exactly where it is. Calling it again is the - next round of the same visit — the loop shape a hub screen wants. + It holds only the session and the screen. :meth:`result` arms a new future on that screen + and awaits it, and the screen stays exactly where it is. A second call is the next round + of the same visit. This is the loop shape that a hub screen must have. """ __slots__ = ("_session", "_screen") def __init__(self, session: TuiSession, screen: Screen) -> None: - """Bind a visit to its session and screen, and arm the screen's first round.""" + """Bind a visit to its session and screen, and arm the first round of the screen.""" self._session = session self._screen = screen self._arm() @property def screen(self) -> Screen: - """The screen being visited (the same object for the whole stay).""" + """The screen of this visit (the same object for the whole stay).""" return self._screen def _arm(self) -> None: - """Give the screen a fresh future to resolve into. + """Give the screen a new future to resolve into. - A visited screen is *always* armed — from the moment it is pushed until the visit - ends — because it is on the stack the whole time and a key can reach it whenever it - is on top. Arming only inside :meth:`result` would leave a gap between rounds in - which :meth:`~meshterm.ui.tui.screen.Screen.resolve` has nowhere to put its value - and the press is silently dropped. + A visited screen is always armed, from the moment when it is pushed until the end of + the visit. The reason is that it is on the stack all the time, and a key press can + get to it each time that it is on top. If only :meth:`result` arms it, there is a + gap between the rounds. In that gap, + :meth:`~meshterm.ui.tui.screen.Screen.resolve` has no place to put its value, and the + key press is lost with no message. """ self._screen.future = asyncio.get_running_loop().create_future() async def result(self) -> Any: """Await one round of the visited screen: its resolved value, or ``CANCEL`` on Esc. - A round already resolved — because the screen was armed while the caller was still - busy with the last one — is returned immediately rather than waited for again. + A round can be already resolved, because the screen was armed while the caller was + still busy with the last round. Such a round is returned immediately, and the method + does not wait for it again. Raises: - PopToMenu: If the pop-all key was pressed, here or while the caller was busy. + PopToMenu: If the user pressed the pop-all key, here or while the caller was + busy. """ self._session._check_unwind() future = self._screen.future @@ -505,87 +547,91 @@ class Visit: try: return self._session._unpack(await future) finally: - self._arm() # the next round is live the moment this one is read + self._arm() # the next round is live from the moment when this round is read class TuiSession: - """A running full-screen TUI: screen stack, frame, input loop, and async prompts.""" + """A running full-screen TUI: the screen stack, the frame, the input loop, and async prompts.""" def __init__( self, header: Callable[[int], RenderableType] | None = None, *, - input: Any = None, # noqa: A002 - matches prompt_toolkit's Application(input=) name + input: Any = None, # noqa: A002 - the same name as Application(input=) in prompt_toolkit output: Any = None, ) -> None: """Create a session. Args: - header: Callable taking the terminal width in columns and returning the - persistent header renderable (banner + live status), re-invoked on - every repaint — the width lets it stretch trailing content (the - activity sparkline) to fill the row exactly. Defaults to a plain title. - input: Optional prompt_toolkit input to drive the app from (tests use a pipe); - defaults to the real terminal. - output: Optional prompt_toolkit output to render to (tests use a dummy); - defaults to the real terminal. + header: A callable that takes the width of the terminal in cells and returns + the persistent header renderable (the banner and the live status). The + session calls it again at each paint. With the width, the header can + stretch the content at its end (the activity sparkline) to fill the row + exactly. The default is a plain title. + input: An optional prompt_toolkit input that drives the app (the tests use a + pipe). The default is the real terminal. + output: An optional prompt_toolkit output to render to (the tests use a dummy). + The default is the real terminal. """ self._stack: list[Screen] = [] self._header = header or (lambda cols: Text("MeshTerm", style="brand")) self._app: Application | None = None self._input = input self._output = output - # The top-most floating "working" overlay (a skeleton card), or None when idle. It is - # deliberately *not* on the screen stack: it hovers above every layer and is shown/ - # hidden by busy_overlay, independent of whatever screens are pushed. + # The top floating "working" overlay (a skeleton card), or None when the app is idle. + # It is not on the screen stack, on purpose: it floats above each layer, and + # busy_overlay shows and hides it, independently of the screens that are pushed. self._overlay: BusyOverlay | None = None - # The busy card currently pushed by :meth:`busy_dialog`, or None. Unlike the overlay - # this one *is* a screen — it has to be, to take the keys the hub underneath would - # otherwise bank — and this holds it so a nested wait rides it instead of stacking. + # The busy card that :meth:`busy_dialog` pushed, or None. Different from the + # overlay, this card is a screen. It must be a screen, so that it takes the key + # presses. If it does not take them, the hub below it keeps them for later. This + # attribute holds the card, so that a nested wait uses the same card instead of a + # second card on the stack. self._busy: BusyDialog | None = None - # What each drawn layer last composed — ``layer -> (text, carries a wide glyph)`` — so - # :meth:`_emit` can tell a frame that actually changed from one the 1 Hz refresh just - # re-rendered identically, and can ask whether anything currently on screen needs the - # full-repaint treatment. Reconciled against the layers actually drawn on every paint - # (see :meth:`_reconcile_layers`). + # The last composition of each drawn layer: ``layer -> (text, carries a wide + # glyph)``. With it, :meth:`_emit` can tell a frame that changed from a frame that + # the 1 Hz paint timer rendered again with no change. It can also find if anything + # on the screen now must have a full paint. At each paint, this dict is reconciled + # against the layers that were drawn (refer to :meth:`_reconcile_layers`). self._layers: dict[str, tuple[str, bool]] = {} - # Armed by the pop-all key (^W) and disarmed by the menu loop once it has caught the - # unwind. While armed, every navigation boundary raises PopToMenu rather than showing - # another screen — see :meth:`request_pop_all`. + # The pop-all key (^W) arms this flag, and the menu loop disarms it after it catches + # the unwind. While the flag is armed, each navigation boundary raises PopToMenu + # instead of showing another screen. Refer to :meth:`request_pop_all`. self._unwinding = False - # The screen the unwind lands on (the main menu), so ^W can no-op when it is already - # the top rather than pointlessly rebuilding it — and what a popup floats over when - # nothing else is pushed (see :meth:`_floated`). ``None`` until the menu declares it. + # The screen at the end of the unwind (the main menu). With it, ^W can do nothing + # when that screen is already the top, instead of a rebuild with no purpose. A + # dialog also floats over it when no other screen is pushed (refer to + # :meth:`_floated`). ``None`` until the menu declares it. self._root: Screen | None = None - # The quit confirm ^Q raises from anywhere (see :meth:`request_quit`), declared by - # the app with :meth:`set_quit_confirm`; and whether it is up right now, which is - # what turns the next ^Q into the leaving itself. + # The quit confirm that ^Q opens from any screen (refer to :meth:`request_quit`). + # The app declares it with :meth:`set_quit_confirm`. Then a flag that tells if the + # confirm is open now. When it is open, the next ^Q quits the app. 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. + # What the app does to stop the start of new work before it possibly must quit + # (refer to :meth:`set_quiesce`). Then the quiesce while it is held. Then the + # one-way flag that :meth:`leave` raises, which tells if the app is on its way out. 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`). + # The Esc of a terminal, held back while the keyboard says that the key is still + # down (where something can tell this, refer to :meth:`set_esc_probe`). self._watched_esc: WatchedEsc | None = None # --- stack --------------------------------------------------------------- @property def top(self) -> Screen | None: - """The active (top-most) screen, or ``None`` when the stack is empty.""" + """The active screen (the top screen), or ``None`` when the stack is empty.""" return self._stack[-1] if self._stack else None def push(self, screen: Screen) -> None: - """Push a screen onto the stack and repaint.""" + """Push a screen onto the stack, and paint the frame again.""" self._stack.append(screen) self.invalidate() def pop(self, screen: Screen | None = None) -> None: - """Pop ``screen`` (or the top) off the stack and repaint.""" + """Pop ``screen`` (or the top screen) off the stack, and paint the frame again.""" if not self._stack: return popped: Screen | None = None @@ -595,37 +641,41 @@ class TuiSession: self._stack.remove(screen) popped = screen self._expose_overlay() - # A floating dialog is drawn as a content-sized box over the screen beneath. If any - # of its cells held a glyph the terminal painted wider than prompt_toolkit tracks - # (an emoji or box-draw fallback the differential renderer can't see), that overhang - # would otherwise survive as stray characters in the dialog's wake. Force the frame - # beneath to rewrite every cell as the dialog is torn down so nothing of it lingers. + # A floating dialog is drawn as a box, sized to its content, over the screen below + # it. A cell of the dialog can hold a glyph that the terminal drew wider than + # prompt_toolkit tracks (an emoji or a box-drawing fallback that the differential + # renderer cannot see). Then the extra part stays as stray characters after the + # dialog closes. Thus, when the dialog closes, force the frame below it to write + # each cell again, so that nothing of the dialog stays. if popped is not None and getattr(popped, "floating", False): self._invalidate_last_frame() self.invalidate() def reset(self) -> None: - """Clear the whole screen stack and repaint. + """Clear the full screen stack, and paint the frame again. - Used to unwind to a blank frame after a cancelled activity — e.g. when a mid-session - device disconnect abandons whatever screens the interrupted work had pushed, before - the reconnect dialog is shown over a clean slate. Screens hold no external resources - (their callers pop them in ``finally``), so dropping any stragglers here is safe. + MeshTerm uses this method to unwind to a blank frame after a cancelled activity. For + example, when the device disconnects during a session, MeshTerm abandons all the + screens that the interrupted work pushed. Then it shows the reconnect dialog over a + clean frame. Screens hold no external resources (their callers pop them in + ``finally``). Thus it is safe to remove the remaining screens here. """ self._stack.clear() - # A reset is its own unwind — the caller has already abandoned whatever was running - # (see :func:`~meshterm.ui.menu._session_loop`), so an armed ^W has nothing left to - # unwind and would otherwise fire into the reconnect flow that replaces it. + # A reset is an unwind itself. The caller has already abandoned all that was running + # (refer to :func:`~meshterm.ui.menu._session_loop`). Thus an armed ^W has nothing + # more to unwind. If it stays armed, it goes off in the reconnect flow that + # replaces the abandoned work. self._unwinding = False self._expose_overlay() self.invalidate() def _expose_overlay(self) -> None: - """Restart the busy overlay's fade whenever a stack change re-exposes it. + """Restart the fade of the busy overlay when a stack change shows it again. - A prompt pushed over an active overlay hides the card; popping back to an empty stack - re-exposes it. Restart the intro then so the black hold and fade-in replay fresh each - time the card is shown, rather than snapping back at full brightness (see + A prompt that is pushed over an active overlay hides the card. A pop back to an empty + stack shows the card again. Then restart the intro, so that the black hold and the + fade-in start again from the beginning each time that the card is shown. Without the + restart, the card comes back immediately at full brightness (refer to :meth:`~meshterm.ui.tui.overlay.BusyOverlay.restart`). """ if self._overlay is not None and not self._stack: @@ -634,13 +684,16 @@ class TuiSession: # --- navigation ---------------------------------------------------------- def set_root(self, screen: Screen | None) -> None: - """Declare ``screen`` the navigation root — where an unwind lands. + """Declare ``screen`` as the navigation root: the screen at the end of an unwind. - The main menu calls this with its own list. Only two things depend on it: ^W is a - no-op while the root is already the top screen (you cannot go back to where you - are), and a popup with nothing under it floats over the root rather than over an - empty frame (:meth:`_floated`). Nothing else in the app needs to know which screen - is the menu. + The main menu calls this method with its own list. Only two things depend on it: + + - ^W does nothing while the root is already the top screen (you cannot go back to + where you are). + - A dialog with nothing below it floats over the root, not over an empty frame + (:meth:`_floated`). + + No other part of the app must know which screen is the menu. Args: screen: The root screen, or ``None`` to forget it. @@ -653,26 +706,28 @@ class TuiSession: return self._root def set_quit_confirm(self, ask: Callable[[], Awaitable[bool]] | None) -> None: - """Declare the question the quit chord asks before it leaves. + """Declare the question that the quit chord asks before the app quits. - The app declares it once, because only the app knows what the question offers — - the main menu's confirm adds *Unpair & quit* over a Bluetooth bond, which needs the - application context the session never holds. ``ask`` floats its dialog and returns - whether to leave; it owns any side effect of the answer (recording an unpair). + The app declares it one time, because only the app knows what the question offers. + Over a Bluetooth bond, the confirm of the main menu adds *Unpair & quit*, and that + choice must have the application context, which the session never holds. ``ask`` + floats its dialog and returns whether to quit. It owns all side effects of the answer + (for example, it stores the record of an unpair). Args: - ask: The confirm, or ``None`` to have the quit chord leave without asking. + ask: The confirm, or ``None`` if the quit chord must quit without a question. """ self._quit_confirm = ask async def confirm_quit(self) -> bool: - """Ask the declared quit confirm, as the main menu's Quit row does. + """Ask the declared quit confirm, as the Quit row of the main menu does. - The same question ^Q asks, and the same dialog: while it is up the chord's next - press leaves outright (see :meth:`request_quit`), whichever door opened it. + It is the same question that ^Q asks, and the same dialog. While the dialog is open, + the next press of the chord quits immediately (refer to :meth:`request_quit`), + whichever way opened the dialog. Returns: - Whether the reader chose to leave — ``True`` with no confirm declared. + Whether the user chose to quit. ``True`` if no confirm is declared. """ self._quit_asking = True return await self._asking_quit() @@ -685,24 +740,25 @@ class TuiSession: self._quit_asking = False def request_quit(self) -> None: - """Answer the quit chord (^Q, and ^C beside it): ask first, leave on the second press. + """Answer the quit chord (^Q, and also ^C): ask first, and quit on the second press. - ^Q sits one key from ^W, the chord that climbs back to the menu, so a slip on the way - to the menu used to close the app — and a running capture or a courier queue with - it. It now floats the quit confirm over whatever is up, from anywhere (issue #22, - option D). The confirm is a detached flow (:meth:`run_detached`): nothing under it - is interrupted, a capture keeps capturing behind the box, and Esc puts the reader - back exactly where they were. + ^Q is one key from ^W, the chord that goes back to the menu. Thus a wrong key press + on the way to the menu once closed the app, and with it a running capture or a + courier queue. Now the chord floats the quit confirm over the current screen, from + any screen (issue #22, option D). The confirm is a detached flow + (:meth:`run_detached`). Nothing below it is interrupted, a capture continues behind + the box, and Esc puts the user back exactly where they were. - While the confirm is up, the chord leaves at once, so the fastest way out is still - two keys and still works when a screen is wedged or a device read hangs — the - second press never waits on the dialog to paint or take a key. The flag is raised - here, synchronously, so two presses arriving in one input batch are still a quit - rather than two dialogs. + While the confirm is open, the chord quits immediately. Thus the fastest way out is + still two key presses, and it still works when a screen is stuck or a device read + does not return. The second press never waits for the dialog to paint or to take a + key. The flag is raised here, synchronously. Thus two presses that arrive in one + input batch are still a quit, not two dialogs. - Leaving is clean either way: :meth:`run` cancels the coroutine driving the app and - waits for its unwind, so the history and chat runs close, the services stop, and the - exit watchdog is armed, the same as quitting from the menu. + In the two cases, the app quits cleanly. :meth:`run` cancels the coroutine that + drives the app and waits for its unwind. Thus the history runs and the chat runs + close, the services stop, and the exit watchdog is armed, the same as a quit from + the menu. """ if self._quit_asking or self._quit_confirm is None: self._exit_app() @@ -716,20 +772,21 @@ class TuiSession: self.run_detached(ask()) def _exit_app(self) -> None: - """Exit the running application, from under whatever flow is driving it.""" + """Exit the running application, whatever flow drives it.""" 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. + """Declare how the app stops the start of new work, for when it possibly must quit soon. - 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. + The session enters the quiesce when a held Esc opens its box, and ends it again if + the user releases the key (refer to :mod:`~meshterm.services.hold_to_quit`). + :meth:`leave` also enters it on the way out, and then keeps it until the process + ends. The quiesce must not take anything apart, because a release of the key must + undo it. The quiesce of the app holds the transmit lock of the device. Thus nothing + new goes on the air, and a scoped channel send in progress closes its window first. + The app declares the quiesce, 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. @@ -737,49 +794,51 @@ 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. + """Declare how to ask whether the Esc key is physically down, for the Esc of a terminal. - 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. + With a probe, an Esc that arrives while its key is still down is held back and + watched as a hold (:class:`~meshterm.ui.tui.holdquit.WatchedEsc`). This gives the + hold-to-quit gesture where a terminal sends the keys, and a terminal never reports + that a key comes up. The app declares the probe, because only the app knows that the + keys are the keys of this machine. They are not the keys of a front end that reads + them itself (the emulator), and not the keys of another machine over SSH. Args: - down: Answers whether Esc is down right now + down: Tells whether the Esc key is down 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.""" + """Whether the app is on its way out (:meth:`leave`). Nothing reverses this state.""" return self._leaving def quiet(self) -> Quiet: - """Engage the app's quiesce (:meth:`set_quiesce`), or return the one already held.""" + """Engage the quiesce of the app (:meth:`set_quiesce`), or return the held quiesce.""" 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.""" + """Release the quiesce, except after :meth:`leave`: then the app 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. + """Quit the app now, without a question, when no transmission is in progress. - 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. + The end of a held Esc and the SIGTERM of the launcher call this method. The decision + is 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 more step first. The quiesce of + the app is engaged, so that a scoped channel send in progress closes its window + before the device goes. :data:`QUIESCE_WAIT_S` limits that wait, because on the + Cardputer Zero, the SIGKILL of the launcher comes three seconds after its SIGTERM, + whatever the app does. - Idempotent and one-way: a SIGTERM landing on a hold that just ran out is the same - exit, not a second one. + The method is idempotent and one-way. A SIGTERM that arrives when a hold has just run + out is the same exit, not a second exit. """ if self._leaving: return @@ -795,42 +854,45 @@ class TuiSession: self.run_detached(go()) def request_pop_all(self) -> bool: - """Arm the unwind to the navigation root (the ^W key). Returns whether it fired. + """Arm the unwind to the navigation root (the ^W key). Return whether it is armed. - Two refusals, both deliberate: + The method refuses in two cases, both on purpose: - * **A modal layer is on top.** A dialog is an unanswered question and a progress or - busy screen is work in flight (:attr:`~meshterm.ui.tui.screen.Screen.modal`); - unwinding past either would discard something the user is in the middle of, so ^W - simply does nothing there and they answer or wait first. - * **The root is already the top.** There is nowhere to go. + * **A modal layer is on top.** A dialog is a question with no answer yet, and a + progress screen or a busy screen is work in progress + (:attr:`~meshterm.ui.tui.screen.Screen.modal`). An unwind past either one + discards something that the user is in the middle of. Thus ^W does nothing there, + and the user must first answer or wait. + * **The root is already the top.** There is no place to go. - Otherwise it sets the unwind flag and resolves **every** frame's future with - :data:`~meshterm.ui.tui.screen.POP_ALL` — top first, down to but never including - the root — which each frame awaiting one turns into + In all other cases, the method sets the unwind flag, and resolves the future of + **each** screen on the stack with :data:`~meshterm.ui.tui.screen.POP_ALL`. It starts + at the top and goes down to the root, but it never includes the root. Each caller + that awaits one of these futures changes the value into :class:`~meshterm.ui.tui.screen.PopToMenu`. - Arming the whole stack, not just the top, is what makes ^W a *stack* verb rather - than a *call chain* one. A screen opened from a key handler cannot be awaited by - its opener — a handler is sync, so the live feed floats the packet viewer with - ``ensure_future(run_screen(...))`` and the chain that would have carried an unwind - ends in a detached task. Sending the sentinel only to the top left that unwind to - die there while the hub below sat on a ``visit.result()`` nothing would resolve: - ^W closed the viewer and stopped, and the still-armed flag fired at whatever the - reader pressed next instead (JP, 2026-08-31). Every frame is on the stack whether - or not anything awaits it, so the stack is the reliable path down. + The method arms the full stack, not only the top. This makes ^W a verb of the stack, + not a verb of the call chain. The code that opens a screen from a key handler cannot + await that screen, because a handler is sync. Thus the live feed floats the packet + viewer with ``ensure_future(run_screen(...))``, and the chain that could carry an + unwind ends in a detached task. When the method sent the sentinel only to the top, + the unwind stopped there, while the hub below waited on a ``visit.result()`` that + nothing could resolve. ^W closed the viewer and stopped. Then the flag, which was + still armed, went off at the next key that the user pressed (JP, 2026-08-31). Each + screen is on the stack, whether something awaits it or not. Thus the stack is the + reliable way down. - The walk stops at a **modal** frame for the reason the top-of-stack refusal above - gives: work in flight is not to be discarded out from under itself. The flag stays - armed, so the unwind still fires at the next navigation boundary past it. Resolving - a frame that is not being awaited is inert — the value is simply never read, and - :meth:`~meshterm.ui.tui.screen.Screen.resolve` no-ops on a screen with no future - at all. + The walk stops at a **modal** screen, for the same reason as the refusal above for + the top of the stack: the method must not discard work in progress from below that + work. The flag stays armed, so the unwind still goes off at the next navigation + boundary after that screen. If the method resolves a screen that nothing awaits, + nothing occurs: nothing reads the value, and + :meth:`~meshterm.ui.tui.screen.Screen.resolve` does nothing on a screen with no + future. - The flag matters independently of the futures: a key can arrive while *no* screen - is awaiting anything (mid device read, under the busy overlay), and then the - unwind is raised by the next navigation boundary instead — see - :meth:`_check_unwind`. + The flag is important independently of the futures. A key press can arrive while no + screen awaits anything (during a device read, below the busy overlay). Then the next + navigation boundary raises the unwind instead (refer to :meth:`_check_unwind`). Returns: ``True`` if the unwind was armed, ``False`` if it was refused. @@ -841,33 +903,33 @@ class TuiSession: self._unwinding = True for screen in reversed(self._stack): if screen is self._root: - break # the root is where the unwind lands; it is not unwound itself + break # the unwind ends at the root, and the root itself is not unwound if screen is not top and screen.modal: break screen.resolve(POP_ALL) return True def unwound(self) -> None: - """Disarm the unwind — called by the menu loop once it has caught :class:`PopToMenu`.""" + """Disarm the unwind. The menu loop calls this after it catches :class:`PopToMenu`.""" self._unwinding = False def _check_unwind(self) -> None: - """Raise :class:`PopToMenu` if an unwind is armed, before showing another screen. + """Raise :class:`PopToMenu` if an unwind is armed, before another screen is shown. - Every navigation boundary calls this on the way *in* as well as reading the result on - the way out, which is what makes ^W work during a device read: the key arms the flag - while no future is armed to carry :data:`POP_ALL`, and the very next screen the flow - tries to open refuses to open and unwinds instead. + Each navigation boundary calls this method on the way in, and also reads the result + on the way out. This makes ^W work during a device read. The key arms the flag while + no future is armed to carry :data:`POP_ALL`. Then the next screen that the flow tries + to open does not open, and it unwinds instead. """ if self._unwinding: raise PopToMenu() @staticmethod def _unpack(result: Any) -> Any: - """Return a screen's result, turning :data:`POP_ALL` into :class:`PopToMenu`. + """Return the result of a screen, and change :data:`POP_ALL` into :class:`PopToMenu`. - The sentinel exists only to travel through an ``asyncio.Future``; no caller in the - app ever sees it, so it is converted at the one boundary that reads a future. + The sentinel exists only to go through an ``asyncio.Future``. No caller in the app + ever sees it. Thus it is changed at the only boundary that reads a future. """ if result is POP_ALL: raise PopToMenu() @@ -875,10 +937,10 @@ class TuiSession: @asynccontextmanager async def stay(self, screen: Screen, *, dialog: bool = False) -> AsyncIterator[Visit]: - """Keep ``screen`` pushed for a whole visit while its sub-screens come and go. + """Keep ``screen`` pushed for a full visit, while the screens above it open and close. - The counterpart to :meth:`run_screen`, and the shape every screen that *owns a loop* - should use:: + This method is the counterpart of :meth:`run_screen`. Each screen that *owns a loop* + must use this shape:: screen = ContactsScreen(...) async with session.stay(screen) as visit: @@ -888,20 +950,20 @@ class TuiSession: return await open_node_detail(ctx, chosen) # nests above the list - One push, one pop, and the object survives the whole visit — so the cursor, the sort, - the scroll offset and any live filter are simply still there when a sub-screen closes, - without a ``default=`` restore that can only ever recover the cursor. Because the - screen never leaves the stack, a dialog raised from inside the loop already has it as - a backdrop, and a full-frame sub-screen pushed above it draws over it (see - :meth:`_base_index`) — the two things callers used to arrange by popping and - re-pushing the same screen by hand. + One push and one pop, and the object stays for the full visit. Thus the highlight, + the sort, the scroll offset, and any live filter are still there when a screen above + it closes. No ``default=`` restore is necessary, and such a restore can only recover + the highlight. The screen never leaves the stack. Thus a dialog that the loop opens + already has the screen as its backdrop, and a full-frame screen that is pushed above + it draws over it (refer to :meth:`_base_index`). Before, callers got these two + results by hand: they popped the same screen and pushed it again. Args: - screen: The screen to keep pushed for the duration of the block. - dialog: The visit is a *popup's* — a stepped dialog turning its pages - (:func:`~meshterm.ui.menus.run_wizard`) rather than a hub — so it must draw - as a box even when it is the only thing on the stack: a blank base goes under - it for the visit, exactly as :meth:`run_dialog` does for a one-shot. + screen: The screen to keep pushed while the block runs. + dialog: The visit belongs to a dialog: a stepped dialog that turns its pages + (:func:`~meshterm.ui.menus.run_wizard`), not a hub. Thus it must draw as a + box, also when it is the only screen on the stack. A blank base goes below it + for the visit, exactly as :meth:`run_dialog` does for a one-time dialog. Yields: A :class:`Visit` whose :meth:`~Visit.result` awaits one round of the screen. @@ -915,40 +977,43 @@ class TuiSession: self.pop(screen) def invalidate(self) -> None: - """Request a repaint if the application is running.""" + """Request a paint if the application is running.""" if self._app is not None: self._app.invalidate() def request_full_repaint(self) -> None: - """Force the next paint to rewrite every cell, then schedule it. + """Force the next paint to write each cell again, then schedule that paint. - prompt_toolkit repaints differentially: cells equal to the previous frame are left - untouched. That is normally what we want, but it also means terminal-side corruption - (a double-width fallback glyph the diff can't see) survives until those exact cells - change. Callers use this when leaving a screen that could have smeared the terminal — - the map — so the screen drawn underneath starts from a clean slate. + prompt_toolkit paints differentially: it does not touch the cells that are equal to + the cells of the last frame. Usually we want this. But then damage on the terminal + side (a double-width fallback glyph that the diff cannot see) stays until those exact + cells change. Callers use this method when the user leaves a screen that can leave + stray characters on the terminal (the map). Thus the screen that is drawn below it + starts from a clean frame. """ self._invalidate_last_frame() self.invalidate() def _invalidate_last_frame(self) -> None: - """Drop prompt_toolkit's cached last frame so the next paint rewrites every cell. + """Remove the cached last frame of prompt_toolkit, so that the next paint writes all cells. - Touches a prompt_toolkit internal, so it fails soft if the attribute ever moves. + This method uses an internal of prompt_toolkit. Thus it fails softly if the attribute + moves. """ renderer = getattr(self._app, "renderer", None) if renderer is not None and hasattr(renderer, "_last_screen"): renderer._last_screen = None def _scrub_columns(self, start: int, stop: int) -> None: - """Force prompt_toolkit to repaint terminal columns ``[start, stop)`` on the next diff. + """Force prompt_toolkit to paint the terminal columns ``[start, stop)`` at the next diff. - Overwrites those cells in pt's remembered last frame with a sentinel that can't equal - any real content, so the differential renderer treats them as changed and redraws - them — scrubbing a double-width fallback glyph that smeared over a *static* edge (the - map's panel border, a floating dialog's), without the whole-frame flicker of dropping - the entire cached frame. Touches a pt internal, so it fails soft if the structure ever - moves. + This method writes a sentinel over those cells in the last frame that pt remembers. + The sentinel can never be equal to real content. Thus the differential renderer + thinks that the cells changed, and draws them again. This removes a double-width + fallback glyph that left stray characters on a static edge (the panel border of the + map, or the border of a floating dialog). It does this without the flicker of the + full frame that occurs when the full cached frame is removed. This method uses an + internal of pt, so it fails softly if the structure moves. """ renderer = getattr(self._app, "renderer", None) last = getattr(renderer, "_last_screen", None) @@ -958,38 +1023,40 @@ class TuiSession: from prompt_toolkit.layout.screen import Char buffer = last.data_buffer - sentinel = Char("￿") # a non-character; never equals real cell content + sentinel = Char("￿") # a non-character, never equal to real cell content for x in range(max(0, start), stop): for row in list(buffer.keys()): buffer[row][x] = sentinel - except Exception: # noqa: BLE001 - a cosmetic scrub must never break rendering + except Exception: # noqa: BLE001 - a cosmetic scrub must never stop the render pass def _scrub_right_columns(self, count: int) -> None: - """Scrub the terminal's rightmost ``count`` columns — a full-frame panel's edge.""" + """Scrub the last ``count`` columns of the terminal: the edge of a full-frame panel.""" cols, _ = self._size() self._scrub_columns(cols - count, cols) def _scrub_rows(self, rows: Sequence[int]) -> bool: - r"""Force prompt_toolkit to rewrite these whole terminal rows on the next diff. + r"""Force prompt_toolkit to write these full terminal rows again at the next diff. - The row-wise twin of :meth:`_scrub_columns`, and the cheap form of the wide-glyph - repaint (:meth:`_emit`): every column of each listed row is sentinelled, so pt finds - the entire row changed and writes it from column 0 in one contiguous run — which is - the whole requirement for a row whose glyph the terminal draws narrower than pt - reserved. Rows that did not change are not touched at all, and nothing is erased. + This method is the row version of :meth:`_scrub_columns`, and the cheap form of the + wide-glyph paint (:meth:`_emit`). It puts the sentinel in each column of each listed + row. Thus pt finds that the full row changed, and writes it from column 0 in one + continuous sequence. That is all that is necessary for a row with a glyph that the + terminal draws narrower than the cells that pt reserved. The method does not touch + the rows that did not change, and it erases nothing. - Row-scoped is sound because pt's cursor is *relative*: stepping down a row emits - ``\\r\\n``, which returns the terminal to a true column 0 whatever the drift on the row - above, so a mis-measured row can never throw off the rows below it. The drift only - matters *within* a row, and a row rewritten whole never jumps inside itself. + A scrub by row is correct, because the cursor of pt is relative. A step down one row + writes ``\\r\\n``, which puts the terminal back to a real column 0, whatever the + drift on the row above. Thus a row with an incorrect measurement can never move the + rows below it. The drift is important only in a row, and a row that is written again + in full never jumps inside itself. Args: - rows: The terminal row indices to mark changed. + rows: The indices of the terminal rows to mark as changed. Returns: - Whether the scrub was applied — ``False`` when pt has no remembered frame to - scrub (it is already going to repaint everything) or the internals moved. + Whether the scrub was done. ``False`` when pt has no remembered frame to scrub + (it will paint all the frame again), or when the internals moved. """ renderer = getattr(self._app, "renderer", None) last = getattr(renderer, "_last_screen", None) @@ -1000,48 +1067,48 @@ class TuiSession: from prompt_toolkit.layout.screen import Char buffer = last.data_buffer - sentinel = Char("￿") # a non-character; never equals real cell content + sentinel = Char("￿") # a non-character, never equal to real cell content for y in rows: row = buffer[y] for x in range(cols): row[x] = sentinel - except Exception: # noqa: BLE001 - a cosmetic scrub must never break rendering + except Exception: # noqa: BLE001 - a cosmetic scrub must never stop the render return False return True # --- async prompt helpers ------------------------------------------------ def run_detached(self, work: Any) -> asyncio.Future: - """Run ``work`` — a flow that opens a screen — off a key handler, unawaited. + """Run ``work`` (a flow that opens a screen) from a key handler, without an await. - A screen's ``handle`` is synchronous, so a key that opens something over the - current screen (the live feed's packet viewer, the chat's delivery paths, the - trace screen's path flows) can only *start* the flow, as a task. That task sits - outside the navigation call chain: nothing awaits it, so a - :class:`~meshterm.ui.tui.screen.PopToMenu` raised inside it has nowhere to - propagate and lands in the event loop's exception handler as an unretrieved - error. + The ``handle`` method of a screen is synchronous. Thus a key that opens something + over the current screen can only start the flow, as a task. Examples are the packet + viewer of the live feed, the delivery paths of the chat, and the path flows of the + trace screen. That task is outside the navigation call chain: nothing awaits it. + Thus a :class:`~meshterm.ui.tui.screen.PopToMenu` that is raised in the task has no + place to propagate to. It goes to the exception handler of the event loop as an + unretrieved error. - Absorbing it here is safe because the unwind never travelled this way to begin - with: ^W arms every frame on the stack (see :meth:`request_pop_all`), so the - screen that opened this one carries the unwind out on its own awaited frame. What - this catch drops is a duplicate of an unwind already in flight — and the flow's - own ``finally`` blocks still run on the way through it. + It is safe to absorb the exception here, because the unwind never went this way. + ^W arms each screen on the stack (refer to :meth:`request_pop_all`). Thus the screen + that opened this screen takes the unwind out, because its own caller awaits it. This + catch removes only a copy of an unwind that is already in progress. Also, the + ``finally`` blocks of the flow still run when the exception goes through them. Args: work: The coroutine to run, usually a :meth:`run_screen` call. Returns: - The task, for a caller that wants to cancel or await it. The app's own - callers are key handlers and ignore it; the screen they opened is on the - stack, which is how everything else finds it. + The task, for a caller that must cancel it or await it. The callers in the app + are key handlers, and they ignore it. The screen that they opened is on the + stack, and all other code finds the screen there. """ async def guarded() -> None: try: await work except PopToMenu: - pass # the stack carries the unwind; this task was never on its path + pass # the stack carries the unwind, and this task was never on its way return asyncio.ensure_future(guarded()) @@ -1052,11 +1119,11 @@ class TuiSession: screen: The screen to run. Returns: - The screen's resolved value, or :data:`~meshterm.ui.tui.screen.CANCEL`. + The resolved value of the screen, or :data:`~meshterm.ui.tui.screen.CANCEL`. Raises: - PopToMenu: If the pop-all key was pressed — on this screen, or while the caller - was busy and had nothing pushed at all. + PopToMenu: If the user pressed the pop-all key: on this screen, or while the + caller was busy and had nothing pushed. """ self._check_unwind() loop = asyncio.get_running_loop() @@ -1080,17 +1147,17 @@ class TuiSession: delete_hint: str = "", floating: bool = False, ) -> Any: - """Show a select screen; return the chosen value or ``None`` if cancelled. + """Show a select screen. Return the chosen value, or ``None`` if the user cancelled. - ``prompt`` draws an instruction inside the box above the list; ``filterable`` and - ``footer_hint`` are forwarded for short, fixed lists (a yes-or-no style choice) that - want no type-to-filter and a tailored hint. ``delete_hint`` (with rows marked - :attr:`~meshterm.ui.tui.select.Choice.deletable`) surfaces the Delete key's atom - while the highlight sits on such a row; Delete then resolves a - :class:`~meshterm.ui.tui.select.DeleteRequest` the caller unwraps. ``floating`` - is :meth:`text`'s: the list is a *question* asked on the way into a tool (which - node to administer) rather than the tool's own page, so it must draw as a box - even when it is the only frame on the stack — see :meth:`_floated`. + ``prompt`` draws an instruction in the box, above the list. ``filterable`` and + ``footer_hint`` go to the screen for short, fixed lists (a choice of the yes-or-no + type) that must have no type-to-filter and a special hint. ``delete_hint`` (with rows + marked :attr:`~meshterm.ui.tui.select.Choice.deletable`) shows the atom of the Delete + key while the highlight is on such a row. Then Delete resolves a + :class:`~meshterm.ui.tui.select.DeleteRequest`, which the caller unwraps. + ``floating`` is the same as in :meth:`text`: the list is a question on the way into a + tool (which node to administer), not the page of the tool. Thus it must draw as a + box, also when it is the only screen on the stack. Refer to :meth:`_floated`. """ kwargs: dict[str, Any] = dict( prompt=prompt, @@ -1118,36 +1185,36 @@ class TuiSession: live: Callable[[Callable[[list], None]], Awaitable[None]] | None = None, hscroll: bool | None = None, ) -> Any: - """Show a chromeless select splash (banner above a content-sized box). + """Show a chromeless select splash (a banner above a box sized to its content). - Like :meth:`select`, but drawn without the header/footer status bars and centered - under ``banner`` — the startup device picker's presentation. Esc's verb here is - ``bye``, the app's one send-off: this splash is the door, and the reader leaving it - has not started anything to quit out of. Type-to-filter is off: - the device list is short and fixed, so stray keys never narrow it. An optional - ``footnote`` (e.g. a copyright notice) sits muted below the box. When any row opts - into removal (a :attr:`~meshterm.ui.tui.select.Choice.deletable` row), a "Del remove" - atom joins the footer — but only while the highlight is actually on such a row, so the - removal key advertises itself exactly where it acts (see - :attr:`~meshterm.ui.tui.select.SelectScreen.footer_hint`). + The splash is like :meth:`select`, but it has no header or footer status bars, and + it is centred below ``banner``. This is the presentation of the startup device + picker. Here the verb of Esc is ``bye``, the only farewell of the app. This splash is + the door, and a user who leaves it has started nothing to quit. Type-to-filter is + off: the device list is short and fixed, so stray key presses never make it shorter. + An optional ``footnote`` (for example a copyright notice) is muted, below the box. + When a row accepts removal (a :attr:`~meshterm.ui.tui.select.Choice.deletable` row), + a "Del remove" atom is added to the footer. But the atom shows only while the + highlight is on such a row, so the removal key shows itself exactly where it acts + (refer to :attr:`~meshterm.ui.tui.select.SelectScreen.footer_hint`). - ``live`` is work to do *while* the list is up — the device picker's rescan, which - keeps looking for a companion the whole time the splash is open. It is handed one - function, ``redraw(items)``, which swaps the rows under the reader and repaints; - the screen itself stays in here, since a caller holding one could not repaint it - anyway (``invalidate`` is the session's, not the screen's). It runs as a task for - exactly as long as the screen does and is cancelled when the screen resolves, so - nothing outlives the list it was redrawing and no repaint lands on a dialog that - has since opened over it. + ``live`` is work to do while the list is visible: the rescan of the device picker, + which looks for a companion all the time that the splash is open. It gets one + function, ``redraw(items)``, which replaces the rows while the user looks at them, + and paints the frame again. The screen itself stays in this method, because a caller + that held it could not paint it again (``invalidate`` belongs to the session, not to + the screen). The work runs as a task for exactly as long as the screen runs, and it + is cancelled when the screen resolves. Thus nothing continues after the list that it + drew, and no paint goes onto a dialog that opened over the list later. - ``hscroll`` overrules what the rows imply: a splash whose rows pin no head block - still wants ←→ to read a long row to its end, and a row that pins nothing cannot - ask for that on its own (see :class:`~meshterm.ui.tui.select.SelectScreen`). + ``hscroll`` overrules what the rows imply. A splash whose rows pin no head block + still must let ←→ read a long row to its end, and a row that pins nothing cannot ask + for that itself (refer to :class:`~meshterm.ui.tui.select.SelectScreen`). - ``keys`` hands the list bare-key shortcuts — which a splash can afford precisely - because it does not filter, so every letter is free (see :class:`SelectScreen`) — - and ``key_hint`` says what they are called on the row the highlight is standing on, - so they advertise themselves exactly where they act, as ``Del remove`` does. + ``keys`` gives bare-key shortcuts to the list. A splash can have them because it does + not filter, so each letter is free (refer to :class:`SelectScreen`). ``key_hint`` + gives their names on the row where the highlight is. Thus they show themselves + exactly where they act, as ``Del remove`` does. """ delete_hint = ( "Del remove" if any(isinstance(it, Choice) and it.deletable for it in items) else "" @@ -1166,16 +1233,16 @@ class TuiSession: screen.chrome = False screen.banner = banner screen.footnote = footnote - # The splash's border is its only hint line and it is narrow (47 cells on the - # PicoCalc), so when the sentence outgrows the box it gives up the scroll atom - # first — ←→ are already named by the move atom in front of it — and then the - # *hide* key. Between the two shortcuts the one that survives is the way back: - # ⇧H only appears at all once something is hidden, which is exactly the state where - # a reader needs to be told how to undo it, and by then they have already found h. + # The border of the splash is its only hint line, and it is narrow (47 cells on the + # PicoCalc). Thus, when the sentence becomes wider than the box, it first removes + # the scroll atom (the move atom in front of it already names ←→). Then it removes + # the hide key. Of the two shortcuts, the one that stays is the way back. ⇧H shows + # only after something is hidden, and that is exactly the state where the user must + # learn how to undo it. At that time, the user has already found h. screen.spare_hint_atoms = ("←→ scroll", "h hide") def redraw(new_items: list) -> None: - """Swap the rows and repaint. The reader keeps their place, by value.""" + """Replace the rows and paint again. The user keeps their place, by value.""" screen.replace_items(new_items) self.invalidate() @@ -1204,34 +1271,36 @@ class TuiSession: ) -> bool: """Confirm a destructive splash action with a Cancel/verb dialog (chromeless). - The startup-splash sibling of :meth:`button_dialog`: the same platform-dialog layout - — the safe *Cancel* on the left and the committing verb on the right and default, so - Enter commits and Esc backs out. Themed as data loss (the reserved red prompt and - border), since it only ever gates forgetting a remembered device — the splash sibling - of a ``destructive`` :meth:`button_dialog`. + This is the startup-splash version of :meth:`button_dialog`, with the same + platform-dialog layout. The safe *Cancel* is on the left, and the committing verb is + on the right and is the default. Thus Enter commits, and Esc backs out. The theme is + the theme of data loss (the reserved red prompt and border), because this dialog only + asks before MeshTerm forgets a remembered device. It is the splash version of a + ``destructive`` :meth:`button_dialog`. - When ``backdrop_items`` is given, the device list they describe is redrawn as the - chromeless base and the red confirm *floats over it* as a centred box (a modal popup - over the pushed backdrop, the way every other dialog behaves) — so removing a device - reads as a popup on top of the picker rather than a splash that replaces it. The - ``backdrop_default`` row is pre-highlighted so the confirm reads as being about it. - Without ``backdrop_items`` the confirm draws as its own chromeless splash under - ``banner`` (the fallback for a caller with no list to float over). + When ``backdrop_items`` is given, the device list that they describe is drawn again + as the chromeless base. The red confirm floats over it as a centred box (a modal + dialog over the pushed backdrop, as each other dialog does). Thus the removal of a + device looks like a dialog on top of the picker, not a splash that replaces it. The + ``backdrop_default`` row is highlighted first, so that the user sees that the confirm + is about it. Without ``backdrop_items``, the confirm draws as its own chromeless + splash below ``banner`` (the fallback for a caller with no list to float over). Args: - prompt: The question shown above the buttons. - title: Short heading shown in the dialog's border. - confirm_label: Label for the committing button (e.g. ``"Remove"``). - banner: Wordmark rows drawn above the box (as on the other startup splashes). - footnote: Muted line drawn below the box. - backdrop_items: The picker's rows to redraw behind the confirm; ``None`` falls - back to a standalone chromeless confirm splash. - backdrop_default: The row value to pre-highlight in the backdrop list. - backdrop_title: Heading for the backdrop list (the picker's own title). - footer_hint: Footer key hint. + prompt: The question above the buttons. + title: The short heading in the border of the dialog. + confirm_label: The label of the committing button (for example ``"Remove"``). + banner: The wordmark rows above the box (as on the other startup splashes). + footnote: The muted line below the box. + backdrop_items: The rows of the picker to draw again behind the confirm. + ``None`` gives a standalone chromeless confirm splash instead. + backdrop_default: The row value to highlight in the backdrop list. + backdrop_title: The heading of the backdrop list (the title of the picker). + footer_hint: The key hint of the footer. Returns: - ``True`` only when the user chose the committing button; ``False`` on Cancel/Esc. + ``True`` only when the user chose the committing button. ``False`` on Cancel or + Esc. """ dialog = ButtonDialog( prompt, @@ -1248,9 +1317,10 @@ class TuiSession: dialog.banner = banner dialog.footnote = footnote return await self.run_screen(dialog) is True - # Keep the picker on screen as the chromeless base and float the red confirm over it, - # so the removal confirm sits *on top of* the device list it acts on. The backdrop is - # a static redraw of the same rows (it never takes a key — the dialog above owns input). + # Keep the picker on the screen as the chromeless base, and float the red confirm over + # it. Thus the removal confirm is on top of the device list that it acts on. The + # backdrop is a static copy of the same rows. It never takes a key, because the dialog + # above it owns the input. backdrop = SelectScreen( backdrop_title, backdrop_items, @@ -1277,7 +1347,7 @@ class TuiSession: footnote: str | None = None, footer_hint: str = "Enter continue", ) -> None: - """Show a chromeless message splash (banner above a boxed renderable) until dismissed.""" + """Show a chromeless message splash (a banner over a boxed renderable) until it closes.""" screen = ScrollScreen(renderable, title=title, footer_hint=footer_hint) screen.chrome = False screen.banner = banner @@ -1294,26 +1364,28 @@ class TuiSession: footnote: str | None = None, interval: float | None = None, ) -> Any: - """Await ``coro`` while showing an animated spinner on the chromeless splash. + """Await ``coro``, and show an animated spinner on the chromeless splash while it runs. - Keeps the startup splash on screen (same wordmark and box) and swaps its contents for - an ASCII spinner beside ``message`` while the awaited task runs, then returns the - task's result. A background timer advances the spinner and repaints every - ``interval`` seconds; it is always cancelled and the splash popped before returning. + The method keeps the startup splash on the screen (the same wordmark and box). While + the awaited task runs, the method replaces the content of the splash with an ASCII + spinner next to ``message``. Then it returns the result of the task. A background + timer moves the spinner forward and paints the frame again every ``interval`` + seconds. Before the method returns, it always cancels the timer and pops the splash. Args: - message: The line shown beside the spinner (e.g. "Talking to Wio on COM5…"). - coro: The awaitable to run (e.g. a device smoke test). - title: Optional panel title for the splash box. - banner: Wordmark rows drawn above the box (as on the other startup splashes). - footnote: Muted line drawn below the box. - interval: Seconds between spinner frames. Defaults to the platform's cadence, - which is the point on a slow console: a repaint there costs more than this - loop used to wait between them, so a hardcoded rate spent the whole event - loop redrawing the spinner and starved the very work it was reporting on. + message: The line next to the spinner (for example "Talking to Wio on COM5…"). + coro: The awaitable to run (for example a device smoke test). + title: An optional panel title for the splash box. + banner: The wordmark rows above the box (as on the other startup splashes). + footnote: The muted line below the box. + interval: The seconds between two animation steps of the spinner. The default is + the cadence of the platform, and on a slow console that is the purpose. + There, a paint costs more time than this loop waited between two paints + before. Thus a hardcoded rate used all the event loop to draw the spinner, + and the work that the spinner reported on did not get time to run. Returns: - Whatever ``coro`` resolves to. + The value that ``coro`` resolves to. """ tick = spinner_interval() if interval is None else interval screen = BusyScreen(message, title=title) @@ -1333,14 +1405,15 @@ class TuiSession: return await coro finally: ticker.cancel() - # Await the cancelled ticker so it is never garbage-collected while still - # pending: that surfaces as a screen-corrupting "Task was destroyed but it is - # pending!" loop error. The spinner is cosmetic, so any glitch is swallowed. + # Await the cancelled ticker, so that it is never garbage-collected while it is + # still pending. If it is, the loop shows the error "Task was destroyed but it is + # pending!", which damages the screen. The spinner is cosmetic, so any problem + # is ignored. try: await ticker except asyncio.CancelledError: pass - except Exception: # noqa: BLE001 - a spinner hiccup must never break startup + except Exception: # noqa: BLE001 - a small spinner problem must never stop the startup pass self.pop(screen) @@ -1353,18 +1426,19 @@ class TuiSession: banner: Any | None = None, footnote: str | None = None, ) -> str | None: - """Ask for a companion's Bluetooth PIN on the chromeless startup splash. + """Ask for the Bluetooth PIN of a companion on the chromeless startup splash. - Drawn like :meth:`notify_startup` / :meth:`select_startup` — a bordered box centered - under ``banner`` with no status bars — so the PIN request is visually part of the same - device-selection flow. ``error`` is shown in the box on a re-ask after a rejected code. + It is drawn like :meth:`notify_startup` / :meth:`select_startup`: a box with a + border, centred below ``banner``, with no status bars. Thus the PIN request looks like + a part of the same device-selection flow. When the method asks again after a rejected + code, ``error`` shows in the box. Args: - device_name: The companion's display name, shown in the prompt. - error: A rejected-PIN message to display (empty on the first ask). - help_text: A muted hint under the field. - banner: Wordmark rows drawn above the box (as on the other startup splashes). - footnote: Muted line drawn below the box. + device_name: The display name of the companion, shown in the prompt. + error: A message about a rejected PIN, to show (empty at the first request). + help_text: A muted hint below the field. + banner: The wordmark rows above the box (as on the other startup splashes). + footnote: The muted line below the box. Returns: The entered PIN, or ``None`` if the user pressed Esc to cancel. @@ -1387,21 +1461,22 @@ class TuiSession: banner: Any | None = None, footnote: str | None = None, ) -> str | None: - """Ask for a line of text on the chromeless startup splash (e.g. a TCP host:port). + """Ask for a line of text on the chromeless startup splash (for example a TCP host:port). - Drawn like :meth:`prompt_pin_startup` — a bordered :class:`TextScreen` centered under - ``banner`` with no status bars — so entering a network address reads as part of the - same device-selection flow. ``validate`` blocks submission on a bad value the same way - the in-menu text prompt does. + It is drawn like :meth:`prompt_pin_startup`: a :class:`TextScreen` with a border, + centred below ``banner``, with no status bars. Thus the entry of a network address + looks like a part of the same device-selection flow. ``validate`` blocks the + submission of a bad value, the same as the text prompt in the menu. Args: - title: Short heading shown in the dialog's border. - prompt: The instruction shown inside the box, above the field. - default: Prefilled text. - validate: Optional validator run on Enter; a returned string blocks submission. - help_text: A muted hint under the field. - banner: Wordmark rows drawn above the box (as on the other startup splashes). - footnote: Muted line drawn below the box. + title: The short heading in the border of the dialog. + prompt: The instruction in the box, above the field. + default: The text that is in the field at the start. + validate: An optional validator that runs on Enter. If it returns a string, the + submission is blocked. + help_text: A muted hint below the field. + banner: The wordmark rows above the box (as on the other startup splashes). + footnote: The muted line below the box. Returns: The entered text, or ``None`` if the user pressed Esc to cancel. @@ -1416,11 +1491,11 @@ class TuiSession: return None if result is CANCEL else result async def reorder(self, title: str, labels: list[str]) -> list[int]: - """Show a drag-with-arrows reorder screen; return the final order of row indices. + """Show a reorder screen (arrows move rows). Return the final order of the row indices. - The Apply action row below the list commits the rearrangement; Back (or Esc) - cancels, which comes back as the original (identity) order so the caller - treats it as "no change". + The Apply action row below the list commits the new order. Back (or Esc) cancels. A + cancel returns the original (identity) order, so that the caller sees it as "no + change". """ result = await self.run_screen(ReorderScreen(title, labels)) return list(range(len(labels))) if result is CANCEL else result @@ -1437,16 +1512,17 @@ class TuiSession: byte_limit: int | None = None, floating: bool = False, ) -> str | None: - """Show a text prompt; return the string or ``None`` if cancelled. + """Show a text prompt. Return the string, or ``None`` if the user cancelled. - ``floating`` guarantees the prompt draws as a centered popup even on an empty stack - — a question asked on the way in (a remote-admin password, a typed trace target) - rather than a tool's own page. It then floats over the menu the way - :meth:`button_dialog` and :meth:`typed_confirm` do (see :meth:`run_dialog`); with - a screen already beneath it there is no difference. + ``floating`` makes sure that the prompt draws as a centred dialog, also on an empty + stack. Use it for a question on the way into a tool (a remote-admin password, a typed + trace target), not for the page of a tool. The prompt then floats over the menu, as + :meth:`button_dialog` and :meth:`typed_confirm` do (refer to :meth:`run_dialog`). + When a screen is already below it, there is no difference. - ``byte_limit`` puts the shared UTF-8 byte gauge on the field and blocks submission - past it — for a field that feeds a size-capped packet (see :class:`TextScreen`). + ``byte_limit`` puts the shared UTF-8 byte gauge on the field, and blocks a submission + that is longer than the limit. Use it for a field that goes into a packet with a + maximum size (refer to :class:`TextScreen`). """ screen = TextScreen( title, @@ -1462,7 +1538,7 @@ class TuiSession: return None if result is CANCEL else result async def confirm(self, title: str, *, default: bool = True) -> bool | None: - """Show a yes/no prompt; return the bool or ``None`` if cancelled.""" + """Show a yes/no prompt. Return the bool, or ``None`` if the user cancelled.""" result = await self.run_screen(ConfirmScreen(title, default=default)) return None if result is CANCEL else result @@ -1481,13 +1557,14 @@ class TuiSession: border_style: str = "accent", lane: Sequence[fkeys.FPair | None] | None = None, ) -> Any: - """Show a centered button dialog; return the chosen value or ``None`` if cancelled. + """Show a centred button dialog. Return the chosen value, or ``None`` if cancelled. - A reusable prompt-above-buttons dialog (see :class:`~meshterm.ui.tui.prompt. - ButtonDialog`): the colours, prompt, buttons, and single-key shortcuts are all - parametrised, so a caller can theme it (e.g. a destructive action in red) or wire - instant y/n keys. ``keys`` maps a shortcut character to the value it commits. - The prompt may be a pre-styled :class:`Text` (see the ButtonDialog docs). + A reusable dialog with a prompt above buttons (refer to + :class:`~meshterm.ui.tui.prompt.ButtonDialog`). The colours, the prompt, the + buttons, and the single-key shortcuts are all parameters. Thus a caller can give it + a theme (for example, red for a destructive action), or connect immediate y/n keys. + ``keys`` maps a shortcut character to the value that it commits. The prompt can be a + :class:`Text` that already has styles (refer to the ButtonDialog docs). """ screen = ButtonDialog( prompt, @@ -1507,17 +1584,17 @@ class TuiSession: @asynccontextmanager async def _floated(self) -> AsyncIterator[None]: - """Guarantee that whatever is pushed inside the block draws as a box, not full-frame. + """Make sure that all that is pushed in the block draws as a box, not as a full frame. - On an empty stack a lone floating screen is drawn *as* the background — framed - chrome filling the terminal, no popup (see :meth:`_base_index`) — so a base is - pushed first and popped once the block ends. The base is the **root** (the main - menu, popped while a tool runs but still the screen the reader chose the tool - from), so a question asked on the way into a tool floats over the menu it came - from: a dialog is smaller than the frame, and what shows around it should be the - page behind it, never an empty frame. A blank base is the fallback for a session - with no root declared. With a background already present there is nothing to do: - the dialog simply floats over it. + On an empty stack, a lone floating screen is drawn as the background: the full + chrome, which fills the terminal, and no dialog (refer to :meth:`_base_index`). Thus + a base is pushed first, and popped when the block ends. The base is the **root**: + the main menu. The menu is popped while a tool runs, but it is still the screen where + the user chose the tool. Thus a question on the way into a tool floats over the menu + that it came from. A dialog is smaller than the frame, and the area around it must + show the page behind it, never an empty frame. A blank base is the fallback for a + session with no declared root. When a background is already there, there is nothing + to do: the dialog floats over it. """ backdrop: Screen | None = None if not self._stack: @@ -1530,16 +1607,16 @@ class TuiSession: self.pop(backdrop) async def run_dialog(self, screen: Screen) -> Any: - """Run a floating dialog as a one-shot, drawn as a centered box (see :meth:`_floated`).""" + """Run a floating dialog one time, drawn as a centred box (refer to :meth:`_floated`).""" async with self._floated(): return await self.run_screen(screen) async def typed_confirm(self, warning: str, word: str, *, title: str = "Are you sure?") -> bool: - """Gate a destructive action behind typing ``word``; return whether it was typed. + """Ask the user to type ``word`` before a destructive action. Return whether it was typed. - Shows the error-themed :class:`~meshterm.ui.tui.prompt.TypedConfirmDialog` and - collapses its result to a plain bool: ``True`` only when the user typed the word, - ``False`` when they backed out with Esc. + The method shows the :class:`~meshterm.ui.tui.prompt.TypedConfirmDialog` with the + error theme, and changes its result into a plain bool: ``True`` only when the user + typed the word, ``False`` when the user backed out with Esc. """ result = await self.run_dialog(TypedConfirmDialog(warning, word, title=title)) return result is True @@ -1553,27 +1630,29 @@ class TuiSession: default: str = "", validate: Validator | None = None, ) -> str | None: - """Show a free-text prompt with suggestions; return text or ``None`` if cancelled.""" + """Show a free-text prompt with suggestions. Return the text, or ``None`` if cancelled.""" result = await self.run_dialog( AutocompleteScreen(title, choices, prompt=prompt, default=default, validate=validate) ) return None if result is CANCEL else result async def message_dialog(self, message: Text | str, *, title: str = "") -> None: - """Show a short outcome in a centered popup with a single OK button. + """Show a short result in a centred dialog with one OK button. - The lightweight acknowledgement counterpart of :meth:`scroll`: a one-line result - ("✓ flood advertisement sent") doesn't warrant a full result window, so it floats - as a small dialog over whatever screen is beneath — Enter (OK) or Esc dismisses - it. The border takes the message's strongest tone (see :func:`_message_border`), - so an error pops red while a success stays in the standard accent. It delegates to - :meth:`button_dialog`, which floats it over a blank base when the stack is empty (a - tool run straight from the menu, which is popped while the tool executes). + This is the light acknowledgement counterpart of :meth:`scroll`. A one-line result + ("✓ flood advertisement sent") is too small for a full result screen. Thus it floats + as a small dialog over the screen below it. Enter (OK) or Esc closes it. The border + takes the strongest tone of the message (refer to :func:`_message_border`). Thus an + error shows in red, and a success stays in the standard accent. The method calls + :meth:`button_dialog`, which floats the dialog over a blank base when the stack is + empty (a tool that runs directly from the menu, which is popped while the tool + runs). Args: - message: The outcome to show — a pre-styled :class:`Text` (note markup - survives into the dialog) or a plain string. - title: Optional dialog heading (typically the tool or action name). + message: The result to show: a :class:`Text` that already has styles (the note + markup stays in the dialog), or a plain string. + title: An optional dialog heading (usually the name of the tool or of the + action). """ await self.button_dialog( message, @@ -1586,7 +1665,7 @@ class TuiSession: async def scroll( self, renderable: RenderableType, *, title: str = "", footer_hint: str = "" ) -> None: - """Show a dismissable, scrollable view of a renderable (a result window).""" + """Show a renderable on a scrollable screen that the user can close (a result screen).""" screen = ScrollScreen( renderable, title=title, @@ -1595,7 +1674,7 @@ class TuiSession: await self.run_screen(screen) def progress(self, title: str = "Working") -> TuiProgress: - """Return a progress context manager backed by a pushed :class:`ProgressScreen`.""" + """Return a progress context manager that uses a pushed :class:`ProgressScreen`.""" return TuiProgress(self, title) @asynccontextmanager @@ -1606,51 +1685,53 @@ class TuiSession: title: str = "", interval: float | None = None, ) -> AsyncIterator[BusyOverlay]: - """Float a skeleton card on top of everything for the duration of a block. + """Float a skeleton card on top of all other content while a block runs. - Wrap a slow, screen-affecting operation — most usefully a device menu navigation, - which can otherwise sit on a blank frame while the companion answers — in:: + Put a slow operation that affects the screen in this block. The most useful case is + a device menu navigation, which can otherwise stay on a blank frame while the + companion answers:: async with session.busy_overlay("reading…", title="Nodes"): await slow_work() - The card stands in for the screen being fetched: a title and the one-cell working - chip beside the caption. A background timer advances the chip, - fades the card in, and repaints while the block runs; it is always cleared and the - timer cancelled on exit, even on error. The card fades in from black rather than - popping in (see :attr:`BusyOverlay.brightness`), so a quick operation only paints a - near-black card and it never appears suddenly. It is drawn only in the gaps between - screens (see :meth:`_overlay_visible`), so it announces the wait without covering a - prompt the user is interacting with. + The card takes the place of the screen whose data MeshTerm reads: a title, and the + one-cell working chip next to the caption. While the block runs, a background timer + moves the chip forward, fades the card in, and paints the frame again. At the exit, + the card is always cleared and the timer cancelled, also after an error. The card + fades in from black (refer to :attr:`BusyOverlay.brightness`). Thus a quick + operation paints only an almost black card, and the card never appears suddenly. It + is drawn only in the gaps between screens (refer to :meth:`_overlay_visible`). Thus + it shows the wait, and it does not cover a prompt that the user works in. Args: - message: An optional caption drawn beside the working chip. - title: An optional heading naming the screen being fetched. - interval: Seconds between animation frames (also the fade's repaint cadence). - Defaults to the platform's cadence — see :meth:`busy_startup`, which this - shares a hazard with: the card animates *over* a device read, so a rate the - console can't sustain steals the loop from the read it is covering for. + message: An optional caption next to the working chip. + title: An optional heading that names the screen whose data MeshTerm reads. + interval: The seconds between two animation steps (also the cadence of the fade + paints). The default is the cadence of the platform. Refer to + :meth:`busy_startup`, which has the same hazard: the card animates over a + device read. Thus a rate that the console cannot sustain takes the loop from + the read that the card covers. Yields: - The live :class:`BusyOverlay`, in case the caller wants to update its caption. + The live :class:`BusyOverlay`, if the caller must change its caption. """ tick = spinner_interval() if interval is None else interval - # A nested busy_overlay keeps the outer one (the outermost wait owns the screen); its - # own body still runs, it just doesn't install a second card. + # A nested busy_overlay keeps the outer overlay (the outermost wait owns the screen). + # Its own body still runs, but it does not install a second card. if self._overlay is not None: yield self._overlay return overlay = BusyOverlay(message, title=title) self._overlay = overlay if self._overlay_visible(): - self.invalidate() # start the fade-in promptly, before the first tick + self.invalidate() # start the fade-in immediately, before the first tick async def animate() -> None: while True: await asyncio.sleep(tick) overlay.tick() - # Only repaint when the card is actually on screen, so an overlay waiting - # behind a live prompt doesn't churn that prompt's repaints for nothing. + # Paint again only when the card is on the screen. Thus an overlay that waits + # behind a live prompt does not cause paints of that prompt with no purpose. if self._overlay_visible(): self.invalidate() @@ -1676,54 +1757,58 @@ class TuiSession: title: str = "", interval: float | None = None, ) -> AsyncIterator[BusyDialog]: - """Float a modal busy card over the current screen for the duration of a block. + """Float a modal busy card over the current screen while a block runs. - The in-stack counterpart to :meth:`busy_overlay`, and the one a screen wants when - *it* starts the slow work:: + This is the counterpart of :meth:`busy_overlay` on the stack. A screen must use it + when that screen itself starts the slow work:: async with session.busy_dialog("saving Lakeside…", title="Channels"): await device.set_channel(...) - Two things separate it from the overlay, and both are why the overlay could not do - this job. It is a real :class:`~meshterm.ui.tui.screen.BusyDialog` *pushed on the - stack*, so it draws over a hub instead of only in the gaps between screens — the - overlay paints on an empty stack alone (see :meth:`_overlay_visible`), which is - exactly never while a hub is visited. And being modal, it **owns the keyboard**: a - hub kept up with :meth:`stay` stays armed while the work runs, so without a modal - layer every key pressed during the wait still reaches it — letters landing in its - live filter (a list that comes back showing nothing), Esc resolving it to be handed - back the instant the work finishes (a screen that appears to close on its own a - beat later). Those presses now reach this card and stop there. + Two things make it different from the overlay, and for these two reasons the + overlay could not do this job: - Nesting keeps the outermost card, so a batch of writes reports as one wait rather - than flashing a box per write; the inner block still runs. The caller may retitle - the card as it goes — ``busy.message = …`` — which is how a sequence says which - step it is on. + - It is a real :class:`~meshterm.ui.tui.screen.BusyDialog` that is pushed on the + stack. Thus it draws over a hub, not only in the gaps between screens. The overlay + paints only on an empty stack (refer to :meth:`_overlay_visible`), and the stack + is never empty while the user visits a hub. + - It is modal, so it **owns the keyboard**. A hub that :meth:`stay` keeps up stays + armed while the work runs. Without a modal layer, each key that the user presses + during the wait still gets to the hub. Letters go into its live filter, and the + list comes back with nothing in it. Esc resolves the hub, and the hub is returned + at the instant when the work finishes: the screen seems to close by itself a + moment later. Now these key presses get to this card, and stop there. - Unlike :meth:`busy_overlay` there is no fade-in. The fade is there so a fast - operation shows nothing at all, and that is a fine trade for a cosmetic card; this - one is also the key guard, and a guard that arrives late is a guard with a hole in - it. + Nesting keeps the outermost card. Thus a batch of writes shows as one wait, and a + box does not flash for each write. The inner block still runs. The caller can + change the caption of the card while the work continues (``busy.message = …``). + This is how a sequence tells which step it is on. + + Different from :meth:`busy_overlay`, this card has no fade-in. The fade makes sure + that a fast operation shows nothing, and that is a good exchange for a cosmetic + card. But this card is also the key guard, and a guard that arrives late lets some + keys through. Args: - message: The caption drawn beside the spinner. - title: An optional heading naming the feature doing the work. - interval: Seconds between spinner frames; defaults to the platform's cadence - (see :meth:`busy_startup`, which shares the hazard: the card animates *over* - a device read, so a rate the console can't sustain steals the loop from the - work it is reporting on). + message: The caption next to the spinner. + title: An optional heading that names the feature that does the work. + interval: The seconds between two animation steps of the spinner. The default is + the cadence of the platform (refer to :meth:`busy_startup`, which has the + same hazard: the card animates over a device read, so a rate that the console + cannot sustain takes the loop from the work that the card reports on). Yields: - The live :class:`~meshterm.ui.tui.screen.BusyDialog`, so its caption can change. + The live :class:`~meshterm.ui.tui.screen.BusyDialog`, so that its caption can + change. """ tick = spinner_interval() if interval is None else interval - if self._busy is not None: # a nested wait rides the card its caller already put up + if self._busy is not None: # a nested wait uses the card that its caller already shows yield self._busy return screen = BusyDialog(message, title=title) - # A lone floating screen on an empty stack is drawn *as* the background, framed and - # full-frame rather than as a box, so it gets the same blank backdrop every other - # dialog uses (see :meth:`run_dialog`). + # A lone floating screen on an empty stack is drawn as the background, full-frame and + # with borders, not as a box. Thus it gets the same blank backdrop that each other + # dialog uses (refer to :meth:`run_dialog`). backdrop = None if not self._stack: backdrop = ScrollScreen("", floating=False, footer_hint="") @@ -1746,7 +1831,7 @@ class TuiSession: await ticker except asyncio.CancelledError: pass - except Exception: # noqa: BLE001 - a spinner hiccup must never break a flow + except Exception: # noqa: BLE001 - a small spinner problem must never break a flow pass self._busy = None self.pop(screen) @@ -1756,21 +1841,22 @@ class TuiSession: # --- application lifecycle ------------------------------------------------ async def run(self, main: Any) -> None: - """Run ``main`` (the menu loop) inside the full-screen application. + """Run ``main`` (the menu loop) in the full-screen application. - Starts the prompt_toolkit event loop, drives ``main`` as a background task on that - same loop, and exits the application when ``main`` returns. Any exception from - ``main`` is re-raised after the loop unwinds. + The method starts the prompt_toolkit event loop, and drives ``main`` as a background + task on that same loop. When ``main`` returns, the method exits the application. If + ``main`` raises an exception, the method raises it again after the loop unwinds. Args: - main: The coroutine driving the session (typically the menu loop). + main: The coroutine that drives the session (usually the menu loop). """ self._app = self._build_app() keyboard = get_platform().modifier_watch if keyboard: - # The Shift watcher flips the F-key lane's labels live. It reports from its - # own thread; hop onto the app loop for the repaint. Failure to engage (no - # device, no permission) just leaves the lane static — see the module doc. + # The Shift watcher changes the labels of the F-key lane live. It reports from + # its own thread, so go to the app loop for the paint. If the watcher cannot + # start (no input device, no permission), the lane stays static. Refer to the + # module doc. loop = asyncio.get_running_loop() modifier_watch.start(lambda: loop.call_soon_threadsafe(self.invalidate), keyboard) box: dict[str, BaseException] = {} @@ -1781,49 +1867,51 @@ class TuiSession: await main except asyncio.CancelledError: raise - except BaseException as exc: # noqa: BLE001 - re-raised after the app unwinds + except BaseException as exc: # noqa: BLE001 - raised again after the app unwinds box["exc"] = exc finally: - # ``is_running`` rather than ``not is_done``: prompt_toolkit clears its - # future on the way out, which makes ``is_done`` read False again once the - # app has already finished — and ``exit()`` on a finished app raises. This - # ``finally`` now also runs *after* the app is gone (the quit chords exit it - # from under us and ``run`` then cancels this task), so it has to tell "still - # up" from "already down" rather than "not yet finished". + # ``is_running`` instead of ``not is_done``: prompt_toolkit clears its future + # on the way out. Thus ``is_done`` reads False again after the app has + # finished, and ``exit()`` on a finished app raises. This ``finally`` now + # also runs after the app is gone (the quit chords exit the app from below + # us, and then ``run`` cancels this task). Thus it must tell "still up" from + # "already down", instead of "not yet finished". if self._app is not None and self._app.is_running: self._app.exit() def pre_run() -> None: task["driver"] = asyncio.ensure_future(driver()) - # 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. + # A held Esc opens the quit box, where a front end can detect one (the emulator). + # The SIGTERM of the launcher also quits through here. Refer to + # services.hold_to_quit. The listener costs nothing where nothing reports that a key + # goes 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``. + # Do not let prompt_toolkit install its own loop exception handler. On a stray + # error in a background task, that handler prints a traceback and a "Press ENTER + # to continue..." prompt directly over the full-screen UI. When it is disabled, + # the default handler of asyncio logs such errors to the ``asyncio`` logger + # instead. That logger goes to the file log (refer to + # :func:`meshterm.persistence.logging.configure_logging`), and never touches the + # screen. Errors from ``main`` still propagate through ``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. + # Whichever way the app exited, it tears down from here. A SIGTERM that arrives + # now must join this teardown, not 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 - # ``main`` is still parked on whatever screen was up. Left alone, that coroutine is - # simply abandoned mid-await and its ``finally`` never runs — which is where the - # history and chat runs are closed, the background services stopped, and the exit - # watchdog armed. Cancel it and wait for the unwind so quitting from anywhere tears - # down exactly as much as quitting from the menu does. + # The app can also exit from below the driver. The quit chords (^Q/^C) call + # ``Application.exit`` from their detached confirm, or directly from the key handler + # on the second press (refer to request_quit). Thus ``run_async`` returns while + # ``main`` still waits on the screen that was open. If nothing is done, that + # coroutine is abandoned during its await, and its ``finally`` never runs. That + # ``finally`` closes the history runs and the chat runs, stops the background + # services, and arms the exit watchdog. Cancel the coroutine and wait for the + # unwind. Thus a quit from any screen tears down exactly as much as a quit from the + # menu. driver_task = task.get("driver") if driver_task is not None and not driver_task.done(): driver_task.cancel() @@ -1835,14 +1923,15 @@ class TuiSession: raise box["exc"] def _build_app(self) -> Application: - """Construct the prompt_toolkit application, layout, and key bindings.""" + """Build the prompt_toolkit application, its layout, and its key bindings.""" base_control = ClusterTextControl(self._render_base, focusable=True) base_window = Window(base_control, always_hide_cursor=True) - # One centered-box float per stacked dialog layer, bottom-to-top: each renders the - # k-th screen floating above the background (see :meth:`_float_layers`), so a dialog - # opened over an existing popup draws *over* it — both at their own size — instead of - # the lower one being stretched to fill the frame. A generous fixed pool covers any - # realistic nesting; the ConditionalContainer hides the layers not in use this frame. + # One float with a centred box for each dialog layer on the stack, from bottom to + # top. Each float renders the k-th screen that floats above the background (refer to + # :meth:`_float_layers`). Thus a dialog that opens over a dialog draws over it, and + # the two keep their own sizes. The lower dialog is not stretched to fill the frame. + # A large fixed pool covers all realistic nesting. The ConditionalContainer hides + # the layers that this frame does not use. dialog_floats = [ Float( ConditionalContainer( @@ -1855,9 +1944,10 @@ class TuiSession: ) for i in range(_MAX_DIALOG_LAYERS) ] - # The busy overlay is the last float, so it draws on top of every dialog float — the - # top of the z-order. It is a content-sized window (dont_extend_*) with no anchors, so - # the FloatContainer centres just its skeleton card over the screen rather than blanking it. + # The busy overlay is the last float, so it draws on top of each dialog float: the + # top of the z-order. It is a ``Window`` sized to its content (dont_extend_*), with + # no anchors. Thus the FloatContainer centres only its skeleton card over the screen, + # and does not blank the screen. overlay_window = Window( ClusterTextControl(self._render_overlay), always_hide_cursor=True, @@ -1878,26 +1968,29 @@ class TuiSession: key_bindings=self._key_bindings(), full_screen=True, mouse_support=False, - # Keeps the live monitor counter in the header ticking. Per-platform, so a host - # where an idle repaint is expensive can breathe more slowly between frames. + # Keeps the live monitor counter in the header up to date. The value is set for + # each platform, so that a host where an idle paint is expensive can wait + # longer between frames. refresh_interval=get_platform().tick_s, - # Repaint as soon as the loop is free, rather than spinning the event loop for - # up to 10 ms first. prompt_toolkit's default postpone is there to protect a - # UI whose *own* output floods it with invalidations (its motivating case was - # a terminal multiplexer); here an invalidation is a keystroke or the 2 s - # header tick, so the delay buys nothing and was measured as a flat 3 ms on - # the PicoCalc and 10 ms on desktop, paid on every single key. + # Paint as soon as the loop is free, instead of a spin of the event loop for up + # to 10 ms first. The default postpone of prompt_toolkit protects a UI whose own + # output floods it with invalidations (the case that caused it was a terminal + # multiplexer). Here an invalidation is a key press or the 2 s header tick. Thus + # the delay gives no advantage. We measured it as a constant 3 ms on the + # PicoCalc and 10 ms on the desktop, for each key press. max_render_postpone_time=None, input=self._input, output=self._resolve_output(), - # None leaves the output's own default alone; see _color_depth for why the - # two prompt_toolkit outputs disagree and why only a raise is ever applied. + # None keeps the default of the output. Refer to _color_depth for the reason + # why the two prompt_toolkit outputs do not agree, and why the function only + # increases the depth. color_depth=_color_depth(), ) if fastrender.enabled(): - # Swap in the row-diff renderer for plain full-screen frames. Built with the - # same arguments Application gave the stock one, so everything except the - # paint itself — CPR, alternate screen, mouse, cursor shape — is unchanged. + # Use the row-diff renderer for plain full-screen frames. It is built with the + # same arguments that Application gave the standard renderer. Thus all is + # unchanged (CPR, alternate screen, mouse, cursor shape), except the paint + # itself. app.renderer = fastrender.FastRenderer( app._merged_style, app.output, @@ -1909,21 +2002,24 @@ class TuiSession: return app def _resolve_output(self) -> Any: - """The output the app renders to: the real terminal, pinned and optionally widened. + """The output that the app renders to: the real terminal, with pins and possibly wider. - Only the *real* terminal (``self._output is None``, so prompt_toolkit would build its - own output) is wrapped: a test that supplies its own output keeps the exact size and - the exact bytes it set, so headless rendering stays deterministic. Two wraps, each - where its own gate says so, and either may be the only one: + Only the real terminal is wrapped (``self._output is None``, so prompt_toolkit would + build its own output). A test that gives its own output keeps the exact size and the + exact bytes that it set. Thus a headless render stays deterministic. There are two + wraps. Each one applies where its own gate says so, and either one can be the only + one: * :class:`~meshterm.ui.tui.colsnap.PinnedOutput`, where - :func:`~meshterm.ui.tui.colsnap.enabled` — every glyph prompt_toolkit's renderer - writes lands in the column that renderer measured it into. - * :class:`_WidthExtendedOutput`, where :func:`_reclaim_last_column` — or, left to the - terminal, where :func:`_probe_hides_last_column` — outermost, since the size it - reports is what both renderers and the compositor lay out against. + :func:`~meshterm.ui.tui.colsnap.enabled` is true. Each glyph that the renderer of + prompt_toolkit writes goes to the column that the renderer measured for it. + * :class:`_WidthExtendedOutput`, where :func:`_reclaim_last_column` is true (or, if + the terminal decides, where :func:`_probe_hides_last_column` is true). This wrap is + the outermost, because the two renderers and the compositor lay out against the + size that it reports. - With neither, this is ``None`` and prompt_toolkit builds its own output as before. + With neither wrap, this is ``None``, and prompt_toolkit builds its own output as + before. """ pin = colsnap.enabled() reclaim = _reclaim_last_column() @@ -1950,19 +2046,21 @@ class TuiSession: return max(20, size.columns), max(6, size.rows) def base_body_size(self) -> tuple[int, int]: - """Return the ``(width, height)`` in cells available to the base screen's body. + """Return the ``(width, height)`` in cells that the body of the base screen can use. - Mirrors the layout math in :func:`~meshterm.ui.tui.frame.compose_base` so a - full-screen screen (e.g. the map) can size its own content to fill the frame exactly, - without waiting a repaint to learn its height. *Both* of that function's branches: - a borderless platform swaps the panel's two border rows and four padding columns for - a single title-bar row, so a screen sizing itself against the bordered math there - would leave a row of the frame it was handed permanently blank. The width is the - current base screen's, which a :attr:`~meshterm.ui.tui.screen.Screen.flush` one - widens by the two padding columns it does without. + This method copies the layout arithmetic of + :func:`~meshterm.ui.tui.frame.compose_base`. Thus a full-screen screen (for example + the map) can size its own content to fill the frame exactly, and it does not wait for + a paint to learn its height. It copies the two branches of that function. A + borderless platform replaces the two border rows and the four padding columns of the + panel with one title-bar row. If a screen uses the arithmetic for borders there, one + row of the frame that it gets stays blank permanently. The width is the width of + the current base screen. A :attr:`~meshterm.ui.tui.screen.Screen.flush` screen adds + the two padding columns that it does not use. Returns: - The inner content width and the body viewport height, both in character cells. + The width of the inner content and the height of the body viewport, both in + cells. """ cols, rows = self._size() header_h = len(frame.header_lines(self._header(cols), cols)) @@ -1974,13 +2072,13 @@ class TuiSession: return cols, max(1, rows - header_h - 1 - 1) # minus footer(1) and title bar(1) def _base_index(self) -> int: - """Stack index of the full-frame background screen. + """The stack index of the full-frame background screen. - The background is the top-most *non-floating* screen — a menu, map, or list that - fills the frame — and every floating dialog above it is drawn as a centered box - over it (see :meth:`_float_layers`). When the whole stack is floating (a tool - whose own primary screen is a floating select, e.g. Channels), the bottom screen - is the background: it is the one the dialogs above it should float over. + The background is the top screen that does not float: a menu, the map, or a list + that fills the frame. Each floating dialog above it is drawn as a centred box over + it (refer to :meth:`_float_layers`). When all the screens on the stack float (a tool + whose own main screen is a floating select, for example Channels), the bottom screen + is the background: the dialogs above it must float over it. """ for i in range(len(self._stack) - 1, -1, -1): if not getattr(self._stack[i], "floating", False): @@ -1994,55 +2092,56 @@ class TuiSession: return self._stack[self._base_index()] def _float_layers(self) -> list[Screen]: - """The floating dialogs stacked above the background, bottom-to-top. + """The floating dialogs on the stack above the background, from bottom to top. - Each is drawn as its own centered box over the ones beneath — so opening a dialog - over an existing popup leaves that popup at its own size rather than stretching it - to fill the frame (the single-float compositor's old failing). + Each one is drawn as its own centred box over the dialogs below it. Thus when a + dialog opens over a dialog, the lower dialog keeps its own size, and is not stretched + to fill the frame (this was the old fault of the compositor with one float). """ if not self._stack: return [] return self._stack[self._base_index() + 1 :] def _has_float(self) -> bool: - """Whether any dialog floats over the background this frame.""" + """Whether a dialog floats over the background in this frame.""" return bool(self._float_layers()) def _emit(self, text: str, layer: str = "base") -> ANSI: - r"""Wrap a composed frame as prompt_toolkit :class:`ANSI`. + r"""Wrap a composed frame as a prompt_toolkit :class:`ANSI`. - A row holding a glyph the terminal may draw narrower than pt reserves for it is - repainted whole, rather than differentially. + A row with a glyph that the terminal may draw narrower than the cells that pt + reserves for it gets a full paint, not a differential paint. - prompt_toolkit paints differentially: it rewrites only the cells that changed since - the last frame, and it steps the cursor *relative* to its own width model. That is - sound only while every glyph is one cell wide. A width-2 glyph the terminal draws in - a single cell (an emoji in a chat line, a menu icon) leaves everything to its right on - that row one column left of where pt thinks it is; a later paint that jumps into the - row — skipping the unchanged emoji — writes at pt's column, one past the content it - meant to overwrite, and the stale cell lingers. + prompt_toolkit paints differentially. It writes again only the cells that changed + since the last frame, and it moves the cursor relative to its own width model. That + is correct only while each glyph is one cell wide. The terminal can draw a width-2 + glyph in one cell (an emoji in a chat line, a menu icon). Then all the text to its + right on that row is one column to the left of where pt thinks it is. A later paint + that jumps into the row (and skips the unchanged emoji) writes at the column of pt, + one column after the content that it must write over. Thus the old cell stays. - The requirement that fixes is narrow: a row carrying such a glyph must be rewritten - *whole*, from column 0, so the terminal's own cursor advance re-lays it. It does not - need the screen erased, and it does not need the rows around it touched — pt steps - down a row with ``\\r\\n``, which returns the terminal to a true column 0 whatever the - drift above it, so the misalignment can never spread past the row it is on. + The repair has a narrow requirement: a row that has such a glyph must be written + again in full, from column 0, so that the cursor of the terminal lays it out again. + It is not necessary to erase the screen, or to touch the rows around it. pt goes down + a row with ``\\r\\n``, which puts the terminal back to a real column 0, whatever the + drift above it. Thus the incorrect alignment can never spread past its row. - So the changed rows are rewritten and nothing else is (:meth:`_scrub_rows`). Three - things narrow it to that: + Thus the changed rows are written again, and nothing else is (:meth:`_scrub_rows`). + Three rules limit the work to that: - * **Nothing changed → nothing to do.** The app repaints on a 1 Hz timer to tick the - header's pulse, and an idle screen composes identically each time. pt writes no - cells, so its cursor cannot drift; the previous paint already left the terminal - aligned. (This alone is the flicker: erasing an emoji-bearing screen and rewriting - it identically, once a second.) + * **Nothing changed → nothing to do.** The app paints on a 1 Hz timer to move the + pulse of the header, and an idle screen composes the same each time. pt writes no + cells, so its cursor cannot drift. The last paint already left the terminal + aligned. (This case alone caused the flicker: once each second, the app erased a + screen with an emoji and wrote it again, with no change.) * **No wide glyph drawn → nothing to do.** The plain differential paint is exact. - * **Otherwise, only the rows that changed.** The background composes one line per - terminal row, so its diff maps straight onto rows — a ticking header repaints the - header, not the screen under it. A *float* is a centred box whose rows the layout - places, not us, so a dialog changing (or closing — see :meth:`_reconcile_layers`) - still falls back to dropping pt's cached frame, as does a frame whose height moved. - Those are user-driven and occasional; the timer is neither. + * **In all other cases, only the rows that changed.** The background composes one + line for each terminal row, so its diff maps directly onto rows. Thus a header that + ticks paints the header again, not the screen below it. A float is a centred box, + and the layout places its rows, not us. Thus when a dialog changes (or closes, + refer to :meth:`_reconcile_layers`), the fallback still removes the cached frame of + pt. The same occurs for a frame whose height changed. The user causes these cases, + and they are not frequent. The timer is neither of the two. """ entry = (text, _has_wide_glyph(text)) previous = self._layers.get(layer) @@ -2051,24 +2150,25 @@ class TuiSession: self._layers[layer] = entry if any(wide for _text, wide in self._layers.values()): rows = _changed_rows(previous[0], text) if previous is not None else None - # The background's line i *is* terminal row i; nothing else can claim that. + # Line i of the background is terminal row i. No other layer can claim that. if layer != "base" or rows is None or not self._scrub_rows(rows): self._invalidate_last_frame() return ANSI(text) def _repaint_if_wide(self) -> None: - """Upgrade this paint to a full repaint if any drawn layer holds a wide glyph.""" + """Change this paint into a full paint if a drawn layer has a wide glyph.""" if any(wide for _text, wide in self._layers.values()): self._invalidate_last_frame() def _reconcile_layers(self) -> None: - """Forget the layers this paint won't draw, and treat their leaving as a change. + """Forget the layers that this paint will not draw, and count their removal as a change. - A float is hidden by dropping its window from the layout, so a closing dialog simply - stops calling :meth:`_emit` — nothing would otherwise notice it had gone, and the - cells it gives back to the base would be rewritten piecemeal over a row the terminal - may be drawing shifted. Called at the top of the paint, from the base layer, since - the background is composed before the floats above it. + A float is hidden when its ``Window`` is removed from the layout. Thus a dialog that + closes only stops its calls to :meth:`_emit`. Without this method, nothing sees that + the dialog is gone. Then the cells that it gives back to the base are written again + in small parts, over a row that the terminal may draw out of position. + The base layer calls this method at the start of the paint, because the background + is composed before the floats above it. """ live = {f"float{i}" for i in range(len(self._float_layers()))} if self._base_screen() is not None: @@ -2082,7 +2182,7 @@ class TuiSession: self._repaint_if_wide() def _render_base(self) -> ANSI: - """Render the persistent frame around the background screen.""" + """Render the background screen with the persistent header and footer around it.""" self._reconcile_layers() # the paint starts here: the background composes first cols, rows = self._size() base = self._base_screen() @@ -2091,11 +2191,11 @@ class TuiSession: scrub = base.consume_edge_scrub() if scrub: self._scrub_right_columns(scrub) - # A bare base (the share screen's QR code) is its body on blank rows, nothing else. + # A bare base (the QR code of the share screen) is only its body on blank rows. if base.bare: return self._emit(frame.compose_bare(base, cols, rows)) - # A chromeless base (the startup splash) forgoes the header/footer bars and is - # centered under its banner instead of stretched across the terminal. + # A chromeless base (the startup splash) has no header or footer bars. It is + # centred below its banner, instead of stretched across the terminal. if not base.chrome: return self._emit(frame.compose_startup(base, cols, rows)) footer = self.top.footer_hint if self.top else base.footer_hint @@ -2105,21 +2205,22 @@ class TuiSession: ) def _plain_frame(self) -> str | None: - """The whole frame as rows, when this paint is one the fast path may take. + """The full frame as rows, when the fast path can do this paint. - The background screen, with every floating dialog composited over it exactly where - prompt_toolkit's ``FloatContainer`` would centre it (see - :func:`~meshterm.ui.tui.frame.composite_float`) — so a confirm, a picker or the - packet viewer stays on the row-diff path rather than paying prompt_toolkit's whole - grid rebuild on every keystroke. + The frame is the background screen, with each floating dialog composited over it + exactly where the ``FloatContainer`` of prompt_toolkit would centre it (refer to + :func:`~meshterm.ui.tui.frame.composite_float`). Thus a confirm, a picker, or the + packet viewer stays on the row-diff path, and does not pay for the full grid rebuild + of prompt_toolkit at each key press. - Answers ``None`` — meaning "let prompt_toolkit lay this one out" — for the two - frames we don't place ourselves: the busy overlay, which is a content-sized window - the float container measures, and an empty stack, which has no background at all. + The method returns ``None`` (that is, "let prompt_toolkit lay this one out") for the + two frames that we do not place ourselves: the busy overlay, which is a ``Window`` + sized to its content that the float container measures, and an empty stack, which + has no background. - Every layer still goes through its usual renderer (:meth:`_render_base`, - :meth:`_render_float_layer`), so the layer bookkeeping those keep is identical - whichever path the paint takes. + Each layer still goes through its usual renderer (:meth:`_render_base`, + :meth:`_render_float_layer`). Thus the layer records that those renderers keep are + the same, whichever path the paint takes. """ if self._overlay_visible() or not self._stack: return None @@ -2135,11 +2236,12 @@ class TuiSession: @staticmethod def _fkey_lane(active: Screen) -> Callable[[], Text] | None: - """A deferred F-key lane row for ``active``, or ``None`` on a platform without one. + """A deferred F-key lane row for ``active``, or ``None`` on a platform without a lane. - Deferred because the frame resolves it *after* the body renders: a lane dims the - slots whose action would do nothing, and that reading comes from the scroll - metrics this paint is about to record (see :func:`~meshterm.ui.tui.fkeys.default_lane`). + The row is deferred because the frame resolves it after the body renders. A lane + dims the slots whose action does nothing, and that information comes from the + scroll metrics that this paint will store (refer to + :func:`~meshterm.ui.tui.fkeys.default_lane`). """ deck = fkeys.active_deck() if deck is None: @@ -2147,7 +2249,7 @@ class TuiSession: return lambda: deck.lane_text(active.fkey_lane, shifted=modifier_watch.shift_down()) def _render_float_layer(self, index: int) -> ANSI: - """Render the ``index``-th floating dialog (bottom-to-top) as a centered box.""" + """Render the ``index``-th floating dialog (from bottom to top) as a centred box.""" layers = self._float_layers() if index >= len(layers): return ANSI("") @@ -2155,18 +2257,19 @@ class TuiSession: return self._emit(frame.compose_dialog(layers[index], cols, rows), f"float{index}") def _overlay_visible(self) -> bool: - """Whether the busy overlay should be painted this frame. + """Whether to paint the busy overlay in this frame. - Gated on an empty screen stack so the card only appears in the "black screen" gaps a - device operation opens between screens (a menu navigation before the tool's first - prompt, say) and never buries a dialog the user is meant to be reading. It also stays - unpainted through the overlay's initial hold (:attr:`BusyOverlay.brightness` is 0), so - an operation that finishes within the hold shows nothing and never flashes. + The overlay shows only on an empty screen stack. Thus the card appears only in the + "black screen" gaps that a device operation opens between screens (for example, a + menu navigation before the first prompt of the tool). It never covers a dialog that + the user must read. It also stays unpainted during the initial hold of the overlay + (:attr:`BusyOverlay.brightness` is 0). Thus an operation that finishes during the + hold shows nothing and never flashes. """ return self._overlay is not None and not self._stack and self._overlay.brightness > 0 def _render_overlay(self) -> ANSI: - """Render the busy overlay's skeleton card (only when :meth:`_overlay_visible`).""" + """Render the skeleton card of the busy overlay (only when :meth:`_overlay_visible`).""" if self._overlay is None: return ANSI("") return self._emit(self._overlay.render(), "overlay") @@ -2174,11 +2277,11 @@ class TuiSession: # --- input --------------------------------------------------------------- def _key_bindings(self) -> KeyBindings: - """Build the global key bindings that dispatch normalized actions to the top. + """Build the global key bindings that send normalized actions to the top screen. - Every key — navigation, Ctrl chord, typed character, pasted run — funnels through - :meth:`_dispatch`, which is what lets the right-Ctrl rescue there cover the whole app - rather than the screen actions only. + Each key (navigation, Ctrl chord, typed character, pasted text) goes through + :meth:`_dispatch`. Thus the right-Ctrl rescue there covers the full app, not only the + screen actions. """ kb = KeyBindings() @@ -2199,57 +2302,61 @@ class TuiSession: self._dispatch("text", data) elif len(data) > 1: # A bracketed paste (Ctrl-V, right-click, Ctrl-Shift-V) arrives as one - # multi-character run — hand the whole thing to the top screen as a paste it - # can confirm and insert, rather than dropping it as the old len==1 guard did. + # multi-character sequence. Give all of it to the top screen as a paste that + # the screen can confirm and insert. The old len==1 guard removed it instead. self._dispatch("paste", data) return kb def _dispatch(self, action: str, data: str = "") -> None: - """Forward an action to the top screen and repaint. + """Send an action to the top screen, and paint the frame again. - Right Ctrl is read as Ctrl first, app-wide: a plain navigation key, or *any* bare - letter arriving as text, is promoted to its Ctrl chord while the right Ctrl key is - physically held (see :func:`_right_ctrl_down`, :data:`_CTRL_CHORDS`, - :data:`_CTRL_LETTER_CHORDS`) — a no-op when the console already reported the chord, and - the rescue when a layout-claimed right Ctrl stripped it to a bare character. Because - every binding funnels through here, the rescue covers the session's own chords too, not - just the screen actions: right Ctrl-V pastes into a compose line instead of typing a - ``v``, right Ctrl-C quits. + In all the app, the right Ctrl key is first read as Ctrl. While the right Ctrl key is + physically held, a plain navigation key, or any bare letter that arrives as text, + changes into its Ctrl chord (refer to :func:`_right_ctrl_down`, :data:`_CTRL_CHORDS`, + :data:`_CTRL_LETTER_CHORDS`). When the console already reported the chord, this does + nothing. When a keyboard layout claimed the right Ctrl key and removed it, so that + only a bare character arrived, this is the rescue. Each binding goes through this + method. Thus the rescue also covers the chords of the session, not only the screen + actions: right Ctrl-V pastes into a compose line instead of a typed ``v``, and right + Ctrl-C quits. - The session-level actions are answered here rather than forwarded — no screen ever - sees ``to_menu``, ``quit``, ``quit_now`` or ``paste_clipboard``. + This method answers the session-level actions itself, and does not send them to a + screen. No screen ever gets ``to_menu``, ``quit``, ``quit_now``, or + ``paste_clipboard``. - The repaint keeps prompt_toolkit's fast differential paint; a frame carrying a glyph - the terminal may draw narrower than pt reserves for it (an emoji) upgrades itself to a - full repaint at compose time — see :meth:`_emit`. + The paint keeps the fast differential paint of prompt_toolkit. A frame with a glyph + that the terminal may draw narrower than the cells that pt reserves for it (an emoji) + changes itself into a full paint when it is composed. Refer to :meth:`_emit`. """ - # An F-key resolves against the top screen's lane on the platform's deck (see - # ui.tui.fkeys) into a normal screen action; an unassigned slot, a key the deck - # doesn't use, or a platform without a lane drops the press here. + # An F-key resolves against the lane of the top screen, on the deck of the platform + # (refer to ui.tui.fkeys), into a normal screen action. With an unassigned slot, a + # key that the deck does not use, or a platform without a lane, the key press stops + # here. if len(action) in (2, 3) and action[0] == "f" and action[1:].isdigit(): number = int(action[1:]) deck = fkeys.active_deck() if deck is None: return if deck.is_shift_key(number): - # However this resolves, the code only exists because Shift was - # physically down for the keyboard to emit it — latch the lane's shifted - # display against the release/re-assert flicker (see modifier_watch). + # Whatever this resolves to, the keyboard sent this code only because Shift + # was physically down. Thus latch the shifted labels of the lane, to stop the + # flicker when Shift is released and pressed again (refer to modifier_watch). modifier_watch.note_shift_bank_key() top = self.top or self._base_screen() resolved = deck.action_for(top.fkey_lane, number) if top else None if resolved is None: return action = resolved - # The key-state probe comes last in each test, so it only runs for a key that could - # be a chord at all — not on every keystroke. + # The key-state probe comes last in each test. Thus it runs only for a key that can + # be a chord, not at each key press. if action in _CTRL_CHORDS and _right_ctrl_down(): 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). + # An Esc of a terminal that is still held down is a hold, not yet a press. Any other + # key goes after an Esc that is held back, so that the keys keep their order (refer + # to set_esc_probe). watched = self._watched_esc if watched is not None: if action == "escape": @@ -2259,38 +2366,43 @@ class TuiSession: 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 - # changes nothing, and an armed unwind is about to change everything. + # Pop all the screens on the stack at one time (^W). The unwind is refused over a + # dialog or over work in progress (refer to request_pop_all). The paint below is + # still wanted in the two cases. After a refusal, it changes nothing, and an + # armed unwind will soon change everything. self.request_pop_all() self.invalidate() return if action == "quit": - # Asks first, from anywhere; a second press while it asks leaves (see - # request_quit). "Unpair & quit" rides the confirm the menu declared. + # Ask first, from any screen. A second press while the question is open quits + # (refer to request_quit). "Unpair & quit" comes with the confirm that the menu + # declared. self.request_quit() self.invalidate() return if action == "quit_now": - # Straight out, no question: the main menu's ``Quit!`` chip, on the Shift half - # of the ``Quit?`` it sits behind — a deliberate two-key reach on the one screen - # that offers it, never a chord a slip on the way to ^W could land on. + # Quit immediately, with no question: the ``Quit!`` chip of the main menu, on the + # Shift half of the ``Quit?`` chip. It is a two-key press on purpose, on the only + # screen that offers it. It is never a chord that a wrong key press on the way to + # ^W can hit. self._exit_app() return if action == "paste_clipboard": - # Some terminals deliver Ctrl-V as the literal control key — no bracketed-paste - # sequence, so no text on the event. Read the OS clipboard ourselves and hand the - # run to the top screen as a paste. Terminals that instead translate Ctrl-V into a - # bracketed paste never reach here — that lands in _typed as a multi-char run. + # Some terminals send Ctrl-V as the literal control key, with no bracketed-paste + # sequence, so the event has no text. Read the OS clipboard here, and give the + # text to the top screen as a paste. Terminals that change Ctrl-V into a + # bracketed paste never get here: that paste goes to _typed as a multi-character + # sequence. text = _read_clipboard() if text: self._dispatch("paste", text) return top = self.top - # Edge scroll and its snap-back get the key first (Screen.edge_scroll): a key that - # would act on a highlight scrolled out of view brings it back before doing anything, - # and Home/End take the page to its ends. An arrow goes on to the screen, and the - # next paint scrolls the page instead if it moved nothing (Screen.note_highlight). + # The edge scroll and its snap-back get the key first (Screen.edge_scroll). A key + # that acts on a highlight that is not visible first brings the highlight back, and + # does nothing more. Home/End take the page to its ends. An arrow continues to the + # screen. If the arrow moved nothing, the next paint scrolls the page instead + # (Screen.note_highlight). if top is not None and not top.edge_scroll(action): top.handle(action, data) self.invalidate() diff --git a/meshterm/ui/tui/spinner.py b/meshterm/ui/tui/spinner.py index 759083b..18495ee 100644 --- a/meshterm/ui/tui/spinner.py +++ b/meshterm/ui/tui/spinner.py @@ -1,11 +1,12 @@ # SPDX-License-Identifier: Apache-2.0 """A reusable text spinner: one animated glyph for a "working" indicator. -A small, screen-agnostic animation helper. It holds a cycle of frame glyphs and a current -position; a caller advances it with :meth:`tick` (typically from an animation timer) and -reads the current frame as a bare glyph or as a styled Rich :class:`~rich.text.Text`. The -busy splash uses it, but it is deliberately independent of any screen so any "working" -indicator across the toolkit can reuse the same animation. +A small animation helper that does not depend on a screen. It holds a cycle of glyphs, one +for each animation step, and a current position. A caller moves it forward with +:meth:`tick` (usually from an animation timer). Then the caller reads the current +animation step as a bare glyph, or as a styled Rich :class:`~rich.text.Text`. The busy +splash uses it. But it is independent of all screens on purpose, so that each "working" +indicator in the toolkit can use the same animation. """ from __future__ import annotations @@ -16,42 +17,44 @@ from ...platforms import get_platform def spinner_interval() -> float: - """Seconds a "working" animation should wait between frames, on this platform. + """The seconds that a "working" animation waits between animation steps, on this platform. - The single source of the app's spin cadence — every animated wait sleeps on this rather - than on its own constant, so the rate is one platform decision instead of five copies - drifting apart. Called at each tick rather than read into a module constant: a constant - would freeze whatever platform was active at *import* time, which is always the default - (``set_platform`` runs later, in the CLI callback — see :mod:`meshterm.platforms`). + This function is the only source of the spin rate of the app. Each animated wait sleeps + for this value, not for its own constant. Thus the rate is one decision of the + platform, not five copies that become different over time. The function is called at + each tick, and its value is not read into a module constant. A constant keeps the + platform that was active at import time, and that is always the default platform + (``set_platform`` runs later, in the CLI callback: refer to :mod:`meshterm.platforms`). Returns: - The active platform's :attr:`~meshterm.platforms.Platform.spinner_tick_s`. + The :attr:`~meshterm.platforms.Platform.spinner_tick_s` of the active platform. """ return get_platform().spinner_tick_s class Spinner: - """An animated spinner that cycles through a set of frame glyphs. + """An animated spinner that cycles through a set of glyphs, one for each animation step. Attributes: - style: The Rich style :meth:`text` applies to the current glyph. + style: The Rich style that :meth:`text` applies to the current glyph. """ - #: The default Braille-dot frames — a smooth, single-cell rotation. + #: The default animation steps, in Braille dots: a smooth rotation in one cell. BRAILLE = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" - #: A plain ASCII cycle for terminals/fonts without Braille glyphs. + #: A plain ASCII cycle for terminals or fonts that have no Braille glyphs. LINE = "|/-\\" def __init__(self, frames: str | None = None, *, style: str = "accent") -> None: - """Create a spinner resting on its first frame. + """Create a spinner at its first animation step. Args: - frames: The glyphs to cycle through, one per animation frame. Defaults to the - active platform's cycle — :data:`BRAILLE` where effects are on, the - four-frame :data:`LINE` where they aren't. Resolved here, at construction, - so a spinner built after ``set_platform`` picks the right cycle and never - re-decides while it spins. - style: The Rich style :meth:`text` applies to the current glyph. + frames: The glyphs to cycle through, one for each animation step. The default + is the cycle of the active platform: :data:`BRAILLE` where effects are on, + and :data:`LINE` (four animation steps) where effects are off. The default + is resolved here, at construction. Thus a spinner that is built after + ``set_platform`` gets the correct cycle, and never decides again while it + spins. + style: The Rich style that :meth:`text` applies to the current glyph. """ if frames is None: frames = self.BRAILLE if get_platform().effects else self.LINE @@ -63,20 +66,20 @@ class Spinner: @property def frame(self) -> str: - """The current frame's glyph.""" + """The glyph of the current animation step.""" return self._frames[self._index] @property def frames(self) -> str: - """The full cycle of frame glyphs, in order.""" + """The glyphs of the full cycle of animation steps, in order.""" return self._frames def tick(self) -> None: - """Advance to the next frame, wrapping around at the end of the cycle.""" + """Go to the next animation step. After the end of the cycle, go back to the start.""" self._index = (self._index + 1) % len(self._frames) def reset(self) -> None: - """Return the spinner to its first frame.""" + """Put the spinner back at its first animation step.""" self._index = 0 def text(self, style: str | None = None) -> Text: