From 935b4fb3b6e77c24e3c55a0651e43dcabb65dd7e Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Fri, 7 Aug 2026 20:08:31 -0400 Subject: [PATCH] PicoCalc: nodes colour by key, like everywhere else MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A platform's ceiling may change a rule's resolution, never the rule. P3 had picocalc colour node names by *type* instead of by key, so a name's colour there meant something different than it does on the desktop — the node's kind, not its identity. Both platforms now run one rule: the key's first byte picks the hue. The console just spends fewer of them. node_style gains the binding the heat scale already had. Regular keeps the full 256-hue wheel; picocalc snaps the same hue to its sixth of it — the six chromatic bright slots, ~43 first bytes each. It returns the slot's own hex rather than a color(N), so every downsample on the way out (Rich's, and the fold's quantizer) lands on that exact slot instead of guessing a neighbour, and the callers that read an RGB back out of a style string keep working. The type marks needed the opposite treatment: their hues are fixed, not derived, and a naive nearest-RGB match drained the repeater's violet to grey — a repeater read as an unknown node. They move to the theme's type.* entries so each platform picks its slot deliberately, and a braille raster resolves the same entry through theme.mark_rgb, so the canvas marker and its Rich-drawn twin can't drift. With names off the type registry, nothing reads it: Platform.name_colour and core/nodetypes.py go, along with the three reception-layer feeders. Co-Authored-By: Claude Opus 5 (1M context) --- CLAUDE.md | 10 +- meshterm/core/contact_store.py | 6 +- meshterm/core/nodetypes.py | 70 ---------- meshterm/persistence/repository.py | 3 - meshterm/platforms.py | 15 +-- meshterm/services/monitor_service.py | 2 - meshterm/ui/node_detail_screen.py | 6 +- meshterm/ui/pathgraph.py | 9 +- meshterm/ui/specimen.py | 24 ++-- meshterm/ui/theme.py | 193 ++++++++++++++++++--------- meshterm/ui/widgets.py | 29 ++-- tests/test_platforms.py | 1 - tests/test_theme16.py | 50 ++++--- 13 files changed, 209 insertions(+), 209 deletions(-) delete mode 100644 meshterm/core/nodetypes.py diff --git a/CLAUDE.md b/CLAUDE.md index 21c6f67..a4c9892 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -132,6 +132,7 @@ Relative ages: `format_ago` for prose ("now", "5m ago", "never" — never "now a - Node names are always coloured: `name_style(name, key)` palette hue, derived from the node's key (its first byte — any known prefix agrees) so a rename keeps the colour. + One rule on **every** platform; only the resolution changes (see **Platforms**). A surface holding only a name resolves it first (`make_name_key_resolver`); a name no known node carries stays muted — colour is reserved for keyed identities, never seeded from a name's characters. Our own node @@ -169,8 +170,13 @@ branch on the platform per frame, and never `from meshterm.platforms import PLAT - The 16-slot palette is `theme._VT_SLOTS` (programmed via `/etc/vtrgb`; same script). `MESH_THEME_16` speaks `color(0..15)` only; bold is brightness on the VT (never bold slots 5/6); backgrounds stop at slot 7. Both themes define identical style names. -- On picocalc, names colour by node **type** (`core/nodetypes` registry), heat - quantizes to the `heat.*` steps, and footer hints are replaced by the **F-key lane** +- On picocalc, the node hue and the heat gradient **quantize** — same rule, coarser + resolution: `node_style` snaps the key's hue to its sixth of the wheel + (`theme._NODE_SLOT_HEXES`, the six chromatic bright slots) and heat to the `heat.*` + steps. Nothing loses its colour for being on the console. Marks whose hue is *fixed* + rather than derived go through a theme name so the slot is chosen deliberately (the + node types' `type.*`; a raster resolves the same entry via `theme.mark_rgb`) — a naive + downsample greys the repeater's violet. Footer hints are replaced by the **F-key lane** (`ui/tui/fkeys.py`): five `FPair` slots per screen, F1–F5 primary and F6–F10 their paired opposites (physical Shift+F1..F5), labels ≤7 cells. Screens override `fkey_lane` for their own verbs; slots 3/4 are the customary free pair. **A chip names diff --git a/meshterm/core/contact_store.py b/meshterm/core/contact_store.py index affadcb..cd50ec4 100644 --- a/meshterm/core/contact_store.py +++ b/meshterm/core/contact_store.py @@ -33,7 +33,6 @@ from pathlib import Path from typing import Optional from .models import Contact, advert_time -from .nodetypes import register_node_type def _norm(pubkey: str) -> str: @@ -285,7 +284,4 @@ def merge_contacts( for remembered in store.contacts(device_pubkey) if remembered.public_key and remembered.public_key not in present ] - merged = list(live) + extra - for contact in merged: # every contact read passes through here — feed the type registry - register_node_type(contact.public_key or contact.key_prefix, contact.node_type) - return merged + return list(live) + extra diff --git a/meshterm/core/nodetypes.py b/meshterm/core/nodetypes.py deleted file mode 100644 index e526840..0000000 --- a/meshterm/core/nodetypes.py +++ /dev/null @@ -1,70 +0,0 @@ -"""A process-wide map from a node's key prefix to its advert type. - -PicoCalc's 16-slot console palette can't afford the regular platform's 256-hue key-derived -name spectrum, so there a name is coloured by its node's *type* (client / repeater / room / -sensor) instead — see ``name_colour`` on :class:`~meshterm.platforms.Platform`. The theme's -type-based ``name_style`` needs the type for a bare key at render time, long after the -advert that carried it; this registry is that lookup. - -It is fed by the reception layer wherever typed nodes materialize — live observations -(:class:`~meshterm.services.monitor_service.MonitorService`), heard nodes read back from -the history DB (:meth:`~meshterm.persistence.repository.Repository.heard_nodes`), and the -device's contact list (:func:`~meshterm.core.contact_store.merge_contacts`) — so both a -fresh session and a long-running one resolve the same nodes to the same types. - -Keys are reduced to their **first byte**, the same slice every key-prefix surface agrees -on (see :func:`~meshterm.ui.theme.node_style`): any prefix of a key a caller happens to -hold — a 2-hex path hop, the stored 12-hex id, the full public key — lands on the same -entry. Two nodes sharing a first byte with different types will colour by whichever was -registered last; colour is a hint, not a guarantee, and the collision odds mirror the -hue-collision odds the regular platform already accepts. -""" - -from __future__ import annotations - -from typing import Optional - -from .models import NODE_TYPE_LABELS - -#: first key byte (two lowercase hex chars) → type name ("node"/"repeater"/"room"/"sensor"). -_TYPES_BY_PREFIX: dict[str, str] = {} - - -def _prefix(key: str) -> Optional[str]: - """The registry key for ``key``: its first byte as two lowercase hex chars.""" - raw = key.lower().removeprefix("0x") - return raw[:2] if len(raw) >= 2 else None - - -def register_node_type(key: Optional[str], node_type: Optional[int]) -> None: - """Record that the node ``key`` belongs to advertises as ``node_type``. - - A no-op for a missing key, a too-short prefix, or a type outside the known - ``NODE_TYPE_*`` set, so reception paths can call it unconditionally. - - Args: - key: The node's public key or any hex prefix of it (first byte is used). - node_type: The advert type (``NODE_TYPE_CHAT``/``REPEATER``/``ROOM``/``SENSOR``), - or ``None`` when the packet didn't carry one. - """ - if not key or node_type is None: - return - name = NODE_TYPE_LABELS.get(node_type) - prefix = _prefix(key) - if name and prefix: - _TYPES_BY_PREFIX[prefix] = name - - -def node_type_name(key: Optional[str]) -> Optional[str]: - """The registered type name for ``key``'s node, or ``None`` when never registered. - - Args: - key: The node's key/hash as hex (any length ≥ 1 byte). - - Returns: - ``"node"``, ``"repeater"``, ``"room"``, ``"sensor"``, or ``None``. - """ - if not key: - return None - prefix = _prefix(key) - return _TYPES_BY_PREFIX.get(prefix) if prefix else None diff --git a/meshterm/persistence/repository.py b/meshterm/persistence/repository.py index 164da84..3a88adc 100644 --- a/meshterm/persistence/repository.py +++ b/meshterm/persistence/repository.py @@ -15,7 +15,6 @@ from pathlib import Path from typing import Any, Optional from ..core.frames import CHANNEL_CLASSES, ENDPOINT_HASH_BYTES -from ..core.nodetypes import register_node_type from ..core.models import ( PATH_TRACE_TARGET, ChatMessage, @@ -1585,8 +1584,6 @@ class Repository: ) for node, s in stats.items() ] - for heard in nodes: # backfill the type registry from history (PicoCalc colour) - register_node_type(heard.public_key or heard.node, heard.node_type) return sorted(nodes, key=lambda n: n.last_seen, reverse=True) # -- chat messages ---------------------------------------------------------- diff --git a/meshterm/platforms.py b/meshterm/platforms.py index f05aac6..b128b96 100644 --- a/meshterm/platforms.py +++ b/meshterm/platforms.py @@ -62,12 +62,10 @@ class Platform: ascii_fold: Whether names and message bodies are NFKD-folded (accents stripped) at the render boundary before display. Storage is never touched. Wired in P3. truecolor: Whether the theme may use arbitrary 24-bit SGR colour. ``False`` selects - a 16-slot palette theme instead (the console's real ceiling — no per-cell RGB). - Wired in P3. - name_colour: ``"key"`` (today's per-node hash-derived hue spectrum) or ``"type"`` - (colour by node type — client/repeater/room/sensor — because PicoCalc's 16 - colour slots can't also afford a hash spectrum without collisions). Wired into - :func:`~meshterm.ui.theme.name_style` in P3. + a 16-slot palette theme instead (the console's real ceiling — no per-cell RGB), + and quantizes the two scales that would otherwise spend a gradient — the + per-node key hue (:func:`~meshterm.ui.theme.node_style`) and the heard-age heat + (:func:`~meshterm.ui.widgets._recency_style`). Wired in P3. effects: Whether animated/decorative rendering runs at all: corner glow, the header battery blink, the braille spinner. ``False`` drops to static chrome and a ``LINE`` spinner fallback — cheaper, and the glow already no-ops on a @@ -106,7 +104,6 @@ class Platform: emoji: bool ascii_fold: bool truecolor: bool - name_colour: str effects: bool tick_s: float spinner_tick_s: float @@ -126,7 +123,6 @@ REGULAR = Platform( emoji=True, ascii_fold=False, truecolor=True, - name_colour="key", effects=True, tick_s=1.0, spinner_tick_s=0.12, @@ -135,7 +131,7 @@ REGULAR = Platform( ) #: The PicoCalc/Lyra/Calculinux framebuffer console. Field values not yet consumed by a -#: binding point (header_atoms, ascii_fold, truecolor, name_colour, effects beyond the +#: binding point (header_atoms, ascii_fold, truecolor, effects beyond the #: two P1 bindings, tick_s, battery, modifier_watch) are P2–P5's targets, recorded here #: now so the seam exists before the flavour work lands — see .claude/plans/picocalc-platform.md. PICOCALC = Platform( @@ -152,7 +148,6 @@ PICOCALC = Platform( emoji=False, ascii_fold=True, truecolor=False, - name_colour="type", effects=False, tick_s=2.0, spinner_tick_s=0.5, diff --git a/meshterm/services/monitor_service.py b/meshterm/services/monitor_service.py index 35da80e..168aa06 100644 --- a/meshterm/services/monitor_service.py +++ b/meshterm/services/monitor_service.py @@ -25,7 +25,6 @@ from typing import TYPE_CHECKING, Optional from ..core.connection import Unsubscribe from ..core.events import EventKind, MeshEvent from ..core.models import Observation, utcnow -from ..core.nodetypes import register_node_type if TYPE_CHECKING: from ..context import AppContext @@ -256,7 +255,6 @@ class MonitorService: "monitor", {"mode": "background"}, self._ctx.profile_name ) self._ctx.repo.record_observation(self._run_id, obs) - register_node_type(obs.node, obs.node_type) except Exception as exc: # noqa: BLE001 - never let logging break capture self._ctx.log.debug("monitor: failed to record observation: %s", exc) finally: diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index cf210ed..189a61c 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -70,7 +70,7 @@ from rich.text import Text from ..core.geo import EARTH_RADIUS_KM, usable_fix from ..core.models import NODE_TYPE_LABELS, Contact, utcnow -from .mapcanvas import RGB, parse_hex +from .mapcanvas import RGB from .minimap import MiniMap from .pathgraph import ( DST_NODE, @@ -83,7 +83,7 @@ from .pathgraph import ( bidir_clusters, render_path_graph, ) -from .theme import name_style, snr_style +from .theme import mark_rgb, name_style, snr_style from .tui.render import crop_cells, render_hanging, render_lines, render_to_ansi from .pathline import PathHop, PathLine, path_line from .tui.screen import CANCEL, ListWindow, Screen @@ -1253,7 +1253,7 @@ def _cluster_presentation(members: tuple[str, ...], type_of) -> _Cluster: # noq else: glyph, color = _DEFAULT_GLYPH kind = "node" - return _Cluster(glyph=glyph, color=color, label=f"{len(members)} {kind}s", rgb=parse_hex(color)) + return _Cluster(glyph=glyph, color=color, label=f"{len(members)} {kind}s", rgb=mark_rgb(color)) def _contract_bidir_clusters( diff --git a/meshterm/ui/pathgraph.py b/meshterm/ui/pathgraph.py index 95fbcec..bb0cb39 100644 --- a/meshterm/ui/pathgraph.py +++ b/meshterm/ui/pathgraph.py @@ -109,6 +109,7 @@ from .marks import ( # noqa: F401 - canonical home; re-exported for existing im LabelRgbOf, parse_hex, ) +from .theme import mark_rgb #: Joins a hop id to its occurrence index when ``allow_duplicate_nodes`` splits a path's #: revisits into their own markers. Leans on the same guarantee the endpoint sentinels do — @@ -438,7 +439,9 @@ def render_path_graph( hop sequences collapse to one drawn path owned by the highest priority among them. width: Canvas width in character cells. glyph_of: Marker glyph + colour per node id (endpoints keyed by - :data:`SRC_NODE` / :data:`DST_NODE`). + :data:`SRC_NODE` / :data:`DST_NODE`). The colour is whatever + :func:`~meshterm.ui.theme.mark_rgb` takes — a literal ``#rrggbb`` or a theme + style name. label_of: Label text per node id (``None``/``""`` = bare marker). A label is kept whole unless it is wider than the canvas, when it is ellipsized to fit. label_rgb_of: Label colour per node id. @@ -620,8 +623,8 @@ def render_path_graph( # -- Markers for every node (endpoints and relays alike each draw once). for node in ordered_nodes: - glyph, color_hex = glyph_of(node) - canvas.marker(*pos[node], glyph, parse_hex(color_hex)) + glyph, colour = glyph_of(node) + canvas.marker(*pos[node], glyph, mark_rgb(colour)) _place_labels(canvas, ordered_nodes, pos, node_lane, width, rows * 2, label_of, label_rgb_of) return canvas.to_ansi_lines() diff --git a/meshterm/ui/specimen.py b/meshterm/ui/specimen.py index 7122efa..5b22c2f 100644 --- a/meshterm/ui/specimen.py +++ b/meshterm/ui/specimen.py @@ -19,9 +19,10 @@ from .packet_viewer import KIND_ICONS, PAYLOAD_ICONS from .theme import _VT_SLOTS, fold_text, glyph, name_style, snr_style from .widgets import _recency_style, channel_glyph -#: Demo identities for the name-colour row: (name, key, node type registered for it). -#: Keys are synthetic and only ever registered inside the one-shot specimen process. -_DEMO_NAMES = (("Alice", "a1b2", 1), ("YUL-Poly", "3d63", 2), ("Lounge", "cc10", 3)) +#: Demo identities for the name-colour row: ``(name, key)``. The keys are synthetic, and +#: chosen so their first bytes land in three different sectors of the hue wheel — on the +#: console that means three different palette slots (see ``theme._NODE_SLOT_HEXES``). +_DEMO_NAMES = (("Alice", "a1b2"), ("YUL-Poly", "3d63"), ("Lounge", "cc10")) def _palette_row() -> Text: @@ -50,14 +51,12 @@ def _ages_row() -> Text: def specimen_lines() -> list[RenderableType]: """The specimen card, one renderable per line (print through the themed console).""" - from meshterm.core.nodetypes import register_node_type - platform = get_platform() lines: list[RenderableType] = [] lines.append(Text.assemble(("Specimen", "accent"), (" · ", "muted"), platform.name)) lines.append(Text()) lines.append(_palette_row()) - legend = Text("stock palette · 8 muted · 13 clients · 15 you", style="muted") + legend = Text("stock palette · 8 muted · 9-14 node hues · 15 you", style="muted") lines.append(legend) lines.append(Text()) @@ -66,10 +65,11 @@ def specimen_lines() -> list[RenderableType]: status.append(mark + " ", style=style) lines.append(status) - # The node marks wear the *type* styles (not the map's raw hex colours): on the - # console they resolve to exact palette slots, and the row then agrees with the - # names row below it. Raw hex here would also trip Rich's per-Style ANSI memo — - # a style first rendered by a truecolor console replays truecolor everywhere. + # The node-type marks in the theme's own ``type.*`` entries — the same styles every + # typed node in the app is drawn in (ui.widgets._NODE_GLYPHS), so this row *is* the + # marker language rather than a restatement of it. The star and the unknown ring have + # no type of their own: they take the ``you`` white and ``muted`` grey they carry + # everywhere else. nodes = Text("nodes ") nodes.append("★ ", style="you") for mark, style in ( @@ -105,10 +105,8 @@ def specimen_lines() -> list[RenderableType]: lines.append(Text("keys ⌫ ⇧ … ↕ ↔ ↻ ⌖ ❯ ▸")) lines.append(Text()) - for name, key, node_type in _DEMO_NAMES: - register_node_type(key, node_type) names = Text("names ") - for name, key, _ in _DEMO_NAMES: + for name, key in _DEMO_NAMES: names.append(name + " ", style=name_style(name, key)) names.append("me", style="you") lines.append(names) diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index 0555793..839fd7a 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -20,7 +20,6 @@ from rich.cells import cell_len from rich.console import Console from rich.theme import Theme -from ..core.nodetypes import node_type_name from ..platforms import Platform, on_platform from .fontset import FONT_CODEPOINTS @@ -87,15 +86,15 @@ MESH_THEME = Theme( "batt.mid": "bold #fb923c", "batt.low": "bold #f87171", "batt.dim": "#475569", - # Node-type colours, used where the platform colours names by *type* instead of by - # key (PicoCalc — see name_style). Defined in both themes so the names always - # resolve; the regular platform simply never asks for them. Hues follow the map's - # marker language: clients the map's pink, repeaters its violet, sensors its - # orange; rooms take a teal of their own (the map's white square is reserved for - # "you" in name contexts). + # 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. "type.node": "#f472b6", "type.repeater": "#a78bfa", - "type.room": "#5eead4", + "type.room": "#ffffff", "type.sensor": "#fb923c", # The heard-age heat scale's quantized steps (hot → cold). The regular platform # interpolates a continuous gradient instead (ui.widgets._recency_style); these @@ -123,26 +122,28 @@ MESH_THEME = Theme( #: * The kernel VT renders **bold as brightness**: ``bold`` on a 0–7 foreground jumps it #: to slot N+8. A style may only combine ``bold`` with a dim slot when the bright #: partner keeps its meaning — and never with 5/6, whose partners are claimed by -#: *different* semantics here (5 purple = repeater names, 13 pink = client names; -#: 6 cyan = room names/hint.brand, 14 bright cyan = brand). +#: *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`). _VT_SLOTS: tuple[tuple[int, str, str], ...] = ( (0, "background (black)", "#000000"), (1, "red (hint.err)", "#aa0000"), (2, "green (hint.ok)", "#00aa00"), - (3, "brown/orange (hint.warn, batt.mid, heat.cool, sensors)", "#aa5500"), + (3, "brown/orange (hint.warn, batt.mid, heat.cool, the sensor mark)", "#aa5500"), (4, "blue (hint.accent, bluetooth bg)", "#0000aa"), - (5, "purple (repeater names)", "#aa00aa"), - (6, "cyan (room names, hint.brand)", "#00aaaa"), + (5, "purple (the repeater mark)", "#aa00aa"), + (6, "cyan (hint.brand)", "#00aaaa"), (7, "light grey (default text, heat.cold)", "#aaaaaa"), (8, "dark grey (muted, faint, track)", "#555555"), - (9, "bright red (err)", "#ff5555"), - (10, "bright green (ok)", "#55ff55"), - (11, "bright yellow (warn, heat.warm)", "#ffff55"), - (12, "bright blue (accent)", "#5555ff"), - (13, "bright pink (client names — the map's pink, for free)", "#ff55ff"), - (14, "bright cyan (brand)", "#55ffff"), - (15, "white (you, heat.hot)", "#ffffff"), + (9, "bright red (err; node hue 0°)", "#ff5555"), + (10, "bright green (ok; node hue 120°)", "#55ff55"), + (11, "bright yellow (warn, heat.warm; node hue 60°)", "#ffff55"), + (12, "bright blue (accent; node hue 240°)", "#5555ff"), + (13, "bright pink (the node mark — the map's pink, for free; node hue 300°)", "#ff55ff"), + (14, "bright cyan (brand; node hue 180°)", "#55ffff"), + (15, "white (you, heat.hot, the room mark)", "#ffffff"), ) #: The custom 16-slot remap P3 originally shipped (tailwind-family RGBs programmed via @@ -232,7 +233,7 @@ MESH_THEME_16 = Theme( "batt.dim": "color(8)", "type.node": "color(13)", "type.repeater": "color(5)", - "type.room": "color(6)", + "type.room": "color(15)", "type.sensor": "color(3)", "heat.hot": "bold color(15)", "heat.warm": "color(11)", @@ -253,6 +254,43 @@ def active_theme() -> Theme: return _ACTIVE_THEME +def mark_rgb(colour: str) -> tuple[int, int, int]: + """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.*``). + + 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. + + Args: + colour: ``#rrggbb``, or a style name defined in both themes. + + Returns: + The ``(r, g, b)`` triple; mid-grey for a style with no colour of its own. + """ + cached = _STYLE_RGB.get(colour) + if cached is None: + if colour.startswith("#"): + cached = (int(colour[1:3], 16), int(colour[3:5], 16), int(colour[5:7], 16)) + else: + color = _ACTIVE_THEME.styles[colour].color + if color is None: + cached = (0xAA, 0xAA, 0xAA) + elif color.number is not None and color.number < len(_SLOT_RGBS): + cached = _SLOT_RGBS[color.number] + else: + triplet = color.get_truecolor() + cached = (triplet.red, triplet.green, triplet.blue) + _STYLE_RGB[colour] = cached + return cached + + def make_console() -> Console: """Create the application's themed Rich console. @@ -312,26 +350,47 @@ def hint_style(border_style: str) -> str: #: 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, rather than folding onto a handful -#: of palette entries. The app-wide rule is unchanged: a node's *name* is always coloured — -#: by this spectrum, 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. +#: 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. _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. +_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° +) + def node_style(key: str) -> str: """The stable spectrum hue a node's *key* selects — the hash-derived node colour. The node's first key byte is mapped straight onto the HSV colour wheel (``0x00`` red, - sweeping round to ``0xff``) at a fixed saturation/value (:data:`_NODE_HUE_SAT`, - :data:`_NODE_HUE_VAL`), so all 256 first-byte values give 256 distinct hues. Only the - first byte picks the colour, so any prefix of the key a surface happens to hold — a + 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. + hue. One node, one colour, however it was learned. + + 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. Args: key: The node's key/hash as hex (any length ≥ 1 byte, ``0x``/mixed-case tolerated). @@ -339,25 +398,42 @@ def node_style(key: str) -> str: Returns: A ``"bold #rrggbb"`` style string. """ + return _node_impl(key) + + +def _key_byte(key: str) -> int: + """The node's first key byte — the only slice any hue derives from.""" raw = key.lower().removeprefix("0x") try: - byte = int(raw[:2], 16) + return int(raw[:2], 16) except ValueError: # not hex — fall back to the character sum so *something* stable shows - byte = sum(map(ord, raw)) % 256 - r, g, b = colorsys.hsv_to_rgb(byte / 256, _NODE_HUE_SAT, _NODE_HUE_VAL) + 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``.""" + 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`). + + 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). + """ + sector = round(_key_byte(key) / 256 * len(_NODE_SLOT_HEXES)) % len(_NODE_SLOT_HEXES) + return f"bold {_NODE_SLOT_HEXES[sector]}" + + def name_style(name: str, key: Optional[str] = None) -> str: """The stable colour a node or sender name is drawn in — keyed on the node's key. - On the regular platform the hue is :func:`node_style`'s hash-derived spectrum, so a - rename keeps the colour and every surface that knows the key agrees. On PicoCalc - (``name_colour="type"``) the 16-slot palette can't afford a hue spectrum on top of - the semantic colours, so the name takes its node's *type* colour instead - (``type.node``/``type.repeater``/``type.room``/``type.sensor``), looked up in the - :mod:`~meshterm.core.nodetypes` registry the reception layer feeds. The dispatch is - bound at platform-switch time — this wrapper stays importable by name everywhere. + 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`). Args: name: The display name (unused for the hue; kept so every call site reads @@ -371,27 +447,7 @@ def name_style(name: str, key: Optional[str] = None) -> str: 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. """ - return _name_impl(name, key) - - -def _name_style_by_key(name: str, key: Optional[str] = None) -> str: - """Regular-platform name colouring: the hash-derived spectrum (``muted`` keyless).""" - if key: - return node_style(key) - return "muted" - - -def _name_style_by_type(name: str, key: Optional[str] = None) -> str: - """PicoCalc name colouring: the node's registered *type* picks a palette colour. - - An unknown type — never heard with one, or no key at all — stays ``muted``: colour - remains reserved for identities we actually know something about. A first-byte - prefix collision types by whichever node registered last (colour is a hint). - """ - if not key: - return "muted" - node_type = node_type_name(key) - return f"type.{node_type}" if node_type else "muted" + return node_style(key) if key else "muted" # -- the compact icon language (PicoCalc) --------------------------------------------- @@ -699,19 +755,24 @@ def snr_style(snr: float | None) -> str: # -- platform binding ------------------------------------------------------------------ _ACTIVE_THEME: Theme = MESH_THEME -_name_impl: Callable[[str, Optional[str]], str] = _name_style_by_key +_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). +_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).""" - global _ACTIVE_THEME, _name_impl, _glyph_impl, _fold_impl, _FOLD_TABLE + global _ACTIVE_THEME, _node_impl, _glyph_impl, _fold_impl, _FOLD_TABLE _ACTIVE_THEME = MESH_THEME if platform.truecolor else MESH_THEME_16 - _name_impl = _name_style_by_key if platform.name_colour == "key" else _name_style_by_type + _node_impl = _node_style_spectrum if platform.truecolor else _node_style_quantized _glyph_impl = _glyph_identity if platform.emoji else _glyph_compact _fold_impl = _fold_to_font if platform.ascii_fold 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. diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index 46194be..57d8b93 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -52,7 +52,7 @@ from .marks import ( parse_hex, ) from .pathline import PathLine, path_line -from .theme import glyph, name_style, node_style, snr_style +from .theme import glyph, mark_rgb, name_style, node_style, snr_style if TYPE_CHECKING: from ..core.discovery import DiscoveredDevice @@ -770,28 +770,31 @@ def stats_panel( # ``●`` 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. -_ROOM_COLOR = "#ffffff" -_SENSOR_COLOR = "#fb923c" +# 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. _NODE_GLYPHS: dict[int, tuple[str, str]] = { - NODE_TYPE_REPEATER: (REPEATER_MARK[0], REPEATER_MARK[1]), - NODE_TYPE_ROOM: ("■", _ROOM_COLOR), - NODE_TYPE_SENSOR: ("◉", _SENSOR_COLOR), - NODE_TYPE_CHAT: (NODE_MARK[0], NODE_MARK[1]), + NODE_TYPE_REPEATER: (REPEATER_MARK[0], "type.repeater"), + NODE_TYPE_ROOM: ("■", "type.room"), + NODE_TYPE_SENSOR: ("◉", "type.sensor"), + NODE_TYPE_CHAT: (NODE_MARK[0], "type.node"), } -_DEFAULT_GLYPH: tuple[str, str] = (NODE_MARK[0], NODE_MARK[1]) +_DEFAULT_GLYPH: tuple[str, str] = (NODE_MARK[0], "type.node") def node_marker(node_type: Optional[int]) -> tuple[str, RGB]: - """The map-palette glyph and truecolour for a node type, as a ``(glyph, rgb)`` pair. + """The map-palette glyph and colour 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. An unknown type falls - back to the plain node mark. + 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. """ - glyph, color = _NODE_GLYPHS.get(node_type or -1, _DEFAULT_GLYPH) - return glyph, parse_hex(color) + glyph, style = _NODE_GLYPHS.get(node_type or -1, _DEFAULT_GLYPH) + return glyph, mark_rgb(style) def self_marker() -> tuple[str, RGB]: diff --git a/tests/test_platforms.py b/tests/test_platforms.py index 718b3c0..a237f0c 100644 --- a/tests/test_platforms.py +++ b/tests/test_platforms.py @@ -29,7 +29,6 @@ def test_picocalc_is_the_narrower_plainer_flavour() -> None: assert PICOCALC.width_reclaim is False # a phantom column would tear the exact-width frame assert PICOCALC.emoji is False assert PICOCALC.truecolor is False - assert PICOCALC.name_colour == "type" def test_get_platform_defaults_to_regular() -> None: diff --git a/tests/test_theme16.py b/tests/test_theme16.py index dde6fb0..846a923 100644 --- a/tests/test_theme16.py +++ b/tests/test_theme16.py @@ -16,8 +16,6 @@ from pathlib import Path from rich.cells import cell_len from rich.default_styles import DEFAULT_STYLES -from meshterm.core import nodetypes -from meshterm.core.nodetypes import node_type_name, register_node_type from meshterm.platforms import PICOCALC, REGULAR, set_platform from meshterm.ui import theme from meshterm.ui.fontset import FONT_CODEPOINTS @@ -58,7 +56,7 @@ def test_theme16_bold_never_jumps_a_dim_slot_to_an_unrelated_bright_one() -> Non """The VT draws bold as brightness: bold on slots 0-7 lands on N+8. Slots 5 and 6 carry semantics whose bright partners mean something *else* here - (5 purple = repeater names vs 13 pink = client names; 6 cyan = rooms/hint.brand vs + (5 purple = the repeater mark vs 13 pink = the node mark; 6 cyan = hint.brand vs 14 = brand), so no style may combine bold with them. """ for name, style in _our_styles(MESH_THEME_16).items(): @@ -174,24 +172,40 @@ def test_fold_drops_zero_width_machinery() -> None: # -- name colouring ------------------------------------------------------------------- -def test_name_style_by_type_reads_the_registry(monkeypatch) -> None: - monkeypatch.setattr(nodetypes, "_TYPES_BY_PREFIX", {"3d": "repeater"}) +def test_names_colour_by_key_on_both_platforms() -> None: + """One rule everywhere: the key picks the hue, and only its first byte does.""" + for platform in (REGULAR, PICOCALC): + set_platform(platform) + hue = name_style("YUL-Cartierville", "3d63c6429436") + assert hue.startswith("bold #"), platform.name + # Any prefix of the key agrees, a rename does not move the colour, and a sender + # we could not place stays muted — colour is reserved for keyed identities. + assert name_style("YUL-Cartierville", "3d") == hue + assert name_style("renamed", "3d63c6429436") == hue + assert name_style("nameless", None) == "muted" + + +def test_picocalc_node_hues_land_on_their_own_palette_slots() -> None: + """The quantized wheel spends only the six chromatic bright slots, evenly. + + Each returned hex is a slot's own RGB, so every downsample on the way out — Rich's, + and the fold's — lands on that exact slot instead of guessing a neighbour. + """ set_platform(PICOCALC) - assert name_style("YUL-Cartierville", "3d63c6429436") == "type.repeater" - assert name_style("stranger", "beef") == "muted" # never registered → muted - assert name_style("nameless", None) == "muted" - set_platform(REGULAR) - assert name_style("YUL-Cartierville", "3d63c6429436").startswith("bold #") + slots = {hex_: slot for slot, _, hex_ in theme._VT_SLOTS} + landed = [name_style("n", f"{byte:02x}").removeprefix("bold ") for byte in range(256)] + assert set(landed) == set(theme._NODE_SLOT_HEXES) + assert {slots[hex_] for hex_ in landed} == {9, 10, 11, 12, 13, 14} + assert min(landed.count(h) for h in set(landed)) >= 256 // 8 # no starved sector -def test_type_registry_round_trip() -> None: - register_node_type("A1B2C3", 2) - assert node_type_name("a1") == "repeater" - assert node_type_name("a1ffff") == "repeater" # any prefix of the key agrees - register_node_type("a1b2c3", None) # no type carried → no clobber - assert node_type_name("a1") == "repeater" - assert node_type_name(None) is None - assert node_type_name("f") is None # too short for a first byte +def test_node_type_marks_stay_distinct_on_the_console() -> None: + """Each type mark owns a slot — a naive downsample would grey the repeater's violet.""" + set_platform(PICOCALC) + marks = ("type.node", "type.repeater", "type.room", "type.sensor") + rgbs = [theme.mark_rgb(name) for name in marks] + assert len(set(rgbs)) == len(marks) + assert theme.mark_rgb("type.repeater") != theme.mark_rgb("muted") # -- the font build script stays mirrored ---------------------------------------------