pingerplot 1.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,409 @@
1
+ """Canvas drawing for the hop graph, the all-hops timeline and the map.
2
+
3
+ Pure drawing: each function takes a Canvas, the data to draw, and an ``Ink``
4
+ (the palette, fonts and pixel scale), and touches nothing else. The window
5
+ decides when to call them (only for the visible view, and only when the data
6
+ changed, see model.draw_version).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from dataclasses import dataclass
12
+ from typing import Callable, Dict, List, Optional
13
+
14
+ from . import geoip, locating, worldmap
15
+ from .model import HopView, Sample
16
+
17
+ WARN_MS = 120.0 # a hop goes amber at/above this average latency
18
+ BAD_MS = 250.0 # ...and red at/above this
19
+
20
+
21
+ def fmt_ms(v: Optional[float]) -> str:
22
+ if v is None:
23
+ return "—"
24
+ if v < 1:
25
+ return "<1"
26
+ if v < 10:
27
+ return f"{v:.1f}"
28
+ return f"{v:.0f}"
29
+
30
+
31
+ def row_tag(v: HopView, is_dest: bool) -> str:
32
+ """Row colour: red for a problem, amber for a warning.
33
+
34
+ BAD_MS used to be tested one branch too late -- `avg >= BAD_MS` returned
35
+ "warn", and any average clearing 250 ms also clears WARN_MS's 120 ms and
36
+ would have hit the next branch for the same answer. The condition could
37
+ never change the outcome, so latency alone never turned a row red no
38
+ matter how bad it got, contradicting BAD_MS's own comment.
39
+ """
40
+ if v.loss_pct > 25 or (v.avg is not None and v.avg >= BAD_MS):
41
+ return "bad"
42
+ if v.loss_pct > 0 or (v.avg is not None and v.avg >= WARN_MS):
43
+ return "warn"
44
+ return "dest" if is_dest else "ok"
45
+
46
+
47
+ @dataclass
48
+ class Ink:
49
+ """What drawing needs from the window: colours by role, fonts, scale."""
50
+ col: Dict[str, str]
51
+ font: Callable[..., tuple] # Theme.font(delta, weight)
52
+ s: Callable[[float], int] # logical pixels -> screen pixels
53
+
54
+ def hop_fg(self, v: HopView, is_dest: bool) -> str:
55
+ return {"bad": self.col["fg_bad"], "warn": self.col["fg_warn"],
56
+ "dest": self.col["fg_dest"], "ok": self.col["fg_ok"]}[row_tag(v, is_dest)]
57
+
58
+
59
+ def nice_max(v: float) -> float:
60
+ """The axis top: ``v`` rounded up to a round step (1, 1.5, 2, 3, 4, 5, 6
61
+ or 8 times a power of ten), so the gridlines read 0 / 40 / 80 rather
62
+ than 0 / 31 / 62."""
63
+ if v <= 0:
64
+ return 1.0
65
+ exp = 10 ** math.floor(math.log10(v))
66
+ for m in (1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10):
67
+ if m * exp >= v - 1e-9:
68
+ return m * exp
69
+ return 10 * exp
70
+
71
+
72
+ def _flush_segment(c, ink: Ink, segment: List[float], baseline: float) -> None:
73
+ if len(segment) >= 4: # at least two points
74
+ poly = [segment[0], baseline] + segment + [segment[-2], baseline]
75
+ c.create_polygon(poly, fill=ink.col["fill"], outline="")
76
+ c.create_line(segment, fill=ink.col["line"], width=max(1, ink.s(2)), joinstyle="round")
77
+ elif len(segment) == 2:
78
+ r = max(1, ink.s(2))
79
+ c.create_oval(segment[0] - r, segment[1] - r, segment[0] + r, segment[1] + r,
80
+ fill=ink.col["line"], outline="")
81
+
82
+
83
+ def plot_series(c, ink: Ink, samples, x0, x1, y_base, y_top, y_max, t_min, span, tick=8) -> None:
84
+ """One latency series (filled line + loss ticks) inside a rectangle.
85
+ ``y_base`` is the bottom (value 0), ``y_top`` the top (value y_max)."""
86
+ if not samples:
87
+ return
88
+
89
+ def X(t):
90
+ return x0 + (x1 - x0) * ((t - t_min) / span) if span else (x0 + x1) / 2
91
+
92
+ def Y(v):
93
+ return y_base + (y_top - y_base) * (min(v, y_max) / y_max)
94
+
95
+ segment: List[float] = []
96
+ loss_x: List[float] = []
97
+ for s in samples:
98
+ if s.rtt is None:
99
+ loss_x.append(X(s.t))
100
+ _flush_segment(c, ink, segment, y_base)
101
+ segment = []
102
+ else:
103
+ segment.extend((X(s.t), Y(s.rtt)))
104
+ _flush_segment(c, ink, segment, y_base)
105
+
106
+ tick_h = min(tick, max(2, y_base - y_top))
107
+ for x in loss_x:
108
+ c.create_line(x, y_base, x, y_base - tick_h, fill=ink.col["loss"], width=1)
109
+
110
+
111
+ def draw_graph(c, ink: Ink, ttl: Optional[int], samples: List[Sample]) -> None:
112
+ """The selected hop's latency over the samples kept."""
113
+ S = ink.s
114
+ c.delete("all")
115
+ w, h = c.winfo_width(), c.winfo_height()
116
+ if w < 40 or h < 40:
117
+ return
118
+ pad_l, pad_r, pad_t, pad_b = S(52), S(16), S(30), S(26)
119
+ x0, x1 = pad_l, w - pad_r
120
+ y_base, y_top = h - pad_b, pad_t
121
+ rtts = [s.rtt for s in samples if s.rtt is not None]
122
+ y_max = nice_max(max(10.0, (max(rtts) if rtts else 50.0) * 1.1))
123
+
124
+ for frac in (0.0, 0.25, 0.5, 0.75, 1.0):
125
+ y = y_base + (y_top - y_base) * frac
126
+ c.create_line(x0, y, x1, y, fill=ink.col["grid"])
127
+ c.create_text(x0 - S(8), y, text=f"{y_max * frac:g}", anchor="e",
128
+ fill=ink.col["axis_text"], font=ink.font(-2))
129
+
130
+ title = "Select a hop to graph" if ttl is None else f"Hop {ttl} · latency (ms)"
131
+ c.create_text(x0, y_top - S(16), text=title, anchor="w", fill=ink.col["title"],
132
+ font=ink.font(-1, "semibold"))
133
+ if not samples:
134
+ return
135
+
136
+ t0, t1 = samples[0].t, samples[-1].t
137
+ span = max(1e-6, t1 - t0)
138
+ plot_series(c, ink, samples, x0, x1, y_base, y_top, y_max, t0, span, tick=S(10))
139
+
140
+ last = samples[-1]
141
+ if last.rtt is not None:
142
+ lx = x0 + (x1 - x0) * ((last.t - t0) / span)
143
+ ly = y_base + (y_top - y_base) * (min(last.rtt, y_max) / y_max)
144
+ r = S(3)
145
+ c.create_oval(lx - r, ly - r, lx + r, ly + r, fill=ink.col["line"], outline="")
146
+ c.create_text(lx - S(6), ly - S(8), text=fmt_ms(last.rtt), anchor="se",
147
+ fill=ink.col["line"], font=ink.font(-2, "semibold"))
148
+ c.create_text(x1, y_base + S(13), text=f"← {span:.0f}s · now →",
149
+ anchor="e", fill=ink.col["axis_text"], font=ink.font(-2))
150
+
151
+
152
+ def fit_text(widget, text: str, font, width: int) -> str:
153
+ """``text``, shortened with "…" to fit ``width`` pixels in ``font``.
154
+ Measured, not counted: a long router name in a wide font (DejaVu Sans on
155
+ Linux) ran into the column beside it at the 30 characters that fitted
156
+ Segoe UI."""
157
+ from tkinter import font as tkfont
158
+ f = tkfont.Font(root=widget, font=font)
159
+ if width <= 0 or f.measure(text) <= width:
160
+ return text if width > 0 else ""
161
+ lo, hi = 0, len(text)
162
+ while lo < hi: # the longest prefix that fits with "…"
163
+ mid = (lo + hi + 1) // 2
164
+ if f.measure(text[:mid] + "…") <= width:
165
+ lo = mid
166
+ else:
167
+ hi = mid - 1
168
+ return text[:lo].rstrip() + "…" if lo else ""
169
+
170
+
171
+ def draw_timeline(c, ink: Ink, views: List[HopView], data: Dict[int, List[Sample]]) -> str:
172
+ """Every hop as a strip on one shared time and latency scale. Returns the
173
+ caption for the view's header."""
174
+ S = ink.s
175
+ c.delete("all")
176
+ w = c.winfo_width()
177
+ if w < 60:
178
+ return ""
179
+ if not views:
180
+ c.configure(scrollregion=(0, 0, w, 1))
181
+ return "No data yet."
182
+
183
+ all_s = [s for lst in data.values() for s in lst]
184
+ rtts = [s.rtt for s in all_s if s.rtt is not None]
185
+ g_max = max(10.0, (max(rtts) if rtts else 50.0) * 1.1)
186
+ times = [s.t for s in all_s]
187
+ t_min = min(times) if times else 0.0
188
+ span = max(1e-6, (max(times) if times else 1.0) - t_min)
189
+
190
+ n = len(views)
191
+ strip_h, gutter, pad = S(44), S(200), S(6)
192
+ c.configure(scrollregion=(0, 0, w, n * strip_h))
193
+ last_ttl = views[-1].ttl
194
+
195
+ for i, v in enumerate(views):
196
+ y0 = i * strip_h
197
+ y_top, y_base = y0 + pad, y0 + strip_h - pad
198
+ gx0, gx1 = gutter, w - S(12)
199
+ if i:
200
+ c.create_line(0, y0, w, y0, fill=ink.col["strip_sep"])
201
+ c.create_rectangle(gx0, y_top, gx1, y_base, fill=ink.col["graph_bg"],
202
+ outline=ink.col["strip_border"])
203
+ loss = c.create_text(gutter - S(8), (y_top + y_base) / 2, anchor="e",
204
+ text=f"{v.loss_pct:.0f}% loss", fill=ink.col["axis_text"],
205
+ font=ink.font(-3))
206
+ room = (c.bbox(loss) or (gutter - S(8),))[0] - S(8) - S(8)
207
+ label = fit_text(c, f"{v.ttl}. {v.hostname or v.address or '*'}", ink.font(-2), room)
208
+ c.create_text(S(8), (y_top + y_base) / 2, anchor="w", text=label,
209
+ fill=ink.hop_fg(v, v.ttl == last_ttl), font=ink.font(-2))
210
+ plot_series(c, ink, data.get(v.ttl, []), gx0, gx1, y_base, y_top, g_max, t_min, span,
211
+ tick=S(6))
212
+ c.create_text(gx1 - S(4), y_top + S(2), anchor="ne", text=fmt_ms(v.current),
213
+ fill=ink.col["line"], font=ink.font(-3, "semibold"))
214
+ return f"All hops on one scale, 0 to {g_max:.0f} ms · last {span:.0f} s · {n} hops"
215
+
216
+
217
+ def _ttl_list(ttls: List[int]) -> str:
218
+ """[5] -> "5"; [5, 6] -> "5–6"; [2, 5] -> "2, 5"."""
219
+ if len(ttls) > 1 and ttls == list(range(ttls[0], ttls[-1] + 1)):
220
+ return f"{ttls[0]}–{ttls[-1]}"
221
+ return ", ".join(str(t) for t in ttls)
222
+
223
+
224
+ def _overlaps(a, b) -> bool:
225
+ return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3]
226
+
227
+
228
+ def _crosses(seg, box) -> bool:
229
+ """Whether the line segment ((x0, y0), (x1, y1)) passes through ``box``
230
+ (Liang–Barsky clipping)."""
231
+ (x0, y0), (x1, y1) = seg
232
+ t0, t1 = 0.0, 1.0
233
+ dx, dy = x1 - x0, y1 - y0
234
+ for p, q in ((-dx, x0 - box[0]), (dx, box[2] - x0), (-dy, y0 - box[1]), (dy, box[3] - y0)):
235
+ if p == 0:
236
+ if q < 0:
237
+ return False
238
+ continue
239
+ r = q / p
240
+ if p < 0:
241
+ t0 = max(t0, r)
242
+ else:
243
+ t1 = min(t1, r)
244
+ if t0 > t1:
245
+ return False
246
+ return True
247
+
248
+
249
+ def _label_places(c, ink: Ink, located, gap: int, rad: int = 0, bounds=None) -> None:
250
+ """One label per place, in path order. Hops at the same spot share one
251
+ ("5–6. Denver"). Each label goes right of its dot, left, above or below:
252
+ the first of those that covers no other label or dot, stays inside
253
+ ``bounds`` (x0, y0, x1, y1) and doesn't cross the path's line; failing
254
+ that, the first that only crosses the line, on a plate in the map's
255
+ colour so it stays readable; failing that, it's left off. At world scale
256
+ a path within one region is a few pixels across, and one label per hop
257
+ piled up into an unreadable smear."""
258
+ places: List[list] = [] # [x, y, ttls, name]
259
+ for v, g, x, y in located:
260
+ name = g.city or g.country or ""
261
+ for p in places:
262
+ if abs(p[0] - x) < 1 and abs(p[1] - y) < 1 and p[3] == name:
263
+ p[2].append(v.ttl)
264
+ break
265
+ else:
266
+ places.append([x, y, [v.ttl], name])
267
+ path = [(located[i - 1][2:4], located[i][2:4]) for i in range(1, len(located))]
268
+ taken: List[tuple] = [(x - rad, y - rad, x + rad, y + rad) for x, y, _t, _n in places]
269
+ font = ink.font(-2)
270
+ for x, y, ttls, name in places:
271
+ text = f"{_ttl_list(ttls)}. {name}".strip()
272
+ clear, on_line = None, None
273
+ for anchor, dx, dy in (("w", gap, 0), ("e", -gap, 0), ("s", 0, -gap), ("n", 0, gap)):
274
+ item = c.create_text(x + dx, y + dy, anchor=anchor, text=text, font=font)
275
+ box = c.bbox(item)
276
+ c.delete(item)
277
+ if not box or any(_overlaps(box, b) for b in taken):
278
+ continue
279
+ if bounds and (box[0] < bounds[0] or box[1] < bounds[1]
280
+ or box[2] > bounds[2] or box[3] > bounds[3]):
281
+ continue
282
+ if any(_crosses(s, box) for s in path):
283
+ on_line = on_line or (anchor, dx, dy, box)
284
+ continue
285
+ clear = (anchor, dx, dy, box)
286
+ break
287
+ chosen = clear or on_line
288
+ if chosen is None:
289
+ continue
290
+ anchor, dx, dy, box = chosen
291
+ taken.append(box)
292
+ if chosen is on_line and ink.col.get("graph_bg"):
293
+ c.create_rectangle(box[0] - 2, box[1], box[2] + 2, box[3],
294
+ fill=ink.col["graph_bg"], outline="")
295
+ c.create_text(x + dx, y + dy, anchor=anchor, text=text, fill=ink.col["title"], font=font)
296
+
297
+
298
+ MAP_MIN_SPAN = 16.0 # degrees: the coastlines are Natural Earth 110m, about 0.8 deg a step
299
+ MAP_PAD = 0.25 # of the hops' extent, on each side
300
+
301
+
302
+ def map_view(points, w: float, h: float, margin: float = 0.0):
303
+ """The Map's projection, ``(lon, lat) -> (x, y)``, for a ``w`` x ``h``
304
+ canvas: zoomed to ``points`` (the located hops, as (lon, lat)) with some
305
+ room around them, but never narrower than MAP_MIN_SPAN degrees, where the
306
+ coarse coastlines would turn to zigzags. A degree of longitude is drawn
307
+ cos(latitude) as wide as one of latitude, at the middle of the view, so
308
+ nothing is stretched. With no points it's the whole world, as before.
309
+
310
+ A path across the Pacific (lon jumping from about -120 to +140) gets a
311
+ view nearly the world's width, as it did before; it isn't wrapped round
312
+ the date line."""
313
+ if not points:
314
+ return lambda lon, lat: ((lon + 180.0) / 360.0 * w, (90.0 - lat) / 180.0 * h)
315
+ lons = [p[0] for p in points]
316
+ lats = [p[1] for p in points]
317
+ lat_mid = (min(lats) + max(lats)) / 2.0
318
+ k = max(0.2, math.cos(math.radians(lat_mid)))
319
+ x0, x1 = min(lons) * k, max(lons) * k
320
+ y0, y1 = min(lats), max(lats)
321
+ span_x = max((x1 - x0) * (1 + 2 * MAP_PAD), MAP_MIN_SPAN)
322
+ span_y = max((y1 - y0) * (1 + 2 * MAP_PAD), MAP_MIN_SPAN / 2)
323
+ scale = min(max(w - 2 * margin, 1) / span_x, max(h - 2 * margin, 1) / span_y)
324
+ cx, cy = (x0 + x1) / 2.0, (y0 + y1) / 2.0
325
+ return lambda lon, lat: (w / 2.0 + (lon * k - cx) * scale, h / 2.0 - (lat - cy) * scale)
326
+
327
+
328
+ def draw_map(c, ink: Ink, views: List[HopView], geo, locator=None, past=None) -> str:
329
+ """Located public hops on the coastline backdrop, joined in path order,
330
+ zoomed to the path (map_view). Asks ``geo`` for any it hasn't looked up.
331
+ ``locator`` (locating.Locator) places each router: its name first, then
332
+ the IP database unless the round trips rule that out. ``past`` is
333
+ earlier routes, each a list of ``(lat, lon)``, drawn faded underneath.
334
+ Returns the header caption."""
335
+ S = ink.s
336
+ c.delete("all")
337
+ w, h = c.winfo_width(), c.winfo_height()
338
+ if w < 80 or h < 80:
339
+ return ""
340
+
341
+ if locator is None:
342
+ locator = locating.Locator(geo)
343
+ public = 0
344
+ found = []
345
+ by_name = left_out = 0
346
+ for v in views:
347
+ if v.address and geoip._is_public(v.address):
348
+ public += 1
349
+ geo.request(v.address)
350
+ where = locator.view(v)
351
+ if where.point is not None:
352
+ found.append((v, _Spot(where.point[0], where.point[1], where.label)))
353
+ by_name += where.source == "name"
354
+ left_out += bool(where.why)
355
+ past = [r for r in (past or []) if len(r) >= 2]
356
+ proj = map_view([(g.lon, g.lat) for _v, g in found] +
357
+ [(lon, lat) for route in past for lat, lon in route], w, h, margin=S(24))
358
+
359
+ for poly in worldmap.COASTLINES:
360
+ pts = []
361
+ for lon, lat in poly:
362
+ pts.extend(proj(lon, lat))
363
+ if len(pts) >= 4:
364
+ c.create_line(pts, fill=ink.col["grid"], width=1)
365
+
366
+ # Earlier routes first, faded and dashed, so the current one reads on top.
367
+ for route in past:
368
+ pts = []
369
+ for lat, lon in route:
370
+ pts.extend(proj(lon, lat))
371
+ c.create_line(pts, fill=ink.col["axis_text"], width=1, dash=(3, 4))
372
+ for i in range(0, len(pts), 2):
373
+ r = max(2, S(3))
374
+ c.create_oval(pts[i] - r, pts[i + 1] - r, pts[i] + r, pts[i + 1] + r,
375
+ outline=ink.col["axis_text"], fill="")
376
+
377
+ located = [(v, g) + proj(g.lon, g.lat) for v, g in found]
378
+
379
+ for i in range(1, len(located)):
380
+ c.create_line(located[i - 1][2], located[i - 1][3], located[i][2], located[i][3],
381
+ fill=ink.col["line"], width=max(1, S(2)))
382
+ last_ttl = views[-1].ttl if views else None
383
+ rad = max(2, S(4))
384
+ for v, g, x, y in located:
385
+ c.create_oval(x - rad, y - rad, x + rad, y + rad,
386
+ fill=ink.hop_fg(v, v.ttl == last_ttl), outline=ink.col["graph_bg"])
387
+ _label_places(c, ink, located, rad + S(3), rad, bounds=(0, 0, w, h))
388
+
389
+ if not views:
390
+ return "No data yet: start a target to map its hops."
391
+ # The failure count only appears when the lookup service is actually
392
+ # misbehaving. Without it, a map that has quietly stopped resolving looks
393
+ # identical to one whose hops simply have no location.
394
+ note = f" · {geo.failures} lookup error(s), retrying" if geo.failures else ""
395
+ paused = f" · lookups paused: {geo.paused}" if getattr(geo, "paused", "") else ""
396
+ earlier = f" · {len(past)} earlier route(s) dashed" if past else ""
397
+ doubted = (f" · {left_out} left off: ipwho.is's answer doesn't fit the round trip (see Details)"
398
+ if left_out else "")
399
+ return (f"{len(located)} of {public} public hops located: {by_name} by the router's name, "
400
+ f"{len(located) - by_name} by ipwho.is (private and LAN hops have no location)"
401
+ f"{doubted}{earlier}{note}{paused}")
402
+
403
+
404
+ class _Spot:
405
+ """Where a hop is drawn: what the label code reads from a GeoInfo."""
406
+ __slots__ = ("lat", "lon", "city", "country")
407
+
408
+ def __init__(self, lat, lon, city) -> None:
409
+ self.lat, self.lon, self.city, self.country = lat, lon, city, ""