Files
MeshTerm/meshterm/ui/tui/frame.py
T
Jean-Pierre MartineauandClaude Opus 5 63cd4e5f96 Performance: SQLite WAL, lighter startup, per-platform tick rates
PicoCalc plan phase P2, driven by measurements taken on the Lyra as a
paired A/B (git archive HEAD vs the working tree, run side by side
against the same venv).

The headline is the database. Every packet the monitor hears is one
durable commit, and on the SD card each was costing 33.78 ms of fsync.
db._tune() opens in WAL with temp_store=MEMORY: 0.59 ms per commit, a
54x cut. synchronous=NORMAL is requested only once WAL is confirmed
engaged - the pragma returns the mode it settled on rather than raising
when a filesystem refuses it - because under WAL it risks the last
transactions to a power cut, and under the rollback journal it risks the
file itself. This device runs on a battery pack.

Startup: bleak/dbus-fast were already lazy; the real finds were two
cheap *values* dragging heavy subtrees. core/connection.py imports one
constant from core/channels.py, which imported PyCryptodome at module
level (224 ms of CPU-feature probing per run) - now deferred into the
two functions that decrypt. And tools/map.py's register_cli, which runs
for every tool at boot, reached into ui/map_screen.py for a --fraction
default, dragging the basemap's urllib.request -> http.client -> ssl
behind it; DEFAULT_VIEW_FRACTION moves to core/geo.py (pure arithmetic,
already on the boot path) and is re-exported so existing importers are
untouched. 26 modules and 316 ms of import self-time gone.

Per-frame: the corner glow only ever recolours truecolor foregrounds, so
on a 16-slot console it scanned every line of every frame to hand back
the identical list - skipped outright where effects are off, along with
the battery blink and the braille spinner cycle. _has_wide_glyph answers
from the platform when no emoji can be drawn instead of scanning the
composed frame (6.5-9.1 ms per repaint on its own). The header built its
segments twice to measure the compact separator, on exactly the narrow
terminals that take that branch every frame; it now builds once and
measures arithmetically. Together: 101.2 -> 73.2 ms per frame at 53x26,
151.8 -> 110.4 at 53x40, and 72x24 unregressed at 91.7.

That finally gave numbers to set the clocks against. refresh_interval
becomes per-platform tick_s (2.0 s on picocalc: a 1 Hz idle tick alone
was 7-11% of a core doing nothing, and only the header's per-minute
pulse drifts, since screens push their own repaints via invalidate).
The 0.12 s spinner was untenable - 84% of a core at 53x26, and at 53x40
it did not fit in its own interval at all. Five duplicate
_SPINNER_INTERVAL = 0.12 constants across the UI collapse into one
platform-aware spinner_interval() beside the Spinner it paces.

The header refactor was verified equivalent over 540 renders, plain text
and style spans both. The span check earned its keep: the first cut
passed style= to the Text constructor, which makes it the object's base
style and blankets everything appended after, so the version string
would have rendered brand-under-muted. test_header.py only asserted on
.plain and never saw it; it now pins the styling too.

tests/test_performance.py pins each contract as behaviour rather than
timing, including a subprocess guard that fails if Crypto, the network
stack, or the map screen ever creep back onto the startup import graph.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 03:40:42 -04:00

379 lines
18 KiB
Python

