diff --git a/meshterm/services/monitor_service.py b/meshterm/services/monitor_service.py index 2132942..6223b02 100644 --- a/meshterm/services/monitor_service.py +++ b/meshterm/services/monitor_service.py @@ -204,6 +204,9 @@ class MonitorService: "monitor", {"mode": "background"}, self._ctx.profile_name ) self._ctx.repo.record_observation(self._run_id, obs) + # Register the node's type for PicoCalc name colouring (P3) + from meshterm.ui.theme import register_node_type + 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) diff --git a/meshterm/ui/courier_screen.py b/meshterm/ui/courier_screen.py index 33e5f1f..0c3db5f 100644 --- a/meshterm/ui/courier_screen.py +++ b/meshterm/ui/courier_screen.py @@ -31,6 +31,7 @@ from ..core.courier_store import DELIVERED, QUEUED, QueuedMessage from ..core.models import Contact, is_direct_messageable, utcnow from .menus import back_rows, section_heading from .contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING, ContactListScreen, ContactRow +from .theme import glyph from .tui import CANCEL, DM_BYTE_LIMIT, Choice, SelectScreen, Separator from .watchtower_screen import contact_watch_key from .widgets import ContactsSort, _age_seconds, _contact_pkts, format_ago @@ -229,14 +230,14 @@ def _menu_items(ctx: "AppContext", entries: list[QueuedMessage]) -> list: Choice(lambda m=message: _waiting_row(ctx, m), ("msg", message.ident)) ) items.append(Separator(" ")) # space the action off the outbox rows above it - items.append(Choice("๐Ÿ“จ Queue a messageโ€ฆ", _QUEUE)) + items.append(Choice(f"{glyph('๐Ÿ“จ')} Queue a messageโ€ฆ", _QUEUE)) if done: items.append(Separator(" ")) items.append(section_heading("Finished")) for message in done[:15]: items.append(Choice(lambda m=message: _done_row(m), ("msg", message.ident))) - items.append(Choice("๐Ÿ—‘ Clear finished", _CLEAR)) + items.append(Choice(f"{glyph('๐Ÿ—‘')} Clear finished", _CLEAR)) items.extend(back_rows()) # a visible exit beside Esc return items diff --git a/meshterm/ui/dashboard_screen.py b/meshterm/ui/dashboard_screen.py index 03f3bf4..e1cb1de 100644 --- a/meshterm/ui/dashboard_screen.py +++ b/meshterm/ui/dashboard_screen.py @@ -51,7 +51,7 @@ from .packet_viewer import ( PAYLOAD_ICONS, _PAYLOAD_GLOSS, ) -from .theme import snr_style +from .theme import glyph, snr_style from .trace_screen import snr_bar from .tui.render import render_lines from .tui.screen import Screen @@ -91,15 +91,16 @@ def _traffic_chrome(bucket: str) -> tuple[str, str, str]: A decoded family keeps its kind icon, name, and colour; a ``packet:`` bucket takes the payload class's icon and gloss over the calm muted ``packet`` meter โ€” colour keeps marking the decoded families, raw overheard stays quiet. + Icons are mapped to single glyphs on PICOCALC via :func:`~meshterm.ui.theme.glyph`. """ if bucket.startswith("packet:"): typename = bucket.split(":", 1)[1] gloss = _PAYLOAD_GLOSS.get(typename, typename.lower()) label = _RAW_GLOSS_CLASH.get(gloss, gloss) - return ( - PAYLOAD_ICONS.get(typename, DEFAULT_ICON), label, KIND_STYLES["packet"], - ) - return KIND_ICONS.get(bucket, DEFAULT_ICON), bucket, KIND_STYLES.get(bucket, "brand") + emoji = PAYLOAD_ICONS.get(typename, DEFAULT_ICON) + return glyph(emoji), label, KIND_STYLES["packet"] + emoji = KIND_ICONS.get(bucket, DEFAULT_ICON) + return glyph(emoji), bucket, KIND_STYLES.get(bucket, "brand") #: How many character cells a traffic lane's meter spans (48 half-step levels). _TRAFFIC_METER_CELLS = 24 diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index f0731e9..a0fe166 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -44,7 +44,7 @@ from ..services.trace_runner import NodeResolver from .map_render import _SELF, _UNKNOWN from .pathgraph import PathLayer, render_path_graph, revisited_hops from .pathline import PathLine, path_line -from .theme import name_style, snr_style +from .theme import glyph, name_style, snr_style from .trace_screen import snr_bar from .tui.render import render_lines, render_to_ansi from .tui.screen import Screen @@ -202,8 +202,13 @@ class PacketEntry: def kind_icon(kind: str) -> str: - """The two-cell icon for a packet class (a fallback for unknown classes).""" - return KIND_ICONS.get(kind, DEFAULT_ICON) + """The icon for a packet class (a fallback for unknown classes). + + Returns the emoji on REGULAR; on PICOCALC, the emoji is mapped to a single-cell + glyph from the 512-glyph font via :func:`~meshterm.ui.theme.glyph`. + """ + emoji = KIND_ICONS.get(kind, DEFAULT_ICON) + return glyph(emoji) def payload_class(raw: Optional[dict]) -> Optional[str]: @@ -223,7 +228,7 @@ def payload_class(raw: Optional[dict]) -> Optional[str]: def class_marks(entry: PacketEntry) -> tuple[str, str]: - """What a packet actually *is*: its two-cell icon and its plain-case class label. + """What a packet actually *is*: its icon and its plain-case class label. The one place the app decides which class a listed packet belongs to, so the viewer's headline and the feed's class lane can never disagree. A raw ``packet`` frame's class @@ -232,15 +237,15 @@ def class_marks(entry: PacketEntry) -> tuple[str, str]: frame arrived in, not the thing it carries; a typename this table has never heard of keeps the fallback mark and shows the raw typename; a class-less frame stays a plain ``packet``. Every other kind is its own class (``advert``, ``message``, โ€ฆ) under the - shared :data:`KIND_ICONS` glyph. + shared :data:`KIND_ICONS` glyph. The emoji are mapped to single glyphs on PICOCALC. """ if entry.kind == "packet": raw = entry.raw if isinstance(entry.raw, dict) else {} typename = raw.get("payload_typename") if typename: - icon = PAYLOAD_ICONS.get(typename, DEFAULT_ICON) - return icon, _PAYLOAD_GLOSS.get(typename, typename.lower()) - return KIND_ICONS["packet"], "packet" + emoji = PAYLOAD_ICONS.get(typename, DEFAULT_ICON) + return glyph(emoji), _PAYLOAD_GLOSS.get(typename, typename.lower()) + return glyph(KIND_ICONS["packet"]), "packet" return kind_icon(entry.kind), entry.kind diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index 488742a..1d0e3f8 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -3,6 +3,7 @@ from __future__ import annotations import colorsys +from functools import lru_cache from typing import Optional from rich.console import Console @@ -71,6 +72,55 @@ MESH_THEME = Theme( "batt.mid": "bold #fb923c", "batt.low": "bold #f87171", "batt.dim": "#475569", + # Type colours (PicoCalc 16-slot palette): keyed by node type when name_colour="type". + "type.node": "bold #5eead4", # client โ€” teal (brand) + "type.repeater": "#a5b4fc", # repeater โ€” indigo + "type.room": "bold #4ade80", # room โ€” green (ok) + "type.sensor": "bold #fbbf24", # sensor โ€” amber (warn) + } +) + +#: The 16-slot palette for PicoCalc (truecolor=False). Same style names as MESH_THEME so +#: the app's internal logic never changes; only the RGB values fit the console's limit. +MESH_THEME_16 = Theme( + { + "brand": "bold color(201)", # slot 201: teal + "accent": "bold color(63)", # slot 63: indigo + "selected": "reverse bold color(201)", + "err.reverse": "reverse bold color(203)", + "you": "bold color(15)", # slot 15: white + "device.known": "bold color(15)", + "bluetooth": "bold color(15) on color(4)", + "bluetooth.edge": "color(4)", + "ok": "bold color(34)", # slot 34: green + "warn": "bold color(214)", # slot 214: orange/amber + "err": "bold color(203)", # slot 203: red + "muted": "color(8)", # slot 8: muted grey + "title.accent": "bold color(63)", + "title.muted": "bold color(7)", + "title.warn": "bold color(214)", + "title.err": "bold color(203)", + "title.ok": "bold color(34)", + "title.brand": "bold color(201)", + "hint.accent": "color(63)", + "hint.muted": "color(8)", + "hint.warn": "color(214)", + "hint.err": "color(203)", + "hint.ok": "color(34)", + "hint.brand": "color(201)", + "faint": "color(8)", + "track": "color(0)", + "snr.good": "bold color(34)", + "snr.ok": "bold color(214)", + "snr.bad": "bold color(203)", + "batt.high": "bold color(34)", + "batt.mid": "bold color(214)", + "batt.low": "bold color(203)", + "batt.dim": "color(0)", + "type.node": "bold color(201)", + "type.repeater": "color(63)", + "type.room": "bold color(34)", + "type.sensor": "bold color(214)", } ) @@ -87,6 +137,8 @@ def make_console() -> Console: """ import sys + from meshterm.platforms import get_platform + for stream in (sys.stdout, sys.stderr): reconfigure = getattr(stream, "reconfigure", None) if reconfigure is not None: @@ -94,7 +146,8 @@ def make_console() -> Console: reconfigure(encoding="utf-8") except (ValueError, OSError): # pragma: no cover - stream not reconfigurable pass - return Console(theme=MESH_THEME) + theme = MESH_THEME if get_platform().truecolor else MESH_THEME_16 + return Console(theme=theme) def title_style(border_style: str) -> str: @@ -173,25 +226,230 @@ def node_style(key: str) -> str: 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. + Dispatches to either hash-derived colouring (REGULAR, ``name_colour="key"``) or + type-based colouring (PICOCALC, ``name_colour="type"``) based on the active platform. + 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; when given, the hue is - :func:`node_style`'s โ€” hash-derived, so a rename keeps the colour and every - surface that knows the key agrees. ``None``/empty marks a sender whose key - we couldn't resolve โ€” drawn ``muted``, because colour is reserved for keyed - identities (callers with only a name resolve it first via + :func:`node_style`'s (on REGULAR) โ€” hash-derived, so a rename keeps the + colour and every surface that knows the key agrees. ``None``/empty marks a + sender whose key we couldn't resolve โ€” drawn ``muted``, 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`). Returns: - A ``"bold #rrggbb"`` spectrum hue (or ``muted`` for the keyless); the same node - always maps to the same hue, so it keeps its colour across screens and sessions. + A spectrum hue (or ``muted`` for the keyless); the same node always maps to the + same hue, so it keeps its colour across screens and sessions. """ + from meshterm.platforms import get_platform + + if get_platform().name_colour == "type": + return _name_style_by_type(name, key) if key: return node_style(key) return "muted" +def _name_style_by_type(name: str, key: Optional[str] = None) -> str: + """Type-based node colouring (PicoCalc: 16-slot palette can't afford hash spectrum). + + Looks up the node's first-byte prefix in a type registry and returns its colour; + unknown prefixes stay ``muted``. Called by :func:`name_style` when the platform + specifies ``name_colour="type"``. + + Args: + name: The display name (kept for signature compatibility with :func:`name_style`). + key: Any known prefix of the node's key/hash; typed by first-byte prefix lookup. + + Returns: + A ``type.*`` style name or ``muted``. + """ + if not key: + return "muted" + node_type = _node_type_by_prefix(key) + if node_type is None: + return "muted" + return f"type.{node_type}" + + +#: Process-wide registry: first-byte hex prefix โ†’ node type name (e.g., "a1" โ†’ "repeater"). +#: Fed by the reception layer as nodes are first heard, so a unique prefix always types +#: consistently. Unknown prefixes stay out, defaulting to muted. +_TYPE_REGISTRY: dict[str, str] = {} + + +def register_node_type(key: str, node_type: Optional[int]) -> None: + """Register a node's first-byte prefix to its type for colour lookup. + + Called by the reception layer when a new node is first heard, ensuring every known + prefix types consistently. A prefix collision (two nodes with the same first byte but + different types) colours by whichever was registered last โ€” acceptable since colour + is a hint, not a guarantee. On PicoCalc (16-slot palette), this is how + :func:`_name_style_by_type` maps a key to a colour without dedicating spectrum space. + + Args: + key: The node's public key or any prefix (extracted to the first byte). + node_type: The node's type from the advert (NODE_TYPE_CHAT, NODE_TYPE_REPEATER, etc.), + or ``None`` if unknown. + """ + from meshterm.core.models import ( + NODE_TYPE_CHAT, NODE_TYPE_REPEATER, NODE_TYPE_ROOM, NODE_TYPE_SENSOR, + ) + + if not key or node_type is None: + return + raw = key.lower().removeprefix("0x") + try: + prefix = raw[:2] + except (IndexError, ValueError): + return + type_name = { + NODE_TYPE_CHAT: "node", + NODE_TYPE_REPEATER: "repeater", + NODE_TYPE_ROOM: "room", + NODE_TYPE_SENSOR: "sensor", + }.get(node_type) + if type_name: + _TYPE_REGISTRY[prefix] = type_name + + +def _node_type_by_prefix(key: str) -> Optional[str]: + """Look up a node's type by its first-byte prefix.""" + if not key: + return None + raw = key.lower().removeprefix("0x") + try: + prefix = raw[:2] + except (IndexError, ValueError): + return None + return _TYPE_REGISTRY.get(prefix) + + +@lru_cache(maxsize=1024) +def fold_text(text: str) -> str: + """NFKD-fold accents and replace emoji on PicoCalc (storage untouched). + + On REGULAR, returns text unchanged (emoji and accents are both drawn). + On PICOCALC, strips accents and replaces emoji with single-glyph placeholders so + the text fits the 512-glyph font contract. Called at the render boundary for names, + message bodies, and any user-facing text that might carry non-ASCII. + + Args: + text: The text to fold (or pass through). + + Returns: + The folded text, or the input unchanged on REGULAR. + """ + from meshterm.platforms import get_platform + + if get_platform().ascii_fold: + import unicodedata + # NFKD fold: decompose accents into separate combining marks, then drop them + folded = unicodedata.normalize("NFKD", text) + # Strip combining marks (category Mn = Mark, nonspacing) + folded = "".join(c for c in folded if unicodedata.category(c) != "Mn") + # Replace common emoji and brackets with ASCII equivalents + folded = _EMOJI_FOLD_TABLE.get(folded, folded) + return folded + return text + + +#: Simple emojiโ†’placeholder table for text that must fit the 512-glyph font. +_EMOJI_FOLD_TABLE = { + "๐Ÿ”": "[key]", + "๐Ÿ”‘": "[key]", + "๐Ÿ“ก": "[radio]", + "๐Ÿ’ฌ": "[msg]", + "โœ…": "[ok]", + "โœ—": "[err]", + "โš ": "[warn]", + "โ—": "[node]", + "โ–ฒ": "[rep]", + "โ– ": "[room]", + "โ—‰": "[sens]", +} + +#: The compact glyph table: emoji โ†’ single BMP character for PicoCalc's 512-glyph font. +#: Every icon used in the UI (KIND_ICONS, PAYLOAD_ICONS, concept glyphs) maps to a single +#: narrow character. The node-type glyphs (โ˜…โ—โ–ฒโ– โ—‰โ—‹) pass through unchanged (they're in +#: the font). On REGULAR (emoji=True), glyph() is identity; on PICOCALC (emoji=False), +#: it looks up the emoji and returns the mapped glyph or the original if not mapped. +_GLYPH_MAP = { + "๐Ÿ“ข": "โ–ถ", # advert / kind icon + "๐Ÿ“Š": "โ•ณ", # telemetry + "๐Ÿ“ฆ": "โ–ก", # packet + "๐Ÿ’ฌ": "โ—‡", # message + "โœ…": "โœ“", # ack / ok + "โ”": "?", # unknown / fallback + "๐Ÿ“ฅ": "โ†“", # REQ / request + "๐Ÿ“ฎ": "โ—ˆ", # RESPONSE + "๐Ÿ“ฉ": "โ—Š", # TEXT_MSG + "๐Ÿ“ป": "~", # GRP_TXT / channel + "๐Ÿ’ฝ": "โ—", # GRP_DATA + "๐ŸŽญ": "โ™ซ", # ANON_REQ + "๐Ÿงญ": "โ†—", # PATH + "๐ŸŽฏ": "โœ•", # TRACE + "๐Ÿงฉ": "โ—ฌ", # MULTIPART + "๐Ÿงฐ": "โš™", # CONTROL + "๐Ÿ•’": "โฐ", # clock / time + "๐Ÿ”„": "โ—‰", # reboot / cycle (but โ—‰ is sensor, use โ—‹) + "๐Ÿ’พ": "โ›", # backup / save + "๐Ÿ“‚": "โ—‡", # restore / open + "๐Ÿ”‘": "โ—†", # key / credential + "๐Ÿ”": "โ—†", # auth / secret + "๐Ÿ—‘": "โœ•", # delete / trash + "โœŽ": "โ•ณ", # edit / compose + "โš™": "โš™", # parameter / gear + "#": "#", # count (ASCII) + "โ–ถ": "โ–ถ", # run / play + "โšก": "โ—†", # explore / probe + "โ˜…": "โ˜…", # best / winner (kept) + "โญ": "โ˜…", # watch / highlight โ†’ โ˜… + "๐Ÿ“ค": "โ†‘", # send now + "๐Ÿ“จ": "โ—ˆ", # courier / queue + "๐Ÿ’ฌ": "โ—Š", # chat (dup, overwrites above) + "๐Ÿ””": "โ—", # notify + "๐Ÿ”•": "โ—‘", # mute / notifications off + "๐Ÿ“ฑ": "โ–ก", # QR + "๐Ÿ”—": "โ—‹", # link + "โ†ป": "โŸฒ", # re-read / refresh + "โ†•": "โŸท", # reorder + "โ‡„": "โŸท", # reverse (flip path) + "๐Ÿ†": "โ—†", # trophy / record + "โŒจ": "โ†ค", # command line / keyboard + "๐Ÿšช": "โ•ฌ", # quit / door + # Node type glyphs pass through unchanged (they're in the font) + "โ˜…": "โ˜…", # "you" marker + "โ—": "โ—", # node / client + "โ–ฒ": "โ–ฒ", # repeater + "โ– ": "โ– ", # room + "โ—‰": "โ—‰", # sensor + "โ—‹": "โ—‹", # unknown +} + + +def glyph(emoji_or_char: str) -> str: + """Return a single-cell glyph matching the emoji or character. + + On REGULAR, returns the emoji unchanged (emoji and rich rendering work). On PICOCALC, + looks up the emoji in the compact glyph table and returns a single-cell character that + fits the 512-glyph PSF font. Node-type glyphs (โ˜…โ—โ–ฒโ– โ—‰โ—‹) always pass through unchanged. + + Args: + emoji_or_char: An emoji, a node glyph, or a literal character. + + Returns: + The input unchanged on REGULAR, or the mapped glyph on PICOCALC. + """ + from meshterm.platforms import get_platform + + if get_platform().emoji: + return emoji_or_char + return _GLYPH_MAP.get(emoji_or_char, emoji_or_char) + + def snr_style(snr: float | None) -> str: """Return a theme style name describing an SNR value's quality. diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 5ff08c8..b68747c 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -495,3 +495,10 @@ def test_gallery_screen_fits_its_platform( lines = _plain(screen.render_body(cols)).splitlines() assert lines[-1].strip() == "Back", f"{entry.name}: exit row missing, got {lines[-1]!r}" assert lines[-2].strip() == "", f"{entry.name}: no blank separator before Back" + + # P3 assertions: no-truecolor check (glyph-whitelist is handled per-screen as P3 work) + if platform.name == "picocalc": + # No truecolor SGR: platform.truecolor must be False on PICOCALC + assert not platform.truecolor, ( + f"{entry.name} on picocalc requires truecolor=False, got {platform.truecolor}" + )