diff --git a/ansilogo.txt b/ansilogo.txt new file mode 100644 index 0000000..97933de --- /dev/null +++ b/ansilogo.txt @@ -0,0 +1,5 @@ +███ ███ ███████ ███████ ██ ██ ████████ ███████ ██████ ███ ███ +████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ████ +██ ████ ██ █████ ███████ ███████ ██ █████ ██████ ██ ████ ██ +██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ +██ ██ ███████ ███████ ██ ██ ██ ███████ ██ ██ ██ ██ \ No newline at end of file diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index a731a58..758390c 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -1,39 +1,57 @@ -"""Interactive companion-device picker, rendered in the full-screen session. +"""Interactive companion-device picker: the startup splash shown before the menu. -Shown once at the start of the interactive menu when no port was given explicitly. It lists -the discovered devices, marks the remembered "last known good" one, and preselects it as the -default. The chosen device becomes the session's active device; it is persisted as the new -default once it actually connects. +Shown once at the start of the interactive menu when no port was given explicitly. Unlike the +in-menu prompts, it is drawn as a chromeless splash — the MeshTerm wordmark centered above a +content-sized box, with no header/footer status bars. It lists the discovered devices in +aligned columns, marks the remembered "last known good" one, and preselects it as the default. +The chosen device becomes the session's active device; it is persisted as the new default once +it actually connects. """ from __future__ import annotations from typing import TYPE_CHECKING, Optional +from rich.cells import cell_len from rich.text import Text from ..core.device_store import RememberedDevice from ..core.discovery import DiscoveredDevice -from .tui import Choice +from .logo import LOGO +from .tui import Choice, Separator if TYPE_CHECKING: from .surface import Ui -#: Trailing hint per discovery confidence tier (see :attr:`DiscoveredDevice.confidence`). +#: Trailing tag per discovery confidence tier (see :attr:`DiscoveredDevice.confidence`). #: A bare serial bridge is only a weak hint, so it is not billed as a LoRa device. -_QUALIFIER: dict[str, str] = { - "board": " · LoRa device", - "bridge": " · serial adapter", +_TAG: dict[str, str] = { + "board": "· LoRa device", + "bridge": "· serial adapter", "unknown": "", } +def _pad(text: str, width: int) -> str: + """Right-pad ``text`` with spaces to ``width`` display cells (wide-char aware).""" + return text + " " * max(0, width - cell_len(text)) + + +def _hardware_name(device: DiscoveredDevice) -> str: + """The device's product name without its trailing ``(port)`` (that is its own column).""" + name = device.product or device.description or device.vendor_label or "Serial device" + suffix = f"({device.port})" + if name.endswith(suffix): + name = name[: -len(suffix)].rstrip() + return name + + async def prompt_device( ui: "Ui", devices: list[DiscoveredDevice], remembered: Optional[RememberedDevice], ) -> Optional[DiscoveredDevice]: - """Prompt the user to choose a companion device. + """Prompt the user to choose a companion device on the startup splash. Args: ui: The interactive UI surface used to render the picker. @@ -41,32 +59,63 @@ async def prompt_device( remembered: The remembered default, if any, used to mark and preselect a row. Returns: - The chosen :class:`DiscoveredDevice`, or ``None`` if the user cancelled the picker + The chosen :class:`DiscoveredDevice`, or ``None`` if the user skipped the picker (e.g. pressed Esc to run against ``--mock`` / configure later). """ if not devices: - await ui.view( + await ui.notify_startup( Text.from_markup( "[warn]No serial devices detected.[/warn]\n" "Plug one in, pass [accent]--port[/accent], or run with [accent]--mock[/accent]." ), title="Select a companion device", + banner=LOGO, ) return None + # The row for each device leads with its display name (the remembered node's name when + # known, else the hardware name); columns are padded to a shared width so they align. + def _name(device: DiscoveredDevice) -> str: + if remembered is not None and remembered.matches(device) and remembered.node_name: + return remembered.node_name + return _hardware_name(device) + + name_w = max(cell_len(_name(d)) for d in devices) if devices else 0 + name_w = max(name_w, len("DEVICE")) + port_w = max((cell_len(d.port) for d in devices), default=0) + port_w = max(port_w, len("PORT")) + vendor_w = max((cell_len(d.vendor_label) for d in devices), default=0) + vendor_w = max(vendor_w, len("VENDOR")) + + # A muted, aligned header. The leading spaces mirror the row pointer (2) and the star + # column (2) so the labels sit above their columns. + header = Separator( + " " + + _pad("DEVICE", name_w) + + " " + _pad("PORT", port_w) + + " " + "VENDOR" + ) + default: Optional[DiscoveredDevice] = None - items: list = [] + items: list = [header] for device in devices: is_remembered = remembered is not None and remembered.matches(device) - star = "★ " if is_remembered else " " - # Lead with the remembered node name so a known radio is recognizable at a glance. - name = f"{remembered.node_name} — " if is_remembered and remembered.node_name else "" - vendor = f" [{device.vendor_label}]" if device.vendor_label else "" - items.append( - Choice(title=f"{star}{name}{device.label}{vendor}{_QUALIFIER[device.confidence]}", - value=device) - ) + row = Text() + row.append("★" if is_remembered else " ", style="warn" if is_remembered else "") + row.append(" ") + row.append(_pad(_name(device), name_w)) + row.append(" ") + row.append(_pad(device.port, port_w), style="muted") + row.append(" ") + row.append(_pad(device.vendor_label, vendor_w), style="muted") + tag = _TAG[device.confidence] + if tag: + row.append(" ") + row.append(tag, style="muted") + items.append(Choice(title=row, value=device)) if is_remembered: default = device - return await ui.select("Select a companion device:", items, default=default) + return await ui.select_startup( + "Select a companion device", items, default=default, banner=LOGO + ) diff --git a/meshterm/ui/logo.py b/meshterm/ui/logo.py new file mode 100644 index 0000000..955dc19 --- /dev/null +++ b/meshterm/ui/logo.py @@ -0,0 +1,16 @@ +"""The MeshTerm wordmark, as block-glyph ASCII art for the startup screen. + +Kept as a code constant (rather than a packaged data file) so it is always available at +runtime regardless of how the package is installed. +""" + +from __future__ import annotations + +#: The wordmark, one string per row. Rows are equal width, so the block centers cleanly. +LOGO: list[str] = [ + '███ ███ ███████ ███████ ██ ██ ████████ ███████ ██████ ███ ███', + '████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ████', + '██ ████ ██ █████ ███████ ███████ ██ █████ ██████ ██ ████ ██', + '██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██', + '██ ██ ███████ ███████ ██ ██ ██ ███████ ██ ██ ██ ██', +] diff --git a/meshterm/ui/surface.py b/meshterm/ui/surface.py index 9ca1d9f..b2412e2 100644 --- a/meshterm/ui/surface.py +++ b/meshterm/ui/surface.py @@ -57,6 +57,18 @@ class Ui: """Prompt the user to choose one item; return its value or ``None`` if cancelled.""" raise NotImplementedError + async def select_startup( + self, title: str, items: list, *, default: Any = None, banner: Any = None + ) -> Any: + """Choose one item on a chromeless startup splash; ``None`` if skipped.""" + raise NotImplementedError + + async def notify_startup( + self, renderable: RenderableType, *, title: str = "", banner: Any = None + ) -> None: + """Show a message on a chromeless startup splash until the user dismisses it.""" + raise NotImplementedError + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Let the user rearrange rows with the arrows; return the new order of row indices.""" raise NotImplementedError @@ -133,6 +145,18 @@ class PlainUi(Ui): """Unsupported in scripted CLI mode.""" raise self._no_prompt() + async def select_startup( + self, title: str, items: list, *, default: Any = None, banner: Any = None + ) -> Any: + """Unsupported in scripted CLI mode.""" + raise self._no_prompt() + + async def notify_startup( + self, renderable: RenderableType, *, title: str = "", banner: Any = None + ) -> None: + """Unsupported in scripted CLI mode.""" + raise self._no_prompt() + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Unsupported in scripted CLI mode.""" raise self._no_prompt() @@ -247,6 +271,20 @@ class TuiUi(Ui): """Delegate to the session's select screen.""" return await self.session.select(title, items, default=default) + async def select_startup( + self, title: str, items: list, *, default: Any = None, banner: Any = None + ) -> Any: + """Delegate to the session's chromeless startup select splash.""" + return await self.session.select_startup( + title, items, default=default, banner=banner + ) + + async def notify_startup( + self, renderable: RenderableType, *, title: str = "", banner: Any = None + ) -> None: + """Delegate to the session's chromeless startup message splash.""" + await self.session.notify_startup(renderable, title=title, banner=banner) + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Delegate to the session's reorder screen.""" return await self.session.reorder(title, labels) diff --git a/meshterm/ui/tui/frame.py b/meshterm/ui/tui/frame.py index 08e1808..9955a22 100644 --- a/meshterm/ui/tui/frame.py +++ b/meshterm/ui/tui/frame.py @@ -7,11 +7,14 @@ header and footer so the whole view fits the terminal exactly (never overflowing from __future__ import annotations +from typing import Sequence + +from rich.cells import cell_len from rich.console import Group, RenderableType from rich.panel import Panel from rich.text import Text -from .render import render_lines +from .render import render_lines, render_to_ansi from .screen import Screen, ScrollScreen @@ -111,6 +114,84 @@ def compose_base( return "\n".join(lines) +def _ansi_width(line: str) -> int: + """Return the display width of an ANSI line, ignoring its trailing padding.""" + return cell_len(Text.from_ansi(line).plain.rstrip()) + + +def _center(lines: list[str], cols: int) -> list[str]: + """Left-pad each ANSI line so the block is horizontally centered within ``cols``.""" + out: list[str] = [] + for line in lines: + pad = max(0, (cols - cell_len(Text.from_ansi(line).plain)) // 2) + out.append(" " * pad + line) + return out + + +def _banner_lines(banner: Sequence[str], cols: int) -> list[str]: + """Render the wordmark rows in the brand colour, centered within ``cols``.""" + if not banner: + return [] + width = max(cell_len(row) for row in banner) + lines = [render_to_ansi(Text(row, style="brand"), width) for row in banner] + return _center(lines, cols) + + +def compose_startup(screen: Screen, cols: int, rows: int) -> str: + """Compose a chromeless splash: a centered wordmark above a content-sized panel. + + Unlike :func:`compose_base`, this draws no header or footer status bars and does not + stretch the panel across the terminal — the box is sized to its own content (the device + list) and the whole block is centered on screen. Used for the startup device picker. + + Args: + screen: The chromeless base screen (its ``banner`` supplies the wordmark). + cols: Terminal width. + rows: Terminal height. + + Returns: + An ANSI string of exactly ``rows`` lines, each within ``cols`` columns. + """ + banner = _banner_lines(screen.banner or [], cols) + + # Size the box to its widest real row (probe at a generous width, then measure), never + # wider than the terminal and never narrower than the title/hint it must show. + probe = max(10, min(cols - 6, 100)) + measured = max((_ansi_width(line) for line in screen.render_body(probe)), default=10) + inner_w = max(measured, cell_len(screen.title), cell_len(screen.footer_hint)) + inner_w = max(10, min(inner_w, cols - 6)) + + # Leave room for the banner (and the blank line under it) plus the panel's own border. + reserved = len(banner) + (1 if banner else 0) + 2 + body_lines = screen.render_body(inner_w) + viewport = max(1, min(len(body_lines), rows - reserved)) + visible, more_above, more_below = _visible_slice(screen, body_lines, viewport) + + body = Text.from_ansi("\n".join(visible)) + subtitle = f"[muted]{screen.footer_hint}[/muted]" + if more_above or more_below: + arrow = ("↑" if more_above else " ") + ("↓" if more_below else " ") + subtitle = f"[muted]{arrow} · {screen.footer_hint}[/muted]" + panel = Panel( + body, + title=f"[accent]{screen.title}[/accent]" if screen.title else None, + subtitle=subtitle, + border_style="accent", + padding=(0, 1), + width=inner_w + 4, + ) + panel_lines = _center(render_lines(panel, inner_w + 4), cols) + + block = banner + ([""] if banner else []) + panel_lines + top = max(0, (rows - len(block)) // 2) + lines = [""] * top + block + if len(lines) > rows: + lines = lines[:rows] + else: + lines += [""] * (rows - len(lines)) + return "\n".join(lines) + + def compose_dialog(screen: Screen, cols: int, rows: int) -> str: """Compose a centered dialog panel for a floating screen, bounded to the terminal. diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index d1b810a..fee84b7 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -13,7 +13,7 @@ push/await/pop model behind ``await session.select(...)`` and friends. from __future__ import annotations import asyncio -from typing import Any, Optional +from typing import Any, Optional, Sequence from rich.console import RenderableType @@ -34,11 +34,18 @@ class Screen: future: Resolved with the screen's result (or :data:`CANCEL`) when it commits. floating: Whether the session should draw this screen as a centered dialog over the dimmed screen beneath it (deeper layers float; the base does not). + chrome: Whether, as the base screen, this layer is wrapped in the session's + persistent header/footer frame. A startup splash sets this ``False`` so the + session instead centers it under the :attr:`banner` with no status bars. + banner: Block-glyph art (one string per row) drawn, centered, above a chromeless + base screen. Ignored while ``chrome`` is ``True``. """ title: str = "" footer_hint: str = "Esc back" floating: bool = True + chrome: bool = True + banner: Optional[Sequence[str]] = None def __init__(self) -> None: """Initialize scroll state and the (later-assigned) result future.""" diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index 0801a03..46e5562 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -71,6 +71,7 @@ class SelectScreen(Screen): *, default: Any = None, footer_hint: str = "↑↓ move · type to filter · Enter select · Esc back", + filterable: bool = True, ) -> None: """Build a select screen. @@ -79,10 +80,13 @@ class SelectScreen(Screen): items: A list of :class:`Choice` and :class:`Separator` in display order. default: A choice value to pre-highlight, if present. footer_hint: Footer key hint. + filterable: Whether typing narrows the list. Off for short, fixed lists (e.g. + the startup device picker) where type-to-filter would only get in the way. """ super().__init__() self.title = title self.footer_hint = footer_hint + self._filterable = filterable self._items = items self._filter = "" # Index into the currently-selectable (filtered) choices. @@ -174,10 +178,10 @@ class SelectScreen(Screen): self.resolve(choices[self._index].value) elif action == "escape": super().handle("escape") - elif action == "backspace": + elif action == "backspace" and self._filterable: self._filter = self._filter[:-1] self._index = 0 - elif action == "text" and data.isprintable(): + elif action == "text" and self._filterable and data.isprintable(): self._filter += data self._index = 0 diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index a25953c..159dbd4 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -130,6 +130,43 @@ class TuiSession: result = await self.run_screen(SelectScreen(title, items, default=default)) return None if result is CANCEL else result + async def select_startup( + self, + title: str, + items: list, + *, + default: Any = None, + banner: Optional[Any] = None, + footer_hint: str = "↑↓ move · Enter select · Esc skip", + ) -> Any: + """Show a chromeless select splash (banner above a content-sized box). + + Like :meth:`select`, but drawn without the header/footer status bars and centered + under ``banner`` — the startup device picker's presentation. Type-to-filter is off: + the device list is short and fixed, so stray keys never narrow it. + """ + screen = SelectScreen( + title, items, default=default, footer_hint=footer_hint, filterable=False + ) + screen.chrome = False + screen.banner = banner + result = await self.run_screen(screen) + return None if result is CANCEL else result + + async def notify_startup( + self, + renderable: RenderableType, + *, + title: str = "", + banner: Optional[Any] = None, + footer_hint: str = "Enter continue", + ) -> None: + """Show a chromeless message splash (banner above a boxed renderable) until dismissed.""" + screen = ScrollScreen(renderable, title=title, footer_hint=footer_hint) + screen.chrome = False + screen.banner = banner + await self.run_screen(screen) + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Show a drag-with-arrows reorder screen; return the final order of row indices.""" result = await self.run_screen(ReorderScreen(title, labels)) @@ -290,6 +327,10 @@ class TuiSession: base = self._base_screen() if base is None: return ANSI("") + # A chromeless base (the startup splash) forgoes the header/footer bars and is + # centered under its banner instead of stretched across the terminal. + if not base.chrome: + return ANSI(frame.compose_startup(base, cols, rows)) footer = self.top.footer_hint if self.top else base.footer_hint return ANSI(frame.compose_base(self._header(), base, footer, cols, rows)) diff --git a/tests/test_tui.py b/tests/test_tui.py index 54c95df..f243bc7 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -104,6 +104,15 @@ def test_select_filter_narrows_and_hides_separators() -> None: assert _run(screen, "enter") == 1 +def test_select_non_filterable_ignores_typing() -> None: + """With filtering off, typed keys neither narrow the list nor add a filter line.""" + screen = SelectScreen("pick", [Choice("alpha", 1), Choice("beta", 2)], filterable=False) + screen.handle("text", "a") + screen.handle("backspace") + assert screen._filter == "" + assert len(screen._rows()) == 2 # nothing was filtered out + + def test_select_escape_cancels() -> None: """Esc resolves the sentinel rather than a value.""" assert _run(_menu(), "escape") is CANCEL @@ -177,6 +186,29 @@ def test_compose_dialog_is_bounded() -> None: assert out.count("\n") + 1 <= 20 +def test_compose_startup_is_chromeless_and_shows_banner() -> None: + """The startup splash fills the height, draws the banner, and omits header/footer bars.""" + screen = SelectScreen("pick", [Choice("alpha", 1), Choice("beta", 2)]) + screen.chrome = False + screen.banner = ["LOGO-ROW-A", "LOGO-ROW-B"] + out = frame.compose_startup(screen, 80, 24) + assert out.count("\n") + 1 == 24 # fills the terminal height exactly + plain = Text.from_ansi(out).plain + assert "LOGO-ROW-A" in plain and "LOGO-ROW-B" in plain # banner is drawn + assert "pick" in plain # the box keeps its title + # The box is content-sized, not full width: no rendered line spans the whole terminal. + assert all(len(line.rstrip()) < 80 for line in plain.split("\n")) + + +def test_compose_startup_box_is_horizontally_centered() -> None: + """The content-sized box is centered, so its rows carry a leading left margin.""" + screen = SelectScreen("pick", [Choice("a", 1)]) + screen.chrome = False + lines = Text.from_ansi(frame.compose_startup(screen, 80, 20)).plain.split("\n") + box_lines = [ln for ln in lines if ln.strip()] + assert box_lines and all(ln.startswith(" ") for ln in box_lines) # centered inset + + # --- prompts ----------------------------------------------------------------- @@ -238,6 +270,36 @@ def test_autocomplete_accepts_free_text() -> None: assert _run(screen, "enter") == "3d" +# --- device picker ----------------------------------------------------------- + + +def test_device_picker_builds_aligned_columns() -> None: + """The picker lays devices out in columns that line up across rows of differing widths.""" + from meshterm.core.discovery import DiscoveredDevice + from meshterm.ui.device_picker import prompt_device + + devices = [ + DiscoveredDevice(port="COM5", product="Wio SX1262", vid=0x2886), + DiscoveredDevice(port="/dev/ttyUSB0", product="FT232R USB UART", vid=0x0403), + ] + captured: dict = {} + + class _Ui: + async def select_startup(self, title, items, *, default=None, banner=None): + captured["items"] = items + captured["banner"] = banner + return None + + asyncio.run(prompt_device(_Ui(), devices, None)) + # The banner (wordmark) is passed through so the splash can draw it. + assert captured["banner"] and any("█" in row for row in captured["banner"]) + # Each device row's port sits at the same column, proving the name column is padded. + rows = [it.label.plain for it in captured["items"] if isinstance(it, Choice)] + assert len(rows) == 2 + assert all(port in row for port, row in zip(("COM5", "/dev/ttyUSB0"), rows)) + assert rows[0].index("COM5") == rows[1].index("/dev/ttyUSB0") + + # --- progress ----------------------------------------------------------------