"""Composition helpers: turn a screen + terminal size into a bounded, framed ANSI view.
The session owns input and the screen stack; this module owns *layout* — slicing a screen's
body to a scroll viewport, wrapping it in a titled panel, and assembling the persistent
header and footer so the whole view fits the terminal exactly (never overflowing it).
"""
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 ...platforms import get_platform
from ..theme import hint_style, title_style
from .glow import apply_corner_glow
from .render import render_lines
from .screen import Screen
#: How many times :func:`_visible_slice` re-settles the scroll against the rows a screen
#: pins above it. Each pin costs a content row, so gaining one can push the highlighted row
#: back out of view and call for another nudge; two or three passes always reach a fixed
#: point at the pin counts screens actually use (a column header and a section heading).
_PIN_SETTLE_PASSES = 3
def _window_start(scroll: int, total: int, viewport: int, pinned: int) -> int:
"""The body line the visible window starts at, given ``pinned`` reserved top rows.
Normally the scroll offset itself. Scrolled fully to the bottom, the reserved rows must
not cost the *last* body lines (a chat's input row would vanish exactly when the
transcript fills the screen), so the window slides down by as many rows as are pinned —
the lines it drops are at the top, right under the pins, where they are stale.
"""
cap = max(1, viewport - pinned)
if scroll >= total - viewport and total > cap:
return min(scroll + pinned, total - cap)
return scroll
def _visible_slice(screen: Screen, lines: list[str], viewport: int) -> tuple[list[str], bool, bool]:
"""Clamp the screen's scroll and return the visible lines plus clip flags.
Keeps the screen's cursor line in view (for select/text screens) and clamps the scroll
offset to the content, then pads the slice to exactly ``viewport`` rows so the panel
always fills its allotted height. Any sticky rows the screen offers (a grouped list's
section heading that has scrolled off, over a table's column header — see
:meth:`Screen.sticky_rows`) are pinned to the top rows: each reserves one row, so the
cursor is kept within the remaining ``viewport - pinned`` and the bottom clamp is relaxed
by as many so the final content row can still reach the last visible line.
Args:
screen: The screen being rendered (its ``scroll`` is adjusted in place).
lines: The screen's full, unclipped body lines.
viewport: The visible body height in rows.
Returns:
A tuple of (padded visible lines, more-above, more-below).
"""
total = len(lines)
# Record the body height and viewport so the screen's shared scroll helpers can page by a
# screenful and clamp to the content (see :meth:`Screen.note_metrics`).
screen.note_metrics(total, viewport)
cursor = screen.cursor_line()
scroll = screen.scroll
if cursor is not None:
if cursor < scroll:
scroll = cursor
elif cursor >= scroll + viewport:
scroll = cursor - viewport + 1
scroll = max(0, min(scroll, max(0, total - viewport)))
# Each pinned row takes a top row, leaving that many fewer for content: nudge the scroll
# down if the cursor would fall in the reserved rows, then re-ask — moving can change
# which heading governs (crossing a section boundary pins another, or none), and a pin
# gained that way reserves one more row, which can call for a further nudge. Settles
# within _PIN_SETTLE_PASSES, since a screen pins at most a column header and a heading.
pinned = screen.sticky_rows(scroll) if scroll > 0 else []
for _ in range(_PIN_SETTLE_PASSES):
cap = max(1, viewport - len(pinned))
if not pinned or cursor is None or cursor < scroll + cap:
break
scroll = min(cursor - cap + 1, max(0, total - cap))
pinned = screen.sticky_rows(scroll) if scroll > 0 else []
screen.scroll = scroll
if pinned:
start = _window_start(scroll, total, viewport, len(pinned))
if start != scroll:
# The window slid down off the scroll offset, so the pins must describe the row
# it now *starts* at — otherwise a section heading among the dropped lines would
# simply vanish instead of being pinned. Re-ask, then re-settle the start against
# however many rows that reserves (never unpinning: the slide depends on it).
pinned = screen.sticky_rows(start) or pinned
start = _window_start(scroll, total, viewport, len(pinned))
cap = max(1, viewport - len(pinned))
visible = pinned + lines[start : start + cap]
more_below = start + cap < total
visible = visible + [""] * (viewport - len(visible))
return visible, True, more_below
visible = lines[scroll : scroll + viewport]
more_above = scroll > 0
more_below = scroll + viewport < total
visible = visible + [""] * (viewport - len(visible))
return visible, more_above, more_below
def _breathing_room(body_len: int, budget: int) -> int:
"""Rows of blank vertical padding a content-sized box should draw inside its borders.
Every popup box (:func:`compose_dialog` floats and the :func:`compose_startup` splash
boxes alike) aerates its layout with a blank row above and below the body whenever that
doesn't cost visible content; on a terminal too short for both, the content wins and the
box sits flush. Full-screen panels (:func:`compose_base`) deliberately skip this — they
hold dense content and would only waste rows.
Args:
body_len: The body's full height in rows.
budget: Rows the box may spend between its borders — on body and padding alike.
Returns:
The vertical padding (1 or 0) to pass to the panel.
"""
return 1 if body_len + 2 <= budget else 0
def _panel(screen: Screen, inner_w: int, viewport: int, active: bool) -> Panel:
"""Render a screen's body into a titled, scroll-aware panel.
Args:
screen: The screen to frame.
inner_w: Inner content width in columns.
viewport: Visible body height in rows.
active: Whether this is the focused (top) screen, brightening its border.
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))
border = "accent" if active else "muted"
subtitle = None
if more_above or more_below:
arrow = ("↑" if more_above else " ") + ("↓" if more_below else " ")
subtitle = f"[{hint_style(border)}]{arrow} more[/]"
return Panel(
body,
title=f"[{title_style(border)}]{screen.title}[/]" if screen.title else None,
subtitle=subtitle,
border_style=border,
padding=(0, 1),
)
def compose_base(
header: RenderableType,
base: Screen,
footer_hint: str,
cols: int,
rows: int,
) -> str:
"""Compose the full-screen ANSI view: header, the base screen's panel, and a footer.
Args:
header: The persistent header renderable (banner + live status).
base: The screen filling the background (the deepest non-floating layer).
footer_hint: The active screen's key hint, shown at the very bottom.
cols: Terminal width.
rows: Terminal height.
Returns:
An ANSI string of exactly ``rows`` lines, each within ``cols`` columns.
"""
# The header is a single status line: crop it to one row so a narrow terminal never
# wraps it onto a second line (which would push the panel down and misreport its height).
header_lines = render_lines(header, cols, no_wrap=True)
header_h = len(header_lines)
viewport = max(1, rows - header_h - 1 - 2) # minus footer(1) and panel border(2)
panel = _panel(base, cols - 4, viewport, active=True)
footer = Text.from_markup(f"[muted]{footer_hint}[/muted]")
# The glow pass lights the outer frame *and* any tool panels nested in the body. It only
# ever recolours truecolor foregrounds (see glow._advance_fg), so on a platform without
# effects — which is also a platform without truecolor — it would scan every line of
# every frame and hand back the identical list. Skipping it outright is the same picture
# for none of the work. Read live rather than bound at import: set_platform() runs in the
# CLI callback, long after this module is imported (see meshterm.platforms).
body = render_lines(Group(panel, footer), cols)
lines = header_lines + (apply_corner_glow(body) if get_platform().effects else body)
# Guarantee we never exceed the terminal height (pt would otherwise clip unpredictably).
if len(lines) > rows:
lines = lines[:rows]
else:
lines += [""] * (rows - len(lines))
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]:
"""Center the wordmark rows (already-coloured ANSI) as one left-aligned block.
Each row is padded to the block's widest display width first, so the shared left margin
keeps the art internally aligned rather than centering every row on its own axis.
"""
if not banner:
return []
widths = [cell_len(Text.from_ansi(row).plain) for row in banner]
width = max(widths)
padded = [row + " " * (width - w) for row, w in zip(banner, widths)]
return _center(padded, 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)
banner_h = len(banner)
gap = 1 if banner else 0 # the blank line under the banner
# The logo's own left margin and width, so the footnote below can hang off its right edge
# (the wordmark is centered as one block, so every row shares this margin).
raw_banner = screen.banner or []
logo_w = max((cell_len(Text.from_ansi(row).plain) for row in raw_banner), default=0)
logo_right = max(0, (cols - logo_w) // 2) + logo_w
# 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)
# Size to the fullest the footer can get, not this frame's — a screen whose hint grows
# as the highlight moves (a select's per-row "Del remove") reports that width here, so
# the box is reserved for it up front and never widens mid-navigation.
sizing_footer = getattr(screen, "sizing_footer_hint", screen.footer_hint)
inner_w = max(measured, cell_len(screen.title), cell_len(sizing_footer))
inner_w = max(10, min(inner_w, cols - 6))
# Pin the banner to a fixed vertical anchor that depends only on the terminal height and
# the banner's own (constant) height, so the wordmark never moves as the box below it
# swaps contents between splash states (device list → spinner → message). The box hangs
# from just under the banner and only *it* grows or shrinks; the logo stays put. The
# anchor sits at 2/5 of the terminal rather than the midline so the block reads centered
# once the device list has populated (the box only ever grows downward); the brief small
# states sit slightly high, the conventional optical placement for dialogs.
top = max(0, rows * 2 // 5 - banner_h - gap)
footnote_h = 1 if screen.footnote else 0 # the note sits directly under the logo
# Rows left for the box below the fixed banner block: the panel border is 2 rows.
below = rows - top - banner_h - footnote_h - gap
body_lines = screen.render_body(inner_w)
budget = below - 2
vpad = _breathing_room(len(body_lines), budget)
viewport = max(1, min(len(body_lines), budget - 2 * vpad))
visible, more_above, more_below = _visible_slice(screen, body_lines, viewport)
body = Text.from_ansi("\n".join(visible))
hint = hint_style("accent")
subtitle = f"[{hint}]{screen.footer_hint}[/]"
if more_above or more_below:
arrow = ("↑" if more_above else " ") + ("↓" if more_below else " ")
subtitle = f"[{hint}]{arrow} · {screen.footer_hint}[/]"
panel = Panel(
body,
title=f"[{title_style('accent')}]{screen.title}[/]" if screen.title else None,
subtitle=subtitle,
border_style="accent",
padding=(vpad, 1),
width=inner_w + 4,
)
# Glow before centering, while the box still starts at column 0 of its own lines.
panel_lines = _center(apply_corner_glow(render_lines(panel, inner_w + 4)), cols)
# A small muted line (e.g. a copyright notice) sits immediately under the logo, its right
# edge hung off the logo's right edge so the two read as one signed block.
footnote_lines: list[str] = []
if screen.footnote:
note = Text.from_markup(f"[muted]{screen.footnote}[/muted]")
rendered = render_lines(note, cell_len(screen.footnote))
pad = max(0, logo_right - cell_len(screen.footnote))
footnote_lines = [" " * pad + line for line in rendered]
block = banner + footnote_lines + ([""] * gap) + panel_lines
lines = [""] * top + block
if len(lines) > rows:
lines = lines[:rows]
else:
lines += [""] * (rows - len(lines))
return "\n".join(lines)
def _dialog_layout(screen: Screen, cols: int, rows: int) -> tuple[int, int, int, list[str]]:
"""Size a floating dialog: ``(outer_width, vpad, viewport, body_lines)``."""
# Most dialogs stretch to a generous cap; a screen may instead request a natural width
# (a short confirm sized to its content), still bounded to the terminal. A grow-only
# screen's natural width ratchets like its height, so the box never narrows either.
cap = min(cols - 6, 100)
natural = getattr(screen, "dialog_width", None)
max_w = cap if natural is None else max(24, min(cap, screen.ratchet_width(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
# re-centring smaller — the frame blank-pads the slack. The breathing room is taken
# from that ratcheted height, so the box stays put as the body shrinks below it.
body_h = screen.ratchet_viewport(max(1, len(body_lines)))
vpad = _breathing_room(body_h, budget)
viewport = min(budget - 2 * vpad, body_h)
return max_w, vpad, viewport, body_lines
def compose_dialog(screen: Screen, cols: int, rows: int) -> str:
"""Compose a centered dialog panel for a floating screen, bounded to the terminal.
Args:
screen: The floating (top) screen.
cols: Terminal width.
rows: Terminal height.
Returns:
An ANSI string sized to the dialog's content (never larger than the terminal).
"""
max_w, vpad, viewport, body_lines = _dialog_layout(screen, cols, rows)
visible, more_above, more_below = _visible_slice(screen, body_lines, viewport)
body = Text.from_ansi("\n".join(visible))
border = getattr(screen, "border_style", "accent")
hint = hint_style(border)
subtitle = f"[{hint}]{screen.footer_hint}[/]"
if more_above or more_below:
arrow = ("↑" if more_above else " ") + ("↓" if more_below else " ")
subtitle = f"[{hint}]{arrow} · {screen.footer_hint}[/]"
panel = Panel(
body,
title=f"[{title_style(border)}]{screen.title}[/]" if screen.title else None,
subtitle=subtitle,
border_style=border,
padding=(vpad, 1),
width=max_w,
)
return "\n".join(apply_corner_glow(render_lines(panel, max_w)))