diff --git a/meshterm/ui/fontset.py b/meshterm/ui/fontset.py index 938ad5d..8790f36 100644 --- a/meshterm/ui/fontset.py +++ b/meshterm/ui/fontset.py @@ -1,34 +1,37 @@ # SPDX-License-Identifier: Apache-2.0 -"""The handhelds' glyph inventories — the glyph contract. +"""The glyph inventories of the handhelds. They are the glyph contract. -The PicoCalc panel draws through the kernel console with one 512-glyph PSF font -(``meshterm.psf.gz``, built by ``scripts/picocalc-lyra/calculinux-console-font-6x12.sh``): the stock -Terminus 6×12 base (a Cyrillic-coverage table — note there are **no accented Latin -letters**), the full braille block, MeshTerm's own marks drawn into donor slots, and a -few aliases. A character outside this set renders as a blank on the panel, so *nothing -outside it may ever be emitted* on the picocalc-lyra platform — the render boundary folds -text down to it (:func:`meshterm.ui.theme.fold_text`), and the dual-platform gallery -asserts the fold held. +The PicoCalc display draws through the kernel console with one 512-glyph PSF font +(``meshterm.psf.gz``, built by ``scripts/picocalc-lyra/calculinux-console-font-6x12.sh``). +The font has these parts: the stock Terminus 6×12 base (a table that covers Cyrillic, +which has **no accented Latin letters**), the full braille block, the marks of MeshTerm +that are drawn into donor slots, and a few aliases. The display shows a character that is +not in this set as a blank. Thus MeshTerm must never send a character that is not in the +set on the picocalc-lyra platform. The render boundary folds the text down to the set +(:func:`meshterm.ui.theme.fold_text`), and the dual-platform gallery test makes sure that +the fold held. -This table is the **single source of truth** for that contract, shared by the runtime -fold and the tests. It mirrors the font actually installed on the device: the base -inventory was dumped live from the PSF's Unicode table (2026-08-01), minus the donor -codepoints the build script now repurposes, plus the marks it draws in their place. -If the build script's ``MARKS``/``DONORS``/``ALIASES`` change, this table must move in -the same commit — and vice versa. +This table is the only source of truth for that contract. The fold at run time and the +tests share it. It copies the font that is installed on the handheld. The base inventory +was dumped from the Unicode table of the PSF on the handheld (2026-08-01). The table has +no donor codepoints that the build script now uses for other glyphs, and it has the marks +that the script draws in their place. If the ``MARKS``, ``DONORS``, or ``ALIASES`` of the +build script change, this table must change in the same commit. The reverse is also true. -The Cardputer Zero has a contract of its own, :data:`CARDPUTER_ZERO_CODEPOINTS`: what its console -host draws, which no kernel caps. :data:`FONTS` names both, for ``Platform.font``. +The Cardputer Zero has its own contract, :data:`CARDPUTER_ZERO_CODEPOINTS`. It is what +the console host draws, and no kernel limits it. :data:`FONTS` names both contracts, for +``Platform.font``. """ from __future__ import annotations -#: Inclusive ``(first, last)`` codepoint ranges present in the font. 519 codepoints over -#: 512 glyphs — aliases (the rounded corners onto the square ones, ``⋯`` onto ``…``) and -#: shared slots give a few glyphs more than one codepoint. Verified against a live table -#: dump of the installed font (2026-08-01, post-P3 build). On 2026-10-06, the two powerline -#: chevrons of the path chips (U+E0B0, U+E0B1) took the donor slots of U+2559 and U+255B. -#: The same day, a dump of the font installed on the Lyra matched this table exactly. +#: Inclusive ``(first, last)`` codepoint ranges that are in the font. There are 519 +#: codepoints for 512 glyphs, because aliases (the rounded corners onto the square ones, +#: ``⋯`` onto ``…``) and shared slots give a few glyphs more than one codepoint. We +#: checked this table against a dump of the table of the installed font (2026-08-01, +#: post-P3 build). On 2026-10-06, the two powerline chevrons of the path chips (U+E0B0, +#: U+E0B1) took the donor slots of U+2559 and U+255B. The same day, a dump of the font +#: that is installed on the Lyra was exactly the same as this table. # fmt: off FONT_RANGES: tuple[tuple[int, int], ...] = ( (0x0020, 0x007F), (0x00A0, 0x00A0), (0x00A7, 0x00A7), (0x00A9, 0x00A9), @@ -56,25 +59,27 @@ FONT_RANGES: tuple[tuple[int, int], ...] = ( ) # fmt: on -#: Every codepoint the console font can draw, as one frozen set (built once at import; -#: 519 members, so the set is small and the per-character membership test is a dict hit). +#: All the codepoints that the console font can draw, as one frozen set. MeshTerm builds +#: it one time, at import. It has 519 members, so it is small, and the membership test for +#: each character is a fast hash lookup. FONT_CODEPOINTS: frozenset[int] = frozenset( cp for first, last in FONT_RANGES for cp in range(first, last + 1) ) def in_font(char: str) -> bool: - """Whether the console font has a glyph for ``char``.""" + """Check if the console font has a glyph for ``char``.""" return ord(char) in FONT_CODEPOINTS -#: The Cardputer Zero's inventory: what its emulator draws (:mod:`meshterm.emulator.font`) -#: — Terminus 4.49's 12-pixel face, every one of its 1,356 glyphs, with MeshTerm's own -#: marks drawn over it and ``⋯`` aliased onto the ellipsis, as on the PicoCalc. No 512-glyph -#: cap here, so braille, the powerline chevrons and accented Latin are all simply present. -#: Generated from ``ter-u12n.bdf`` plus the host's ``MARKS`` and ``ALIASES``; if either -#: changes, this table moves in the same commit (``tests/test_emulator.py`` checks the -#: marks, and the font itself wherever it is installed). +#: The inventory of the Cardputer Zero. It is what its emulator draws +#: (:mod:`meshterm.emulator.font`): the 12-pixel face of Terminus 4.49 with all its 1,356 +#: glyphs, with the marks of MeshTerm drawn over it, and ``⋯`` as an alias of the +#: ellipsis, as on the PicoCalc. There is no 512-glyph limit here, so braille, the +#: powerline chevrons, and accented Latin are all present. The table comes from +#: ``ter-u12n.bdf`` plus the ``MARKS`` and ``ALIASES`` of the host. If either of them +#: changes, this table must change in the same commit. ``tests/test_emulator.py`` checks +#: the marks, and it checks the font itself where the font is installed. # fmt: off CARDPUTER_RANGES: tuple[tuple[int, int], ...] = ( (0x0020, 0x007E), (0x00A0, 0x017F), (0x0186, 0x0186), (0x018E, 0x0190), @@ -120,12 +125,12 @@ CARDPUTER_RANGES: tuple[tuple[int, int], ...] = ( ) # fmt: on -#: The Cardputer's inventory as one frozen set. +#: The inventory of the Cardputer as one frozen set. CARDPUTER_ZERO_CODEPOINTS: frozenset[int] = frozenset( cp for first, last in CARDPUTER_RANGES for cp in range(first, last + 1) ) -#: Every handheld's glyph inventory, by the name ``Platform.font`` gives it. +#: The glyph inventory of each handheld, by the name that ``Platform.font`` gives it. FONTS: dict[str, frozenset[int]] = { "picocalc-lyra": FONT_CODEPOINTS, "cardputer-zero": CARDPUTER_ZERO_CODEPOINTS, diff --git a/meshterm/ui/oklab.py b/meshterm/ui/oklab.py index c59c86a..75def80 100644 --- a/meshterm/ui/oklab.py +++ b/meshterm/ui/oklab.py @@ -1,19 +1,20 @@ # SPDX-License-Identifier: Apache-2.0 -"""OKLab — the perceptual colour space the UI measures and shades ``#rrggbb`` values in. +"""OKLab: the perceptual colour space in which the UI measures and shades ``#rrggbb`` values. -Where the app has to ask a question about two colours *as the eye sees them* — are these -two chip fills the same to a reader, what is a slightly darker version of this one — it -asks here, not in RGB and not by hue. sRGB is a device encoding: a fixed step in it is a -different size to the eye in every region of the wheel (a step across the greens is a -whisper, the same step across the cyans a shout), and a hue-only comparison is worse, -blind to lightness and saturation altogether. OKLab (Björn Ottosson, 2020) is built so -that Euclidean distance approximates perceived difference and so that changing ``L`` -alone changes lightness and nothing else, which is exactly the two operations wanted. +Sometimes the app must compare two colours as the eye sees them. Two examples: are two +chip fills the same to the user, and what is a slightly darker version of this fill? The +app asks these questions here, not in RGB and not by hue. sRGB is a device encoding. A +fixed step in sRGB has a different size to the eye in each region of the colour wheel. A +step across the greens is small, but the same step across the cyans is large. A +comparison of hue only is worse, because it does not see lightness or saturation at all. +OKLab (Björn Ottosson, 2020) is made so that the Euclidean distance approximates the +perceived difference. It is also made so that a change of ``L`` alone changes the +lightness and nothing else. These are the two operations that the app needs. -Everything is the reference transform, no dependencies: linear sRGB → LMS → cube root → -Lab. ``L`` runs 0 (black) to 1 (white); ``a``/``b`` are the two chroma axes, roughly -±0.4 at the sRGB gamut's edge. A distance of about 0.02 is a just-noticeable difference -between two large patches. +The module uses the reference transform with no dependencies: linear sRGB → LMS → cube +root → Lab. ``L`` runs from 0 (black) to 1 (white). ``a`` and ``b`` are the two chroma +axes, approximately ±0.4 at the edge of the sRGB gamut. A distance of approximately 0.02 +is the smallest difference that a user can see between two large patches. """ from __future__ import annotations @@ -25,20 +26,20 @@ Lab = tuple[float, float, float] def _linear(channel: float) -> float: - """The sRGB transfer function, 0–1 encoded → 0–1 linear.""" + """The sRGB transfer function: 0–1 encoded to 0–1 linear.""" return channel / 12.92 if channel <= 0.04045 else ((channel + 0.055) / 1.055) ** 2.4 def _encoded(channel: float) -> float: - """The inverse: 0–1 linear → 0–1 sRGB encoded.""" + """The inverse function: 0–1 linear to 0–1 sRGB encoded.""" return 12.92 * channel if channel <= 0.0031308 else 1.055 * channel ** (1 / 2.4) - 0.055 def from_hex(colour: str) -> Lab: - """``#rrggbb`` → OKLab. + """Change a ``#rrggbb`` colour to OKLab. Args: - colour: A six-digit hex colour, ``#`` optional, either case. + colour: A six-digit hex colour. The ``#`` is optional. The case does not matter. Raises: ValueError: If the string is not six hex digits. @@ -58,19 +59,19 @@ def from_hex(colour: str) -> Lab: def to_hex(lab: Lab) -> str: - """OKLab → ``#rrggbb``, each channel clipped to the sRGB gamut. + """Change an OKLab colour to ``#rrggbb``. Each channel is clipped to the sRGB gamut. - Clipping is the honest answer for the one caller that can leave the gamut — a - saturated fill darkened at constant chroma pushes a channel below zero — because the - clipped colour is the nearest the terminal can show, and it stays the right hue to - the eye at the shifts the app asks for. + The clip is the correct answer for the one caller that can leave the gamut. A + saturated fill that is darkened at constant chroma pushes a channel below zero. The + clipped colour is the nearest colour that the terminal can show. At the shifts that + the app uses, it also keeps the correct hue to the eye. """ linear = _linear_rgb(lab) return "#" + "".join(f"{round(_encoded(min(1.0, max(0.0, c))) * 255):02x}" for c in linear) def _linear_rgb(lab: Lab) -> tuple[float, float, float]: - """OKLab → linear sRGB. A channel outside 0 to 1 is outside the sRGB gamut.""" + """Change an OKLab colour to linear sRGB. A channel outside 0 to 1 is outside the sRGB gamut.""" lightness, a, b = lab l_ = lightness + 0.3963377774 * a + 0.2158037573 * b m_ = lightness - 0.1055613458 * a - 0.0638541728 * b @@ -84,18 +85,18 @@ def _linear_rgb(lab: Lab) -> tuple[float, float, float]: def _in_gamut(lab: Lab) -> bool: - """Whether the sRGB gamut holds ``lab`` (a very small tolerance for rounding).""" + """Check if the sRGB gamut holds ``lab``. A very small tolerance is for rounding.""" return all(-1e-6 <= channel <= 1 + 1e-6 for channel in _linear_rgb(lab)) def fitted(lab: Lab) -> Lab: """``lab`` with its chroma lowered until the sRGB gamut holds it. - The lightness and the hue do not change. A colour that is already in the gamut comes - back unchanged. Use this instead of the clip in :func:`to_hex` when a set of colours - must stay apart: a dark, saturated colour leaves the gamut, and the clip moves many - such colours to one corner of the gamut. For example, two greens a few steps apart - on the hue wheel both clip to ``#008000``. + The lightness and the hue do not change. A colour that is already in the gamut is + returned unchanged. Use this function instead of the clip in :func:`to_hex` when a set + of colours must stay apart. A dark, saturated colour leaves the gamut, and the clip + moves many such colours to one corner of the gamut. For example, two greens that are + a few steps apart on the hue wheel both clip to ``#008000``. """ if _in_gamut(lab): return lab @@ -111,28 +112,30 @@ def fitted(lab: Lab) -> Lab: def distance(first: str, second: str) -> float: - """Perceived difference between two ``#rrggbb`` colours: Euclidean distance in OKLab. + """The perceived difference between two ``#rrggbb`` colours: the Euclidean distance in OKLab. - ``0`` for the same colour; about ``0.02`` at the threshold of noticing between two - large patches; ``1`` is black to white. + The distance is ``0`` for the same colour. Approximately ``0.02`` is the smallest + difference that a user can see between two large patches. The distance from black to + white is ``1``. """ return math.dist(from_hex(first), from_hex(second)) def shaded(colour: str, by: float, *, floor: float | None = None) -> str: - """``colour`` moved ``by`` in lightness, away from whichever end it is nearer. + """``colour`` moved ``by`` in lightness, away from the end of the scale that is nearer. - A light colour comes back darker and a dark one lighter, at the same chroma, so the - result is recognisably *the same colour, shaded* rather than a different one — the - version of a fill that draws a line on itself. + A light colour is returned darker and a dark colour is returned lighter, at the same + chroma. Thus the user sees the same colour, shaded, and not a different colour. This + is the version of a fill that draws a line on itself. Args: - colour: The ``#rrggbb`` to shade. - by: The lightness shift, in OKLab ``L`` (``0.1`` is a clear step, ``0.25`` bold). - floor: If given, the shift starts from this lightness rather than the colour's - own where that is further along — a caller guaranteeing the result clears a - *second* colour's lightness by ``by`` as well as this one's passes that - colour's ``L``. Read as "at least this far from both". + colour: The ``#rrggbb`` colour to shade. + by: The lightness shift, in OKLab ``L`` (``0.1`` is a clear step, ``0.25`` is bold). + floor: If it is given, the shift starts from this lightness instead of the + lightness of the colour, where this lightness is further along. A caller + that must clear the lightness of a second colour by ``by``, and also that of + this colour, passes the ``L`` of the second colour. The result is at least + this far from both colours. """ lightness, a, b = from_hex(colour) if lightness >= 0.5: diff --git a/meshterm/ui/pathline.py b/meshterm/ui/pathline.py index 20e6b62..72adb0f 100644 --- a/meshterm/ui/pathline.py +++ b/meshterm/ui/pathline.py @@ -1,82 +1,99 @@ # SPDX-License-Identifier: Apache-2.0 -"""Path lines — the flexible hop-sequence text widget (powerline chips or arrows). +"""Path lines: the flexible text widget for a sequence of hops (powerline chips or arrows). -This is the successor to :func:`~meshterm.ui.widgets.path_text` as THE way a hop -sequence renders as text — a trace's walked route, a packet's ``via`` chain, a -message's delivery paths, the composer's preview, a trophy row. Where ``path_text`` -is one fixed presentation (arrow-joined, one line, overflow left entirely to the -caller), a :class:`PathLine` separates *what the hops are* from *how the line is -drawn*, so every surface the survey found can eventually route through it: +This widget is the successor to :func:`~meshterm.ui.widgets.path_text` as the only way +that a sequence of hops renders as text. It is used for the walked route of a trace, the +``via`` chain of a packet, the delivery paths of a message, the preview of the composer, +and a row of the trophy case. ``path_text`` is one fixed presentation: the hops are joined +by arrows, the result is one line, and the caller must handle all overflow. A +:class:`PathLine` separates *what the hops are* from *how the line is drawn*. Thus each +surface that the survey found can in the end use it. -* **Two separator styles.** ``plain`` joins hops with muted ``→`` arrows — today's - look, unchanged. ``powerline`` renders each hop as a colour-filled chip, joined by one - solid triangle U+E0B0 interlocked between them — the chip behind as its foreground, the - chip ahead as its background — so a route reads as a ribbon whose segments meet on a - chevron: the oh-my-posh look, at one cell a seam. The label of a node's chip is its - hash-derived hue (:func:`~meshterm.ui.theme.node_style`), the colour that its name has - on each surface, and the fill is that hue, darker (:data:`CHIP_LIGHTNESS`). Our own - node is the map's yellow ``★`` on a neutral dark grey, a faded hop is dark slate, and a +* **Two separator styles.** ``plain`` joins the hops with muted ``→`` arrows. This is the + look that exists today, without a change. ``powerline`` renders each hop as a chip with + a colour fill. One solid triangle U+E0B0 joins the chips, and it interlocks between + them. The chip behind it is its foreground, and the chip ahead of it is its background. + Thus a route reads as a ribbon whose segments meet on a chevron. This is the oh-my-posh + look, and each seam uses one cell. The label of the chip of a node has the hue that + comes from its hash (:func:`~meshterm.ui.theme.node_style`). This is the colour that its + name has on each surface. The fill is that hue, but darker (:data:`CHIP_LIGHTNESS`). Our + node is the yellow ``★`` of the map on a neutral dark grey. A faded hop is dark slate. A keyless hop is light grey on grey. (On the 16-colour console of the PicoCalc, the fill - is the dim twin of the hue. Refer to :func:`_slot_colours`.) Two chips that - land on the *same* fill — a mirrored return leg, a stretch of keyless greys — or on two - fills too close to tell apart (under :data:`SEAM_BLUR` apart in OKLab, the perceptual - distance :mod:`~meshterm.ui.oklab` measures) take the one exception the interlock can't - draw: the seam is the *thin* chevron instead, in the colour of the previous chip's - label and drawn on the next, so the ribbon runs on unbroken and the - join is a line the chip draws on itself (:meth:`PathLine._seam`). Hops elided out of - the middle break the - ribbon instead of joining it: the mark sits bare on the page between a closing point and - the next chip's notch (:func:`elision_hop`), because a filled ``⋯`` chip would read as a - node by that name. A chip caught by a *cut* — a lane that ran out, a line scrolled past - its edge — breaks off on a half block in its own fill - (:func:`cut_mark`), and that crack is what says the segment continues; only chips - crack, an arrow line still ellipsizes. A line's two *outer* ends read the same way: - a path that begins at its origin and ends at its destination opens and closes flat (a - rounded cap where the font has one), while one drawing only the *middle* of a route — - a packet's ``via`` chain, which names relays and neither of the nodes the packet went - between — wears the chevron at that end instead, the same mark a wrapped line uses for - "there is more of this out there" (``from_origin`` / ``to_destination``). - A row that also carries the app-wide - opens-further-prompts ``…`` hangs it *outside* the budget - (:func:`with_action_mark`) — chrome may not cost the route cells. ``auto`` (the default) - picks powerline exactly when the terminal can draw it - (:func:`~meshterm.ui.termfont.powerline_enabled` — - a recommended font, a glyph-capable renderer, or the user's override) and falls - back to arrows everywhere else, so no terminal ever sees tofu. -* **Three overflow answers**, matching the three patterns the surfaces already use: - :meth:`PathLine.text` is the full one-liner (for callers that crop it with - :func:`cut_to` or read it through a sliding window of their own, each cut edge - marked by :func:`cut_mark`), :meth:`PathLine.ellipsized` fits a width by eliding - hops behind a ``⋯`` mark, on whichever side it is told to eat into - (:data:`ELIDE_TAIL` by default — both endpoints survive, unlike a plain tail - truncation that amputates the destination; :data:`ELIDE_HEAD` where a surface - wants the head given up whole) — and :meth:`PathLine.wrapped` breaks - at hop boundaries under a hanging indent (never mid-name, never mid-chip), - folding where the route *means* something: the fewest lines it can take, evened - out across them rather than greedily crammed, and preferring the seam where the - path fades from composed to mirrored when that fold is free. A caller that doesn't - know its width — a value dropped into a label/value grid — hands the - :class:`PathLine` itself to Rich and gets the wrapped shape at whatever cell width - the layout works out (see :meth:`PathLine.__rich_console__`). -* **The same hop semantics everywhere.** A :class:`PathHop` carries what the app's - conventions need: the label (a name, or a hash standing as identity), the key any - known prefix of which picks the hue, the ``you`` flag, the trace-flavour - ``(3d)`` annotation, the lit-prefix width for hash labels (the - ``highlighted_hash`` two-tone), the ``dim`` fade for resolved return legs, and an - explicit style override for context colourings that outrank identity. Chips keep - the exact same words as arrows — only colours and separators change — so a route - reads identically whichever mode drew it. A surface whose route always starts and - ends on us can ask for ``bare_self``, replacing our name and hash with the app-wide - ``★`` — the reader already knows who both ends are, and the cells belong to the hops - that *are* news. Those stars fade where the route is being *composed* (our two ends - are fixtures, not choices); a surface that only *shows* a walk passes ``dim_self=False`` - and keeps us in the ``you`` white. + is the dim twin of the hue. Refer to :func:`_slot_colours`.) -Existing call sites still render through ``path_text``; migrating them here is a -separate, per-surface pass. The composer's insertion cursor rides along as a hop in -its own right (``cursor=True``, drawn as the :data:`CURSOR_GLYPH` slot): an insertion -point *is* a position in the route, not a gap between two of them, so it measures, -wraps and colours like every other hop — the preview keeps whichever mode the terminal + Sometimes two chips have the *same* fill (a mirrored return leg, or a stretch of + keyless greys). Sometimes they have two fills that are too close to tell apart (less + than :data:`SEAM_BLUR` apart in OKLab, the perceptual distance that + :mod:`~meshterm.ui.oklab` measures). Then the interlock cannot draw the seam, and the + seam is the *thin* chevron instead. It has the colour of the label of the previous chip, + and it is drawn on the next chip. Thus the ribbon continues without a break, and the + join is a line that the chip draws on itself (:meth:`PathLine._seam`). + + Hops that are elided from the middle break the ribbon and do not join it. The mark is + bare on the page, between a closing point and the notch of the next chip + (:func:`elision_hop`). A filled ``⋯`` chip reads as a node with that name. A chip that a + *cut* catches (a lane that ran out, or a line that scrolled past its edge) breaks off on + a half block in its own fill (:func:`cut_mark`). This crack shows that the segment + continues. Only chips crack, and an arrow line still ellipsizes. + + The two *outer* ends of a line read in the same way. A path that begins at its origin and + ends at its destination opens and closes flat (with a rounded cap where the font has + one). A path that draws only the *middle* of a route has the chevron at that end + instead. An example is the ``via`` chain of a packet, which names relays and neither of + the nodes between which the packet went. The chevron is the same mark that a wrapped + line uses for "there is more of this out there" (``from_origin`` and + ``to_destination``). + + A row can also have the ``…`` of the app that shows that the row opens further prompts. + The widget hangs this mark *outside* the budget (:func:`with_action_mark`), because + chrome must not use cells of the route. ``auto`` (the default) picks powerline only when + the terminal can draw it (:func:`~meshterm.ui.termfont.powerline_enabled`: a + recommended font, a renderer that can draw the glyphs, or the override of the user). In + all other cases it uses arrows, so no terminal ever shows tofu. +* **Three answers to overflow.** They match the three patterns that the surfaces already + use: + + * :meth:`PathLine.text` is the full one-line text. It is for callers that crop it with + :func:`cut_to`, or that read it through a sliding window of their own. :func:`cut_mark` + marks each cut edge. + * :meth:`PathLine.ellipsized` fits a width, and it elides hops behind a ``⋯`` mark. It + eats into the side that the caller names. :data:`ELIDE_TAIL` is the default, and both + endpoints stay. A plain truncation of the tail removes the destination, and this + method does not. :data:`ELIDE_HEAD` is for a surface that wants to give up the whole + head. + * :meth:`PathLine.wrapped` breaks at the boundaries of hops, under a hanging indent + (never in the middle of a name, never in the middle of a chip). It folds where the + route has a meaning. It uses the fewest lines that it can, and it makes them even. + It does not pack the lines greedily. When the fold costs nothing, it prefers the seam + where the path changes from composed to mirrored. + + A caller that does not know its width (for example a value in a grid of labels and + values) gives the :class:`PathLine` itself to Rich. It gets the wrapped shape at the + cell width that the layout finds (refer to :meth:`PathLine.__rich_console__`). +* **The same hop semantics everywhere.** A :class:`PathHop` has what the conventions of + the app need: + + * the label (a name, or a hash that stands as the identity), + * the key, of which any known prefix selects the hue, + * the ``you`` flag, + * the ``(3d)`` annotation for traces, + * the width of the lit prefix for hash labels (the two tones of ``highlighted_hash``), + * the ``dim`` fade for resolved return legs, + * an explicit style override for colourings of a context that win over the identity. + + Chips keep exactly the same words as arrows. Only the colours and the separators + change. Thus a route reads the same in each mode. A surface whose route always starts + and ends on us can ask for ``bare_self``. This replaces our name and hash with the + ``★`` of the app. The user already knows who both ends are, and the cells are for the + hops that *are* news. These stars fade where the route is being *composed*, because our + two ends are fixtures and not choices. A surface that only *shows* a walk passes + ``dim_self=False`` and keeps us in the ``you`` white. + +The existing call sites still render through ``path_text``. A separate pass for each +surface will move them here. The insertion cursor of the composer is a hop in its own +right (``cursor=True``, drawn as the :data:`CURSOR_GLYPH` slot). An insertion point *is* a +position in the route, and it is not a gap between two positions. Thus it is measured, +wrapped, and coloured like each other hop. The preview keeps the mode that the terminal earned, and a cursor can never be stranded on a line break. """ @@ -99,63 +116,66 @@ from .marks import SELF_MARK from .termfont import powerline_enabled, powerline_full from .theme import DIM_TWIN, active_theme, node_style, slot_hex -#: The powerline solid right-pointing triangle (U+E0B0) — the glyph the widget draws -#: at every seam and closing edge, deliberately from the *core* set so every recommended -#: font qualifies (the rounded caps at U+E0B4+ exist only in full Nerd Font patches). A -#: path only ever flows one way, so the point only ever faces right; what changes is -#: whether it lands on a field (a seam) or on the page (an edge). +#: The powerline solid right-pointing triangle (U+E0B0). It is the glyph that the widget +#: draws at each seam and closing edge. It is from the *core* set on purpose, so that each +#: recommended font qualifies (the rounded caps at U+E0B4 and later exist only in full Nerd +#: Font patches). A path flows in one direction only, so the point always faces right. What +#: changes is if it lands on a field (a seam) or on the page (an edge). POWERLINE_SEP = "\ue0b0" -#: The thin right-pointing chevron (U+E0B1), the solid point's outline sibling in the -#: same core set — powerline's own mark for a join *inside* one colour. It draws the seam -#: between two chips whose fills the eye can't tell apart (:meth:`PathLine._seam`): the -#: previous fill, shaded, drawn on the next, where a solid point would have vanished. +#: The thin right-pointing chevron (U+E0B1). It is the outline sibling of the solid point, +#: in the same core set. It is the own mark of powerline for a join *inside* one colour. It +#: draws the seam between two chips whose fills the eye cannot tell apart +#: (:meth:`PathLine._seam`). It is the previous fill, shaded, and drawn on the next chip, +#: where a solid point disappears. POWERLINE_THIN = "\ue0b1" -#: The rounded caps (U+E0B6 opening, U+E0B4 closing) that finish a path's two outer -#: ends as a lozenge. These live in the *extended* block, which only a full Nerd Font -#: patch carries (:func:`~meshterm.ui.termfont.powerline_full`) — a terminal with just -#: the core four squares those ends off instead of showing tofu. +#: The rounded caps (U+E0B6 opening, U+E0B4 closing) that finish the two outer ends of a +#: path as a lozenge. They are in the *extended* block, which only a full Nerd Font patch +#: has (:func:`~meshterm.ui.termfont.powerline_full`). A terminal that has only the core +#: four glyphs makes these ends square, and does not show tofu. POWERLINE_ROUND_OPEN = "" POWERLINE_ROUND_CLOSE = "" -#: Our own node, wherever a surface asks for it stripped of name and hash -#: (``bare_self``): the app-wide ``★`` — literally the map's own marker, taken from -#: :data:`~meshterm.ui.marks.SELF_MARK` so the star in a route and the star on the map -#: can never drift apart, in glyph or in hue. +#: Our node, where a surface asks for it without its name and hash (``bare_self``): the +#: ``★`` of the app. It is the own marker of the map, taken from +#: :data:`~meshterm.ui.marks.SELF_MARK`. Thus the star in a route and the star on the map +#: can never be different, in glyph or in hue. SELF_GLYPH, _SELF_INK = SELF_MARK -#: The composer's insertion cursor, standing in the route as a hop of its own: the -#: empty slot the next chosen hop drops into. A ``+`` because that is exactly what -#: Enter does there — and because no node is ever named one, so the slot can't be -#: misread as a hop that is already in the route. +#: The insertion cursor of the composer. It stands in the route as a hop of its own: the +#: empty slot into which the next chosen hop goes. It is a ``+``, because this is what +#: Enter does there. Also, no node has this name, so the user cannot read the slot as a hop +#: that is already in the route. CURSOR_GLYPH = "+" -#: The plain-mode joining arrow, exactly as ``path_text`` draws it today. +#: The arrow that joins hops in plain mode, the same as ``path_text`` draws it today. _ARROW = " → " -#: The theme name a rendered path line wears as its base style: it draws *nothing* and -#: exists to be recognised. Every shape this widget mints is stamped with it (see -#: :meth:`PathLine._render`), so a row that appends a path carries a span saying where the -#: route lies — which is how the cursor row's identity fold knows to spare the hop hues -#: (:func:`~meshterm.ui.tui.render._whiten_identities`) instead of whitening a whole route. +#: The theme name that a rendered path line has as its base style. It draws *nothing*, and +#: it exists so that code can recognize it. Each shape that this widget makes has it (refer +#: to :meth:`PathLine._render`). Thus a row that appends a path has a span that says where +#: the route is. The identity fold of the cursor row uses this to spare the hop hues +#: (:func:`~meshterm.ui.tui.render._whiten_identities`), and it does not make a whole route +#: white. PATH_INK = "pathline" -#: The lightness of a node's chip, as a part of the lightness of its hue (OKLab ``L``). -#: On a truecolor terminal, the fill of a node's chip is its hue with ``L`` multiplied by -#: this value, and the label on it is the hue itself: the colour that the name has in each -#: list and in arrow mode. Thus a node is one colour on each surface, and a chip only puts -#: a darker ground of that colour under it. JP chose this look on the PicoCalc -#: (2026-10-06), where the dim twin of a slot is the same rule at the resolution of the -#: console (:data:`~meshterm.ui.theme.DIM_TWIN`). Its dim twins have 0.55 to 0.73 of the -#: lightness of their bright slots. +#: The lightness of the chip of a node, as a part of the lightness of its hue (OKLab ``L``). +#: On a truecolor terminal, the fill of the chip of a node is its hue with ``L`` multiplied +#: by this value, and the label on it is the hue itself. This is the colour that the name +#: has in each list and in arrow mode. Thus a node has one colour on each surface, and a +#: chip only puts a darker ground of that colour under it. JP chose this look on the +#: PicoCalc (2026-10-06). There, the dim twin of a slot is the same rule at the resolution +#: of the console (:data:`~meshterm.ui.theme.DIM_TWIN`). Its dim twins have 0.55 to 0.73 of +#: the lightness of their bright slots. #: #: The value came from two ladders of rules over twelve hues. A fixed step down in ``L`` -#: made the blue fills almost black, because the blue hue is the darkest on the wheel. -#: One ``L`` for all fills made the blue label hard to read on its fill. ``0.65`` made the -#: blue label weak, and ``0.55`` made the yellow fills dull. The fill also keeps its hue -#: when the darker colour leaves the sRGB gamut: the chroma comes down, refer to -#: :func:`~meshterm.ui.oklab.fitted`. A clip there made the greens near ``0x50`` one colour. +#: made the blue fills almost black, because the blue hue is the darkest on the wheel. One +#: ``L`` for all fills made the blue label hard to read on its fill. ``0.65`` made the blue +#: label weak, and ``0.55`` made the yellow fills dull. The fill also keeps its hue when +#: the darker colour leaves the sRGB gamut, because the chroma comes down (refer to +#: :func:`~meshterm.ui.oklab.fitted`). A clip there made the greens near ``0x50`` one +#: colour. CHIP_LIGHTNESS = 0.60 @@ -166,36 +186,38 @@ def _chip_fill(colour: str) -> str: def _chip_label(fill: str) -> str: - """The label for a chip whose fill is ``fill``: the reverse of :func:`_chip_fill`.""" + """The label for a chip whose fill is ``fill``: the inverse of :func:`_chip_fill`.""" lightness, a, b = oklab.from_hex(fill) return oklab.to_hex(oklab.fitted((min(1.0, lightness / CHIP_LIGHTNESS), a, b))) #: The text of the composer's slot: near-black slate on the white chip. _CHIP_FG = "#0f172a" -#: Chip fill for a keyless hop — the ``faint`` grey; colour stays reserved for -#: keyed identities in chips just as it is in arrow mode. +#: The chip fill for a keyless hop: the ``faint`` grey. Colour is only for identities that +#: have a key, in chips and in arrow mode. _KEYLESS_BG = "#64748b" -#: The label of a keyless chip: the same pair as a node's chip, in grey. +#: The label of a keyless chip: the same pair as the chip of a node, in grey. _KEYLESS_FG = _chip_label(_KEYLESS_BG) -#: Our own node's chip fill: a neutral dark grey, so the yellow ``★`` riding it reads as -#: the map's marker rather than as a node's hue (JP, 2026-08-09). Deliberately *not* a -#: spectrum colour and not the white it used to be — our end of a route is a fixture the -#: reader already knows, so it sits back and lets the hops that differ carry the colour. +#: The chip fill of our node: a neutral dark grey. Thus the yellow ``★`` on it reads as the +#: marker of the map and not as the hue of a node (JP, 2026-08-09). It is *not* a colour +#: of the spectrum on purpose, and it is not the white that it was before. Our end of a +#: route is a fixture that the user already knows. It stays back and lets the hops that +#: differ carry the colour. _YOU_BG = "#3f3f46" -#: A dimmed hop's chip: dark slate fill with muted ink, receding like ``faint`` text. +#: The chip of a dimmed hop: a dark slate fill with muted ink. It recedes like ``faint`` +#: text. _DIM_BG = "#334155" _DIM_FG = "#94a3b8" #: On the 16-colour console, the page: slot 0, black. It is the fill of a chip that the -#: console cannot fill, because the VT has no dark grey background. That chip is our -#: ``★``, a faded hop, or the composer's slot. Its text then sits on the page, and the -#: chips on each side close on a point and open on a notch. +#: console cannot fill, because the VT has no dark grey background. That chip is our ``★``, +#: a faded hop, or the slot of the composer. Its text then sits on the page, and the chips +#: on each side close on a point and open on a notch. _SLOT_PAGE = slot_hex(0) #: On the console, the text of a faded hop: slot 8, the dark grey. _SLOT_FAINT = slot_hex(8) -#: On the console, white: slot 15. It is the text of a keyless chip and of the -#: composer's slot. +#: On the console, white: slot 15. It is the text of a keyless chip and of the slot of the +#: composer. _SLOT_WHITE = slot_hex(15) @@ -213,77 +235,80 @@ class _ChipColours(NamedTuple): soft: str -#: The mark standing in for elided hops (see :meth:`PathLine.ellipsized`) — rendered as -#: a dim pseudo-hop so it recedes in both modes. +#: The mark for elided hops (refer to :meth:`PathLine.ellipsized`). It renders as a dim +#: pseudo-hop, so it recedes in both modes. _ELISION = "⋯" -#: The classic truncation mark, and what an *arrow* line still cuts with: three dots -#: standing where words were. An arrow hop is text, so shortening it is what happened. +#: The classic truncation mark, which an *arrow* line still uses to cut: three dots where +#: words were. An arrow hop is text, so a shorter text is what happened. _ELLIPSIS = "…" -#: The app-wide "this row opens further prompts" mark (see the UX standards), as a *path* -#: row wears it — see :func:`with_action_mark` for why it is spelled here rather than -#: appended by each surface. +#: The mark of the app for "this row opens further prompts" (refer to the UX standards), as +#: a *path* row has it. Refer to :func:`with_action_mark` for the reason that the module +#: spells it here, and each surface does not append it. ACTION_MARK = " …" -#: What a *chip* line cuts with instead (JP, 2026-08-09) — the half block, drawn in the -#: cut chip's own fill with no background, so the cell is half segment and half bare -#: page: the chip breaks off mid-body and the crack says it is incomplete. An ellipsis -#: would claim the opposite, that a *word* was shortened, when what ran out is the lane. -#: :data:`CRACK_TAIL` closes a line the path runs on past (the fill's left half survives, -#: the page takes the right); :data:`CRACK_HEAD` is its mirror, opening a line whose -#: start is off-screen. Only chips crack — :func:`cut_mark` finds a fill or falls back to -#: :data:`_ELLIPSIS`, so arrow lines are untouched by the whole idea. +#: What a *chip* line uses to cut instead (JP, 2026-08-09): the half block. It is drawn in +#: the own fill of the cut chip, with no background. Thus the cell is half segment and +#: half bare page. The chip breaks off in the middle of its body, and the crack says that +#: it is incomplete. An ellipsis says the opposite: that a *word* was made shorter, when +#: what ran out is the lane. :data:`CRACK_TAIL` closes a line past which the path runs on +#: (the left half of the fill stays, and the page takes the right half). +#: :data:`CRACK_HEAD` is its mirror, and it opens a line whose start is off the screen. +#: Only chips crack. :func:`cut_mark` finds a fill, or it uses :data:`_ELLIPSIS`. Thus this +#: idea does not change arrow lines. CRACK_TAIL = "▐" CRACK_HEAD = "▌" -#: Which side of a path an :meth:`PathLine.ellipsized` fit eats into. ``ELIDE_TAIL`` is -#: the route reading — the origin anchors the line, the destination is rescued off the -#: far end, and the mark lands in the middle. ``ELIDE_HEAD`` is the trail reading — the -#: last hop anchors the line and everything before it goes, origin included. +#: The side of a path into which a fit of :meth:`PathLine.ellipsized` eats. ``ELIDE_TAIL`` +#: is the reading for a route. The origin anchors the line, the destination is saved from +#: the far end, and the mark lands in the middle. ``ELIDE_HEAD`` is the reading for a +#: trail. The last hop anchors the line, and everything before it goes, also the origin. ELIDE_TAIL = "tail" ELIDE_HEAD = "head" -#: Extra columns a wrapped line steps in past the hanging indent. The continuation -#: marks (a trailing ``→``, a notched chip edge) say the path goes on; the step says -#: it at a glance, from the shape of the block alone — a route that folds reads as one -#: value that ran long, not as a second value stacked under the first. +#: The extra columns that a wrapped line steps in after the hanging indent. The marks of +#: continuation (a trailing ``→``, a chip edge with a notch) say that the path goes on. +#: The step says it at a glance, from the shape of the block alone. A route that folds +#: reads as one value that ran long, and not as a second value under the first. WRAP_OFFSET = 2 @dataclass(frozen=True) class PathHop: - """One hop of a path line — the semantics, independent of how it is drawn. + """One hop of a path line: the semantics, and not how the hop is drawn. Attributes: - label: What is shown — a resolved name, a hash standing as the node's - identity (set ``lit_bytes`` for the two-tone prefix in that case), or the - bare :data:`SELF_GLYPH` where a surface has no need to name us. - key: Any known prefix of the node's key/hash — picks the hash-derived hue - (its first byte, so every prefix agrees). ``None`` renders muted/grey: - colour is reserved for keyed identities. - you: Our own node. Arrows draw it in the pure-white ``you`` style; chips draw it - in the map's own yellow on the neutral dark grey :data:`_YOU_BG`, padded like - every other chip. - annotation: The trace-flavour hash note, rendered ``" (3d)"`` after the - label in both modes (pass the bare ``3d``, no parentheses). - lit_bytes: For a hash label: leading *bytes* drawn in the hue (the - ``highlighted_hash`` two-tone), the rest muted/soft. ``0`` for names. - dim: Fade the hop (and the arrow leading into it) — a planned route's - resolved return leg, "not yours to compose". - style: Explicit colour override — a hex style (``"#rrggbb"``, attributes - allowed) or theme name — for context colourings that outrank identity. - Plain mode uses it as the label style; powerline as the chip fill. - cursor: This hop is an editor's insertion slot rather than a node — the - :data:`CURSOR_GLYPH` in the app's ``cursor`` white, the same colour the list - cursor (``❯``) below it wears, so the two halves of one gesture (the row - you pick, the slot it lands in) read as one thing. - gap: This hop is a mark standing *between* two nodes rather than being one — the - elision (:func:`elision_hop`). Chips draw it in the break between two - segments, bare on the page with no fill and no padding, because what it says - is "the ribbon stops here and picks up again"; a chip would say the opposite, - that some node in the route is called ``⋯``. Arrow mode needs no special case: - a bare label between two arrows is already exactly that. + label: What the line shows. It is a resolved name, a hash that stands as the + identity of the node (in that case, set ``lit_bytes`` for the prefix in two + tones), or the bare :data:`SELF_GLYPH` where a surface does not need to name us. + key: Any known prefix of the key or hash of the node. It selects the hue that + comes from the hash (its first byte, so each prefix gives the same hue). + ``None`` renders muted and grey, because colour is only for identities that + have a key. + you: Our node. Arrows draw it in the pure-white ``you`` style. Chips draw it in the + own yellow of the map on the neutral dark grey :data:`_YOU_BG`, with padding + like each other chip. + annotation: The hash note for traces. It is rendered ``" (3d)"`` after the label in + both modes (pass the bare ``3d``, without parentheses). + lit_bytes: For a hash label: the leading *bytes* that are drawn in the hue (the two + tones of ``highlighted_hash``). The rest is muted or soft. ``0`` for names. + dim: Fade the hop (and the arrow that leads into it). It is the resolved return leg + of a planned route, which the user does not compose. + style: An explicit colour override. It is a hex style (``"#rrggbb"``, attributes are + permitted) or a theme name. It is for colourings of a context that win over the + identity. Plain mode uses it as the label style, and powerline uses it as the + chip fill. + cursor: This hop is an insertion slot of an editor, and not a node. It is the + :data:`CURSOR_GLYPH` in the ``cursor`` white of the app. The list cursor + (``❯``) below it has the same colour. Thus the two halves of one gesture (the + row that the user selects, and the slot where it lands) read as one thing. + gap: This hop is a mark *between* two nodes, and it is not a node. It is the elision + (:func:`elision_hop`). Chips draw it in the break between two segments, bare on + the page, with no fill and no padding. It says "the ribbon stops here and + continues again". A chip says the opposite: that a node in the route has the + name ``⋯``. Arrow mode does not need a special case, because a bare label + between two arrows is already the same thing. """ label: str @@ -298,17 +323,17 @@ class PathHop: def elision_hop() -> PathHop: - """The mark standing in for hops dropped out of a path's middle (or its head). + """The mark for hops that MeshTerm removed from the middle (or the head) of a path. - THE way to say "hops were left out here", so every surface that shortens a path - agrees on the glyph *and* on the fact that it is a gap rather than a node (see - :attr:`PathHop.gap`). + This is the only way to say "hops were left out here". Thus each surface that makes a + path shorter uses the same glyph, *and* the same fact that it is a gap and not a node + (refer to :attr:`PathHop.gap`). """ return PathHop(_ELISION, dim=True, gap=True) def _style_hex(style: str) -> str | None: - """The ``#rrggbb`` a style string or theme name resolves to, else ``None``.""" + """The ``#rrggbb`` colour to which a style string or theme name resolves, else ``None``.""" for token in reversed(style.split()): if token.startswith("#") and len(token) == 7: return token @@ -321,41 +346,43 @@ def _style_hex(style: str) -> str | None: return None -#: How far apart two chip fills must sit, as the eye measures it, for the seam between -#: them to interlock: closer than this and the solid point would be laid on a field it -#: can't be told from, so the seam is the thin chevron instead (:meth:`PathLine._seam`). -#: The unit is OKLab distance (:func:`~meshterm.ui.oklab.distance`), where ``0.02`` is a -#: just-noticeable difference between two large patches and ``1`` is black to white. +#: The distance that two chip fills must have, as the eye measures it, for the seam between +#: them to interlock. If they are closer than this, the solid point is on a field from +#: which the eye cannot tell it, so the seam is the thin chevron instead +#: (:meth:`PathLine._seam`). The unit is the OKLab distance +#: (:func:`~meshterm.ui.oklab.distance`). ``0.02`` is the smallest difference that a user +#: can see between two large patches, and ``1`` is from black to white. #: -#: The rule it replaced was first key bytes under ``0x10`` apart on the hue wheel (JP, -#: 2026-09-15), which measures ``0.087`` at the median hue but ``0.026`` across the greens -#: and ``0.165`` across the cyans: the wheel is not uniform to the eye, so a hue gap -#: blurred too little there and too much here, and an sRGB distance would only have -#: restated the hue gap (a fixed byte step is a near-constant ``55``–``60`` of 8-bit RGB -#: all the way round). The value was then set by eye on a ladder of the spectrum's own -#: pairs drawn both ways (JP, 2026-09-16), and it sits where the solid point is not just -#: detectable at one cell but *found* without looking for it: ``0.06``, three noticeable -#: differences. Tighter (``0.035``) left wedges a reader had to hunt for; looser -#: (``0.10``) blurred pairs whose point still read plainly; ``0.05`` was a shade too -#: tight. ``0x10`` of green is ``0.026`` and blurs; ``0x10`` of red is ``0.124`` and -#: doesn't; the two greys, ``0.18`` apart, keep their interlock on the metric alone. +#: The rule that this value replaced was first key bytes less than ``0x10`` apart on the +#: hue wheel (JP, 2026-09-15). That rule measures ``0.087`` at the median hue, but ``0.026`` +#: across the greens and ``0.165`` across the cyans. The wheel is not uniform to the eye. +#: Thus a gap of hue blurred too little there and too much here. An sRGB distance only +#: restates the hue gap (a fixed step of one byte is a near-constant ``55`` to ``60`` of 8-bit +#: RGB all the way round). Then JP set the value by eye, on a ladder of the own pairs of the +#: spectrum, drawn in both ways (JP, 2026-09-16). The value is where the solid point is not +#: only visible at one cell, but the user *finds* it without a search: ``0.06``, which is +#: three differences that the user can see. A tighter value (``0.035``) left wedges that +#: the user must search for. A looser value (``0.10``) blurred pairs whose point still read +#: clearly. ``0.05`` was a little too tight. ``0x10`` of green is ``0.026`` and blurs. +#: ``0x10`` of red is ``0.124`` and does not blur. The two greys, which are ``0.18`` apart, +#: keep their interlock by the metric alone. SEAM_BLUR = 0.06 def _fills_blur(before: str, after: str) -> bool: - """Whether two fills are the same to the eye: identical, or under :data:`SEAM_BLUR`.""" + """Check if two fills look the same: identical, or less than :data:`SEAM_BLUR` apart.""" return before == after or oklab.distance(before, after) < SEAM_BLUR -#: A chip's fill, as it appears in a rendered span's style — the ``on #rrggbb`` half. -#: Only :meth:`PathLine._chip` sets a background, which is what makes this the test for -#: "is there a chip here": a seam's point, a notch, and every arrow-mode span carry a +#: The fill of a chip, as it appears in the style of a rendered span: the ``on #rrggbb`` +#: half. Only :meth:`PathLine._chip` sets a background. Thus this is the test for "is there +#: a chip here". The point of a seam, a notch, and each span in arrow mode have a #: foreground alone. _ON_FILL = re.compile(r"\bon\s+(#[0-9a-fA-F]{6})\b") def _fills(line: Text) -> list[str | None]: - """The chip fill under each *character* of a rendered line (``None`` off a chip).""" + """The chip fill under each *character* of a rendered line (``None`` if not on a chip).""" fills: list[str | None] = [None] * len(line.plain) for span in line.spans: style = span.style if isinstance(span.style, str) else str(span.style) @@ -368,7 +395,7 @@ def _fills(line: Text) -> list[str | None]: def _char_of_cell(plain: str, cell: int) -> int: - """The character index a display cell falls in, clamped to the string's ends.""" + """The index of the character in which a display cell falls, limited to the string.""" if cell <= 0: return 0 at = 0 @@ -380,30 +407,32 @@ def _char_of_cell(plain: str, cell: int) -> int: def cut_mark(line: Text, at: int, side: str) -> Text: - """The one cell that says a rendered path line was cut here. + """The one cell that says that a rendered path line was cut here. - A chip caught by the cut breaks off in its own colour (:data:`CRACK_TAIL` / - :data:`CRACK_HEAD`) — half the cell is still segment, half is bare page, so the - reader sees a chip that *continues* rather than a route that ended. A line drawn in - arrows has no fill to shear, so it cuts the classic way, with :data:`_ELLIPSIS`; that - fallback is the whole mode test, and it costs the caller nothing to ask for. + A chip that the cut catches breaks off in its own colour (:data:`CRACK_TAIL` and + :data:`CRACK_HEAD`). Half of the cell is still segment, and half is bare page. Thus the + user sees a chip that *continues*, and not a route that ended. A line that is drawn in + arrows has no fill to shear, so it cuts the classic way, with :data:`_ELLIPSIS`. This + fallback is the whole test of the mode, and the caller has no cost to ask for it. - The fill is read from the nearest cell *inside* the line — scanning back from ``at`` - for a tail cut, forward for a head cut — so a cut landing on a seam or on the closing - edge still cracks in the colour of the chip the reader can see, not in nothing. + The function reads the fill from the nearest cell *inside* the line. For a tail cut it + scans back from ``at``, and for a head cut it scans forward. Thus a cut that lands on a + seam or on the closing edge still cracks in the colour of the chip that the user can + see, and not in nothing. Args: - line: The rendered line being cut (whole, unshifted — cells are absolute). - at: The cell index of the nearest *visible* cell on the mark's side: the last - one still drawn for :data:`ELIDE_TAIL`, the first for :data:`ELIDE_HEAD`. - side: Which end of the line the mark closes — :data:`ELIDE_TAIL` (the path runs + line: The rendered line that MeshTerm cuts (whole, not shifted, with absolute cells). + at: The index of the nearest *visible* cell on the side of the mark. For + :data:`ELIDE_TAIL` it is the last cell that is still drawn. For + :data:`ELIDE_HEAD` it is the first. + side: The end of the line that the mark closes. :data:`ELIDE_TAIL` (the path runs on to the right) or :data:`ELIDE_HEAD` (it began off to the left). Returns: The styled single cell, ready to append or prepend. """ fills = _fills(line) - if not fills: # nothing drawn to shear — a caller cutting an empty line + if not fills: # there is nothing drawn to shear: a caller cut an empty line return Text(_ELLIPSIS, style="muted") index = _char_of_cell(line.plain, at) steps = range(index, len(fills)) if side == ELIDE_HEAD else range(index, -1, -1) @@ -414,27 +443,29 @@ def cut_mark(line: Text, at: int, side: str) -> Text: def with_action_mark(line: Text, width: int) -> Text: - """``line`` plus the opens-further-prompts ``…`` — riding *past* the width budget. + """``line`` plus the ``…`` for "opens further prompts". The mark goes *past* the width budget. - The mark says what Enter on the row does. It is not part of the path, so it must not - cost the path a cell: reserving room for it up front made a route that fitted its lane - exactly crack on its last chip (JP, 2026-08-10), so the row claimed the walk ran on - when the walk had in fact finished — the crack only replaces the closing cap, and the - two cells the mark wanted were the two the reader lost. + The mark says what Enter does on the row. It is not part of the path, so it must not + cost the path a cell. If the function kept room for it first, a route that fitted its + lane exactly cracked on its last chip (JP, 2026-08-10). Then the row claimed that the + walk ran on, when the walk was in fact finished. The crack replaces only the closing + cap, and the two cells that the mark needed were the two cells that the user lost. - So the path is fitted to the *whole* lane first and the mark lands in whatever is left - over; where nothing is left, it simply isn't drawn. Losing it costs the reader a hint - the row's own behaviour gives them the moment they press Enter; losing the tail of a - hop costs them the route. That is the widget's default answer wherever a path row - carries the mark, not one surface's local trade — pass the *fitted* line here (after - :func:`cut_to` or after a scroll window) and let the leftovers decide. + So the path is fitted to the *whole* lane first, and the mark lands in the space that + is left. If no space is left, the function does not draw the mark. If the user loses + the mark, the user loses a hint that the behaviour of the row gives when the user + presses Enter. If the user loses the tail of a hop, the user loses the route. This is + the default answer of the widget in each place where a path row has the mark. It is not + a local trade of one surface. Pass the *fitted* line here (after :func:`cut_to` or after + a scroll window), and let the space that is left decide. Args: line: The path line, already fitted to ``width``. - width: The lane's cell budget. + width: The budget of cells for the lane. Returns: - The line with the mark appended, or unchanged when the lane has no room for it. + The line with the mark appended, or the line unchanged when the lane has no room + for the mark. """ if line.cell_len + cell_len(ACTION_MARK) > width: return line @@ -444,21 +475,21 @@ def with_action_mark(line: Text, width: int) -> Text: def cut_to(line: Text, width: int, *, action: bool = False) -> Text: - """Fit a rendered path line to ``width`` by cutting its tail — cracked, not elided. + """Fit a rendered path line to ``width`` by a cut of its tail. The cut cracks, not elides. - The drop-in for ``Text.truncate(width, overflow="ellipsis")`` wherever the line being - cut is a path: the body is cropped a cell short and the freed cell carries - :func:`cut_mark`, so chips break off in their own colour and arrow lines end in the - same ``…`` they always did. A line that already fits comes back untouched. + This function replaces ``Text.truncate(width, overflow="ellipsis")`` where the line + that MeshTerm cuts is a path. The function crops the body one cell short, and the free + cell has :func:`cut_mark`. Thus chips break off in their own colour, and arrow lines + end in the same ``…`` as always. A line that already fits is returned unchanged. Args: line: The rendered line to fit. - width: The cell budget. - action: Append the opens-further-prompts mark afterwards, free of the budget - (:func:`with_action_mark`) — for a row Enter opens something from. + width: The budget of cells. + action: Append the mark for "opens further prompts" afterwards, outside the budget + (:func:`with_action_mark`). It is for a row from which Enter opens something. Returns: - A line no wider than ``width``. + A line that is not wider than ``width``. """ if width <= 0: return Text() @@ -473,21 +504,22 @@ def cut_to(line: Text, width: int, *, action: bool = False) -> Text: def hops_atom(count: int) -> Text: - """The hop count, as the stats line hanging under a path line spells it. + """The hop count, as the line of statistics under a path line spells it. - Wherever a surface hangs stats under a path, the number of hops is one of them (JP, - 2026-08-10): it is the figure the picture above encodes but never states, the one two - routes are most often compared on, and the one a reader would otherwise have to count - chips to get. ``direct`` where there are none — a path with no relays isn't "0 hops", - it is the app's own word for a frame that went straight there (:class:`PathLine`'s - own ``empty`` note says exactly that). + Where a surface puts statistics under a path, the number of hops is one of them (JP, + 2026-08-10). The picture above encodes this number but never states it. Users often + compare two routes by this number, and without it the user must count the chips. The + text is ``direct`` where there are no hops. A path with no relays is not "0 hops". It + is the own word of the app for a packet that went straight there (the ``empty`` note + of :class:`PathLine` says the same). Args: - count: How many *relay* hops the route took (endpoints excluded — us and the far - node are on every route here, so counting them would say nothing). + count: The number of *relay* hops that the route took. The endpoints are not + counted. Us and the far node are on each route here, so a count of them says + nothing. Returns: - The muted atom, ready to join a ``·`` chain. + The muted atom, ready to join a chain of ``·``. """ if count <= 0: return Text("direct", style="muted") @@ -495,27 +527,28 @@ def hops_atom(count: int) -> Text: class PathLine: - """A hop sequence, renderable as arrow-joined text or powerline chips. + """A sequence of hops that renders as text joined by arrows, or as powerline chips. - Build one from :class:`PathHop` entries, then ask for the shape the surface - needs: :meth:`text` (full line), :meth:`ellipsized` (middle-elided to a width), - or :meth:`wrapped` (hop-boundary lines under a hanging indent). + Build one from :class:`PathHop` entries. Then ask for the shape that the surface + needs: :meth:`text` (the full line), :meth:`ellipsized` (elided in the middle to a + width), or :meth:`wrapped` (lines that break at hop boundaries, under a hanging + indent). Args: - hops: The hops in display order (the widget never reorders; a reversed or - mirrored walk is the caller's composition). - mode: ``"auto"`` (powerline when the terminal can draw it — the default), + hops: The hops in the order of display. The widget never changes the order. A + reversed or mirrored walk is the composition of the caller. + mode: ``"auto"`` (powerline when the terminal can draw it, the default), ``"powerline"``, or ``"plain"``. - separator: The plain-mode joiner. Defaults to the app-wide ``" → "``; a - surface with its own convention (the mesh walk trail's ``" › "``) may pass - it. Ignored by powerline mode. - empty: The muted text a hopless path reads as (``"direct"``). - from_origin: The first hop *is* the route's origin. Clear it where the line - draws only the middle of a route — a packet's ``via`` chain names its - relays and neither the node that sent it nor the one that received it — and - the head is drawn as a continuation instead of as a beginning. - to_destination: The last hop *is* the route's destination. Clear it under the - same reading at the other end. + separator: The joiner for plain mode. The default is the ``" → "`` of the app. A + surface that has its own convention (the trail of the mesh walk uses + ``" › "``) can pass it. Powerline mode ignores it. + empty: The muted text that a path with no hops reads as (``"direct"``). + from_origin: The first hop *is* the origin of the route. Clear it where the line + draws only the middle of a route. (The ``via`` chain of a packet names its + relays, and neither the node that sent it nor the node that received it.) + Then the head is drawn as a continuation and not as a beginning. + to_destination: The last hop *is* the destination of the route. Clear it in the + same case, at the other end. """ def __init__( @@ -528,9 +561,9 @@ class PathLine: from_origin: bool = True, to_destination: bool = True, ) -> None: - """Hold the hops and the drawing choices; nothing is measured or drawn yet. + """Hold the hops and the drawing choices. MeshTerm does not measure or draw yet. - Every argument is described in the class docstring above. + The class docstring above describes each argument. """ self._hops = list(hops) self._mode = mode @@ -541,13 +574,13 @@ class PathLine: @property def hops(self) -> list[PathHop]: - """The hops, for callers that splice lines together (endpoints + relays).""" + """The hops, for callers that join lines (endpoints and relays).""" return list(self._hops) # --- the three shapes --------------------------------------------------------- def text(self) -> Text: - """The full one-line rendering; overflow is the caller's call, per surface. + """The full one-line rendering. For overflow, the caller decides for each surface. Returns: A one-line :class:`Text` (the ``empty`` note when there are no hops). @@ -557,40 +590,40 @@ class PathLine: return self._render(self._hops) def ellipsized(self, width: int, *, elide: str = ELIDE_TAIL) -> Text: - """The line fitted to ``width`` by eliding hops behind a ``⋯`` mark. + """The line fitted to ``width`` by the elision of hops behind a ``⋯`` mark. - ``elide`` names the *side* the mark eats into — which end of the path pays for - the overflow: + ``elide`` names the *side* into which the mark eats. It decides which end of the + path pays for the overflow: - * :data:`ELIDE_TAIL` (the default) anchors the line on its head: the origin - holds and hops go from the tail end. The destination is rescued out of that - side along with as much of the run before it as fits, so the ``⋯`` settles in - the *middle* and both endpoints survive — a route reads origin and - destination first, and a plain right-truncation would amputate the second. - The origin is only given up if even that won't fit, and a lone over-long hop - is cut where the width runs out as the last resort (:func:`cut_to` — a chip - cracks off in its own colour, an arrow line ellipsizes). - * :data:`ELIDE_HEAD` anchors the line on its tail: the last hop holds and hops - go from the head end, the origin among them, with no endpoint rescued. A - breadcrumb trail's news is where the walk *is*; where it set out from is - exactly the part worth losing. + * :data:`ELIDE_TAIL` (the default) anchors the line on its head. The origin stays, + and hops go from the tail end. The function saves the destination from that side, + with as much of the run before it as fits. Thus the ``⋯`` settles in the + *middle*, and both endpoints stay. A route reads the origin and the destination + first, and a plain truncation on the right removes the second. The function gives + up the origin only if even this does not fit. As the last resort, a single hop + that is too long is cut where the width runs out (:func:`cut_to`: a chip cracks + off in its own colour, and an arrow line ellipsizes). + * :data:`ELIDE_HEAD` anchors the line on its tail. The last hop stays, and hops go + from the head end, with the origin among them. The function saves no endpoint. The + news of a breadcrumb trail is where the walk *is*. Where it started is the part + that is best to lose. Args: - width: The cell budget the returned line must fit in. - elide: Which side the ``⋯`` eats into — :data:`ELIDE_TAIL` (the default, - keeping both endpoints) or :data:`ELIDE_HEAD` (keeping the tail alone). + width: The budget of cells in which the returned line must fit. + elide: The side into which the ``⋯`` eats. :data:`ELIDE_TAIL` (the default) + keeps both endpoints, and :data:`ELIDE_HEAD` keeps the tail alone. Returns: - A one-line :class:`Text` no wider than ``width``. + A one-line :class:`Text` that is not wider than ``width``. """ full = self.text() if full.cell_len <= width or not self._hops: return full mark = elision_hop() count = len(self._hops) - # The heads worth trying, most-rescued first: a tail-side elision spares the - # origin while it fits and gives it up only when it must; a head-side one is - # eating the head on purpose, so it never spares it at all. + # The heads to try, with the most saved first. An elision on the tail side spares + # the origin while it fits, and gives it up only when it must. An elision on the + # head side eats the head on purpose, so it never spares the origin. for head in (0,) if elide == ELIDE_HEAD else (1, 0): for tail in range(count - 1 - head, 0, -1): kept = self._hops[:head] + [mark] + self._hops[-tail:] @@ -601,31 +634,31 @@ class PathLine: return cut_to(last, width) def wrapped(self, width: int, *, indent: int = 0) -> list[Text]: - """The line broken at hop boundaries, hanging under ``indent`` columns. + """The line broken at hop boundaries, with a hanging indent of ``indent`` columns. - The hanging-indent convention: the caller lays its label lane on the first - line, so that line is returned *without* the indent prefix while every - continuation starts with ``indent`` spaces — plus :data:`WRAP_OFFSET`, the - step that makes a fold legible as a fold. Every line fits ``width``. - Plain-mode lines that - continue end with the separator's own mark — a trailing ``→`` for an - arrow-joined path, the bare ``,`` for a comma-joined wire spec — the "path - goes on" cue; chip lines always close with their pointed edge and, from the - second line down, open by redrawing the seam the break interrupted — the point - arriving out of the previous line's last fill — so a continuation is never - mistakable for a path starting over. A single hop wider than the content column - stands alone, cut to it by :func:`cut_to`: a chip breaks off on the crack, an - arrow hop ellipsizes. + This follows the convention of the hanging indent. The caller puts its label lane + on the first line, so the function returns that line *without* the indent prefix. + Each continuation starts with ``indent`` spaces, plus :data:`WRAP_OFFSET`. This step + makes a fold clear as a fold. Each line fits in ``width``. - Where the breaks fall is chosen for how it *reads* (see :meth:`_flow` and - :meth:`_turn_seam`), not by cramming each line full: the fold takes the - fewest lines the hops allow, spread evenly across them, and lands on the - route's turn — where a leg gives way to its mirrored return — when folding - there costs no extra line. + Plain-mode lines that continue end with the own mark of the separator: a trailing + ``→`` for a path that arrows join, or the bare ``,`` for a wire spec that commas + join. This is the cue "the path goes on". Chip lines always close with their pointed + edge. From the second line down, they open when they draw again the seam that the + break interrupted: the point that arrives out of the last fill of the previous line. + Thus the user can never mistake a continuation for a path that starts again. A + single hop that is wider than the content column stands alone, and :func:`cut_to` + cuts it to the column: a chip breaks off at the crack, and an arrow hop ellipsizes. + + MeshTerm chooses where the breaks fall by how the result *reads* (refer to + :meth:`_flow` and :meth:`_turn_seam`), and does not pack each line full. The fold + takes the fewest lines that the hops allow, and spreads the hops evenly across them. + It lands on the turn of the route, where a leg gives way to its mirrored return, + when a fold there costs no extra line. Args: - width: The full line budget, indent included. - indent: The hanging-indent column the continuations align under. + width: The full budget of the line, with the indent. + indent: The column of the hanging indent, under which the continuations align. Returns: The lines, in order (a single ``empty`` note when there are no hops). @@ -634,17 +667,17 @@ class PathLine: return [Text(self._empty, style="muted")] budget = max(1, width - indent) plain = self._resolved_mode() != "powerline" - # The continuation cue is the separator's own mark, minus the space the next - # hop would have sat in: " → " reads " →", a wire spec's "," stays ",". + # The continuation cue is the own mark of the separator, without the space where the + # next hop sat: " → " reads " →", and the "," of a wire spec stays ",". cue = self._separator.rstrip() if plain else "" groups = self._flow(self._hops, budget, plain, len(cue), 0) seam = self._turn_seam() if seam is not None and len(groups) > 1: - # The outbound leg's own last line still continues into the return, so it - # holds the cue back where the whole path's final line doesn't. + # The last line of the outbound leg still continues into the return, so it + # keeps the cue, but the final line of the whole path does not. legs = self._flow(self._hops[:seam], budget, plain, len(cue), len(cue), ends=False) legs += self._flow(self._hops[seam:], budget, plain, len(cue), 0, carry_in=True) - if len(legs) <= len(groups): # the turn folds for free — take it + if len(legs) <= len(groups): # the fold at the turn costs nothing, so use it groups = legs lines: list[Text] = [] @@ -657,9 +690,10 @@ class PathLine: carry_in=bool(i), carry_on=i < len(groups) - 1, ) - # A lone hop too wide for the column is truncated — leaving room for the - # cue it still has to carry, so even that line stays inside the width. A - # column too narrow to hold both drops the cue: content wins the cells. + # MeshTerm truncates a lone hop that is too wide for the column. It leaves room + # for the cue that the line must still carry, so that line also stays inside the + # width. If the column is too narrow for both, the line drops the cue, because + # content wins the cells. continues = i < len(groups) - 1 and 0 < cell_len(cue) < budget room = budget - step - (cell_len(cue) if continues else 0) if body.cell_len > room: @@ -670,29 +704,29 @@ class PathLine: lines.append(line) return lines - # --- the shape a Rich layout asks for ----------------------------------------- + # --- the shape that a Rich layout asks for ------------------------------------ def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult: - """Render into a Rich layout — a table cell, a group — as the wrapped shape. + """Render into a Rich layout (a table cell, a group) as the wrapped shape. - The one shape a caller doesn't have to size itself. Dropped straight into a - label/value grid (the packet viewer's ``via`` row), the line folds at hop - boundaries to whatever cell width the layout works out for the value column, - hanging its continuations under the value block exactly as :meth:`wrapped` - lays them out — so a surface whose lane width is decided *by* the other rows - never has to compute it twice. A caller that already knows its width still - asks for a shape directly. + This is the one shape for which the caller does not have to find the size. The + caller can put the line directly into a grid of labels and values (the ``via`` row + of the packet viewer). The line folds at hop boundaries to the cell width that the + layout finds for the value column. It hangs its continuations under the value block + in the same way as :meth:`wrapped` lays them out. Thus a surface whose lane width + depends on the other rows does not have to compute it twice. A caller that already + knows its width can still ask for a shape directly. """ yield from self.wrapped(max(1, options.max_width)) def __rich_measure__(self, console: Console, options: ConsoleOptions) -> Measurement: - """How wide the line wants to be: the whole one-liner, down to one hop's cells. + """The width that the line wants: from the whole one-line text down to the cells of one hop. - The maximum is the unwrapped line — given the room, a route reads best without - folding at all. The minimum is the widest single hop plus the chrome every line - carries (a chip's closing edge, a continuation's reopened seam, the - :data:`WRAP_OFFSET` step): below that no column can hold a hop whole, so a - narrower lane is the layout choosing to crop rather than to wrap. + The maximum is the unwrapped line. If there is room, a route reads best without a + fold. The minimum is the widest single hop plus the chrome that each line has (the + closing edge of a chip, the seam that a continuation opens again, and the + :data:`WRAP_OFFSET` step). Below this value, no column can hold a hop whole. Thus a + narrower lane means that the layout chooses to crop and not to wrap. """ full = self.text().cell_len if not self._hops: @@ -708,26 +742,27 @@ class PathLine: def _measure( self, hops: list[PathHop], plain: bool ) -> tuple[list[int], int, int, int, int, int]: - """Each hop's own width, plus what joining, opening and closing a line costs. + """The width of each hop, plus the cost to join, open, and close a line. - Fitting hops to a column is arithmetic once every hop has been measured once — - which matters because :meth:`_flow` tries a whole series of columns, and the - screens re-fit on every repaint (a spinner tick included). + After MeshTerm measures each hop one time, the fit of hops to a column is + arithmetic. This is important because :meth:`_flow` tries a whole series of columns, + and the screens fit again at each repaint (also at the tick of a spinner). Args: hops: The hops to measure, in order. - plain: Measure as arrow text rather than as chips. + plain: Measure as text with arrows and not as chips. Returns: - ``(cells, join, tail, lead, head, foot)`` — each hop's cells, the cells one - join between two hops costs (chip mode's seam is the single interlocked - chevron — and so is either side of an elision gap, so the figure holds there - too), the cells a line the path *runs on past* closes with (chip mode's - point; nothing in arrow mode), the cells every line *after the first* opens - with (chip mode's notch, the seam redrawn), and the two outer caps: what the - *first* line opens with and what the line that *ends* the path closes with — - one cell each where the font has the rounded caps, nothing where it hasn't, - a squared end being drawn by appending nothing at all. + ``(cells, join, tail, lead, head, foot)``. These are the cells of each hop. Then + the cells that one join between two hops costs. (In chip mode, the seam is the + single interlocked chevron. This is also true on each side of an elision gap, so + the figure is correct there too.) Then the cells with which a line closes, when + the path *runs on past* it (the point in chip mode, and nothing in arrow mode). + Then the cells with which each line *after the first* opens (the notch in chip + mode, which is the seam drawn again). The last two are the outer caps: what the + *first* line opens with, and what the line that *ends* the path closes with. + Each is one cell where the font has the rounded caps and nothing where it does + not have them. MeshTerm draws a square end when it appends nothing. """ if plain: plain_cells = [self._plain_hop(hop).cell_len for hop in hops] @@ -740,10 +775,10 @@ class PathLine: ] sep = cell_len(POWERLINE_SEP) cap = cell_len(POWERLINE_ROUND_OPEN) if powerline_full() else 0 - # An end the route runs on past costs its chevron whatever the font can draw: - # the point and the notch are core glyphs, and it is the *cap* that is optional. - # So a relays-only line is measured a cell wider at that end than a whole route - # is on a terminal with no rounded caps to spend. + # An end that the route runs on past costs its chevron, for any font. The point and + # the notch are core glyphs, and the *cap* is optional. Thus a line with only relays + # is a cell wider at that end than a whole route, on a terminal that has no rounded + # caps. head = cap if self._from_origin else sep foot = cap if self._to_destination else sep return widths, sep, sep, sep, head, foot @@ -761,30 +796,33 @@ class PathLine: foot: int = 0, ends: bool = True, ) -> list[int]: - """Pack hop widths into lines of ``budget`` cells, greedily, never splitting one. + """Pack the hop widths into lines of ``budget`` cells. It is greedy and never splits a hop. Args: - cells: Each hop's width, in order (see :meth:`_measure`). - join: Cells one join between two hops costs. - tail: Cells a line the path runs on past closes with. - budget: The content column's width in cells. - reserve: Cells held back on a line for the continuation cue it will carry. - last: Cells held back on a line ending at the *final* hop — ``0`` when the - path really ends there (nothing follows to cue), ``reserve`` when this - is only one leg of a path that goes on. - lead: Cells every line but the first opens with — the reopened seam plus - the :data:`WRAP_OFFSET` step it hangs past the indent. - head: Cells the first line opens with (the rounded cap, when drawn). - foot: Cells the line that *ends the path* closes with (the rounded cap, when - drawn) — charged in place of ``tail``, a finished path closing on a cap - or, where the font has none, on nothing at all. + cells: The width of each hop, in order (refer to :meth:`_measure`). + join: The cells that one join between two hops costs. + tail: The cells with which a line closes, when the path runs on past it. + budget: The width of the content column in cells. + reserve: The cells that the function keeps on a line for the continuation cue + that the line will have. + last: The cells that the function keeps on a line that ends at the *final* hop. + It is ``0`` when the path really ends there (nothing follows, so there is + no cue). It is ``reserve`` when this is only one leg of a path that goes on. + lead: The cells with which each line but the first opens: the seam that opens + again, plus the :data:`WRAP_OFFSET` step by which it hangs past the indent. + head: The cells with which the first line opens (the rounded cap, when it is + drawn). + foot: The cells with which the line that *ends the path* closes (the rounded + cap, when it is drawn). The function charges it instead of ``tail``. A + finished path closes on a cap, or on nothing at all where the font has no + cap. ends: These hops finish the path, so their last line pays ``foot``. ``False`` - where they are one leg of a route that goes on and every line, the last - included, still closes on the point. + where they are one leg of a route that goes on. Then each line, also the + last, still closes on the point. Returns: - How many hops each line takes; a hop too wide for ``budget`` gets a line of - its own (the caller truncates it). + The number of hops that each line takes. A hop that is too wide for ``budget`` + gets a line of its own (the caller truncates it). """ sizes: list[int] = [] count = 0 @@ -812,32 +850,34 @@ class PathLine: carry_in: bool = False, ends: bool = True, ) -> list[list[PathHop]]: - """Break ``hops`` into the fewest lines, then even those lines out. + """Break ``hops`` into the fewest lines, then make those lines even. - Greedy packing alone widows the tail: a route whose last hop misses the first - line by a cell or two strands ``us`` alone underneath a full one. Since the - line *count* is what costs screen rows — and greedy already achieves the - minimum — the same count is re-packed at the narrowest column that still - needs it, which spreads the hops across the lines instead of cramming the - first and starving the last (``us → a → b → c →`` / ``us`` becomes - ``us → a →`` / ``b → c → us``). + Greedy packing alone leaves a widow at the tail. If the last hop of a route misses + the first line by a cell or two, ``us`` is alone under a full line. The *number* of + lines costs screen rows, and greedy packing already gives the minimum. Thus the + function packs the same number of lines again, at the narrowest column that still + needs it. This spreads the hops across the lines, and it does not pack the first + line full and starve the last. For example, ``us → a → b → c →`` / ``us`` becomes + ``us → a →`` / ``b → c → us``. Args: hops: The hops to break up, in order. - budget: The content column's width in cells. - plain: Render as arrows rather than chips. - reserve: Cells held back on a line for the continuation cue it carries. - last: Cells held back on the line the hops end on (see :meth:`_fill`). - carry_in: These hops are a *later* leg of a path already under way, so - even their first line opens as a continuation, not as a beginning. + budget: The width of the content column in cells. + plain: Render as arrows and not as chips. + reserve: The cells that the function keeps on a line for the continuation cue + that the line has. + last: The cells that the function keeps on the line on which the hops end + (refer to :meth:`_fill`). + carry_in: These hops are a *later* leg of a path that is already in progress. + Thus their first line also opens as a continuation, and not as a beginning. ends: These hops finish the path, so their last line closes on the outer cap - rather than on the continuation point (see :meth:`_fill`). + and not on the continuation point (refer to :meth:`_fill`). Returns: - The hops grouped per line. + The hops, grouped for each line. """ cells, join, tail, lead, head, foot = self._measure(hops, plain) - lead += WRAP_OFFSET # every continuation steps in past the hanging indent + lead += WRAP_OFFSET # each continuation steps in past the hanging indent if carry_in: head = lead @@ -846,7 +886,7 @@ class PathLine: lines = len(fill(budget)) low, high = 1, budget - while low < high: # the narrowest column still taking `lines` rows + while low < high: # the narrowest column that still takes `lines` rows mid = (low + high) // 2 if len(fill(mid)) <= lines: high = mid @@ -860,25 +900,25 @@ class PathLine: return groups def _turn_seam(self) -> int | None: - """The hop index a fold would read best at — where the route turns — or ``None``. + """The index of the hop where a fold reads best, where the route turns, or ``None``. - Two things mark a turn. A dimmed *tail* is one: the composed outbound leg ends - and the mirrored return begins (see :attr:`PathHop.dim`). It is read as the run - of faded hops that reaches the end of the line, not merely the first faded hop — - a route's opening ``★`` fades too (setting out from us is nobody's choice - either), and that lone fixture at the head marks nothing. A walked boomerang is - the other — nothing is dimmed once a trace has actually answered, but the hop - sequence is its own mirror, so its middle *is* that same turn; folding the plan - and the walk that answered it in the same place keeps the two readings of one - route looking like one route. Either way the fold needs real legs on both - sides — at least two hops each — so a path whose only faded tail is the - automatic landing back on us never widows it onto a line of its own; that lone - hop marks no turn, and the walk's own mirror still gets to name one. + Two things mark a turn. One is a dimmed *tail*: the composed outbound leg ends and + the mirrored return begins (refer to :attr:`PathHop.dim`). The function reads it as + the run of faded hops that reaches the end of the line, and not only the first faded + hop. The opening ``★`` of a route also fades (nobody chooses to set out from us + either), and that single fixture at the head marks nothing. The other is a walked + boomerang. Nothing is dimmed after a trace has answered, but the sequence of hops is + its own mirror, so its middle *is* the same turn. If the plan and the walk that + answered it fold in the same place, the two readings of one route look like one + route. In both cases, the fold needs real legs on both sides, with at least two hops + each. Thus a path whose only faded tail is the automatic return to us never leaves + that hop as a widow on a line of its own. That single hop marks no turn, and the own + mirror of the walk can still name one. """ seam: int | None = len(self._hops) while seam and self._hops[seam - 1].dim: seam -= 1 - if seam == len(self._hops): # nothing faded at the tail + if seam == len(self._hops): # nothing is faded at the tail seam = None if seam is None or len(self._hops) - seam < 2: marks = [(hop.label, hop.annotation) for hop in self._hops] @@ -891,7 +931,7 @@ class PathLine: # --- rendering ---------------------------------------------------------------- def _resolved_mode(self) -> str: - """The effective mode: ``auto`` resolves against the terminal's verdict.""" + """The effective mode: ``auto`` resolves with the verdict for the terminal.""" if self._mode != "auto": return self._mode return "powerline" if powerline_enabled() else "plain" @@ -904,18 +944,18 @@ class PathLine: carry_in: bool = False, carry_on: bool = False, ) -> Text: - """Join ``hops`` in the effective mode, marked as a path line. + """Join ``hops`` in the effective mode, and mark the result as a path line. - The two carry flags mark a wrapped line's ends and only mean anything to - chips; arrow mode says the same thing with the trailing cue. + The two carry flags mark the ends of a wrapped line. They have a meaning only for + chips. Arrow mode says the same thing with the trailing cue. - Every shape leaves through here, so this is where the line stamps its own extent: - the returned text's base style is :data:`PATH_INK`, which draws nothing and says - "these cells are a route". A row that appends it (``Text.append_text``) carries - that stamp along as a span over the hops, and the cursor row's identity fold reads - it there — see :func:`~meshterm.ui.tui.render._whiten_identities`. Inside a path - line the hue is not decoration on a name, it is what tells one hop from the next, - so the highlight lights the row without eating it. + Each shape leaves through this function, so here the line stamps its own extent. The + base style of the returned text is :data:`PATH_INK`, which draws nothing and says + "these cells are a route". A row that appends it (``Text.append_text``) carries that + stamp as a span over the hops, and the identity fold of the cursor row reads it there + (refer to :func:`~meshterm.ui.tui.render._whiten_identities`). In a path line, the + hue is not a decoration on a name. It shows the difference between one hop and the + next. Thus the highlight lights the row and does not remove the hues. """ if not force_plain and self._resolved_mode() == "powerline": line = self._render_chips(hops, carry_in=carry_in, carry_on=carry_on) @@ -927,16 +967,16 @@ class PathLine: def _render_plain( self, hops: list[PathHop], *, carry_in: bool = False, carry_on: bool = False ) -> Text: - """Arrow-joined hops — ``path_text``'s presentation, hop by hop. + """The hops, joined by arrows: the presentation of ``path_text``, hop by hop. - An end the route runs on past wears the separator with nothing on the far side - of it: a leading ``→`` where the origin isn't drawn, a trailing one where the - destination isn't. Arrow mode already spells "the path goes on" with that - trailing mark when a line wraps, so a chain of relays says it the same way — - which is what keeps the two modes telling the reader the same thing on a console - with no chevrons to shear (see :meth:`_render_chips`). The wrap flags win where - they overlap: a continuation already opens under its predecessor, and - :meth:`wrapped` appends the cue itself on a line the path outruns. + An end that the route runs on past has the separator with nothing on the far side of + it. It is a leading ``→`` where the origin is not drawn, and a trailing ``→`` where + the destination is not drawn. Arrow mode already spells "the path goes on" with that + trailing mark when a line wraps, so a chain of relays says it in the same way. Thus + the two modes tell the user the same thing, on a console that has no chevrons to + shear (refer to :meth:`_render_chips`). The wrap flags win where they overlap. A + continuation already opens under its predecessor, and :meth:`wrapped` appends the + cue itself on a line that the path outruns. """ text = Text() if hops and not carry_in and not self._from_origin and not hops[0].gap: @@ -950,13 +990,14 @@ class PathLine: return text def _plain_hop(self, hop: PathHop) -> Text: - """One arrow-mode hop: label in its identity style, annotation muted.""" + """One hop in arrow mode: the label in its identity style, and a muted annotation.""" note_style = "faint" if hop.dim else "muted" text = Text() if hop.cursor: - # No chip fill to carry the slot's white, so it takes the app's reverse-video - # `selected` grey — the same block a dialog's committing button is drawn as, - # and the same block the editor's cursor has always been. + # There is no chip fill to carry the white of the slot. Thus it takes the + # reverse-video `selected` grey of the app. This is the same block as the one + # that draws the committing button of a dialog, and the same block that the + # cursor of the editor always had. text.append(hop.label, style="selected") elif hop.dim: text.append(hop.label, style="faint") @@ -965,15 +1006,16 @@ class PathLine: elif hop.you: text.append(hop.label, style="you") elif hop.key and hop.lit_bytes > 0: - split = hop.lit_bytes * 2 # the highlighted_hash two-tone, in hex digits + split = hop.lit_bytes * 2 # the two tones of highlighted_hash, in hex digits text.append(hop.label[:split], style=node_style(hop.key)) text.append(hop.label[split:], style="muted") elif hop.key: text.append(hop.label, style=node_style(hop.key)) else: - # No key to derive a hue from: the hop is a bare hash standing in for a node - # we can't identify, so it takes the app-wide unknown-node grey — not `muted`, - # which is chrome and sits a step darker on a console with only two greys. + # There is no key from which to get a hue. The hop is a bare hash for a node + # that MeshTerm cannot identify. Thus it takes the grey of the app for an + # unknown node, and not `muted`. `muted` is chrome, and on a console that has + # only two greys it is a step darker. text.append(hop.label, style="node.unknown") if hop.annotation: text.append(f" ({hop.annotation})", style=note_style) @@ -982,34 +1024,36 @@ class PathLine: def _render_chips( self, hops: list[PathHop], *, carry_in: bool = False, carry_on: bool = False ) -> Text: - """Powerline chips: each hop filled with its hue, a two-cell gap at every seam. + """Powerline chips: each hop is filled with its hue, and each seam is one cell. - The two outer ends say whether the reader is looking at the whole route, and - two separate things can shorten it. **This line** may be one of several a wrapped - path folds into (``carry_in``/``carry_on``), and **the path itself** may only ever - have been the middle of a route — a packet's ``via`` chain names its relays and - neither of the nodes it actually went between (``from_origin``/``to_destination`` - on the line). Either one draws the same mark at that end, because the reader is - being told the same thing: *the route goes on out there, past what is drawn*. A - head like that opens on the break's other half — the seam's own second cell, so a - fold looks like the seam it interrupted, and a relays-only chain looks like a - route caught mid-stride. A tail like that closes on the point, the same "goes on" - cue arrow mode spells with a trailing ``→``. + The two outer ends tell the user if the line shows the whole route. Two separate + things can make it shorter. **This line** can be one of several lines into which a + wrapped path folds (``carry_in`` and ``carry_on``). Also, **the path itself** can be + only the middle of a route. For example, the ``via`` chain of a packet names its + relays and neither of the nodes between which it went (``from_origin`` and + ``to_destination`` on the line). Both draw the same mark at that end, because they + tell the user the same thing: *the route goes on out there, past what is drawn*. A + head like that opens on the other half of the break. This is the second cell of the + seam. Thus a fold looks like the seam that it interrupted, and a chain with only + relays looks like a route that is caught in the middle of a stride. A tail like that + closes on the point. This is the same cue "goes on" that arrow mode spells with a + trailing ``→``. - An end that really is the route's own opens or closes **rounded**, and, where the - font has no rounded caps, **square** — the chip's own pad is the edge, and nothing - is appended. Square is not a degraded cap, it is the one shape left that says - *stop*: the point is spoken for as the continuation cue, so closing a finished - path on one claimed a hop had been cut off (JP, 2026-09-09). Only the *opening* - used to square itself off, which left every route on a core-only terminal ending - on the mark for "there is more". The pair now reads both ways round — a square end - is a promise that the node beside it is where the route began or ended, which is - why a chain that starts and finishes on relays must not wear one (JP, 2026-09-09). + An end that really is the own end of the route opens or closes **rounded**. Where the + font has no rounded caps, it is **square**: the own pad of the chip is the edge, and + the function appends nothing. A square end is not a degraded cap. It is the one shape + that is left that says *stop*. The point is the continuation cue. Thus, when a + finished path closed on a point, it claimed that a hop was cut off (JP, 2026-09-09). + Before, only the *opening* squared itself off. Then each route on a terminal that has + only the core glyphs ended on the mark for "there is more". Now the pair reads + correctly in both directions. A square end is a promise that the node next to it is + where the route began or ended. Thus a chain that starts and finishes on relays must + not have a square end (JP, 2026-09-09). - An elision (:attr:`PathHop.gap`) interrupts the ribbon rather than joining it: the - chip before it closes on the page, the mark sits on the page bare, and the chip - after it opens on its notch — the picture of a route whose middle was left out, - where a filled ``⋯`` chip would have read as a node by that name. + An elision (:attr:`PathHop.gap`) interrupts the ribbon and does not join it. The chip + before it closes on the page, the mark is bare on the page, and the chip after it + opens on its notch. This is the picture of a route whose middle was left out. A + filled ``⋯`` chip reads as a node with that name. Args: hops: The hops of this one line, in order. @@ -1019,19 +1063,19 @@ class PathLine: colours = [_colours_of(hop) for hop in hops] fills = [colour.fill for colour in colours] rounded = powerline_full() - # A fold and a half-drawn route are two reasons for the same mark; either is - # enough. An elision already breaks the ribbon on that side, and a mark cut out - # of a bare ``⋯`` would have no fill to cut into. + # A fold and a route that is half drawn are two reasons for the same mark. One of + # them is enough. An elision already breaks the ribbon on that side, and a mark that + # MeshTerm cuts from a bare ``⋯`` has no fill into which to cut. opens_mid = (carry_in or not self._from_origin) and not hops[0].gap text = Text() if opens_mid: - text.append_text(self._notch(fills[0])) # the break's other half + text.append_text(self._notch(fills[0])) # the other half of the break elif rounded and not hops[0].gap: text.append(POWERLINE_ROUND_OPEN, style=f"{_FLAT}{fills[0]}") for i, hop in enumerate(hops): if i: if hops[i - 1].gap: - text.append_text(self._notch(fills[i])) # the ribbon picks up again + text.append_text(self._notch(fills[i])) # the ribbon continues again elif hop.gap: text.append(POWERLINE_SEP, style=f"{_FLAT}{fills[i - 1]}") # …and stops else: @@ -1041,49 +1085,51 @@ class PathLine: else: text.append_text(self._chip(hop, colours[i])) if hops[-1].gap: - return text # the line ended on the page; there is no chip left to close + return text # the line ended on the page, and no chip is left to close if carry_on or not self._to_destination: - text.append(POWERLINE_SEP, style=f"{_FLAT}{fills[-1]}") # the point: it goes on + text.append(POWERLINE_SEP, style=f"{_FLAT}{fills[-1]}") # the point: the route goes on elif rounded: text.append(POWERLINE_ROUND_CLOSE, style=f"{_FLAT}{fills[-1]}") # the far end return text @staticmethod def _seam(before: _ChipColours, after: _ChipColours) -> Text: - """The one cell between two chips: the previous fill's point, laid on the next. + """The one cell between two chips: the point of the previous fill, laid on the next. - The classic interlock — foreground the chip behind, background the chip ahead — - so the route reads as one ribbon whose segments meet on a chevron. It costs a - single cell, and with 256 node hues on the wheel two neighbours are near enough - to always differ that the join reads as a join (JP, 2026-08-09; the widget used - to spend two cells leaving a sliver of page between every pair, insurance against - a collision that the palette makes rare). + This is the classic interlock. The foreground is the chip behind, and the background + is the chip ahead. Thus the route reads as one ribbon whose segments meet on a + chevron. It costs a single cell. There are 256 node hues on the wheel, so two + neighbours almost always differ enough that the join reads as a join (JP, + 2026-08-09). Before, the widget used two cells and left a sliver of page between + each pair. This was insurance against a collision that the palette makes rare. - Two fills the eye can't tell apart are the exception the interlock cannot draw — - a chevron in its own background is no chevron — and they are not always bad luck: - a mirrored return leg is a run of identically faded hops by construction, and so - is a stretch of keyless greys. Nor is "can't tell apart" the same as "identical": - two hues a few steps apart on the wheel draw a point the eye can't find either, - one shade of green on the next, so the test is a perceptual distance under - :data:`SEAM_BLUR` (:func:`_fills_blur`), not equality and not a hue gap. + Two fills that the eye cannot tell apart are the exception that the interlock cannot + draw, because a chevron in its own background is not a chevron. This is not always bad + luck. A mirrored return leg is a run of hops that are identically faded, by + construction. A stretch of keyless greys is the same. "Cannot tell apart" is also not + the same as "identical". Two hues that are a few steps apart on the wheel draw a point + that the eye cannot find, for example one shade of green on the next. Thus the test is + a perceptual distance of less than :data:`SEAM_BLUR` (:func:`_fills_blur`). It is not + equality, and it is not a gap of hue. - There the seam is the **thin** chevron, :data:`POWERLINE_THIN`, drawn on the fill - ahead in the colour of the previous chip's label: powerline's own mark for a join - inside one colour, and the chip it belongs to drawing a line on itself, so the - ribbon runs on unbroken and nothing on it is a colour that isn't a chip's. The - solid point drawn bare used to cut a wedge of page out of the route here (a run of - near hues read as dashes, and on a light terminal the wedge was a hole). The thin - chevron was then the previous fill, a lightness step darker (JP, 2026-09-16). When - the label became the node's hue on a darker fill of itself (2026-10-06), the label - colour became the line: it is the light half of the same pair, so it is visible - on each fill and is still the chip's own colour. One cell either way. + There the seam is the **thin** chevron, :data:`POWERLINE_THIN`. It is drawn on the + fill ahead, in the colour of the label of the previous chip. It is the own mark of + powerline for a join inside one colour, and the chip to which it belongs draws a line + on itself. Thus the ribbon continues without a break, and nothing on it is a colour + that is not a colour of a chip. Before, the solid point that was drawn bare cut a + wedge of page out of the route here. (A run of near hues read as dashes, and on a + light terminal the wedge was a hole.) Then the thin chevron was the previous fill, + one step darker in lightness (JP, 2026-09-16). When the label became the hue of the + node on a darker fill of itself (2026-10-06), the label colour became the line. It is + the light half of the same pair, so it is visible on each fill, and it is still the + own colour of the chip. In both cases the seam is one cell. Args: before: The colours of the previous chip. The point is drawn in its fill. after: The colours of the next chip. The point is laid on its fill. Returns: - The seam's single styled cell. + The single styled cell of the seam. """ if _fills_blur(before.fill, after.fill): return Text(POWERLINE_THIN, style=f"{_FLAT}{before.ink} on {after.fill}") @@ -1091,15 +1137,15 @@ class PathLine: @staticmethod def _notch(fill: str) -> Text: - """A chip's left edge: the point cut inward out of its own fill. + """The left edge of a chip: the point, cut inward out of its own fill. - Reverse video paints the notch in the terminal's own background — the only way - to name the page's colour without knowing it — so nothing of whatever sits left - of the chip (the previous chip's taper, the line above a wrapped break) bleeds - into it, and the point still faces the way the path flows. + Reverse video paints the notch in the own background of the terminal. This is the + only way to name the colour of the page without knowing it. Thus nothing that is on + the left of the chip (the taper of the previous chip, the line above a wrapped break) + bleeds into it, and the point still faces the direction in which the path flows. Args: - fill: The chip's fill colour, which the notch is cut out of. + fill: The fill colour of the chip, out of which the notch is cut. Returns: The one styled cell. @@ -1110,14 +1156,14 @@ class PathLine: @staticmethod def _chip(hop: PathHop, colours: _ChipColours) -> Text: - """One chip: the same words as arrow mode, in the chip's ink on its fill. + """One chip: the same words as in arrow mode, in the ink of the chip on its fill. - Every chip is padded on both sides, the ``★`` included (JP, 2026-08-09): the pads - are not there to make room for a long *word*, they are the chip's own shape, and a - star squeezed between two chevrons reads as a glyph wedged into the seam rather - than as a segment of the route. Our own chip's ink is the map's yellow on the - neutral dark grey :data:`_YOU_BG`, so the star in the line and the star on the map - read as one mark. + Each chip has padding on both sides, also the ``★`` (JP, 2026-08-09). The pads are + not there to make room for a long *word*. They are the own shape of the chip. A star + that is squeezed between two chevrons reads as a glyph that is wedged into the seam, + and not as a segment of the route. The ink of our chip is the yellow of the map on + the neutral dark grey :data:`_YOU_BG`. Thus the star in the line and the star on the + map read as one mark. The colours come from the palette of the platform (:func:`_colours_of`). """ @@ -1140,21 +1186,21 @@ class PathLine: def _spectrum_colours(hop: PathHop) -> _ChipColours: """The colours of a chip on a truecolor terminal: the hue on a darker fill of itself. - A node's label is its hue: the colour that its name has in each list and in arrow - mode. The fill is that hue, darker (:data:`CHIP_LIGHTNESS`). The whole - label is in the hue, a hash label and an annotation too, and the lit bytes of a hash - are bold. A keyless chip is the same pair in grey. Our ``★`` and a faded hop keep their - dark greys, which already carry a light label. The PicoCalc draws the same rules at - the resolution of its console (:func:`_slot_colours`). + The label of a node is its hue. This is the colour that its name has in each list and + in arrow mode. The fill is that hue, but darker (:data:`CHIP_LIGHTNESS`). The whole + label is in the hue, also a hash label and an annotation. The lit bytes of a hash are + bold. A keyless chip is the same pair in grey. Our ``★`` and a faded hop keep their dark + greys, which already carry a light label. The PicoCalc draws the same rules at the + resolution of its console (:func:`_slot_colours`). - The insertion slot outranks everything — it is the one chip that isn't a node, - and it wears the ``cursor`` white so it reads as chrome among identities rather - than as a hop with an unlucky hue (white sits outside the node spectrum, and its - dark text stays readable on it). It is the only light chip on the ribbon. The fade - comes next, outranking identity including our own: a dimmed hop is one nobody - composed (an automatic landing back home, a mirrored return leg), and our end must - recede with the rest of that automatic half rather than keep its yellow among the - greys. Plain mode says the same thing by fading the name. + The insertion slot wins over all other rules. It is the one chip that is not a node, and + it has the ``cursor`` white. Thus it reads as chrome among identities, and not as a hop + with a hue that is unlucky. (White is outside the node spectrum, and its dark text stays + readable on it.) It is the only light chip on the ribbon. The fade is next, and it wins + over the identity, also our own. A dimmed hop is a hop that nobody composed (an + automatic return home, a mirrored return leg). Our end must recede with the rest of + that automatic half, and not keep its yellow among the greys. Plain mode says the same + thing when it fades the name. """ if hop.cursor: return _ChipColours(_style_hex("cursor") or _KEYLESS_BG, _CHIP_FG, _CHIP_FG) @@ -1174,18 +1220,18 @@ def _spectrum_colours(hop: PathHop) -> _ChipColours: def _slot_colours(hop: PathHop) -> _ChipColours: """The colours of a chip on the 16-colour console: a bright slot on its dim twin. - The VT draws a background only from slots 0 to 7, which are the dim twins of the - bright slots that colour the node names. Thus a node's chip is the dim twin of its - hue, and its label is in the hue itself: the colour that its name has in arrow mode - and in each list. A pink name gets a purple chip, a yellow name a brown chip. The - whole label is in this colour, a hash label too: a grey for the rest of a hash was - not readable on the green and the cyan fills (JP, 2026-10-06). + The VT draws a background only from slots 0 to 7. These are the dim twins of the bright + slots that give the colour of the node names. Thus the chip of a node is the dim twin of + its hue, and its label is in the hue itself. This is the colour that its name has in + arrow mode and in each list. A pink name gets a purple chip, and a yellow name gets a + brown chip. The whole label is in this colour, also a hash label. A grey for the rest of + a hash was not readable on the green and the cyan fills (JP, 2026-10-06). - A keyless chip is white on light grey, the same pair one bank down. Our ``★``, a - faded hop, and the composer's slot have no fill of their own, because the console - has no dark grey background. They stand on the page (:data:`_SLOT_PAGE`): the star - in its yellow, a faded hop in the dark grey, the slot as a white ``+`` in a break of - the ribbon. The order of the rules is the same as on a truecolor terminal + A keyless chip is white on light grey, the same pair one bank down. Our ``★``, a faded + hop, and the slot of the composer have no fill of their own, because the console has no + dark grey background. They stand on the page (:data:`_SLOT_PAGE`): the star in its + yellow, a faded hop in the dark grey, and the slot as a white ``+`` in a break of the + ribbon. The order of the rules is the same as on a truecolor terminal (:func:`_spectrum_colours`). """ if hop.cursor: @@ -1205,8 +1251,8 @@ def _slot_colours(hop: PathHop) -> _ChipColours: return _ChipColours(DIM_TWIN[ink], ink, ink) -#: The colours of a chip, and the two prefixes of the chip styles. They are bound at -#: platform-switch time (:func:`_bind_chips`). +#: The colours of a chip, and the two prefixes of the chip styles. MeshTerm binds them when +#: the platform switches (:func:`_bind_chips`). _colours_of: Callable[[PathHop], _ChipColours] = _spectrum_colours #: The weight of a chip label: ``bold`` on a truecolor terminal. _WEIGHT = "bold " @@ -1216,12 +1262,12 @@ _FLAT = "" @on_platform def _bind_chips(platform: Platform) -> None: - """Bind the chip palette to the platform (runs now and on every switch). + """Bind the chip palette to the platform (runs now and at each switch). - On the 16-colour console, bold is brightness. Rich merges the base style of a row - into each span on it, so the ``bold`` of a selected row would move each dim fill on - the ribbon to its bright twin. Thus each chip style there says ``not bold``, and a - label gets no weight: its bright slot is its emphasis. + On the 16-colour console, bold is brightness. Rich merges the base style of a row into + each span on it. Thus the ``bold`` of a selected row moves each dim fill on the ribbon + to its bright twin. For this reason each chip style there says ``not bold``, and a label + gets no weight. Its bright slot is its emphasis. """ global _colours_of, _WEIGHT, _FLAT if platform.truecolor: @@ -1231,7 +1277,7 @@ def _bind_chips(platform: Platform) -> None: def _shorten(value: str, hash_bytes: int | None) -> str: - """Bare lowercase hex, truncated to ``hash_bytes`` bytes (whole when falsy).""" + """Bare hex in lower case, truncated to ``hash_bytes`` bytes (whole when it is empty).""" raw = value.lower().removeprefix("0x") return raw[: hash_bytes * 2] if hash_bytes else raw @@ -1255,57 +1301,61 @@ def path_line( from_origin: bool = True, to_destination: bool = True, ) -> PathLine: - """Build a :class:`PathLine` from raw hop hashes — ``path_text``'s vocabulary. + """Build a :class:`PathLine` from raw hop hashes, with the vocabulary of ``path_text``. - The migration bridge: every parameter means exactly what it means to - :func:`~meshterm.ui.widgets.path_text` (see there for the full rendering rules), - so a call site swaps builders without changing what it says — a named hop reads - ``Name`` (annotated ``Name (3d)`` under ``show_hash``), an unnamed hop its hash in - the unknown-node grey (colour marks an identified node, as in the path graph), - ``None`` is our own device in white — or, under ``bare_self``, the lone ``★`` — and - ``dim_from`` fades a resolved tail. The plain rendering - is character- and style-identical to ``path_text``; what the swap buys is the - :class:`PathLine` shapes (ellipsized / wrapped) and the powerline mode. + This is the migration bridge. Each parameter has the same meaning as for + :func:`~meshterm.ui.widgets.path_text` (refer to that function for the full rendering + rules). Thus a call site changes builders and does not change what it says. A named hop + reads ``Name`` (with ``show_hash`` it is ``Name (3d)``). An unnamed hop is its hash in + the grey for an unknown node (colour marks an identified node, as in the path graph). + ``None`` is our device in white, or the lone ``★`` with ``bare_self``. ``dim_from`` + fades a resolved tail. The plain rendering is identical to ``path_text`` in characters + and in style. What the change gives is the shapes of :class:`PathLine` (ellipsized and + wrapped) and the powerline mode. Args: - hops: The hops in propagation order — hex hashes, ``None`` marking our own - device (empty strings are skipped; ``dim_from`` counts rendered hops). - resolve: Maps a hop hash to a friendly name when known. - prefix_bytes: Path-hash width an unnamed hop's identity hash presents at under - ``hash_as_name`` (unnamed hops are otherwise shown grey whole, no prefix lit). - self_name: Our own node's name — white when a resolved name matches it, and - naming any ``None`` device hop. - empty: The muted text shown when there are no hops (e.g. ``"direct"``). - show_hash: Annotate named hops (and, with ``device_hash``, our device) with - their hash in parentheses — the trace presentation. - hash_bytes: Truncate shown/annotated hashes to this byte width. - device_hash: Our own device's key, annotated onto ``None`` hops when + hops: The hops in the order of propagation. They are hex hashes, and ``None`` marks + our device. (The function skips empty strings. ``dim_from`` counts the hops + that are rendered.) + resolve: Maps a hop hash to a friendly name when it is known. + prefix_bytes: The path-hash width at which the identity hash of an unnamed hop shows + under ``hash_as_name``. (In all other cases, unnamed hops are fully grey, and no + prefix is lit.) + self_name: The name of our node. The function makes a resolved name that matches it + white. It is also the name of each ``None`` device hop. + empty: The muted text to show when there are no hops (for example ``"direct"``). + show_hash: Add the hash in parentheses to the named hops (and to our device, with + ``device_hash``). This is the form for traces. + hash_bytes: Truncate the hashes that the function shows or adds to this byte width. + device_hash: The key of our device. The function adds it to the ``None`` hops when ``show_hash`` is on. - dim_from: Fade hops at/after this rendered index (``None`` dims nothing). - hash_as_name: Present each unnamed hop as its muted identity hash at the - ``prefix_bytes`` width, annotated with its addressed byte. - bare_self: Draw our own device (a ``None`` hop) as the bare - :data:`SELF_GLYPH`. For a surface whose route *always* begins and ends on - us, the name and hash on both ends say nothing the reader doesn't know, - and cost the cells the hops in between need. - dim_self: Fade the bare stars (the default). On a surface where the route is - something you *compose*, setting out from us and coming home to us are - fixtures — no more yours to choose or remove than a mirrored return leg — - so they wear the same automatic grey, and the colour on the line belongs to - the nodes actually being picked. Pass ``False`` where nothing is being - composed (a record of a walk already made): there is no "not yours" to say, - and our node then reads in the app-wide ``you`` white like everywhere else. - A ``dim_from`` that reaches a star still fades it either way. - cursor: Splice an editor's insertion slot (:data:`CURSOR_GLYPH`) in *at* this - rendered-hop index — the position a chosen hop would take, so index ``0`` - opens the route and ``len`` closes it. Counted over rendered hops exactly - as ``dim_from`` is, and applied after them, so a slot never shifts what a - hop shows or fades. ``None`` draws no cursor. - mode: The :class:`PathLine` mode (``"auto"``/``"powerline"``/``"plain"``). - from_origin: The first hop is the route's origin (see :class:`PathLine`). Clear - it where ``hops`` is a chain of *relays* — the raw ``path`` field a packet - carries names neither the node it came from nor the one it reached. - to_destination: The last hop is the route's destination, same reading. + dim_from: Fade the hops at this rendered index and after it (``None`` dims nothing). + hash_as_name: Show each unnamed hop as its muted identity hash at the + ``prefix_bytes`` width, with the byte by which it is addressed. + bare_self: Draw our device (a ``None`` hop) as the bare :data:`SELF_GLYPH`. It is for + a surface whose route *always* begins and ends on us. The name and the hash on + both ends tell the user nothing new, and they use the cells that the hops + between them need. + dim_self: Fade the bare stars (the default). On a surface where the user *composes* + the route, to set out from us and to come home to us are fixtures. The user does + not choose or remove them, the same as for a mirrored return leg. Thus they have + the same automatic grey, and the colour on the line is for the nodes that the + user really picks. Pass ``False`` where nobody composes anything (a record of a + walk that is already made). Then there is no "not yours" to say, and our node + reads in the ``you`` white of the app, as in other places. A ``dim_from`` that + reaches a star still fades it in both cases. + cursor: Insert the insertion slot of an editor (:data:`CURSOR_GLYPH`) *at* this + index of the rendered hops. This is the position that a chosen hop takes, so + index ``0`` opens the route and ``len`` closes it. The function counts it over + the rendered hops, the same as ``dim_from``, and applies it after them. Thus a + slot never changes what a hop shows or how it fades. ``None`` draws no cursor. + mode: The mode of :class:`PathLine` (``"auto"``, ``"powerline"``, or ``"plain"``). + from_origin: The first hop is the origin of the route (refer to :class:`PathLine`). + Clear it where ``hops`` is a chain of *relays*. The raw ``path`` field that a + packet carries names neither the node that it came from nor the node that it + reached. + to_destination: The last hop is the destination of the route. The same reading + applies. Returns: The assembled :class:`PathLine`. @@ -1316,12 +1366,12 @@ def path_line( dim = dim_from is not None and i >= dim_from if hop is None: if bare_self: - # Where the route is being composed, both our ends are fixed — a walk - # leaves us and comes home to us, and neither end is anybody's to choose - # or remove — so the stars fade like every other automatic hop and the - # colour belongs to the nodes actually being picked. Where nothing is - # being composed (``dim_self=False``), that has nothing to say, and our - # own node keeps the app-wide ``you`` white. + # Where the user composes the route, both our ends are fixed. A walk leaves + # us and comes home to us, and nobody chooses or removes either end. Thus + # the stars fade like each other automatic hop, and the colour is for the + # nodes that the user really picks. Where nobody composes anything + # (``dim_self=False``), this does not apply, and our node keeps the ``you`` + # white of the app. built.append(PathHop(SELF_GLYPH, you=True, dim=dim_self or dim)) continue note = _shorten(device_hash, hash_bytes) if (show_hash and device_hash) else None @@ -1342,16 +1392,16 @@ def path_line( ) continue compact = _shorten(hop, hash_bytes) - if dim: # a faded unnamed hop shows its compact hash, exactly as path_text does + if dim: # a faded unnamed hop shows its compact hash, as path_text does built.append(PathHop(compact, dim=True)) elif hash_as_name: identity = _shorten(hop, prefix_bytes or None) note = compact if (show_hash and compact and compact != identity) else None built.append(PathHop(identity, annotation=note)) else: - # No name resolved: the node is unknown, so its hash carries no key — the hop - # takes the app-wide unknown-node grey (arrow and chip alike), never a hue its - # bytes would derive. Colour marks an identified node, as in the path graph. + # No name resolved: the node is unknown, so its hash has no key. The hop takes + # the grey of the app for an unknown node (in arrows and in chips), and never a + # hue that its bytes give. Colour marks an identified node, as in the path graph. built.append(PathHop(compact)) if cursor is not None: built.insert(max(0, min(cursor, len(built))), PathHop(CURSOR_GLYPH, cursor=True)) diff --git a/meshterm/ui/termfont.py b/meshterm/ui/termfont.py index 773b3a4..a0bf53e 100644 --- a/meshterm/ui/termfont.py +++ b/meshterm/ui/termfont.py @@ -1,79 +1,82 @@ # SPDX-License-Identifier: Apache-2.0 -"""Terminal capability detection — what can this terminal actually draw? +"""Terminal capability detection: what can this terminal draw? -Two questions, both answered out-of-band because a terminal cannot be asked in-band: a -glyph it does not have still occupies its cell, so the screen looks the same whether the -character arrived or not. +There are two questions. MeshTerm answers both out-of-band, because it cannot ask a +terminal in-band. A glyph that the terminal does not have still occupies its cell, so the +screen looks the same if the character arrived or not. -**Powerline separators**, below, are a *font* question — read the terminal's configured -face and match it against fonts known to carry the block. +**Powerline separators**, below, are a question about the font. MeshTerm reads the +configured face of the terminal and matches it against fonts that are known to have the +block. -**Emoji** (:func:`emoji_support`) are a *host* question, and only on Windows. The classic -console — ``conhost``, which is what a double-clicked program still gets — rasterises -through GDI with the console font and nothing behind it, so an emoji lands as a -replacement box however the font is configured. Everything that replaced it draws them -fine. So the verdict identifies the host, structurally rather than from the environment -(``WT_SESSION`` is inherited across process launches, so a program started from Windows -Terminal into a console of its own still claims to be in one), and a ``False`` routes -every icon through the compact single-glyph table :func:`meshterm.ui.theme.glyph` already -keeps for the PicoCalc — that whole vocabulary is BMP, so it draws wherever the plain -status marks already do. +**Emoji** (:func:`emoji_support`) are a question about the host, and only on Windows. The +classic console (``conhost``, which a program that the user double-clicks still gets) +rasterizes through GDI with the console font and nothing behind it. Thus an emoji is a +replacement box, in any font configuration. All the hosts that replaced it draw emoji +correctly. So the verdict identifies the host, from its structure and not from the +environment. (``WT_SESSION`` is inherited across process launches. A program that starts +from Windows Terminal into a console of its own still says that it is in Windows +Terminal.) A ``False`` sends each icon through the compact single-glyph table +:func:`meshterm.ui.theme.glyph`, which MeshTerm already keeps for the PicoCalc. All of +this vocabulary is in the BMP, so it draws wherever the plain status marks draw. -Both verdicts are hints that pick a default, and both have an override for the reader who -knows better than the probe: ``MESHTERM_POWERLINE`` and ``MESHTERM_EMOJI``. +Both verdicts are hints that pick a default. Each has an override for the user who knows +better than the probe: ``MESHTERM_POWERLINE`` and ``MESHTERM_EMOJI``. -The path-line widget (:mod:`~meshterm.ui.pathline`) can render a hop sequence as -interlocking powerline segments — each hop a colour-filled chip, joined by the solid -triangle U+E0B0 whose foreground is the previous chip's fill and whose background is -the next's, the oh-my-posh look. That triangle lives in the Private Use Area, so it -only draws when the *terminal's configured font* (or the terminal itself) supplies the -glyph; a font without it shows tofu boxes. Nothing in-band can ask "do you have this -glyph?" — a missing glyph still occupies its cell, so even cursor-position probes see -nothing — which makes this an *out-of-band* detection problem: identify the terminal, -read its configuration, and match the configured face against fonts known to carry the -powerline block. +The path-line widget (:mod:`~meshterm.ui.pathline`) can render a sequence of hops as +interlocking powerline segments. Each hop is a chip with a colour fill. The solid +triangle U+E0B0 joins the chips. Its foreground is the fill of the previous chip, and its +background is the fill of the next chip (the oh-my-posh look). That triangle is in the +Private Use Area, so it draws only when the configured font of the terminal (or the +terminal itself) supplies the glyph. A font without the glyph shows tofu boxes. MeshTerm +cannot ask in-band if the terminal has this glyph. A missing glyph still occupies its +cell, so even a probe of the cursor position sees nothing. Thus this is a problem of +out-of-band detection. MeshTerm identifies the terminal, reads its configuration, and +matches the configured face against fonts that are known to have the powerline block. -Four sources of truth, in confidence order: +There are four sources of truth, in the order of confidence: -* **An explicit override** — ``MESHTERM_POWERLINE`` (``1``/``full``, ``core``, - ``0``/``off``) always wins, the same gate pattern as ``MESHTERM_FULL_WIDTH``. The - user knows their glass better than any probe. -* **A handheld's own font.** Where the platform names a glyph contract - (:attr:`~meshterm.platforms.Platform.font`), every frame is folded down to that font - at the render boundary, whatever terminal started the app — so the inventory is the - answer, and asking the terminal would be asking the wrong glass. The Cardputer's panel - is Terminus, which carries the core chevrons. The PicoCalc's 512-glyph console font - draws the two chevrons in two donor slots. Thus the paths are chips on both handhelds. - Nothing is probed: :data:`~meshterm.ui.fontset.FONTS` already says what each font can - draw. -* **The configured font**, resolved per terminal: Windows Terminal (``WT_SESSION`` + - ``WT_PROFILE_ID`` → the profile's ``font.face`` in ``settings.json``), VS Code's - integrated terminal (``TERM_PROGRAM=vscode`` → ``terminal.integrated.fontFamily``, - workspace over user, falling back to ``editor.fontFamily``), and classic conhost - (``GetCurrentConsoleFontEx`` — trusted only when no ConPTY host is detected, because - the hidden conhost under one reports a stub face, not what's on screen). The face is - matched against :data:`RECOMMENDED_FONTS` — the list MeshTerm recommends to users — - with the alias spellings Nerd Fonts ship under (``Hack Nerd Font Mono`` / ``Hack - NFM``), plus a generic "any Nerd Font" rule, since every Nerd Font patch carries the - full powerline block. -* **The terminal's own renderer**: several terminals draw the core triangles - regardless of font — Windows Terminal falls back to its bundled Cascadia Code NF for - the symbol ranges (≥ 1.22), VS Code's terminal draws them as custom glyphs - (``terminal.integrated.customGlyphs``, default on), and kitty / WezTerm / Alacritty - ship built-in powerline glyphs. Those count as ``core`` support even when the - configured font matches nothing. +* **An explicit override.** ``MESHTERM_POWERLINE`` (``1``/``full``, ``core``, + ``0``/``off``) always wins. It is the same gate pattern as ``MESHTERM_FULL_WIDTH``. The + user knows their own display better than any probe. +* **The font of a handheld.** Where the platform names a glyph contract + (:attr:`~meshterm.platforms.Platform.font`), the render boundary folds each frame down + to that font, in any terminal that started the app. Thus the inventory is the answer, + and a question to the terminal is a question to the wrong display. The panel of the + Cardputer is Terminus, which has the core chevrons. The 512-glyph console font of the + PicoCalc draws the two chevrons in two donor slots. Thus the paths are chips on both + handhelds. MeshTerm does not probe: :data:`~meshterm.ui.fontset.FONTS` already says + what each font can draw. +* **The configured font**, found for each terminal. The terminals are Windows Terminal + (``WT_SESSION`` + ``WT_PROFILE_ID`` → the ``font.face`` of the profile in + ``settings.json``), the integrated terminal of VS Code (``TERM_PROGRAM=vscode`` → + ``terminal.integrated.fontFamily``, the workspace before the user, with + ``editor.fontFamily`` as the fallback), and classic conhost (``GetCurrentConsoleFontEx``, + which MeshTerm trusts only when it detects no ConPTY host, because the hidden conhost + under a ConPTY host reports a stub face and not what is on the screen). MeshTerm + matches the face against :data:`RECOMMENDED_FONTS` (the list of fonts that MeshTerm + recommends to users). The list has the alias spellings that Nerd Fonts use (``Hack Nerd + Font Mono`` / ``Hack NFM``). A generic rule, "any Nerd Font", is also in the match, + because each Nerd Font patch has the full powerline block. +* **The renderer of the terminal.** Several terminals draw the core triangles in any + font. Windows Terminal falls back to its bundled Cascadia Code NF for the symbol ranges + (version 1.22 and later). The terminal of VS Code draws them as custom glyphs + (``terminal.integrated.customGlyphs``, on by default). kitty, WezTerm, and Alacritty + have built-in powerline glyphs. These terminals count as ``core`` support, also when + the configured font matches nothing. -Coverage comes in two levels: ``full`` (a Nerd Font patch — triangles *and* the -extended block: rounded caps, slants) and ``core`` (just U+E0B0–U+E0B3, which many -stock coder fonts — Fira Code, JetBrains Mono, Source Code Pro — include natively). -The path widget only uses the core triangle, so ``core`` is enough to switch it on; -``full`` is headroom for fancier chrome. When nothing can be known — an ssh session -(the font lives on the far client's machine), an unrecognised terminal — the verdict -is honestly ``unknown`` and callers should keep the plain-arrow rendering. +There are two levels of coverage. ``full`` is a Nerd Font patch: the triangles and the +extended block (rounded caps and slants). ``core`` is only U+E0B0–U+E0B3, which many +stock coder fonts (Fira Code, JetBrains Mono, Source Code Pro) have natively. The path +widget uses only the core triangle, so ``core`` is enough to switch it on. ``full`` is +more than the widget needs, for more complex chrome. When MeshTerm cannot know the +answer, for example in an ssh session (the font is on the machine of the far client) or +in an unrecognized terminal, the verdict is ``unknown``. Then callers must keep the +plain-arrow rendering. -Every probe is best-effort: unreadable settings, missing registry keys, or a failed -Win32 call degrade the verdict, never raise. The result is a *hint that picks a -default*, not a gate the user has to fight. +Each probe does its best. Unreadable settings, missing registry keys, or a failed Win32 +call lower the verdict, and never raise an exception. The result is a hint that picks a +default. It is not a gate that the user must fight. """ from __future__ import annotations @@ -91,7 +94,7 @@ from ..core import win32dll from ..platforms import Platform, on_platform from .fontset import FONTS -#: Coverage levels a verdict (or a recommended font) can carry, strongest first. +#: The levels of coverage that a verdict (or a recommended font) can have, the strongest first. FULL = "full" CORE = "core" NONE = "none" @@ -100,16 +103,16 @@ UNKNOWN = "unknown" @dataclass(frozen=True) class RecommendedFont: - """One font MeshTerm recommends for powerline path rendering. + """One font that MeshTerm recommends for the rendering of powerline paths. Attributes: - name: The canonical display name (what a recommendation screen shows). - aliases: Normalised name prefixes that identify the family — every spelling a - terminal config might hold, lower-case with collapsed spaces (Nerd Fonts - deliberately ship several: ``hack nerd font mono`` and ``hack nfm`` are the - same file). - coverage: :data:`FULL` when the family carries the whole powerline block - (Nerd Font patches), :data:`CORE` when it ships just the four triangles. + name: The canonical display name (what a screen of recommendations shows). + aliases: The normalized name prefixes that identify the family. They are all the + spellings that the config of a terminal can have, in lower case with + collapsed spaces. Nerd Fonts have several spellings on purpose: ``hack nerd + font mono`` and ``hack nfm`` are the same file. + coverage: :data:`FULL` when the family has the whole powerline block (Nerd Font + patches). :data:`CORE` when it has only the four triangles. """ name: str @@ -117,9 +120,10 @@ class RecommendedFont: coverage: str -#: The fonts MeshTerm recommends, full-coverage Nerd Fonts first — order matters, the -#: first alias hit wins, so ``JetBrainsMono Nerd Font`` must match its ``full`` entry -#: before the plain ``JetBrains Mono`` prefix could claim it as ``core``. +#: The fonts that MeshTerm recommends, with the full-coverage Nerd Fonts first. The order +#: is important, because the first alias that matches wins. Thus ``JetBrainsMono Nerd +#: Font`` must match its ``full`` entry before the plain ``JetBrains Mono`` prefix can +#: claim it as ``core``. RECOMMENDED_FONTS: tuple[RecommendedFont, ...] = ( RecommendedFont( "MesloLGM Nerd Font", @@ -179,9 +183,10 @@ RECOMMENDED_FONTS: tuple[RecommendedFont, ...] = ( RecommendedFont("Iosevka", ("iosevka",), CORE), ) -#: The catch-all for a patched font the explicit list doesn't spell out: any family -#: whose name carries the Nerd Font branding — the long ``… Nerd Font [Mono|Propo]`` -#: or the v3 short suffixes ``NF``/``NFM``/``NFP`` — has the full powerline block. +#: The catch-all for a patched font that the explicit list does not name. Each family +#: whose name has the Nerd Font branding has the full powerline block. The branding is the +#: long ``… Nerd Font [Mono|Propo]`` or the short suffixes of version 3 +#: (``NF``/``NFM``/``NFP``). NERD_FONT_GENERIC = RecommendedFont("Nerd Font (patched)", (), FULL) _NERD_RE = re.compile(r"\bnerd font\b|\bnf[mp]?\b") @@ -189,10 +194,10 @@ _NERD_RE = re.compile(r"\bnerd font\b|\bnf[mp]?\b") @dataclass(frozen=True) class FontDetection: - """The configured terminal font, and which terminal it was read from. + """The configured terminal font, and the terminal that MeshTerm read it from. Attributes: - face: The font family name as configured (unnormalised). + face: The font family name as configured (not normalized). source: ``"windows-terminal"``, ``"vscode"``, or ``"conhost"``. """ @@ -202,17 +207,17 @@ class FontDetection: @dataclass(frozen=True) class PowerlineSupport: - """The verdict: how confidently this terminal can draw powerline separators. + """The verdict: how certain MeshTerm is that this terminal can draw powerline separators. Attributes: level: :data:`FULL`, :data:`CORE`, :data:`NONE`, or :data:`UNKNOWN`. - source: What decided it — ``"env"`` (the override), ``"platform:"`` (a - handheld's own font inventory), ``"font:"`` - (a configured face matched, or definitively didn't), ``"renderer:"`` - (the terminal draws the glyphs itself), ``"ssh"`` (the font lives on the far - client, unknowable), or ``"unknown"``. - face: The configured face when one was found, for the curious. - matched: The recommended-list entry the face matched, if any. + source: What decided the verdict. ``"env"`` is the override. ``"platform:"`` + is the font inventory of a handheld. ``"font:"`` is a configured + face that matched, or that definitely did not match. ``"renderer:"`` + is a terminal that draws the glyphs itself. ``"ssh"`` is a font on the far + client, which MeshTerm cannot know. ``"unknown"`` is all other cases. + face: The configured face, when MeshTerm found one. It is for information. + matched: The entry of the recommended list that the face matched, if any. """ level: str @@ -222,7 +227,7 @@ class PowerlineSupport: @property def capable(self) -> bool: - """Whether the core triangle (all the path widget needs) will draw.""" + """Check if the core triangle (the only glyph that the path widget needs) will draw.""" return self.level in (FULL, CORE) @@ -230,29 +235,29 @@ class PowerlineSupport: def primary_family(value: str) -> str: - """The first family of a CSS-style font list, unquoted. + """The first family of a font list in the CSS style, without quotes. - VS Code stores ``"'Hack Nerd Font Mono', monospace"``; the first family is the - one the renderer tries first, so it is the one we judge. + VS Code stores ``"'Hack Nerd Font Mono', monospace"``. The renderer tries the first + family first, so MeshTerm judges that family. Args: - value: A font-family setting value (single name or comma list). + value: The value of a font-family setting (a single name or a comma list). Returns: - The first family with quotes and outer whitespace stripped. + The first family, with the quotes and the outer whitespace removed. """ first = value.split(",")[0] return first.strip().strip("'\"").strip() def normalize_face(face: str) -> str: - """Fold a face name to its matchable form: lower-case, single-spaced, unquoted. + """Fold a face name to its form for a match: lower case, single-spaced, without quotes. Args: face: A font family name as a config file spells it. Returns: - The normalised name (may be empty). + The normalized name (it can be empty). """ return " ".join(face.strip().strip("'\"").lower().split()) @@ -260,17 +265,17 @@ def normalize_face(face: str) -> str: def match_recommended(face: str | None) -> RecommendedFont | None: """Match a configured face against the recommended-font list. - A face matches an entry when it *is* one of the entry's aliases or extends one as - a longer family name (``hack nerd font mono`` extends ``hack nerd font``); the - generic Nerd Font rule (:data:`NERD_FONT_GENERIC`) catches patched families the - explicit list doesn't spell out. + A face matches an entry when it is one of the aliases of the entry, or when it extends + one alias as a longer family name (``hack nerd font mono`` extends ``hack nerd + font``). The generic Nerd Font rule (:data:`NERD_FONT_GENERIC`) matches the patched + families that the explicit list does not name. Args: - face: The configured font family (single name or comma list); ``None`` is a - polite no-op. + face: The configured font family (a single name or a comma list). ``None`` does + nothing and is not an error. Returns: - The matched :class:`RecommendedFont`, or ``None`` when the face is unknown. + The matched :class:`RecommendedFont`, or ``None`` when the face is not known. """ if not face: return None @@ -289,7 +294,7 @@ def match_recommended(face: str | None) -> RecommendedFont | None: def _strip_jsonc(text: str) -> str: - """Strip ``//`` and ``/* */`` comments from JSON-with-comments, string-safely.""" + """Remove the ``//`` and ``/* */`` comments from JSON with comments. Strings are safe.""" out: list[str] = [] i, n = 0, len(text) in_string = False @@ -297,7 +302,7 @@ def _strip_jsonc(text: str) -> str: ch = text[i] if in_string: out.append(ch) - if ch == "\\" and i + 1 < n: # keep the escaped char verbatim + if ch == "\\" and i + 1 < n: # keep the escaped character exactly out.append(text[i + 1]) i += 2 continue @@ -326,12 +331,12 @@ def _strip_jsonc(text: str) -> str: def _read_jsonc(path: Path) -> dict | None: - """Parse a JSONC settings file (comments, trailing commas), ``None`` on any failure. + """Parse a JSONC settings file (comments, trailing commas). Return ``None`` on any failure. - Both Windows Terminal and VS Code write JSON-with-comments; a strict parser dies - on the first ``//``. Trailing commas are swept with a best-effort regex after the - string-aware comment strip (a *string* containing ``", }"`` could theoretically be - clipped — no font config holds one). + Windows Terminal and VS Code both write JSON with comments. A strict parser fails at + the first ``//``. After the removal of the comments, which does not change strings, + a regex removes the trailing commas. The regex does its best. A string that contains + ``", }"`` can in theory be cut, but no font config has such a string. """ try: text = path.read_text(encoding="utf-8-sig") @@ -342,17 +347,17 @@ def _read_jsonc(path: Path) -> dict | None: def _profile_face(profile: object) -> str | None: - """A Windows Terminal profile's configured font face. + """The configured font face of a Windows Terminal profile. - Reads the new ``font.face`` or the legacy ``fontFace``, and answers ``None`` when - the profile leaves the choice to the defaults chain. + The function reads the new ``font.face`` or the legacy ``fontFace``. It returns + ``None`` when the profile leaves the choice to the chain of defaults. """ if not isinstance(profile, dict): return None font = profile.get("font") if isinstance(font, dict): face = font.get("face") - if isinstance(face, list) and face: # defensive: an array face takes its head + if isinstance(face, list) and face: # defensive: for an array face, use its first item face = face[0] if isinstance(face, str) and face.strip(): return face @@ -363,9 +368,10 @@ def _profile_face(profile: object) -> str | None: def _wt_settings_paths(environ: Mapping[str, str]) -> list[Path]: - """Where Windows Terminal might keep its ``settings.json``. + """The places where Windows Terminal can keep its ``settings.json``. - The packaged, preview, and unpackaged locations — existing files only. + These are the packaged, preview, and unpackaged locations. The list has only files + that exist. """ local = environ.get("LOCALAPPDATA") if not local: @@ -385,12 +391,13 @@ def _wt_settings_paths(environ: Mapping[str, str]) -> list[Path]: def _windows_terminal_face(environ: Mapping[str, str]) -> str: - """The face Windows Terminal is rendering this session with. + """The face that Windows Terminal uses to render this session. - Resolved the way the terminal itself does: the ``WT_PROFILE_ID`` profile's font, - else ``profiles.defaults``, else the built-in default ``Cascadia Mono``. An - unreadable settings file lands on the built-in default too — a pristine install - is exactly that. + The function finds the face in the same way as the terminal. First it uses the font + of the ``WT_PROFILE_ID`` profile. If there is none, it uses ``profiles.defaults``. + If there is none, it uses the built-in default ``Cascadia Mono``. An unreadable + settings file also gives the built-in default, which is the same as a new + installation. """ guid = (environ.get("WT_PROFILE_ID") or "").strip().lower() for path in _wt_settings_paths(environ): @@ -403,7 +410,7 @@ def _windows_terminal_face(environ: Mapping[str, str]) -> str: if isinstance(profiles, dict): plist = profiles.get("list") or [] defaults = profiles.get("defaults") or {} - elif isinstance(profiles, list): # the ancient flat-list schema + elif isinstance(profiles, list): # the old flat-list schema plist = profiles profile = ( next( @@ -420,15 +427,15 @@ def _windows_terminal_face(environ: Mapping[str, str]) -> str: face = _profile_face(profile) or _profile_face(defaults) if face: return face - break # a parsed settings file with no face set → the built-in default + break # a settings file that parsed but has no face: use the built-in default return "Cascadia Mono" def _vscode_settings_paths(environ: Mapping[str, str], start: Path | None) -> list[Path]: - """VS Code's settings files, nearest first. + """The settings files of VS Code, the nearest first. - The closest workspace, then the user's own (stable and Insiders, in their - per-platform locations) — existing files only. + First is the closest workspace. Then come the user files (stable and Insiders, in + their locations for each platform). The list has only files that exist. """ paths: list[Path] = [] try: @@ -457,7 +464,7 @@ def _vscode_settings_paths(environ: Mapping[str, str], start: Path | None) -> li def _vscode_default_face() -> str: - """VS Code's per-platform default editor font family's first name.""" + """The first name of the default editor font family of VS Code on this platform.""" if sys.platform == "win32": return "Consolas" if sys.platform == "darwin": @@ -466,11 +473,11 @@ def _vscode_default_face() -> str: def _vscode_face(environ: Mapping[str, str], start: Path | None = None) -> str: - """The face VS Code's integrated terminal is rendering with. + """The face that the integrated terminal of VS Code uses to render. - ``terminal.integrated.fontFamily`` wins over ``editor.fontFamily`` (VS Code's own - fallback), and within each key the workspace file wins over the user file. The - stored value is a CSS-style comma list; the first family is judged. + ``terminal.integrated.fontFamily`` wins over ``editor.fontFamily`` (the own fallback + of VS Code). For each key, the workspace file wins over the user file. The stored + value is a comma list in the CSS style, and MeshTerm judges the first family. """ paths = _vscode_settings_paths(environ, start) settings = [data for data in (_read_jsonc(p) for p in paths) if data is not None] @@ -483,11 +490,11 @@ def _vscode_face(environ: Mapping[str, str], start: Path | None = None) -> str: def _conhost_face() -> str | None: - """The classic-console face via ``GetCurrentConsoleFontEx``, or ``None``. + """The face of the classic console, from ``GetCurrentConsoleFontEx``, or ``None``. - Only meaningful on a *genuine* conhost — the caller gates on the absence of ConPTY - markers first, because the hidden conhost under Windows Terminal / VS Code reports - a stub face, not the glyphs on screen. + The result has a meaning only on a real conhost. The caller first makes sure that + there are no ConPTY markers, because the hidden conhost under Windows Terminal or + VS Code reports a stub face and not the glyphs on the screen. """ if sys.platform != "win32": return None @@ -531,19 +538,26 @@ def detect_terminal_font( cwd: Path | None = None, conhost_probe: Callable[[], str | None] = _conhost_face, ) -> FontDetection | None: - """Identify the terminal and read the font it is configured to render with. + """Identify the terminal and read the font that it is configured to render with. - The ladder, most to least certain: Windows Terminal (``WT_SESSION`` names the app, - ``WT_PROFILE_ID`` the exact profile), VS Code (``TERM_PROGRAM=vscode``), then a - genuine classic conhost (no ConPTY markers, no ``TERM`` — a set ``TERM`` means some - other emulator is hosting the console) asked directly via Win32. Anything else — - an unrecognised terminal, an ssh session — is ``None``: the face is unknowable - from here. + The ladder goes from the most certain to the least certain source: + + * Windows Terminal. ``WT_SESSION`` names the app and ``WT_PROFILE_ID`` names the + exact profile. + * VS Code (``TERM_PROGRAM=vscode``). + * A real classic conhost, which the function asks directly through Win32. It has no + ConPTY markers and no ``TERM``. A ``TERM`` that is set means that another emulator + hosts the console. + + For all other cases the result is ``None``, for example an unrecognized terminal or an + ssh session. MeshTerm cannot know the face from here. Args: - environ: The environment to inspect (defaults to ``os.environ``). - cwd: Where the VS Code workspace walk starts (defaults to the process cwd). - conhost_probe: The classic-console face reader (injectable for tests). + environ: The environment to examine (the default is ``os.environ``). + cwd: Where the search for the VS Code workspace starts (the default is the cwd of + the process). + conhost_probe: The function that reads the face of the classic console (a + parameter, so that tests can replace it). Returns: The configured face and its source, or ``None`` when no source applies. @@ -561,13 +575,13 @@ def detect_terminal_font( def _renderer_backed(environ: Mapping[str, str]) -> str | None: - """The terminal id when the terminal draws the core triangles itself. + """The terminal id, when the terminal draws the core triangles itself. - Windows Terminal falls back to its bundled Cascadia Code NF for the powerline - symbol ranges (≥ 1.22), VS Code's terminal draws them as custom glyphs - (``terminal.integrated.customGlyphs``, default on), and kitty / WezTerm / - Alacritty ship built-in powerline glyphs — on those, the separators render - whatever the configured font holds. + Windows Terminal falls back to its bundled Cascadia Code NF for the powerline symbol + ranges (version 1.22 and later). The terminal of VS Code draws them as custom glyphs + (``terminal.integrated.customGlyphs``, on by default). kitty, WezTerm, and Alacritty + have built-in powerline glyphs. In these terminals, the separators render in any + configured font. """ if environ.get("WT_SESSION"): return "windows-terminal" @@ -587,16 +601,21 @@ def _renderer_backed(environ: Mapping[str, str]) -> str | None: return None -#: The glyphs the path widget draws at ``core``: the solid triangle every seam is, and the -#: thin one that joins two fills the eye can't tell apart (:mod:`~meshterm.ui.pathline`). +#: The glyphs that the path widget draws at ``core``: the solid triangle that each seam +#: is, and the thin triangle that joins two fills that the eye cannot tell apart +#: (:mod:`~meshterm.ui.pathline`). _CORE_GLYPHS = (0xE0B0, 0xE0B1) -#: What ``full`` adds that the widget uses: the rounded caps a path's square ends become. +#: What ``full`` adds that the widget uses: the rounded caps that replace the square ends +#: of a path. _FULL_GLYPHS = (0xE0B4, 0xE0B6) def _inventory_coverage(inventory: frozenset[int]) -> str: - """The coverage level a known glyph inventory earns — no guess, it is all listed.""" + """The level of coverage that a known glyph inventory has. + + The result is not a guess, because the inventory lists all the glyphs. + """ if not all(code in inventory for code in _CORE_GLYPHS): return NONE return FULL if all(code in inventory for code in _FULL_GLYPHS) else CORE @@ -609,14 +628,16 @@ def _powerline_support( conhost_probe: Callable[[], str | None] = _conhost_face, handheld: tuple[str, frozenset[int]] | None = None, ) -> PowerlineSupport: - """The uncached verdict (see :func:`powerline_support` for the ladder). + """The verdict without the cache (refer to :func:`powerline_support` for the ladder). Args: - environ: The environment to inspect (defaults to ``os.environ``). - cwd: Where the VS Code workspace walk starts (defaults to the process cwd). - conhost_probe: The classic-console face reader (injectable for tests). - handheld: The platform's name and glyph inventory where a handheld's own font - draws the screen, or ``None`` on a terminal. + environ: The environment to examine (the default is ``os.environ``). + cwd: Where the search for the VS Code workspace starts (the default is the cwd of + the process). + conhost_probe: The function that reads the face of the classic console (a + parameter, so that tests can replace it). + handheld: The name and the glyph inventory of the platform, where the own font of + a handheld draws the screen. ``None`` on a terminal. """ env = os.environ if environ is None else environ override = (env.get("MESHTERM_POWERLINE") or "").strip().lower() @@ -637,7 +658,7 @@ def _powerline_support( backed = _renderer_backed(env) if backed: return PowerlineSupport(CORE, f"renderer:{backed}", detected.face if detected else None) - if detected: # a face we could read, matching nothing, on a terminal with no fallback + if detected: # MeshTerm read a face, it matches nothing, and the terminal has no fallback return PowerlineSupport(NONE, f"font:{detected.source}", detected.face) if env.get("SSH_CONNECTION") or env.get("SSH_TTY") or env.get("SSH_CLIENT"): return PowerlineSupport(UNKNOWN, "ssh") @@ -646,14 +667,20 @@ def _powerline_support( @lru_cache(maxsize=1) def powerline_support() -> PowerlineSupport: - """The session's powerline verdict, decided once and cached. + """The powerline verdict of the session. MeshTerm decides it one time and caches it. - The ladder: the ``MESHTERM_POWERLINE`` override, then a handheld platform's own font - inventory, then the configured font matched against :data:`RECOMMENDED_FONTS`, then - a renderer that draws the glyphs itself, then an honest ``none`` (face read, no - match, no fallback) or ``unknown`` (ssh, or a terminal we can't identify). Cached - because the environment and settings files don't change mid-session, and cleared on - a platform switch (:func:`_bind`); tests exercise :func:`_powerline_support` directly. + The ladder has these steps, in this order: + + * The ``MESHTERM_POWERLINE`` override. + * The own font inventory of a handheld platform. + * The configured font, matched against :data:`RECOMMENDED_FONTS`. + * A renderer that draws the glyphs itself. + * ``none`` (MeshTerm read the face, but there is no match and no fallback) or + ``unknown`` (an ssh session, or a terminal that MeshTerm cannot identify). + + The result is cached, because the environment and the settings files do not change + during a session. A switch of platform clears the cache (:func:`_bind`). Tests call + :func:`_powerline_support` directly. Returns: The :class:`PowerlineSupport` verdict. @@ -662,31 +689,31 @@ def powerline_support() -> PowerlineSupport: def powerline_enabled() -> bool: - """Whether path lines should default to powerline separators (see ``.capable``).""" + """Check if path lines must use powerline separators by default (refer to ``.capable``).""" return powerline_support().capable def powerline_full() -> bool: - """Whether the *extended* block is there too — the rounded caps at U+E0B4+. + """Check if the extended block is also present: the rounded caps at U+E0B4 and later. - Only a Nerd Font patch carries them, so this is strictly narrower than - :func:`powerline_enabled`: a stock coder font (Fira Code, JetBrains Mono) draws - the core triangles natively and nothing beyond, and a terminal that supplies the - separators from its own renderer is only promising those four. Callers use it for - chrome that must degrade — :mod:`~meshterm.ui.pathline` rounds a path's two outer - ends when it is true and squares them off when it isn't. + Only a Nerd Font patch has these glyphs. Thus this check is narrower than + :func:`powerline_enabled`. A stock coder font (Fira Code, JetBrains Mono) draws the + core triangles natively and no other glyph. A terminal that supplies the separators + from its own renderer promises only those four glyphs. Callers use this check for + chrome that must degrade. When it is true, :mod:`~meshterm.ui.pathline` rounds the + two outer ends of a path. When it is false, the module squares them off. """ return powerline_support().level == FULL -#: The active handheld's name and glyph inventory, or ``None`` where a terminal draws -#: whatever it is sent. Bound at platform-switch time (:func:`_bind`). +#: The name and the glyph inventory of the active handheld, or ``None`` where a terminal +#: draws all that it receives. MeshTerm binds it when the platform switches (:func:`_bind`). _HANDHELD_FONT: tuple[str, frozenset[int]] | None = None @on_platform def _bind(platform: Platform) -> None: - """Bind the handheld font the verdict reads, and drop the verdict the last one made.""" + """Bind the handheld font that the verdict reads, and clear the verdict of the last font.""" global _HANDHELD_FONT inventory = FONTS.get(platform.font) _HANDHELD_FONT = (platform.name, inventory) if inventory is not None else None @@ -697,7 +724,7 @@ def _bind(platform: Platform) -> None: def _installed_families() -> Iterable[str]: - """Every installed font family name this platform will admit to, best-effort.""" + """All the installed font family names that this platform reports. It does its best.""" if sys.platform == "win32": try: import winreg @@ -735,13 +762,13 @@ def _installed_families() -> Iterable[str]: def installed_recommended() -> RecommendedFont | None: - """The best recommended font *installed* on this machine, selected or not. + """The best recommended font that is installed on this machine, selected or not. - The weaker, always-available check that a future recommendation screen splits its - message on: "not installed — here's the list" versus "installed but not selected - in your terminal's profile" versus "active". Prefers :data:`FULL` coverage over - :data:`CORE`; returns ``None`` when nothing recommended is installed (or the - platform offers no way to ask). + This check is weaker, but it is always available. A future screen of recommendations + can use it to choose between three messages: "not installed — here's the list", + "installed but not selected in your terminal's profile", and "active". The function + prefers :data:`FULL` coverage to :data:`CORE`. It returns ``None`` when no + recommended font is installed, or when the platform has no way to ask. """ best: RecommendedFont | None = None for family in _installed_families(): @@ -759,14 +786,15 @@ def installed_recommended() -> RecommendedFont | None: @dataclass(frozen=True) class EmojiSupport: - """Whether this terminal can show an emoji at all, and what decided that. + """The verdict if this terminal can show an emoji at all, and what decided it. Attributes: - supported: ``True`` when an emoji icon reaches the screen as itself. + supported: ``True`` when an emoji icon reaches the screen as the emoji. source: ``"env"`` (the ``MESHTERM_EMOJI`` override), ``"platform"`` (not Windows, - so not the classic console's problem), ``"console"`` (the host was identified - — see :func:`_is_classic_console`), or ``"no-console"`` (nothing to identify: - output is redirected, or the call failed). + so the problem of the classic console does not apply), ``"console"`` (the + host was identified, refer to :func:`_is_classic_console`), or + ``"no-console"`` (there is nothing to identify: the output is redirected, or + the call failed). """ supported: bool @@ -774,37 +802,38 @@ class EmojiSupport: def _is_classic_console() -> bool | None: - """Whether this process is drawing into a genuine ``conhost`` window. + """Check if this process draws into a real ``conhost`` window. - Which is the whole question, because that host renders through GDI with the console - font and no emoji font behind it, while everything that replaced it — Windows - Terminal, VS Code's terminal, anything over ssh — draws emoji as a matter of course. + This is the whole question. That host renders through GDI with the console font and + has no emoji font behind it. All the hosts that replaced it draw emoji correctly. + These are Windows Terminal, the terminal of VS Code, and anything over ssh. - It cannot be asked in band. A missing glyph still occupies its cell, so the screen - reads back exactly as it would have if the character had drawn: measured on Windows 10 - 22H2, a classic console stores ``📡`` intact and advances two cells while showing a - single replacement box, and a ConPTY (which does draw it) reads back as U+FFFD because - the buffer behind it is updated asynchronously. A write-and-read-back probe answers - both hosts *backwards*, which is the trap this docstring exists to record. + MeshTerm cannot ask in band. A missing glyph still occupies its cell, so the screen + reads back the same as if the character had drawn. We measured this on Windows 10 + 22H2. A classic console stores ``📡`` correctly and advances two cells, but it shows + a single replacement box. A ConPTY (which does draw the emoji) reads back as U+FFFD, + because the buffer behind it is updated asynchronously. A probe that writes and reads + back gives the wrong answer for both hosts. This docstring records this trap. - Nor can the environment be trusted alone: ``WT_SESSION`` is inherited by child - processes, so a program launched from Windows Terminal into a console of its own still - carries it and would answer for the wrong host. + MeshTerm also cannot trust the environment alone. Child processes inherit + ``WT_SESSION``. A program that starts from Windows Terminal into a console of its own + still has it, and the answer is for the wrong host. - So the host is identified structurally, from two independent facts, and both must - agree before anything is dimmed (the costly mistake is stripping icons from a terminal - that could draw them): + So MeshTerm identifies the host from its structure, with two independent facts. Both + facts must agree before MeshTerm dims anything. The costly mistake is to remove the + icons from a terminal that can draw them. - * **The console font has a real pixel width.** A ConPTY's hidden conhost reports a - stub — face ``Consolas``, cell width ``0`` — because nothing is rasterised there. + * **The console font has a real pixel width.** The hidden conhost of a ConPTY reports + a stub (face ``Consolas``, cell width ``0``), because it rasterizes nothing. * **The buffer is taller than its window.** A classic console owns its scrollback - (9001 rows by default); under a ConPTY the terminal owns it, so the buffer is - exactly the window. + (9001 rows by default). Under a ConPTY the terminal owns the scrollback, so the + buffer is the same as the window. Returns: - ``True`` for a genuine classic console, ``False`` for anything else drawing to a - console, and ``None`` when there is no console on stdout (redirected output, not - Windows, or the call failed) — an unknown is never a reason to degrade. + ``True`` for a real classic console. ``False`` for all other hosts that draw to a + console. ``None`` when there is no console on stdout (the output is redirected, + the platform is not Windows, or the call failed). An unknown result is never a + reason to degrade. """ if sys.platform != "win32": return None @@ -842,9 +871,10 @@ def _is_classic_console() -> bool | None: ("FaceName", ctypes.c_wchar * 32), ] - # Safe to declare: this handle is ours alone (see meshterm.core.win32dll). The - # explicit restype matters — ctypes would assume a 32-bit int and truncate the - # 64-bit HANDLE, turning every later call into a silent failure. + # It is safe to declare these types, because this handle is only ours (refer to + # meshterm.core.win32dll). The explicit restype is important. Without it, ctypes + # assumes a 32-bit int and cuts the 64-bit HANDLE, and each later call fails + # without a message. kernel32 = win32dll.kernel32() kernel32.GetStdHandle.argtypes = [wintypes.DWORD] kernel32.GetStdHandle.restype = wintypes.HANDLE @@ -859,8 +889,9 @@ def _is_classic_console() -> bool | None: handle = kernel32.GetStdHandle(wintypes.DWORD(-11).value) # STD_OUTPUT_HANDLE info = _CSBI() - # Fails when stdout is a pipe or a file — nothing is being drawn, so there is - # nothing to answer, and this is what keeps redirected and CI runs out of it. + # This call fails when stdout is a pipe or a file. Then MeshTerm draws nothing and + # there is no answer. This is the reason that redirected runs and CI runs do not + # use the rest of this function. if not kernel32.GetConsoleScreenBufferInfo(handle, ctypes.byref(info)): return None @@ -872,7 +903,7 @@ def _is_classic_console() -> bool | None: rasterised = font.dwFontSize.X > 0 owns_scrollback = info.dwSize.Y > (info.srWindow.Bottom - info.srWindow.Top + 1) return rasterised and owns_scrollback - except Exception: # pragma: no cover - a probe that fails is an unknown, not a crash + except Exception: # pragma: no cover - a probe that fails gives an unknown result, not a crash return None @@ -882,7 +913,7 @@ def _emoji_support( console_probe: Callable[[], bool | None] = _is_classic_console, system: str | None = None, ) -> EmojiSupport: - """The uncached verdict (see :func:`emoji_support` for the ladder).""" + """The verdict without the cache (refer to :func:`emoji_support` for the ladder).""" env = os.environ if environ is None else environ override = (env.get("MESHTERM_EMOJI") or "").strip().lower() if override in {"0", "off", "no", "none", "false"}: @@ -900,22 +931,24 @@ def _emoji_support( @lru_cache(maxsize=1) def classic_console() -> bool: - """Whether this session is drawing into a genuine ``conhost`` window. + """Check if this session draws into a real ``conhost`` window. - The one host with no font fallback of its own, so the only one where the configured - font's own repertoire decides what the reader sees. See :func:`_is_classic_console` - for how it is identified, and why not from the environment. + This is the only host that has no font fallback of its own. Thus it is the only host + where the glyphs of the configured font decide what the user sees. Refer to + :func:`_is_classic_console` for how MeshTerm identifies it, and why it does not use + the environment. """ return _is_classic_console() is True @lru_cache(maxsize=1) def emoji_support() -> EmojiSupport: - """Whether emoji icons can be drawn here, decided once and cached. + """Check if emoji icons can be drawn here. MeshTerm decides one time and caches it. - The ladder: the ``MESHTERM_EMOJI`` override, then everything that isn't Windows (where - a UTF-8 terminal draws them as a matter of course), then :func:`_is_classic_console`. - Cached because a session does not change host halfway through. + The ladder has these steps, in this order: the ``MESHTERM_EMOJI`` override, then all + platforms that are not Windows (where a UTF-8 terminal draws emoji correctly), then + :func:`_is_classic_console`. The result is cached, because a session does not change + its host during the session. Returns: The :class:`EmojiSupport` verdict. @@ -924,50 +957,52 @@ def emoji_support() -> EmojiSupport: def emoji_enabled() -> bool: - """Whether icons should render as emoji rather than through the compact table.""" + """Check if icons must render as emoji instead of through the compact table.""" return emoji_support().supported # --- chart glyphs ----------------------------------------------------------------- -#: Families measured to carry the Braille Patterns block (U+2800–U+28FF) that -#: :mod:`meshterm.ui.braillechart` draws every timeline from. +#: The families that we measured to have the Braille Patterns block (U+2800–U+28FF). +#: :mod:`meshterm.ui.braillechart` draws each timeline from this block. #: -#: The list is short on purpose, and each entry is a measurement rather than a -#: reputation: reading the ``cmap`` of every font installed on a development machine -#: (2026-09-07) found that nearly no monospace font carries the block at all. Hack Nerd -#: Font, JetBrains Mono, Fira Code, Source Code Pro, Consolas, Lucida Console and — the -#: surprise — DejaVu Sans *Mono* all measure zero of 256. DejaVu *Sans*, which is -#: proportional, carries all 256, which is where the widespread "install DejaVu for -#: braille" advice comes from: it works only because terminals fall back from the mono -#: face to the proportional one for that block. +#: The list is short on purpose. Each entry is a measurement, not a reputation. On +#: 2026-09-07 we read the ``cmap`` of each font that is installed on a development +#: machine. Almost no monospace font has the block. Hack Nerd Font, JetBrains Mono, Fira +#: Code, Source Code Pro, Consolas, Lucida Console, and DejaVu Sans *Mono* (a surprise) +#: all measure zero of 256. DejaVu *Sans* is proportional, and it has all 256. This is +#: the source of the common advice "install DejaVu for braille". The advice works only +#: because terminals fall back from the mono face to the proportional face for that +#: block. #: -#: Which is the point. On every host that falls back — Windows Terminal, VS Code's -#: terminal, macOS, Linux — the charts draw whatever the chosen font holds, so this list -#: never has to be right. It matters on the one host with no fallback at all, the classic -#: Windows console, where a font outside this list means boxes where the charts should be. +#: This is the important point. On each host that falls back (Windows Terminal, the +#: terminal of VS Code, macOS, Linux), the charts draw in any chosen font. Thus this list +#: does not have to be correct there. It matters on the one host that has no fallback, the +#: classic Windows console. There, a font that is not in this list gives boxes where the +#: charts must be. CHART_FONTS: tuple[str, ...] = ( - # Microsoft's console font: 44/44, and the family MeshTerm bundles (see - # meshterm.core.consolefont). Covers the PL and NF builds by prefix. + # The console font of Microsoft: 44/44, and the family that MeshTerm bundles (refer to + # meshterm.core.consolefont). The prefix also matches the PL and NF builds. "cascadia mono", "cascadia code", - # The Nerd Font patches of the same, which keep what they patch. + # The Nerd Font patches of the same fonts. They keep what they patch. "caskaydiacove", "caskaydiamono", - # Widely reported to carry the block; not measured here, no copy to hand. + # Many reports say that it has the block. We did not measure it, because we have no + # copy. "iosevka", ) def face_draws_charts(face: str | None) -> bool: - """Whether ``face`` can draw the braille the timelines are made of. + """Check if ``face`` can draw the braille that the timelines use. Args: face: A configured font family, in any spelling, or ``None``. Returns: - Whether it is one of :data:`CHART_FONTS`. + ``True`` if it is one of :data:`CHART_FONTS`. """ if not face: return False @@ -978,11 +1013,12 @@ def face_draws_charts(face: str | None) -> bool: def installed_chart_font() -> str | None: """The first installed family that can draw the charts, or ``None``. - What separates "select the font they already have" — every Windows 11 machine, and - anyone who has installed Windows Terminal — from "offer to install ours". + The result decides between two actions: "select the font that the user already has" + (each Windows 11 machine, and each user who installed Windows Terminal) and "offer to + install our font". Returns: - The family name as installed, or ``None`` when nothing installed can do it. + The family name as installed, or ``None`` when no installed family can do it. """ for family in _installed_families(): if face_draws_charts(family): diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index bd8d85e..98dc637 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -1,13 +1,14 @@ # SPDX-License-Identifier: Apache-2.0 -"""Shared Rich theme and console factory for a consistent, modern look. +"""The shared Rich theme and the console factory, for a consistent, modern look. -Two palettes, one vocabulary: every style *name* here exists in both -:data:`MESH_THEME` (the regular platform's truecolor look) and :data:`MESH_THEME_16` -(the PicoCalc console's 16-slot look), so screens never know which one is active — they -ask for ``"warn"`` or ``"snr.good"`` and the platform decides what that means. The -active theme, the name-colouring rule, the icon funnel and the render-boundary fold are -all **bound at platform-switch time** through :func:`meshterm.platforms.on_platform`: -the hot render paths read module globals and never re-derive platform state per call. +There are two palettes and one vocabulary. Each style name here is in both +:data:`MESH_THEME` (the truecolor look of the regular platform) and :data:`MESH_THEME_16` +(the 16-slot look of the PicoCalc console). Thus screens do not know which theme is +active. They ask for ``"warn"`` or ``"snr.good"``, and the platform decides what that +means. The active theme, the rule for the colour of names, the icon funnel, and the fold +at the render boundary are all **bound when the platform switches**, through +:func:`meshterm.platforms.on_platform`. The hot render paths read module globals, and +they never find the platform state again for each call. """ from __future__ import annotations @@ -28,155 +29,172 @@ MESH_THEME = Theme( { "brand": "bold #5eead4", "accent": "bold #818cf8", - # THE reverse-video chip — a dialog's committing button, a running action's Abort, - # the composer's insertion slot where there is no chip fill to carry it. A *grey* - # block with the page's own ink showing through, because the cyan it used to be - # was the wordmark's teal doing a third job (identity, and a node hue, and now a - # selection), and a chip is chrome: it marks where a press lands, it does not - # claim a colour. The slate is ``muted``'s, light enough that the reversed ink — - # whatever the terminal's background happens to be — reads on it. It must be a - # *single* theme name: Rich silently drops a style string that mixes a theme name - # with an attribute (e.g. "reverse muted" renders as plain text), so the reverse is - # baked into the definition here rather than tacked on at the call site. + # The only reverse-video chip: the committing button of a dialog, the Abort of a + # running action, and the insertion slot of the composer where no chip fill carries + # it. It is a *grey* block, and the ink of the page shows through it. It was cyan + # before. That cyan was the teal of the wordmark with a third job (identity, a + # node hue, and now a selection). A chip is chrome. It shows where a press lands, + # and it does not claim a colour. The slate is the slate of ``muted``. It is light + # enough that the reversed ink reads on it, in any background of the terminal. It + # must be a *single* theme name. Rich removes without a message a style string that + # mixes a theme name with an attribute (for example "reverse muted" renders as plain + # text). Thus the reverse is part of the definition here, and the call site does + # not add it. "selected": "reverse bold #94a3b8", - # THE ink of "this is the one you picked" — the row the ❯ points at, in every - # select list and in every screen that draws its own rows (feed, routes, records, - # walk, composer), and the lit column heading one axis over where a list is - # sorted. White, and deliberately *not* ``brand``: the highlight used to borrow - # the wordmark's teal, which put the app's identity ink and "the row you're on" - # on the same hue, and worse, teal/cyan is itself a node hue — a cyan-keyed - # node's name vanished into its own highlight. White is outside the per-node - # spectrum (see node_style) so it can never collide with an identity. It does - # share ink with ``you``, which is the accepted cost. Spans that set their own - # colour keep it over the base — the heat of an age, an SNR reading, a red badge - # — with the one exception the highlight is *for*: a node's own key-derived hue - # folds to this white on the cursor row (see theme.is_identity_style and - # ui.tui.render._whiten_identities), so the row the reader is on reads as one - # thing rather than as a name competing with its own selection. Bold like - # ``brand`` was, so the dim-slot ``not bold`` pins that protect a span inside a - # highlighted row (see MESH_THEME_16) go on meaning what they meant. + # The only ink for "this is the one that the user selected". It is the row that the + # ❯ points at, in each select list and in each screen that draws its own rows + # (feed, routes, records, walk, composer). It is also the lit column heading one + # axis over, where a list is sorted. It is white, and not ``brand`` on purpose. The + # highlight once used the teal of the wordmark. Then the identity ink of the app and + # "the row you are on" had the same hue. Also, teal/cyan is a node hue, so the name + # of a node with a cyan key disappeared into its own highlight. White is outside the + # spectrum of the nodes (refer to node_style), so it can never be the same as an + # identity. It has the same ink as ``you``, and we accept that cost. Spans that set + # their own colour keep it over the base: the heat of an age, an SNR reading, a red + # badge. The highlight exists for one exception. The hue of a node, which comes from + # its key, folds to this white on the cursor row (refer to theme.is_identity_style + # and ui.tui.render._whiten_identities). Thus the row that the user is on reads as + # one thing, and not as a name that competes with its own selection. It is bold, as + # ``brand`` was. Thus the ``not bold`` pins of the dim slots (refer to + # MESH_THEME_16), which protect a span in a highlighted row, keep their meaning. "cursor": "bold #ffffff", - # THE mark a path line puts around its own hops (PathLine._render), so the cursor - # row's identity fold can see where a route starts and stops - # (ui.tui.render._whiten_identities): inside a path line a node's hue is not - # decoration on a name, it is what tells one hop from the next — and what the - # graph drawn above the row cross-references, since a graph label is only a - # marker and one byte of hash. Folding those to white made a picked route read as - # one long white smear with no way back to the picture. Chips were never affected - # (their fills sit outside the fold's vocabulary); this is what makes the arrow - # form — every path line on the PicoCalc, and on any terminal without the - # powerline glyphs — say the same thing. Renders as nothing: it exists to be read - # at the render boundary, not seen. + # The only mark that a path line puts around its own hops (PathLine._render). The + # identity fold of the cursor row (ui.tui.render._whiten_identities) uses it to see + # where a route starts and stops. In a path line, the hue of a node is not a + # decoration on a name. It shows the difference between one hop and the next. The + # graph above the row also cross-references it, because a label of the graph is + # only a marker and one byte of a hash. When the fold made these hues white, a + # selected route looked like one long white smear, and the user could not find the + # way back to the picture. Chips were never affected, because their fills are + # outside the vocabulary of the fold. This mark makes the arrow form say the same + # thing. The arrow form is every path line on the PicoCalc, and every path line on + # a terminal without the powerline glyphs. The mark renders as nothing. The render + # boundary reads it, and the user does not see it. "pathline": "none", - # Reversed error (the text-editor cursor sitting on an over-budget character). Baked - # in for the same reason as ``selected`` — "reverse err" would render as plain text. + # Reversed error (the cursor of the text editor on a character over the budget). It + # is part of the definition for the same reason as ``selected``: "reverse err" + # renders as plain text. "err.reverse": "reverse bold #f87171", - # Our own node, anywhere it is named: pure white, deliberately outside the - # per-node hue spectrum (see node_style) so "you" is always easy to spot. + # Our node, in each place where it has a name: pure white, and outside the spectrum + # of the node hues on purpose (refer to node_style). Thus the user can always find + # "you" easily. "you": "bold #ffffff", - # A confirmed companion's name on the startup device picker: pure white so the - # devices we've actually talked to before jump out above the merely-detected ports. + # The name of a confirmed companion on the picker for the startup device: pure + # white. Thus the devices that we talked to before are more visible than the ports + # that MeshTerm only detected. "device.known": "bold #ffffff", - # A QR code's modules: pure white ink on a pure black field, both ends named so - # no palette can dilute the contrast a camera reads (see ui/qr.py). Never black - # on white — a light-on-dark code is what a scanner expects of a screen. + # The modules of a QR code: pure white ink on a pure black field. Both ends have + # names, so no palette can reduce the contrast that a camera reads (refer to + # ui/qr.py). The code is never black on white, because a scanner expects a code + # that is light on dark on a screen. "qr": "#ffffff on #000000", - # The picker's Bluetooth TYPE badge: a white rune on the official Bluetooth blue - # (Pantone 300, #0057b8), echoing the real logo so BLE reads at a glance. + # The Bluetooth TYPE badge of the picker: a white rune on the official Bluetooth + # blue (Pantone 300, #0057b8). It is like the real logo, so the user can see BLE + # at a glance. "bluetooth": "bold #ffffff on #0057b8", - # The badge's tapered edges: half-block glyphs drawn in the same blue as the - # foreground (over the terminal's own background), so only their inner half fills and - # the badge reads a touch wider than the single rune cell without a hard rectangle. + # The tapered edges of the badge: half-block glyphs in the same blue as the + # foreground (over the background of the terminal). Only their inner half fills. + # Thus the badge looks a little wider than the single rune cell, and it has no hard + # rectangle. "bluetooth.edge": "#0057b8", "ok": "bold #4ade80", "warn": "bold #fbbf24", "err": "bold #f87171", "muted": "#94a3b8", - # A node we can't identify — its ``○`` ring, and its label wherever a bare key or - # hash stands in for a name (see name_style's keyless return). Its own name rather - # than plain ``muted`` because the two must not track each other: ``muted`` is - # chrome and may sit a step down from body text, while an unidentified node is - # *content* you can still act on. On the console that difference is the whole - # ladder — chrome takes the dark grey slot, this one the light grey. + # A node that MeshTerm cannot identify: its ``○`` ring, and its label where a bare + # key or hash is the name (refer to the return of name_style when there is no key). + # It has its own name and does not use ``muted``, because the two styles must not + # change together. ``muted`` is chrome, and it can be a step darker than the body + # text. An unidentified node is *content* on which the user can still act. On the + # console this difference is the whole ladder: chrome takes the dark grey slot, + # and this style takes the light grey slot. "node.unknown": "#94a3b8", - # Panel/dialog titles: the same hue as the border they sit in, one shade brighter, - # so the title reads as part of its frame while still standing out from it. One - # entry per border style the frame compositor is given (see theme.title_style). + # The titles of panels and dialogs: the same hue as the border that they are in, + # one shade brighter. Thus the title reads as part of its frame, and it is still + # different from the frame. There is one entry for each border style that the frame + # compositor receives (refer to theme.title_style). "title.accent": "bold #a5b4fc", "title.muted": "bold #cbd5e1", "title.warn": "bold #fcd34d", "title.err": "bold #fca5a5", "title.ok": "bold #86efac", "title.brand": "bold #99f6e4", - # Panel/dialog footer hints: the border's hue one shade *darker* (and not bold), the - # mirror image of the ``title.*`` brightening — the hint reads as part of the frame - # while receding behind it. One entry per border style (see theme.hint_style). + # The footer hints of panels and dialogs: the hue of the border, one shade *darker* + # (and not bold). This is the opposite of the brightening of the ``title.*`` styles. + # The hint reads as part of the frame, and it stays behind the frame. There is one + # entry for each border style (refer to theme.hint_style). "hint.accent": "#6366f1", "hint.muted": "#64748b", "hint.warn": "#f59e0b", "hint.err": "#ef4444", "hint.ok": "#22c55e", "hint.brand": "#2dd4bf", - # A step darker than ``muted`` for placeholder dashes (a node's missing packet count / - # age) that should recede below the real, muted values around them. + # A step darker than ``muted``, for placeholder dashes (the missing packet count or + # age of a node). They must stay behind the real, muted values around them. "faint": "#64748b", - # A section heading's ``── Label ──`` — a grouped list's, a chat's day divider. A - # dark grey, never the frame's accent: in the border's own colour a heading's rule - # read as part of the frame it sits in (JP, 2026-10-02). Bold, so the label still - # reads as a landmark at that shade. + # The ``── Label ──`` of a section heading: in a grouped list, and the day divider + # of a chat. It is a dark grey, and never the accent of the frame. When the rule of + # a heading had the colour of the border, it looked like part of the frame that it + # is in (JP, 2026-10-02). It is bold, so the label is still a landmark at that + # shade. "heading": "bold #64748b", - # A further step darker than ``faint``, for a meter's unlit track (the SNR quality - # bars): dark enough to read as background, not as a dimmer version of the reading. + # A further step darker than ``faint``, for the unlit track of a meter (the SNR + # quality bars). It is dark enough to look like a background, and not like a + # dimmer version of the reading. "track": "#334155", "snr.good": "bold #4ade80", "snr.ok": "bold #fbbf24", "snr.bad": "bold #f87171", - # The status-bar battery gauge: a filled block, not four thin dots. Every cell is a - # lit foreground over its own darker ground of the same hue — light green on green - # over half, yellow on brown over a quarter, light red on red below — so the gauge - # reads as a *block* at a glance and the braille fill inside it says how much of the - # pack is left. ``batt.flash`` and ``batt.flash.off`` are the two beats of the - # last-percent alarm: black dots on red, alternating with the light red on the bare - # page. Losing the ground for a beat is a bigger change than any hue swap could be, - # which is what makes it read across a room. + # The battery gauge of the status bar: a filled block, and not four thin dots. Each + # cell is a lit foreground over its own darker ground of the same hue: light green + # on green above half, yellow on brown above a quarter, light red on red below. + # Thus the gauge looks like a *block* at a glance, and the braille fill in it shows + # how much of the battery is left. ``batt.flash`` and ``batt.flash.off`` are the two + # beats of the alarm for the last percent: black dots on red, then in turn the light + # red on the bare page. When the ground is lost for one beat, the change is bigger + # than a change of hue. Thus the user can see it from across a room. "batt.full": "bold #4ade80 on #15803d", "batt.mid": "bold #fbbf24 on #a16207", "batt.low": "bold #f87171 on #991b1b", "batt.flash": "not bold #000000 on #dc2626", "batt.flash.off": "bold #f87171", - # The node-type *marks* — THE colours behind ● ▲ ■ ◉ wherever a typed node is - # drawn (see ui.widgets.NODE_GLYPHS), and the map's own marker language: clients - # the loud pink, repeaters the calmer violet, rooms a white square, sensors an - # orange ringed dot. Named styles rather than raw hex so the 16-slot console picks - # its slot *deliberately* — a naive downsample of the violet lands on grey, which - # would make a repeater read as an unknown node. + # The node-type *marks*: the only colours for ● ▲ ■ ◉ where a node with a type is + # drawn (refer to ui.widgets.NODE_GLYPHS). They are also the language of the markers + # of the map: clients are the loud pink, repeaters are the calmer violet, rooms are + # a white square, and sensors are an orange dot with a ring. They are named styles + # and not raw hex, so the 16-slot console chooses its slot *on purpose*. A naive + # downsample of the violet gives grey, and a repeater looks like an unknown node. "type.node": "#f472b6", "type.repeater": "#a78bfa", "type.room": "#ffffff", "type.sensor": "#fb923c", - # A region name (a flood's scope). Not a node, so no hue from the node wheel: a - # light slate, set apart from prose by its slant the way a tag is from a sentence. + # A region name (the scope of a flood). It is not a node, so it has no hue from the + # node wheel. It is a light slate. Its slant makes it different from prose, as a + # tag is different from a sentence. "scope": "italic #cbd5e1", - # The basemap features whose *hue* is the information — water is blue, parks are - # green, a highway is the warm one — and which a naive downsample therefore ruins - # (the dark blue lands on grey, the dark green on black, the amber on bright red). - # Named for the same reason as ``type.*``: the console picks the slot itself. The - # rest of the basemap is grey by design and quantizes honestly, so minor roads, - # rail, boundaries and labels stay literal hex in ui.map_render. + # The features of the basemap for which the *hue* is the information: water is + # blue, parks are green, and a highway is the warm colour. A naive downsample + # damages them (the dark blue becomes grey, the dark green becomes black, and the + # amber becomes bright red). They have names for the same reason as ``type.*``: the + # console chooses the slot itself. The rest of the basemap is grey by design, and + # it quantizes correctly. Thus minor roads, rail, boundaries, and labels stay + # literal hex in ui.map_render. "map.water": "#153b56", "map.river": "#49b0ec", "map.stream": "#3f8fbf", "map.ditch": "#3a7ba6", "map.park": "#173a29", "map.highway": "#f2a13d", - # The heard-age heat scale's steps, named for how old the node they colour is: - # a node heard eight minutes ago is ``heat.minutes``, one heard eight days ago is - # ``heat.days``. Seven steps from white-hot to cold ash (JP's spec) — a cooling - # ember, then what's left of it. ``heat.never`` is both "over a year" and "never - # heard": past a year the distinction stops being worth a colour. + # The steps of the heat scale for the heard age. Each step has the name of the age + # of the node that it colours: a node that MeshTerm heard eight minutes ago is + # ``heat.minutes``, and a node that it heard eight days ago is ``heat.days``. There + # are seven steps, from white-hot to cold ash (JP's spec). It is a cooling ember, + # and then what is left of it. ``heat.never`` is both "over a year" and "never + # heard", because after one year a different colour is not worth the difference. # The regular platform interpolates a continuous gradient over the same anchors - # rather than stepping (see ui.widgets._recency_style), so these are its ladder - # spelled out — every style name resolves on both platforms either way. + # and does not use steps (refer to ui.widgets._recency_style). Thus these styles + # are its ladder, written out. Each style name resolves on both platforms in + # both cases. "heat.now": "#ffffff", # under 5 minutes "heat.minutes": "#facc15", # 5 minutes "heat.hours": "#f87171", # 1 hour @@ -184,26 +202,29 @@ MESH_THEME = Theme( "heat.weeks": "#dc2626", # 1 week "heat.months": "#94a3b8", # 1 month "heat.never": "#64748b", # 1 year, and never heard - # The PicoCalc F-key lane's chip fills (see ui.tui.fkeys): gray for the plain - # F1-F5 bank, green while the Shift watcher reports F6-F10. White text on both — - # defined here too so the style names resolve on every platform, even though - # only PicoCalc's footer_fkeys ever asks for them. + # The chip fills of the F-key lane of the PicoCalc (refer to ui.tui.fkeys): grey for + # the plain F1-F5 bank, and green while the Shift watcher reports F6-F10. The text + # is white on both. They are also defined here so that the style names resolve on + # each platform, although only footer_fkeys of the PicoCalc asks for them. "fkey.chip": "bold #ffffff on #475569", "fkey.chip.shift": "bold #ffffff on #16a34a", - # The Cardputer Zero deck's fills, taken from its own keyboard (JP, 2026-09-30): - # the orange-red the fn key and its F4–F8 legends are printed in, and while Shift - # is held, the dark blue of the Shift key in M5's product photo. The print's - # #ff6633 holds white text at only 2.9:1, so the chip is that colour a step darker - # in OKLab at the same hue and chroma (L 0.70 → 0.62, h 38°): 4.0:1, still a - # vermilion — chroma is in gamut all the way down, so nothing greys it to brown. + # The fills of the Cardputer Zero deck, taken from its own keyboard (JP, + # 2026-09-30). The normal fill is the orange-red in which the fn key and its F4–F8 + # legends are printed. While Shift is held, the fill is the dark blue of the Shift + # key in the product photo of M5. White text on the #ff6633 of the print has a + # contrast of only 2.9:1. Thus the chip is that colour, a step darker in OKLab at + # the same hue and chroma (L 0.70 → 0.62, h 38°). The contrast is 4.0:1, and the + # colour is still a vermilion. The chroma is in the gamut all the way down, so + # nothing makes it a grey brown. "fkey.chip.cardputer_zero": "bold #ffffff on #e34b0f", "fkey.chip.cardputer_zero.shift": "bold #ffffff on #0f72bd", - # The prose voices — what a markdown page's inline marks are drawn in (see - # ui.markdown). Headings borrow the styles the rest of the app already heads - # sections with (``brand``, ``accent``), so only the *body* marks need names of - # their own: emphasis brighter than the page, an aside dimmer than it, code and - # links in the two hues nothing else in a body claims, a struck-out run receding - # to the placeholder grey, and the bullet/rail chrome a list or a quote hangs on. + # The prose voices: the styles of the inline marks of a markdown page (refer to + # ui.markdown). Headings use the styles that the rest of the app already uses for + # section headings (``brand``, ``accent``). Thus only the *body* marks need their own + # names. Emphasis is brighter than the page. An aside is dimmer than the page. Code + # and links have the two hues that nothing else in a body uses. A struck-out run + # goes back to the placeholder grey. The bullet and the rail are the chrome on which + # a list or a quote hangs. "md.strong": "bold #e2e8f0", "md.em": "italic #cbd5e1", "md.code": "#7dd3fc", @@ -215,25 +236,26 @@ MESH_THEME = Theme( } ) -#: The PicoCalc console's 16 palette slots — the **standard kernel VT palette**, by JP's -#: decision (2026-08-01): the console is not remapped, so other software looks stock and -#: the black background stays black. :data:`MESH_THEME_16` is designed against these -#: RGBs, and the fold's stray-truecolor quantizer matches against them. Rules that still -#: bind: +#: The 16 palette slots of the PicoCalc console. They are the **standard kernel VT +#: palette**, by the decision of JP (2026-08-01): the console is not remapped, so other +#: software looks stock and the black background stays black. :data:`MESH_THEME_16` is +#: designed for these RGB values, and the quantizer of the fold for stray truecolor +#: matches against them. These rules still apply: #: -#: * The kernel VT renders **bold as brightness**: ``bold`` on a 0–7 foreground jumps it -#: to slot N+8. So a dim-slot style must say what it means about bold — it cannot leave -#: the question open, because Rich merges a *base* style into every span it wraps and a -#: selected row's ``bold`` would then recolour the span outright (a light-grey unknown -#: hash arriving as white "you", a purple repeater as pink). Every dim-slot style is -#: therefore either explicitly ``not bold`` (the colour is load-bearing; keep it) or -#: explicitly ``bold`` (the promotion *is* the intent — only ``title.muted``). Never -#: silent, and never bold on 5/6, whose partners are claimed by *different* semantics -#: here (5 purple = the repeater mark, 13 pink = the node mark; 6 cyan = hint.brand, -#: 14 bright cyan = brand). -#: * Backgrounds can only address slots 0–7 (SGR 40–47). -#: * The six *chromatic bright* slots (9-14) are the node-name spectrum's landing zone — -#: the console's rendering of the key-derived hue wheel (see :data:`_NODE_SLOT_HEXES`). +#: * The kernel VT renders **bold as brightness**. ``bold`` on a foreground in slots 0–7 +#: moves it to slot N+8. Thus a style for a dim slot must say what it means about +#: bold. It cannot leave the question open, because Rich merges a *base* style into +#: each span that it wraps. Then the ``bold`` of a selected row changes the colour of +#: the span completely (a light-grey unknown hash becomes the white "you", and a purple +#: repeater becomes pink). Thus each style for a dim slot is explicitly ``not bold`` +#: (the colour is necessary, so keep it) or explicitly ``bold`` (the promotion is the +#: intent, and only ``title.muted`` has it). A style is never silent. Never use bold on +#: 5 and 6, because *different* meanings use their partners here (5 purple = the +#: repeater mark, 13 pink = the node mark. 6 cyan = hint.brand, 14 bright cyan = brand). +#: * Backgrounds can use only slots 0–7 (SGR 40–47). +#: * The six *chromatic bright* slots (9-14) are the place where the spectrum of node +#: names lands. They are the console rendering of the hue wheel that comes from the key +#: (refer to :data:`_NODE_SLOT_HEXES`). _VT_SLOTS: tuple[tuple[int, str, str], ...] = ( (0, "background (black)", "#000000"), (1, "red (hint.err)", "#aa0000"), @@ -266,12 +288,14 @@ def slot_hex(slot: int) -> str: #: and the bright slot is the text on it. DIM_TWIN: dict[str, str] = {slot_hex(n + 8): slot_hex(n) for n in range(8)} -#: The custom 16-slot remap P3 originally shipped (tailwind-family RGBs programmed via -#: ``setvtrgb``) — **archived, not installed**: JP chose the standard palette but asked -#: to keep this in case he changes his mind. Reinstall with +#: The custom 16-slot remap that P3 shipped first (tailwind-family RGB values that +#: ``setvtrgb`` programs). It is **archived and not installed**. JP chose the standard +#: palette, but he asked us to keep this remap in case he changes his mind. To install it +#: again, run #: ``MESHTERM_CUSTOM_PALETTE=1 sh scripts/picocalc-lyra/calculinux-console-font-6x12.sh`` -#: (whose opt-in block a test keeps byte-identical to :func:`vtrgb_lines`); MESH_THEME_16 would then -#: want re-tuning against it (see git history at c6485c6 for the matching theme). +#: (a test makes sure that its opt-in block is byte-identical to :func:`vtrgb_lines`). +#: Then MESH_THEME_16 needs a new adjustment for this remap (refer to the git history at +#: c6485c6 for the matching theme). _VT_SLOTS_CUSTOM: tuple[tuple[int, str, str], ...] = ( (0, "background slate", "#0f172a"), (1, "red (hint.err)", "#ef4444"), @@ -295,9 +319,10 @@ _VT_SLOTS_CUSTOM: tuple[tuple[int, str, str], ...] = ( def vtrgb_lines() -> str: """The ``setvtrgb`` file content for the **archived custom** palette (three CSV lines). - Not installed by default — see :data:`_VT_SLOTS_CUSTOM`. The deploy script's opt-in - block carries this same content literally (a test keeps the two in sync), so the - remap stays one environment variable away without running Python. + MeshTerm does not install it by default (refer to :data:`_VT_SLOTS_CUSTOM`). The + opt-in block of the deploy script has this same content as literal text (a test makes + sure that the two are the same). Thus the remap needs only one environment variable, + and it does not need Python. """ channels = [] for shift in (16, 8, 0): @@ -306,29 +331,32 @@ def vtrgb_lines() -> str: return "\n".join(channels) + "\n" -#: The 16-slot palette theme: the same style names as :data:`MESH_THEME`, expressed as -#: ``color(N)`` references into :data:`_VT_SLOTS` — the **standard** VT palette. Kept -#: literal (rather than derived) so a slot choice is reviewable next to its meaning; the -#: bold-brightness and background rules it must obey are documented on -#: :data:`_VT_SLOTS` and pinned by tests. Notable stock-palette wins: bright pink (13) -#: is the map's client colour for free, and dim purple (5) stands in for the map's -#: repeater violet. The cost: the three grey depths (muted/faint/track) all collapse -#: onto slot 8 — the stock palette has exactly one dark grey. +#: The 16-slot palette theme. It has the same style names as :data:`MESH_THEME`, written +#: as ``color(N)`` references into :data:`_VT_SLOTS`, which is the **standard** VT +#: palette. The theme is literal and not derived, so a reviewer can see each slot choice +#: next to its meaning. The rules for bold-brightness and for backgrounds, which the +#: theme must obey, are in the documentation of :data:`_VT_SLOTS`, and tests pin them. +#: The stock palette gives two important results. Bright pink (13) is the colour of the +#: clients on the map, at no cost. Dim purple (5) replaces the violet of the repeaters +#: on the map. The cost is that the three greys (muted, faint, track) all become slot 8, +#: because the stock palette has only one dark grey. MESH_THEME_16 = Theme( { "brand": "bold color(14)", "accent": "bold color(12)", - # Slot 7 is the only grey the VT can put *behind* a reverse: backgrounds stop at - # the dim bank, and slot 8's dark grey lands on black there. It is the same light - # grey the F-key lane already fills its chips with, which is the point — one chip - # look on the device. ``not bold`` because 7 is a dim slot (see the bold rule). + # Slot 7 is the only grey that the VT can put *behind* a reverse. Backgrounds stop at + # the dim bank, and the dark grey of slot 8 becomes black there. It is the same + # light grey that the F-key lane already uses to fill its chips. This is the + # purpose: the handheld has one chip look. It is ``not bold`` because 7 is a dim + # slot (refer to the bold rule). "selected": "reverse not bold color(7)", - # Slot 15, the top of the bright bank — so the row's bold cannot promote it - # further, and every dim-slot span inside it behaves exactly as it did under the - # old bold slot-14 highlight. + # Slot 15 is the top of the bright bank. Thus the bold of the row cannot promote it + # more, and each span for a dim slot in the row behaves as it did under the old + # highlight, which was bold slot 14. "cursor": "bold color(15)", - # The path line's extent mark — see the regular theme. Nothing to draw, but both - # themes name the same styles, and the fold that reads it runs on both. + # The mark for the extent of a path line (refer to the regular theme). It draws + # nothing. Both themes have the same style names, and the fold that reads it runs on + # both. "pathline": "none", "err.reverse": "reverse bold color(9)", "you": "bold color(15)", @@ -340,12 +368,12 @@ MESH_THEME_16 = Theme( "warn": "bold color(11)", "err": "bold color(9)", "muted": "color(8)", - # Light grey, a step *above* muted's dark grey: the console has exactly two greys, - # and an unidentified node's hash is content, not chrome. + # Light grey, a step *above* the dark grey of muted. The console has only two greys, + # and the hash of an unidentified node is content, not chrome. "node.unknown": "not bold color(7)", "title.accent": "bold color(12)", - # The one deliberate promotion: bold takes slot 7 to 15, and near-white is exactly - # what this title wants (the regular theme spells it #cbd5e1). + # The one promotion on purpose: bold moves slot 7 to 15. This title needs a colour + # that is almost white (the regular theme writes it as #cbd5e1). "title.muted": "bold color(7)", "title.warn": "bold color(11)", "title.err": "bold color(9)", @@ -358,15 +386,16 @@ MESH_THEME_16 = Theme( "hint.ok": "not bold color(2)", "hint.brand": "not bold color(6)", "faint": "color(8)", - # The console's one dark grey; slot 8 is already the bright bank, so bold moves nothing. + # The one dark grey of the console. Slot 8 is already in the bright bank, so bold + # changes nothing. "heading": "bold color(8)", "track": "color(8)", "snr.good": "bold color(10)", "snr.ok": "bold color(11)", "snr.bad": "bold color(9)", - # Each band is its bright slot over its own dim one — the console has exactly one - # pair per hue, and backgrounds stop at the dim bank, so the block look is the - # palette's natural shape rather than a compromise with it. + # Each band is its bright slot over its own dim slot. The console has only one pair + # for each hue, and backgrounds stop at the dim bank. Thus the block look is the + # natural shape of the palette, and it is not a compromise. "batt.full": "bold color(10) on color(2)", "batt.mid": "bold color(11) on color(3)", "batt.low": "bold color(9) on color(1)", @@ -376,24 +405,27 @@ MESH_THEME_16 = Theme( "type.repeater": "not bold color(5)", "type.room": "color(15)", "type.sensor": "not bold color(3)", - # A region name: the VT has no italic and every chromatic slot is a node hue, so - # the plain light grey — the word "scope" in front of it does the setting apart. + # A region name: the VT has no italic, and each chromatic slot is a node hue. Thus + # the style is the plain light grey. The word "scope" in front of it makes it + # different from other text. "scope": "not bold color(7)", - # The basemap on the console: a water body is the dim blue, every watercourse - # crossing it the bright blue one rung up (the palette has exactly one of each — - # a river's depth of shade is a truecolour luxury, and all three waterway shades - # land on the same rung here), parks the dim green, highways brown. Backgrounds - # never come into it: the canvas paints these as braille dots in the foreground. + # The basemap on the console: a body of water is the dim blue, and each watercourse + # that crosses it is the bright blue, one step up. (The palette has only one of + # each. A depth of shade for a river is a luxury of truecolour, and all three + # shades of waterway are the same step here.) Parks are the dim green, and highways + # are brown. Backgrounds are not used here, because the canvas paints these as + # braille dots in the foreground. "map.water": "not bold color(4)", "map.river": "color(12)", "map.stream": "color(12)", "map.ditch": "color(12)", "map.park": "not bold color(2)", "map.highway": "not bold color(3)", - # JP's ladder, slot by slot: white-hot, yellow, the ember's light red, brown as it - # chars, dark red as it dies, then ash — light grey, and cold grey for what may as - # well never have been heard. Six of the sixteen slots do the whole scale; the - # three in the dim bank say ``not bold`` or a selected row would jump them a rung. + # The ladder of JP, slot by slot: white-hot, yellow, the light red of the ember, + # brown as it chars, dark red as it dies, then ash (light grey), and cold grey for + # a node that is the same as never heard. Six of the sixteen slots make the whole + # scale. The three styles in the dim bank say ``not bold``. If they do not, a + # selected row moves them up one step. "heat.now": "bold color(15)", "heat.minutes": "color(11)", "heat.hours": "color(9)", @@ -401,25 +433,26 @@ MESH_THEME_16 = Theme( "heat.weeks": "not bold color(1)", "heat.months": "not bold color(7)", "heat.never": "color(8)", - # The F-key lane's chip fills: light-grey background (the palette's only "gray" - # addressable as a background — see _VT_SLOTS) for the plain bank, green for the - # Shift bank, white text on both. + # The chip fills of the F-key lane: a light-grey background for the plain bank (the + # only grey in the palette that a background can use, refer to _VT_SLOTS), green for + # the Shift bank, and white text on both. "fkey.chip": "bold color(15) on color(7)", "fkey.chip.shift": "bold color(15) on color(2)", - # The Cardputer deck's fills, for name parity: that panel is truecolor, so these - # are only its colours' nearest slots — red for the fn key's orange, blue for the - # Shift blue. + # The fills of the Cardputer deck, so that the names are the same on both. That + # display is truecolor, so these are only the nearest slots to its colours: red for + # the orange of the fn key, and blue for the blue of Shift. "fkey.chip.cardputer_zero": "bold color(15) on color(1)", "fkey.chip.cardputer_zero.shift": "bold color(15) on color(4)", - # Prose on the console. The page's body text is the default light grey (slot 7), - # so emphasis is the one place the VT's bold-is-brightness rule *is* the design: - # ``md.strong`` says bold on purpose and lands on white, exactly the step up the - # truecolor theme spells out. Its opposite, ``md.em``, keeps slot 7 by saying so. - # Code takes the dim cyan (never bold — slot 6's bright partner is the brand), - # links the bright blue, and the chrome (bullets, rails, a struck run) the two - # greys, so a page reads as text with landmarks rather than as a colour chart. - # No underline anywhere: the VT renders it by swapping in the console's own - # underline colour, which would take the link's hue away from it. + # Prose on the console. The body text of the page is the default light grey (slot + # 7). Thus emphasis is the one place where the rule of the VT, bold is brightness, + # is the design. ``md.strong`` says bold on purpose and becomes white. This is the + # same step up that the truecolor theme writes out. Its opposite, ``md.em``, keeps + # slot 7 because it says so. Code uses the dim cyan (never bold, because the bright + # partner of slot 6 is the brand). Links use the bright blue. The chrome (bullets, + # rails, a struck-out run) uses the two greys. Thus a page reads as text with + # landmarks and not as a colour chart. There is no underline anywhere. The VT + # renders it with the own underline colour of the console, and this removes the hue + # of the link. "md.strong": "bold color(7)", "md.em": "not bold color(7)", "md.code": "not bold color(6)", @@ -433,29 +466,32 @@ MESH_THEME_16 = Theme( def active_theme() -> Theme: - """The platform's theme — :data:`MESH_THEME`, or :data:`MESH_THEME_16` on PicoCalc.""" + """The theme of the platform: :data:`MESH_THEME`, or :data:`MESH_THEME_16` on the PicoCalc.""" return _ACTIVE_THEME def mark_rgb(colour: str) -> tuple[int, int, int]: - """A marker colour as an RGB triple — for the braille rasters. + """A marker colour as an RGB triple, for the braille rasters. - A canvas paints in RGB, not in styles (see :mod:`~meshterm.ui.mapcanvas`), so a marker - that wants to agree with its Rich-drawn twin resolves the *same colour* through here. - Takes either encoding the marker language uses: a literal ``#rrggbb`` (the fixed map - marks in :mod:`~meshterm.ui.marks`) or a theme style name (the node-type marks, which - are named so each platform picks its own — see the theme's ``type.*``). + A canvas paints in RGB and not in styles (refer to :mod:`~meshterm.ui.mapcanvas`). A + marker that must agree with its twin that Rich draws gets the *same colour* through + this function. The function accepts both encodings that the marker language uses. One + is a literal ``#rrggbb`` (the fixed map marks in :mod:`~meshterm.ui.marks`). The other + is a theme style name (the node-type marks, which have names so that each platform + chooses its own colour, refer to ``type.*`` of the theme). - On the 16-slot theme a ``color(N)`` entry resolves to that slot's own :data:`_VT_SLOTS` - RGB rather than Rich's stock triple: Rich's palette is a shade off ours and the fold's - quantizer matches against ours, so the round trip would otherwise land the marker on a - neighbouring slot. Memoized (cleared on a platform switch); a raster asks per node. + On the 16-slot theme, a ``color(N)`` entry gives the own :data:`_VT_SLOTS` RGB of that + slot, and not the stock triple of Rich. The palette of Rich is a shade different from + ours, and the quantizer of the fold matches against ours. If the function used the + stock triple, the round trip would put the marker on a neighbouring slot. The + function caches its results (a platform switch clears the cache). A raster asks for + each node. Args: - colour: ``#rrggbb``, or a style name defined in both themes. + colour: ``#rrggbb``, or a style name that both themes define. Returns: - The ``(r, g, b)`` triple; mid-grey for a style with no colour of its own. + The ``(r, g, b)`` triple. For a style that has no colour of its own, it is mid-grey. """ cached = _STYLE_RGB.get(colour) if cached is None: @@ -475,11 +511,12 @@ def mark_rgb(colour: str) -> tuple[int, int, int]: def make_console() -> Console: - """Create the application's themed Rich console. + """Create the Rich console of the application, with its theme. - On legacy Windows consoles the standard streams default to ``cp1252``, which cannot - encode the box-drawing and marker glyphs (``◆ ● ★``) the UI uses; this reconfigures - them to UTF-8 where the runtime supports it so output never raises ``UnicodeEncodeError``. + On legacy Windows consoles, the standard streams use ``cp1252`` by default. It cannot + encode the box-drawing and marker glyphs (``◆ ● ★``) that the UI uses. This function + sets the streams to UTF-8 where the runtime lets it, so that the output never raises + ``UnicodeEncodeError``. Returns: A :class:`rich.console.Console` configured with the platform's theme. @@ -491,94 +528,101 @@ def make_console() -> Console: if reconfigure is not None: try: reconfigure(encoding="utf-8") - except (ValueError, OSError): # pragma: no cover - stream not reconfigurable + except (ValueError, OSError): # pragma: no cover - the stream cannot be set again pass return Console(theme=_ACTIVE_THEME) def title_style(border_style: str) -> str: - """Return the title style matching a panel's border: the same hue, brighter. + """Return the title style that matches the border of a panel: the same hue, brighter. Args: - border_style: The theme name the panel's border is drawn in (``"accent"``, - ``"warn"``, ...). + border_style: The theme name in which the border of the panel is drawn + (``"accent"``, ``"warn"``, and other names). Returns: - The matching ``title.*`` theme name, or ``border_style`` itself when no brighter - variant is defined (so an unknown border still gets a consistently-tinted title). + The matching ``title.*`` theme name. If no brighter variant is defined, it is + ``border_style`` itself. Thus an unknown border still gets a title with a + consistent tint. """ name = f"title.{border_style}" return name if name in MESH_THEME.styles else border_style def hint_style(border_style: str) -> str: - """Return the footer-hint style matching a panel's border: the same hue, muted. + """Return the footer-hint style that matches the border of a panel: the same hue, muted. - The bottom-border counterpart of :func:`title_style` — where the title brightens the - border's hue, the hint darkens it, so both read as part of the frame with the right - emphasis. + This is the counterpart of :func:`title_style` for the bottom border. The title + brightens the hue of the border, and the hint darkens it. Thus both read as part of + the frame, with the correct emphasis. Args: - border_style: The theme name the panel's border is drawn in (``"accent"``, - ``"warn"``, ...). + border_style: The theme name in which the border of the panel is drawn + (``"accent"``, ``"warn"``, and other names). Returns: - The matching ``hint.*`` theme name, or ``"muted"`` when no variant is defined (so - an unknown border keeps the old neutral hint rather than a loud one). + The matching ``hint.*`` theme name. If no variant is defined, it is ``"muted"``. + Thus an unknown border keeps the old neutral hint, and not a loud hint. """ name = f"hint.{border_style}" return name if name in MESH_THEME.styles else "muted" -#: The per-node hue *spectrum*: a node's first key byte maps straight onto the HSV colour -#: wheel — ``0x00`` is red, sweeping the full spectrum round to ``0xff`` — at a fixed -#: saturation and value tuned to stay vivid and readable on the dark theme across every hue. -#: So all 256 first-byte values give 256 distinct hues on a truecolor terminal. The app-wide -#: rule holds on every platform: a node's *name* is always coloured — by this wheel, keyed -#: on the node's key (see :func:`node_style`) so the colour is the node's identity, surviving -#: renames and colouring every surface that knows any prefix of the key identically — and our -#: own node is always the pure-white ``you`` style instead, so "us" never blends into the -#: crowd. Shared by the node lists, the chat transcript, the dashboard feed, and the packet -#: viewer, so one node reads as one colour everywhere. +#: The per-node hue *spectrum*. The first key byte of a node maps directly onto the HSV +#: colour wheel. ``0x00`` is red, and the full spectrum goes round to ``0xff``. The +#: saturation and the value are fixed, and they are tuned to stay vivid and readable on +#: the dark theme in all hues. Thus the 256 values of the first byte give 256 different +#: hues on a truecolor terminal. The rule of the whole app is the same on each platform: +#: the *name* of a node always has a colour. The colour comes from this wheel, and the key +#: of the node selects it (refer to :func:`node_style`). Thus the colour is the identity +#: of the node. It stays the same after a rename, and it is the same on each surface that +#: knows any prefix of the key. Our node always has the pure-white ``you`` style instead, +#: so "us" never merges into the crowd. The node lists, the chat transcript, the feed of +#: the dashboard, and the packet viewer share this wheel. Thus one node has one colour +#: everywhere. _NODE_HUE_SAT = 0.65 _NODE_HUE_VAL = 0.95 -#: The same wheel at the PicoCalc console's resolution: the six *chromatic bright* palette -#: slots, listed in hue order from red so index ``round(byte / 256 * 6) % 6`` is the sector -#: the byte's hue falls in — 60° apart, an even sixth of the wheel each. Written as the -#: slots' own :data:`_VT_SLOTS` RGBs rather than as ``color(N)`` so the value is still a -#: hex a caller can parse into an RGB (the map canvas and the mesh walk read the hue back -#: out of the style string), and so every downsample on the way out — Rich's, and the -#: fold's :func:`_quantize_sgr` — lands on that exact slot rather than guessing. +#: The same wheel at the resolution of the PicoCalc console: the six *chromatic bright* +#: palette slots. They are in hue order, from red. Thus the index ``round(byte / 256 * 6) +#: % 6`` is the sector in which the hue of the byte is. The sectors are 60° apart, and +#: each is an equal sixth of the wheel. They are written as the own :data:`_VT_SLOTS` RGB +#: values of the slots and not as ``color(N)``. Thus the value is still a hex that a +#: caller can parse into an RGB (the map canvas and the mesh walk read the hue from the +#: style string). Also, each downsample on the way out (the downsample of Rich, and +#: :func:`_quantize_sgr` of the fold) gives exactly that slot, and does not guess. # fmt: off _NODE_SLOT_HEXES: tuple[str, ...] = ( - "#ff5555", # 9 red — 0° - "#ffff55", # 11 yellow — 60° - "#55ff55", # 10 green — 120° - "#55ffff", # 14 cyan — 180° - "#5555ff", # 12 blue — 240° - "#ff55ff", # 13 magenta — 300° + "#ff5555", # 9 red : 0° + "#ffff55", # 11 yellow : 60° + "#55ff55", # 10 green : 120° + "#55ffff", # 14 cyan : 180° + "#5555ff", # 12 blue : 240° + "#ff55ff", # 13 magenta : 300° ) # fmt: on def node_style(key: str) -> str: - """The stable spectrum hue a node's *key* selects — the hash-derived node colour. + """The stable spectrum hue that the *key* of a node selects: the node colour from its hash. - The node's first key byte is mapped straight onto the HSV colour wheel (``0x00`` red, - sweeping round to ``0xff``), so the colour is the node's identity: it survives a - rename, and only the first byte picks it, so any prefix a surface happens to hold — a - 2-hex path hop, the stored 12-hex id, the full 64-hex public key — lands on the same - hue. One node, one colour, however it was learned. + The first key byte of the node maps directly onto the HSV colour wheel (``0x00`` is + red, and the wheel goes round to ``0xff``). Thus the colour is the identity of the + node. It stays the same after a rename. Only the first byte selects it, so each prefix + that a surface has gives the same hue. A prefix can be a 2-hex path hop, the stored + 12-hex id, or the full 64-hex public key. One node has one colour, in whatever way + MeshTerm learned it. - The *rule* is the platform's only constant here; its resolution is not. The regular - platform spends the full spectrum (:func:`_node_style_spectrum`, 256 distinct hues at - a fixed saturation/value); PicoCalc snaps the same hue to the nearest of the console's - six chromatic slots (:func:`_node_style_quantized`), exactly as the heard-age heat - scale quantizes its gradient there. Bound at platform-switch time. + The *rule* is the only constant of the platform here, but the resolution is not. The + regular platform uses the full spectrum (:func:`_node_style_spectrum`, 256 different + hues at a fixed saturation and value). The PicoCalc snaps the same hue to the nearest + of the six chromatic slots of the console (:func:`_node_style_quantized`). The heat + scale of the heard age quantizes its gradient in the same way there. MeshTerm binds + this function when the platform switches. Args: - key: The node's key/hash as hex (any length ≥ 1 byte, ``0x``/mixed-case tolerated). + key: The key or hash of the node as hex (any length of 1 byte or more. The + function accepts ``0x`` and mixed case). Returns: A ``"bold #rrggbb"`` style string. @@ -587,39 +631,40 @@ def node_style(key: str) -> str: def _key_byte(key: str) -> int: - """The node's first key byte — the only slice any hue derives from.""" + """The first key byte of the node: the only slice from which each hue comes.""" raw = key.lower().removeprefix("0x") try: return int(raw[:2], 16) - except ValueError: # not hex — fall back to the character sum so *something* stable shows + except ValueError: # not hex: use the sum of the characters, so that a stable colour shows return sum(map(ord, raw)) % 256 def _node_style_spectrum(key: str) -> str: - """Regular platform: the full 256-hue wheel at :data:`_NODE_HUE_SAT`/``_VAL``.""" + """The regular platform: the full 256-hue wheel at :data:`_NODE_HUE_SAT`/``_VAL``.""" r, g, b = colorsys.hsv_to_rgb(_key_byte(key) / 256, _NODE_HUE_SAT, _NODE_HUE_VAL) return f"bold #{round(r * 255):02x}{round(g * 255):02x}{round(b * 255):02x}" def _node_style_quantized(key: str) -> str: - """PicoCalc: the same hue, snapped to its sixth of the wheel (:data:`_NODE_SLOT_HEXES`). + """The PicoCalc: the same hue, snapped to its sixth of the wheel (:data:`_NODE_SLOT_HEXES`). - Deliberate rather than left to a nearest-RGB downsample: the spectrum's pastels sit - close enough to white that a naive match would drain the loudest hues toward grey, - and grey is ``muted``'s — an unkeyed sender. Snapping by hue keeps all six families - saturated and evenly populated (~43 of the 256 first bytes each). + This is on purpose, and a downsample to the nearest RGB does not do it. The pastels of + the spectrum are near white. A naive match moves the loudest hues toward grey, and + grey is the colour of ``muted``, which is for a sender without a key. A snap by hue + keeps all six families saturated and evenly populated (approximately 43 of the 256 + first bytes for each family). """ sector = round(_key_byte(key) / 256 * len(_NODE_SLOT_HEXES)) % len(_NODE_SLOT_HEXES) return f"bold {_NODE_SLOT_HEXES[sector]}" -#: Every style string a node's key can mint, on *either* platform: the 256-hue spectrum -#: and the console's six chromatic slots. A surface that has to *recognise* identity ink -#: rather than produce it matches against this — today that is the cursor row, where a -#: name gives way to the highlight's white. Both vocabularies live in the one set so the -#: answer never depends on which platform happens to be bound, and they cannot collide: -#: the spectrum's channels top out at ``0xf2`` (value 0.95) while every console slot -#: spells ``0xff``. +#: All the style strings that the key of a node can make, on *each* platform: the 256-hue +#: spectrum and the six chromatic slots of the console. A surface that must *recognize* +#: identity ink, and does not make it, matches against this set. Today this is the cursor +#: row, where a name gives way to the white of the highlight. Both vocabularies are in the +#: one set. Thus the answer does not depend on the platform that is bound, and the two +#: vocabularies cannot collide: the channels of the spectrum have a maximum of ``0xf2`` +#: (value 0.95), and each console slot has ``0xff``. _IDENTITY_STYLES: frozenset[str] = frozenset( [_node_style_spectrum(f"{byte:02x}") for byte in range(256)] + [f"bold {hex_}" for hex_ in _NODE_SLOT_HEXES] @@ -627,177 +672,185 @@ _IDENTITY_STYLES: frozenset[str] = frozenset( def is_identity_style(style: str) -> bool: - """Is ``style`` a hue some node's key minted — a *name's* ink rather than the page's? + """Check if ``style`` is a hue that the key of a node made (the ink of a *name*). - :func:`node_style` read backwards, for the one surface that needs the vocabulary as a - question: the cursor row, whose node names are drawn in its white instead of their own - hue (see :func:`~meshterm.ui.tui.render.render_to_ansi`). Deliberately narrow — only a - key-derived hue answers yes, so ``node.unknown``'s grey (a node we *cannot* identify, - which the highlight has no business claiming to know), the ``you`` white, and every - context colouring keep exactly what they were given. + This function is :func:`node_style` read in reverse. One surface needs the vocabulary + as a question: the cursor row, which draws node names in its white and not in their + own hue (refer to :func:`~meshterm.ui.tui.render.render_to_ansi`). The check is narrow + on purpose. Only a hue that comes from a key gives ``True``. Thus the grey of + ``node.unknown`` (a node that MeshTerm *cannot* identify, and the highlight must not + claim to know it), the white of ``you``, and each colouring for a context keep the + colour that they have. Args: style: A style string as it appears on a span. Returns: - ``True`` if it is one of the hues :func:`node_style` mints. + ``True`` if it is one of the hues that :func:`node_style` makes. """ return style in _IDENTITY_STYLES def name_style(name: str, key: str | None = None) -> str: - """The stable colour a node or sender name is drawn in — keyed on the node's key. + """The stable colour of the name of a node or sender. The key of the node selects it. - One rule on every platform: the hue is :func:`node_style`'s key-derived spectrum, so a - rename keeps the colour and every surface that knows any prefix of the key agrees. - Only the *resolution* changes with the platform (see :func:`node_style`). + The rule is the same on each platform. The hue is the spectrum of :func:`node_style` + that comes from the key. Thus a rename keeps the colour, and each surface that knows + any prefix of the key gives the same colour. Only the *resolution* changes with the + platform (refer to :func:`node_style`). Args: - name: The display name (unused for the hue; kept so every call site reads - ``name_style(name, key)`` and the pair stays greppable). - key: Any known prefix of the node's key/hash. ``None``/empty marks a sender whose - key we couldn't resolve — drawn ``node.unknown``, because colour is reserved - for keyed identities (callers with only a name resolve it first via - :func:`~meshterm.services.trace_runner.make_name_key_resolver`). + name: The display name. It does not change the hue. It is a parameter so that each + call site reads ``name_style(name, key)``, and a search finds the pair. + key: Any known prefix of the key or hash of the node. ``None`` or an empty value + marks a sender whose key MeshTerm could not resolve. The name is drawn as + ``node.unknown``, because colour is only for identities that have a key. + (A caller that has only a name must first resolve it with + :func:`~meshterm.services.trace_runner.make_name_key_resolver`.) Returns: - A style for the name; the same node always maps to the same style on a given - platform, so it keeps its colour across screens and sessions. + A style for the name. On one platform, the same node always has the same style. + Thus it keeps its colour across screens and sessions. """ return node_style(key) if key else "node.unknown" # -- the compact icon language (PicoCalc) --------------------------------------------- -#: Emoji → single console-font character: the PicoCalc icon language. One glyph per -#: concept, chosen from what the 512-glyph font actually holds (see ui.fontset); -#: concepts that only ever share a *family* (outbound ↑, route ∟) share deliberately. -#: The node-type marks (★●▲■◉○) and status marks (✓ ✗ ⚠ ● ○) are already font-native -#: and never appear here. ``glyph()`` consumes this table at explicit icon call sites -#: (a 1-cell lane the screen composes); the render-boundary fold consumes it for -#: everything else, padding to the emoji's measured width so layout survives. +#: The map from an emoji to a single console-font character. It is the icon language of +#: the PicoCalc. There is one glyph for each concept, chosen from the glyphs that the +#: 512-glyph font has (refer to ui.fontset). Concepts that only share a *family* (outbound +#: ↑, route ∟) share a glyph on purpose. The node-type marks (★●▲■◉○) and the status marks +#: (✓ ✗ ⚠ ● ○) are already native to the font, and they are never in this table. +#: ``glyph()`` uses this table at the explicit icon call sites (a lane of 1 cell that the +#: screen composes). The fold at the render boundary uses it for all other cases. It adds +#: padding to the measured width of the emoji, so that the layout stays correct. # fmt: off _GLYPH_MAP: dict[str, str] = { # Packet classes (KIND_ICONS) - "📢": "☼", # advert — a node radiating its presence - "📊": "≈", # telemetry — a waveform of readings - "📦": "▬", # packet — a plain slab of payload - "💬": "¶", # message — text + "📢": "☼", # advert: a node that radiates its presence + "📊": "≈", # telemetry: a waveform of readings + "📦": "▬", # packet: a plain slab of payload + "💬": "¶", # message: text "✅": "✓", # ack (the ok-family check) - "❔": "·", # unknown class — a neutral dot - # Raw payload classes (PAYLOAD_ICONS); raw ADVERT/ACK reuse ☼/✓ above - "📥": "↑", # REQ — a question going out - "📮": "↓", # RESPONSE — the answer coming back - "📩": "→", # TEXT_MSG (overheard direct message) — text in flight - "📻": "#", # GRP_TXT — channel text (the # channel mark) - "💽": "§", # GRP_DATA — a data section on a channel - "🎭": "?", # ANON_REQ — a request from an unproven identity - "🧭": "∟", # PATH — a route with a bend in it - "🎯": "⌖", # TRACE — the crosshair (also the map's position mark) - "🧩": "▒", # MULTIPART — a frame in fragments - "🧰": "↨", # CONTROL — adjustment up-and-down + "❔": "·", # unknown class: a neutral dot + # Raw payload classes (PAYLOAD_ICONS). Raw ADVERT and ACK use ☼ and ✓ above + "📥": "↑", # REQ: a question that goes out + "📮": "↓", # RESPONSE: the answer that comes back + "📩": "→", # TEXT_MSG (an overheard direct message): text in flight + "📻": "#", # GRP_TXT: channel text (the # channel mark) + "💽": "§", # GRP_DATA: a data section on a channel + "🎭": "?", # ANON_REQ: a request from an identity that is not proven + "🧭": "∟", # PATH: a route with a bend in it + "🎯": "⌖", # TRACE: the crosshair (also the position mark of the map) + "🧩": "▒", # MULTIPART: a packet in fragments + "🧰": "↨", # CONTROL: adjustment up and down # Channel openness (widgets.channel_glyph) "#": "#", # name-derived channel "🌐": "@", # well-known public channel "🔒": "⚿", # private channel, locked contact (the padlock mark) - "🔓": "⚿", # unlock — the same padlock; the row's word says which way it turns + "🔓": "⚿", # unlock: the same padlock. The word of the row says which way it turns # Concept icons (menu/list rows) - "📡": "☼", # advert tool — same concept as the advert class + "📡": "☼", # advert tool: the same concept as the advert class "🕒": "◷", # clock/sync (the clock-face mark) - "🔄": "°", # reboot — the power dot - "💾": "⌂", # backup — put it somewhere safe - "📂": "^", # restore — bring it back up - "🔑": "*", # channel/credential key — masked-secret asterisk - "🔐": "*", # identity/auth secret — same secret-material mark - "🗑": "✗", # clear/delete — the destructive mark - "✎": "~", # compose/edit — a scribble + "🔄": "°", # reboot: the power dot + "💾": "⌂", # backup: put it in a safe place + "📂": "^", # restore: bring it back up + "🔑": "*", # channel/credential key: the asterisk of a masked secret + "🔐": "*", # identity/auth secret: the same mark for secret material + "🗑": "✗", # clear/delete: the destructive mark + "✎": "~", # compose/edit: a scribble "⚡": "!", # explore/probe - "⭐": "+", # watch — added to the watchlist + "⭐": "+", # watch: added to the watchlist "📤": "↑", # send now (outbound family) - "📨": "=", # courier/queue — stacked letters - "🔔": "•", # notify — the badge dot - "🔕": "·", # mute — the hollowed-out dot - "📱": "▓", # QR — a dense block - "🔗": "&", # link — the joining glyph - "🏆": "★", # trophy case — the best/winner star - "⌨": "❯", # command line — the prompt cursor - "📖": "¶", # read/about — a page of prose (the text mark, as ¶ is for a message) - "💰": "$", # support/donate — the plainest possible money mark - "🚪": "", # quit — no icon; the word carries it + "📨": "=", # courier/queue: stacked letters + "🔔": "•", # notify: the badge dot + "🔕": "·", # mute: the hollowed-out dot + "📱": "▓", # QR: a dense block + "🔗": "&", # link: the joining glyph + "🏆": "★", # trophy case: the best/winner star + "⌨": "❯", # command line: the prompt pointer + "📖": "¶", # read/about: a page of prose (the text mark, as ¶ is for a message) + "💰": "$", # support/donate: the plainest money mark + "🚪": "", # quit: no icon, because the word carries it "🌍": "@", # map/world (globe family) "🕸": "∟", # mesh walk (route family) "🚨": "⚠", # watchtower alert "🛣": "∟", # longest-haul route (route family) - "🏹": "►", # longest leg — the arrow in flight (▶ is the run *action*, not this) + "🏹": "►", # longest leg: the arrow in flight (▶ is the run *action*, not this) "🧳": "→", # trip/journey - "🔆": "°", # brightest sighting - "📶": "≥", # TX power sweep — the power ramp + "🔆": "°", # the brightest reception + "📶": "≥", # TX power sweep: the power ramp "🔧": "⚙", # config (parameter concept) "📋": "i", # info - "🩺": "?", # diagnostics — the question a diagnosis answers (🎭 shares the mark) - "📰": "…", # live feed — a stream of items - "🎧": "≈", # monitor — listening to the waveform - "🗼": "▲", # repeater admin — the repeater mark itself - "📌": "■", # rooms — the room server mark itself - "🔌": "~", # serial port — the cable - "📍": "╨", # a radio on the host's SPI bus — the antenna on its board - "🔖": "╬", # region/scope — a flood's label; the grid square of an area + "🩺": "?", # diagnostics: the question that a diagnosis answers (🎭 has the same mark) + "📰": "…", # live feed: a stream of items + "🎧": "≈", # monitor: listening to the waveform + "🗼": "▲", # repeater admin: the repeater mark itself + "📌": "■", # rooms: the room server mark itself + "🔌": "~", # serial port: the cable + "📍": "╨", # a radio on the SPI bus of the host: the antenna on its board + "🔖": "╬", # region/scope: the label of a flood. It is the grid square of an area "👤": "%", # a person (two-circle silhouette) - "👥": "%", # contacts — people - "👋": "", # a wave in prose — the words carry it + "👥": "%", # contacts: people + "👋": "", # a wave in prose: the words carry it "⏳": "…", # pending/waiting - "+": "+", # fullwidth plus (channels' add row) + "+": "+", # fullwidth plus (the add row of the channels) } # fmt: on def glyph(icon: str) -> str: - """The platform's rendering of an icon: the emoji itself, or its compact glyph. + """The rendering of an icon on the platform: the emoji itself, or its compact glyph. - On the regular platform this is the identity — emoji icons render as themselves. - On PicoCalc every icon funnels to a single console-font character via - :data:`_GLYPH_MAP` (an unmapped icon passes through and is caught by the glyph - whitelist test / render-boundary fold, not silently invented here). Note the - compact form is *one cell* where the emoji was two: call sites compose their lanes - from the returned glyph, so the lane simply tightens on PicoCalc. + On the regular platform, this function returns the icon unchanged, and emoji icons + render as themselves. On the PicoCalc, each icon goes through :data:`_GLYPH_MAP` to a + single console-font character. An icon that is not in the map passes through. The test + for the glyph whitelist or the fold at the render boundary finds it. This function + does not invent a glyph without a message. The compact form is *one cell*, where the + emoji was two cells. Call sites compose their lanes from the returned glyph, so the + lane becomes narrower on the PicoCalc. Args: icon: An emoji, a node/status mark, or any literal character. Returns: - The character(s) to render for it on the active platform. + The characters to render for it on the active platform. """ return _glyph_impl(icon) def _glyph_identity(icon: str) -> str: - """Regular platform: icons render as themselves.""" + """The regular platform: icons render as themselves.""" return icon def _glyph_compact(icon: str) -> str: - """PicoCalc: icons collapse to their single-cell console-font glyph.""" + """The PicoCalc: icons become their single-cell console-font glyph.""" return _GLYPH_MAP.get(icon, icon) # -- the render-boundary fold (the handhelds) ------------------------------------------ -#: The active platform's glyph inventory (``Platform.font``), bound in :func:`_bind`: the -#: PicoCalc's 512-glyph console font, or what the Cardputer's emulator draws. +#: The glyph inventory of the active platform (``Platform.font``). :func:`_bind` binds it. +#: It is the 512-glyph console font of the PicoCalc, or what the emulator of the Cardputer +#: draws. _FOLD_FONT: frozenset[int] = FONT_CODEPOINTS -#: What may survive the fold: every font codepoint, plus the C0 controls the rendered -#: ANSI itself is built from (ESC in its sequences, the newlines between lines). +#: The characters that the fold lets stay: each font codepoint, and the C0 controls from +#: which the rendered ANSI is made (ESC in its sequences, and the newlines between lines). _FOLD_ALLOWED: frozenset[int] = _FOLD_FONT.union(range(0x00, 0x20)) -#: Whether the fold also quantizes embedded truecolor/256-colour SGR to the 16 slots — a -#: console that has no more (the PicoCalc's), never a panel the host paints in 24 bits. +#: Shows if the fold also quantizes embedded truecolor and 256-colour SGR to the 16 slots. +#: It does this for a console that has no more colours (the PicoCalc). It never does this +#: for a display that the host paints in 24 bits. _FOLD_QUANTIZE = True -#: Width-1 characters outside the font with a natural width-1 stand-in. Applied by the -#: fold's translation table (storage is never touched). Characters *in* the font — -#: ``— … ⋯ ⚠ ⌫ ⇧ ⚙ ↻ ◷ ⌖ ⚿ ← ↑ → ↓ ↔ ↕ • ·`` and the Cyrillic block — never appear -#: here: they pass through untranslated. +#: The characters of width 1 that are not in the font and have a natural stand-in of width +#: 1. The translation table of the fold applies them (MeshTerm never changes the stored +#: data). The characters that are *in* the font are never here, and they pass through +#: without a change. These are ``— … ⋯ ⚠ ⌫ ⇧ ⚙ ↻ ◷ ⌖ ⚿ ← ↑ → ↓ ↔ ↕ • ·`` and the Cyrillic +#: block. # fmt: off _FOLD_SINGLES: dict[str, str] = { "–": "-", "−": "-", "‒": "-", "―": "—", @@ -811,28 +864,29 @@ _FOLD_SINGLES: dict[str, str] = { "œ": "o", "Œ": "O", "æ": "a", "Æ": "A", "ø": "o", "Ø": "O", "ß": "s", "þ": "p", "Þ": "P", "ð": "d", "Ð": "D", "đ": "d", "Đ": "D", "ł": "l", "Ł": "L", "ı": "i", - # Powerline path-pill chrome (private-use): caps become half-blocks, the separator - # a plain wedge. + # Chrome of the powerline path pills (private use): the caps become half-blocks, and + # the separator becomes a plain wedge. "": ">", "": "▌", "": "▐", - # Zero-width machinery folds away entirely (width 0 → empty keeps cell math exact): - # VS16, ZWJ, ZWSP. + # The zero-width characters fold away completely (width 0 becomes empty, and the + # arithmetic of the cells stays exact): VS16, ZWJ, ZWSP. "️": "", "‍": "", "​": "", } # fmt: on -#: Built lazily on first fold: ``str.translate`` table = accent folds (NFKD, computed -#: over the Latin ranges once) + :data:`_FOLD_SINGLES` + the emoji map padded to each -#: emoji's measured cell width. +#: MeshTerm builds it lazily, at the first fold. It is the ``str.translate`` table. It has +#: the accent folds (NFKD, computed one time over the Latin ranges), :data:`_FOLD_SINGLES`, +#: and the emoji map padded to the measured cell width of each emoji. _FOLD_TABLE: dict[int, str] | None = None -#: Truecolor / 256-colour SGR sequences embedded in *pre-rendered* ANSI. The rasterizer -#: console downsamples everything it renders itself, but the braille canvases -#: (``ui.mapcanvas``) emit their own truecolor escapes which pass through Rich verbatim -#: — the fold quantizes those to the 16 slots so the contract holds for every byte out. -#: Any SGR sequence, its parameter list captured whole. The quantizer walks the list -#: rather than matching a colour standing alone: Rich writes a style's foreground and -#: background as *one* sequence (``ESC[38;2;255;255;255;48;2;0;0;0m`` — a QR module), -#: and a colour in the middle of such a list is no less a colour for having company. +#: The SGR sequences for truecolor and 256 colours that are embedded in *pre-rendered* +#: ANSI. The rasterizer console downsamples all that it renders itself. But the braille +#: canvases (``ui.mapcanvas``) emit their own truecolor escapes, which pass through Rich +#: without a change. The fold quantizes those to the 16 slots, so that the contract holds +#: for each byte that goes out. The pattern matches any SGR sequence, and it captures its +#: whole parameter list. The quantizer walks the list and does not match a colour that +#: stands alone. Rich writes the foreground and the background of a style as *one* +#: sequence (``ESC[38;2;255;255;255;48;2;0;0;0m``, a QR module). A colour in the middle of +#: such a list is a colour also when other parameters are with it. _SGR = _re.compile(r"\x1b\[([\d;]*)m") _SLOT_RGBS: tuple[tuple[int, int, int], ...] = tuple( @@ -840,28 +894,32 @@ _SLOT_RGBS: tuple[tuple[int, int, int], ...] = tuple( for _, _, h in _VT_SLOTS ) -#: (is_background, r, g, b) → the replacement SGR string. The app uses a few dozen -#: distinct colours; this stays tiny. +#: The map from (is_background, r, g, b) to the replacement SGR string. The app uses a few +#: dozen different colours, so this cache stays very small. _SLOT_CACHE: dict[tuple[bool, int, int, int], str] = {} def _nearest_slot_params(background: bool, r: int, g: int, b: int) -> str: - """The 16-colour SGR *parameters* closest to ``(r, g, b)`` in the :data:`_VT_SLOTS` palette. + """The 16-colour SGR *parameters* closest to ``(r, g, b)`` in :data:`_VT_SLOTS`. - ``22;31``, ``91``, ``40`` — without the ``ESC[…m`` around them, so the answer can be - spliced into a sequence that carries other parameters too (:func:`_quantize_sgr`). + Examples are ``22;31``, ``91``, and ``40``. They do not have the ``ESC[…m`` around + them. Thus the caller can splice the answer into a sequence that also has other + parameters (:func:`_quantize_sgr`). - Foregrounds may land on any slot (30–37 / 90–97); backgrounds only on 0–7 (the VT has - no bright backgrounds), so a bright colour used as a fill picks its dim-bank cousin. + A foreground can be in any slot (30–37 and 90–97). A background can be only in slots + 0–7 (the VT has no bright backgrounds). Thus a bright colour that is used as a fill + gets the related colour in the dim bank. - A **dim-bank foreground states its intent** (``22;3N``, normal intensity) rather than - emitting a bare ``3N``. Bold is brightness on the VT, and ``9N`` *is* how the console - spells bright — so a bare ``31`` immediately after a ``90`` inherits the intensity bit - and silently renders as ``91``. Quantized art is a run of adjacent colour spans with - no style boundaries to reset between them (the wordmark's every-other-span slate - bevel; a map raster's neighbouring cells), so the promotion lands mid-row and colours - half a row wrong: the narrow wordmark's fourth row — its only dim-slot row — came out - part red, part light red, split at each span that happened to follow the bevel. + A **foreground in the dim bank states its intent** (``22;3N``, normal intensity), and + does not emit a bare ``3N``. Bold is brightness on the VT, and ``9N`` is the way that + the console spells bright. Thus a bare ``31`` immediately after a ``90`` inherits the + intensity bit, and renders as ``91`` without a message. Quantized art is a run of + colour spans that are next to each other, and no style boundary between them resets + the intensity (the bevel of the wordmark has a slate span in every other span, and a + map raster has neighbouring cells). Thus the promotion happens in the middle of a row + and gives the wrong colour to half a row. The fourth row of the narrow wordmark (its + only row with a dim slot) was part red and part light red. The split was at each span + that followed the bevel. """ key = (background, r, g, b) cached = _SLOT_CACHE.get(key) @@ -886,7 +944,7 @@ def _nearest_slot_params(background: bool, r: int, g: int, b: int) -> str: def _rgb_of_256(index: int) -> tuple[int, int, int]: - """The canonical RGB of xterm-256 ``index`` (cube and grayscale ramps).""" + """The canonical RGB of xterm-256 ``index`` (the cube and the ramps of grey).""" if index < 16: return _SLOT_RGBS[index] if index < 232: @@ -898,10 +956,11 @@ def _rgb_of_256(index: int) -> tuple[int, int, int]: def _quantize_sgr(text: str) -> str: - """Fold any embedded truecolor / 256-colour SGR down to the 16 palette slots. + """Fold each embedded truecolor or 256-colour SGR down to the 16 palette slots. - Every sequence's parameter list is walked (see :data:`_SGR`), so a colour folds - whether it stands alone or shares its sequence with a second colour or an attribute. + The function walks the parameter list of each sequence (refer to :data:`_SGR`). Thus a + colour folds when it stands alone, and when it shares its sequence with a second + colour or an attribute. """ if "8;2;" not in text and "8;5;" not in text: return text @@ -909,7 +968,7 @@ def _quantize_sgr(text: str) -> str: def _quantize_params(match: _re.Match[str]) -> str: - """One SGR sequence with each ``38/48;2;r;g;b`` and ``38/48;5;n`` in it folded to a slot.""" + """One SGR sequence, in which each ``38/48;2;r;g;b`` and ``38/48;5;n`` is folded to a slot.""" params = match.group(1).split(";") out: list[str] = [] i = 0 @@ -933,18 +992,19 @@ def _quantize_params(match: _re.Match[str]) -> str: def _build_fold_table() -> dict[int, str]: - """Compose the full translation table (see :data:`_FOLD_TABLE`). + """Compose the full translation table (refer to :data:`_FOLD_TABLE`). - Only for what the active font lacks: a character it draws passes as itself, so the - Cardputer keeps the accents, chevrons and the rest Terminus has that the PicoCalc's - 512 glyphs don't. + The table has only what the active font does not have. A character that the font + draws passes as itself. Thus the Cardputer keeps the accents, the chevrons, and the + other glyphs that Terminus has and the 512 glyphs of the PicoCalc do not have. """ import unicodedata table: dict[int, str] = {} - # Accented Latin (the font's base table is Cyrillic-coverage Terminus: *no* accented - # Latin at all) plus fullwidth forms: NFKD-decompose, drop combining marks, keep a - # clean single ASCII survivor. é→e, Å→A, #→#, fi→(skipped: two chars). + # Accented Latin (the base table of the font is Terminus with Cyrillic coverage, with + # *no* accented Latin at all) and the fullwidth forms. Decompose with NFKD, remove the + # combining marks, and keep one clean ASCII character, if there is one. é→e, Å→A, #→#, + # fi→(skipped, because it is two characters). for first, last in ((0x00A1, 0x024F), (0x1E00, 0x1EFF), (0xFF01, 0xFF5E)): for cp in range(first, last + 1): if cp in _FOLD_FONT: @@ -965,16 +1025,19 @@ def _build_fold_table() -> dict[int, str]: @lru_cache(maxsize=4096) def _fold_to_font(text: str) -> str: - """Fold ``text`` down to the console font's inventory, cell widths preserved. + """Fold ``text`` down to the inventory of the console font. The cell widths stay the same. - Three stages, cheapest first: the translation table (accents, symbol stand-ins, - the emoji map — one C-level pass), then only if something non-ASCII survives, a - per-character sweep replacing anything still outside the font with ``?`` at the - character's own cell width. The sweep is the safety net that makes the platform's - no-wide-glyphs guarantee (see ``session._has_wide_glyph``) true *by construction*: - an emoji this module has never heard of still leaves as narrow ``?``s, never as a - tofu box that breaks the frame's cell math. Cached — render output repeats heavily - frame to frame, and the fold is platform-independent once this impl is bound. + There are three stages, and the cheapest is first. The first stage is the translation + table (accents, symbol stand-ins, and the emoji map), in one pass at the C level. The + second stage is only for text in which a non-ASCII character is still present. It is + a sweep of each character. It replaces each character that is still not in the font + with ``?`` at the cell width of the character. The sweep is the safety net. It makes + the guarantee of the platform, that there are no wide glyphs (refer to + ``session._has_wide_glyph``), true *by construction*. An emoji that this module does + not know still leaves as narrow ``?`` characters, and never as a tofu box that breaks + the cell arithmetic of the frame. The function is cached, because the render output + repeats much from one frame to the next. When this implementation is bound, the fold + does not depend on the platform. """ global _FOLD_TABLE if _FOLD_TABLE is None: @@ -988,31 +1051,33 @@ def _fold_to_font(text: str) -> str: def fold_text(text: str) -> str: - """The render-boundary text filter for the active platform. + """The text filter at the render boundary for the active platform. - Identity on the regular platform. On PicoCalc, folds any string that is about to be - drawn — names, message bodies, whole rendered ANSI lines — down to characters the - console font can shape (see :func:`_fold_to_font`); storage is never touched. ANSI - escape sequences pass through untouched (they are pure ASCII, and the fold never - rewrites ASCII). Applied once, centrally, in :func:`meshterm.ui.tui.render.render_to_ansi` - — individual screens should not need to call it. + On the regular platform, it returns the text unchanged. On the PicoCalc, it folds each + string that MeshTerm is about to draw, down to the characters that the console font + can show (refer to :func:`_fold_to_font`). The strings are names, message bodies, and + whole rendered ANSI lines. MeshTerm never changes the stored data. ANSI escape + sequences pass through without a change, because they are pure ASCII and the fold + never changes ASCII. The function is applied one time, in one central place, in + :func:`meshterm.ui.tui.render.render_to_ansi`. A screen does not need to call it. Args: - text: The text to fold (or pass through). + text: The text to fold (or to pass through). Returns: - The folded text; cell widths are preserved (wide emoji become glyph + pad). + The folded text. The cell widths stay the same (a wide emoji becomes a glyph and + padding). """ return _fold_impl(text) def _no_fold(text: str) -> str: - """Regular platform: text renders as stored.""" + """The regular platform: text renders as it is stored.""" return text def snr_style(snr: float | None) -> str: - """Return a theme style name describing an SNR value's quality. + """Return a theme style name that shows the quality of an SNR value. Args: snr: An SNR reading in dB, or ``None``. @@ -1036,14 +1101,14 @@ _node_impl: Callable[[str], str] = _node_style_spectrum _glyph_impl: Callable[[str], str] = _glyph_identity _fold_impl: Callable[[str], str] = _no_fold -#: Marker colour → RGB, filled by :func:`mark_rgb` and dropped on a platform switch (the -#: answer is the *active* theme's). +#: The map from a marker colour to RGB. :func:`mark_rgb` fills it, and a platform switch +#: clears it (the answer is from the *active* theme). _STYLE_RGB: dict[str, tuple[int, int, int]] = {} @on_platform def _bind(platform: Platform) -> None: - """Bind the theme's platform-dependent choices (runs now and on every switch).""" + """Bind the choices of the theme that depend on the platform (runs now and at each switch).""" global _ACTIVE_THEME, _node_impl, _glyph_impl, _fold_impl, _FOLD_TABLE global _FOLD_FONT, _FOLD_ALLOWED, _FOLD_QUANTIZE _ACTIVE_THEME = MESH_THEME if platform.truecolor else MESH_THEME_16 @@ -1056,8 +1121,9 @@ def _bind(platform: Platform) -> None: _FOLD_QUANTIZE = not platform.truecolor _fold_impl = _fold_to_font if font is not None else _no_fold _STYLE_RGB.clear() - # The fold table's emoji pads are computed with cell_len at build time. Cell widths - # can be re-measured/patched (the emoji-width calibration on the regular platform), - # so a platform switch drops the table and cache rather than trusting stale pads. + # MeshTerm computes the emoji pads of the fold table with cell_len when it builds the + # table. The cell widths can be measured again or patched (the calibration of the emoji + # width on the regular platform). Thus a platform switch clears the table and the + # cache, and does not trust old pads. _FOLD_TABLE = None _fold_to_font.cache_clear() diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index 6c0cf6a..036955e 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""Reusable Rich widgets: banner, status pill, trace tables, and progress bars.""" +"""Rich widgets for many screens: banner, status pill, trace tables, and progress bars.""" from __future__ import annotations @@ -66,18 +66,20 @@ if TYPE_CHECKING: def channel_glyph(name: str, secret: bytes | None) -> str: - """The one-character openness marker for a channel, shared across channel-facing screens. + """The one-character mark for the openness of a channel. The screens for channels share it. - ``#`` marks a name-derived (``#``-style) channel, ``🌐`` a fixed-key well-known public - channel (e.g. the firmware default ``Public``), and ``🔒`` a private one — mapped - through :func:`~meshterm.ui.theme.glyph`, so PicoCalc draws the compact ``# @ ⚿`` - instead. Within a platform every glyph is one width (double on regular, single on - PicoCalc), so callers can prefix rows with ``"{glyph} "`` without disturbing column - alignment. When the secret is unknown, the name alone is used to guess. + ``#`` marks a channel with a name-derived key (a ``#`` channel). ``🌐`` marks a + well-known public channel with a fixed key (for example the firmware default + ``Public``). ``🔒`` marks a private channel. The function sends each mark through + :func:`~meshterm.ui.theme.glyph`, so the PicoCalc draws the compact ``# @ ⚿`` + instead. On one platform, all the glyphs have the same width (double on regular, + single on the PicoCalc). Thus callers can put ``"{glyph} "`` before rows and the + columns stay aligned. When the secret is not known, the function uses the name alone + to guess. Args: name: The channel name. - secret: The channel's 16-byte secret, or ``None`` when only the name is known. + secret: The 16-byte secret of the channel, or ``None`` when only the name is known. Returns: A single-character glyph. @@ -91,29 +93,32 @@ def channel_glyph(name: str, secret: bytes | None) -> str: return glyph("🔒") -#: The concept icon for a region — a flood's scope (see ``CLAUDE.md``'s icon table). +#: The concept icon for a region (the scope of a flood). Refer to the icon table of ``CLAUDE.md``. REGION_ICON = "🔖" def scope_text(scope: Scope | None, *, bare: bool = False) -> Text: - """THE rendering of a flood's scope, for every surface that states one. + """The only rendering of the scope of a flood, for each surface that states one. - Three readings, one per :attr:`~meshterm.core.regions.Scope.state`: + There are three forms, one for each :attr:`~meshterm.core.regions.Scope.state`: - * ``scope yul`` — a scoped flood whose region is known, the name in the ``scope`` - style (a region is not a node, so it never takes a node hue); - * ``unknown scope 3fa1`` (``? 3fa1`` bare) — a scoped flood no known name - reproduces: the code is shown so - two frames can still be told to share a region, ``muted`` because it names nothing; - * ``unscoped`` — a plain flood, ``muted``: the ordinary case, stated not stressed. + * ``scope yul`` is a scoped flood with a known region. The name has the ``scope`` + style (a region is not a node, so it never has a node hue). + * ``unknown scope 3fa1`` (``? 3fa1`` bare) is a scoped flood that no known name + reproduces. The widget shows the code, so that the user can still see that two + packets share a region. It is ``muted`` because it names nothing. + * ``unscoped`` is a plain flood. It is ``muted`` because it is the ordinary case, and + the widget states it without stress. - ``None`` (a direct frame, or one whose route type was never kept) draws nothing — a - repeater never region-filters those, so a word there would claim a meaning it lacks. + ``None`` (a direct packet, or a packet whose route type MeshTerm did not keep) draws + nothing. A repeater never filters these by region, so a word there claims a meaning + that it does not have. Args: - scope: The frame's scope (:meth:`~meshterm.core.region_store.RegionStore.scope_of`). - bare: Drop the ``scope`` lead-in and draw the region name alone, for a lane whose - heading already says what it holds. + scope: The scope of the packet + (:meth:`~meshterm.core.region_store.RegionStore.scope_of`). + bare: Remove the ``scope`` lead-in and draw the region name alone, for a lane + whose heading already says what it holds. Returns: The styled text (empty for ``None``). @@ -126,8 +131,8 @@ def scope_text(scope: Scope | None, *, bare: bool = False) -> Text: text.append("scope ", style="muted") text.append(scope.region, style="scope") elif scope.scoped: - # No `·` inside the reading: a title chains its status atoms with `·`, and - # ``scoped · 3fa1`` there read as two atoms where it is one fact. + # Do not put a `·` inside the text. A title chains its status atoms with `·`, and + # ``scoped · 3fa1`` there looks like two atoms, but it is one fact. text.append("?" if bare else "unknown scope", style="muted") if scope.code: text.append(f" {scope.code}", style="muted") @@ -137,20 +142,20 @@ def scope_text(scope: Scope | None, *, bare: bool = False) -> Text: def identity_label(label: str | None) -> str | None: - """Default node resolver: leave labels untouched.""" + """The default node resolver: it does not change labels.""" return label def banner( profile: str | None, mock: bool, selected_device: DiscoveredDevice | None = None ) -> Panel: - """Build the application header panel. + """Build the header panel of the application. Args: - profile: Active device profile name, if any. - mock: Whether the simulator is in use. - selected_device: The discovered device chosen for this session, if any, shown - when no named profile is in use. + profile: The name of the active device profile, if any. + mock: ``True`` if the simulator is in use. + selected_device: The discovered device that the user chose for this session, if + any. The panel shows it when no named profile is in use. Returns: A Rich :class:`Panel` showing the app name, version, and connection target. @@ -170,13 +175,13 @@ def banner( def make_progress(console: Console) -> Progress: - """Create a themed progress bar for trace sweeps. + """Create a progress bar with the theme, for trace sweeps. Args: console: The console to render into. Returns: - A configured :class:`rich.progress.Progress` (use as a context manager). + A configured :class:`rich.progress.Progress` (use it as a context manager). """ return Progress( SpinnerColumn(style="accent"), @@ -197,23 +202,25 @@ def link_text( hash_bytes: int | None = None, device_hash: str | None = None, ) -> Text: - """Render an ``origin -> destination`` link through THE path widget. + """Render an ``origin -> destination`` link through the only path widget. - A two-node :func:`path_text` in the trace presentation: a known node as - ``name (hash)``, an unknown one as its bare hash, our own device as its label - (plus ``device_hash`` when supplied). Hashes are truncated to ``hash_bytes`` so - they match how the trace command addressed each node. + It is a :func:`path_text` of two nodes in the trace form. A known node is + ``name (hash)``, an unknown node is its bare hash, and our device is its label (plus + ``device_hash`` when the caller supplies it). The function truncates hashes to + ``hash_bytes``, so that they match the way the trace command addressed each node. Args: origin: The transmitting node (``None`` = our device). destination: The receiving node (``None`` = our device). - device_label: The label used for our own device. + device_label: The label for our device. resolve: Maps a raw hop hash to a friendly name when the node is known. - hash_bytes: Path-hash width (bytes) to truncate shown hashes to. - device_hash: Our own device's key/hash, shown alongside its label when known. + hash_bytes: The path-hash width (bytes) to which the function truncates the + hashes that it shows. + device_hash: The key or hash of our device. It is shown with its label when it + is known. Returns: - A :class:`Text` like ``us (a1) → Alice (3d)`` with the arrow muted. + A :class:`Text` such as ``us (a1) → Alice (3d)`` with a muted arrow. """ ends = [None if not node or node == device_label else node for node in (origin, destination)] return path_text( @@ -233,27 +240,30 @@ def traces_table( resolve: NodeResolver = identity_label, device_hash: str | None = None, ) -> Table: - """Render every trace's per-hop SNR side by side, one column per trace. + """Render the SNR of each hop of all traces side by side, with one column for each trace. - Hops are framed as ``origin -> destination`` links (the first originates at our - device, the last returns to it) and aligned by position across traces, so each - column is one trace's SNR readings down the shared path. Each node is annotated with - its hash at the command's path-hash width. A trailing ``min`` row shows each trace's - bottleneck — the per-trace values the run's *median min SNR* summarizes. Traces that - never replied appear as a ``✗`` column. + The table shows the hops as ``origin -> destination`` links. The first link starts at + our device, and the last link returns to it. The table aligns the hops by position + across the traces. Thus each column is the SNR readings of one trace down the shared + path. Each node has its hash at the path-hash width of the command. A ``min`` row at + the end shows the bottleneck of each trace. These are the values for each trace that + the *median min SNR* of the run summarizes. Traces that never received a reply + appear as a ``✗`` column. Args: - traces: The individual traces to display, in run order. - device_label: Name to show for our own device at the path's endpoints. - resolve: Maps a raw hop hash to a friendly contact name when known. - device_hash: Our own device's key/hash, annotated onto the path's endpoints. + traces: The individual traces to show, in the order of the run. + device_label: The name to show for our device at the endpoints of the path. + resolve: Maps a raw hop hash to a friendly contact name when it is known. + device_hash: The key or hash of our device. The table adds it to the endpoints of + the path. Returns: - A Rich :class:`Table` with a column per trace. + A Rich :class:`Table` with one column for each trace. """ target = traces[0].target if traces else "" - # All traces in a run share the command's path-hash width; take it from the first - # successful one so node hashes render at the width they were addressed. + # All traces in a run have the path-hash width of the command. Take it from the first + # successful trace, so that node hashes render at the width at which they were + # addressed. hash_bytes = next((t.path_hash_bytes for t in traces if t.success), None) table = Table(title=f"Trace → {target}", border_style="muted", expand=False) table.add_column("HOP", justify="right", style="muted") @@ -261,8 +271,9 @@ def traces_table( for i in range(1, len(traces) + 1): table.add_column(f"#{i}", justify="right") - # Index each trace's edges by hop position so columns line up even when traces - # take different-length paths (a missing hop shows as a muted dash). + # Index the edges of each trace by hop position. Thus the columns stay aligned also + # when the traces take paths of different lengths (a missing hop shows as a muted + # dash). edges_by_trace = [ {e.index: e for e in t.edges(device_label)} if t.success else {} for t in traces ] @@ -292,7 +303,8 @@ def traces_table( row.append(Text(f"{edge.snr:+.1f}", style=snr_style(edge.snr))) table.add_row(*row) - # Bottleneck per trace: the weakest link the run's median min SNR is taken over. + # The bottleneck of each trace: the weakest link, from which MeshTerm takes the median + # min SNR of the run. min_row: list[Text] = [Text("min", style="muted"), Text("bottleneck", style="muted")] for trace in traces: if not trace.success: @@ -319,51 +331,59 @@ def path_text( dim_from: int | None = None, hash_as_name: bool = False, ) -> Text: - """Render a hop sequence compactly on one line — THE path widget. + """Render a sequence of hops compactly on one line. This is the only path widget. - The one way MeshTerm shows a walked, relayed, or planned hop sequence, wherever one - appears: a packet's ``via`` row, a message's delivery paths, a feed note, a trace's - walked route or planned spec. Each hop renders as its resolved name — coloured in - the app-wide per-name hue, our own node pure white — or, unnamed, as its hash in - the ``node.unknown`` grey (colour marks an identified node, exactly as in the path - graph; an unresolvable hop never wears a hue its bytes would derive). Hops are - joined by muted ``→`` arrows and, by - default, no hash is repeated after a name, so the compact form survives a 72-column - row. The trace-flavoured options: ``show_hash`` annotates each named hop with the - hash it is addressed by (``Alice (3d63)``), a ``None`` hop is our own device at a - route's endpoints, and ``dim_from`` fades the tail a caller wants read as automatic - (a boomerang's mirrored return leg). ``hash_as_name`` reframes an *unnamed* hop as - its own identity — the hash at the path-hash-mode (``prefix_bytes``) width, muted - grey with no prefix lit (colour is the "this is a name" signal, and there is no - name), annotated with its addressed byte like a named hop (``e839f2 (e8)``) — where - the default instead lights the compact addressed hash. An empty path reads as + MeshTerm shows a walked, relayed, or planned sequence of hops in this one way, in each + place where it appears: the ``via`` row of a packet, the delivery paths of a message, + a feed note, and the walked route or planned spec of a trace. Each hop renders as its + resolved name, in the hue of the app for that name. Our node is pure white. An + unnamed hop renders as its hash in the grey of ``node.unknown``. (Colour marks an + identified node, as in the path graph. A hop that MeshTerm cannot resolve never has + the hue that its bytes give.) Muted ``→`` arrows join the hops. By default, the + widget does not repeat a hash after a name, so the compact form fits in a row of 72 + columns. + + These options are for traces. ``show_hash`` adds to each named hop the hash by which + it is addressed (``Alice (3d63)``). A ``None`` hop is our device at the endpoints of a + route. ``dim_from`` fades the tail that a caller wants the user to read as automatic + (the mirrored return leg of a boomerang). + + ``hash_as_name`` shows an *unnamed* hop as its own identity. The identity is the hash + at the width of the path-hash mode (``prefix_bytes``), in muted grey with no prefix + lit. (Colour is the signal "this is a name", and there is no name.) The widget adds + to it the byte by which it is addressed, as for a named hop (``e839f2 (e8)``). By + default, the widget instead lights the compact addressed hash. An empty path reads as ``empty``. Args: - hops: The hops in propagation order — hex hashes, with ``None`` marking our - own device (empty strings are skipped; ``dim_from`` counts rendered hops). - resolve: Maps a hop hash to a friendly name when known. - prefix_bytes: Path-hash width an unnamed hop's identity hash presents at under - ``hash_as_name`` (unnamed hops are otherwise shown grey whole, no prefix lit). - self_name: Our own node's name — drawn in the white ``you`` style when a - resolved name matches it, and naming any ``None`` device hop. - empty: The muted text shown when there are no hops (e.g. ``"direct"``). - show_hash: Annotate named hops (and, with ``device_hash``, our device) with - their hash in parentheses — the trace presentation. - hash_bytes: Truncate shown/annotated hashes to this byte width (the width the - hops were addressed at); ``None`` shows them whole. - device_hash: Our own device's key, annotated onto ``None`` hops when + hops: The hops in the order of propagation. They are hex hashes, and ``None`` + marks our device. (The function skips empty strings. ``dim_from`` counts the + hops that are rendered.) + resolve: Maps a hop hash to a friendly name when it is known. + prefix_bytes: The path-hash width at which the identity hash of an unnamed hop + shows under ``hash_as_name``. (In all other cases, unnamed hops are fully + grey, and no prefix is lit.) + self_name: The name of our node. The function draws a resolved name that matches + it in the white ``you`` style. It is also the name of each ``None`` device + hop. + empty: The muted text to show when there are no hops (for example ``"direct"``). + show_hash: Add the hash in parentheses to the named hops (and to our device, with + ``device_hash``). This is the form for traces. + hash_bytes: Truncate the hashes that the function shows or adds to this byte + width (the width at which the hops were addressed). ``None`` shows them whole. + device_hash: The key of our device. The function adds it to the ``None`` hops when ``show_hash`` is on. - dim_from: Render hops at/after this index — and the arrows into them — faint - (a planned route's return leg); ``None`` dims nothing. - hash_as_name: Present each unnamed hop as its identity hash — muted grey at the - ``prefix_bytes`` width, annotated with its addressed byte (``hash_bytes``) - like a named hop — rather than the compact prefix-lit addressed hash. + dim_from: Render the hops at this index and after it, and the arrows into them, + as faint (the return leg of a planned route). ``None`` dims nothing. + hash_as_name: Show each unnamed hop as its identity hash, in muted grey at the + ``prefix_bytes`` width, with the byte by which it is addressed + (``hash_bytes``), as for a named hop. The default is the compact addressed + hash with a lit prefix. Returns: - A one-line :class:`Text`. Space tighter than the path is the caller's call, - per surface: ellipsize (``no_wrap``), wrap under a hanging indent, or crop - with horizontal scrolling. + A one-line :class:`Text`. When the space is narrower than the path, the caller + decides what to do for each surface: ellipsize (``no_wrap``), wrap under a + hanging indent, or crop with horizontal scrolling. """ shown = [h for h in hops if h is None or h] if not shown: @@ -396,37 +416,43 @@ def revisit_note( prefix_bytes: int = 0, self_name: str | None = None, ) -> Text | None: - """The warning a path that touches one hop twice owes its reader, or ``None`` for none. + """The warning for a path that touches one hop twice, or ``None`` when there is none. - A route graph drawn with ``allow_duplicate_nodes`` - (:func:`~meshterm.ui.pathgraph.render_path_graph`) plants two markers carrying the same - name, and the ``via`` row above it names the same node twice — both honest, both confusing - left unexplained. This is the one line that explains them, and it refuses to pick between the - two readings, because nothing in the packet can: an observed chain addresses its hops by a - hash a single byte wide, so a repeat is as easily two different nodes colliding on that byte - as one node the packet genuinely passed twice. It names the repeated hops through THE path - widget (:func:`path_text`), so each reads in its own name hue exactly as it does in the - ``via`` row the reader is comparing against. + A route graph that is drawn with ``allow_duplicate_nodes`` + (:func:`~meshterm.ui.pathgraph.render_path_graph`) puts two markers with the same name. + The ``via`` row above it names the same node twice. Both are correct, but both confuse + the user if nothing explains them. This function makes the one line that explains + them. It does not choose between the two readings, because nothing in the packet can. + An observed chain addresses its hops with a hash that is one byte wide. Thus a repeat + is as probably two different nodes that have the same byte as one node that the packet + really passed twice. The function names the repeated hops through the only path widget + (:func:`path_text`). Thus each hop has its own name hue, the same as in the ``via`` + row with which the user compares it. - Takes the repeated hops rather than the path itself, so the caller decides what "repeated" - means for its surface: one path asks :func:`~meshterm.ui.pathgraph.revisited_hops`, while a - surface drawing a *fan* of paths must union each path's own revisits — a hop two different - routes share is not a revisit at all, and pooling their hops would libel it as one. + The function takes the repeated hops and not the path itself. Thus the caller decides + what "repeated" means for its surface. One path asks + :func:`~meshterm.ui.pathgraph.revisited_hops`. A surface that draws a *fan* of paths + must join the own revisits of each path. A hop that two different routes share is not + a revisit. If the surface pools their hops, it wrongly calls that hop a revisit. Args: - repeats: The hops to warn about, already known repeated (empty = no warning). - resolve: Maps a hop hash to a friendly name when known. - prefix_bytes: Path-hash width to light in an unnamed hop's hash (0 = none). - self_name: Our own node's name, so a repeat of *us* draws in the white ``you`` style. + repeats: The hops to warn about, which are already known to be repeated (empty = + no warning). + resolve: Maps a hop hash to a friendly name when it is known. + prefix_bytes: The path-hash width to light in the hash of an unnamed hop (0 = + none). + self_name: The name of our node, so that a repeat of *us* draws in the white + ``you`` style. Returns: - A one-line :class:`Text` fitting 72 cells for the paths a radio really carries, or - ``None`` when ``repeats`` is empty and there is nothing to warn about. + A one-line :class:`Text` that fits in 72 cells for the paths that a radio really + carries. ``None`` when ``repeats`` is empty and there is nothing to warn about. """ if not repeats: return None - # The mark carries its own span rather than riding the Text's base style, so nothing that - # follows can inherit ``warn`` — the names keep their node hues and the prose stays muted. + # The mark has its own span and does not use the base style of the Text. Thus nothing + # that follows can inherit ``warn``. The names keep their node hues, and the prose + # stays muted. note = Text() note.append("⚠ ", style="warn") for i, hop in enumerate(repeats): @@ -449,7 +475,7 @@ def _path_node( dim: bool, hash_as_name: bool = False, ) -> Text: - """One node of :func:`path_text` (see there for the rendering rules).""" + """One node of :func:`path_text` (refer to that function for the rendering rules).""" note_style = "faint" if dim else "muted" if hop is None: text = Text(self_name or LOCAL_DEVICE_LABEL, style="faint" if dim else "you") @@ -473,72 +499,76 @@ def _path_node( if dim: return Text(shown, style="faint") if hash_as_name: - # No name: the hash is the node's identity. Show it at the path-hash-mode - # width, fully muted (prefix_bytes=0 lights nothing — colour is the "this is - # a name" signal, and there is no name), then annotate it with the byte it - # was addressed by, exactly as a named hop is — unless that byte already *is* - # the whole shown hash. So a 3-byte mode reads ``e839f2 (e8)`` and still - # cross-references a byte-labelled route graph. + # There is no name, so the hash is the identity of the node. Show it at the width + # of the path-hash mode, fully muted (prefix_bytes=0 lights nothing, because colour + # is the signal "this is a name", and there is no name). Then add the byte by which + # it was addressed, as for a named hop, unless that byte is already the whole hash + # that the function shows. Thus a mode of 3 bytes reads ``e839f2 (e8)``, and it + # still cross-references a route graph that has labels of one byte. identity = _shorten_hash(hop, prefix_bytes or None) text = highlighted_hash(identity, 0, known=False) if show_hash and shown and shown != identity: text.append(f" ({shown})", style=note_style) return text - # No name resolved: the node is unknown, and an unknown node's hash is grey whole — - # the prefix never lights (colour marks an identified node; see highlighted_hash). + # No name resolved: the node is unknown, and the hash of an unknown node is fully grey. + # The prefix is never lit (colour marks an identified node, refer to highlighted_hash). return highlighted_hash(shown, prefix_bytes, known=False) def highlighted_hash( value: str, prefix_bytes: int, width: int | None = None, *, known: bool = True ) -> Text: - """Render a hex key with its leading path-hash prefix highlighted — THE hash widget. + """Render a hex key with its leading path-hash prefix lit. This is the only hash widget. - The one way MeshTerm displays a hash, wherever one appears: the first - ``prefix_bytes`` bytes are the slice other nodes address in a forced trace path - (the path-hash), lit in the node's hash-derived palette hue — the same hue its - name wears (see :func:`~meshterm.ui.theme.node_style`) — with the remainder muted, - so the addressable prefix stands out within the otherwise full key. A ``width`` - budget shorter than the key ellipsizes it (the ``…`` takes the colour of the digit - it replaces, so a highlight wider than the budget still reads as one). + MeshTerm displays a hash in this one way, in each place where one appears. The first + ``prefix_bytes`` bytes are the slice that other nodes address in a forced trace path + (the path hash). The widget lights them in the palette hue that comes from the hash of + the node, which is the same hue as its name (refer to + :func:`~meshterm.ui.theme.node_style`). The remainder is muted. Thus the addressable + prefix is clear in the otherwise full key. If the ``width`` budget is shorter than the + key, the widget ellipsizes the key. The ``…`` has the colour of the digit that it + replaces, so a highlight that is wider than the budget still reads as one. - Colour marks an *identified* node (JP, 2026-08-08): a hash whose node nobody can - name passes ``known=False`` and reads whole in the app-wide ``node.unknown`` grey — - exactly as an unknown node draws in the path graph — never in a hue its bytes would - derive. ``prefix_bytes=0`` on a known node likewise lights nothing and the key, - standing in *as* a name, takes ``node.unknown`` rather than ``muted``: it is the - row's content, not the dim tail of a hash whose head already carries the hue. + Colour marks an *identified* node (JP, 2026-08-08). A hash for which nobody can name + the node has ``known=False``, and it reads fully in the ``node.unknown`` grey of the + app. An unknown node draws in the same way in the path graph. It never has a hue that + its bytes give. In the same way, ``prefix_bytes=0`` on a known node lights + nothing, and a key that is the name takes ``node.unknown`` and not ``muted``. It is the + content of the row. It is not the dim tail of a hash whose head already has the hue. Args: - value: The key as hex, optionally ``0x``-prefixed and mixed-case. - prefix_bytes: Number of leading bytes the current path-hash mode addresses; ``0`` - (or negative) leaves the whole key un-highlighted. - width: Display budget in cells; a longer key is truncated to the whole leading - bytes that fit in ``width - 1`` cells (an even digit count — a hash reads in - bytes, two hex digits each) plus an ellipsis, a shorter one is right-padded to - the budget so lanes stay aligned. ``None`` shows the key whole, unpadded. - known: Whether the hash belongs to a node the caller can identify (name it, or - place it as a real contact). ``False`` greys the whole run, prefix included. + value: The key as hex. It can have the ``0x`` prefix and mixed case. + prefix_bytes: The number of leading bytes that the current path-hash mode + addresses. ``0`` (or a negative value) leaves the whole key without a + highlight. + width: The display budget in cells. The widget truncates a longer key to the + whole leading bytes that fit in ``width - 1`` cells (an even number of digits, + because a hash reads in bytes of two hex digits each) plus an ellipsis. It + pads a shorter key on the right to the budget, so that the lanes stay + aligned. ``None`` shows the whole key, without padding. + known: ``True`` if the hash belongs to a node that the caller can identify (name + it, or place it as a real contact). ``False`` makes the whole run grey, + also the prefix. Returns: - A styled :class:`Text` of the key (exactly ``width`` cells when given). + A styled :class:`Text` of the key (exactly ``width`` cells when it is given). """ raw = value.lower().removeprefix("0x") split = max(0, prefix_bytes) * 2 if known else 0 pad = 0 ellipsis = False if width is not None and len(raw) > width: - # Truncate on a byte boundary: keep an even number of hex digits, the ellipsis - # taking the next cell and any odd cell left over padding out, so a mid-byte digit - # never shows and the lane still spans exactly ``width``. + # Truncate on a byte boundary. Keep an even number of hex digits. The ellipsis uses + # the next cell, and any odd cell that is left is padding. Thus a digit from the + # middle of a byte never shows, and the lane still has exactly ``width`` cells. kept = max(0, width - 1) kept -= kept % 2 raw, ellipsis = raw[:kept], True pad = width - kept - 1 elif width is not None: pad = width - len(raw) - # The hue derives from the untruncated key (any prefix agrees) — but only an - # identified node earns one at all; an unknown node's hash is grey throughout. + # The hue comes from the key that is not truncated (any prefix gives the same hue). But + # only an identified node has a hue. The hash of an unknown node is grey everywhere. hue = node_style(value) if known else "node.unknown" rest = "muted" if split else "node.unknown" text = Text() @@ -551,26 +581,30 @@ def highlighted_hash( def name_chip(label: str, key: str | None = None, *, you: bool = False) -> Text: - """A node name drawn as a path line's single chip — THE way a surface *frames* a name. + """A node name drawn as the single chip of a path line: the only frame for a name. - Not an imitation of the chip language but a use of it: this builds a one-hop - :class:`~meshterm.ui.pathline.PathLine` and asks it for its line, so the fill, the - ink, the padding, the rounded cap and the closing point are all whatever a route's - segments are wearing today, and can never drift from them (JP, 2026-08-12). The colour - reads exactly as it does in a route. The name is in the node's hue, on a darker fill - of that hue. A node that no key can place takes the keyless grey, and our own end is - the map's ``★`` on its neutral dark grey instead of a name. + This is not an imitation of the chip language. It uses the chip language. The function + builds a :class:`~meshterm.ui.pathline.PathLine` with one hop and asks it for its line. + Thus the fill, the ink, the padding, the rounded cap, and the closing point are the + same as those of the segments of a route today, and they can never be different from + them (JP, 2026-08-12). The colour reads the same as in a route. The name has the hue + of the node, on a darker fill of that hue. A node that no key can place has the + keyless grey. Our own end is the ``★`` of the map on its neutral dark grey, and not a + name. - Degrading is inherited too: where the terminal can't draw powerline separators, a path - line is arrow-mode text and a lone hop is simply the name in its own hue — which is - what a sender label was before it was framed. + The degradation is also inherited. Where the terminal cannot draw powerline + separators, a path line is text in arrow mode, and a single hop is only the name in its + own hue. This is what a sender label was before it had a frame. Args: - label: The name as it should read (already resolved; this never renames it). - Ignored when ``you`` — our own end is the star, never our name. - key: Any known prefix of the node's key, which picks the hue. ``None`` is a node - we can't place: the keyless grey, colour being reserved for keyed identities. - you: This is our own node — the ``★``, exactly as a route draws our end of it. + label: The name as it must read (it is already resolved, and this function never + renames it). The function ignores it when ``you`` is true, because our own end + is the star and never our name. + key: Any known prefix of the key of the node, which selects the hue. ``None`` is a + node that MeshTerm cannot place. It has the keyless grey, because colour is + only for identities that have a key. + you: ``True`` if this is our node. It is the ``★``, the same as a route draws our + end of it. Returns: The chip as a one-line :class:`Text`. @@ -583,45 +617,50 @@ def _shorten_hash(value: str, hash_bytes: int | None) -> str: """Return ``value`` as bare hex truncated to ``hash_bytes`` bytes. Args: - value: A hex hash, optionally ``0x``-prefixed and mixed-case. - hash_bytes: Width in bytes to truncate to; the full value when falsy/unknown. + value: A hex hash. It can have the ``0x`` prefix and mixed case. + hash_bytes: The width in bytes to which the function truncates. When it is empty + or unknown, the function returns the full value. Returns: - Lowercase hex with no ``0x`` prefix, at most ``hash_bytes`` bytes wide. + Hex in lower case, without the ``0x`` prefix, with a maximum width of + ``hash_bytes`` bytes. """ raw = value.lower().removeprefix("0x") return raw[: hash_bytes * 2] if hash_bytes else raw -#: The pure-white our-own-node hue, matching the ``you`` style — an endpoint that is us -#: (and any relay resolving to our own name) takes it over its palette colour. +#: The pure-white hue of our node, which matches the ``you`` style. An endpoint that is us +#: (and each relay that resolves to our name) takes it instead of its palette colour. _SELF_RGB: RGB = (255, 255, 255) def _name_rgb(name: str, key: str | None = None) -> RGB: - """The RGB of a node's stable palette hue (``theme.name_style`` minus its bold). + """The RGB of the stable palette hue of a node (``theme.name_style`` without its bold). - A name with no resolvable key styles ``node.unknown`` (a theme name, not a hex), so - it lands on that grey here — the raster twin of the app-wide keyless-stays-grey rule. + A name that has no key that MeshTerm can resolve has the style ``node.unknown`` (a + theme name, not a hex). Thus it gets that grey here. This is the raster twin of the + rule of the app that a name without a key stays grey. """ hexpart = name_style(name, key).split()[-1] return parse_hex(hexpart) if hexpart.startswith("#") else mark_rgb(hexpart) def name_rgb(name: str, key: str | None = None) -> RGB: - """The truecolour of a node's stable palette hue, for a braille canvas. + """The truecolour of the stable palette hue of a node, for a braille canvas. - The public face of :func:`_name_rgb` — the same hue :func:`~meshterm.ui.theme.name_style` - paints a name in (hash-derived when ``key`` is given), as an ``(r, g, b)`` tuple a - raster can plot. A caller colouring node markers by their mesh identity (the trophy - case's area drawing) mints them through here. + This is the public face of :func:`_name_rgb`. It gives the same hue that + :func:`~meshterm.ui.theme.name_style` paints a name in (it comes from the hash when + ``key`` is given), as an ``(r, g, b)`` tuple that a raster can plot. A caller that + colours node markers by their mesh identity (the drawing of the area in the trophy + case) makes them through this function. """ return _name_rgb(name, key) -#: Maps a relay hash to its node type (see the ``NODE_TYPE_*`` constants), or ``None`` when -#: the type is unknown — the hook that lets the route graph mark a repeater ``▲`` and not -#: just a generic ``●``. Endpoint sentinels are never passed to it. +#: Maps a relay hash to its node type (refer to the ``NODE_TYPE_*`` constants), or to +#: ``None`` when the type is unknown. It is the hook that lets the route graph mark a +#: repeater as ``▲`` and not only as a generic ``●``. MeshTerm never passes the endpoint +#: sentinels to it. TypeOf = Callable[[str], int | None] @@ -634,48 +673,50 @@ def route_graph_style( type_of: TypeOf | None = None, key_of: NameKeyResolver | None = None, ) -> tuple[GlyphOf, LabelOf, LabelRgbOf]: - """Build the per-node callbacks that draw a route on THE route graph (``pathgraph``). + """Build the callbacks for each node that draw a route on the only route graph (``pathgraph``). - The shared presentation the Message paths dialog and the Trophy case both draw their - graphs with: the two endpoints carry node names, every relay in between its marker - plus the first byte of its hash, and each label takes its node's own name hue (us the - pure-white ``you``) so a byte reads as the mesh name it stands for. It maps the graph's - two endpoint sentinels — :data:`~meshterm.ui.pathgraph.SRC_NODE` on the left, - :data:`~meshterm.ui.pathgraph.DST_NODE` on the right — plus every relay hash, to a - glyph, a label, and a label colour. + The dialog for message paths and the Trophy case both draw their graphs with this + shared presentation. The two endpoints have node names. Each relay between them has + its marker and the first byte of its hash. Each label has the name hue of its node + (us: the pure-white ``you``), so a byte reads as the mesh name that it stands for. The + function maps the two endpoint sentinels of the graph and each relay hash to a glyph, + a label, and a label colour. The sentinels are :data:`~meshterm.ui.pathgraph.SRC_NODE` + on the left and :data:`~meshterm.ui.pathgraph.DST_NODE` on the right. - The right endpoint is *usually* us, and was once unconditionally so. That is right for - a route we walked or a message we received, and wrong for one we sent: with our own - name on both ends, every outgoing message's graph drew a round trip (JP, 2026-09-02). - ``destination`` names it when it is somebody else. + The right endpoint is *usually* us, and it was once always us. That is correct for a + route that we walked or a message that we received. It is wrong for a message that we + sent. With our name on both ends, the graph of each outgoing message drew a round trip + (JP, 2026-09-02). ``destination`` names the endpoint when it is another node. Args: - resolve: Maps a relay's hash to a friendly name when one is known. - self_name: Our own node's name — the right endpoint's label, drawn white. - source: The left endpoint's display name (a message's origin, or us for a walk - that starts at home — pass ``self_name`` to draw both ends as us). ``None`` - reads as an unknown ``?`` origin. - destination: The right endpoint's display name, when the route does not end at us — - the recipient of a message we sent. ``None`` (the default) draws us, which is - what a walk and every received message want. - type_of: Maps a relay's hash to its node type, so a relay draws its own map marker - (``▲`` repeater, ``■`` room, ``◉`` sensor) in the shared palette instead of a - generic dot. ``None``, or a hash whose type it can't resolve, keeps the old - named-dot / unknown-ring fallback. - key_of: Maps the ``source`` display name back to its node's key (see - :func:`~meshterm.services.trace_runner.make_name_key_resolver`), so the left - endpoint's label takes its key-derived hue; ``None``, or a name it can't - place, leaves the origin muted — colour is reserved for keyed identities. + resolve: Maps the hash of a relay to a friendly name when one is known. + self_name: The name of our node. It is the label of the right endpoint, drawn in + white. + source: The display name of the left endpoint (the origin of a message, or us for + a walk that starts at home. Pass ``self_name`` to draw both ends as us). + ``None`` reads as an unknown origin ``?``. + destination: The display name of the right endpoint, when the route does not end at + us (the recipient of a message that we sent). ``None`` (the default) draws us. + A walk and each received message need this. + type_of: Maps the hash of a relay to its node type, so that a relay draws its own + map marker (``▲`` repeater, ``■`` room, ``◉`` sensor) in the shared palette + instead of a generic dot. For ``None``, or a hash whose type it cannot + resolve, the old fallback stays: a named dot or an unknown ring. + key_of: Maps the display name of ``source`` back to the key of its node (refer to + :func:`~meshterm.services.trace_runner.make_name_key_resolver`), so that the + label of the left endpoint has its hue from the key. For ``None``, or a name + that it cannot place, the origin stays muted, because colour is only for + identities that have a key. Returns: - The ``(glyph_of, label_of, label_rgb_of)`` triple to hand to + The ``(glyph_of, label_of, label_rgb_of)`` triple to give to :func:`~meshterm.ui.pathgraph.render_path_graph`. """ src_is_self = bool(source) and source == self_name dst_is_self = not destination or destination == self_name def glyph_of(node: str) -> tuple[str, str]: - """Us a star, a typed relay its map marker, a named node a dot, else a ring.""" + """Us: a star. A relay with a type: its map marker. A named node: a dot. Else: a ring.""" if node == DST_NODE: return SELF_MARK if dst_is_self else NODE_MARK if node == SRC_NODE: @@ -688,7 +729,7 @@ def route_graph_style( return NODE_MARK if named and named != node else UNKNOWN_MARK def label_of(node: str) -> str | None: - """Endpoints by name, relays by their first hash byte.""" + """The endpoints have their names, and the relays have their first hash byte.""" if node == DST_NODE: return (self_name or "you") if dst_is_self else destination if node == SRC_NODE: @@ -696,11 +737,12 @@ def route_graph_style( return node[:2] def label_rgb_of(node: str) -> RGB: - """A label's colour: its node's name hue, us pure white, an unknown its ring. + """The colour of a label: the name hue of its node, white for us, the ring if unknown. - A relay we can't name keeps its *marker's* colour, so the hash under a repeater's - ``▲`` reads as that repeater rather than as a stray grey byte — which means this - resolves whatever ``glyph_of`` hands back, style name or hex alike. + A relay that MeshTerm cannot name keeps the colour of its *marker*. Thus the hash + under the ``▲`` of a repeater reads as that repeater, and not as a stray grey + byte. For this reason, this function resolves what ``glyph_of`` returns, a style + name or a hex. """ if node == DST_NODE: if dst_is_self: @@ -729,30 +771,31 @@ def route_path( bare_self: bool = False, show_hash: bool = True, ) -> PathLine: - """A trace's walked route as THE path widget's line object. + """The route that a trace walked, as the line object of the only path widget. - The same route :func:`_route_text` renders — this hands back the - :class:`~meshterm.ui.pathline.PathLine` itself, so a surface with room to spare - can wrap it at hop boundaries (:meth:`~meshterm.ui.pathline.PathLine.wrapped`) - rather than taking the one-liner and folding it mid-name. + It is the same route that :func:`_route_text` renders. This function returns the + :class:`~meshterm.ui.pathline.PathLine` itself. Thus a surface that has space can wrap + it at the hop boundaries (:meth:`~meshterm.ui.pathline.PathLine.wrapped`) and does + not take the one-line text and fold it in the middle of a name. Args: - result: The trace whose route to build. - device_label: Name to show for our own device at the path's endpoints. - resolve: Maps a raw hop hash to a friendly contact name when known. - device_hash: Our own device's key/hash, annotated onto its endpoints when known. - bare_self: Draw both ``us`` endpoints as their bare arrow — for a surface (the - trace screens' route lane) where a walk starting and ending on us is the - premise, not news. - show_hash: Annotate each *named* hop with the hash it was addressed by. On for - the scripted table output, where the hash is half the answer; off for the - live screens, whose route lane reads as the sequence of nodes and leaves - the hex to the wire-spec lane below it. Unnamed hops always show their - hash — it is the only identity they have. + result: The trace for which to build the route. + device_label: The name to show for our device at the endpoints of the path. + resolve: Maps a raw hop hash to a friendly contact name when it is known. + device_hash: The key or hash of our device. The function adds it to the endpoints + when it is known. + bare_self: Draw both ``us`` endpoints as their bare arrow. A surface (the route + lane of the trace screens) uses this where a walk that starts and ends on us + is the premise and not news. + show_hash: Add to each *named* hop the hash by which it was addressed. This is on + for the table output of scripts, where the hash is half of the answer. It is + off for the live screens. Their route lane reads as the sequence of nodes, and + the lane for the wire spec below it has the hex. Unnamed hops always show their + hash, because it is the only identity that they have. Returns: - The route's :class:`~meshterm.ui.pathline.PathLine` (hopless — reading - ``no hops recorded`` — when the trace recorded none). + The :class:`~meshterm.ui.pathline.PathLine` of the route. When the trace recorded + no hops, it has no hops and it reads ``no hops recorded``. """ edges = result.edges(device_label) if not edges: @@ -778,22 +821,22 @@ def _route_text( resolve: NodeResolver = identity_label, device_hash: str | None = None, ) -> Text: - """Render a trace's walked route through THE path widget, on one line. + """Render the route that a trace walked through the only path widget, on one line. - Shows the path the trace actually walked — the forced path, or the route the - device resolved when auto-routing — in the trace presentation: each node - annotated by its hash at the command's path-hash width, our own device - bracketing both ends, e.g. - ``Me (a1b2) → Alice (3d63) → Bob (f2a1) → Me (a1b2)``. + The function shows the path that the trace really walked. This is the forced path, or + the route that the device resolved with auto-routing. It uses the trace form. Each node + has its hash at the path-hash width of the command, and our device is at both ends. An + example is ``Me (a1b2) → Alice (3d63) → Bob (f2a1) → Me (a1b2)``. Args: - result: The trace whose route to display. - device_label: Name to show for our own device at the path's endpoints. - resolve: Maps a raw hop hash to a friendly contact name when known. - device_hash: Our own device's key/hash, annotated onto its endpoints when known. + result: The trace for which to show the route. + device_label: The name to show for our device at the endpoints of the path. + resolve: Maps a raw hop hash to a friendly contact name when it is known. + device_hash: The key or hash of our device. The function adds it to the endpoints + when it is known. Returns: - A :class:`Text` with the node sequence, or a muted note when no hops exist. + A :class:`Text` with the sequence of nodes, or a muted note when there are no hops. """ return route_path(result, device_label, resolve, device_hash).text() @@ -805,14 +848,16 @@ def _hop_medians_table( hash_bytes: int | None = None, device_hash: str | None = None, ) -> Table: - """Render the per-hop median SNR aggregated across a run's traces. + """Render the median SNR of each hop, aggregated across the traces of a run. Args: - hop_snrs: The per-hop aggregates to display. - device_label: Name to show for our own device at the path's endpoints. - resolve: Maps a raw hop hash to a friendly contact name when known. - hash_bytes: Path-hash width (bytes) to truncate shown node hashes to. - device_hash: Our own device's key/hash, annotated onto the path's endpoints. + hop_snrs: The aggregates for each hop to show. + device_label: The name to show for our device at the endpoints of the path. + resolve: Maps a raw hop hash to a friendly contact name when it is known. + hash_bytes: The path-hash width (bytes) to which the function truncates the node + hashes that it shows. + device_hash: The key or hash of our device. The function adds it to the endpoints + of the path. Returns: A compact Rich :class:`Table` of hop, link, and median SNR. @@ -837,23 +882,24 @@ def stats_panel( route: TraceResult | None = None, device_hash: str | None = None, ) -> Panel: - """Summarize aggregated trace statistics in a panel. + """Summarize the aggregated trace statistics in a panel. - Includes the median SNR for every hop along the path (not just the bottleneck), so - a weak link anywhere in the route is visible. When a representative ``route`` trace - is given, the path it actually walked is shown as a node sequence, e.g. - ``Me → Alice → Bob → Me``. + The panel has the median SNR for each hop along the path (and not only the + bottleneck). Thus a weak link anywhere in the route is visible. When the caller gives + a representative ``route`` trace, the panel shows the path that it really walked as a + sequence of nodes, for example ``Me → Alice → Bob → Me``. Args: - stats: The aggregated statistics to display. - device_label: Name to show for our own device at the path's endpoints. - resolve: Maps a raw hop hash to a friendly contact name when known. - route: A representative trace whose walked route to display, if any. - device_hash: Our own device's key/hash, annotated onto the route endpoints. + stats: The aggregated statistics to show. + device_label: The name to show for our device at the endpoints of the path. + resolve: Maps a raw hop hash to a friendly contact name when it is known. + route: A representative trace for which to show the route that it walked, if any. + device_hash: The key or hash of our device. The function adds it to the endpoints + of the route. Returns: - A Rich :class:`Panel` with the route, success rate, robust SNR/RTT, and - per-hop medians. + A Rich :class:`Panel` with the route, the success rate, the robust SNR and RTT, + and the medians for each hop. """ snr = stats.median_min_snr snr_text = Text(f"{snr:+.1f} dB", style=snr_style(snr)) if snr is not None else Text("n/a") @@ -873,7 +919,7 @@ def stats_panel( if route is not None: sections.append(Text("Route", style="accent")) sections.append(_route_text(route, device_label, resolve, device_hash)) - sections.append(Text()) # blank line before the stats block + sections.append(Text()) # a blank line before the block of statistics sections.append(summary) if stats.hop_snrs: sections.append(Text("\nPer-hop medians", style="accent")) @@ -885,14 +931,15 @@ def stats_panel( return Panel(body, title="[accent]Trace summary[/accent]", border_style="accent", expand=False) -# Node-type glyphs and their colours, consistent with the map's marker palette across the -# whole app (see ui.map_render): our own node is the yellow ``★``, plain nodes the loud pink -# ``●`` and repeaters the calmer violet ``▲``. The remaining types take map-safe hues that -# stay distinct from those — a white square for rooms (the house glyph read poorly) and an -# orange ringed dot for sensors. All are single-width BMP glyphs so columns stay aligned. -# The colours are the theme's ``type.*`` entries rather than raw hex, so the 16-slot console -# picks its slot deliberately (the violet would otherwise downsample to grey, and a repeater -# would read as an unknown node); on the regular platform they *are* the map's hues. +# The glyphs and colours of the node types. They are the same as the marker palette of the +# map in the whole app (refer to ui.map_render). Our node is the yellow ``★``, plain nodes +# are the loud pink ``●``, and repeaters are the calmer violet ``▲``. The other types have +# hues that are safe on the map and different from those: a white square for rooms (the +# house glyph was difficult to read) and an orange dot with a ring for sensors. All are +# single-width BMP glyphs, so the columns stay aligned. The colours are the ``type.*`` +# entries of the theme and not raw hex. Thus the 16-slot console chooses its slot on +# purpose (otherwise the violet downsamples to grey, and a repeater looks like an unknown +# node). On the regular platform, they *are* the hues of the map. NODE_GLYPHS: dict[int, tuple[str, str]] = { NODE_TYPE_REPEATER: (REPEATER_MARK[0], "type.repeater"), NODE_TYPE_ROOM: ("■", "type.room"), @@ -903,49 +950,50 @@ DEFAULT_GLYPH: tuple[str, str] = (NODE_MARK[0], "type.node") def node_marker(node_type: int | None) -> tuple[str, RGB]: - """The map-palette glyph and colour for a node type, as a ``(glyph, rgb)`` pair. + """The glyph and colour from the map palette for a node type, as a ``(glyph, rgb)`` pair. - The shared node-type marks (``▲`` repeater, ``■`` room, ``◉`` sensor, ``●`` plain - node) in the map's own colours, minted here for a braille raster the way - :data:`NODE_GLYPHS` mints them for a Rich row — so a spatial drawing pins its nodes - in the exact glyphs and hues the map and the nodes list use. Both read the same - ``type.*`` theme entry (through :func:`~meshterm.ui.theme.mark_rgb` here), so the - raster and the row agree on whatever the platform's palette can afford. An unknown - type falls back to the plain node mark. + These are the shared node-type marks (``▲`` repeater, ``■`` room, ``◉`` sensor, ``●`` + plain node) in the own colours of the map. This function makes them for a braille + raster, as :data:`NODE_GLYPHS` makes them for a Rich row. Thus a spatial drawing pins + its nodes with the same glyphs and hues that the map and the list of nodes use. Both + read the same ``type.*`` entry of the theme (here through + :func:`~meshterm.ui.theme.mark_rgb`). Thus the raster and the row agree on the colour + that the palette of the platform can show. An unknown type uses the plain node mark. """ glyph, style = NODE_GLYPHS.get(node_type or -1, DEFAULT_GLYPH) return glyph, mark_rgb(style) def self_marker() -> tuple[str, RGB]: - """Our own node's map marker — the yellow ``★`` — as a ``(glyph, rgb)`` pair.""" + """The map marker of our node, the yellow ``★``, as a ``(glyph, rgb)`` pair.""" return SELF_MARK[0], parse_hex(SELF_MARK[1]) -# A heat-map gradient for a node's heard age, hottest (most recently heard) to coldest: white -# → yellow → orange → red → grey. Each stop pairs an age anchor (log10 of seconds since heard) -# with an RGB colour; :func:`_recency_style` interpolates continuously between them, so the -# colour glides with recency rather than snapping between a handful of discrete shades. +# A heat-map gradient for the heard age of a node, from the hottest (heard most recently) to +# the coldest: white → yellow → orange → red → grey. Each stop pairs an age anchor (log10 of +# the seconds since the node was heard) with an RGB colour. :func:`_recency_style` +# interpolates continuously between the stops. Thus the colour glides with the recency, and +# does not snap between a few separate shades. _HEAT_STOPS: tuple[tuple[float, tuple[int, int, int]], ...] = ( - (math.log10(300), (255, 255, 255)), # ≤5m — white (fresh) - (math.log10(3600), (250, 204, 21)), # ~1h — yellow - (math.log10(21600), (251, 146, 60)), # ~6h — orange - (math.log10(86400), (248, 113, 113)), # ~1d — red - (math.log10(604800), (148, 163, 184)), # ~1w — grey - (math.log10(2592000), (100, 116, 139)), # ~30d+ — cold slate + (math.log10(300), (255, 255, 255)), # ≤5m: white (fresh) + (math.log10(3600), (250, 204, 21)), # ~1h: yellow + (math.log10(21600), (251, 146, 60)), # ~6h: orange + (math.log10(86400), (248, 113, 113)), # ~1d: red + (math.log10(604800), (148, 163, 184)), # ~1w: grey + (math.log10(2592000), (100, 116, 139)), # ~30d+: cold slate ) -_RECENCY_NEVER = "#64748b" # never heard — the coldest slate +_RECENCY_NEVER = "#64748b" # never heard: the coldest slate def age_seconds(when: datetime | None) -> float | None: - """Seconds since ``when`` (aware UTC), or ``None`` when unknown/naive.""" + """The seconds since ``when`` (aware UTC), or ``None`` when it is unknown or naive.""" if when is None or getattr(when, "tzinfo", None) is None: return None return max(0.0, (utcnow() - when).total_seconds()) def format_age(secs: float | None) -> str: - """A compact relative age — ``now``, ``5m``, ``3h``, ``2d``, ``4w`` — or ``never``.""" + """A compact relative age (``now``, ``5m``, ``3h``, ``2d``, ``4w``), or ``never``.""" if secs is None: return "never" if secs < 60: @@ -960,17 +1008,18 @@ def format_age(secs: float | None) -> str: def body_heading(title: str, note: str = "") -> Text: - """A section heading inside a screen's body: accent title, optional muted `` · note``. + """A section heading in a screen body: an accent title, and an optional muted `` · note``. - THE form for a heading that sits *in* a page's prose or drawings (the Time Machine's - Volume / SNR / Rhythm, a record's Stats / Area walked / Route), as opposed to a grouped - list's ``── Label ──`` landmark (:func:`~meshterm.ui.menus.section_heading`), which - pins and is jumped to. The note reads the block back — its unit, its window, what its - labels mean — and is muted so the title stays the landmark. + This is the only form for a heading that is *in* the prose or the drawings of a page + (Volume, SNR, and Rhythm in the Time Machine, and Stats, Area walked, and Route in a + record). It is not the ``── Label ──`` landmark of a grouped list + (:func:`~meshterm.ui.menus.section_heading`), which pins and which the section jumps + go to. The note explains the block: its unit, its window, and what its labels mean. It + is muted so that the title stays the landmark. Args: - title: The section's name, sentence case. - note: An aside after the roomy separator, or ``""`` for none. + title: The name of the section, in sentence case. + note: An aside after the wide separator, or ``""`` for none. Returns: The heading as one styled line. @@ -982,32 +1031,34 @@ def body_heading(title: str, note: str = "") -> Text: def format_ago(secs: float | None) -> str: - """The relative-age *phrase* — ``now``, ``5m ago``, ``never`` — for running prose. + """The relative-age *phrase* (``now``, ``5m ago``, ``never``) for prose. - The canonical grammar for every "heard … (…)" and "delivered …" row: a fresh - sighting reads as bare ``now`` and an unknown one as bare ``never`` (neither takes - the suffix — "now ago" is nonsense), while any measured age reads ``5m ago``. - Callers embedding an age in a sentence or parenthetical use this; - :func:`format_age` stays the bare column form for aligned age lanes. + This is the standard grammar for each row "heard … (…)" and "delivered …". A packet + that MeshTerm heard now reads as the bare ``now``, and an unknown age reads as the + bare ``never``. Neither takes the suffix, because "now ago" is nonsense. Each measured + age reads ``5m ago``. Callers that put an age in a sentence or in parentheses use this + function. :func:`format_age` stays the bare form for the columns of aligned age lanes. """ age = format_age(secs) return age if age in ("now", "never") else f"{age} ago" def _recency_style(secs: float | None) -> str: - """The heat-map colour for a node's heard age of ``secs`` (hotter = more recent). + """The heat-map colour for a heard age of ``secs`` for a node (hotter = more recent). - Dispatches to the platform-bound implementation: the regular platform's continuous - gradient, or PicoCalc's quantized steps (a 16-slot palette has no room to glide). + The function calls the implementation that is bound to the platform. It is the + continuous gradient of the regular platform, or the quantized steps of the PicoCalc (a + 16-slot palette has no space for a glide). """ return _recency_impl(secs) def _recency_gradient(secs: float | None) -> str: - """The regular platform's heat: continuous interpolation over :data:`_HEAT_STOPS`. + """The heat of the regular platform: continuous interpolation over :data:`_HEAT_STOPS`. - Interpolates the RGB channels between the two stops bracketing ``secs`` (in log-age - space), clamping to white below the first stop and cold slate above the last. + The function interpolates the RGB channels between the two stops on each side of + ``secs`` (in log-age space). Below the first stop, it gives white. Above the last stop, + it gives cold slate. """ if secs is None: return _RECENCY_NEVER @@ -1025,25 +1076,26 @@ def _recency_gradient(secs: float | None) -> str: return f"#{r:02x}{g:02x}{b:02x}" -#: The heat ladder as ``(younger than, style)``, hottest first — JP's spec. Every boundary -#: is a plain human unit, so a colour change always lands on a number you can say out loud -#: ("under five minutes", "over a week"). Past a year nothing is worth distinguishing from -#: never heard, so the two share the coldest step. +#: The heat ladder as ``(younger than, style)``, with the hottest first (JP's spec). Each +#: boundary is a plain human unit. Thus a colour change is always at a number that a person +#: can say aloud ("under five minutes", "over a week"). After one year, a node is not +#: different enough from a node that was never heard, so the two share the coldest step. _HEAT_STEPS: tuple[tuple[float, str], ...] = ( - (300, "heat.now"), # under 5 minutes — white - (3600, "heat.minutes"), # 5 minutes — yellow - (86400, "heat.hours"), # 1 hour — light red - (604800, "heat.days"), # 1 day — brown - (2592000, "heat.weeks"), # 1 week — red - (31536000, "heat.months"), # 1 month — light grey -) # 1 year / never — dark grey (heat.never) + (300, "heat.now"), # under 5 minutes: white + (3600, "heat.minutes"), # 5 minutes : yellow + (86400, "heat.hours"), # 1 hour : light red + (604800, "heat.days"), # 1 day : brown + (2592000, "heat.weeks"), # 1 week : red + (31536000, "heat.months"), # 1 month : light grey +) # 1 year / never: dark grey (heat.never) def _recency_quantized(secs: float | None) -> str: - """PicoCalc's heat: the gradient stepped onto the theme's ``heat.*`` rungs. + """The heat of the PicoCalc: the gradient in steps, on the ``heat.*`` rungs of the theme. - Same scale as the regular platform's gradient and the same anchors — a console that - can't spend a hue per second spends one per unit instead (see :data:`_HEAT_STEPS`). + The scale and the anchors are the same as for the gradient of the regular platform. A + console that cannot use a hue for each second uses one hue for each unit instead (refer + to :data:`_HEAT_STEPS`). """ if secs is None: return "heat.never" @@ -1058,42 +1110,43 @@ _recency_impl: Callable[[float | None], str] = _recency_gradient @on_platform def _bind_heat(platform: Platform) -> None: - """Pick the heat implementation for the platform (runs now and on every switch).""" + """Pick the heat implementation for the platform (runs now and at each switch).""" global _recency_impl _recency_impl = _recency_gradient if platform.truecolor else _recency_quantized def _key_id(value: str) -> str: - """Normalise a key/prefix to the lowercased 12-hex id used to match heard nodes.""" + """Normalize a key or prefix to the 12-hex id, in lower case, that matches heard nodes.""" return value.lower().removeprefix("0x")[:12] def contact_packets(contact: Contact, counts: dict[str, int]) -> int | None: - """The overheard-packet tally for ``contact``, or ``None`` if never overheard.""" + """The count of overheard packets for ``contact``, or ``None`` if it was never overheard.""" ident = contact.public_key or contact.key_prefix return counts.get(_key_id(ident)) if ident else None -# The columns the contact list can be sorted by, left-to-right, and the direction each opens on -# — name A→Z, most-recently-heard first, most packets first — chosen so a fresh sort shows -# the "interesting" end at the top. +# The columns by which the contact list can be sorted, from left to right, and the direction +# in which each one opens: name A→Z, most recently heard first, most packets first. We chose +# these so that a new sort shows the interesting end at the top. _SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets") _SORT_OPENS_ASCENDING: dict[str, bool] = {"name": True, "heard": True, "packets": False} @dataclass class ContactsSort: - """Which column the contact list is sorted by, and in which direction. + """The column by which the contact list is sorted, and the direction. - ``column`` is one of :attr:`columns`; ``ascending`` sorts the column's underlying - metric low-to-high — name A→Z, *age* (so ascending = most recently heard first), packet - count low-to-high. The interactive screen mutates this in place as the user presses the - arrows. + ``column`` is one of :attr:`columns`. ``ascending`` sorts the metric of the column from + low to high. For the name this is A→Z. For the *age* it is the most recently heard + first (ascending). For the packet count it is from low to high. The screen changes this + object in place when the user presses the arrows. - The sort *ring* is per-instance: :attr:`columns` and :attr:`opens_ascending` default to - the Contacts list's three (:data:`_SORT_COLUMNS`), but the Time Machine picker passes a - wider set — it adds a sortable ``hash`` column — so the same model drives both without a - module-global column list that one screen would have to share with the other. + The sort *ring* belongs to each instance. By default, :attr:`columns` and + :attr:`opens_ascending` are the three columns of the Contacts list + (:data:`_SORT_COLUMNS`). But the picker of the Time Machine passes a wider set. It adds + a sortable ``hash`` column. Thus the same model works for both, and the two screens do + not need to share a global list of columns of the module. """ column: str = "name" @@ -1103,11 +1156,11 @@ class ContactsSort: @classmethod def names(cls, columns: tuple[str, ...] = _SORT_COLUMNS) -> tuple[str, ...]: - """The orders :meth:`from_name` accepts — what a caller may legitimately ask for. + """The orders that :meth:`from_name` accepts: what a caller can validly ask for. - :meth:`from_name` answers "which sort is this?" and forgives anything it does not - recognise. A surface that wants to *refuse* an unknown order needs the set itself, - which is this. + :meth:`from_name` answers "which sort is this?" and accepts anything that it does + not recognize. A surface that must *refuse* an unknown order needs the set itself, + and this method returns it. """ return columns @@ -1118,18 +1171,18 @@ class ContactsSort: columns: tuple[str, ...] = _SORT_COLUMNS, opens_ascending: dict[str, bool] | None = None, ) -> ContactsSort: - """Build a sort for ``name`` over ``columns``, opening in that column's natural direction. + """Build a sort for ``name`` over ``columns``, in the natural direction of that column. - Falls back to the ring's first column when ``name`` isn't one of ``columns`` (so a - stale saved key can't wedge the sort). ``opens_ascending`` defaults to the Nodes - list's directions when omitted. + If ``name`` is not one of ``columns``, the function uses the first column of the + ring. Thus an old stored key cannot block the sort. If the caller does not give + ``opens_ascending``, the function uses the directions of the Nodes list. """ opens = opens_ascending if opens_ascending is not None else _SORT_OPENS_ASCENDING column = name if name in columns else columns[0] return cls(column, opens[column], columns, opens) def move(self, delta: int) -> None: - """Step the active column ``delta`` places (wrapping), adopting its natural direction.""" + """Move the active column ``delta`` places (it wraps), and use its natural direction.""" index = (self.columns.index(self.column) + delta) % len(self.columns) self.column = self.columns[index] self.ascending = self.opens_ascending[self.column] @@ -1138,17 +1191,18 @@ class ContactsSort: def ordered_contacts( contacts: list[Contact], counts: dict[str, int], sort: ContactsSort ) -> list[Contact]: - """Contacts sorted per ``sort`` (our own node is pinned separately, above these). + """The contacts, sorted as ``sort`` says (our node is pinned separately, above these). - The active column's metric drives the order (reversed for a descending sort); ties always - break by case-folded name *ascending*, so two contacts sharing a metric (e.g. the same - ``heard`` age) keep a stable A→Z order instead of flipping with the primary direction. - Never-heard / never-overheard rows carry an extreme metric so they gather at the ascending - end. + The metric of the active column sets the order (reversed for a descending sort). A tie + always breaks by the case-folded name, *ascending*. Thus two contacts with the same + metric (for example the same ``heard`` age) keep a stable A→Z order, and the order does + not flip with the primary direction. The rows that were never heard or never overheard + have an extreme metric, so they gather at the ascending end. """ if sort.column == "heard": - # One clock snapshot for the whole sort: per-row utcnow() calls would skew two - # identical last_seen stamps apart by microseconds and defeat the name tie-break. + # Use one clock snapshot for the whole sort. If each row calls utcnow(), two + # identical last_seen stamps differ by a few microseconds, and the tie-break by + # name does not work. now = utcnow() def metric(c: Contact) -> float: @@ -1164,21 +1218,22 @@ def ordered_contacts( def metric(c: Contact) -> object: return c.name.casefold() - # Name-ascending first, then a stable sort by the primary metric: equal-metric rows retain - # their A→Z order under both directions (reversing the whole list would flip the tiebreak). + # Sort by name ascending first, then make a stable sort by the primary metric. Rows with + # the same metric keep their A→Z order in both directions. (If the code reverses the + # whole list, it flips the tie-break.) ordered = sorted(contacts, key=lambda c: c.name.casefold()) ordered.sort(key=metric, reverse=not sort.ascending) return ordered def _sort_header(label: str, column: str, sort: ContactsSort) -> str: - """A column header: plain-muted, or lit with a direction triangle when it's the sort key. + """A column header: plain and muted, or lit with a direction triangle when it is the sort key. - The active column's name and its triangle are lit together in the app's ``cursor`` white - (so the interactive left/right selection is obvious) — ``▲`` for ascending, ``▼`` for - descending. Same ink as the highlighted *row*, because it is the same claim one axis - over. The column reserves its width (see :func:`contacts_table`) so toggling the sort - doesn't shift the row. + The name of the active column and its triangle are lit together in the ``cursor`` white + of the app, so that the selection with left and right is clear. The triangle is ``▲`` + for ascending and ``▼`` for descending. The ink is the same as that of the highlighted + *row*, because it is the same claim on the other axis. The column keeps its width + (refer to :func:`contacts_table`), so a change of the sort does not shift the row. """ if column != sort.column: return label @@ -1186,27 +1241,29 @@ def _sort_header(label: str, column: str, sort: ContactsSort) -> str: return f"[cursor]{label} {triangle}[/]" -#: The legend's word for each node type: the type's one name (:data:`NODE_TYPE_LABELS`), -#: except where a shorter word is unmistakable beside its glyph — ``room`` for a room -#: server (JP, 2026-10-02). The name everywhere else, the CLI's included, stays whole. +#: The word of the legend for each node type: the one name of the type +#: (:data:`NODE_TYPE_LABELS`). The exception is where a shorter word is clear next to its +#: glyph: ``room`` for a room server (JP, 2026-10-02). In all other places, including the +#: CLI, the name stays whole. _LEGEND_WORDS = {**NODE_TYPE_LABELS, NODE_TYPE_ROOM: "room"} def node_type_legend(indent: str = "", width: int | None = None) -> Text: - """The key to the node-type marks: ``★ you ▲ repeater ● companion …``. + """The legend for the node-type marks: ``★ you ▲ repeater ● companion …``. - Every glyph in its shared map colour (see :data:`NODE_GLYPHS`), each named muted after - it (:data:`_LEGEND_WORDS`). THE legend for any surface that draws typed node markers — - the contacts list under its table, the route graph under its lanes — so one glyph means - one thing app-wide. + Each glyph has its shared map colour (refer to :data:`NODE_GLYPHS`), and its name + follows it in muted style (:data:`_LEGEND_WORDS`). This is the only legend for each + surface that draws node markers with types: the contacts list under its table, and the + route graph under its lanes. Thus one glyph has one meaning in the whole app. - One line where it fits: 52 cells, inside the handhelds' 53. Where it does not — an - indent, a narrower box — it breaks onto a second line between entries, never inside - one, so a mark is never parted from its name and no name is cropped. + The legend has one line where it fits: 52 cells, inside the 53 cells of the handhelds. + Where it does not fit (an indent, a narrower box), it breaks onto a second line between + entries and never inside an entry. Thus a mark is never separated from its name, and + no name is cropped. Args: - indent: Leading spaces to sit the legend under a table or graph body. - width: The cells available. None keeps the legend on one line. + indent: The leading spaces that put the legend under the body of a table or graph. + width: The cells that are available. ``None`` keeps the legend on one line. """ entries = [Text.assemble((SELF_MARK[0], SELF_MARK[1]), (" you", "muted"))] for node_type in (NODE_TYPE_REPEATER, NODE_TYPE_CHAT, NODE_TYPE_ROOM, NODE_TYPE_SENSOR): @@ -1229,89 +1286,96 @@ def node_type_legend(indent: str = "", width: int | None = None) -> Text: return legend -#: Blank rows of air around a tab strip — one above and one under on the desktop; none -#: on the PicoCalc (JP, 2026-08-08), where rows are the scarce resource and both lines go -#: to the stage instead (the route graph's ceiling, the location preview's growth room). -#: Rides the same frugality signal as the borderless frame, and is bound at -#: platform-switch time like every platform-derived constant — never branched per paint. +#: The blank rows of air around a tab strip: one above and one under on the desktop, and +#: none on the PicoCalc (JP, 2026-08-08). On the PicoCalc, rows are scarce, and both lines +#: go to the stage instead (the ceiling of the route graph, and the room for the preview of +#: the location to grow). The constant follows the same signal of frugality as the +#: borderless frame. MeshTerm binds it when the platform switches, as it does for each +#: constant that comes from the platform. It never branches for each paint. _TAB_AIR = 1 @on_platform def _bind_tab_air(platform: Platform) -> None: - """Bind the strip's air to the platform (runs now and on every switch).""" + """Bind the air of the strip to the platform (runs now and at each switch).""" global _TAB_AIR _TAB_AIR = 1 if platform.frame_border else 0 def tab_air() -> int: - """Blank rows a tabbed page spends above its strip and under it (see :data:`_TAB_AIR`). + """The blank rows that a tabbed page uses above and under its strip (refer to :data:`_TAB_AIR`). - Read by every screen that draws :func:`tab_strip` — the node page, a record — so the - strip sits in the same air everywhere, and loses it on the same platform. + Each screen that draws :func:`tab_strip` reads it, for example the node page and a + record. Thus the strip has the same air everywhere, and it loses the air on the same + platform. """ return _TAB_AIR -#: The viewport, in rows, below which a frame is *short* and spends its rows on content: -#: a tabbed page draws its strip on one row (see :func:`tab_strip`'s ``compact``), and a -#: graph's caption and node-type key step aside so the list under it gets the rows. The -#: boxed strip alone costs three; on the Cardputer's 11-row viewport that was the -#: difference between a page's actions on screen and below the fold. Read from the -#: viewport rather than the platform, so a desktop terminal dragged short gets the same -#: answer the handheld does. +#: The viewport, in rows, under which a frame is *short* and uses its rows for content. +#: A tabbed page draws its strip on one row (refer to ``compact`` of :func:`tab_strip`). +#: The caption and the node-type legend of a graph step aside, so that the list under it +#: gets the rows. The boxed strip alone costs three rows. On the viewport of 11 rows of the +#: Cardputer, this was the difference between the actions of a page on the screen and +#: below the fold. The value comes from the viewport and not from the platform. Thus a +#: desktop terminal that the user drags to a short size gets the same result as the +#: handheld. SHORT_FRAME_BELOW = 16 def short_frame(viewport: int) -> bool: - """Whether a page with ``viewport`` rows is short (see :data:`SHORT_FRAME_BELOW`).""" + """Check if a page with ``viewport`` rows is short (refer to :data:`SHORT_FRAME_BELOW`).""" return viewport < SHORT_FRAME_BELOW def tab_strip(labels: Sequence[str], active: int, width: int, *, compact: bool = False) -> Group: - """A boxed tab strip: every tab always boxed on top, the active one open into the page. + """A boxed tab strip: each tab has a box on top, and the active tab is open into the page. - THE navigation header for a screen that pages one full-height view at a time between a - handful of named views (the node detail page's ``Info`` / ``Routes``) instead of stacking - them. Every tab is always drawn as a full-topped box — a dim ``faint`` outline by - default, lit ``accent`` when active — instead of only the active one; this keeps every - tab's width fixed regardless of which is selected, so switching tabs never shifts the - labels that come after it. Tabs share a vertical between neighbours (one glyph, not - two), and each shared *top* corner is drawn as if the tab to the left sits on top of the - tab to the right: it "opens" (rounds toward the tab starting there) only at the very - first tab and at the active tab's own left edge, and "closes" (rounds back, ceding the - position to the tab on its left) everywhere else — so the active tab is the one exception - that always wins both of its top corners, reading as lifted in front of its neighbours. + This is the only navigation header for a screen that shows one view of the full height + at a time, between a few named views (for example ``Info`` and ``Routes`` on the node + detail page), and does not stack them. Each tab always has a box with a full top. The + box has a dim ``faint`` outline by default, and a lit ``accent`` outline when the tab + is active. It is not only the active tab that has a box. Thus the width of each tab is + fixed, in any selection, and a switch of tabs never shifts the labels that follow it. + Neighbouring tabs share a vertical line (one glyph, not two). Each shared *top* corner + is drawn as if the tab on the left sits on top of the tab on the right. It "opens" + (rounds toward the tab that starts there) only at the first tab and at the left edge of + the active tab. It "closes" (rounds back, and gives the position to the tab on its + left) in all other places. Thus the active tab is the one exception. It always wins both + of its top corners, and it looks lifted in front of its neighbours. - The *bottom* border is a single continuous accent-coloured rule — it's one line, so it - carries one colour throughout, the active tab's — that the inactive tabs sit flush - against: they get no corners or seams of their own down there, just the rule passing - behind them, broken only under the active tab, which is why it reads as merged into the - page below it: the rule turns up into ``╯`` (closing off the flat run from the west, - turning north into the tab's wall), leaves the active tab's width open (no line — that - gap *is* the page starting), then turns back down through ``╰`` (the wall meeting the - flat run continuing east) and carries on flat. A lone tab collapses to the plain accent - heading (:func:`~meshterm.ui.menus.section_heading`'s ``── Label ──`` form) since there - is nothing to switch between or layer. When there's slack in ``width``, the tab boxes - (top and label rows) sit two columns in from the left; the bottom rule is one continuous - line regardless, so it fills that margin rather than being indented with them. The - owning screen switches the active index (``Tab``/``Shift+Tab``); the strip itself is - pure presentation. + The *bottom* border is a single continuous rule with the accent colour. It is one line, + so it has one colour throughout, the colour of the active tab. The inactive tabs sit + flush against it. They have no corners or seams of their own there. The rule only + passes behind them. It is broken only under the active tab, and thus the tab looks + merged into the page below it. The rule turns up into ``╯`` (it closes the flat run + from the west, and turns north into the wall of the tab). It leaves the width of the + active tab open (no line, because that gap *is* the start of the page). Then it turns + back down through ``╰`` (the wall meets the flat run that continues east) and goes on + flat. A lone tab becomes the plain accent heading (the ``── Label ──`` form of + :func:`~meshterm.ui.menus.section_heading`), because there is nothing to switch + between or to layer. When ``width`` has more space than necessary, the tab boxes (the + top row and the label row) are two columns from the left. The bottom rule is one + continuous line in all cases, so it fills that margin and does not have the indent of + the boxes. The screen that owns the strip changes the active index (``Tab`` and + ``Shift+Tab``). The strip itself is only a presentation. - Where rows are scarcer than that (``compact``, see :func:`short_frame`) the same strip is - drawn on its own bottom rule, in one row: ``──┤ Info ├── Routes ──────``. The active tab - stands on the rule between tees, lit; an inactive one is its label on the rule, faint. - Every tab is the same width in either state, so switching still never moves a label. + Where rows are scarcer than that (``compact``, refer to :func:`short_frame`), the + function draws the same strip on its own bottom rule, in one row: + ``──┤ Info ├── Routes ──────``. The active tab stands on the rule between tees, and it is + lit. An inactive tab is its label on the rule, in faint style. In both states, each tab + has the same width, so a switch still never moves a label. Args: - labels: The tab names in display order. - active: Index of the lit tab. - width: The strip's render width — the closing rule fills out to it. + labels: The tab names, in the order of display. + active: The index of the lit tab. + width: The render width of the strip. The closing rule fills to it. compact: Draw the strip on one row instead of three. Returns: - A :class:`~rich.console.Group` of one line (a lone tab, none, or a compact strip) or - three (the shared top border, the boxed labels, and the shared bottom rule). + A :class:`~rich.console.Group` of one line (a lone tab, no tab, or a compact strip) + or three lines (the shared top border, the boxed labels, and the shared bottom + rule). """ if not labels: return Group(Text("")) @@ -1337,17 +1401,18 @@ def tab_strip(labels: Sequence[str], active: int, width: int, *, compact: bool = pad = " " * margin def top_owner(junction: int) -> int: - """Which tab's top corner glyph sits at this junction — see the docstring's rule.""" + """The tab whose top corner glyph is at this junction (refer to the docstring rule).""" return junction if junction == 0 or junction == active else junction - 1 def top_style(junction: int) -> str: return "accent" if top_owner(junction) == active else "faint" def bot_glyph(junction: int) -> str: - """The bottom rule's glyph at this junction. + """The glyph of the bottom rule at this junction. - A corner turning into or out of the active tab's wall, else a flat - pass-through. Always accent — see the enclosing docstring for why. + It is a corner that turns into or out of the wall of the active tab, or else a flat + pass-through. It always has the accent colour. Refer to the enclosing docstring for + the reason. """ if junction == active: return "╯" @@ -1375,7 +1440,7 @@ def tab_strip(labels: Sequence[str], active: int, width: int, *, compact: bool = def _contacts_legend() -> Text: - """The node-type legend, indented to sit under the contacts table body.""" + """The node-type legend, with an indent so that it is under the body of the contacts table.""" return node_type_legend(indent=" ") @@ -1387,32 +1452,34 @@ def contacts_table( counts: dict[str, int], sort: ContactsSort | None = None, ) -> Group: - """List this node and its known contacts with recency, packets, type, key, and legend. + """List our node and its known contacts with the age, packets, type, key, and legend. - Our own node is the first row (``★``, name in the white ``you`` style); contacts follow - in ``sort`` order. - A per-type glyph marks each node in the app's shared colours, the name takes the node's - hash-derived palette hue, the heard age glows with recency heat (brighter = fresher), - and the full key is shown with its path-hash prefix lit — chopped with an ellipsis only + Our node is the first row (``★``, with the name in the white ``you`` style). The + contacts follow in the order of ``sort``. A glyph for the type marks each node in the + shared colours of the app. The name has the palette hue that comes from the hash of the + node. The heard age glows with the heat of recency (brighter = fresher). The table + shows the full key with its path-hash prefix lit. It cuts the key with an ellipsis only when the terminal is too narrow. Args: - self_name: This node's advertised name. - self_key: This node's full public key (hex); blank renders as ``?``. - contacts: Known contacts, listed after our own node. - prefix_bytes: Path-hash width in bytes to highlight in every key. - counts: Overheard-packet counts keyed by lowercased 12-hex node id (from - monitoring); a contact with no entry shows ``—``. - sort: The active sort (column + direction); defaults to name-ascending. The sorted - column's header is lit cyan with an up/down direction triangle. + self_name: The advertised name of our node. + self_key: The full public key of our node (hex). If it is blank, the table shows + ``?``. + contacts: The known contacts, listed after our node. + prefix_bytes: The path-hash width in bytes to light in each key. + counts: The counts of overheard packets, keyed by the 12-hex node id in lower case + (from monitoring). A contact with no entry shows ``—``. + sort: The active sort (column and direction). The default is name ascending. The + header of the sorted column is lit cyan, with a triangle for the direction. Returns: - A Rich :class:`Group` of the frameless table and its glyph legend. + A Rich :class:`Group` of the table without a frame and its legend of glyphs. """ sort = sort if sort is not None else ContactsSort() - # expand=True lets the key column (the only flexible one) soak up all spare width and be - # the sole column Rich squeezes when narrow — the fixed columns keep their natural size. + # expand=True lets the key column (the only flexible column) take all the spare width. + # It is also the only column that Rich squeezes when the terminal is narrow. The fixed + # columns keep their natural size. table = Table( title=f"[accent]Contacts[/accent] [muted]· {len(contacts)} known[/muted]", title_justify="left", @@ -1423,9 +1490,10 @@ def contacts_table( expand=True, padding=(0, 2, 0, 0), ) - # Each sortable header reserves two extra columns for its " ▲" direction marker (via - # min_width = label + 2) so the same width holds whether or not it's the active sort — - # switching the sort never widens a column and shifts the rest of the row. + # Each sortable header keeps two more columns for its " ▲" direction marker (with + # min_width = label + 2). Thus the width is the same if the header is the active sort or + # not. A change of the sort never makes a column wider and never shifts the rest of the + # row. table.add_column("", no_wrap=True) # node-type glyph table.add_column(_sort_header("NAME", "name", sort), no_wrap=True, min_width=6) table.add_column( @@ -1434,13 +1502,13 @@ def contacts_table( table.add_column( _sort_header("PKTS", "packets", sort), justify="right", no_wrap=True, min_width=6 ) - # The full key, chopped to an ellipsis by Rich only when the row won't otherwise fit. + # The full key. Rich cuts it to an ellipsis only when the row does not fit in another way. table.add_column("KEY", no_wrap=True, overflow="ellipsis", ratio=1, min_width=10) unknown = Text("?", style="muted") table.add_row( Text(SELF_MARK[0], style=SELF_MARK[1]), - # Our own name is the app-wide pure-white "you" style, never a palette hue. + # Our name has the pure-white "you" style of the app, and never a palette hue. Text.assemble((self_name, "you"), (" (you)", "muted")), Text("—", style="faint"), Text("—", style="faint"), @@ -1462,10 +1530,10 @@ def contacts_table( def tx_opt_table(result: TxOptResult) -> Table: - """Render every measured TX level of an optimization sweep, best row highlighted. + """Render each measured TX level of an optimization sweep, with the best row highlighted. Args: - result: The optimization result to display. + result: The optimization result to show. Returns: A Rich :class:`Table` of TX level, target SNR, success rate, and sample count. @@ -1484,7 +1552,7 @@ def tx_opt_table(result: TxOptResult) -> Table: marker = "[ok]★[/ok] " if is_best else " " snr = lv.target_snr snr_cell = Text(f"{snr:+.1f}", style=snr_style(snr)) if snr is not None else Text("—") - # Highlight anything short of a perfect success rate — reliability comes first. + # Highlight each rate that is less than a perfect success rate. Reliability is first. rate = lv.success_rate rate_style = "ok" if rate >= 1.0 else ("warn" if rate > 0 else "err") rate_cell = Text(f"{rate:.0%}", style=rate_style) @@ -1495,13 +1563,14 @@ def tx_opt_table(result: TxOptResult) -> Table: def tx_opt_summary(result: TxOptResult) -> Panel: - """Summarize a TX optimization outcome. + """Summarize the result of a TX optimization. Args: result: The optimization result to summarize. Returns: - A Rich :class:`Panel` stating the chosen optimum and whether it was applied. + A Rich :class:`Panel` that states the optimum that was chosen and if MeshTerm + applied it. """ snr = result.best_snr snr_text = Text(f"{snr:+.1f} dB", style=snr_style(snr)) if snr is not None else Text("n/a") @@ -1535,70 +1604,77 @@ def tx_opt_summary(result: TxOptResult) -> Panel: # -- battery gauge -------------------------------------------------------------------------- -#: Unicode braille pattern base; add an 8-bit dot mask (a 2×4 cell) to get the glyph. +#: The base of the Unicode braille patterns. Add an 8-bit dot mask (a cell of 2×4) to get +#: the glyph. _BRAILLE_BASE = 0x2800 -#: Dot bit per (column, row) within a braille cell — the Unicode standard layout, the same -#: mapping the map canvas rasters with. Kept here so the one-cell battery glyph needn't reach -#: into the canvas module for two constants. +#: The dot bit for each (column, row) in a braille cell. This is the standard layout of +#: Unicode, and it is the same mapping that the map canvas uses for its rasters. It is +#: here, so that the one-cell battery glyph does not need to reach into the canvas module +#: for two constants. _BRAILLE_DOTS = ((0x01, 0x02, 0x04, 0x40), (0x08, 0x10, 0x20, 0x80)) -#: The fuel-gauge bands: ``(percent floor, style)``, highest first. Colour answers *how much -#: pack is left* in three broad steps — light green on green over half, yellow on brown over a -#: quarter, light red on red below — while the eight-rung braille fill inside the block -#: answers *how much more precisely*. Two questions, two channels: a band that stayed put -#: while the dots climbed is what makes the cell readable at a glance and still exact on a -#: second look. +#: The bands of the fuel gauge: ``(percent floor, style)``, with the highest first. The +#: colour answers *how much of the battery is left* in three broad steps: light green on +#: green above half, yellow on brown above a quarter, and light red on red below. The +#: braille fill with eight rungs in the block answers *how much, more exactly*. There are +#: two questions and two channels. A band that stays the same while the dots climb makes +#: the cell readable at a glance, and it is still exact at a second look. _BATTERY_BANDS: tuple[tuple[int, str], ...] = ( (50, "batt.full"), (25, "batt.mid"), (0, "batt.low"), ) -#: Steps in the fill: one braille cell is 2×4 dots, and each dot row lights left-then-right, -#: so the cell reads as an eight-rung ladder — one rung per 12.5% of charge. +#: The steps in the fill. One braille cell is 2×4 dots, and each row of dots lights from +#: left to right. Thus the cell reads as a ladder with eight rungs, one rung for each 12.5% +#: of charge. _BATTERY_STEPS = 8 -#: Halfway down the last rung the cell starts alarming, and it does it by dropping the ground -#: rather than by changing hue: black dots on red one frame (``batt.flash``), the light red on -#: the bare page the next (``batt.flash.off``). Every other cell in the app's gauge is a -#: filled block, so a beat with no fill at all is the loudest thing the palette can say. -#: A percentage rather than a rung because half a rung is not a rung: a rung is ``100 / 8`` = -#: 12.5% of the pack, so its midpoint is 6.25% — the last dot half spent. +#: Halfway down the last rung, the cell starts to alarm. It does this by dropping the +#: ground, and not by a change of hue. In one frame it shows black dots on red +#: (``batt.flash``), and in the next frame the light red on the bare page +#: (``batt.flash.off``). Each other cell of the gauge of the app is a filled block. Thus a +#: beat with no fill at all is the loudest thing that the palette can say. The threshold +#: is a percentage and not a rung, because half of a rung is not a rung. A rung is +#: ``100 / 8`` = 12.5% of the battery, so its midpoint is 6.25%, where the last dot is half +#: spent. #: -#: The alternation is ours, drawn a frame at a time. The console's own blink attribute is no -#: use even where a terminal honours it: SGR 5 toggles the *foreground* and leaves the ground -#: alone, which is the half of this that matters (and the PicoCalc's framebuffer console -#: ignores it outright — device-checked, along with its want of bright backgrounds). +#: MeshTerm makes the alternation itself, one frame at a time. The blink attribute of the +#: console is not useful, also where a terminal supports it. SGR 5 toggles the +#: *foreground* and leaves the ground, and the ground is the half that matters here. (The +#: framebuffer console of the PicoCalc ignores it completely. We checked this on the +#: handheld, with its lack of bright backgrounds.) _BATTERY_FLASH_PCT = 100 / _BATTERY_STEPS / 2 -#: Frames in the charging sweep: empty → four fills → round again (bottom-to-full loop). +#: The frames in the charging sweep: empty → four fills → round again (a loop from the +#: bottom to full). _CHARGE_FRAMES = 5 -#: A full pack reads ``100``, with no ``%`` — the one charge whose sign is dropped, so the -#: reading is three cells wide exactly as ``99%`` is. +#: A full battery reads ``100`` with no ``%``. It is the only charge for which MeshTerm +#: removes the sign, so the reading has three cells, the same as ``99%``. #: -#: Which matters because 99 and 100 are the two numbers a topped-off pack sits *between*: -#: the charger cuts out at full, the pack settles back to 99, the charger restarts, and the -#: companion reports the flip every poll for as long as it is plugged in (JP, 2026-09-09). -#: The gauge is pinned to the header's right edge and the pulse takes what is left, so a -#: number that grew a cell at the top of the range took that cell off the sparkline and -#: redrew the whole activity history at a new scale, twice a minute, on a device sitting -#: still. Every other width change in the range — 9 to 10 on the way down — is a boundary a -#: discharging pack crosses once and never comes back over, so it costs one repaint and -#: needs no answer. +#: This is important because a battery that is topped off is *between* 99 and 100. The +#: charger stops at full, the battery goes back to 99, the charger starts again, and the +#: companion reports the change at each poll as long as it is plugged in (JP, 2026-09-09). +#: The gauge is pinned to the right edge of the header, and the pulse takes what is left. +#: Thus a number that grew by a cell at the top of the range took that cell from the +#: sparkline. It drew the whole activity history again at a new scale, twice each minute, +#: on a device that was not moving. All other width changes in the range, for example 9 to +#: 10 on the way down, are a boundary that a discharging battery crosses one time and never +#: crosses again. They cost one repaint and need no answer. #: -#: A bare ``100`` beside a full block reads as a percentage without being told; ``%`` is -#: doing its work at the readings that could be mistaken for something else. +#: A bare ``100`` next to a full block reads as a percentage without a sign. The ``%`` does +#: its work at the readings that a user can mistake for something else. _BATTERY_FULL = "100" def _braille_fill(steps: int) -> str: - """A single braille cell filled from the bottom by ``steps`` (0–8) half-rows. + """A single braille cell that is filled from the bottom by ``steps`` (0–8) half-rows. - Each dot row is two steps: the left dot lights first, then the right one completes the - row, so the fill climbs in half-rows rather than whole ones and one cell carries eight - distinguishable levels. + Each row of dots is two steps. The left dot lights first, and then the right dot + completes the row. Thus the fill climbs in half-rows and not in whole rows, and one + cell has eight levels that the user can tell apart. """ steps = max(0, min(_BATTERY_STEPS, steps)) bits = 0 @@ -1609,21 +1685,22 @@ def _braille_fill(steps: int) -> str: def _battery_steps(percent: int) -> int: - """How many half-rows a charge lights: one rung per 12.5%, never fewer than one. + """The half-rows that a charge lights: one rung for each 12.5%, and never fewer than one. - The bands are ``0–12.5`` → one rung … ``87.5–100`` → the full cell, each one taking its - lower bound. A pack on its last percent still lights a single dot, so the gauge is never - an empty cell while the pack is still running. + The bands are ``0–12.5`` → one rung … ``87.5–100`` → the full cell. Each band takes its + lower bound. A battery at its last percent still lights a single dot. Thus the gauge is + never an empty cell while the battery is still running. """ pct = max(0, min(100, int(percent))) return max(1, min(_BATTERY_STEPS, int(pct * _BATTERY_STEPS / 100) + 1)) def _battery_band(percent: int) -> str: - """The band a charge draws in (see :data:`_BATTERY_BANDS`) — always the *true* charge. + """The band in which a charge draws (refer to :data:`_BATTERY_BANDS`): the *true* charge. - Read off the pack rather than off the cell, so the charging sweep keeps saying what the - pack holds while its fill climbs through frames that mean nothing on their own. + The function reads the value from the battery and not from the cell. Thus the charging + sweep keeps showing what the battery holds, while its fill climbs through frames that + have no meaning on their own. """ for floor, style in _BATTERY_BANDS: if percent >= floor: @@ -1632,65 +1709,70 @@ def _battery_band(percent: int) -> str: def battery_cell(percent: int, *, charging: bool = False, frame: int = 0) -> Text: - """The status-bar battery gauge: one filled braille block, then its ``%``. + """The battery gauge of the status bar: one filled braille block, then its ``%``. - The cell is a lit foreground over its own darker ground — a *block*, coloured by band - (:data:`_BATTERY_BANDS`): light green on green over half, yellow on brown over a quarter, - light red on red below. Inside that block the braille fills from the bottom up in eight - half-row steps (see :func:`_braille_fill`), one rung per 12.5% of charge, the left dot of - a row lighting before the right. So the block answers *roughly how much* from across the - room and the dots answer *exactly how much* on a second look. Two live states animate off - the caller's ``frame`` counter (advanced one step per repaint tick), so the gauge moves - without any per-frame plumbing: + The cell is a lit foreground over its own darker ground. It is a *block*, with a colour + for each band (:data:`_BATTERY_BANDS`): light green on green above half, yellow on brown + above a quarter, and light red on red below. In that block, the braille fills from the + bottom up in eight half-row steps (refer to :func:`_braille_fill`), one rung for each + 12.5% of charge. The left dot of a row lights before the right dot. Thus the block + answers *approximately how much* from across the room, and the dots answer *exactly how + much* at a second look. Two live states animate from the ``frame`` counter of the + caller (it advances one step for each repaint tick). Thus the gauge moves, and no + plumbing for each frame is necessary. - * **Charging** overrides the fill: the cell sweeps empty-to-full on a loop, so a - plugged-in pack visibly climbs. The band does *not* sweep with it — colour keeps - answering for the real charge, since a frame of the animation means nothing on its own - — and neither does the number beside it, which stays the true percent throughout. The - sweep climbs by whole dot rows, not by the fill's half-rows: it is a "power is coming - in" animation rather than a reading, and its tick is slow enough (a step per repaint) - that five frames say that better than nine. - * **Below :data:`_BATTERY_FLASH_PCT`** — half the last dot's worth of charge, and only - when nothing is charging it — the cell alternates between black dots on red and the - light red on the bare page. Dropping the ground for a beat is a bigger change than any - hue swap in a palette where every other cell is filled, which is the point: it is the - last warning a handheld gives before it dies. + * **Charging** replaces the fill. The cell sweeps from empty to full in a loop, so the + user can see a plugged-in battery climb. The band does *not* sweep with it. The colour + keeps answering for the real charge, because a frame of the animation has no meaning + on its own. The number next to the cell does not sweep either, and it stays the true + percent. The sweep climbs by whole rows of dots, and not by the half-rows of the + fill. It is an animation for "power is coming in" and not a reading. Its tick is slow + (one step for each repaint), so five frames show this better than nine. + * **Below** :data:`_BATTERY_FLASH_PCT` (half of the charge of the last dot, and only + when nothing charges the battery), the cell alternates between black dots on red and + the light red on the bare page. When the ground drops for a beat, the change is bigger + than any change of hue in a palette where each other cell is filled. This is the + purpose: it is the last warning that a handheld gives before it dies. - Both run on every platform, stepping at whatever that platform repaints at — 2 s on the - PicoCalc, where the header is rebuilt on the idle tick anyway, so an animation costs a - colour swap in a frame already being painted and nothing else. Neither is behind - ``Platform.effects``: one *is* the charging state, and the other is the last warning a - handheld gives before it dies. + Both states run on each platform. They step at the rate at which that platform + repaints. On the PicoCalc this is every 2 s, where the header is rebuilt on the idle + tick in any case. Thus an animation costs only a colour swap in a frame that MeshTerm + already paints. Neither state is behind ``Platform.effects``, because one of them *is* + the charging state, and the other is the last warning that a handheld gives before it + dies. - A pack at 100% is drawn as **not charging** whichever way the flag reads: a full cell - resting full is the honest picture, and a topped-off charger left plugged in shouldn't - leave the gauge sweeping forever. It also drops its ``%`` (:data:`_BATTERY_FULL`), so - that full reading is the same three cells as the 99% it keeps flipping back to and the - header stops resizing under a pack on a charger. + A battery at 100% is drawn as **not charging**, for each value of the flag. A full cell + that stays full is the correct picture, and a charger that is topped off and left + plugged in must not leave the gauge sweeping forever. The function also removes its + ``%`` (:data:`_BATTERY_FULL`). Thus the full reading has the same three cells as the 99% + to which it keeps flipping back, and the header does not change its size under a + battery on a charger. Args: - percent: State of charge, 0–100 (clamped). - charging: Whether the pack is taking charge (drives the fill sweep). Ignored at 100%. - frame: A monotonically advancing tick; only its phase is read, so any - steadily-incrementing integer animates the two live states. + percent: The state of charge, 0–100 (clamped). + charging: ``True`` if the battery takes charge (it drives the fill sweep). The + function ignores it at 100%. + frame: A tick that always advances. The function reads only its phase, so any + integer that increases steadily animates the two live states. Returns: - A Rich :class:`Text`: the coloured block, a space, and ``NN%`` in muted text — a - full pack's bare ``100`` the one exception (:data:`_BATTERY_FULL`) — with the - block's colours on the glyph's span alone, so the ground stops at the cell. + A Rich :class:`Text`: the coloured block, a space, and ``NN%`` in muted text. The + one exception is the bare ``100`` of a full battery (:data:`_BATTERY_FULL`). The + colours of the block are on the span of the glyph alone, so the ground stops at the + cell. """ pct = max(0, min(100, int(percent))) - # The sweep climbs by whole rows, so the loop stays legible. Colour comes off the pack - # either way: a sweep frame is an animation, not a reading, and must not be coloured - # as though it were one. + # The sweep climbs by whole rows, so the loop stays easy to read. In both cases, the + # colour comes from the battery. A sweep frame is an animation and not a reading, and + # it must not have a colour as if it were a reading. sweeping = charging and pct < 100 steps = (frame % _CHARGE_FRAMES) * 2 if sweeping else _battery_steps(pct) color = _battery_band(pct) if not sweeping and pct < _BATTERY_FLASH_PCT: color = "batt.flash.off" if frame % 2 else "batt.flash" - # The colours ride the *glyph's own span*, never the Text's base style: the block paints - # a background, and a base style merges into every span, so a base block would drag the - # muted percent onto the coloured ground alongside the cell. + # The colours are on the *own span of the glyph* and never on the base style of the Text. + # The block paints a background, and a base style merges into each span. If the block + # is the base style, the muted percent goes onto the coloured ground next to the cell. out = Text() out.append(_braille_fill(steps), style=color) out.append(f" {_BATTERY_FULL if pct == 100 else f'{pct}%'}", style="muted")