Mesh Atlas rebuilt: a radar scope you can zoom, pan, and search
Ground-up rework of the unusably busy first cut. A new atlas_layout service lays the evidence graph out in camera-independent unit space: radii stay pinned to evidenced hop distance (the atlas's core question) while angles relax toward each node's strength-weighted neighbour mean — chains straighten into spokes, clusters gather into wedges — then each ring enforces a minimum angular separation. Deterministic throughout, so the mesh keeps its shape across rebuilds. The screen becomes a camera over that layout, with the street map's exact controls: arrows pan (Shift fine, clamped so the graph can't be lost), PgUp/PgDn zoom 1–12x, Home refits, and every letter feeds a find-as-you-type filter — matches labelled bright white over dimmed context, Enter adopting the first match. Tab walks the selection (recentring it when off-screen), Ctrl+R rebuilds, Esc peels find → selection → screen. Hop rings draw as faint dotted guides, and the label budget grows with the zoom's square, so 1x is a calm overview and zooming in is what buys the detail. Panel and footer rows all fit 72 columns. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
36e8173b5a
commit
ffa834182b
4 files changed
+702
-284
No files matched your search
@@ -0,0 +1,189 @@
|
||||
"""The Mesh Atlas's graph layout: hop-distance rings with force-relaxed angles.
|
||||
|
||||
The atlas answers the mesh's first spatial question — *how far out is everything?* —
|
||||
so the layout is radial by construction: our own node pins the origin and every other
|
||||
node sits at a radius fixed by its evidenced hop distance (BFS over the link graph).
|
||||
That leaves exactly one degree of freedom per node, its **angle**, and that is what
|
||||
the relaxation optimises: nodes are pulled toward the circular mean of their
|
||||
neighbours' bearings (weighted by link strength), so chains stay radial, clusters
|
||||
gather into wedges, and edges shorten — then each ring's members are pushed apart to
|
||||
a minimum angular separation so markers and labels never pile up. One angular degree
|
||||
of freedom keeps the optimisation deterministic and stable (no oscillating springs,
|
||||
no random restarts): the same evidence lays out the same picture every time, and a
|
||||
node keeps roughly the same bearing across rebuilds because its seed angle is a hash
|
||||
of its id.
|
||||
|
||||
Evidence islands — link clusters known only through a repeater's neighbour table,
|
||||
with no observed path back to us — take one shared ring outside everything reached;
|
||||
their mutual edges pull them into a visible cluster there.
|
||||
|
||||
Positions come out in **unit space**: radius ``ring / max_ring`` (≤ 1.0), centre at
|
||||
the origin. The screen owns projection — aspect, zoom, and pan — so the layout never
|
||||
needs recomputing as the user moves the camera; only fresh evidence relays it.
|
||||
|
||||
Pure data-in/data-out (no UI, no storage), like every service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
|
||||
_TAU = math.tau
|
||||
|
||||
#: Angular relaxation sweeps. Each sweep moves every node part-way toward its
|
||||
#: neighbours' mean bearing then re-spaces each ring; a few dozen sweeps settle a
|
||||
#: mesh-sized graph (tens of nodes) far below one dot of movement.
|
||||
_RELAX_SWEEPS = 48
|
||||
|
||||
#: How far a node moves toward its neighbours' mean bearing per sweep (0..1).
|
||||
_RELAX_ALPHA = 0.35
|
||||
|
||||
#: The widest minimum angular separation a ring enforces (radians, ≈20°). Crowded
|
||||
#: rings fall back to their even-spacing angle (2π/n) — the most separation that
|
||||
#: exists — so the floor only ever *relaxes*, never over-constrains.
|
||||
_MIN_SEPARATION = 0.35
|
||||
|
||||
#: Separation passes per sweep: each pass walks the ring once, splitting deficits
|
||||
#: between neighbouring pairs; a handful converges since rings hold few nodes.
|
||||
_SEPARATION_PASSES = 4
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AtlasLayout:
|
||||
"""One laid-out atlas graph, in unit space.
|
||||
|
||||
Attributes:
|
||||
positions: Per-node ``(x, y)`` with the centre at the origin and every
|
||||
radius ≤ 1.0. The screen projects these through aspect/zoom/pan.
|
||||
rings: Per-node hop ring (0 = our own node; islands share the outermost).
|
||||
islands: Nodes with no observed path back to us.
|
||||
max_ring: The outermost ring index in use (0 for a lone node).
|
||||
"""
|
||||
|
||||
positions: dict[str, tuple[float, float]]
|
||||
rings: dict[str, int]
|
||||
islands: frozenset[str]
|
||||
max_ring: int
|
||||
|
||||
|
||||
def _hash_angle(node: str) -> float:
|
||||
"""A deterministic per-node seed bearing, stable across processes and rebuilds.
|
||||
|
||||
A CRC rather than :func:`hash`, which Python salts per process — the whole point
|
||||
is that a node sits at the same clock position tomorrow as today.
|
||||
"""
|
||||
return zlib.crc32(node.encode()) / 0xFFFFFFFF * _TAU
|
||||
|
||||
|
||||
def _circular_mean(bearings: list[tuple[float, float]]) -> float | None:
|
||||
"""The weighted circular mean of ``(angle, weight)`` bearings, or ``None`` if flat."""
|
||||
sin_sum = sum(w * math.sin(a) for a, w in bearings)
|
||||
cos_sum = sum(w * math.cos(a) for a, w in bearings)
|
||||
if abs(sin_sum) < 1e-12 and abs(cos_sum) < 1e-12:
|
||||
return None
|
||||
return math.atan2(sin_sum, cos_sum) % _TAU
|
||||
|
||||
|
||||
def _toward(angle: float, target: float, alpha: float) -> float:
|
||||
"""``angle`` moved ``alpha`` of the way toward ``target`` along the short arc."""
|
||||
delta = (target - angle + math.pi) % _TAU - math.pi
|
||||
return (angle + alpha * delta) % _TAU
|
||||
|
||||
|
||||
def _space_ring(members: list[str], angles: dict[str, float]) -> None:
|
||||
"""Push one ring's members apart to the separation floor, preserving their order.
|
||||
|
||||
Members are walked in angular order and every adjacent pair (wrap included)
|
||||
closer than the floor is split apart symmetrically. Deficits propagate around
|
||||
the ring over :data:`_SEPARATION_PASSES` passes; a full ring (n·floor ≥ 2π)
|
||||
degrades gracefully toward even spacing rather than fighting itself, because
|
||||
the floor never exceeds ``2π / n``.
|
||||
"""
|
||||
n = len(members)
|
||||
if n < 2:
|
||||
return
|
||||
floor = min(_MIN_SEPARATION, _TAU / n)
|
||||
for _ in range(_SEPARATION_PASSES):
|
||||
ordered = sorted(members, key=lambda m: angles[m])
|
||||
moved = False
|
||||
for i in range(n):
|
||||
a, b = ordered[i], ordered[(i + 1) % n]
|
||||
gap = (angles[b] - angles[a]) % _TAU
|
||||
if gap + 1e-12 < floor:
|
||||
push = (floor - gap) / 2
|
||||
angles[a] = (angles[a] - push) % _TAU
|
||||
angles[b] = (angles[b] + push) % _TAU
|
||||
moved = True
|
||||
if not moved:
|
||||
return
|
||||
|
||||
|
||||
def compute_layout(self_id: str, links: list[tuple[str, str, float]]) -> AtlasLayout:
|
||||
"""Lay the evidence graph out on hop rings with relaxed angular placement.
|
||||
|
||||
Args:
|
||||
self_id: Canonical id of our own node (always placed, even with no links).
|
||||
links: The evidence graph as ``(a, b, strength)`` triples (strength > 0;
|
||||
parallel duplicates keep their strongest reading).
|
||||
|
||||
Returns:
|
||||
The unit-space :class:`AtlasLayout`.
|
||||
"""
|
||||
adjacency: dict[str, dict[str, float]] = {self_id: {}}
|
||||
for a, b, strength in links:
|
||||
adjacency.setdefault(a, {})
|
||||
adjacency.setdefault(b, {})
|
||||
adjacency[a][b] = max(strength, adjacency[a].get(b, 0.0))
|
||||
adjacency[b][a] = max(strength, adjacency[b].get(a, 0.0))
|
||||
|
||||
# Hop rings: BFS from us; unreached nodes (islands) share one outer ring.
|
||||
rings: dict[str, int] = {self_id: 0}
|
||||
frontier = [self_id]
|
||||
while frontier:
|
||||
nxt: list[str] = []
|
||||
for node in frontier:
|
||||
for other in sorted(adjacency.get(node, {})):
|
||||
if other not in rings:
|
||||
rings[other] = rings[node] + 1
|
||||
nxt.append(other)
|
||||
frontier = nxt
|
||||
islands = frozenset(n for n in adjacency if n not in rings)
|
||||
if islands:
|
||||
island_ring = max(rings.values(), default=0) + 1
|
||||
for node in islands:
|
||||
rings[node] = island_ring
|
||||
max_ring = max(rings.values(), default=0)
|
||||
|
||||
# Seed every bearing from the node's id hash, then relax: each sweep pulls a
|
||||
# node toward the strength-weighted circular mean of its neighbours' bearings
|
||||
# (the centre node exerts no pull — it has no bearing) and re-spaces each ring.
|
||||
angles: dict[str, float] = {
|
||||
node: _hash_angle(node) for node in adjacency if node != self_id
|
||||
}
|
||||
by_ring: dict[int, list[str]] = {}
|
||||
for node, ring in rings.items():
|
||||
if ring:
|
||||
by_ring.setdefault(ring, []).append(node)
|
||||
order = sorted(angles) # a stable sweep order keeps the result deterministic
|
||||
for _ in range(_RELAX_SWEEPS):
|
||||
for node in order:
|
||||
bearings = [
|
||||
(angles[other], strength)
|
||||
for other, strength in adjacency[node].items()
|
||||
if other != self_id
|
||||
]
|
||||
target = _circular_mean(bearings)
|
||||
if target is not None:
|
||||
angles[node] = _toward(angles[node], target, _RELAX_ALPHA)
|
||||
for members in by_ring.values():
|
||||
_space_ring(members, angles)
|
||||
|
||||
positions: dict[str, tuple[float, float]] = {self_id: (0.0, 0.0)}
|
||||
for node, angle in angles.items():
|
||||
radius = rings[node] / max_ring if max_ring else 1.0
|
||||
positions[node] = (radius * math.cos(angle), radius * math.sin(angle))
|
||||
return AtlasLayout(
|
||||
positions=positions, rings=rings, islands=islands, max_ring=max_ring
|
||||
)
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
Opens the full-screen Mesh Atlas (see :mod:`meshterm.ui.atlas_screen`): every link the
|
||||
evidence graph holds — trace walks, firmware routes, overheard relay chains, repeater
|
||||
neighbour tables — drawn as braille edges coloured by SNR around our own node, with
|
||||
node-by-node walking and per-link detail. The geographic map answers *where* the mesh
|
||||
neighbour tables — drawn as braille edges coloured by SNR on hop-distance rings around
|
||||
our own node. Pannable and zoomable like the street map, with find-as-you-type node
|
||||
search, Tab-walking, and per-link detail. The geographic map answers *where* the mesh
|
||||
is; the atlas answers *how it hangs together*.
|
||||
|
||||
Menu-only: the atlas is an interactive reading of stored evidence (and transmits
|
||||
|
||||
+341
-226
@@ -1,4 +1,4 @@
|
||||
"""The Mesh Atlas: the mesh's observed shape, drawn as a live braille link graph.
|
||||
"""The Mesh Atlas: the mesh's observed shape, drawn as an explorable braille graph.
|
||||
|
||||
The interactive face of the ``atlas`` tool. The trace path composer already distills
|
||||
every fragment of topology we ever received — trace walks, firmware routes, RX-logged
|
||||
@@ -7,24 +7,26 @@ relay chains, repeater neighbour tables — into one evidence graph
|
||||
here transmits: the atlas is a reading of what the radio has already heard.
|
||||
|
||||
Our own node anchors the centre and every other node sits on a concentric ring at its
|
||||
evidenced hop distance, so the picture answers the mesh's first spatial question — *how
|
||||
far out is everything?* — at a glance. Edges are braille lines coloured by the link's
|
||||
median SNR (green → amber → red, slate for links with no reading) and faded by evidence
|
||||
age, drawn on the same :class:`~meshterm.ui.mapcanvas.MapCanvas` the street map uses.
|
||||
Evidence islands — link clusters we know of only through a repeater's neighbour table,
|
||||
with no observed path back to us — ride an outermost ring of their own.
|
||||
evidenced hop distance — the rings are drawn as faint dotted guides, so the picture
|
||||
answers *how far out is everything?* like a radar scope. Angles come from the
|
||||
:mod:`~meshterm.services.atlas_layout` relaxation, so linked nodes gather into wedges
|
||||
instead of piling onto one line. Edges are braille lines coloured by the link's median
|
||||
SNR (green → amber → red, slate for links with no reading) and faded by evidence age.
|
||||
|
||||
``←``/``→`` walk the graph node by node: the selection brightens its links, dims the
|
||||
rest, and fills the bottom panel with the node's links strongest-first; ``Enter`` floats
|
||||
a detail dialog with every link's readings. ``r`` rebuilds from storage (new evidence
|
||||
lands while the screen is open), ``Esc`` backs out.
|
||||
The camera is the map's: **arrows pan** (Shift for fine), **PgUp/PgDn zoom**, and
|
||||
**Home** resets to the full fit — so a tangle that reads as noise at 1× opens right up
|
||||
at 4×, with the label budget growing as the zoom does. **Typing finds nodes** (matches
|
||||
keep bright labels, everything else dims; ``Enter`` selects the first match), **Tab**
|
||||
walks the graph selection node by node (recentring when the selection is off-screen),
|
||||
``Enter`` floats the selected node's per-link details, ``Ctrl+R`` rebuilds from
|
||||
storage, and ``Esc`` peels find → selection → screen. The bottom panel reads the
|
||||
overview, the selection, or the find state, whichever is active.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
import zlib
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Callable, Optional
|
||||
|
||||
@@ -36,6 +38,7 @@ from ..core.models import (
|
||||
Contact,
|
||||
utcnow,
|
||||
)
|
||||
from ..services.atlas_layout import AtlasLayout, compute_layout
|
||||
from ..services.topology import Link, MeshTopology
|
||||
from .map_render import _NODE, _REPEATER, _SELF
|
||||
from .mapcanvas import RGB, MapCanvas, parse_hex
|
||||
@@ -47,10 +50,8 @@ from .widgets import _format_age
|
||||
if TYPE_CHECKING:
|
||||
from ..context import AppContext
|
||||
|
||||
_TAU = math.tau
|
||||
|
||||
#: Horizontal / vertical dot-space margins the ring layout keeps clear of the canvas
|
||||
#: edge, so a node's marker glyph and its collision-avoided label have room to land.
|
||||
#: Horizontal / vertical dot-space margins the 1× fit keeps clear of the canvas edge,
|
||||
#: so an outermost node's marker and label have room to land.
|
||||
_PAD_X_DOTS = 16
|
||||
_PAD_Y_DOTS = 5
|
||||
|
||||
@@ -60,11 +61,24 @@ _PANEL_H = 4
|
||||
#: The widest a node label may render on the canvas before it is ellipsized.
|
||||
_LABEL_W = 16
|
||||
|
||||
#: Radians each successive ring is twisted beyond its wish-fitted rotation. Sparse
|
||||
#: rings (a two-node mesh is *pairs* all the way out) would otherwise all align along
|
||||
#: their parents' axis and the whole graph would degenerate to one crowded line; the
|
||||
#: twist staggers the rings so markers and labels get their own rows.
|
||||
_RING_TWIST = 0.55
|
||||
#: Zoom bounds and the factor one PgUp/PgDn step multiplies by. 1.0 is the full fit;
|
||||
#: the ceiling is deep enough to open up any realistic wedge of nodes.
|
||||
_ZOOM_MIN = 1.0
|
||||
_ZOOM_MAX = 12.0
|
||||
_ZOOM_STEP = 1.5
|
||||
|
||||
#: Fraction of the visible span one coarse pan keypress moves the camera.
|
||||
_PAN_STEP = 0.30
|
||||
|
||||
#: How many labels the canvas offers at 1×; the budget grows with the zoom's square
|
||||
#: (zooming in *creates* the space the labels need). Selection, find matches, and our
|
||||
#: own node are always offered regardless.
|
||||
_LABEL_BUDGET_BASE = 6
|
||||
|
||||
#: Ring-guide dot colour — dark slate, beneath every edge — and the dot-space gap
|
||||
#: between its dots (sparse enough to read as a guide, not a feature).
|
||||
_RING_RGB: RGB = (52, 61, 78)
|
||||
_RING_DOT_GAP = 4.0
|
||||
|
||||
#: SNR (dB) → edge colour anchors, interpolated linearly and clamped at the ends: the
|
||||
#: red/amber/green of the app's snr styles, so the graph and the tables agree.
|
||||
@@ -80,6 +94,9 @@ _NO_READING: RGB = (100, 116, 139)
|
||||
#: Marker style for a node no contact matches — heard of, never identified.
|
||||
_UNKNOWN = ("○", "#94a3b8")
|
||||
|
||||
#: Label colour for find-filter matches: full white, the brightest thing drawn.
|
||||
_MATCH_LABEL: RGB = (255, 255, 255)
|
||||
|
||||
|
||||
def _snr_rgb(snr: Optional[float]) -> RGB:
|
||||
"""The edge colour for a link's median SNR (see :data:`_SNR_STOPS`)."""
|
||||
@@ -113,137 +130,10 @@ def _freshness(last_seen: Optional[datetime], now: datetime) -> float:
|
||||
return 0.5
|
||||
|
||||
|
||||
def _hash_angle(node: str) -> float:
|
||||
"""A deterministic per-node angle, so a node keeps its bearing across rebuilds.
|
||||
|
||||
Derived from a CRC of the canonical id rather than :func:`hash`, which Python
|
||||
salts per process — the whole point is that YUL sits at the same clock position
|
||||
tomorrow as today.
|
||||
"""
|
||||
return zlib.crc32(node.encode()) / 0xFFFFFFFF * _TAU
|
||||
|
||||
|
||||
def _ring_angles(desired: dict[str, float], twist: float = 0.0) -> dict[str, float]:
|
||||
"""Distribute one ring's members evenly, honouring their desired bearings.
|
||||
|
||||
Members are placed at exactly even angular slots — the only spacing that keeps
|
||||
markers and their labels apart on a crowded ring — but in the *order* of the
|
||||
angles they wished for, and with the whole ring rotated to the circular best
|
||||
fit of those wishes plus ``twist`` (see :data:`_RING_TWIST`). A child therefore
|
||||
still comes out on its parent's side of the graph; it just never piles onto a
|
||||
sibling, and successive rings never fall into one straight line.
|
||||
"""
|
||||
if not desired:
|
||||
return {}
|
||||
ordered = sorted(desired, key=lambda n: desired[n] % _TAU)
|
||||
count = len(ordered)
|
||||
slots = [i * _TAU / count for i in range(count)]
|
||||
sin_sum = sum(math.sin(desired[n] - s) for n, s in zip(ordered, slots))
|
||||
cos_sum = sum(math.cos(desired[n] - s) for n, s in zip(ordered, slots))
|
||||
phase = math.atan2(sin_sum, cos_sum) if (sin_sum or cos_sum) else 0.0
|
||||
return {n: (s + phase + twist) % _TAU for n, s in zip(ordered, slots)}
|
||||
|
||||
|
||||
def radial_layout(
|
||||
self_id: str,
|
||||
links: list[tuple[str, str, float]],
|
||||
dot_w: int,
|
||||
dot_h: int,
|
||||
) -> tuple[dict[str, tuple[int, int]], dict[str, int], frozenset[str]]:
|
||||
"""Place every linked node on concentric rings around our own node.
|
||||
|
||||
Rings are evidenced hop distance (BFS over the link graph from ``self_id``);
|
||||
nodes with no observed path to us — evidence islands — take one shared ring
|
||||
outside everything reached. Within a ring each node *wants* the angle of its
|
||||
strongest parent one ring in (ring one and islands want a stable per-id hash
|
||||
angle instead), and the wishes are then pushed apart (:func:`_relax`) so markers
|
||||
and labels never pile up. Rings span an ellipse fitted to the canvas, using the
|
||||
terminal's width rather than forcing a circle into it.
|
||||
|
||||
Args:
|
||||
self_id: Canonical id of our own node (always placed, even with no links).
|
||||
links: The evidence graph as ``(a, b, strength)`` triples.
|
||||
dot_w: Canvas width in braille dots.
|
||||
dot_h: Canvas height in braille dots.
|
||||
|
||||
Returns:
|
||||
``(positions, rings, islands)``: dot-space coordinates per node, the ring
|
||||
number per node (0 = us), and the ids that had no path back to us.
|
||||
"""
|
||||
adjacency: dict[str, dict[str, float]] = {self_id: {}}
|
||||
for a, b, strength in links:
|
||||
adjacency.setdefault(a, {})
|
||||
adjacency.setdefault(b, {})
|
||||
adjacency[a][b] = max(strength, adjacency[a].get(b, 0.0))
|
||||
adjacency[b][a] = max(strength, adjacency[b].get(a, 0.0))
|
||||
|
||||
rings: dict[str, int] = {self_id: 0}
|
||||
frontier = [self_id]
|
||||
while frontier:
|
||||
nxt: list[str] = []
|
||||
for node in frontier:
|
||||
for other in adjacency.get(node, {}):
|
||||
if other not in rings:
|
||||
rings[other] = rings[node] + 1
|
||||
nxt.append(other)
|
||||
frontier = nxt
|
||||
|
||||
islands = frozenset(n for n in adjacency if n not in rings)
|
||||
if islands:
|
||||
island_ring = max(rings.values(), default=0) + 1
|
||||
for node in islands:
|
||||
rings[node] = island_ring
|
||||
max_ring = max(rings.values(), default=0)
|
||||
|
||||
angles: dict[str, float] = {self_id: 0.0}
|
||||
for ring in range(1, max_ring + 1):
|
||||
members = sorted(n for n, r in rings.items() if r == ring)
|
||||
if not members:
|
||||
continue
|
||||
desired: dict[str, float] = {}
|
||||
for node in members:
|
||||
parents = sorted(
|
||||
(
|
||||
(strength, p)
|
||||
for p, strength in adjacency.get(node, {}).items()
|
||||
if rings.get(p) == ring - 1 and p in angles and rings[p] > 0
|
||||
),
|
||||
key=lambda t: -t[0],
|
||||
)
|
||||
if parents:
|
||||
# Near the strongest parent, offset a touch by identity so siblings
|
||||
# wish for distinct bearings before the even spacing orders them.
|
||||
desired[node] = (
|
||||
angles[parents[0][1]] + (_hash_angle(node) / _TAU - 0.5) * 0.4
|
||||
)
|
||||
else:
|
||||
# Ring one (and any orphan) wishes for its stable per-id bearing, so
|
||||
# a node keeps roughly the same clock position across rebuilds.
|
||||
desired[node] = _hash_angle(node)
|
||||
angles.update(_ring_angles(desired, twist=_RING_TWIST * (ring - 1)))
|
||||
|
||||
cx, cy = dot_w / 2.0, dot_h / 2.0
|
||||
rx = max(8.0, dot_w / 2.0 - _PAD_X_DOTS)
|
||||
ry = max(6.0, dot_h / 2.0 - _PAD_Y_DOTS)
|
||||
positions: dict[str, tuple[int, int]] = {}
|
||||
for node, ring in rings.items():
|
||||
if ring == 0:
|
||||
positions[node] = (round(cx), round(cy))
|
||||
continue
|
||||
frac = ring / max_ring if max_ring else 1.0
|
||||
a = angles[node]
|
||||
positions[node] = (
|
||||
round(cx + rx * frac * math.cos(a)),
|
||||
round(cy + ry * frac * math.sin(a)),
|
||||
)
|
||||
return positions, rings, islands
|
||||
|
||||
|
||||
class AtlasScreen(Screen):
|
||||
"""The full-screen atlas: canvas on top, a live info panel along the bottom."""
|
||||
"""The full-screen atlas: pannable/zoomable canvas, a live info panel beneath."""
|
||||
|
||||
floating = False
|
||||
footer_hint = "←/→ walk nodes · Enter details · r rebuild · Esc back"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -261,7 +151,7 @@ class AtlasScreen(Screen):
|
||||
topo: The evidence graph to draw.
|
||||
contacts: Contacts keyed by canonical id, for glyphs, names, and ages.
|
||||
self_label: Display name for our own node (its mesh name when known).
|
||||
rebuild: Rebuilds the graph from storage for the ``r`` key; ``None``
|
||||
rebuild: Rebuilds the graph from storage for the ``Ctrl+R`` key; ``None``
|
||||
leaves the snapshot fixed (tests, and the odd caller without a repo).
|
||||
"""
|
||||
super().__init__()
|
||||
@@ -272,54 +162,140 @@ class AtlasScreen(Screen):
|
||||
self._rebuild = rebuild
|
||||
#: Selected canonical id, or ``None`` for the whole-mesh overview.
|
||||
self._selected: Optional[str] = None
|
||||
#: Selection cycle: us first, then rings inside-out, each ring by angle.
|
||||
#: Tab cycle: us first, then rings inside-out, each ring by angle.
|
||||
self._cycle: list[str] = []
|
||||
self._positions: dict[str, tuple[int, int]] = {}
|
||||
self._rings: dict[str, int] = {}
|
||||
self._islands: frozenset[str] = frozenset()
|
||||
self._layout_key: Optional[tuple[int, int, int]] = None
|
||||
#: The camera: zoom (1.0 = the whole graph fits) and its unit-space centre.
|
||||
self._zoom = _ZOOM_MIN
|
||||
self._cam = (0.0, 0.0)
|
||||
#: The live find-as-you-type node filter ("" = off).
|
||||
self._filter = ""
|
||||
#: A node to bring on-screen at the next paint (set by Tab / find-select).
|
||||
self._reveal: Optional[str] = None
|
||||
self._layout: Optional[AtlasLayout] = None
|
||||
self._layout_generation: Optional[int] = None
|
||||
self._generation = 0 # bumped by rebuild so the layout cache invalidates
|
||||
self._dot_size = (2, 2) # dot-space canvas size, recorded each render
|
||||
self._dialog_open = False
|
||||
self._needs_scrub = True # braille smear scrub, exactly like the map
|
||||
|
||||
# --- input -----------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def footer_hint(self) -> str: # type: ignore[override]
|
||||
"""Camera and find hints; the find query takes the row over while active."""
|
||||
if self._filter:
|
||||
return f"find: {self._filter}▏ · Enter select · Bksp erase · Esc clear"
|
||||
return "↑↓←→ pan · PgUp/PgDn zoom · Tab walk · Enter info · type to find · Esc"
|
||||
|
||||
def handle(self, action: str, data: str = "") -> None:
|
||||
"""Walk the selection, open details, rebuild, or dismiss."""
|
||||
"""Pan, zoom, walk, find, rebuild, or dismiss.
|
||||
|
||||
Every printable key feeds the find filter — no letters are bound to actions —
|
||||
and Esc peels one layer at a time: the filter, then the selection, then the
|
||||
screen itself.
|
||||
"""
|
||||
if action == "escape":
|
||||
self.resolve(None)
|
||||
return
|
||||
if action in ("right", "down", "tab"):
|
||||
self._step_selection(1)
|
||||
elif action in ("left", "up"):
|
||||
self._step_selection(-1)
|
||||
elif action == "enter":
|
||||
self._open_details()
|
||||
elif action == "text":
|
||||
low = data.lower()
|
||||
if low == "r":
|
||||
self._do_rebuild()
|
||||
elif low == "q":
|
||||
if self._filter:
|
||||
self._filter = ""
|
||||
elif self._selected is not None:
|
||||
self._selected = None
|
||||
else:
|
||||
self.resolve(None)
|
||||
return
|
||||
elif action in ("up", "down", "left", "right"):
|
||||
self._pan(action, fine=False)
|
||||
elif action.startswith("shift_") and action[len("shift_"):] in (
|
||||
"up", "down", "left", "right",
|
||||
):
|
||||
self._pan(action[len("shift_"):], fine=True)
|
||||
elif action == "pageup":
|
||||
self._set_zoom(self._zoom * _ZOOM_STEP)
|
||||
elif action == "pagedown":
|
||||
self._set_zoom(self._zoom / _ZOOM_STEP)
|
||||
elif action in ("home", "ctrl_home"):
|
||||
self._zoom = _ZOOM_MIN
|
||||
self._cam = (0.0, 0.0)
|
||||
elif action == "tab":
|
||||
self._step_selection(1)
|
||||
elif action == "enter":
|
||||
self._commit_enter()
|
||||
elif action == "text":
|
||||
self._filter += data
|
||||
elif action == "space" and self._filter:
|
||||
self._filter += " " # node names carry spaces; only meaningful mid-query
|
||||
elif action == "backspace":
|
||||
self._filter = self._filter[:-1]
|
||||
elif action == "retry": # Ctrl+R
|
||||
self._do_rebuild()
|
||||
self._needs_scrub = True
|
||||
self._session.invalidate()
|
||||
|
||||
def _pan(self, direction: str, *, fine: bool) -> None:
|
||||
"""Move the camera one step (or one character cell, when ``fine``).
|
||||
|
||||
The step is a fraction of the *visible* unit span, so panning covers the same
|
||||
on-screen distance at every zoom; the camera is then clamped so the graph can
|
||||
never be lost off-screen (at 1× it snaps back to centre).
|
||||
"""
|
||||
dx = {"left": -1, "right": 1}.get(direction, 0)
|
||||
dy = {"up": -1, "down": 1}.get(direction, 0)
|
||||
span = 2.0 / self._zoom # the visible extent of unit space, edge to edge
|
||||
step = span * (_PAN_STEP / 8 if fine else _PAN_STEP)
|
||||
self._cam = (self._cam[0] + dx * step, self._cam[1] + dy * step)
|
||||
self._clamp_cam()
|
||||
|
||||
def _set_zoom(self, zoom: float) -> None:
|
||||
"""Clamp and apply a zoom level, re-clamping the camera to the new range."""
|
||||
self._zoom = max(_ZOOM_MIN, min(_ZOOM_MAX, zoom))
|
||||
self._clamp_cam()
|
||||
|
||||
def _clamp_cam(self) -> None:
|
||||
"""Keep the camera within the graph: the pan range grows as the zoom does.
|
||||
|
||||
At 1× the whole graph is on screen and the only sensible centre is the
|
||||
origin; each zoom step frees ``1 - 1/zoom`` of unit space per side (plus a
|
||||
small overshoot so an edge node can be centred).
|
||||
"""
|
||||
limit = max(0.0, 1.0 - 1.0 / self._zoom) * 1.1
|
||||
self._cam = (
|
||||
max(-limit, min(limit, self._cam[0])),
|
||||
max(-limit, min(limit, self._cam[1])),
|
||||
)
|
||||
|
||||
def _step_selection(self, delta: int) -> None:
|
||||
"""Cycle ``… → overview → us → ring by ring …`` in either direction."""
|
||||
"""Cycle ``… → overview → us → ring by ring …`` and reveal the new selection."""
|
||||
if not self._cycle:
|
||||
return
|
||||
stops: list[Optional[str]] = [None, *self._cycle]
|
||||
at = stops.index(self._selected) if self._selected in stops else 0
|
||||
self._selected = stops[(at + delta) % len(stops)]
|
||||
self._reveal = self._selected
|
||||
|
||||
def _matches(self) -> list[str]:
|
||||
"""Nodes the live find filter matches, in the Tab cycle's stable order."""
|
||||
needle = self._filter.casefold()
|
||||
if not needle:
|
||||
return []
|
||||
return [n for n in self._cycle if needle in self._label(n).casefold()]
|
||||
|
||||
def _commit_enter(self) -> None:
|
||||
"""Enter: adopt the find's first match, or open the selection's details."""
|
||||
if self._filter:
|
||||
matches = self._matches()
|
||||
if matches:
|
||||
self._selected = matches[0]
|
||||
self._reveal = matches[0]
|
||||
self._filter = ""
|
||||
return
|
||||
if self._selected is not None:
|
||||
self._open_details()
|
||||
|
||||
def _do_rebuild(self) -> None:
|
||||
"""Re-read the evidence and relayout, keeping the selection when it survives."""
|
||||
if self._rebuild is None:
|
||||
return
|
||||
self._topo = self._rebuild()
|
||||
self._generation += 1
|
||||
self._layout_key = None # force a relayout on the next paint
|
||||
self._generation += 1 # the next paint recomputes the layout
|
||||
|
||||
def _open_details(self) -> None:
|
||||
"""Float the selected node's full link listing over the atlas."""
|
||||
@@ -351,28 +327,101 @@ class AtlasScreen(Screen):
|
||||
self._needs_scrub = False
|
||||
return 2
|
||||
|
||||
# --- projection --------------------------------------------------------------------
|
||||
|
||||
def _project(self, unit: tuple[float, float]) -> tuple[int, int]:
|
||||
"""Unit-space → dot-space through the current camera (aspect, zoom, pan)."""
|
||||
dot_w, dot_h = self._dot_size
|
||||
rx = max(8.0, dot_w / 2.0 - _PAD_X_DOTS)
|
||||
ry = max(6.0, dot_h / 2.0 - _PAD_Y_DOTS)
|
||||
x = dot_w / 2.0 + (unit[0] - self._cam[0]) * rx * self._zoom
|
||||
y = dot_h / 2.0 + (unit[1] - self._cam[1]) * ry * self._zoom
|
||||
return round(x), round(y)
|
||||
|
||||
def _reveal_if_offscreen(self, node: str) -> None:
|
||||
"""Centre the camera on ``node`` if it currently projects off the canvas."""
|
||||
layout = self._layout
|
||||
if layout is None or node not in layout.positions:
|
||||
return
|
||||
dot_w, dot_h = self._dot_size
|
||||
x, y = self._project(layout.positions[node])
|
||||
if 0 <= x < dot_w and 0 <= y < dot_h:
|
||||
return
|
||||
self._cam = layout.positions[node]
|
||||
self._clamp_cam()
|
||||
|
||||
# --- rendering ---------------------------------------------------------------------
|
||||
|
||||
def render_body(self, width: int) -> list[str]:
|
||||
"""Draw the graph canvas and the info panel to exactly the viewport height."""
|
||||
"""Draw the ring guides, edges, markers, and labels, then the info panel."""
|
||||
_, cell_h = self._session.base_body_size()
|
||||
canvas_h = max(4, cell_h - _PANEL_H)
|
||||
self._dot_size = (width * 2, canvas_h * 4)
|
||||
|
||||
links = self._topo.links()
|
||||
self.title = (
|
||||
f"Mesh Atlas · {max(0, len(self._layout_nodes(links)) )} nodes"
|
||||
f" · {len(links)} links"
|
||||
)
|
||||
matches = self._matches()
|
||||
self.title = self._compose_title(links, matches)
|
||||
if not links:
|
||||
return self._empty_state(width)
|
||||
|
||||
self._ensure_layout(width * 2, canvas_h * 4, links)
|
||||
self._ensure_layout(links)
|
||||
if self._reveal is not None:
|
||||
self._reveal_if_offscreen(self._reveal)
|
||||
self._reveal = None
|
||||
layout = self._layout
|
||||
assert layout is not None # _ensure_layout just ran
|
||||
|
||||
canvas = MapCanvas(width, canvas_h)
|
||||
now = utcnow()
|
||||
match_set = set(matches)
|
||||
|
||||
self._draw_rings(canvas, layout)
|
||||
self._draw_edges(canvas, layout, links, now, match_set)
|
||||
self._draw_nodes(canvas, layout, match_set)
|
||||
|
||||
return canvas.to_ansi_lines() + self._panel_lines(width, links, matches)
|
||||
|
||||
def _compose_title(self, links: list[Link], matches: list[str]) -> str:
|
||||
"""The status title: counts, the zoom level, and the find tally when active."""
|
||||
nodes = len(self._layout_nodes(links))
|
||||
title = f"Mesh Atlas · {nodes} nodes · {len(links)} links"
|
||||
if self._zoom > _ZOOM_MIN:
|
||||
title += f" · {self._zoom:.1f}×"
|
||||
if self._filter:
|
||||
title += f" · {len(matches)} match{'es' if len(matches) != 1 else ''}"
|
||||
return title
|
||||
|
||||
def _draw_rings(self, canvas: MapCanvas, layout: AtlasLayout) -> None:
|
||||
"""Dot the hop-ring guides under everything: the atlas's radar-scope grid.
|
||||
|
||||
Each ring is sampled at a spacing that lands one dot every
|
||||
:data:`_RING_DOT_GAP` dots of on-screen arc, so the guides stay sparse at 1×
|
||||
and don't thicken as the zoom multiplies their radius.
|
||||
"""
|
||||
dot_w, dot_h = self._dot_size
|
||||
rx = max(8.0, dot_w / 2.0 - _PAD_X_DOTS) * self._zoom
|
||||
ry = max(6.0, dot_h / 2.0 - _PAD_Y_DOTS) * self._zoom
|
||||
for ring in range(1, layout.max_ring + 1):
|
||||
radius = ring / layout.max_ring
|
||||
arc = math.tau * radius * max(rx, ry) # on-screen circumference, roughly
|
||||
samples = max(24, int(arc / _RING_DOT_GAP))
|
||||
for i in range(samples):
|
||||
angle = i / samples * math.tau
|
||||
x, y = self._project((radius * math.cos(angle), radius * math.sin(angle)))
|
||||
canvas.plot(x, y, _RING_RGB, 0)
|
||||
|
||||
def _draw_edges(
|
||||
self,
|
||||
canvas: MapCanvas,
|
||||
layout: AtlasLayout,
|
||||
links: list[Link],
|
||||
now: datetime,
|
||||
match_set: set[str],
|
||||
) -> None:
|
||||
"""Draw every link, emphasis following the selection or the find filter."""
|
||||
for link in links:
|
||||
pa = self._positions.get(link.a)
|
||||
pb = self._positions.get(link.b)
|
||||
pa = layout.positions.get(link.a)
|
||||
pb = layout.positions.get(link.b)
|
||||
if pa is None or pb is None:
|
||||
continue
|
||||
color = _scaled(_snr_rgb(link.median_snr), _freshness(link.last_seen, now))
|
||||
@@ -383,28 +432,63 @@ class AtlasScreen(Screen):
|
||||
else:
|
||||
color = _scaled(color, 0.3)
|
||||
priority = 1
|
||||
canvas.draw_line([pa, pb], color, priority)
|
||||
elif match_set and not (link.a in match_set or link.b in match_set):
|
||||
color = _scaled(color, 0.3)
|
||||
priority = 1
|
||||
canvas.draw_line([self._project(pa), self._project(pb)], color, priority)
|
||||
|
||||
for node in self._marker_order():
|
||||
x, y = self._positions[node]
|
||||
def _draw_nodes(
|
||||
self, canvas: MapCanvas, layout: AtlasLayout, match_set: set[str]
|
||||
) -> None:
|
||||
"""Place markers, then labels in importance order under the zoom's budget.
|
||||
|
||||
Markers always draw (they are the point of the graph); labels are the scarce
|
||||
resource. The budget starts at :data:`_LABEL_BUDGET_BASE` for the 1× overview
|
||||
and grows with the square of the zoom — zooming in is what creates label room
|
||||
— while the selection, find matches, and our own node are always offered.
|
||||
The canvas's collision avoidance still gets the final say, so a label that
|
||||
doesn't fit cleanly is dropped rather than overprinting a neighbour.
|
||||
"""
|
||||
order = self._marker_order(match_set)
|
||||
for node in order:
|
||||
x, y = self._project(layout.positions[node])
|
||||
glyph, color_hex = self._glyph(node)
|
||||
rgb = (255, 255, 255) if node == self._selected else parse_hex(color_hex)
|
||||
rgb = parse_hex(color_hex)
|
||||
if node == self._selected:
|
||||
rgb = (255, 255, 255)
|
||||
elif match_set and node not in match_set:
|
||||
rgb = _scaled(rgb, 0.35)
|
||||
canvas.marker(x, y, glyph, rgb)
|
||||
for node in self._marker_order():
|
||||
x, y = self._positions[node]
|
||||
|
||||
budget = int(_LABEL_BUDGET_BASE * self._zoom * self._zoom)
|
||||
placed = 0
|
||||
for node in order:
|
||||
always = (
|
||||
node == self._selected
|
||||
or node == self._topo.self_id
|
||||
or node in match_set
|
||||
)
|
||||
if not always and placed >= budget:
|
||||
continue
|
||||
if match_set and not always:
|
||||
continue # while finding, non-matches stay as dim context glyphs
|
||||
x, y = self._project(layout.positions[node])
|
||||
label = self._label(node)
|
||||
if len(label) > _LABEL_W:
|
||||
label = label[: _LABEL_W - 1] + "…"
|
||||
_, color_hex = self._glyph(node)
|
||||
rgb = (255, 255, 255) if node == self._selected else parse_hex(color_hex)
|
||||
# Both sides of a crowded marker (the centre, typically) can be claimed;
|
||||
# retry a cell below, then above, before giving the label up entirely.
|
||||
if node in match_set:
|
||||
rgb = _MATCH_LABEL
|
||||
elif node == self._selected:
|
||||
rgb = (255, 255, 255)
|
||||
else:
|
||||
rgb = parse_hex(self._glyph(node)[1])
|
||||
# Both sides of a crowded marker can be claimed; retry a cell below,
|
||||
# then above, before giving the label up entirely.
|
||||
for dy in (0, 4, -4):
|
||||
if canvas.marker_label(x, y + dy, label, rgb):
|
||||
placed += 1
|
||||
break
|
||||
|
||||
return canvas.to_ansi_lines() + self._panel_lines(width, links)
|
||||
|
||||
def _empty_state(self, width: int) -> list[str]:
|
||||
"""A friendly explanation while the evidence graph is still empty."""
|
||||
lines = [
|
||||
@@ -428,43 +512,52 @@ class AtlasScreen(Screen):
|
||||
nodes.add(link.b)
|
||||
return nodes
|
||||
|
||||
def _ensure_layout(self, dot_w: int, dot_h: int, links: list[Link]) -> None:
|
||||
"""(Re)compute positions when the canvas size or the evidence changed."""
|
||||
key = (dot_w, dot_h, self._generation)
|
||||
if key == self._layout_key:
|
||||
def _ensure_layout(self, links: list[Link]) -> None:
|
||||
"""(Re)compute the unit-space layout when the evidence generation changed.
|
||||
|
||||
The layout is camera-independent (zoom and pan happen at projection time),
|
||||
so moving the view never pays for a relayout — only fresh evidence does.
|
||||
"""
|
||||
if self._layout is not None and self._layout_generation == self._generation:
|
||||
return
|
||||
self._layout_key = key
|
||||
now = utcnow()
|
||||
triples = [(l.a, l.b, l.strength(now)) for l in links]
|
||||
self._positions, self._rings, self._islands = radial_layout(
|
||||
self._topo.self_id, triples, dot_w, dot_h
|
||||
)
|
||||
self._layout = compute_layout(self._topo.self_id, triples)
|
||||
self._layout_generation = self._generation
|
||||
angle = {
|
||||
node: math.atan2(y, x) % math.tau
|
||||
for node, (x, y) in self._layout.positions.items()
|
||||
}
|
||||
order = sorted(
|
||||
(n for n in self._positions if n != self._topo.self_id),
|
||||
key=lambda n: (self._rings.get(n, 99), _hash_angle(n)),
|
||||
(n for n in self._layout.positions if n != self._topo.self_id),
|
||||
key=lambda n: (self._layout.rings.get(n, 99), angle[n]),
|
||||
)
|
||||
self._cycle = [self._topo.self_id, *order]
|
||||
if self._selected is not None and self._selected not in self._positions:
|
||||
if self._selected is not None and self._selected not in self._layout.positions:
|
||||
self._selected = None # the rebuild dropped it
|
||||
|
||||
def _marker_order(self) -> list[str]:
|
||||
"""Marker/label placement order: the selection first (its label must win),
|
||||
then us, then repeaters, then everything else working outward."""
|
||||
def _marker_order(self, match_set: set[str]) -> list[str]:
|
||||
"""Marker/label priority: selection, matches, us, repeaters, then outward."""
|
||||
layout = self._layout
|
||||
assert layout is not None
|
||||
|
||||
def rank(node: str) -> tuple[int, int, float]:
|
||||
def rank(node: str) -> tuple[int, int, str]:
|
||||
if node == self._selected:
|
||||
lead = 0
|
||||
elif node == self._topo.self_id:
|
||||
elif node in match_set:
|
||||
lead = 1
|
||||
elif self._contacts.get(node) is not None and (
|
||||
self._contacts[node].node_type == NODE_TYPE_REPEATER
|
||||
):
|
||||
elif node == self._topo.self_id:
|
||||
lead = 2
|
||||
else:
|
||||
elif (
|
||||
self._contacts.get(node) is not None
|
||||
and self._contacts[node].node_type == NODE_TYPE_REPEATER
|
||||
):
|
||||
lead = 3
|
||||
return (lead, self._rings.get(node, 99), _hash_angle(node))
|
||||
else:
|
||||
lead = 4
|
||||
return (lead, layout.rings.get(node, 99), node)
|
||||
|
||||
return sorted(self._positions, key=rank)
|
||||
return sorted(layout.positions, key=rank)
|
||||
|
||||
def _glyph(self, node: str) -> tuple[str, str]:
|
||||
"""The marker glyph and hex colour for a node, by identity and type."""
|
||||
@@ -485,17 +578,38 @@ class AtlasScreen(Screen):
|
||||
|
||||
# --- the info panel ------------------------------------------------------------
|
||||
|
||||
def _panel_lines(self, width: int, links: list[Link]) -> list[str]:
|
||||
"""The bottom panel: a spacer plus three lines of overview or selection."""
|
||||
if self._selected is None:
|
||||
rows = self._overview_rows(links)
|
||||
else:
|
||||
def _panel_lines(self, width: int, links: list[Link], matches: list[str]) -> list[str]:
|
||||
"""The bottom panel: a spacer plus three lines of find, selection, or overview."""
|
||||
if self._filter:
|
||||
rows = self._find_rows(matches)
|
||||
elif self._selected is not None:
|
||||
rows = self._selection_rows(self._selected)
|
||||
else:
|
||||
rows = self._overview_rows(links)
|
||||
rows = (rows + [Text()] * 3)[:3]
|
||||
return [""] + [render_to_ansi(t, width, no_wrap=True) for t in rows]
|
||||
|
||||
def _find_rows(self, matches: list[str]) -> list[Text]:
|
||||
"""The find state: the query's tally and who matched, brightest first."""
|
||||
tally = Text("find ", style="muted")
|
||||
tally.append(self._filter, style="bold")
|
||||
tally.append(
|
||||
f" · {len(matches)} of {max(0, len(self._cycle))} nodes match",
|
||||
style="muted",
|
||||
)
|
||||
names = Text(" ", style="muted")
|
||||
for i, node in enumerate(matches[:6]):
|
||||
if i:
|
||||
names.append(" · ", style="muted")
|
||||
names.append(self._label(node), style="bold")
|
||||
if len(matches) > 6:
|
||||
names.append(f" · +{len(matches) - 6} more", style="muted")
|
||||
hint = Text(" Enter selects the first match", style="muted")
|
||||
return [tally, names if matches else Text(" no matches", style="muted"), hint]
|
||||
|
||||
def _overview_rows(self, links: list[Link]) -> list[Text]:
|
||||
"""Legend, evidence tallies, and the graph's age span."""
|
||||
# Legend text budgeted to a 72-column terminal (the panel rows never wrap).
|
||||
legend = Text()
|
||||
for glyph, color in (_SELF, _REPEATER, _NODE, _UNKNOWN):
|
||||
legend.append(glyph, style=color)
|
||||
@@ -503,7 +617,7 @@ class AtlasScreen(Screen):
|
||||
{"★": " you ", "▲": " repeater ", "●": " node ", "○": " unknown"}[glyph],
|
||||
style="muted",
|
||||
)
|
||||
legend.append(" · edge colour = SNR · faint = stale", style="muted")
|
||||
legend.append(" · edge = SNR · faint = stale", style="muted")
|
||||
|
||||
counts = {
|
||||
src: sum(1 for l in links if src in l.sources)
|
||||
@@ -512,7 +626,7 @@ class AtlasScreen(Screen):
|
||||
evidence = Text("evidence ", style="muted")
|
||||
parts = [f"{src} {n}" for src, n in counts.items() if n]
|
||||
evidence.append(" · ".join(parts) if parts else "—", style="brand")
|
||||
evidence.append(" (links seen by each source)", style="muted")
|
||||
evidence.append(" (links per source)", style="muted")
|
||||
|
||||
stamps = [l.last_seen for l in links if l.last_seen is not None]
|
||||
span = Text("", style="muted")
|
||||
@@ -523,14 +637,15 @@ class AtlasScreen(Screen):
|
||||
span.append(_format_age(newest), style="brand")
|
||||
span.append(" · oldest ", style="muted")
|
||||
span.append(_format_age(oldest), style="brand")
|
||||
span.append(" · ", style="muted")
|
||||
span.append("←/→ walk the graph", style="muted")
|
||||
span.append(" · ", style="muted")
|
||||
span.append("rings = hops out · Home reset · ^R rebuild", style="muted")
|
||||
return [legend, evidence, span]
|
||||
|
||||
def _selection_rows(self, node: str) -> list[Text]:
|
||||
"""Who the selection is, its links strongest-first, and its evidence roll-up."""
|
||||
glyph, color = self._glyph(node)
|
||||
contact = self._contacts.get(node)
|
||||
layout = self._layout
|
||||
|
||||
who = Text()
|
||||
who.append(glyph, style=color)
|
||||
@@ -545,10 +660,10 @@ class AtlasScreen(Screen):
|
||||
else "unknown node"
|
||||
)
|
||||
who.append(f" · {kind}", style="muted")
|
||||
if node in self._islands:
|
||||
if layout is not None and node in layout.islands:
|
||||
who.append(" · island — no observed path to us", style="warn")
|
||||
else:
|
||||
ring = self._rings.get(node, 0)
|
||||
ring = layout.rings.get(node, 0) if layout is not None else 0
|
||||
who.append(f" · {ring} hop{'s' if ring != 1 else ''} out", style="muted")
|
||||
if contact is not None and contact.last_seen is not None:
|
||||
secs = max(0.0, (utcnow() - contact.last_seen).total_seconds())
|
||||
@@ -632,7 +747,7 @@ async def open_atlas(ctx: "AppContext") -> None:
|
||||
|
||||
Contacts and our own identity come from the device when one is reachable
|
||||
(best-effort — the stored evidence draws fine without them, just with hashes for
|
||||
names), the graph itself comes entirely from the repository, and the ``r`` key
|
||||
names), the graph itself comes entirely from the repository, and ``Ctrl+R``
|
||||
re-reads storage so evidence landing while the screen is open can be pulled in.
|
||||
No transmissions, ever.
|
||||
|
||||
|
||||
+169
-56
@@ -1,4 +1,4 @@
|
||||
"""Mesh Atlas tests: the radial layout and the screen's rendering and selection.
|
||||
"""Mesh Atlas tests: the ring layout service and the screen's camera, find, and panel.
|
||||
|
||||
The layout is a pure function, tested directly; the screen is driven headless against a
|
||||
fake session and a hand-built topology, the same approach as the dashboard tests.
|
||||
@@ -6,12 +6,14 @@ fake session and a hand-built topology, the same approach as the dashboard tests
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from datetime import timedelta
|
||||
|
||||
from meshterm.core.models import Contact, utcnow
|
||||
from meshterm.services.atlas_layout import _MIN_SEPARATION, compute_layout
|
||||
from meshterm.services.topology import MeshTopology
|
||||
from meshterm.ui.atlas_screen import AtlasScreen, radial_layout
|
||||
from meshterm.ui.atlas_screen import AtlasScreen
|
||||
|
||||
US = "aa" * 6
|
||||
YUL = Contact(name="YUL-Cartierville", public_key="3d" * 32, node_type=2)
|
||||
@@ -59,49 +61,61 @@ def _plain(lines: list[str]) -> str:
|
||||
return re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(lines))
|
||||
|
||||
|
||||
# --- the layout ------------------------------------------------------------------------
|
||||
def _radius(pos: tuple[float, float]) -> float:
|
||||
return math.hypot(*pos)
|
||||
|
||||
|
||||
def _angle(pos: tuple[float, float]) -> float:
|
||||
return math.atan2(pos[1], pos[0]) % math.tau
|
||||
|
||||
|
||||
# --- the layout service ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_layout_rings_by_hop_distance() -> None:
|
||||
"""Us at the centre, direct links ring 1, their neighbours ring 2."""
|
||||
links = [(US, "n1", 1.0), ("n1", "n2", 1.0)]
|
||||
positions, rings, islands = radial_layout(US, links, 160, 96)
|
||||
assert rings == {US: 0, "n1": 1, "n2": 2}
|
||||
assert not islands
|
||||
cx, cy = positions[US]
|
||||
d1 = abs(positions["n1"][0] - cx) + abs(positions["n1"][1] - cy)
|
||||
d2 = abs(positions["n2"][0] - cx) + abs(positions["n2"][1] - cy)
|
||||
assert 0 < d1 < d2 # farther evidence, farther out
|
||||
"""Us at the origin, direct links on ring 1, their neighbours on ring 2."""
|
||||
layout = compute_layout(US, [(US, "n1", 1.0), ("n1", "n2", 1.0)])
|
||||
assert layout.rings == {US: 0, "n1": 1, "n2": 2}
|
||||
assert not layout.islands and layout.max_ring == 2
|
||||
assert layout.positions[US] == (0.0, 0.0)
|
||||
assert 0 < _radius(layout.positions["n1"]) < _radius(layout.positions["n2"]) <= 1.0
|
||||
|
||||
|
||||
def test_layout_islands_take_the_outermost_ring() -> None:
|
||||
"""A cluster with no path to us lands outside everything reached."""
|
||||
links = [(US, "n1", 1.0), ("x1", "x2", 1.0)]
|
||||
_positions, rings, islands = radial_layout(US, links, 160, 96)
|
||||
assert islands == {"x1", "x2"}
|
||||
assert rings["x1"] == rings["x2"] == rings["n1"] + 1
|
||||
layout = compute_layout(US, [(US, "n1", 1.0), ("x1", "x2", 1.0)])
|
||||
assert layout.islands == {"x1", "x2"}
|
||||
assert layout.rings["x1"] == layout.rings["x2"] == layout.rings["n1"] + 1
|
||||
|
||||
|
||||
def test_layout_chains_stay_radial() -> None:
|
||||
"""Relaxation pulls a chain's outer node onto its parent's bearing."""
|
||||
layout = compute_layout(US, [(US, "n1", 1.0), ("n1", "n2", 1.0)])
|
||||
gap = abs(_angle(layout.positions["n1"]) - _angle(layout.positions["n2"]))
|
||||
gap = min(gap, math.tau - gap)
|
||||
assert gap < 0.15 # essentially the same bearing: a straight radial spoke
|
||||
|
||||
|
||||
def test_layout_spreads_a_ring_and_stays_deterministic() -> None:
|
||||
"""Ring members never collide, and the same input lays out the same twice."""
|
||||
"""Ring members keep a minimum angular gap, and the same input lays out the same."""
|
||||
links = [(US, f"n{i}", 1.0) for i in range(8)]
|
||||
first = radial_layout(US, links, 200, 120)
|
||||
second = radial_layout(US, links, 200, 120)
|
||||
assert first == second
|
||||
positions = first[0]
|
||||
ring_cells = {(x // 2, y // 4) for n, (x, y) in positions.items() if n != US}
|
||||
assert len(ring_cells) == 8 # every marker in its own character cell
|
||||
first = compute_layout(US, links)
|
||||
second = compute_layout(US, links)
|
||||
assert first.positions == second.positions
|
||||
angles = sorted(_angle(first.positions[f"n{i}"]) for i in range(8))
|
||||
gaps = [b - a for a, b in zip(angles, angles[1:])]
|
||||
gaps.append(math.tau - angles[-1] + angles[0])
|
||||
assert min(gaps) >= min(_MIN_SEPARATION, math.tau / 8) - 1e-6
|
||||
|
||||
|
||||
def test_layout_keeps_nodes_on_canvas() -> None:
|
||||
"""Every position lands within the dot grid, margins included."""
|
||||
links = [(US, f"n{i}", 1.0) for i in range(6)] + [("n0", "m0", 1.0)]
|
||||
positions, _rings, _islands = radial_layout(US, links, 144, 64)
|
||||
for x, y in positions.values():
|
||||
assert 0 <= x < 144 and 0 <= y < 64
|
||||
def test_layout_stays_in_unit_space() -> None:
|
||||
"""Every position lands within the unit circle the screen projects from."""
|
||||
links = [(US, f"n{i}", 1.0) for i in range(6)] + [("n0", "m0", 1.0), ("q1", "q2", 0.5)]
|
||||
layout = compute_layout(US, links)
|
||||
assert all(_radius(p) <= 1.0 + 1e-9 for p in layout.positions.values())
|
||||
|
||||
|
||||
# --- the screen ------------------------------------------------------------------------
|
||||
# --- the screen: rendering ----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_atlas_renders_graph_and_overview_panel() -> None:
|
||||
@@ -112,35 +126,10 @@ def test_atlas_renders_graph_and_overview_panel() -> None:
|
||||
body = _plain(lines)
|
||||
assert "Homestead" in body and "YUL-Cartierville" in body and "Alice" in body
|
||||
assert "trace 1" in body and "packet 1" in body
|
||||
assert "rings = hops out" in body # the overview hint row
|
||||
assert "Mesh Atlas · 3 nodes · 2 links" == screen.title
|
||||
|
||||
|
||||
def test_atlas_selection_walks_and_fills_the_panel() -> None:
|
||||
"""→ steps overview → us → nodes; the panel reads the selection's links."""
|
||||
screen = _screen(_topo())
|
||||
screen.render_body(80) # establish the layout and the cycle
|
||||
screen.handle("right")
|
||||
body = _plain(screen.render_body(80))
|
||||
assert "this device" in body
|
||||
screen.handle("right")
|
||||
body = _plain(screen.render_body(80))
|
||||
assert "repeater" in body and "1 hop out" in body
|
||||
assert "+6.0" in body # the us↔YUL link's median SNR
|
||||
screen.handle("left")
|
||||
screen.handle("left")
|
||||
assert "←/→ walk the graph" in _plain(screen.render_body(80)) # back to overview
|
||||
|
||||
|
||||
def test_atlas_marks_islands_in_the_panel() -> None:
|
||||
"""An island selection says so instead of quoting a bogus hop count."""
|
||||
screen = _screen(_topo(with_island=True))
|
||||
screen.render_body(80)
|
||||
for _ in range(4): # overview → us → YUL → Alice → first island node
|
||||
screen.handle("right")
|
||||
body = _plain(screen.render_body(80))
|
||||
assert "island — no observed path to us" in body
|
||||
|
||||
|
||||
def test_atlas_empty_graph_renders_guidance() -> None:
|
||||
"""With no evidence at all the screen explains how the atlas fills up."""
|
||||
topo = MeshTopology(US, contacts=[])
|
||||
@@ -160,3 +149,127 @@ def test_atlas_details_lists_every_link() -> None:
|
||||
assert "Homestead" in text and "Alice" in text
|
||||
assert "+6.0 dB" in text and "-2.0 dB" in text
|
||||
assert "1×" in text and "trace" in text and "packet" in text
|
||||
|
||||
|
||||
# --- the screen: camera -------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_atlas_zooms_pans_and_resets_like_the_map() -> None:
|
||||
"""PgUp/PgDn step the zoom, arrows pan (clamped), Home restores the full fit."""
|
||||
screen = _screen(_topo())
|
||||
screen.render_body(80)
|
||||
assert screen._zoom == 1.0
|
||||
|
||||
screen.handle("pageup")
|
||||
screen.handle("pageup")
|
||||
assert screen._zoom == 2.25
|
||||
screen.render_body(80)
|
||||
assert "2.2×" in screen.title
|
||||
|
||||
screen.handle("right")
|
||||
screen.handle("down")
|
||||
assert screen._cam != (0.0, 0.0)
|
||||
|
||||
# At 1× the camera clamps back to the origin — the graph can't be lost.
|
||||
screen.handle("pagedown")
|
||||
screen.handle("pagedown")
|
||||
screen.handle("pagedown")
|
||||
assert screen._zoom == 1.0 and screen._cam == (0.0, 0.0)
|
||||
|
||||
screen.handle("pageup")
|
||||
screen.handle("left")
|
||||
screen.handle("home")
|
||||
assert screen._zoom == 1.0 and screen._cam == (0.0, 0.0)
|
||||
|
||||
|
||||
def test_atlas_fine_pan_moves_less_than_coarse() -> None:
|
||||
"""Shift+arrow nudges the camera a fraction of a coarse step."""
|
||||
screen = _screen(_topo())
|
||||
screen.render_body(80)
|
||||
screen.handle("pageup") # free some pan range
|
||||
screen.handle("right")
|
||||
coarse = screen._cam[0]
|
||||
screen.handle("home")
|
||||
screen.handle("pageup")
|
||||
screen.handle("shift_right")
|
||||
assert 0 < screen._cam[0] < coarse
|
||||
|
||||
|
||||
# --- the screen: selection and find --------------------------------------------------------
|
||||
|
||||
|
||||
def test_atlas_tab_walks_and_fills_the_panel() -> None:
|
||||
"""Tab steps overview → us → nodes; the panel reads the selection's links."""
|
||||
screen = _screen(_topo())
|
||||
screen.render_body(80) # establish the layout and the cycle
|
||||
screen.handle("tab")
|
||||
body = _plain(screen.render_body(80))
|
||||
assert "this device" in body
|
||||
screen.handle("tab")
|
||||
body = _plain(screen.render_body(80))
|
||||
assert "repeater" in body and "1 hop out" in body
|
||||
assert "+6.0" in body # the us↔YUL link's median SNR
|
||||
# Esc peels the selection back to the overview.
|
||||
screen.handle("escape")
|
||||
assert "rings = hops out" in _plain(screen.render_body(80))
|
||||
|
||||
|
||||
def test_atlas_marks_islands_in_the_panel() -> None:
|
||||
"""An island selection says so instead of quoting a bogus hop count."""
|
||||
screen = _screen(_topo(with_island=True))
|
||||
screen.render_body(80)
|
||||
for _ in range(4): # overview → us → YUL → Alice → first island node
|
||||
screen.handle("tab")
|
||||
body = _plain(screen.render_body(80))
|
||||
assert "island — no observed path to us" in body
|
||||
|
||||
|
||||
def test_atlas_find_filters_selects_and_peels() -> None:
|
||||
"""Typing narrows to matches, Enter adopts the first, Esc peels layer by layer."""
|
||||
import asyncio
|
||||
|
||||
topo = _topo()
|
||||
screen = _screen(topo)
|
||||
screen.render_body(80)
|
||||
|
||||
for ch in "ali":
|
||||
screen.handle("text", ch)
|
||||
assert screen._filter == "ali"
|
||||
screen.render_body(80)
|
||||
assert "1 match" in screen.title
|
||||
assert "find: ali" in screen.footer_hint
|
||||
body = _plain(screen.render_body(80))
|
||||
assert "1 of" in body and "Alice" in body # the find panel names the match
|
||||
# Non-matching labels drop to context; the match stays labelled on canvas.
|
||||
canvas_only = _plain(screen.render_body(80)[:-4])
|
||||
assert "Alice" in canvas_only and "YUL-Cartierville" not in canvas_only
|
||||
|
||||
screen.handle("enter") # adopt the first match
|
||||
assert screen._filter == ""
|
||||
assert screen._selected == topo.canonical(ALICE.public_key)
|
||||
|
||||
async def drive() -> object:
|
||||
screen.future = asyncio.get_running_loop().create_future()
|
||||
screen.handle("escape") # selection → overview
|
||||
assert screen._selected is None and not screen.future.done()
|
||||
screen.handle("escape") # overview → dismiss
|
||||
return await screen.future
|
||||
|
||||
assert asyncio.run(drive()) is None
|
||||
|
||||
|
||||
def test_atlas_rebuild_refreshes_the_evidence() -> None:
|
||||
"""Ctrl+R re-reads storage and the new link count shows on the next paint."""
|
||||
grown = _topo(with_island=True)
|
||||
screen = AtlasScreen(
|
||||
session=_FakeSession(),
|
||||
topo=_topo(),
|
||||
contacts={},
|
||||
self_label="Homestead",
|
||||
rebuild=lambda: grown,
|
||||
)
|
||||
screen.render_body(80)
|
||||
assert "2 links" in screen.title
|
||||
screen.handle("retry")
|
||||
screen.render_body(80)
|
||||
assert "3 links" in screen.title
|
||||
Reference in new issue
Block a user