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) <noreply@anthropic.com>
This commit is contained in:
1 parent
3e251a9707
commit
d6d49df0a2
15 files changed
+3720
-3292
No files matched your search
+19
-13
@@ -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
|
||||
|
||||
+181
-157
@@ -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)
|
||||
|
||||
|
||||
|
||||
+222
-199
@@ -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
|
||||
|
||||
@@ -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
|
||||
+200
-173
@@ -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
|
||||
|
||||
+386
-353
File diff suppressed because it is too large.
Load diff
+87
-71
@@ -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()
|
||||
|
||||
|
||||
+58
-47
@@ -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"``.
|
||||
|
||||
+51
-40
@@ -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)
|
||||
|
||||
+277
-251
@@ -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
|
||||
|
||||
+171
-152
@@ -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:
|
||||
|
||||
+475
-419
File diff suppressed because it is too large.
Load diff
+525
-478
File diff suppressed because it is too large.
Load diff
+948
-836
File diff suppressed because it is too large.
Load diff
+30
-27
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user