Repaint the map's edge instead of the whole frame, and remember the mode
The braille base map leans on glyphs a terminal font may lack; the terminal draws each missing glyph as a double-width fallback, which shoves the row and smears the panel's right padding and border. prompt_toolkit's differential paint models those cells as single-width, so its picture of the screen diverges from the terminal and it never rewrites the smear. The previous fix forced a full-frame repaint every paint while in braille mode, which the 1s header-refresh tick turned into a visible periodic flicker. Replace it with a targeted scrub: after a move, force just the two right-edge columns (padding + border) to repaint by poking a sentinel into pt's cached frame. The map body redraws wholesale as it pans, so its interior self-heals; only the static edge needed help. Block mode can't smear, so it scrubs nothing. Also: - Persist the braille/block mode (app_state.map_block) so the map reopens the way it was left; braille stays the default. - Blank the frame on exit (drop pt's cached frame once) so the menu drawn underneath doesn't inherit leftover braille garbage. - Reword the t hint to "toggle braille/block". Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
ebac6c3a4f
commit
bfae10b387
5 files changed
+170
-28
No files matched your search
@@ -544,6 +544,32 @@ class Repository:
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
def get_map_block(self) -> bool:
|
||||
"""Return whether the map last used block-element mode (vs. the braille default).
|
||||
|
||||
Lets the interactive map reopen in whichever render mode the user last toggled to
|
||||
with ``t``. Defaults to ``False`` (braille, the higher-resolution default) when no
|
||||
preference has been saved or a stored value can't be parsed.
|
||||
"""
|
||||
row = self._conn.execute(
|
||||
"SELECT value FROM app_state WHERE key = 'map_block'"
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
return row["value"] == "1"
|
||||
|
||||
def set_map_block(self, block: bool) -> None:
|
||||
"""Persist the map render mode so the next session reopens the way it was left.
|
||||
|
||||
Args:
|
||||
block: ``True`` for 2×2 block elements, ``False`` for 2×4 braille.
|
||||
"""
|
||||
self._conn.execute(
|
||||
"INSERT OR REPLACE INTO app_state(key, value) VALUES ('map_block', ?)",
|
||||
("1" if block else "0",),
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
@staticmethod
|
||||
def _row_to_chat(row: sqlite3.Row) -> ChatMessage:
|
||||
"""Rebuild a :class:`ChatMessage` from a ``messages`` row."""
|
||||
|
||||
+46
-16
@@ -68,6 +68,8 @@ class MapScreen(Screen):
|
||||
*,
|
||||
saved_view: Optional[tuple[float, float, int]] = None,
|
||||
on_view_change: Optional[Callable[[Viewport], None]] = None,
|
||||
block: bool = False,
|
||||
on_block_change: Optional[Callable[[bool], None]] = None,
|
||||
view_fraction: float = DEFAULT_VIEW_FRACTION,
|
||||
) -> None:
|
||||
"""Create the map screen.
|
||||
@@ -81,6 +83,10 @@ class MapScreen(Screen):
|
||||
on, or ``None`` to frame the nodes instead.
|
||||
on_view_change: Called with the viewport whenever the centre or zoom changes, so
|
||||
the caller can persist it. Deduplicated — only actual changes fire it.
|
||||
block: Whether to open in 2×2 block-element mode rather than the braille default
|
||||
(the last-used mode, restored by the caller).
|
||||
on_block_change: Called with the new mode whenever ``t`` toggles it, so the
|
||||
caller can persist the preference.
|
||||
view_fraction: Fraction of the nodes the default frame (and ``r`` reset) fits —
|
||||
the densest that many, so outliers don't dominate. See :meth:`geo.Viewport.fit`.
|
||||
"""
|
||||
@@ -92,16 +98,21 @@ class MapScreen(Screen):
|
||||
self._max_tile_zoom = max_tile_zoom
|
||||
self._saved_view = saved_view
|
||||
self._on_view_change = on_view_change
|
||||
self._on_block_change = on_block_change
|
||||
self._view_fraction = view_fraction
|
||||
# The view last handed to ``on_view_change``; seeded with the restored view so
|
||||
# reopening unchanged doesn't rewrite it.
|
||||
self._last_saved = saved_view
|
||||
self._viewport: Optional[Viewport] = None
|
||||
self._size: tuple[int, int] = (0, 0) # (dot_w, dot_h) the viewport is built for
|
||||
# Draw the base map with 2×2 block elements instead of 2×4 braille. Off by default
|
||||
# (braille is higher-res); the user toggles it with ``t`` when their terminal font
|
||||
# can't render the full braille block and stray glyphs appear. See :mod:`mapcanvas`.
|
||||
self._block = False
|
||||
# Draw the base map with 2×2 block elements instead of 2×4 braille. Braille is the
|
||||
# higher-res default; the user toggles this with ``t`` when their terminal font can't
|
||||
# render the full braille block and stray glyphs appear. See :mod:`mapcanvas`.
|
||||
self._block = block
|
||||
# Ask the session to scrub the panel's right edge on the next paint (see
|
||||
# :meth:`consume_edge_scrub`). Seeded ``True`` so the first braille frame's edge is
|
||||
# cleaned even before the first pan.
|
||||
self._needs_scrub = True
|
||||
# Decoded tiles keyed by (z, x, y); a stored ``None`` means "fetched, empty/absent".
|
||||
self._tiles: dict[tuple[int, int, int], Optional[list[Layer]]] = {}
|
||||
self._pending: set[tuple[int, int, int]] = set()
|
||||
@@ -111,25 +122,32 @@ class MapScreen(Screen):
|
||||
@property
|
||||
def footer_hint(self) -> str: # type: ignore[override]
|
||||
"""Key hints plus a live tile-loading indicator."""
|
||||
mode = "block" if self._block else "braille"
|
||||
base = f"wasd/↑↓←→ pan (⇧ fine) · +/-/PgUp/PgDn zoom · r reset · t {mode} · Esc back"
|
||||
base = (
|
||||
"wasd/↑↓←→ pan (⇧ fine) · +/-/PgUp/PgDn zoom · r reset · "
|
||||
"t toggle braille/block · Esc back"
|
||||
)
|
||||
if self._pending:
|
||||
return f"{base} · [muted]loading {len(self._pending)} tiles…[/muted]"
|
||||
if not self._source.available:
|
||||
return f"{base} · [warn]offline — no basemap[/warn]"
|
||||
return base
|
||||
|
||||
@property
|
||||
def force_full_repaint(self) -> bool: # type: ignore[override]
|
||||
"""Force a full-frame repaint each paint while braille mode is active.
|
||||
def consume_edge_scrub(self) -> int:
|
||||
"""Right-edge columns the session should force-repaint on the next paint (0 = none).
|
||||
|
||||
A braille glyph the terminal font lacks gets substituted by a *double-width* fallback,
|
||||
which shoves the row and corrupts the panel's right border. prompt_toolkit's
|
||||
differential repaint then leaves that corruption until those cells are rewritten, so we
|
||||
force a full repaint to scrub it on every pan/zoom. Block mode uses only
|
||||
widely-supported glyphs, so it needs no such scrubbing.
|
||||
A braille glyph the terminal font lacks is substituted by a *double-width* fallback,
|
||||
which shoves the row and smears the panel's right padding and border. The map body
|
||||
itself redraws wholesale as it pans, so those cells self-heal — but the static edge
|
||||
does not change frame-to-frame, so prompt_toolkit's differential paint never rewrites
|
||||
it and the smear lingers there. After a move we ask the session to force just those
|
||||
two columns (right padding + border) to repaint, scrubbing the smear without the
|
||||
whole-frame flicker a full repaint would cause. Block mode can't smear, so it scrubs
|
||||
nothing.
|
||||
"""
|
||||
return not self._block
|
||||
if self._block or not self._needs_scrub:
|
||||
return 0
|
||||
self._needs_scrub = False
|
||||
return 2 # the panel's right padding cell and its right border cell
|
||||
|
||||
def render_body(self, width: int) -> list[str]:
|
||||
"""Build (or resize) the viewport, ensure its tiles, and render the frame."""
|
||||
@@ -236,6 +254,8 @@ class MapScreen(Screen):
|
||||
self._viewport = vp.zoomed(-1)
|
||||
elif action == "text":
|
||||
self._handle_key(data, vp)
|
||||
# Any handled key may have redrawn the body, so clean the right edge next paint.
|
||||
self._needs_scrub = True
|
||||
self._persist()
|
||||
|
||||
def _pan(self, vp: Viewport, direction: str, *, fine: bool) -> None:
|
||||
@@ -272,6 +292,8 @@ class MapScreen(Screen):
|
||||
)
|
||||
elif low == "t":
|
||||
self._block = not self._block # braille ⇄ block-element base map
|
||||
if self._on_block_change is not None:
|
||||
self._on_block_change(self._block)
|
||||
elif low == "q":
|
||||
self.resolve(None)
|
||||
|
||||
@@ -317,6 +339,14 @@ async def open_map(
|
||||
on_view_change=lambda vp: ctx.repo.set_map_view(
|
||||
vp.center_lat, vp.center_lon, vp.zoom
|
||||
),
|
||||
block=ctx.repo.get_map_block(),
|
||||
on_block_change=ctx.repo.set_map_block,
|
||||
view_fraction=fraction,
|
||||
)
|
||||
await session.run_screen(screen)
|
||||
try:
|
||||
await session.run_screen(screen)
|
||||
finally:
|
||||
# The map's braille may have smeared the terminal via double-width fallback glyphs
|
||||
# that prompt_toolkit's diff can't see; force one full repaint so the menu drawn
|
||||
# underneath starts from a clean slate rather than inheriting that garbage.
|
||||
session.request_full_repaint()
|
||||
@@ -51,11 +51,6 @@ class Screen:
|
||||
chrome: bool = True
|
||||
banner: Optional[Sequence[str]] = None
|
||||
footnote: Optional[str] = None
|
||||
#: When this is the base screen, force a full-frame repaint each paint instead of
|
||||
#: prompt_toolkit's differential update. A screen sets this when its body can emit glyphs
|
||||
#: the terminal renders at an unexpected width (see :class:`~meshterm.ui.map_screen.
|
||||
#: MapScreen`), which would otherwise leave stale cells the diff never scrubs.
|
||||
force_full_repaint: bool = False
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize scroll state and the (later-assigned) result future."""
|
||||
@@ -92,6 +87,16 @@ class Screen:
|
||||
"""
|
||||
return None
|
||||
|
||||
def consume_edge_scrub(self) -> int:
|
||||
"""Right-edge columns the session should force-repaint on the next paint (0 = none).
|
||||
|
||||
The default is 0 — no screen needs this. A screen whose body can emit glyphs the
|
||||
terminal renders at an unexpected width (the map's braille) overrides this to have the
|
||||
session redraw just the smeared edge cells, which prompt_toolkit's differential paint
|
||||
would otherwise never rewrite (see :class:`~meshterm.ui.map_screen.MapScreen`).
|
||||
"""
|
||||
return 0
|
||||
|
||||
def sticky_header(self, scroll: int) -> Optional[str]:
|
||||
"""An already-rendered body line to pin to the top row once ``scroll`` moves past it.
|
||||
|
||||
|
||||
@@ -112,20 +112,52 @@ class TuiSession:
|
||||
if self._app is not None:
|
||||
self._app.invalidate()
|
||||
|
||||
def _invalidate_last_frame(self) -> None:
|
||||
"""Drop prompt_toolkit's cached last frame so the next paint rewrites every cell.
|
||||
def request_full_repaint(self) -> None:
|
||||
"""Force the next paint to rewrite every cell, then schedule it.
|
||||
|
||||
prompt_toolkit repaints differentially: cells equal to the previous frame are left
|
||||
untouched. That is normally what we want, but it also means terminal-side corruption
|
||||
(a double-width fallback glyph shoving the panel's right border) is never scrubbed
|
||||
until those exact cells change. Clearing ``_last_screen`` forces a full redraw, so a
|
||||
screen that opts in via :attr:`Screen.force_full_repaint` self-heals on every paint.
|
||||
(a double-width fallback glyph the diff can't see) survives until those exact cells
|
||||
change. Callers use this when leaving a screen that could have smeared the terminal —
|
||||
the map — so the screen drawn underneath starts from a clean slate.
|
||||
"""
|
||||
self._invalidate_last_frame()
|
||||
self.invalidate()
|
||||
|
||||
def _invalidate_last_frame(self) -> None:
|
||||
"""Drop prompt_toolkit's cached last frame so the next paint rewrites every cell.
|
||||
|
||||
Touches a prompt_toolkit internal, so it fails soft if the attribute ever moves.
|
||||
"""
|
||||
renderer = getattr(self._app, "renderer", None)
|
||||
if renderer is not None and hasattr(renderer, "_last_screen"):
|
||||
renderer._last_screen = None
|
||||
|
||||
def _scrub_right_columns(self, count: int) -> None:
|
||||
"""Force prompt_toolkit to repaint the rightmost ``count`` columns on the next diff.
|
||||
|
||||
Overwrites those cells in pt's remembered last frame with a sentinel that can't equal
|
||||
any real content, so the differential renderer treats them as changed and redraws
|
||||
them — scrubbing a double-width fallback glyph that smeared over the panel's right
|
||||
edge, without the whole-frame flicker of dropping the entire cached frame. Touches a
|
||||
pt internal, so it fails soft if the structure ever moves.
|
||||
"""
|
||||
renderer = getattr(self._app, "renderer", None)
|
||||
last = getattr(renderer, "_last_screen", None)
|
||||
if last is None:
|
||||
return
|
||||
try:
|
||||
from prompt_toolkit.layout.screen import Char
|
||||
|
||||
buffer = last.data_buffer
|
||||
cols, _ = self._size()
|
||||
sentinel = Char("") # a non-character; never equals real cell content
|
||||
for x in range(max(0, cols - count), cols):
|
||||
for row in list(buffer.keys()):
|
||||
buffer[row][x] = sentinel
|
||||
except Exception: # noqa: BLE001 - a cosmetic scrub must never break rendering
|
||||
pass
|
||||
|
||||
# --- async prompt helpers ------------------------------------------------
|
||||
|
||||
async def run_screen(self, screen: Screen) -> Any:
|
||||
@@ -432,8 +464,9 @@ class TuiSession:
|
||||
base = self._base_screen()
|
||||
if base is None:
|
||||
return ANSI("")
|
||||
if getattr(base, "force_full_repaint", False):
|
||||
self._invalidate_last_frame()
|
||||
scrub = base.consume_edge_scrub()
|
||||
if scrub:
|
||||
self._scrub_right_columns(scrub)
|
||||
# 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:
|
||||
|
||||
@@ -393,6 +393,15 @@ def test_repository_round_trips_map_view(ctx) -> None:
|
||||
assert ctx.repo.get_map_view() == pytest.approx((40.0, -74.0, 9))
|
||||
|
||||
|
||||
def test_repository_round_trips_map_block(ctx) -> None:
|
||||
"""The saved map render mode persists and reads back; braille (False) by default."""
|
||||
assert ctx.repo.get_map_block() is False
|
||||
ctx.repo.set_map_block(True)
|
||||
assert ctx.repo.get_map_block() is True
|
||||
ctx.repo.set_map_block(False)
|
||||
assert ctx.repo.get_map_block() is False
|
||||
|
||||
|
||||
async def test_map_tool_reports_nothing_to_plot(ctx, monkeypatch) -> None:
|
||||
"""With no located contacts and no located history the tool returns cleanly."""
|
||||
async def _no_contacts(_ctx):
|
||||
@@ -526,6 +535,45 @@ def test_map_screen_restores_and_persists_view() -> None:
|
||||
assert saved[-1][2] == 13
|
||||
|
||||
|
||||
def test_map_screen_restores_and_persists_block_mode() -> None:
|
||||
"""The screen opens in the saved render mode and reports every ``t`` toggle."""
|
||||
from meshterm.ui.map_render import MapMarker
|
||||
from meshterm.ui.map_screen import MapScreen
|
||||
|
||||
modes: list[bool] = []
|
||||
screen = MapScreen(
|
||||
_StubSession(80, 24), [MapMarker("A", 45.5, -73.6)], _StubSource(), 14,
|
||||
block=True,
|
||||
on_block_change=modes.append,
|
||||
)
|
||||
screen.render_body(80)
|
||||
assert screen._block is True # restored to the saved block mode
|
||||
|
||||
screen.handle("text", "t") # toggle back to braille
|
||||
assert screen._block is False
|
||||
assert modes == [False]
|
||||
screen.handle("text", "t")
|
||||
assert modes == [False, True]
|
||||
|
||||
|
||||
def test_map_screen_scrubs_right_edge_in_braille_only() -> None:
|
||||
"""Braille mode asks the session to scrub the right edge after a move; block mode never does."""
|
||||
from meshterm.ui.map_render import MapMarker
|
||||
from meshterm.ui.map_screen import MapScreen
|
||||
|
||||
markers = [MapMarker("A", 45.5, -73.6)]
|
||||
braille = MapScreen(_StubSession(80, 24), markers, _StubSource(), 14)
|
||||
braille.render_body(80)
|
||||
braille.handle("text", "d") # a move flags the edge for a scrub
|
||||
assert braille.consume_edge_scrub() == 2 # right padding + border columns
|
||||
assert braille.consume_edge_scrub() == 0 # consumed — not repeated without another move
|
||||
|
||||
block = MapScreen(_StubSession(80, 24), markers, _StubSource(), 14, block=True)
|
||||
block.render_body(80)
|
||||
block.handle("text", "d")
|
||||
assert block.consume_edge_scrub() == 0 # block glyphs can't smear, so nothing to scrub
|
||||
|
||||
|
||||
def test_map_screen_escape_dismisses() -> None:
|
||||
"""Esc resolves the screen's future with None (backs out to the menu)."""
|
||||
import asyncio
|
||||
|
||||
Reference in new issue
Block a user