Add an interactive braille OpenStreetMap map of mesh nodes
New `map` tool (menu + `meshtools map` CLI) that plots the mesh's location-sharing nodes over a real OSM street basemap rendered as Unicode braille — streets, rivers, water, and place names — the mapscii idea, but able to plot our own nodes and live inside the TUI. - core/mvt.py: dependency-free MVT/protobuf vector-tile decoder. - core/geo.py: Web Mercator + a pannable/zoomable Viewport and tile math. - services/basemap.py: OpenFreeMap vector tiles (free, no API key), resolved from the versioned TileJSON, disk-cached, offline-safe (stdlib urllib only). - ui/mapcanvas.py: colored braille canvas (per-cell priority, line raster, polygon fill, collision-avoided labels), emits truecolor ANSI. - ui/map_render.py: compositor — basemap styling + node markers with names. - ui/map_screen.py: full-screen screen; wasd/arrows pan, =/- zoom, r reset, Esc/q exit; background tile loading. Offline falls back to nodes on a grid. - tools/map.py: interactive in the menu, one-shot static render on the CLI. Repeaters are prioritised over leaf nodes via advert type: threaded `node_type` through Observation/HeardNode and the persistence layer (schema v4->v5, with an idempotent migration adding observations.node_type). Added TuiSession.base_body_size() so a full-screen screen can size itself to the frame. Tests: tests/test_map.py (24) cover MVT decode against a real cached tile fixture, projection, the canvas, the compositor, offline behavior, and the interactive pan/zoom/reset logic. Full suite: 261 passing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
a03dedb09c
commit
d652a4e012
14 files changed
+2233
-7
No files matched your search
@@ -0,0 +1,313 @@
|
||||
"""Compose a rendered map frame: basemap geometry, labels, and mesh nodes.
|
||||
|
||||
Given a :class:`~meshtools.core.geo.Viewport` and the decoded vector tiles covering it, this
|
||||
projects every street, river, water body and place label onto a :class:`MapCanvas`, then
|
||||
overlays the mesh nodes with their names on top. It is pure and synchronous — tile *fetching*
|
||||
happens elsewhere (:mod:`meshtools.services.basemap`) — so both the interactive screen and
|
||||
the one-shot CLI render call the same code.
|
||||
|
||||
Colours target a dark terminal (the app theme): warm roads, grey minor streets, blue water
|
||||
and rivers, faint green parks. Because a cell shows one colour, draw priorities keep the
|
||||
important feature visible where things overlap (rivers over water, major roads over minor).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
from ..core.geo import Viewport
|
||||
from ..core.mvt import GEOM_LINE, GEOM_POLYGON, Layer
|
||||
from .mapcanvas import RGB, MapCanvas, parse_hex
|
||||
|
||||
# -- node markers -------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MapMarker:
|
||||
"""One mesh node to overlay on the map.
|
||||
|
||||
Attributes:
|
||||
label: Node name shown beside the marker.
|
||||
lat: Latitude in decimal degrees.
|
||||
lon: Longitude in decimal degrees.
|
||||
is_repeater: Whether the node is a repeater (prioritised marker).
|
||||
is_self: Whether this is our own node (highlighted).
|
||||
detail: Extra text for the CLI legend (e.g. ``"18 pkts · +6.0 dB"``).
|
||||
"""
|
||||
|
||||
label: str
|
||||
lat: float
|
||||
lon: float
|
||||
is_repeater: bool = False
|
||||
is_self: bool = False
|
||||
detail: str = ""
|
||||
|
||||
def _rank(self) -> int:
|
||||
"""Draw order: self on top of repeaters on top of leaf nodes."""
|
||||
return 2 if self.is_self else (1 if self.is_repeater else 0)
|
||||
|
||||
|
||||
_SELF = ("★", "#ffffff")
|
||||
_REPEATER = ("▲", "#ff5d73")
|
||||
_NODE = ("●", "#22d3ee")
|
||||
|
||||
|
||||
# -- basemap styling ----------------------------------------------------------
|
||||
|
||||
# Road class -> (colour, priority). Higher priority wins a shared cell.
|
||||
_ROAD_STYLE: dict[str, tuple[str, int]] = {
|
||||
"motorway": ("#f2a13d", 27),
|
||||
"trunk": ("#f2a13d", 26),
|
||||
"primary": ("#e8b24a", 25),
|
||||
"secondary": ("#d7c257", 24),
|
||||
"tertiary": ("#a7adb8", 23),
|
||||
"minor": ("#828894", 21),
|
||||
"unclassified": ("#828894", 21),
|
||||
"residential": ("#828894", 21),
|
||||
"living_street": ("#767c88", 20),
|
||||
"service": ("#5f646e", 19),
|
||||
"pedestrian": ("#5a5f69", 15),
|
||||
"path": ("#4b5560", 12),
|
||||
"track": ("#4b5560", 12),
|
||||
"footway": ("#454e58", 11),
|
||||
"cycleway": ("#455864", 12),
|
||||
}
|
||||
_ROAD_DEFAULT = ("#5f646e", 18)
|
||||
_RAIL = ("#8a8f98", 22)
|
||||
|
||||
# Waterway class -> (colour, priority).
|
||||
_WATERWAY_STYLE: dict[str, tuple[str, int]] = {
|
||||
"river": ("#49b0ec", 30),
|
||||
"canal": ("#49b0ec", 30),
|
||||
"stream": ("#3f8fbf", 29),
|
||||
"ditch": ("#3a7ba6", 28),
|
||||
"drain": ("#3a7ba6", 28),
|
||||
}
|
||||
_WATER_FILL = ("#153b56", 6)
|
||||
_GREEN_FILL = ("#173a29", 4)
|
||||
_GREEN_CLASSES = {"wood", "forest", "grass", "park", "meadow", "scrub", "wetland", "cemetery"}
|
||||
|
||||
# Label styling per place class: (colour, bold, rank, min_display_zoom). Lower rank places
|
||||
# claim screen space first; min zoom hides the fine detail until you zoom in.
|
||||
_PLACE_STYLE: dict[str, tuple[str, bool, int, int]] = {
|
||||
"city": ("#f8fafc", True, 0, 0),
|
||||
"town": ("#e6ebf2", True, 1, 9),
|
||||
"village": ("#cdd6e2", False, 2, 12),
|
||||
"suburb": ("#9fb0c4", False, 3, 12),
|
||||
"quarter": ("#94a5ba", False, 4, 13),
|
||||
"neighbourhood": ("#8496ab", False, 5, 13),
|
||||
"hamlet": ("#8496ab", False, 6, 14),
|
||||
}
|
||||
_WATER_LABEL = ("#7dd3fc", False, 2)
|
||||
_STREET_LABEL = ("#9aa0aa", False, 7)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Label:
|
||||
"""A pending label placement candidate."""
|
||||
|
||||
rank: int
|
||||
x: float
|
||||
y: float
|
||||
text: str
|
||||
color: RGB
|
||||
bold: bool
|
||||
min_zoom: int = 0
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Frame:
|
||||
"""Working state while composing one frame."""
|
||||
|
||||
canvas: MapCanvas
|
||||
viewport: Viewport
|
||||
labels: list[_Label] = field(default_factory=list)
|
||||
|
||||
|
||||
def render_map(
|
||||
viewport: Viewport,
|
||||
tiles: dict[tuple[int, int, int], Optional[list[Layer]]],
|
||||
markers: list[MapMarker],
|
||||
*,
|
||||
max_labels: int = 80,
|
||||
) -> list[str]:
|
||||
"""Render a full map frame to truecolour ANSI lines.
|
||||
|
||||
Args:
|
||||
viewport: The view to render (its dot size sets the canvas size).
|
||||
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.
|
||||
|
||||
Returns:
|
||||
One ANSI string per row, ready for the TUI frame or the console.
|
||||
"""
|
||||
canvas = MapCanvas(viewport.dot_w // 2, viewport.dot_h // 4)
|
||||
frame = _Frame(canvas=canvas, viewport=viewport)
|
||||
|
||||
for (z, x, y), layers in tiles.items():
|
||||
if layers:
|
||||
_draw_tile(frame, layers, z, x, y)
|
||||
|
||||
# Nodes reserve their cells first so basemap labels route around them.
|
||||
_draw_nodes(canvas, viewport, markers)
|
||||
|
||||
# Then place basemap labels by importance, honouring the zoom gate and collisions.
|
||||
placed = 0
|
||||
for label in sorted(frame.labels, key=lambda l: l.rank):
|
||||
if placed >= max_labels:
|
||||
break
|
||||
if viewport.zoom < label.min_zoom:
|
||||
continue
|
||||
if canvas.place_label(label.x, label.y, label.text, label.color, bold=label.bold):
|
||||
placed += 1
|
||||
|
||||
return canvas.to_ansi_lines()
|
||||
|
||||
|
||||
def _draw_tile(frame: _Frame, layers: list[Layer], z: int, x: int, y: int) -> None:
|
||||
"""Draw one decoded tile's geometry and collect its label candidates."""
|
||||
vp = frame.canvas
|
||||
by_name = {layer.name: layer for layer in layers}
|
||||
|
||||
def project(ring: list[tuple[int, int]], extent: int) -> list[tuple[float, float]]:
|
||||
return [
|
||||
frame.viewport.feature_to_dot(x, y, z, extent, lx, ly) for lx, ly in ring
|
||||
]
|
||||
|
||||
# Fills first (water, green space) so lines and labels sit on top.
|
||||
for name in ("water", "landcover", "landuse", "park"):
|
||||
layer = by_name.get(name)
|
||||
if layer is None:
|
||||
continue
|
||||
for feat in layer.features:
|
||||
if feat.geom_type != GEOM_POLYGON:
|
||||
continue
|
||||
if name == "water":
|
||||
color, prio = _WATER_FILL
|
||||
elif str(feat.get("class") or feat.get("subclass")) in _GREEN_CLASSES:
|
||||
color, prio = _GREEN_FILL
|
||||
else:
|
||||
continue
|
||||
vp.fill_polygon(
|
||||
[project(r, layer.extent) for r in feat.rings], parse_hex(color), prio
|
||||
)
|
||||
|
||||
# Waterways (rivers/streams) as lines.
|
||||
waterway = by_name.get("waterway")
|
||||
if waterway is not None:
|
||||
for feat in waterway.features:
|
||||
style = _WATERWAY_STYLE.get(str(feat.get("class")))
|
||||
if style is None or feat.geom_type != GEOM_LINE:
|
||||
continue
|
||||
color, prio = style
|
||||
for ring in feat.rings:
|
||||
if len(ring) >= 2:
|
||||
vp.draw_line(project(ring, waterway.extent), parse_hex(color), prio)
|
||||
if feat.name:
|
||||
_add_line_label(frame, feat.rings, waterway.extent, z, x, y, feat.name, _WATER_LABEL)
|
||||
|
||||
# Roads / rail.
|
||||
transportation = by_name.get("transportation")
|
||||
if transportation is not None:
|
||||
for feat in transportation.features:
|
||||
if feat.geom_type != GEOM_LINE:
|
||||
continue
|
||||
cls = str(feat.get("class") or "")
|
||||
if cls in ("rail", "transit"):
|
||||
color, prio = _RAIL
|
||||
else:
|
||||
color, prio = _ROAD_STYLE.get(cls, _ROAD_DEFAULT)
|
||||
rgb = parse_hex(color)
|
||||
for ring in feat.rings:
|
||||
if len(ring) >= 2:
|
||||
vp.draw_line(project(ring, transportation.extent), rgb, prio)
|
||||
|
||||
# Boundaries (admin) as a faint hint.
|
||||
boundary = by_name.get("boundary")
|
||||
if boundary is not None:
|
||||
for feat in boundary.features:
|
||||
if feat.geom_type != GEOM_LINE:
|
||||
continue
|
||||
try:
|
||||
if int(feat.get("admin_level", 99)) > 6:
|
||||
continue
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
for ring in feat.rings:
|
||||
if len(ring) >= 2:
|
||||
vp.draw_line(project(ring, boundary.extent), parse_hex("#6d5f88"), 14)
|
||||
|
||||
# Street-name labels (only kick in at high zoom via the label's min_zoom gate).
|
||||
tname = by_name.get("transportation_name")
|
||||
if tname is not None:
|
||||
color, bold, rank = _STREET_LABEL
|
||||
for feat in tname.features:
|
||||
if feat.name and feat.rings:
|
||||
_add_line_label(
|
||||
frame, feat.rings, tname.extent, z, x, y, feat.name,
|
||||
(color, bold, rank), min_zoom=15,
|
||||
)
|
||||
|
||||
# Place labels.
|
||||
place = by_name.get("place")
|
||||
if place is not None:
|
||||
for feat in place.features:
|
||||
if not feat.name or not feat.rings or not feat.rings[0]:
|
||||
continue
|
||||
style = _PLACE_STYLE.get(str(feat.get("class")))
|
||||
if style is None:
|
||||
continue
|
||||
color, bold, rank, min_zoom = style
|
||||
lx, ly = feat.rings[0][0]
|
||||
dx, dy = frame.viewport.feature_to_dot(x, y, z, place.extent, lx, ly)
|
||||
frame.labels.append(
|
||||
_Label(rank, dx, dy, feat.name, parse_hex(color), bold, min_zoom)
|
||||
)
|
||||
|
||||
# Water-body names.
|
||||
water_name = by_name.get("water_name")
|
||||
if water_name is not None:
|
||||
color, bold, rank = _WATER_LABEL
|
||||
for feat in water_name.features:
|
||||
if feat.name and feat.rings and feat.rings[0]:
|
||||
lx, ly = feat.rings[0][0]
|
||||
dx, dy = frame.viewport.feature_to_dot(x, y, z, water_name.extent, lx, ly)
|
||||
frame.labels.append(_Label(rank, dx, dy, feat.name, parse_hex(color), bold, 8))
|
||||
|
||||
|
||||
def _add_line_label(
|
||||
frame: _Frame,
|
||||
rings: list[list[tuple[int, int]]],
|
||||
extent: int,
|
||||
z: int,
|
||||
x: int,
|
||||
y: int,
|
||||
text: str,
|
||||
style: tuple[str, bool, int],
|
||||
*,
|
||||
min_zoom: int = 0,
|
||||
) -> None:
|
||||
"""Queue a label at the midpoint of a line feature's longest part."""
|
||||
longest = max(rings, key=len)
|
||||
lx, ly = longest[len(longest) // 2]
|
||||
dx, dy = frame.viewport.feature_to_dot(x, y, z, extent, lx, ly)
|
||||
color, bold, rank = style
|
||||
frame.labels.append(_Label(rank, dx, dy, text, parse_hex(color), bold, min_zoom))
|
||||
|
||||
|
||||
def _draw_nodes(canvas: MapCanvas, viewport: Viewport, markers: list[MapMarker]) -> None:
|
||||
"""Overlay mesh nodes (lowest priority first, so self/repeaters land on top)."""
|
||||
for marker in sorted(markers, key=lambda m: m._rank()):
|
||||
x, y = viewport.lonlat_to_dot(marker.lat, marker.lon)
|
||||
ix, iy = int(round(x)), int(round(y))
|
||||
if not (0 <= ix < viewport.dot_w and 0 <= iy < viewport.dot_h):
|
||||
continue
|
||||
if marker.is_self:
|
||||
glyph, color = _SELF
|
||||
elif marker.is_repeater:
|
||||
glyph, color = _REPEATER
|
||||
else:
|
||||
glyph, color = _NODE
|
||||
canvas.marker(ix, iy, glyph, parse_hex(color), label=marker.label)
|
||||
@@ -0,0 +1,217 @@
|
||||
"""The interactive full-screen map: a pannable, zoomable slippy map in the terminal.
|
||||
|
||||
This drives the braille street map inside the TUI. It owns a :class:`~meshtools.core.geo.
|
||||
Viewport` over the mesh's nodes, fetches the vector tiles covering it in the background (so
|
||||
the UI never blocks on the network), and redraws via :func:`~meshtools.ui.map_render.
|
||||
render_map`. Keys:
|
||||
|
||||
* ``w`` / ``a`` / ``s`` / ``d`` (or the arrow keys) pan north / west / south / east,
|
||||
* ``=`` / ``+`` zoom in, ``-`` / ``_`` zoom out,
|
||||
* ``r`` recenters and refits to the nodes,
|
||||
* ``Esc`` / ``q`` leaves the map.
|
||||
|
||||
With no network (and no cached tiles) the basemap is simply absent and nodes are plotted on a
|
||||
blank grid — the map still works, it just has no streets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
|
||||
from ..core.geo import EARTH_RADIUS_KM, Viewport
|
||||
from ..core.mvt import Layer
|
||||
from ..services.basemap import BasemapSource
|
||||
from .map_render import MapMarker, render_map
|
||||
from .tui.screen import Screen
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..context import AppContext
|
||||
|
||||
#: Fraction of the view a single pan keypress moves.
|
||||
_PAN_STEP = 0.30
|
||||
|
||||
#: How far past the tile source's max zoom the display may go (lower tiles are magnified).
|
||||
_OVERZOOM = 2
|
||||
|
||||
|
||||
class MapScreen(Screen):
|
||||
"""A full-screen, keyboard-driven map of the mesh's located nodes over an OSM basemap."""
|
||||
|
||||
floating = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session, # noqa: ANN001 - TuiSession, imported lazily to avoid a cycle
|
||||
markers: list[MapMarker],
|
||||
source: BasemapSource,
|
||||
max_tile_zoom: int,
|
||||
) -> None:
|
||||
"""Create the map screen.
|
||||
|
||||
Args:
|
||||
session: The running TUI session (for size + repaint scheduling).
|
||||
markers: The located mesh nodes to plot (must be non-empty).
|
||||
source: The vector-tile source (already resolved/warmed).
|
||||
max_tile_zoom: The source's max zoom, captured off the event loop at open time.
|
||||
"""
|
||||
super().__init__()
|
||||
self.title = "mesh map"
|
||||
self._session = session
|
||||
self._markers = markers
|
||||
self._source = source
|
||||
self._max_tile_zoom = max_tile_zoom
|
||||
self._viewport: Optional[Viewport] = None
|
||||
self._size: tuple[int, int] = (0, 0) # (dot_w, dot_h) the viewport is built for
|
||||
# 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()
|
||||
|
||||
# --- rendering -----------------------------------------------------------
|
||||
|
||||
@property
|
||||
def footer_hint(self) -> str: # type: ignore[override]
|
||||
"""Key hints plus a live tile-loading indicator."""
|
||||
base = "wasd/↑↓←→ pan · +/- zoom · r reset · 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
|
||||
|
||||
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()
|
||||
cell_w = width
|
||||
dot_w, dot_h = cell_w * 2, cell_h * 4
|
||||
|
||||
if self._viewport is None:
|
||||
self._viewport = Viewport.fit(
|
||||
[(m.lat, m.lon) for m in self._markers],
|
||||
dot_w,
|
||||
dot_h,
|
||||
max_zoom=self._max_tile_zoom,
|
||||
)
|
||||
self._size = (dot_w, dot_h)
|
||||
elif self._size != (dot_w, dot_h):
|
||||
self._viewport = self._viewport.resized(dot_w, dot_h)
|
||||
self._size = (dot_w, dot_h)
|
||||
|
||||
self._ensure_tiles(self._viewport)
|
||||
self.title = self._title(self._viewport)
|
||||
tiles = {t: self._tiles.get(t) for t in self._viewport.tiles(self._max_tile_zoom)}
|
||||
return render_map(self._viewport, tiles, self._markers)
|
||||
|
||||
def _title(self, vp: Viewport) -> str:
|
||||
"""A compact status title: zoom, node count, and scale (metres per dot)."""
|
||||
# Ground metres per braille dot at the view centre, for a rough sense of scale.
|
||||
m_per_dot = (
|
||||
2 * math.pi * EARTH_RADIUS_KM * 1000
|
||||
* math.cos(math.radians(vp.center_lat))
|
||||
/ (256 * (2**vp.zoom))
|
||||
)
|
||||
scale = f"{m_per_dot * vp.dot_w:.0f} m across" if m_per_dot * vp.dot_w < 1000 else \
|
||||
f"{m_per_dot * vp.dot_w / 1000:.1f} km across"
|
||||
return f"mesh map · z{vp.zoom} · {len(self._markers)} nodes · {scale}"
|
||||
|
||||
# --- tiles ---------------------------------------------------------------
|
||||
|
||||
def _ensure_tiles(self, vp: Viewport) -> None:
|
||||
"""Schedule background fetches for any visible tiles not yet loaded or pending."""
|
||||
if not self._source.available: # offline (resolved at open time) — nodes only
|
||||
return
|
||||
for t in vp.tiles(self._max_tile_zoom):
|
||||
if t in self._tiles or t in self._pending:
|
||||
continue
|
||||
self._pending.add(t)
|
||||
try:
|
||||
asyncio.ensure_future(self._load(t))
|
||||
except RuntimeError: # pragma: no cover - no running loop (non-interactive)
|
||||
self._pending.discard(t)
|
||||
|
||||
async def _load(self, t: tuple[int, int, int]) -> None:
|
||||
"""Fetch+decode one tile off the event loop, then repaint."""
|
||||
try:
|
||||
layers = await asyncio.to_thread(self._source.load_tile, *t)
|
||||
except Exception: # noqa: BLE001 - a failed tile is just an absent one
|
||||
layers = None
|
||||
self._tiles[t] = layers
|
||||
self._pending.discard(t)
|
||||
self._session.invalidate()
|
||||
|
||||
# --- input ---------------------------------------------------------------
|
||||
|
||||
def handle(self, action: str, data: str = "") -> None:
|
||||
"""Pan, zoom, reset, or exit in response to a normalized key action."""
|
||||
vp = self._viewport
|
||||
if action == "escape":
|
||||
self.resolve(None)
|
||||
return
|
||||
if vp is None:
|
||||
return
|
||||
if action == "up":
|
||||
self._viewport = vp.panned(0, -_PAN_STEP)
|
||||
elif action == "down":
|
||||
self._viewport = vp.panned(0, _PAN_STEP)
|
||||
elif action == "left":
|
||||
self._viewport = vp.panned(-_PAN_STEP, 0)
|
||||
elif action == "right":
|
||||
self._viewport = vp.panned(_PAN_STEP, 0)
|
||||
elif action == "text":
|
||||
self._handle_key(data, vp)
|
||||
|
||||
def _handle_key(self, key: str, vp: Viewport) -> None:
|
||||
"""Handle a printable-key action (pan/zoom/reset/quit)."""
|
||||
key = key.lower()
|
||||
if key == "w":
|
||||
self._viewport = vp.panned(0, -_PAN_STEP)
|
||||
elif key == "s":
|
||||
self._viewport = vp.panned(0, _PAN_STEP)
|
||||
elif key == "a":
|
||||
self._viewport = vp.panned(-_PAN_STEP, 0)
|
||||
elif key == "d":
|
||||
self._viewport = vp.panned(_PAN_STEP, 0)
|
||||
elif key in ("=", "+"):
|
||||
self._viewport = vp.zoomed(1, max_zoom=self._max_tile_zoom + _OVERZOOM)
|
||||
elif key in ("-", "_"):
|
||||
self._viewport = vp.zoomed(-1)
|
||||
elif key == "r":
|
||||
self._viewport = Viewport.fit(
|
||||
[(m.lat, m.lon) for m in self._markers],
|
||||
vp.dot_w,
|
||||
vp.dot_h,
|
||||
max_zoom=self._max_tile_zoom,
|
||||
)
|
||||
elif key == "q":
|
||||
self.resolve(None)
|
||||
|
||||
|
||||
def basemap_source(ctx: "AppContext") -> BasemapSource:
|
||||
"""Build the vector-tile source backed by the app's on-disk tile cache."""
|
||||
return BasemapSource(ctx.settings.config_dir / "tilecache")
|
||||
|
||||
|
||||
async def open_map(ctx: "AppContext", markers: list[MapMarker]) -> None:
|
||||
"""Open the interactive full-screen map over ``markers`` and run until dismissed.
|
||||
|
||||
Warms the tile source off the event loop (so the first paint doesn't block on the
|
||||
network), then pushes the :class:`MapScreen` and awaits its dismissal.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context (must be in the interactive menu).
|
||||
markers: The located mesh nodes to plot (non-empty).
|
||||
|
||||
Raises:
|
||||
RuntimeError: If called outside the interactive menu (no full-screen session).
|
||||
"""
|
||||
from .surface import TuiUi
|
||||
|
||||
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
|
||||
raise RuntimeError("the interactive map is only available in the menu")
|
||||
session = ctx.ui.session
|
||||
source = basemap_source(ctx)
|
||||
# Resolve the tile template/zoom in a worker thread so the UI thread never blocks.
|
||||
max_zoom = await asyncio.to_thread(lambda: source.max_zoom)
|
||||
screen = MapScreen(session, markers, source, max_zoom)
|
||||
await session.run_screen(screen)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""A colored Unicode-braille canvas for the terminal map.
|
||||
|
||||
Each character cell holds a 2×4 grid of braille dots, so the drawable resolution is twice
|
||||
the columns by four times the rows. Streets, rivers and water are rasterized as braille
|
||||
*dots*; place names, street names and node labels are written as *text* over whole cells;
|
||||
node markers are single glyphs on top.
|
||||
|
||||
A terminal cell can only show one colour, so each cell keeps the colour of the
|
||||
highest-**priority** feature whose dots fall in it (a river drawn over water keeps the river's
|
||||
blue). Text and markers form a separate overlay that always wins the cell, with greedy
|
||||
collision avoidance so labels never overprint each other. The canvas renders straight to
|
||||
truecolour ANSI lines, which is exactly what the TUI frame consumes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
#: Unicode braille pattern base; add a dot bitmask to get the glyph.
|
||||
_BRAILLE_BASE = 0x2800
|
||||
|
||||
#: 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
|
||||
)
|
||||
|
||||
RGB = tuple[int, int, int]
|
||||
|
||||
|
||||
def parse_hex(color: str) -> RGB:
|
||||
"""Convert ``"#rrggbb"`` (or ``"rrggbb"``) to an ``(r, g, b)`` tuple."""
|
||||
c = color.lstrip("#")
|
||||
return (int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16))
|
||||
|
||||
|
||||
class MapCanvas:
|
||||
"""A colored braille raster with a text/marker overlay and label collision tracking."""
|
||||
|
||||
def __init__(self, cell_w: int, cell_h: int) -> None:
|
||||
"""Create a blank canvas.
|
||||
|
||||
Args:
|
||||
cell_w: Width in character cells.
|
||||
cell_h: Height in character cells.
|
||||
"""
|
||||
self.cell_w = max(1, cell_w)
|
||||
self.cell_h = max(1, cell_h)
|
||||
self.dot_w = self.cell_w * 2
|
||||
self.dot_h = self.cell_h * 4
|
||||
self._bits = [[0] * self.cell_w for _ in range(self.cell_h)]
|
||||
self._color: list[list[Optional[RGB]]] = [
|
||||
[None] * self.cell_w for _ in range(self.cell_h)
|
||||
]
|
||||
self._prio = [[-1] * self.cell_w for _ in range(self.cell_h)]
|
||||
# Overlay: (cx, cy) -> (char, rgb, bold). Occupied tracks cells claimed by labels /
|
||||
# markers so later labels can avoid them.
|
||||
self._overlay: dict[tuple[int, int], tuple[str, RGB, bool]] = {}
|
||||
self._occupied: set[tuple[int, int]] = set()
|
||||
|
||||
# -- primitives -------------------------------------------------------------
|
||||
|
||||
def plot(self, x: int, y: int, color: RGB, priority: int) -> None:
|
||||
"""Light the braille dot at dot ``(x, y)`` and colour its cell by ``priority``."""
|
||||
if not (0 <= x < self.dot_w and 0 <= y < self.dot_h):
|
||||
return
|
||||
cx, cy = x >> 1, y >> 2
|
||||
self._bits[cy][cx] |= _DOT_BITS[x & 1][y & 3]
|
||||
if priority >= self._prio[cy][cx]:
|
||||
self._prio[cy][cx] = priority
|
||||
self._color[cy][cx] = color
|
||||
|
||||
def draw_line(
|
||||
self, points: list[tuple[float, float]], color: RGB, priority: int
|
||||
) -> None:
|
||||
"""Rasterize a polyline through ``points`` (dot coordinates) as braille dots."""
|
||||
for (x0, y0), (x1, y1) in zip(points, points[1:]):
|
||||
self._segment(x0, y0, x1, y1, color, priority)
|
||||
|
||||
def _segment(
|
||||
self, x0: float, y0: float, x1: float, y1: float, color: RGB, priority: int
|
||||
) -> None:
|
||||
"""Bresenham a single segment, skipping ones wholly off the canvas."""
|
||||
# Quick reject: both endpoints beyond the same edge → nothing visible.
|
||||
if (x0 < 0 and x1 < 0) or (x0 >= self.dot_w and x1 >= self.dot_w):
|
||||
return
|
||||
if (y0 < 0 and y1 < 0) or (y0 >= self.dot_h and y1 >= self.dot_h):
|
||||
return
|
||||
xa, ya, xb, yb = int(round(x0)), int(round(y0)), int(round(x1)), int(round(y1))
|
||||
dx, dy = abs(xb - xa), -abs(yb - ya)
|
||||
sx = 1 if xa < xb else -1
|
||||
sy = 1 if ya < yb else -1
|
||||
err = dx + dy
|
||||
while True:
|
||||
self.plot(xa, ya, color, priority)
|
||||
if xa == xb and ya == yb:
|
||||
break
|
||||
e2 = 2 * err
|
||||
if e2 >= dy:
|
||||
err += dy
|
||||
xa += sx
|
||||
if e2 <= dx:
|
||||
err += dx
|
||||
ya += sy
|
||||
|
||||
def fill_polygon(
|
||||
self, rings: list[list[tuple[float, float]]], color: RGB, priority: int
|
||||
) -> None:
|
||||
"""Even-odd scanline fill of a polygon (with holes) in dot space."""
|
||||
edges: list[tuple[float, float, float, float]] = []
|
||||
ys: list[float] = []
|
||||
for ring in rings:
|
||||
for (x0, y0), (x1, y1) in zip(ring, ring[1:]):
|
||||
if y0 != y1:
|
||||
edges.append((x0, y0, x1, y1))
|
||||
ys.extend((y0, y1))
|
||||
if not edges:
|
||||
return
|
||||
y_start = max(0, int(min(ys)))
|
||||
y_end = min(self.dot_h - 1, int(max(ys)))
|
||||
for y in range(y_start, y_end + 1):
|
||||
yc = y + 0.5
|
||||
xs: list[float] = []
|
||||
for x0, y0, x1, y1 in edges:
|
||||
if (y0 <= yc < y1) or (y1 <= yc < y0):
|
||||
xs.append(x0 + (yc - y0) * (x1 - x0) / (y1 - y0))
|
||||
xs.sort()
|
||||
for i in range(0, len(xs) - 1, 2):
|
||||
x_from = max(0, int(round(xs[i])))
|
||||
x_to = min(self.dot_w - 1, int(round(xs[i + 1])))
|
||||
for x in range(x_from, x_to + 1):
|
||||
self.plot(x, y, color, priority)
|
||||
|
||||
# -- overlay (markers + labels) --------------------------------------------
|
||||
|
||||
def marker(
|
||||
self,
|
||||
x: int,
|
||||
y: int,
|
||||
glyph: str,
|
||||
color: RGB,
|
||||
*,
|
||||
label: str = "",
|
||||
label_color: Optional[RGB] = None,
|
||||
) -> None:
|
||||
"""Place a marker glyph at dot ``(x, y)`` with an optional label beside it.
|
||||
|
||||
Markers always draw (they are the point of the map). The label is placed to the
|
||||
right when there's room, otherwise to the left, and its cells are reserved so
|
||||
basemap labels avoid them.
|
||||
"""
|
||||
cx, cy = x >> 1, y >> 2
|
||||
if not (0 <= cx < self.cell_w and 0 <= cy < self.cell_h):
|
||||
return
|
||||
self._overlay[(cx, cy)] = (glyph, color, True)
|
||||
self._occupied.add((cx, cy))
|
||||
if label:
|
||||
lc = label_color or color
|
||||
# Prefer the label to the right of the marker (one blank cell gap); fall back to
|
||||
# the left when it would overflow — never overwriting the marker glyph itself.
|
||||
if cx + 2 + len(label) <= self.cell_w:
|
||||
self._place_run(cx + 2, cy, label, lc, bold=True)
|
||||
else:
|
||||
self._place_run(max(0, cx - 1 - len(label)), cy, label, lc, bold=True)
|
||||
|
||||
def place_label(
|
||||
self, x: float, y: float, text: str, color: RGB, *, bold: bool = False
|
||||
) -> bool:
|
||||
"""Write a centered basemap label at dot ``(x, y)`` if it fits without collision.
|
||||
|
||||
Args:
|
||||
x: Anchor dot x.
|
||||
y: Anchor dot y.
|
||||
text: Label text.
|
||||
color: Text colour.
|
||||
bold: Whether to embolden (used for the most important places).
|
||||
|
||||
Returns:
|
||||
``True`` if placed, ``False`` if it fell off-canvas or overlapped existing text.
|
||||
"""
|
||||
cx = int(x) >> 1
|
||||
cy = int(y) >> 2
|
||||
start = cx - len(text) // 2
|
||||
return self._place_run(start, cy, text, color, bold=bold, checked=True)
|
||||
|
||||
def _place_run(
|
||||
self,
|
||||
start_cx: int,
|
||||
cy: int,
|
||||
text: str,
|
||||
color: RGB,
|
||||
*,
|
||||
bold: bool,
|
||||
checked: bool = False,
|
||||
) -> bool:
|
||||
"""Write ``text`` starting at cell ``(start_cx, cy)``.
|
||||
|
||||
With ``checked`` the run is skipped entirely if any target cell (or a one-cell
|
||||
horizontal margin) is already claimed or off-canvas; otherwise it is forced and
|
||||
simply clipped to the canvas. Returns whether anything was placed.
|
||||
"""
|
||||
if not (0 <= cy < self.cell_h):
|
||||
return False
|
||||
cells = range(start_cx, start_cx + len(text))
|
||||
if checked:
|
||||
if start_cx < 0 or start_cx + len(text) > self.cell_w:
|
||||
return False
|
||||
margin = range(start_cx - 1, start_cx + len(text) + 1)
|
||||
if any((mx, cy) in self._occupied for mx in margin):
|
||||
return False
|
||||
placed = False
|
||||
for offset, ch in enumerate(text):
|
||||
mx = start_cx + offset
|
||||
if 0 <= mx < self.cell_w:
|
||||
self._overlay[(mx, cy)] = (ch, color, bold)
|
||||
self._occupied.add((mx, cy))
|
||||
placed = True
|
||||
return placed
|
||||
|
||||
# -- output -----------------------------------------------------------------
|
||||
|
||||
def to_ansi_lines(self) -> list[str]:
|
||||
"""Render the canvas to one truecolour ANSI string per row."""
|
||||
reset = "\x1b[0m"
|
||||
lines: list[str] = []
|
||||
for cy in range(self.cell_h):
|
||||
parts: list[str] = []
|
||||
cur: Optional[tuple[RGB, bool]] = None
|
||||
for cx in range(self.cell_w):
|
||||
overlay = self._overlay.get((cx, cy))
|
||||
if overlay is not None:
|
||||
ch, color, bold = overlay
|
||||
elif self._bits[cy][cx]:
|
||||
ch = chr(_BRAILLE_BASE + self._bits[cy][cx])
|
||||
color = self._color[cy][cx] or (128, 128, 128)
|
||||
bold = False
|
||||
else:
|
||||
if cur is not None:
|
||||
parts.append(reset)
|
||||
cur = None
|
||||
parts.append(" ")
|
||||
continue
|
||||
style = (color, bold)
|
||||
if style != cur:
|
||||
r, g, b = color
|
||||
parts.append(f"\x1b[0m\x1b[38;2;{r};{g};{b}m" + ("\x1b[1m" if bold else ""))
|
||||
cur = style
|
||||
parts.append(ch)
|
||||
if cur is not None:
|
||||
parts.append(reset)
|
||||
lines.append("".join(parts))
|
||||
return lines
|
||||
@@ -251,6 +251,23 @@ class TuiSession:
|
||||
size = self._app.output.get_size() # type: ignore[union-attr]
|
||||
return max(20, size.columns), max(6, size.rows)
|
||||
|
||||
def base_body_size(self) -> tuple[int, int]:
|
||||
"""Return the ``(width, height)`` in cells available to the base screen's body.
|
||||
|
||||
Mirrors the layout math in :func:`~meshtools.ui.tui.frame.compose_base` so a
|
||||
full-screen screen (e.g. the map) can size its own content to fill the frame exactly,
|
||||
without waiting a repaint to learn its height.
|
||||
|
||||
Returns:
|
||||
The inner content width and the body viewport height, both in character cells.
|
||||
"""
|
||||
from .render import render_lines
|
||||
|
||||
cols, rows = self._size()
|
||||
header_h = len(render_lines(self._header(), cols, no_wrap=True))
|
||||
viewport = max(1, rows - header_h - 1 - 2) # minus footer(1) and panel border(2)
|
||||
return cols - 4, viewport
|
||||
|
||||
def _base_screen(self) -> Optional[Screen]:
|
||||
"""The screen drawn as the background (parent of a floating dialog, else the top)."""
|
||||
if not self._stack:
|
||||
|
||||
Reference in new issue
Block a user