From 94f565e61fecfc849f8fb1baaeabff4cad573ce0 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 12 Jul 2026 17:23:41 -0400 Subject: [PATCH] Windowed lists everywhere the chrome should hold still The atlas's list-in-a-fixed-screen pattern graduates to a shared ListWindow (tui.screen): fit() settles the window, the marker rows, and the highlight clamp together, and remembers the PgUp/PgDn stride; the frame now records the viewport (or a dialog's budget) before render_body runs so screens can size their chrome to it. Adopters: the dashboard pins its charts and windows the feed; the trace screen pins route, aggregates, and actions over a windowed results block; the path composer pins the route preview over windowed suggestions (and gains PgUp/PgDn); the nodes table pins its title, column header, and legend around windowed rows. The composer's route preview and node rows also join THE path widget, dropping its hand-rolled Name (hash) renderer. Co-Authored-By: Claude Fable 5 --- meshterm/ui/atlas_screen.py | 49 +++-------- meshterm/ui/dashboard_screen.py | 104 +++++++++++++---------- meshterm/ui/nodes_screen.py | 89 +++++++++++++++----- meshterm/ui/path_composer.py | 145 ++++++++++++++++++++------------ meshterm/ui/trace_screen.py | 59 +++++++++---- meshterm/ui/tui/frame.py | 8 ++ meshterm/ui/tui/screen.py | 75 +++++++++++++++++ tests/test_atlas.py | 26 +++--- tests/test_dashboard.py | 25 ++++-- tests/test_device_config.py | 25 +++--- tests/test_live_screens.py | 1 + tests/test_topology.py | 21 ++++- 12 files changed, 419 insertions(+), 208 deletions(-) diff --git a/meshterm/ui/atlas_screen.py b/meshterm/ui/atlas_screen.py index af6ca52..e882de0 100644 --- a/meshterm/ui/atlas_screen.py +++ b/meshterm/ui/atlas_screen.py @@ -56,7 +56,7 @@ from .menus import fit_cells from .theme import name_style, snr_style from .trace_screen import snr_bar from .tui.render import render_to_ansi -from .tui.screen import Screen +from .tui.screen import ListWindow, Screen from .widgets import _format_age, highlighted_hash if TYPE_CHECKING: @@ -194,11 +194,9 @@ class AtlasScreen(Screen): #: The live find-as-you-type filter ("" = off; matches every node known). self._filter = "" self._needs_scrub = True # braille smear scrub, exactly like the map - #: First list row the internal window shows (the list scrolls, the screen - #: doesn't), and how many rows that window carried on the last paint — the - #: stride a PgUp/PgDn moves the highlight by. - self._list_top = 0 - self._list_page = 6 + #: The link list's window (the list scrolls, the screen doesn't); its + #: settled capacity is the stride a PgUp/PgDn moves the highlight by. + self._list = ListWindow() # --- state ------------------------------------------------------------------- @@ -296,9 +294,9 @@ class AtlasScreen(Screen): elif action == "pageup" and rows: # The highlight pages by one list windowful: the window follows the # highlight, so paging the view without it would just snap straight back. - self._index = max(0, self._index - self._list_page) + self._index = max(0, self._index - self._list.page) elif action == "pagedown" and rows: - self._index = min(len(rows) - 1, self._index + self._list_page) + self._index = min(len(rows) - 1, self._index + self._list.page) elif action == "enter": self._walk(rows) elif action == "backspace": @@ -376,7 +374,7 @@ class AtlasScreen(Screen): depths = self._hops_out() selected = rows[self._index] if rows else None - _, viewport = self._session.base_body_size() + viewport = self._scroll_viewport # recorded by the frame before this render header = self._header_lines(width, depths) chrome = len(header) + 3 # legend, blank, list heading @@ -680,43 +678,16 @@ class AtlasScreen(Screen): other, link = pairs[i] return self._link_row(other, link, i == self._index, onward.get(other, 0)) - top, count = self._window(len(rows), win) + top, count = self._list.fit(len(rows), win, self._index) if top > 0: - out.append(render_to_ansi(Text(f" ↑ {top} more", style="faint"), width)) + out.append(render_to_ansi(ListWindow.marker(top, "above"), width)) for i in range(top, top + count): out.append(render_to_ansi(render(i), width, no_wrap=True)) below = len(rows) - top - count if below > 0: - out.append(render_to_ansi(Text(f" ↓ {below} more", style="faint"), width)) + out.append(render_to_ansi(ListWindow.marker(below, "below"), width)) return out - def _window(self, n: int, win: int) -> tuple[int, int]: - """The list window: ``(first row, row count)`` keeping the highlight inside. - - The ``↑/↓ n more`` markers eat the window's edge rows exactly when there are - hidden rows on that side, so the content capacity shifts as the window slides; - a couple of passes settles top, capacity, and the highlight clamp together. - The settled capacity is remembered as the PgUp/PgDn stride. - """ - if n <= win: - self._list_top = 0 - self._list_page = max(1, win) - return 0, n - top = max(0, min(self._list_top, n - 1)) - count = 1 - for _ in range(4): - above = 1 if top > 0 else 0 - below = 1 if n - top > win - above else 0 - count = max(1, win - above - below) - if self._index < top: - top = self._index - elif self._index >= top + count: - top = self._index - count + 1 - top = max(0, min(top, n - count)) - self._list_top = top - self._list_page = count - return top, count - def _onward_counts(self, pairs: list[tuple[str, Link]]) -> dict[str, int]: """How many links continue from each neighbour, the one back here excluded.""" counts: dict[str, int] = {} diff --git a/meshterm/ui/dashboard_screen.py b/meshterm/ui/dashboard_screen.py index 409a7d5..283f71c 100644 --- a/meshterm/ui/dashboard_screen.py +++ b/meshterm/ui/dashboard_screen.py @@ -19,16 +19,18 @@ stacks four reads of the mesh, coarsest first: way Device info reads them. * **Feed** — the latest packets, newest first: time, class (icon + label, icon alone on a narrow terminal), node, SNR/RSSI. Seeded from stored history so the screen - opens full, then streamed live off the event hub. ``↑``/``↓`` walk the feed rows - and Enter opens the highlighted packet in the shared - :class:`~meshterm.ui.packet_viewer.PacketViewer` — which then pages through the - feed itself with the same ``↑``/``↓``, and, for an overheard channel-text packet - naming a channel we hold the key for, decrypts it. + opens full, then streamed live off the event hub. The feed scrolls *within* the + screen — the charts above hold still, faint ``↑/↓ n more`` markers bracket its + window — with ``↑``/``↓`` walking the rows and Enter opening the highlighted + packet in the shared :class:`~meshterm.ui.packet_viewer.PacketViewer` — which + then pages through the feed itself with the same ``↑``/``↓``, and, for an + overheard channel-text packet naming a channel we hold the key for, decrypts it. The screen holds no subscriptions of its own — the opener (:func:`open_dashboard`) wires the hub subscription, the device-stats poll, and the once-a-second repaint, and -tears them all down when the screen resolves. PgUp/PgDn/Home/End scroll; Esc first -drops the feed highlight, then backs out. +tears them all down when the screen resolves. PgUp/PgDn/Home/End move the feed window +(carrying the highlight when one is set); Esc first drops the feed highlight, then +backs out. """ from __future__ import annotations @@ -59,8 +61,8 @@ from .packet_viewer import ( ) from .theme import name_style, snr_style from .trace_screen import snr_bar -from .tui.render import render_lines -from .tui.screen import Screen +from .tui.render import render_lines, render_to_ansi +from .tui.screen import ListWindow, Screen if TYPE_CHECKING: from ..context import AppContext @@ -71,7 +73,8 @@ _REFRESH_S = 1.0 #: Seconds between polls of the device's own statistics (noise floor, airtime, battery). _STATS_POLL_S = 10.0 -#: How many feed rows are kept (the body scrolls, so this is history depth, not layout). +#: How many feed rows are kept (the feed windows within the screen, so this is +#: history depth, not layout). _FEED_CAP = 100 #: The feed's fixed node-name lane width; longer names ellipsize so the columns hold. @@ -169,10 +172,10 @@ class DashboardScreen(Screen): self._feed: deque[PacketEntry] = deque(maxlen=_FEED_CAP) for obs in list(self._window)[-_FEED_CAP:][::-1]: self._feed.append(PacketEntry.from_observation(obs)) - #: The highlighted feed row (``None`` = nothing selected, view scrolls free). + #: The highlighted feed row (``None`` = nothing selected, window scrolls free). self._selected: Optional[int] = None - #: Body lines the last render produced before the feed rows began. - self._feed_first_line = 0 + #: The feed's window within the fixed screen (only its rows scroll). + self._feed_window = ListWindow() #: The device's own numbers, refreshed by the opener's poll (Device info's #: dynamic rows): ``stats`` from get_stats, ``battery`` from get_battery. self.stats: dict = {} @@ -224,30 +227,34 @@ class DashboardScreen(Screen): elif action == "enter": self._open_packet() elif action == "pageup": - # With a feed row highlighted the page keys walk the selection (a screenful - # at a time), so the highlight travels with the view instead of the view - # scrolling out from under a pinned selection; with none, they free-scroll. + # With a feed row highlighted the page keys walk the selection (a + # windowful at a time), so the highlight travels with the window; with + # none, they slide the feed window itself under the pinned charts. if self._selected is not None: - self._select_index(self._selected - self._page_step) + self._select_index(self._selected - self._feed_window.page) else: - self.scroll_pages(-1) + self._feed_window.top -= self._feed_window.page + self._session.invalidate() elif action in ("pagedown", "space"): if self._selected is not None: - self._select_index(self._selected + self._page_step) + self._select_index(self._selected + self._feed_window.page) else: - self.scroll_pages(1) + self._feed_window.top += self._feed_window.page + self._session.invalidate() elif action in ("home", "ctrl_home"): # With the feed highlight active, Home jumps to the newest packet; - # otherwise it keeps its plain scroll-to-top meaning (End mirrors it). + # otherwise it slides the window to the feed's newest end (End mirrors). if self._selected is not None: self._select_index(0) else: - self.scroll_to_top() + self._feed_window.top = 0 + self._session.invalidate() elif action in ("end", "ctrl_end"): if self._selected is not None: self._select_index(len(self._feed) - 1) else: - self.scroll_to_bottom() + self._feed_window.to_end() + self._session.invalidate() elif action == "escape": if self._selected is not None: self._selected = None # first Esc peels the highlight, second leaves @@ -296,33 +303,32 @@ class DashboardScreen(Screen): ) asyncio.ensure_future(self._session.run_screen(viewer)) - def cursor_line(self) -> Optional[int]: - """Keep the highlighted feed row in view (free scrolling when nothing is).""" - if self._selected is None or not self._feed: - return None - return self._feed_first_line + self._selected - # --- rendering --------------------------------------------------------------------- def render_body(self, width: int) -> list[str]: - """Render the four stacked sections for the current state.""" + """Render the pinned overview sections, then the feed's window beneath. + + The charts, traffic, and RF sections size the fixed chrome; whatever the + frame's viewport has left is the feed's window — only its rows scroll (see + :class:`~meshterm.ui.tui.screen.ListWindow`), so the overview stays + glanceable however deep the reader digs into the feed. + """ self._prune() if self._selected is not None and self._feed: self._selected = min(self._selected, len(self._feed) - 1) - sections: list[RenderableType] = [ + chrome: list[RenderableType] = [ *self._activity_section(width), Text(), *self._traffic_section(), Text(), *self._rf_section(), Text(), - *self._feed_section(width), + self._feed_heading(), ] - lines = render_lines(Group(*sections), width) + lines = render_lines(Group(*chrome), width) + win = max(1, self._scroll_viewport - len(lines)) + lines.extend(self._feed_lines(width, win)) self._scroll_total = max(1, len(lines)) - # Feed rows are the body's tail, one line each (they never wrap), so the - # highlight's body line is a plain offset from the end. - self._feed_first_line = len(lines) - len(self._feed) return lines # -- activity -- @@ -529,21 +535,33 @@ class DashboardScreen(Screen): # -- feed -- - def _feed_section(self, width: int) -> list[RenderableType]: - """The latest packets, newest first, with a live-light in the heading.""" + def _feed_heading(self) -> Text: + """The feed's pinned heading, with a live-light for the hub.""" heading = Text("Feed", style="accent") heading.append(" · newest first · Enter opens a packet ", style="muted") if self._hub_active(): heading.append("● live", style="ok") else: heading.append("○ waiting for a device", style="muted") - rows: list[RenderableType] = [heading] + return heading + + def _feed_lines(self, width: int, win: int) -> list[str]: + """The feed's windowed rows: newest first, ``↑/↓ n more`` at the edges.""" if not self._feed: - rows.append(Text("nothing heard yet", style="muted")) + return [render_to_ansi(Text("nothing heard yet", style="muted"), width)] show_label = width >= _FEED_LABEL_MIN_WIDTH - for i, entry in enumerate(self._feed): - rows.append(self._feed_row(entry, i == self._selected, show_label)) - return rows + entries = list(self._feed) + top, count = self._feed_window.fit(len(entries), win, self._selected) + out: list[str] = [] + if top > 0: + out.append(render_to_ansi(ListWindow.marker(top, "above"), width)) + for i in range(top, top + count): + row = self._feed_row(entries[i], i == self._selected, show_label) + out.append(render_to_ansi(row, width, no_wrap=True)) + below = len(entries) - top - count + if below > 0: + out.append(render_to_ansi(ListWindow.marker(below, "below"), width)) + return out def _feed_row(self, entry: PacketEntry, selected: bool, show_label: bool) -> Text: """Lay one feed row out in fixed lanes: time, class, node, reception, detail. diff --git a/meshterm/ui/nodes_screen.py b/meshterm/ui/nodes_screen.py index 2d5abe0..888a699 100644 --- a/meshterm/ui/nodes_screen.py +++ b/meshterm/ui/nodes_screen.py @@ -2,7 +2,9 @@ This wraps :func:`~meshterm.ui.widgets.nodes_table` in a full-screen TUI layer whose sort the user steers with the arrows — left/right pick the column, up/down set ascending/descending — -so the table re-renders in place. The one-shot CLI (``meshterm nodes --sort …``) renders the +so the table re-renders in place. The rows scroll in a window inside the fixed screen: the +title, column header, and bottom legend hold still, faint ``↑/↓ n more`` markers bracket the +window, and PgUp/PgDn slide it. The one-shot CLI (``meshterm nodes --sort …``) renders the same table statically; only the menu gets the live sorting. """ @@ -11,9 +13,9 @@ from __future__ import annotations import re from typing import TYPE_CHECKING -from .tui.render import render_lines -from .tui.screen import Screen -from .widgets import NodesSort, nodes_table +from .tui.render import render_lines, render_to_ansi +from .tui.screen import ListWindow, Screen +from .widgets import NodesSort, _nodes_legend, nodes_table if TYPE_CHECKING: from ..context import AppContext @@ -56,9 +58,21 @@ class NodesScreen(Screen): self._prefix_bytes = prefix_bytes self._counts = counts self._sort = sort + #: The row window inside the fixed screen (title, header, and legend pinned). + self._rows_window = ListWindow() + #: Whether the last render actually windowed the rows — degenerate renders + #: (no header rule found, or a viewport too short) fall back to whole-body + #: scrolling, and the page keys follow suit. + self._windowed = False def render_body(self, width: int) -> list[str]: - """Render the table+legend at the current sort, pinning the column header on scroll.""" + """Render the table at the current sort, windowing its rows in place. + + The title, column header, and rule pin above the window; the glyph legend + pins beneath it; only the node rows scroll between them. A render whose + header rule can't be found (degenerate narrow width) or whose viewport + leaves the window no room falls back to the plain whole-body scroll. + """ table = nodes_table( self._self_name, self._self_key, @@ -68,29 +82,46 @@ class NodesScreen(Screen): self._sort, ) lines = render_lines(table, width) - self._scroll_total = max(1, len(lines)) - # Pin the ``Name / Heard / Pkts / Key`` labels so they stay in view once the rows scroll - # past — the base Screen.sticky_header re-draws the recorded line as the top row. The - # header sits directly above the rule the table draws under it (box.SIMPLE_HEAD). - self._sticky_headers = self._column_header(lines) - return lines + rule = self._rule_index(lines) + legend_h = len(render_lines(_nodes_legend(), width)) + 1 # + its blank spacer + win = self._scroll_viewport - (rule + 1) - legend_h if rule is not None else 0 + self._windowed = rule is not None and win >= 3 + if not self._windowed: + self._scroll_total = max(1, len(lines)) + return lines + + head, rows, tail = ( + lines[: rule + 1], lines[rule + 1 : len(lines) - legend_h], + lines[len(lines) - legend_h :], + ) + top, count = self._rows_window.fit(len(rows), win) + out = list(head) + if top > 0: + out.append(render_to_ansi(ListWindow.marker(top, "above"), width)) + out.extend(rows[top : top + count]) + below = len(rows) - top - count + if below > 0: + out.append(render_to_ansi(ListWindow.marker(below, "below"), width)) + out.extend(tail) + self._scroll_total = max(1, len(out)) + return out @staticmethod - def _column_header(lines: list[str]) -> list[tuple[int, str]]: - """Locate the column-header row (the line just above the table's header rule). + def _rule_index(lines: list[str]) -> "int | None": + """Locate the rule the table draws under its column labels. - The table renders a full-width rule of ``─`` under its column labels; the first such - line marks the header, so the row above it carries the labels. Returns a single-entry - sticky-header list, or empty if no rule is found (e.g. a degenerate narrow render). + The table renders a full-width run of ``─`` there (box.SIMPLE_HEAD); the + first such line marks where the pinned head ends and the rows begin. + ``None`` if no rule is found (e.g. a degenerate narrow render). """ for idx in range(1, len(lines)): bare = _ANSI_RE.sub("", lines[idx]).strip() if bare and set(bare) == {"─"}: - return [(idx - 1, lines[idx - 1])] - return [] + return idx + return None def handle(self, action: str, data: str = "") -> None: - """Re-sort with the arrows, scroll with PageUp/PageDown/Home/End, or dismiss.""" + """Re-sort with the arrows, slide the row window with the page keys, or dismiss.""" if action == "left": self._sort.move(-1) elif action == "right": @@ -100,13 +131,25 @@ class NodesScreen(Screen): elif action == "down": self._sort.ascending = False elif action == "pageup": - self.scroll_pages(-1) + if self._windowed: + self._rows_window.top -= self._rows_window.page + else: + self.scroll_pages(-1) elif action in ("pagedown", "space"): - self.scroll_pages(1) + if self._windowed: + self._rows_window.top += self._rows_window.page + else: + self.scroll_pages(1) elif action in ("home", "ctrl_home"): - self.scroll_to_top() + if self._windowed: + self._rows_window.top = 0 + else: + self.scroll_to_top() elif action in ("end", "ctrl_end"): - self.scroll_to_bottom() + if self._windowed: + self._rows_window.to_end() + else: + self.scroll_to_bottom() elif action in ("escape", "enter"): self.resolve(None) diff --git a/meshterm/ui/path_composer.py b/meshterm/ui/path_composer.py index 7f46db2..c1b24da 100644 --- a/meshterm/ui/path_composer.py +++ b/meshterm/ui/path_composer.py @@ -35,9 +35,12 @@ Interaction, following the reorder screen's cursor-over-rows-and-actions pattern topology, and reopens the composer mid-thought (hops preserved). * Enter on **Use this path** commits the composed spec; Esc cancels with no change. -Nodes render exactly as the trace screen's route line does — ``Name (hash)`` with the -name in the brand colour and the hash muted in parentheses — so a node reads the same -wherever it appears. +Nodes and the route preview render through the shared path widget +(:func:`~meshterm.ui.widgets.path_text`, trace flavour) — ``Name (hash)`` with names +in their app-wide hues and our own node the white ``you`` — so a node reads the same +wherever it appears. The suggestion list scrolls in a window under the pinned route +preview (faint ``↑/↓ n more`` markers at its edges; PgUp/PgDn stride by a windowful), +so the route under construction never leaves the screen. """ from __future__ import annotations @@ -51,8 +54,8 @@ from rich.text import Text from ..services.topology import MeshTopology, _is_hex, render_custom_spec, render_forced_spec from .theme import snr_style from .tui.render import render_lines, render_to_ansi -from .tui.screen import Screen -from .widgets import _age_seconds, _format_age, _shorten_hash +from .tui.screen import ListWindow, Screen +from .widgets import _age_seconds, _format_age, path_text #: Sentinel spec meaning "no forced path — let the device route" (the trace screen's #: empty-spec convention). Only meaningful in target mode; a path walk has no target @@ -149,6 +152,8 @@ class PathComposerScreen(Screen): self._fetch_nodes = fetch_nodes self._entry = "" self._index = 0 + #: The suggestion/action list's window under the pinned route preview. + self._list = ListWindow() @property def hops(self) -> list[str]: @@ -232,62 +237,68 @@ class PathComposerScreen(Screen): # --- rendering --------------------------------------------------------------- - def _node_text(self, node: str, *, dim: bool = False) -> Text: - """One route node, rendered exactly as the trace screen's route line does. + def _path_entry(self, node: str) -> Optional[str]: + """A canonical id as a :func:`path_text` hop entry (``None`` = our device). - ``Name (hash)`` when known — name in the brand colour, hash muted in - parentheses — a bare brand hash when not, and our own device as its accent - label plus hash. Hashes show at the spec's preferred path-hash width, the - same width every other trace-feature view truncates to, so a node reads the - same length everywhere. + The pinned target rides as its full hash when one is known, so its hash + annotation shows the spec width even past the canonical id's 12 hex. + """ + if node == self._topology.self_id: + return None + if node == self._target_id: + return self._target_hash or node + return node + + def _resolve_entry(self, entry: str) -> str: + """Resolve a preview entry to its display name (the target by its label).""" + if self._target_id is not None and entry == (self._target_hash or self._target_id): + return self._target_label or entry + return self._topology.display_name(entry) or entry + + def _node_text(self, node: str, *, dim: bool = False) -> Text: + """One route node through THE path widget, the trace presentation. + + ``Name (hash)`` when known — the name in its app-wide hue, our own device + the white ``you`` — a bare brand hash when not. Hashes show at the spec's + preferred path-hash width, the same width every other trace-feature view + truncates to, so a node reads the same length everywhere. Args: node: The node's canonical id (or ``self_id`` for our own device). dim: Whether to render in the resolved-return-leg's uniform faint style rather than the normal route colours. """ - if node == self._topology.self_id: - text = Text(self._device_label, style="faint" if dim else "accent") - if self._device_hash: - shown = _shorten_hash(self._device_hash, self._width_bytes) - text.append(f" ({shown})", style="faint" if dim else "muted") - return text - if node == self._target_id: - name: Optional[str] = self._target_label - hash_source = self._target_hash or node - else: - name = self._topology.display_name(node) - hash_source = node - shown = _shorten_hash(hash_source, self._width_bytes) - if not name: - return Text(shown, style="faint" if dim else "brand") - text = Text(name, style="faint" if dim else "brand") - text.append(f" ({shown})", style="faint" if dim else "muted") - return text + return path_text( + [self._path_entry(node)], self._resolve_entry, + prefix_bytes=self._width_bytes, self_name=self._device_label, + show_hash=True, hash_bytes=self._width_bytes, + device_hash=self._device_hash or None, + dim_from=0 if dim else None, + ) def _route_preview(self) -> Text: """The route under construction, endpoints filled in automatically. - Target mode shows the composed outbound in full colour, then the pinned - target and the mirrored return resolved and dimmed right alongside it — the - dimming reads as "this half isn't yours to compose". Path mode shows every - composed hop in full colour (they are all yours) between our own node at - both ends, with only the final landing back on us dimmed. + One :func:`path_text` in the trace flavour: target mode shows the composed + outbound in full colour, then the pinned target and the mirrored return + resolved and dimmed right alongside it (``dim_from``) — the dimming reads + as "this half isn't yours to compose". Path mode shows every composed hop + in full colour (they are all yours) between our own node at both ends, + with only the final landing back on us dimmed. """ - text = Text() - text.append_text(self._node_text(self._topology.self_id)) - for hop in self._hops: - text.append(" → ", style="muted") - text.append_text(self._node_text(hop)) + entries: list[Optional[str]] = [None] + entries.extend(self._path_entry(hop) for hop in self._hops) if self._mirrored: - text.append(" → ", style="muted") - text.append_text(self._node_text(self._target_id)) - for hop in reversed(self._hops): - text.append(" → ", style="faint") - text.append_text(self._node_text(hop, dim=True)) - text.append(" → ", style="faint") - text.append_text(self._node_text(self._topology.self_id, dim=True)) - return text + entries.append(self._path_entry(self._target_id)) + entries.extend(self._path_entry(hop) for hop in reversed(self._hops)) + entries.append(None) + return path_text( + entries, self._resolve_entry, + prefix_bytes=self._width_bytes, self_name=self._device_label, + show_hash=True, hash_bytes=self._width_bytes, + device_hash=self._device_hash or None, + dim_from=(2 if self._mirrored else 1) + len(self._hops), + ) def _suggestion_text(self, suggestion) -> Text: # noqa: ANN001 """One suggestion row: node, then its link's evidence trail.""" @@ -340,7 +351,12 @@ class PathComposerScreen(Screen): return max(widths, default=20) + 8 def render_body(self, width: int) -> list[str]: - """Render the route preview, filter/hint line, suggestions, and actions.""" + """Render the pinned route preview and filter line, then the windowed rows. + + The preview and heading hold still; the suggestion/action rows scroll in + whatever the dialog's budget has left (see :class:`ListWindow`), so a long + suggestion list can never push the route being composed out of the dialog. + """ rows = self._rows() self._index = max(0, min(self._index, len(rows) - 1)) @@ -354,10 +370,12 @@ class PathComposerScreen(Screen): heading.append(" — strongest first", style="muted") lines.extend(render_lines(heading, width)) - cursor_at: Optional[int] = None + # Each windowable entry is one rendered line tagged with its row index + # (``None`` = a spacer or note line the cursor can't land on). + entries: list[tuple[Optional[int], str]] = [] for i, (kind, payload) in enumerate(rows): if kind == "action" and (i == 0 or rows[i - 1][0] != "action"): - lines.append("") # a spacer sets the action group apart + entries.append((None, "")) # a spacer sets the action group apart is_sel = i == self._index text = Text("❯ " if is_sel else " ", style="brand" if is_sel else "") text.append_text(self._row_text(kind, payload)) @@ -365,17 +383,28 @@ class PathComposerScreen(Screen): text.style = "brand" text.no_wrap = True text.truncate(width, overflow="ellipsis") - if is_sel: - cursor_at = len(lines) - lines.append(render_to_ansi(text, width)) + entries.append((i, render_to_ansi(text, width))) if not any(kind == "hop" for kind, _ in rows): if any(kind == "fetch" for kind, _ in rows): note = "(no observed links from here — fetch the repeater's neighbours, or type a hex hash)" else: note = "(no observed links from here — type a hex hash to force a hop)" - lines.append(render_to_ansi(Text(note, style="muted"), width)) + entries.append((None, render_to_ansi(Text(note, style="muted"), width))) - self._cursor = cursor_at + win = max(3, self._scroll_viewport - len(lines)) + at = next(p for p, (row, _line) in enumerate(entries) if row == self._index) + top, count = self._list.fit(len(entries), win, at) + self._cursor = None + if top > 0: + lines.append(render_to_ansi(ListWindow.marker(top, "above"), width)) + for pos in range(top, top + count): + row, line = entries[pos] + if row == self._index: + self._cursor = len(lines) + lines.append(line) + below = len(entries) - top - count + if below > 0: + lines.append(render_to_ansi(ListWindow.marker(below, "below"), width)) self._scroll_total = max(1, len(lines)) return lines @@ -417,6 +446,10 @@ class PathComposerScreen(Screen): self._index = (self._index - 1) % len(rows) elif action == "down" and rows: self._index = (self._index + 1) % len(rows) + elif action == "pageup" and rows: + self._index = max(0, self._index - self._list.page) + elif action == "pagedown" and rows: + self._index = min(len(rows) - 1, self._index + self._list.page) elif action in ("home", "ctrl_home"): self._index = 0 elif action in ("end", "ctrl_end"): diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index 8fce36b..bbf03ec 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -47,9 +47,10 @@ Layout, top to bottom: the walked route (live when a reply has landed, else the the next Trace will walk — composed by hand, or auto-resolved from the device's learned route or the stored history and labelled with that provenance — else the most recent stored trace), the run's robust aggregates, the -action list, per-hop median SNR with quality bars, and the individual traces -newest-first. The body scrolls with PgUp/PgDn/Home/End (↑/↓ belong to the action -cursor, which only pins the view while it is actually being moved). +action list, then the results — per-hop median SNR with quality bars and the +individual traces newest-first — scrolling in a window beneath the pinned controls: +PgUp/PgDn/Home/End slide it (↑/↓ belong to the action cursor), and faint ``↑/↓ n +more`` markers count what the window hides. Every trace is persisted exactly like a scripted run: one ``runs`` row per trace, recorded under it, so the stored history reads the same no matter which front end @@ -75,7 +76,7 @@ from .braillechart import meter from .menus import back_rows from .theme import snr_style from .tui.render import render_hanging, render_lines, render_to_ansi -from .tui.screen import Screen +from .tui.screen import ListWindow, Screen from .tui.spinner import Spinner from .widgets import NodeResolver, _link_text, _route_text, highlighted_hash, path_text @@ -230,9 +231,10 @@ class TraceScreen(Screen): described the old route, so they clear as if the screen had just opened. ↑/↓ move the cursor over the action rows and Enter commits the selected one — the - cursor opens on Trace, so plain Enter still just traces. PgUp/PgDn/Home/End scroll - the body, and Esc (or the Back row) backs out, cancelling any in-flight trace; - already-recorded traces are kept. + cursor opens on Trace, so plain Enter still just traces. The results (per-hop + medians and the trace log) scroll in a window beneath the pinned controls with + PgUp/PgDn/Home/End, and Esc (or the Back row) backs out, cancelling any + in-flight trace; already-recorded traces are kept. """ floating = False @@ -337,6 +339,9 @@ class TraceScreen(Screen): self._actions: tuple[str, ...] = tuple(actions) self._index = self._actions.index("trace") self._pin_cursor = False # only pin the view while ↑/↓ are actually in use + #: The results window under the pinned actions (per-hop medians + trace + #: log); PgUp/PgDn slide it while the route and controls hold still. + self._tail_window = ListWindow() # --- state ----------------------------------------------------------------- @@ -431,9 +436,9 @@ class TraceScreen(Screen): def handle(self, action: str, data: str = "") -> None: """Move the action cursor, commit the selected action, scroll, or dismiss. - ↑/↓ belong to the action cursor (and pin the view to it); the body scrolls - with PgUp/PgDn/Home/End, each of which releases the pin so a long trace log - can be read without the cursor yanking the view back. + ↑/↓ belong to the action cursor; PgUp/PgDn/Home/End slide the results + window beneath the pinned controls, so a long trace log can be read while + the route and actions stay on screen. """ if action == "enter": self._commit_action() @@ -445,16 +450,16 @@ class TraceScreen(Screen): self._pin_cursor = True elif action == "pageup": self._pin_cursor = False - self.scroll_pages(-1) + self._tail_window.top -= self._tail_window.page elif action in ("pagedown", "space"): self._pin_cursor = False - self.scroll_pages(1) + self._tail_window.top += self._tail_window.page elif action in ("home", "ctrl_home"): self._pin_cursor = False - self.scroll_to_top() + self._tail_window.top = 0 elif action in ("end", "ctrl_end"): self._pin_cursor = False - self.scroll_to_bottom() + self._tail_window.to_end() elif action == "escape": self.cancel() self.resolve(None) @@ -543,6 +548,26 @@ class TraceScreen(Screen): lines.append(render_to_ansi(text, width)) if key in ("explore", "samples"): lines.append("") # set the next group apart + tail = self._tail_lines(stats, current, width) + if tail: + # The results scroll in a window beneath the pinned controls (see + # ListWindow): the route and actions never leave the screen, however + # long a sampling session's log grows. + win = max(3, self._scroll_viewport - len(lines)) + top, count = self._tail_window.fit(len(tail), win) + if top > 0: + lines.append(render_to_ansi(ListWindow.marker(top, "above"), width)) + lines.extend(tail[top : top + count]) + below = len(tail) - top - count + if below > 0: + lines.append(render_to_ansi(ListWindow.marker(below, "below"), width)) + self._scroll_total = max(1, len(lines)) + return lines + + def _tail_lines( + self, stats: TraceStats, current: Optional[TraceResult], width: int + ) -> list[str]: + """The windowed results block: per-hop medians, then the trace log.""" tail: list[RenderableType] = [] if stats.hop_snrs: hash_bytes = current.path_hash_bytes if current is not None else None @@ -551,9 +576,9 @@ class TraceScreen(Screen): if self._running or self._status or self._traces: tail += [Text(), Text("Traces", style="accent")] tail.append(self._trace_log()) - lines.extend(render_lines(Group(*tail), width)) - self._scroll_total = max(1, len(lines)) - return lines + if not tail: + return [] + return render_lines(Group(*tail), width) def cursor_line(self) -> Optional[int]: """The highlighted action row while ↑/↓ are in use; free scrolling otherwise. diff --git a/meshterm/ui/tui/frame.py b/meshterm/ui/tui/frame.py index e483ff0..8c54051 100644 --- a/meshterm/ui/tui/frame.py +++ b/meshterm/ui/tui/frame.py @@ -116,6 +116,10 @@ def _panel(screen: Screen, inner_w: int, viewport: int, active: bool) -> Panel: Returns: A Rich :class:`Panel` of exactly ``viewport + 2`` rows. """ + # Record the viewport *before* the body renders, so a screen that windows a + # list inside itself (see :class:`~meshterm.ui.tui.screen.ListWindow`) can size + # its chrome to the frame it is about to be sliced into. + screen.note_viewport(viewport) body_lines = screen.render_body(inner_w) visible, more_above, more_below = _visible_slice(screen, body_lines, viewport) body = Text.from_ansi("\n".join(visible)) @@ -281,6 +285,10 @@ def _dialog_layout(screen: Screen, cols: int, rows: int) -> tuple[int, int, int, max_w = cap if natural is None else max(24, min(cap, natural)) # Rows the box may spend between its borders — on body lines and breathing room alike. budget = max(3, rows - 6) + # Record the budget as the provisional viewport before the body renders, so a + # dialog that windows a list inside itself (the path composer) can size to what + # it may spend; the slice records the real, body-sized viewport afterwards. + screen.note_viewport(budget) body_lines = screen.render_body(max_w - 4) # A grow-only screen (the packet viewer paging between packets) sizes to the tallest # body it has shown, not this one, so a shorter body keeps the larger box instead of diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index 47c7e37..da8280a 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -240,6 +240,81 @@ class Screen: self.scroll = _clamp_scroll(target, self._scroll_total, self._scroll_viewport) +class ListWindow: + """Scroll state for a list that scrolls *inside* a fixed screen. + + The app-wide windowed-list pattern (established by the atlas's link list): the + screen sizes its fixed chrome — headings, charts, action rows — to the frame's + viewport (see :meth:`Screen.note_viewport`; the frame records it before + ``render_body`` runs) and hands the leftover rows here; only the list's rows + scroll within them. Faint ``↑ n more`` / ``↓ n more`` markers (see + :meth:`marker`) take the window's edge rows exactly when rows are hidden on + that side, and the settled content capacity is remembered as :attr:`page`, the + stride a PgUp/PgDn should move by. + + Attributes: + top: First list row the window shows (clamped by :meth:`fit` each paint). + page: Rows the window carried on the last :meth:`fit` — the paging stride. + """ + + def __init__(self) -> None: + """Start at the top with a conservative pre-first-paint stride.""" + self.top = 0 + self.page = 6 + + def fit(self, n: int, win: int, index: Optional[int] = None) -> tuple[int, int]: + """Settle the window over ``n`` rows into ``win`` lines: ``(top, count)``. + + The edge markers eat the window's boundary rows exactly when rows hide + beyond them, so the content capacity shifts as the window slides; a few + passes settle top, capacity, and the highlight clamp together. + + Args: + n: Total list rows. + win: Lines the window may spend — on content and markers alike. + index: A highlighted row that must stay visible, or ``None`` when the + window scrolls free (a cursor-less log; ``top`` is just clamped). + + Returns: + The first visible row and how many rows to draw. Rows hidden above + number ``top``; below, ``n - top - count`` — each side non-zero exactly + when its marker row should be drawn. + """ + if n <= win: + self.top = 0 + self.page = max(1, win) + return 0, n + top = max(0, min(self.top, n - 1)) + count = 1 + for _ in range(4): + above = 1 if top > 0 else 0 + below = 1 if n - top > win - above else 0 + count = max(1, win - above - below) + if index is not None: + if index < top: + top = index + elif index >= top + count: + top = index - count + 1 + top = max(0, min(top, n - count)) + self.top = top + self.page = count + return top, count + + def to_end(self) -> None: + """Slide the window to the list's tail on the next :meth:`fit`. + + The overshoot is deliberate — the caller rarely knows the list length at + keypress time, and :meth:`fit` clamps to the last windowful either way. + """ + self.top = 10**9 + + @staticmethod + def marker(hidden: int, direction: str) -> Text: + """The faint edge row counting rows hidden ``"above"`` or ``"below"``.""" + arrow = "↑" if direction == "above" else "↓" + return Text(f" {arrow} {hidden} more", style="faint") + + def _clamp_scroll(scroll: int, total: int, viewport: int) -> int: """Clamp a scroll offset to the valid range for the content and viewport. diff --git a/tests/test_atlas.py b/tests/test_atlas.py index d9620b8..ac81202 100644 --- a/tests/test_atlas.py +++ b/tests/test_atlas.py @@ -20,13 +20,9 @@ ALICE = Contact(name="Alice", public_key="b2" * 32, last_seen=utcnow() - timedel class _FakeSession: - def __init__(self, cell_h: int = 24) -> None: - self.cell_h = cell_h + def __init__(self) -> None: self.repaints = 0 - def base_body_size(self) -> tuple[int, int]: - return (80, self.cell_h) - def invalidate(self) -> None: self.repaints += 1 @@ -45,8 +41,8 @@ def _topo(*, with_island: bool = False) -> MeshTopology: def _screen(topo: MeshTopology, cell_h: int = 24) -> AtlasScreen: - return AtlasScreen( - session=_FakeSession(cell_h), + screen = AtlasScreen( + session=_FakeSession(), topo=topo, contacts={ topo.canonical(YUL.public_key): YUL, @@ -54,6 +50,8 @@ def _screen(topo: MeshTopology, cell_h: int = 24) -> AtlasScreen: }, self_label="Homestead", ) + screen.note_viewport(cell_h) # the frame records this before every real paint + return screen def _plain(lines: list[str]) -> str: @@ -175,8 +173,9 @@ def _hub_topo(spokes: int) -> MeshTopology: def test_atlas_collapses_the_weak_links_into_one_ellipsis_marker() -> None: """Beyond the area's capacity, weaker neighbours fold into a single ``…`` node.""" screen = AtlasScreen( - session=_FakeSession(cell_h=20), topo=_hub_topo(14), contacts={}, self_label="us" + session=_FakeSession(), topo=_hub_topo(14), contacts={}, self_label="us" ) + screen.note_viewport(20) body = _plain(screen.render_body(80)) assert "weaker" in body # the collapsed marker is labelled "+n weaker" canvas_part = body.split("Links")[0] @@ -188,8 +187,9 @@ def test_atlas_collapses_the_weak_links_into_one_ellipsis_marker() -> None: def test_atlas_selecting_a_collapsed_row_lights_the_ellipsis_with_its_name() -> None: """Highlighting a weak (collapsed) row surfaces its name at the ``…`` marker.""" screen = AtlasScreen( - session=_FakeSession(cell_h=20), topo=_hub_topo(14), contacts={}, self_label="us" + session=_FakeSession(), topo=_hub_topo(14), contacts={}, self_label="us" ) + screen.note_viewport(20) screen.render_body(80) screen._index = len(screen._rows()) - 1 # the weakest row, surely collapsed body = _plain(screen.render_body(80)) @@ -202,8 +202,9 @@ def test_atlas_selecting_a_collapsed_row_lights_the_ellipsis_with_its_name() -> def test_atlas_body_fits_the_viewport_and_windows_the_list() -> None: """The screen never outgrows the frame; only the link list scrolls, marked.""" screen = AtlasScreen( - session=_FakeSession(cell_h=22), topo=_hub_topo(16), contacts={}, self_label="us" + session=_FakeSession(), topo=_hub_topo(16), contacts={}, self_label="us" ) + screen.note_viewport(22) lines = screen.render_body(80) assert len(lines) <= 22 # canvas + chrome + list window == the viewport body = _plain(lines) @@ -214,10 +215,11 @@ def test_atlas_body_fits_the_viewport_and_windows_the_list() -> None: def test_atlas_pgdn_pages_the_highlight_by_the_list_window() -> None: """PgUp/PgDn stride by the list window, and the window follows the highlight.""" screen = AtlasScreen( - session=_FakeSession(cell_h=22), topo=_hub_topo(16), contacts={}, self_label="us" + session=_FakeSession(), topo=_hub_topo(16), contacts={}, self_label="us" ) + screen.note_viewport(22) screen.render_body(80) - stride = screen._list_page + stride = screen._list.page assert stride >= 1 screen.handle("pagedown") assert screen._index == min(15, stride) diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index caf2be2..1ccb621 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -27,7 +27,7 @@ class _FakeSession: def _screen(window=None, histogram=None, kinds=None, active=True) -> DashboardScreen: - return DashboardScreen( + screen = DashboardScreen( session=_FakeSession(), resolve=lambda h: {"a1b2": "Alice", "3d63": "YUL"}.get(h, ""), window=list(window or []), @@ -36,6 +36,8 @@ def _screen(window=None, histogram=None, kinds=None, active=True) -> DashboardSc kind_counts=lambda: dict(kinds or {}), hub_active=lambda: active, ) + screen.note_viewport(48) # the frame records this before every real paint + return screen def _obs(node="a1b2", kind="advert", snr=5.0, rssi=-90.0, age_s=0, **extra) -> Observation: @@ -180,10 +182,10 @@ def test_dashboard_prunes_the_window_but_keeps_the_feed() -> None: def test_dashboard_page_keys_move_the_feed_selection() -> None: - """With a feed row highlighted, PgUp/PgDn walk the selection a screenful at a time.""" + """With a feed row highlighted, PgUp/PgDn walk the selection a windowful at a time.""" window = [_obs(node=f"n{i}", age_s=i) for i in range(20)] screen = _screen(window=window) - screen.note_metrics(total=40, viewport=6) # a screenful is _page_step = 5 rows + screen._feed_window.page = 5 # as if the last paint settled a five-row window screen.handle("down") # first press lands the highlight on the newest feed row assert screen._selected == 0 screen.handle("pagedown") @@ -191,11 +193,22 @@ def test_dashboard_page_keys_move_the_feed_selection() -> None: screen.handle("pageup") assert screen._selected == 0 - # With nothing highlighted, the page keys free-scroll the body as before. + # With nothing highlighted, the page keys slide the feed window instead. screen._selected = None - screen.scroll = 0 screen.handle("pagedown") - assert screen.scroll > 0 and screen._selected is None + assert screen._feed_window.top > 0 and screen._selected is None + + +def test_dashboard_feed_windows_inside_the_fixed_screen() -> None: + """The charts stay pinned: the body fits the viewport and the feed rows window.""" + window = [_obs(node=f"n{i}", age_s=i) for i in range(40)] + screen = _screen(window=window) + screen.note_viewport(24) + lines = screen.render_body(100) + assert len(lines) <= 24 # charts + feed window == the viewport, never more + body = _plain(_stripped(lines)) + assert "Activity" in body and "Feed" in body # the chrome is all still there + assert "↓" in body and "more" in body # hidden feed rows are counted below def test_dashboard_without_a_device_reads_as_waiting() -> None: diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 75ef03c..5d5fefc 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -205,26 +205,29 @@ def test_nodes_screen_arrows_steer_the_sort() -> None: assert screen._sort.column == "packets" -def test_nodes_screen_pins_column_header_when_scrolled() -> None: - """The NAME/HEARD/PKTS/KEY labels stick to the top row once the rows scroll past them.""" +def test_nodes_screen_windows_rows_between_pinned_header_and_legend() -> None: + """The rows scroll in place: header and legend hold still, hidden rows counted.""" import re from meshterm.core.models import Contact from meshterm.ui.nodes_screen import NodesScreen from meshterm.ui.widgets import NodesSort - contacts = [Contact(name=f"n{i}", public_key="ab" * 16) for i in range(12)] + contacts = [Contact(name=f"n{i:02}", public_key="ab" * 16) for i in range(30)] screen = NodesScreen("Us", "aabbcc" + "00" * 29, contacts, 3, {}, NodesSort()) - screen.render_body(70) + screen.note_viewport(18) # the frame records this before every real paint + lines = screen.render_body(70) + plain = [re.sub(r"\x1b\[[0-9;]*m", "", line) for line in lines] + body = "\n".join(plain) - # Exactly one sticky header — the column-label row — recorded above the table's rule. - (idx, header), = screen._sticky_headers - labels = re.sub(r"\x1b\[[0-9;]*m", "", header) - assert "NAME" in labels and "HEARD" in labels and "KEY" in labels + assert len(lines) <= 18 # header + window + legend fit the frame exactly + assert "NAME" in body and "you" in body # the pinned header and legend survive + assert "↓" in body and "more" in body # hidden rows are counted below + assert "n29" not in body # ...because the tail really is out of the window - # Not pinned while the header is still on screen; pinned once scrolled below it. - assert screen.sticky_header(idx) is None - assert screen.sticky_header(idx + 5) == header + screen.handle("end") # slide the window to the tail + body = "\n".join(re.sub(r"\x1b\[[0-9;]*m", "", ln) for ln in screen.render_body(70)) + assert "n29" in body and "↑" in body # tail visible, hidden rows counted above def test_non_strict_enum_accepts_unlisted_value() -> None: diff --git a/tests/test_live_screens.py b/tests/test_live_screens.py index ae25d70..61ff244 100644 --- a/tests/test_live_screens.py +++ b/tests/test_live_screens.py @@ -223,6 +223,7 @@ def _trace_screen( auto_spec=auto_spec or (lambda: ""), auto_source=auto_source, ) + screen.note_viewport(40) # the frame records this before every real paint return screen, session diff --git a/tests/test_topology.py b/tests/test_topology.py index ec12f14..73d6bd2 100644 --- a/tests/test_topology.py +++ b/tests/test_topology.py @@ -301,7 +301,7 @@ def _composer(topo, hops=None, fetch_nodes=frozenset(), target=True): # noqa: A if target else {} ) - return PathComposerScreen( + screen = PathComposerScreen( device_label="Us", device_hash=US + "0" * 52, topology=topo, @@ -310,6 +310,8 @@ def _composer(topo, hops=None, fetch_nodes=frozenset(), target=True): # noqa: A fetch_nodes=fetch_nodes, **pinned, ) + screen.note_viewport(30) # the frame records the dialog budget before each paint + return screen def _rows_plain(screen: PathComposerScreen) -> str: @@ -328,6 +330,23 @@ def test_composer_suggests_from_tail_and_appends_on_enter() -> None: assert all(s.node != "f2c24f54551e" for s in screen._suggestions()) +def test_composer_windows_rows_under_the_pinned_route_preview() -> None: + """A short dialog windows the rows; the route preview and cursor stay visible.""" + import re + + walks = [ + _traced((f"{i + 16:02x}", 3.0), (None, 3.0)) for i in range(10) + ] + screen = _composer(_topo(trace_paths=walks, contacts=[FAR])) + screen.note_viewport(9) # a short dialog budget: preview + heading + a few rows + body = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(screen.render_body(90))) + assert "Us (aa)" in body # the route preview is pinned, never scrolled out + assert "↓" in body and "more" in body # hidden rows are counted at the edge + screen.handle("end") # cursor to the last action row — the window follows + body = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(screen.render_body(90))) + assert "Cancel" in body and "↑" in body + + def test_composer_typed_hex_adds_a_custom_hop_and_backspace_removes() -> None: """Even-length hex typed into the filter becomes an addable custom hop.""" screen = _composer(_topo())