Files
MeshTerm/meshterm/ui/minimap.py
T
Jean-Pierre MartineauandClaude Opus 4.8 62a2d76e8c Node detail: a full-screen page for each contact, reached by Enter
Pressing Enter on a contact now opens its whole story on one page instead of
a bare row: identity (name in its hue, key with the routing hash lit, type,
first/last heard, packet tally, reception SNR/RSSI), an inline location
preview centred on the node (a small static basemap via the new MiniMap), the
observed routes to it, and an action list (trace armed with the suggested best
path, open full map, time machine). Contacts owns the show/open/reshow loop;
topology.suggested answers "the best evidence-backed way to reach this node",
wired ahead of the firmware route in the trace arming precedence. Timemachine
and Trace grew the entry points the page opens.

Four fixes fell out of driving it on real hardware:

Slow open. Each located-node page built a fresh BasemapSource and resolved its
TileJSON -- a blocking HTTPS round-trip (~100ms, up to the 12s timeout on a bad
link) -- on every open. Hold one source for the session (ctx.basemap_source),
shared by the map, the picker, and the preview, and warm it behind the menu at
login, so the resolve is paid once, off the navigation path.

Black map. A companion advertising nonsense coordinates (Homestead reports
lat -97, lon -1042) flung the viewport off the world, leaving the map a screen
of empty/water fill that reads as solid black -- both from "open full map" and
from filtering to it and framing. The old guard only caught the 0/0 no-GPS
null island; the new geo.usable_fix() rejects any out-of-range fix too, applied
to the map markers and the location preview alike. Verified on-device: of 265
located contacts, only Homestead drops.

Path to node. The route/suggest rows render through THE path widget with a
1-byte hash in parentheses (a "name (3d)" tag), so they cross-read hop for hop
against the route graph's byte labels.

Route graph. Draw us on the left and the target on the right (us to target,
"how we reach it", left to right) via a local endpoint swap that leaves the
shared route_graph_style untouched for its other callers, and give the fan a
generous lane step and row budget so a well-connected node's candidate paths
spread into separate, legible tracks instead of a cramped tangle -- the height
stays adaptive, so a one- or two-route node still draws compact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 23:41:52 -04:00

136 lines
6.1 KiB
Python

"""A small, static, non-interactive map region embeddable inside any screen.
The full-screen :class:`~meshterm.ui.map_screen.MapScreen` is a whole layer of its own —
it pans, zooms, finds nodes, and persists its view. Some screens only want a *glance*: a
few rows of basemap fixed on one place, with the mesh's markers on it, no controls. The
Node detail screen's "Location" preview is the first such caller — it shows where a node
sits without leaving for the big map (which its *Open full map* action still reaches).
This is the map's tile plumbing distilled to that job: a fixed centre and zoom, its own
little tile cache, background fetches off the event loop (so the host screen never blocks
on the network), and a synchronous :meth:`render` that draws whatever tiles have landed —
refining in place as more arrive, exactly like the big map. With no network and no cached
tiles the basemap is simply absent and the markers plot on a blank grid, so the preview is
always *something*. It owns no keys and resolves nothing; the screen that embeds it just
calls :meth:`render` from its own ``render_body`` and forwards nothing back.
"""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Optional
from ..core.geo import Viewport, clamp_lat
from ..core.mvt import Layer
from .map_render import MapMarker, render_map
if TYPE_CHECKING: # pragma: no cover - typing only
from ..services.basemap import BasemapSource
#: How far past the tile source's max zoom a preview may sit — the lower-zoom tiles are
#: magnified to fill it. Matches the big map's overzoom so a close preview still has a
#: (blurred) basemap rather than blank tiles.
_OVERZOOM = 2
class MiniMap:
"""A fixed, non-interactive slippy-map region drawn into a host screen's body.
Build one with the resolved tile source (as :func:`~meshterm.ui.map_screen.open_map`
resolves it) plus the centre, zoom, and markers to plot, then call :meth:`render`
from the host's ``render_body`` with the cell width and row height the region should
take. Tiles fetch in the background and the region redraws as they arrive; nothing
here transmits over the radio.
"""
def __init__(
self,
session, # noqa: ANN001 - TuiSession, untyped to avoid an import cycle
source: "BasemapSource",
max_tile_zoom: int,
*,
center_lat: float,
center_lon: float,
zoom: int,
markers: list[MapMarker],
) -> None:
"""Create the preview over a fixed view.
Args:
session: The running TUI session — used only to repaint the host screen when
a background tile lands (:meth:`_load`).
source: The vector-tile source, already resolved/warmed by the caller.
max_tile_zoom: The source's max zoom, captured off the event loop at open time
(reading it can touch the network, so the host resolves it once up front).
center_lat: Latitude the preview centres on.
center_lon: Longitude the preview centres on.
zoom: Display zoom; clamped to a sane range against the source's max.
markers: The located mesh nodes to overlay (may be empty).
"""
self._session = session
self._source = source
self._max_tile_zoom = max_tile_zoom
self._center_lat = clamp_lat(center_lat)
self._center_lon = center_lon
self._zoom = max(2, min(int(zoom), max_tile_zoom + _OVERZOOM))
self._markers = markers
# 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()
@property
def has_basemap(self) -> bool:
"""Whether the source can serve a basemap at all (network reachable, or cached)."""
return self._source.available
@property
def pending(self) -> int:
"""How many visible tiles are still in flight — for a host's loading note."""
return len(self._pending)
def render(self, width: int, rows: int) -> list[str]:
"""Render the preview at ``width`` cells by ``rows`` rows, scheduling tile loads.
Builds a :class:`~meshterm.core.geo.Viewport` sized to this region (each cell is
two braille dots wide, each row four tall) fixed on the preview's centre and zoom,
kicks off background fetches for any not-yet-loaded tiles, and draws the frame from
whatever has landed. Called every paint; the viewport is cheap to rebuild, so a
resize just re-sizes it.
Args:
width: Region width in character cells.
rows: Region height in character cells.
Returns:
One ANSI string per row (exactly ``rows`` of them, as the canvas fills its box).
"""
viewport = Viewport(
self._center_lat, self._center_lon, self._zoom, max(2, width) * 2, max(1, rows) * 4
)
self._ensure_tiles(viewport)
tiles = {t: self._tiles.get(t) for t in viewport.tiles(self._max_tile_zoom)}
return render_map(viewport, tiles, self._markers)
def _ensure_tiles(self, viewport: Viewport) -> None:
"""Schedule background fetches for any visible tiles not yet loaded or pending."""
if not self._source.available: # offline (resolved at open time) — markers only
return
for t in viewport.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 the host screen."""
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()