Frame: draw only what shows, and stop handing dialogs away
Two halves of the same paint. A screen renders its body whole and the frame then slices a viewport out of it, so a 141-contact list rasterized 150 rows to show the twenty that fit — on every keystroke and on every idle tick. A select screen now plans its body and hands over one callable per row; the count, the cursor, and the sticky landmarks are all still exact (they are layout, not drawing), but only the sliced rows are ever built. A row's live callable title is resolved only while it is on screen. 3.2x on the body. And a floating dialog dropped the whole frame onto prompt_toolkit's renderer, paying its full grid rebuild and diff — 70-125 ms per keystroke in every confirm, picker and viewer in the app. There is nothing in that placement we cannot do: an unanchored, unsized float is centred. So the frame source composites the boxes itself, cell-accurately, memoized per row; the rows a box does not reach come back as the same strings, which is what lets the row diff skip them. The busy overlay, a content-sized window the float container measures, is still prompt_toolkit's to place. The row writer also stops writing entirely when the frame is unchanged — an empty write leaves the panel's damage region empty, so the display never flushes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c9aa9a410d
commit
2decbcf754
7 files changed
+472
-37
No files matched your search
@@ -330,8 +330,15 @@ def test_fastrender_erases_before_it_draws_so_a_full_row_keeps_its_last_cell() -
|
||||
assert not chunk.rstrip().endswith("\x1b[K"), chunk[-40:]
|
||||
|
||||
|
||||
def test_fastrender_hands_dialogs_back_to_prompt_toolkit(monkeypatch) -> None: # noqa: ANN001
|
||||
"""A ``None`` frame means a float is up, which pt lays out — it must own that paint."""
|
||||
def test_fastrender_hands_a_frame_it_cannot_place_back_to_prompt_toolkit(
|
||||
monkeypatch, # noqa: ANN001
|
||||
) -> None:
|
||||
"""A ``None`` frame means the session declined to place it — pt must own that paint.
|
||||
|
||||
The session answers ``None`` for the frames it does not lay out itself: the busy
|
||||
overlay, which the float container measures and centres as a content-sized window, and
|
||||
an empty stack, which has no background at all.
|
||||
"""
|
||||
from prompt_toolkit.renderer import Renderer
|
||||
from prompt_toolkit.styles import Style
|
||||
|
||||
@@ -346,3 +353,88 @@ def test_fastrender_hands_dialogs_back_to_prompt_toolkit(monkeypatch) -> None:
|
||||
assert calls == [True]
|
||||
assert renderer.slow_paints == 1
|
||||
assert renderer.fast_paints == 0
|
||||
|
||||
|
||||
def test_fastrender_writes_nothing_at_all_when_the_frame_is_unchanged() -> None:
|
||||
"""The idle tick's frame is usually identical, and identical must cost no bytes.
|
||||
|
||||
Not merely fewer bytes: an empty write leaves the panel's damage region empty, so the
|
||||
display never flushes and the SPI bus stays quiet between real changes.
|
||||
"""
|
||||
same = "\n".join(f"row {i:02d}" for i in range(26))
|
||||
renderer, out = _fast_renderer([same, same])
|
||||
|
||||
renderer.render(None, None) # first paint: everything
|
||||
out.written.clear()
|
||||
renderer.render(None, None) # the tick: nothing moved
|
||||
|
||||
assert out.written == []
|
||||
assert renderer.fast_paints == 2
|
||||
|
||||
|
||||
# --- dialogs stay on the fast path ---------------------------------------------------
|
||||
|
||||
|
||||
def test_a_dialog_is_composited_onto_the_frame_rather_than_handed_to_prompt_toolkit() -> None:
|
||||
"""A float used to drop the whole frame onto pt's renderer — and pay its grid rebuild.
|
||||
|
||||
The placement is reproducible: an unanchored float with no size of its own is centred
|
||||
on the frame. So the box is merged in here, the row diff still applies, and the rows
|
||||
the box does not reach come back as the *same strings* — which is what lets the diff
|
||||
skip them.
|
||||
"""
|
||||
from meshterm.ui.tui.frame import composite_float
|
||||
|
||||
base = [f"{i:02d}" + "." * 51 for i in range(26)]
|
||||
box = "\n".join(["+" + "-" * 18 + "+"] + ["|" + " " * 18 + "|"] * 4
|
||||
+ ["+" + "-" * 18 + "+"])
|
||||
out = composite_float(base, box, 53, 26)
|
||||
|
||||
assert len(out) == 26
|
||||
# Six box rows, centred vertically: (26 - 6) // 2 = 10.
|
||||
for i in list(range(10)) + list(range(16, 26)):
|
||||
assert out[i] is base[i], f"row {i} was rewritten for nothing"
|
||||
# Centred horizontally too: (53 - 20) // 2 = 16 cells of the base still on the left.
|
||||
plain = _plain_row(out[10])
|
||||
assert plain.startswith("10" + "." * 14)
|
||||
assert plain[16:36] == "+" + "-" * 18 + "+"
|
||||
assert plain[36:].startswith(".")
|
||||
assert len(plain) == 53
|
||||
|
||||
|
||||
def test_a_composited_row_keeps_the_styling_of_both_sides() -> None:
|
||||
"""The merge is cell-accurate over *styled* rows — the base's colour must survive it."""
|
||||
from rich.text import Text
|
||||
|
||||
from meshterm.ui.tui.frame import composite_float
|
||||
from meshterm.ui.tui.render import render_to_ansi
|
||||
|
||||
base = [render_to_ansi(Text("x" * 53, style="bold red"), 53)] * 10
|
||||
box = render_to_ansi(Text("[ ok ]", style="bold green"), 6)
|
||||
out = composite_float(base, box, 53, 10)
|
||||
|
||||
row = out[(10 - 1) // 2]
|
||||
assert "[ ok ]" in _plain_row(row)
|
||||
assert row.count("\x1b[") > 2, "styling was flattened by the merge"
|
||||
|
||||
|
||||
def test_stacked_dialogs_composite_in_z_order() -> None:
|
||||
"""A confirm over a picker over a menu: each box lands on the frame below it."""
|
||||
from meshterm.ui.tui.frame import composite_float
|
||||
|
||||
rows = ["." * 53 for _ in range(26)]
|
||||
rows = composite_float(rows, "\n".join(["under" + "." * 15] * 8), 53, 26)
|
||||
rows = composite_float(rows, "\n".join(["OVER"] * 2), 53, 26)
|
||||
|
||||
middle = _plain_row(rows[12])
|
||||
# The lower box is 20 cells wide, so it starts at (53 - 20) // 2 = 16; the 4-cell box
|
||||
# above it starts at 24 and covers the lower one's middle without disturbing its edges.
|
||||
assert middle.startswith("." * 16 + "under")
|
||||
assert middle[24:28] == "OVER"
|
||||
|
||||
|
||||
def _plain_row(row: str) -> str:
|
||||
"""The row's text with its ANSI escapes stripped."""
|
||||
import re
|
||||
|
||||
return re.sub(r"\x1b\[[0-9;]*m", "", row)
|
||||
@@ -19,6 +19,7 @@ from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from meshterm import copyright_notice
|
||||
from tests.conftest import plain as _plain
|
||||
from meshterm.ui.menus import section_heading
|
||||
from meshterm.ui.tui import frame, glow
|
||||
from meshterm.ui.tui.glow import apply_corner_glow
|
||||
@@ -2496,3 +2497,146 @@ def test_select_hscroll_leaves_the_detail_line_unshifted() -> None:
|
||||
screen.handle("right")
|
||||
lines = _row_plains(screen, 40)
|
||||
assert "weakest -6.0 dB" in lines[1]
|
||||
|
||||
|
||||
# --- the fast path's frame source ----------------------------------------------------
|
||||
|
||||
|
||||
def _framed_session():
|
||||
"""A session with just enough of an app behind it to compose a frame at 53x26."""
|
||||
import types
|
||||
|
||||
from prompt_toolkit.data_structures import Size
|
||||
|
||||
session = TuiSession()
|
||||
session._app = types.SimpleNamespace(
|
||||
renderer=types.SimpleNamespace(_last_screen=None),
|
||||
output=types.SimpleNamespace(get_size=lambda: Size(rows=26, columns=53)),
|
||||
invalidate=lambda: None,
|
||||
)
|
||||
return session
|
||||
|
||||
|
||||
def test_a_dialog_frame_is_composed_here_not_handed_to_prompt_toolkit() -> None:
|
||||
"""A float used to send the whole frame down prompt_toolkit's renderer.
|
||||
|
||||
That cost its full grid rebuild and diff on every keystroke — in every confirm, picker
|
||||
and viewer in the app. The float's placement is reproducible (an unanchored, unsized
|
||||
float is centred), so the frame source returns the finished picture with the box merged
|
||||
in, and the row diff applies to dialogs like everything else.
|
||||
"""
|
||||
session = _framed_session()
|
||||
session.push(ScrollScreen(Text("the list beneath"), title="Nodes", floating=False))
|
||||
session.push(ButtonDialog("Remove this contact?", [("Cancel", 0), ("Remove", 1)]))
|
||||
|
||||
text = session._plain_frame()
|
||||
assert text is not None, "a dialog must not fall back to prompt_toolkit"
|
||||
rows = text.split("\n")
|
||||
assert len(rows) == 26
|
||||
body = "\n".join(rows)
|
||||
assert "Remove this contact?" in _plain(body)
|
||||
assert "the list beneath" in _plain(body), "the backdrop must show around the box"
|
||||
|
||||
|
||||
def test_the_busy_overlay_is_still_prompt_toolkits_to_place() -> None:
|
||||
"""The one float we don't place: a content-sized window the float container measures."""
|
||||
from meshterm.ui.tui.overlay import BusyOverlay
|
||||
|
||||
session = _framed_session()
|
||||
assert session._plain_frame() is None # an empty stack has no background either
|
||||
overlay = BusyOverlay(title="Starting up")
|
||||
overlay.started_at -= overlay.hold + overlay.fade # past the hold: it is on screen
|
||||
session._overlay = overlay
|
||||
assert session._overlay_visible()
|
||||
assert session._plain_frame() is None
|
||||
|
||||
|
||||
def test_the_rows_a_dialog_does_not_reach_come_back_unchanged() -> None:
|
||||
"""What makes compositing worth doing: the diff still skips the untouched rows."""
|
||||
session = _framed_session()
|
||||
session.push(ScrollScreen(Text("\n".join(f"line {i}" for i in range(40))),
|
||||
title="Nodes", floating=False))
|
||||
first = session._plain_frame().split("\n")
|
||||
session.push(ButtonDialog("Sure?", [("Cancel", 0), ("Yes", 1)]))
|
||||
second = session._plain_frame().split("\n")
|
||||
|
||||
unchanged = sum(1 for a, b in zip(first, second) if a == b)
|
||||
assert unchanged >= 10, "the box should only rewrite the rows it covers"
|
||||
|
||||
|
||||
# --- the body is drawn one viewport at a time ----------------------------------------
|
||||
|
||||
|
||||
def test_a_long_list_only_rasterizes_the_rows_the_viewport_shows() -> None:
|
||||
"""141 contacts laid out 150 rows tall still only shows twenty of them.
|
||||
|
||||
Rendering the rest was pure waste on every keystroke *and* on the once-a-second tick.
|
||||
The line count has to stay exact, though — the scroll clamp, the ``↑↓ more`` markers and
|
||||
the sticky-header offsets are all measured against it.
|
||||
"""
|
||||
from meshterm.ui.tui.screen import LazyLines
|
||||
|
||||
drawn: list[int] = []
|
||||
|
||||
def title(i: int):
|
||||
def build():
|
||||
drawn.append(i)
|
||||
return f"contact {i:03d}"
|
||||
|
||||
return build
|
||||
|
||||
screen = SelectScreen("Contacts", [Choice(title(i), i) for i in range(150)])
|
||||
lines = screen.render_body(53)
|
||||
|
||||
assert isinstance(lines, LazyLines)
|
||||
assert len(lines) == 150 # the count is exact and cost nothing
|
||||
assert drawn == [], "no row is rasterized until something reads it"
|
||||
|
||||
window = lines[0:20]
|
||||
assert len(window) == 20
|
||||
assert sorted(drawn) == list(range(20))
|
||||
assert "contact 000" in _plain(window[0])
|
||||
|
||||
lines[5] # a re-read is memoized, never a second render
|
||||
assert sorted(drawn) == list(range(20))
|
||||
|
||||
|
||||
def test_a_lazy_body_slices_frames_and_scrolls_exactly_as_a_list_did() -> None:
|
||||
"""The substitution has to be invisible to the frame: same height, same clip flags.
|
||||
|
||||
Deferring a row's *drawing* must never defer how many rows there are — the scroll
|
||||
clamp, the ``↑↓ more`` subtitle and the pinned heading are all measured against that
|
||||
count, and every one of them would go wrong if the tail were merely unbuilt.
|
||||
"""
|
||||
items = [section_heading("Group")]
|
||||
items += [Choice(f"row {i}", i) for i in range(60)]
|
||||
screen = SelectScreen("Long", items, footer_hint="Esc back")
|
||||
screen.floating = False
|
||||
|
||||
out = frame.compose_base(Text("hdr"), screen, "Esc back", 53, 26)
|
||||
assert len(out.split("\n")) == 26
|
||||
plain = _plain(out)
|
||||
assert "row 0" in plain and "↓ more" in plain
|
||||
assert screen._scroll_total == 61 # the whole body is still measured
|
||||
|
||||
for _ in range(45): # walk the highlight past the fold
|
||||
screen.handle("down")
|
||||
plain = _plain(frame.compose_base(Text("hdr"), screen, "Esc back", 53, 26))
|
||||
assert "row 45" in plain, "the highlight must still be kept in view"
|
||||
assert "row 0 " not in plain, "the top of the list should have scrolled away"
|
||||
assert "── Group ──" in plain, "the section heading pins once it scrolls off"
|
||||
|
||||
|
||||
def test_an_off_screen_rows_live_title_is_left_alone() -> None:
|
||||
"""A row's callable title is resolved only while the row is actually on screen."""
|
||||
calls: list[str] = []
|
||||
items = [
|
||||
Choice(lambda: (calls.append("top"), "top row")[1], 0),
|
||||
*[Choice(f"filler {i}", i) for i in range(1, 40)],
|
||||
Choice(lambda: (calls.append("bottom"), "bottom row")[1], 40),
|
||||
]
|
||||
screen = SelectScreen("Live", items)
|
||||
screen.floating = False
|
||||
lines = screen.render_body(53)
|
||||
lines[0:10]
|
||||
assert calls == ["top"]
|
||||
Reference in new issue
Block a user