Render the map so any terminal font can show it
The braille base map and its labels lean on Unicode a terminal font may not have: 8-dot braille (U+2840-28FF) that many fonts omit, and place/node names in scripts or emoji outside a Latin monospace font. A missing glyph renders as double-width tofu, which both looks wrong and shoves the panel right border. - Prefer a romanized name (name:latin/name:en) over the local script, and strip labels to single-cell characters, so foreign names and emoji node names can no longer tofu or knock the grid out of alignment. - Add a block-element base-map mode, toggled with t: 2x2 quadrant blocks instead of 2x4 braille - half the vertical resolution, but glyphs essentially every monospace font has. Braille stays the default. - Zoom with PageUp/PageDown as well as +/-. - While braille mode is active, force a full repaint each paint so the double-width-fallback corruption on the right border is scrubbed on every move. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
bdbe5cce30
commit
6b84281d0b
6 files changed
+129
-8
No files matched your search
@@ -104,8 +104,15 @@ class Feature:
|
||||
|
||||
@property
|
||||
def name(self) -> Optional[str]:
|
||||
"""The feature's display name, preferring the local ``name`` then latin fallbacks."""
|
||||
for key in ("name", "name:latin", "name:en", "name_en", "name_int"):
|
||||
"""The feature's display name, preferring a romanized form over the local script.
|
||||
|
||||
The terminal map draws labels in a fixed-width cell grid with whatever font the
|
||||
user has, so a local-script name (CJK, Arabic, Thai…) tends to render as tofu or,
|
||||
being double-width, shove the row out of alignment. OpenMapTiles ships a
|
||||
transliterated ``name:latin`` (and often ``name:en``) beside the local ``name``, so
|
||||
prefer those; fall back to the local ``name`` only when no latin form exists.
|
||||
"""
|
||||
for key in ("name:latin", "name:en", "name_en", "name_int", "name"):
|
||||
val = self.tags.get(key)
|
||||
if val:
|
||||
return str(val)
|
||||
|
||||
@@ -133,6 +133,7 @@ def render_map(
|
||||
markers: list[MapMarker],
|
||||
*,
|
||||
max_labels: int = 80,
|
||||
block: bool = False,
|
||||
) -> list[str]:
|
||||
"""Render a full map frame to truecolour ANSI lines.
|
||||
|
||||
@@ -141,6 +142,8 @@ def render_map(
|
||||
tiles: Decoded layers keyed by ``(z, x, y)``; ``None`` values are pending/absent.
|
||||
markers: Mesh nodes to overlay.
|
||||
max_labels: Cap on basemap labels placed, to keep the map readable.
|
||||
block: Draw the base map with 2×2 block elements instead of 2×4 braille — the
|
||||
compatibility mode for terminals that can't render the full braille block.
|
||||
|
||||
Returns:
|
||||
One ANSI string per row, ready for the TUI frame or the console.
|
||||
@@ -165,7 +168,7 @@ def render_map(
|
||||
if canvas.place_label(label.x, label.y, label.text, label.color, bold=label.bold):
|
||||
placed += 1
|
||||
|
||||
return canvas.to_ansi_lines()
|
||||
return canvas.to_ansi_lines(block=block)
|
||||
|
||||
|
||||
def _draw_tile(frame: _Frame, layers: list[Layer], z: int, x: int, y: int) -> None:
|
||||
|
||||
@@ -98,6 +98,10 @@ class MapScreen(Screen):
|
||||
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
|
||||
# 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()
|
||||
@@ -107,13 +111,26 @@ class MapScreen(Screen):
|
||||
@property
|
||||
def footer_hint(self) -> str: # type: ignore[override]
|
||||
"""Key hints plus a live tile-loading indicator."""
|
||||
base = "wasd/↑↓←→ pan (⇧ fine) · +/- zoom · r reset · Esc back"
|
||||
mode = "block" if self._block else "braille"
|
||||
base = f"wasd/↑↓←→ pan (⇧ fine) · +/-/PgUp/PgDn zoom · r reset · t {mode} · 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.
|
||||
|
||||
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.
|
||||
"""
|
||||
return not self._block
|
||||
|
||||
def render_body(self, width: int) -> list[str]:
|
||||
"""Build (or resize) the viewport, ensure its tiles, and render the frame."""
|
||||
_, cell_h = self._session.base_body_size()
|
||||
@@ -131,7 +148,7 @@ class MapScreen(Screen):
|
||||
self.title = self._title(self._viewport)
|
||||
self._persist()
|
||||
tiles = {t: self._tiles.get(t) for t in self._viewport.tiles(self._max_tile_zoom)}
|
||||
return render_map(self._viewport, tiles, self._markers)
|
||||
return render_map(self._viewport, tiles, self._markers, block=self._block)
|
||||
|
||||
def _initial_viewport(self, dot_w: int, dot_h: int) -> Viewport:
|
||||
"""Restore the saved view (clamped to sane bounds) or frame the nodes' dense core.
|
||||
@@ -213,6 +230,10 @@ class MapScreen(Screen):
|
||||
self._pan(vp, action, fine=False)
|
||||
elif action.startswith("shift_") and action[len("shift_"):] in _PAN_DIRS:
|
||||
self._pan(vp, action[len("shift_"):], fine=True)
|
||||
elif action == "pageup":
|
||||
self._viewport = vp.zoomed(1, max_zoom=self._max_tile_zoom + _OVERZOOM)
|
||||
elif action == "pagedown":
|
||||
self._viewport = vp.zoomed(-1)
|
||||
elif action == "text":
|
||||
self._handle_key(data, vp)
|
||||
self._persist()
|
||||
@@ -249,6 +270,8 @@ class MapScreen(Screen):
|
||||
max_zoom=self._max_tile_zoom,
|
||||
fraction=self._view_fraction,
|
||||
)
|
||||
elif low == "t":
|
||||
self._block = not self._block # braille ⇄ block-element base map
|
||||
elif low == "q":
|
||||
self.resolve(None)
|
||||
|
||||
|
||||
@@ -14,17 +14,72 @@ truecolour ANSI lines, which is exactly what the TUI frame consumes.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unicodedata
|
||||
from typing import Optional
|
||||
|
||||
#: Unicode braille pattern base; add a dot bitmask to get the glyph.
|
||||
_BRAILLE_BASE = 0x2800
|
||||
|
||||
|
||||
def single_cell(text: str) -> str:
|
||||
"""Reduce ``text`` to characters that render in exactly one fixed-width cell.
|
||||
|
||||
The map is a fixed-width grid drawn with whatever font the terminal happens to have, and
|
||||
the layout assumes every label character advances exactly one column. Three kinds of
|
||||
character break that: control/format codes, combining marks (which stack onto the previous
|
||||
cell), and East-Asian *wide*/*fullwidth* glyphs and emoji (which take two columns and so
|
||||
shove the rest of the row out of alignment). Those are also the characters least likely to
|
||||
exist in a typical monospace font, so they surface as tofu. Dropping them keeps labels
|
||||
legible in the Latin/Cyrillic/Greek range fonts reliably cover; a label that is *only*
|
||||
such characters (e.g. an all-emoji node name) collapses to empty and is simply not drawn.
|
||||
"""
|
||||
out: list[str] = []
|
||||
for ch in text:
|
||||
if ch == " ":
|
||||
out.append(ch)
|
||||
continue
|
||||
if unicodedata.category(ch)[0] == "C": # control, format, surrogate, unassigned
|
||||
continue
|
||||
if unicodedata.combining(ch):
|
||||
continue
|
||||
if unicodedata.east_asian_width(ch) in ("W", "F"):
|
||||
continue
|
||||
out.append(ch)
|
||||
return "".join(out).strip()
|
||||
|
||||
#: Dot bit for each (col, row) within a cell — the Unicode braille standard layout.
|
||||
_DOT_BITS = (
|
||||
(0x01, 0x02, 0x04, 0x40), # left column, rows 0..3
|
||||
(0x08, 0x10, 0x20, 0x80), # right column, rows 0..3
|
||||
)
|
||||
|
||||
#: Quadrant block-element glyphs indexed by a 4-bit mask (bit 0 top-left, 1 top-right,
|
||||
#: 2 bottom-left, 3 bottom-right). These are the *block-mode* fallback for terminals whose
|
||||
#: font can't render the full braille block: a cell's 2×4 dots collapse to a 2×2 quadrant,
|
||||
#: halving the vertical resolution but using glyphs that exist in essentially every
|
||||
#: monospace font (unlike 8-dot braille, U+2840–28FF, which fonts routinely omit).
|
||||
_QUADRANTS = (
|
||||
" ", "▘", "▝", "▀", # · ▘ ▝ ▀
|
||||
"▖", "▌", "▞", "▛", # ▖ ▌ ▞ ▛
|
||||
"▗", "▚", "▐", "▜", # ▗ ▚ ▐ ▜
|
||||
"▄", "▙", "▟", "█", # ▄ ▙ ▟ █
|
||||
)
|
||||
|
||||
|
||||
def _quadrant_glyph(bits: int) -> str:
|
||||
"""Collapse an 8-dot braille bitmask to its 2×2 quadrant block glyph.
|
||||
|
||||
A quadrant is filled when any braille dot inside it is lit: top rows (0–1) vs bottom rows
|
||||
(2–3), left column vs right. Used only by block mode; braille mode emits the dots directly.
|
||||
"""
|
||||
mask = (
|
||||
(1 if bits & 0x03 else 0) # top-left: left col, rows 0–1
|
||||
| (2 if bits & 0x18 else 0) # top-right: right col, rows 0–1
|
||||
| (4 if bits & 0x44 else 0) # bottom-left: left col, rows 2–3
|
||||
| (8 if bits & 0xA0 else 0) # bottom-right: right col, rows 2–3
|
||||
)
|
||||
return _QUADRANTS[mask]
|
||||
|
||||
RGB = tuple[int, int, int]
|
||||
|
||||
|
||||
@@ -162,6 +217,7 @@ class MapCanvas:
|
||||
free the label is dropped and just the marker glyph shows, so a crowded map stays
|
||||
legible. Returns whether the label was placed.
|
||||
"""
|
||||
text = single_cell(text)
|
||||
if not text:
|
||||
return False
|
||||
cx, cy = x >> 1, y >> 2
|
||||
@@ -187,6 +243,9 @@ class MapCanvas:
|
||||
Returns:
|
||||
``True`` if placed, ``False`` if it fell off-canvas or overlapped existing text.
|
||||
"""
|
||||
text = single_cell(text)
|
||||
if not text:
|
||||
return False
|
||||
cx = int(x) >> 1
|
||||
cy = int(y) >> 2
|
||||
start = cx - len(text) // 2
|
||||
@@ -235,8 +294,15 @@ class MapCanvas:
|
||||
|
||||
# -- output -----------------------------------------------------------------
|
||||
|
||||
def to_ansi_lines(self) -> list[str]:
|
||||
"""Render the canvas to one truecolour ANSI string per row."""
|
||||
def to_ansi_lines(self, *, block: bool = False) -> list[str]:
|
||||
"""Render the canvas to one truecolour ANSI string per row.
|
||||
|
||||
Args:
|
||||
block: Draw the base-map dots as 2×2 quadrant block elements instead of 2×4
|
||||
braille. Overlays (labels, markers) are unaffected. This is the compatibility
|
||||
mode for terminals whose font can't render the full braille block — block
|
||||
elements are near-universally available, at half the vertical resolution.
|
||||
"""
|
||||
reset = "\x1b[0m"
|
||||
lines: list[str] = []
|
||||
for cy in range(self.cell_h):
|
||||
@@ -247,7 +313,8 @@ class MapCanvas:
|
||||
if overlay is not None:
|
||||
ch, color, bold = overlay
|
||||
elif self._bits[cy][cx]:
|
||||
ch = chr(_BRAILLE_BASE + self._bits[cy][cx])
|
||||
bits = self._bits[cy][cx]
|
||||
ch = _quadrant_glyph(bits) if block else chr(_BRAILLE_BASE + bits)
|
||||
color = self._color[cy][cx] or (128, 128, 128)
|
||||
bold = False
|
||||
else:
|
||||
|
||||
@@ -51,6 +51,11 @@ 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."""
|
||||
|
||||
@@ -112,6 +112,20 @@ 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.
|
||||
|
||||
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.
|
||||
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
|
||||
|
||||
# --- async prompt helpers ------------------------------------------------
|
||||
|
||||
async def run_screen(self, screen: Screen) -> Any:
|
||||
@@ -404,6 +418,8 @@ class TuiSession:
|
||||
base = self._base_screen()
|
||||
if base is None:
|
||||
return ANSI("")
|
||||
if getattr(base, "force_full_repaint", False):
|
||||
self._invalidate_last_frame()
|
||||
# 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:
|
||||
|
||||
Reference in new issue
Block a user