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.
pingerplot/gui.py ADDED
@@ -0,0 +1,1792 @@
1
+ """The PingerPlot window: a header with the overall state, the targets on the
2
+ left as cards, the selected target on the right (its hops and their graph, a
3
+ timeline of every hop, a map, its events), and a Settings page.
4
+
5
+ Pure standard library. The window never touches monitor internals: it polls
6
+ the snapshot accessors on a timer and renders immutable copies, so there are no
7
+ cross-thread Tk calls. Canvases are redrawn only while visible and only when
8
+ their data changed. Drawing lives in gui_charts, small widgets in gui_widgets,
9
+ the option forms in gui_settings.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import csv
14
+ import json
15
+ import os
16
+ import queue
17
+ import sys
18
+ import threading
19
+ import time
20
+ import tkinter as tk
21
+ import urllib.parse
22
+ import webbrowser
23
+ from tkinter import filedialog, messagebox, ttk
24
+ from typing import Dict, List, Optional
25
+
26
+ from . import __version__, appicon, compare as cmpmod, geoip, history, icmp, settings
27
+ from . import theme as themes, tkthreads, tray as traymod, updater, winplatform, xdg
28
+ from . import gui_hopinfo, gui_recording, investigate, locating, trouble
29
+ from .gui_charts import BAD_MS, WARN_MS, Ink, draw_graph, draw_map, draw_timeline, fmt_ms, row_tag
30
+ from .gui_history import HistoryPage
31
+ from .gui_settings import REPO_URL, EditTargetDialog, OptionVars, SettingsPage
32
+ from .gui_updates import Updates
33
+ from .gui_widgets import Nav, ScrollFrame, TargetCard, WheelScroll, fit_columns, side_scroll
34
+ from .model import HopView, csv_safe, draw_version, mos, mos_label
35
+ from . import monitor
36
+ from .monitor import Monitor
37
+
38
+ __all__ = ["App", "main", "BAD_MS", "WARN_MS", "COLORS"]
39
+
40
+ REFRESH_MS = 700
41
+ MAX_EVENT_ROWS = 1000 # the Events view keeps what the monitor keeps
42
+
43
+ # The drawing code's colours, under the keys it has always read. They come
44
+ # from the theme engine (theme.legacy_colours) and are replaced in place on
45
+ # every theme change, so draw code that reads COLORS at call time follows.
46
+ COLORS: Dict[str, str] = {}
47
+
48
+ # Only Hostname stretches (and shrinks): the numbers keep their width, so all
49
+ # ten columns fit the detail pane at the window's minimum size.
50
+ COLUMNS = [
51
+ ("ttl", "Hop", 44, "center"),
52
+ ("address", "Address", 118, "w"),
53
+ ("hostname", "Hostname", 170, "w"),
54
+ ("place", "Location", 120, "w"),
55
+ ("network", "Network", 175, "w"),
56
+ ("loss", "Loss", 52, "e"),
57
+ ("sent", "Sent", 50, "e"),
58
+ ("cur", "Last", 50, "e"),
59
+ ("avg", "Avg", 50, "e"),
60
+ ("best", "Best", 50, "e"),
61
+ ("worst", "Worst", 56, "e"),
62
+ ("jitter", "Jitter", 56, "e"),
63
+ ]
64
+
65
+ # The text columns share whatever width the table has, down to these
66
+ # minimums, and shorten their text first: the numbers to their right must
67
+ # never be pushed out of sight (Location and Network made the table wider
68
+ # than the pane at the default window size, and Best to Jitter vanished).
69
+ TEXT_MIN = {"hostname": 80, "place": 70, "network": 70}
70
+
71
+ _ms = fmt_ms
72
+
73
+
74
+ def _csv_num(v: Optional[float]) -> str:
75
+ return "" if v is None else f"{v:.1f}"
76
+
77
+
78
+ class App:
79
+ def __init__(self, root: tk.Tk, use_tray: bool = False, start_minimized: bool = False,
80
+ resume: bool = False) -> None:
81
+ tkthreads.install() # before the first Variable or image: see tkthreads
82
+ self.root = root
83
+ self.tray: Optional[traymod.TrayIcon] = None
84
+ self._desktop_notifier = None # notify-send, where there's no tray (Linux)
85
+ self._tray_state = None
86
+ self._ui_jobs: "queue.SimpleQueue" = queue.SimpleQueue()
87
+ self._notify_seq: Dict[str, int] = {} # per target: newest event already notified
88
+ self._monitors: "dict[str, Monitor]" = {} # target name -> its Monitor
89
+ self._active: Optional[str] = None # which one the detail shows
90
+ self._empty = Monitor() # placeholder when nothing selected
91
+ self._loaded: "set[str]" = set() # offline sessions, not live targets
92
+ # Where routers are and whose network: looked up while monitoring
93
+ # (Settings -> Look up where routers are), answers kept a month.
94
+ self.geo = geoip.GeoResolver(settings.config_dir() / geoip.CACHE_NAME)
95
+ self._geo_started = False
96
+ self._geo_fed = 0.0
97
+ self._anchors_at, self._anchors = -1e9, [] # see _locator
98
+ # Earlier routes for the map, per target: (loaded at, [[(addr, name), ...], ...]).
99
+ self._past_routes: Dict[str, tuple] = {}
100
+ self._past_loading: set = set()
101
+ self._selected_ttl: Optional[int] = None # hop currently graphed
102
+ self._last_ttl: Optional[int] = None # destination hop, per refresh
103
+ self._pinned = False # True once the user picks a row
104
+ self._last_event_seq = -1
105
+ self._draw_ver = None # what the visible canvas last showed
106
+ self._note_until = 0.0
107
+ self._cards: Dict[str, TargetCard] = {}
108
+ self._settings = settings.load() # persisted UI/engine/alert state
109
+ # Everything every target measures goes to one history database.
110
+ self.recorder = history.open_recorder(self._settings, "gui")
111
+
112
+ self.scale = self._init_scaling()
113
+ root.title("PingerPlot")
114
+ self._set_window_icon()
115
+ # Wide enough for the hop table's columns, but never wider than the screen.
116
+ width = min(self.s(1280), root.winfo_screenwidth() - self.s(40))
117
+ root.geometry(f"{width}x{self.s(780)}")
118
+ root.minsize(self.s(900), self.s(560))
119
+ root.protocol("WM_DELETE_WINDOW", self._on_close)
120
+
121
+ # "system" (follow Windows), "dark" or "light". Before 1.4 the choice
122
+ # was dark or light and dark was saved by default, so existing users
123
+ # keep the look they had.
124
+ pref = self._settings.get("theme", "system")
125
+ if pref not in themes.THEMES:
126
+ pref = "system"
127
+ self.theme_var = tk.StringVar(value=pref)
128
+ self.resume_var = tk.BooleanVar(value=True) # resume last targets on launch
129
+ self.keep_tray_var = tk.BooleanVar(value=True) # closing hides to the tray
130
+ self.notify_var = tk.BooleanVar(value=True) # a notification per alert
131
+ self.lookup_var = tk.BooleanVar(value=True) # look up where routers are
132
+ # Start at sign-in: the Run key on Windows, an XDG autostart entry on
133
+ # Linux (same set_autostart/autostart_enabled names in both modules).
134
+ self._autostart = winplatform if winplatform.IS_WINDOWS else (xdg if xdg.IS_LINUX else None)
135
+ self.autostart_var = tk.BooleanVar(
136
+ value=self._autostart.autostart_enabled() if self._autostart else False)
137
+ self.menu_entry_var = tk.BooleanVar(value=xdg.menu_entry_enabled())
138
+ self.target_var = tk.StringVar(value="")
139
+ self._theme_checked = time.monotonic()
140
+ # Before any widget is built: every ttk style comes from here.
141
+ self.look = themes.Theme(root, {"theme": pref})
142
+ self.style = self.look.style
143
+ self._sync_colours()
144
+
145
+ # Defaults for new targets (the Settings page edits them).
146
+ self.defaults = OptionVars(root)
147
+ self.interval_var = self.defaults["interval"]
148
+ self.logpath_var = self.defaults["log_path"]
149
+ self.alert_loss_var = self.defaults["alert_loss_pct"]
150
+ self.updates = Updates(self)
151
+ # What the history keeps (the Settings page's Recording section).
152
+ self.recording = gui_recording.RecordingVars(root, self._settings.get("recording"))
153
+ self._recording_job = None
154
+
155
+ self._build_header()
156
+ self._build_pages()
157
+ self._recolor_widgets()
158
+ self._apply_saved_settings() # restore last defaults and app options
159
+ # Elevated, a log path is only one you choose in this session. The
160
+ # settings file is writable by anything running as you unelevated, and
161
+ # a path in it made the elevated app create, append to and (at 25 MB)
162
+ # rename a file wherever that program chose (the 2026-11-05 review, M1).
163
+ self._elevated = winplatform.is_elevated()
164
+ if self._elevated:
165
+ self.defaults["log_path"].set("")
166
+ # Saved a second after any change, not only on hide or quit: a Windows
167
+ # Update restart overnight, or a crash, lost every target added or
168
+ # edited since. And when Windows ends the session (Tk's
169
+ # WM_SAVE_YOURSELF), straight away.
170
+ self._save_job = None
171
+ for var in [*self.defaults.vars.values(), self.theme_var, self.resume_var,
172
+ self.keep_tray_var, self.notify_var, self.updates.auto_var]:
173
+ var.trace_add("write", lambda *_a: self._save_soon())
174
+ for var in self.recording.vars.values():
175
+ var.trace_add("write", lambda *_a: (self._save_soon(), self._apply_recording_soon()))
176
+ self.lookup_var.trace_add("write", lambda *_a: (self._save_soon(), self._apply_lookups()))
177
+ self._apply_lookups()
178
+ root.protocol("WM_SAVE_YOURSELF", self._save_settings)
179
+
180
+ if not icmp.is_available():
181
+ # Say what to do about it. On Linux this is one sysctl away, and
182
+ # "unsupported platform" would send the user looking for a port
183
+ # that already exists.
184
+ messagebox.showerror(
185
+ "ICMP backend unavailable",
186
+ icmp.unavailable_reason() + "\n\n"
187
+ "TCP and UDP probe modes do not use this backend and may still work.",
188
+ )
189
+
190
+ if use_tray:
191
+ self._start_tray()
192
+ if self.tray is None:
193
+ self._desktop_notifier = xdg.notifier()
194
+ winplatform.refresh_autostart() # the folder moved: point the Run key here
195
+ xdg.refresh_entries() # likewise Linux's menu and autostart entries
196
+ if start_minimized and self.tray is not None:
197
+ self.root.withdraw() # Start with Windows: straight to the tray
198
+ elif start_minimized:
199
+ self.root.iconify() # Linux sign-in: no tray to hide in
200
+ # The last session's targets: when the setting says so, and always
201
+ # after an update, which shouldn't stop anything being monitored.
202
+ self._restore_targets(force=resume)
203
+ self._refresh_once()
204
+ self.root.after(REFRESH_MS, self._refresh)
205
+ self.root.after(50, self._drain_ui) # work posted from other threads
206
+ self.updates.start()
207
+
208
+ @property
209
+ def monitor(self) -> Monitor:
210
+ """The monitor the detail views render: the selected target, or an
211
+ empty one when nothing is selected, so the rendering code needs no
212
+ special case."""
213
+ m = self._monitors.get(self._active) if self._active else None
214
+ return m if m is not None else self._empty
215
+
216
+ # --- DPI / HiDPI scaling ----------------------------------------------------
217
+ def _init_scaling(self) -> float:
218
+ """Size Tk's fonts to the real display DPI and return the pixel scale
219
+ (1.0 at 96 dpi). Needs the process to be DPI aware already (see
220
+ winplatform.enable_dpi_awareness), or Windows reports a flat 96 dpi and
221
+ bitmap-stretches the window."""
222
+ try:
223
+ dpi = float(self.root.winfo_fpixels("1i"))
224
+ except tk.TclError:
225
+ dpi = 96.0
226
+ if dpi <= 0:
227
+ dpi = 96.0
228
+ try:
229
+ # Tk 'scaling' is points->pixels; 1 pt is 1/72 in.
230
+ self.root.tk.call("tk", "scaling", dpi / 72.0)
231
+ except tk.TclError:
232
+ pass
233
+ return dpi / 96.0
234
+
235
+ def s(self, px: float) -> int:
236
+ """Scale a base-96-dpi pixel measurement to the current display."""
237
+ return int(round(px * self.scale))
238
+
239
+ def _set_window_icon(self) -> None:
240
+ """The 'signal ripples' mark in the title bar, taskbar and Alt-Tab, kept
241
+ on self so Tk doesn't garbage-collect it."""
242
+ try:
243
+ self._app_icon = tk.PhotoImage(data=appicon.png_base64(64))
244
+ self.root.iconphoto(True, self._app_icon)
245
+ except tk.TclError:
246
+ pass
247
+
248
+ # --- theming ----------------------------------------------------------------
249
+ def _apply_theme(self, name: str) -> None:
250
+ """``name`` is the setting (system, dark or light): redraw every
251
+ element in the palette it resolves to, then the canvases."""
252
+ self.theme_var.set(name)
253
+ self.look.apply({"theme": name})
254
+ self._sync_colours()
255
+ self._recolor_widgets()
256
+ self._draw_ver = None
257
+ self._refresh_once()
258
+
259
+ def _sync_colours(self) -> None:
260
+ """Point the drawing code's COLORS at the current palette, and give
261
+ every open window a title bar to match."""
262
+ COLORS.clear()
263
+ COLORS.update(themes.legacy_colours(self.look.c))
264
+ self.theme = "dark" if self.look.dark else "light"
265
+ wins = [self.root] + [w for w in self.root.winfo_children() if isinstance(w, tk.Toplevel)]
266
+ for win in wins:
267
+ if win.winfo_exists():
268
+ self.look.style_window(win)
269
+
270
+ def _follow_system_theme(self) -> None:
271
+ """With "Match Windows" ("Match the system" on Linux), notice the
272
+ system switching light/dark. A registry read every few seconds is
273
+ cheaper than it sounds and needs no hidden window to receive the
274
+ broadcast; Linux's portal read is a process, so it's less often."""
275
+ if self.theme_var.get() != "system":
276
+ return
277
+ now = time.monotonic()
278
+ if now - self._theme_checked < winplatform.THEME_POLL_S:
279
+ return
280
+ self._theme_checked = now
281
+ if themes.resolve_dark("system") != self.look.dark:
282
+ self._apply_theme("system")
283
+
284
+ def _recolor_widgets(self) -> None:
285
+ """What doesn't follow ttk styles: canvases, row tags, scroll areas."""
286
+ p = COLORS
287
+ self.root.configure(bg=self.look.c["bg"])
288
+ for c in (self.canvas, self.timeline_canvas, self.map_canvas):
289
+ c.configure(bg=p["graph_bg"])
290
+ for t in ("ok", "warn", "bad", "dest"):
291
+ self.tree.tag_configure(t, background=p[t], foreground=p["fg"])
292
+ for kind in ("alert", "clear", "route", "warn"):
293
+ self.events_tree.tag_configure(kind, background=p[f"ev_{kind}"], foreground=p["fg"])
294
+ for sf in (self.cards_scroll, getattr(self, "settings_page", None),
295
+ getattr(self, "history_page", None)):
296
+ if sf is not None:
297
+ sf.recolor()
298
+ self.header_icon.configure(image=self._header_icon_image())
299
+
300
+ def _ink(self) -> Ink:
301
+ return Ink(COLORS, self.look.font, self.s)
302
+
303
+ # --- layout -----------------------------------------------------------------
304
+ def _header_icon_image(self) -> tk.PhotoImage:
305
+ self._hdr_img = tk.PhotoImage(data=appicon.png_base64(self.s(30)))
306
+ return self._hdr_img
307
+
308
+ def _build_header(self) -> None:
309
+ S = self.s
310
+ head = ttk.Frame(self.root, padding=(S(24), S(16), S(20), S(6)))
311
+ head.pack(side="top", fill="x")
312
+ self.header_icon = ttk.Label(head, image=self._header_icon_image())
313
+ self.header_icon.pack(side="left")
314
+ ttk.Label(head, text="PingerPlot", style="Title.TLabel").pack(side="left", padx=(S(12), 0))
315
+ more = ttk.Button(head, text=self.look.icon("more"), style="Icon.Subtle.TButton",
316
+ command=lambda: self._header_menu(more))
317
+ more.pack(side="right")
318
+ self.note_label = ttk.Label(head, text="", style="Faint.TLabel")
319
+ self.note_label.pack(side="right", padx=(0, S(14)))
320
+ self.status_text = ttk.Label(head, text="", style="TLabel")
321
+ self.status_text.pack(side="right", padx=(0, S(10)))
322
+ self.status_dot = ttk.Label(head, text="●", style="Dot.TLabel")
323
+ self.status_dot.pack(side="right", padx=(0, S(6)))
324
+
325
+ nav_row = ttk.Frame(self.root, padding=(S(24), 0, S(24), 0))
326
+ nav_row.pack(side="top", fill="x")
327
+ self.nav = Nav(nav_row, self.look, [("targets", "Targets"), ("history", "History"),
328
+ ("settings", "Settings")], self._show_page)
329
+ self.nav.pack(side="left")
330
+ self.nav.select("targets")
331
+ ttk.Frame(self.root, style="Divider.TFrame", height=1).pack(side="top", fill="x")
332
+ self.updates.build_bar_holder(self.root)
333
+
334
+ def _build_pages(self) -> None:
335
+ self.pages = ttk.Frame(self.root)
336
+ self.pages.pack(side="top", fill="both", expand=True)
337
+ self.targets_page = ttk.Frame(self.pages)
338
+ self.targets_page.pack(fill="both", expand=True)
339
+ self.settings_page: Optional[SettingsPage] = None
340
+ self.history_page: Optional[HistoryPage] = None
341
+ S = self.s
342
+ split = ttk.Panedwindow(self.targets_page, orient="horizontal")
343
+ split.pack(fill="both", expand=True)
344
+ left = ttk.Frame(split, padding=(S(20), S(14), S(8), S(14)))
345
+ right = ttk.Frame(split, padding=(S(8), S(10), S(20), S(14)))
346
+ split.add(left, weight=1)
347
+ split.add(right, weight=4)
348
+ self._build_target_list(left)
349
+ self._build_detail(right)
350
+ self.root.bind_all("<Control-n>", lambda _e: self._focus_add())
351
+
352
+ def _show_page(self, key: str, target: Optional[str] = None) -> None:
353
+ # The Settings and History pages are built on first use: both are long.
354
+ if key == "settings" and self.settings_page is None:
355
+ self.settings_page = SettingsPage(self.pages, self)
356
+ if key == "history" and self.history_page is None:
357
+ self.history_page = HistoryPage(self.pages, self)
358
+ pages = {"targets": self.targets_page, "settings": self.settings_page,
359
+ "history": self.history_page}
360
+ for name, page in pages.items():
361
+ if page is not None and name != key:
362
+ page.pack_forget()
363
+ if self.history_page is not None and key != "history":
364
+ self.history_page.hide()
365
+ pages[key].pack(fill="both", expand=True)
366
+ if key == "history":
367
+ self.history_page.show(target or self._active)
368
+ elif key == "targets":
369
+ self._draw_ver = None
370
+
371
+ def _show_history(self, name: str) -> None:
372
+ self.nav.select("history")
373
+ self._show_page("history", name)
374
+
375
+ def _build_target_list(self, parent: ttk.Frame) -> None:
376
+ S = self.s
377
+ add = ttk.Frame(parent)
378
+ add.pack(side="top", fill="x")
379
+ self.add_entry = ttk.Entry(add, textvariable=self.target_var)
380
+ self.add_entry.pack(side="left", fill="x", expand=True)
381
+ self.add_entry.bind("<Return>", lambda _e: self._start())
382
+ ttk.Button(add, text="Add", style="Accent.TButton", command=self._start).pack(
383
+ side="left", padx=(S(8), 0))
384
+ ttk.Label(parent, text="A host name or IP address. Ctrl+N comes back here.",
385
+ style="Faint.TLabel").pack(side="top", anchor="w", pady=(S(4), 0))
386
+
387
+ caption = ttk.Frame(parent)
388
+ caption.pack(side="top", fill="x", pady=(S(16), S(6)))
389
+ self.targets_caption = ttk.Label(caption, text="TARGETS", style="Caps.TLabel")
390
+ self.targets_caption.pack(side="left")
391
+ ttk.Button(caption, text="Stop all", style="Subtle.TButton", command=self._stop_all).pack(
392
+ side="right")
393
+
394
+ self.cards_scroll = ScrollFrame(parent, self.look)
395
+ self.cards_scroll.pack(side="top", fill="both", expand=True)
396
+ self.cards_empty = ttk.Label(
397
+ self.cards_scroll.inner, style="Muted.TLabel", wraplength=S(230), justify="left",
398
+ text="Nothing monitored yet. Type a host name or IP address above and press Add: "
399
+ "8.8.8.8, your gateway, a server you care about.")
400
+ self.cards_empty.pack(side="top", anchor="w", pady=(S(4), 0))
401
+
402
+ def _build_detail(self, parent: ttk.Frame) -> None:
403
+ S = self.s
404
+ top = ttk.Frame(parent)
405
+ top.pack(side="top", fill="x")
406
+ top.columnconfigure(0, weight=1)
407
+ self.detail_title = ttk.Label(top, text="", style="Heading.TLabel")
408
+ self.detail_title.grid(row=0, column=0, sticky="w")
409
+ self.detail_status = ttk.Label(top, text="", style="Muted.TLabel")
410
+ self.detail_status.grid(row=1, column=0, sticky="w")
411
+ buttons = ttk.Frame(top)
412
+ buttons.grid(row=0, column=1, rowspan=2, sticky="e")
413
+ self.pause_btn = ttk.Button(buttons, text="Pause", command=self._toggle_pause)
414
+ self.pause_btn.pack(side="left")
415
+ self.stop_btn = ttk.Button(buttons, text="Stop", command=self._toggle_run)
416
+ self.stop_btn.pack(side="left", padx=(S(6), 0))
417
+ self.edit_btn = ttk.Button(buttons, text="Edit settings", command=self._edit_active)
418
+ self.edit_btn.pack(side="left", padx=(S(6), 0))
419
+ # Shown only for a target stopped because it needs Administrator.
420
+ self.elevate_btn = ttk.Button(buttons, text="Restart as administrator",
421
+ style="Accent.TButton", command=self._restart_elevated)
422
+ self._elevate_shown = False
423
+
424
+ stats = ttk.Frame(parent)
425
+ stats.pack(side="top", fill="x", pady=(S(6), 0))
426
+ self.mos_label_w = ttk.Label(stats, text="", style="Strong.TLabel")
427
+ self.mos_label_w.pack(side="left")
428
+ self.detail_stats = ttk.Label(stats, text="", style="Muted.TLabel")
429
+ self.detail_stats.pack(side="left", padx=(S(10), 0))
430
+
431
+ self.banner = ttk.Frame(parent, style="Banner.TFrame", padding=(S(14), S(8)))
432
+ self.banner_label = ttk.Label(self.banner, text="", style="Banner.TLabel",
433
+ wraplength=S(760), justify="left")
434
+ self.banner_label.pack(side="left", fill="x", expand=True)
435
+ self._banner_shown = False
436
+
437
+ nav_row = ttk.Frame(parent)
438
+ nav_row.pack(side="top", fill="x", pady=(S(8), 0))
439
+ self._banner_anchor = nav_row
440
+ self.views: Dict[str, ttk.Frame] = {}
441
+ self.detail_nav = Nav(nav_row, self.look, [("hops", "Hops"), ("timeline", "Timeline"),
442
+ ("map", "Map"), ("events", "Events")],
443
+ self._show_view)
444
+ self.detail_nav.pack(side="left")
445
+ self.view_host = ttk.Frame(parent)
446
+ self.view_host.pack(side="top", fill="both", expand=True, pady=(S(8), 0))
447
+
448
+ self.views["hops"] = self._build_hops_view(self.view_host)
449
+ self.views["timeline"] = self._build_timeline_view(self.view_host)
450
+ self.views["map"] = self._build_map_view(self.view_host)
451
+ self.views["events"] = self._build_events_view(self.view_host)
452
+ self.detail_nav.select("hops")
453
+ self._show_view("hops")
454
+
455
+ def _card(self, parent) -> ttk.Frame:
456
+ """A rounded surface for a table or a canvas to sit on."""
457
+ S = self.s
458
+ card = ttk.Frame(parent, style="Tile.TFrame", padding=(S(6), S(6)))
459
+ return card
460
+
461
+ def _build_hops_view(self, host) -> ttk.Frame:
462
+ S = self.s
463
+ view = ttk.Frame(host)
464
+ split = ttk.Panedwindow(view, orient="vertical")
465
+ split.pack(fill="both", expand=True)
466
+ table_card = self._card(split)
467
+ graph_card = self._card(split)
468
+ split.add(table_card, weight=3)
469
+ split.add(graph_card, weight=2)
470
+
471
+ cols = [c[0] for c in COLUMNS]
472
+ self.tree = ttk.Treeview(table_card, columns=cols, show="headings", selectmode="browse")
473
+ for key, title, width, anchor in COLUMNS:
474
+ self.tree.heading(key, text=title, anchor=anchor if anchor != "center" else "center")
475
+ self.tree.column(key, width=S(width), anchor=anchor, stretch=False,
476
+ minwidth=S(TEXT_MIN.get(key, width)))
477
+ fit_columns(self.tree, {key: (S(width), S(TEXT_MIN[key]))
478
+ for key, _t, width, _a in COLUMNS if key in TEXT_MIN})
479
+ self.tree.bind("<ButtonRelease-1>", self._on_user_select)
480
+ self.tree.bind("<KeyRelease-Up>", self._on_user_select)
481
+ self.tree.bind("<KeyRelease-Down>", self._on_user_select)
482
+ self.tree.bind("<Button-3>", self._on_hop_menu)
483
+ vsb = ttk.Scrollbar(table_card, orient="vertical", command=self.tree.yview,
484
+ style="Card.Vertical.TScrollbar")
485
+ self.tree.configure(yscrollcommand=vsb.set)
486
+ vsb.pack(side="right", fill="y")
487
+ self.tree.pack(side="left", fill="both", expand=True)
488
+ side_scroll(self.tree, table_card)
489
+
490
+ self.canvas = tk.Canvas(graph_card, highlightthickness=0, bd=0)
491
+ self.canvas.pack(fill="both", expand=True)
492
+ self.canvas.bind("<Configure>", lambda _e: self._draw_graph())
493
+ return view
494
+
495
+ def _build_timeline_view(self, host) -> ttk.Frame:
496
+ view = ttk.Frame(host)
497
+ self.timeline_header = ttk.Label(view, text="No data yet.", style="Muted.TLabel")
498
+ self.timeline_header.pack(side="top", anchor="w", pady=(0, self.s(6)))
499
+ card = self._card(view)
500
+ card.pack(side="top", fill="both", expand=True)
501
+ self.timeline_canvas = tk.Canvas(card, highlightthickness=0, bd=0)
502
+ tl_vsb = ttk.Scrollbar(card, orient="vertical", command=self.timeline_canvas.yview,
503
+ style="Card.Vertical.TScrollbar")
504
+ self.timeline_canvas.configure(yscrollcommand=tl_vsb.set)
505
+ tl_vsb.pack(side="right", fill="y")
506
+ self.timeline_canvas.pack(side="left", fill="both", expand=True)
507
+ self.timeline_canvas.bind("<Configure>", lambda _e: self._draw_timeline())
508
+ self._timeline_wheel = WheelScroll(lambda n: self.timeline_canvas.yview_scroll(n, "units"))
509
+ self._timeline_wheel.bind(self.timeline_canvas)
510
+ return view
511
+
512
+ def _build_map_view(self, host) -> ttk.Frame:
513
+ view = ttk.Frame(host)
514
+ self.map_header = ttk.Label(
515
+ view, style="Muted.TLabel",
516
+ text="Router locations come from ipwho.is (public router addresses only, never private "
517
+ "or LAN ones) and from the routers' own names.")
518
+ self.map_header.pack(side="top", anchor="w", pady=(0, self.s(6)))
519
+ # Under the map (packed first so it keeps its room): where on the
520
+ # path the trouble is, by place (trouble.py).
521
+ S = self.s
522
+ box = ttk.Frame(view)
523
+ box.pack(side="bottom", fill="x", pady=(S(8), 0))
524
+ self.trouble_label = ttk.Label(box, text="", style="Strong.TLabel", wraplength=S(900),
525
+ justify="left")
526
+ self.trouble_label.pack(side="top", anchor="w")
527
+ tcard = self._card(box)
528
+ tcard.pack(side="top", fill="x", pady=(S(4), 0))
529
+ cols = (("place", "Place", 240, True), ("hops", "Hops", 120, False),
530
+ ("delay", "Delay added", 110, False), ("loss", "Loss starting here", 150, False))
531
+ self.trouble_tree = ttk.Treeview(tcard, columns=[c[0] for c in cols], show="headings", height=4)
532
+ for key, title, width, stretch in cols:
533
+ self.trouble_tree.heading(key, text=title, anchor="w")
534
+ self.trouble_tree.column(key, width=S(width), stretch=stretch, anchor="w")
535
+ self.trouble_tree.pack(fill="x")
536
+ card = self._card(view)
537
+ card.pack(side="top", fill="both", expand=True)
538
+ self.map_canvas = tk.Canvas(card, highlightthickness=0, bd=0)
539
+ self.map_canvas.pack(fill="both", expand=True)
540
+ self.map_canvas.bind("<Configure>", lambda _e: self._draw_map())
541
+ return view
542
+
543
+ def _build_events_view(self, host) -> ttk.Frame:
544
+ S = self.s
545
+ view = ttk.Frame(host)
546
+ card = self._card(view)
547
+ card.pack(fill="both", expand=True)
548
+ cols = ("time", "type", "detail")
549
+ self.events_tree = ttk.Treeview(card, columns=cols, show="headings")
550
+ for key, title, width, stretch in (("time", "Time", 90, False), ("type", "Type", 80, False),
551
+ ("detail", "Detail", 600, True)):
552
+ self.events_tree.heading(key, text=title, anchor="w")
553
+ self.events_tree.column(key, width=S(width), stretch=stretch, anchor="w")
554
+ ev_vsb = ttk.Scrollbar(card, orient="vertical", command=self.events_tree.yview,
555
+ style="Card.Vertical.TScrollbar")
556
+ self.events_tree.configure(yscrollcommand=ev_vsb.set)
557
+ ev_vsb.pack(side="right", fill="y")
558
+ self.events_tree.pack(side="left", fill="both", expand=True)
559
+ return view
560
+
561
+ def _show_view(self, key: str) -> None:
562
+ for k, v in self.views.items():
563
+ if k == key:
564
+ v.pack(fill="both", expand=True)
565
+ else:
566
+ v.pack_forget()
567
+ self._draw_ver = None
568
+ self._draw_active_view()
569
+
570
+ def build_app_settings(self, card) -> None:
571
+ """The Settings page's rows for running in the background."""
572
+ from .gui_widgets import setting_row
573
+
574
+ def switch(var, command=None, enabled=True):
575
+ def make(parent):
576
+ cb = ttk.Checkbutton(parent, variable=var, style="Card.Switch.TCheckbutton",
577
+ command=command)
578
+ if not enabled:
579
+ cb.state(["disabled"])
580
+ return cb
581
+ return make
582
+ has_tray = self.tray is not None
583
+ if winplatform.IS_WINDOWS:
584
+ setting_row(card, self.look, "Start with Windows",
585
+ "Starts in the notification area when you sign in, and resumes your targets. "
586
+ "It runs without administrator rights, so ICMP and TCP to the destination "
587
+ "work but full TCP/UDP traceroute doesn't: for that, run PingerPlot as "
588
+ "administrator when you need it.",
589
+ switch(self.autostart_var, self._toggle_autostart))
590
+ if self._elevated:
591
+ setting_row(card, self.look, "Running as administrator",
592
+ "Full TCP and UDP traceroute work in this session. To go back, quit "
593
+ "and open PingerPlot as usual.")
594
+ elif winplatform.can_elevate():
595
+ setting_row(card, self.look, "Run as administrator",
596
+ "Full TCP and UDP traceroute (every hop, not just the destination) "
597
+ "need it, to read the replies Windows would otherwise keep to "
598
+ "itself. Windows asks first; your targets carry on.",
599
+ lambda row: ttk.Button(row, text="Restart as administrator",
600
+ style="Card.TButton",
601
+ command=self._restart_elevated))
602
+ elif xdg.IS_LINUX:
603
+ setting_row(card, self.look, "Start when you sign in",
604
+ "Opens PingerPlot minimized when you sign in to your desktop, and resumes "
605
+ "your targets (an entry in ~/.config/autostart).",
606
+ switch(self.autostart_var, self._toggle_autostart))
607
+ setting_row(card, self.look, "Show in the applications menu",
608
+ "Adds PingerPlot, with its icon, to your desktop's applications menu and "
609
+ "search (an entry in ~/.local/share/applications).",
610
+ switch(self.menu_entry_var, self._toggle_menu_entry))
611
+ setting_row(card, self.look, "Keep running in the notification area when closed",
612
+ "Closing the window keeps every target monitored. Quit from the tray icon's "
613
+ "menu or the ⋯ menu." if has_tray else
614
+ "Not available here: there's no notification area to keep running in.",
615
+ switch(self.keep_tray_var, enabled=has_tray))
616
+ notifier = self._notifier()
617
+ if notifier is None:
618
+ about = ("Not available here: install notify-send (libnotify) for notifications."
619
+ if xdg.IS_LINUX else "Not available here: there's no notification area.")
620
+ elif getattr(notifier, "can_click", True):
621
+ about = "When an alert starts or ends. Click it to open that target."
622
+ else:
623
+ about = "When an alert starts or ends."
624
+ setting_row(card, self.look, "Show a notification for alerts", about,
625
+ switch(self.notify_var, enabled=notifier is not None))
626
+
627
+ def _toggle_autostart(self) -> None:
628
+ if self._autostart is None:
629
+ self.autostart_var.set(False)
630
+ return
631
+ on = bool(self.autostart_var.get())
632
+ if self._autostart.set_autostart(on) and on:
633
+ self.resume_var.set(True) # starting with nothing to resume is pointless
634
+ self.autostart_var.set(self._autostart.autostart_enabled())
635
+
636
+ def _toggle_menu_entry(self) -> None:
637
+ xdg.set_menu_entry(bool(self.menu_entry_var.get()))
638
+ self.menu_entry_var.set(xdg.menu_entry_enabled())
639
+
640
+ # --- the notification area ---------------------------------------------------
641
+ def _start_tray(self) -> None:
642
+ if not traymod.AVAILABLE:
643
+ return
644
+ t = traymod.TrayIcon(
645
+ lambda state, size: appicon.png_bytes(size, state), "PingerPlot", self._tray_menu,
646
+ on_open=lambda: self._post(self._show_window),
647
+ on_show=lambda: self._post(self._show_window),
648
+ on_theme=lambda: self._post(self._on_system_theme))
649
+ if t.start():
650
+ self.tray = t
651
+
652
+ def _post(self, fn) -> None:
653
+ """Run ``fn`` on Tk's thread. The tray's callbacks come from its own
654
+ thread, and a Tk call from another thread waits for the main loop."""
655
+ self._ui_jobs.put(fn)
656
+
657
+ def _drain_ui(self) -> None:
658
+ try:
659
+ while True:
660
+ try:
661
+ fn = self._ui_jobs.get_nowait()
662
+ except queue.Empty:
663
+ break
664
+ fn()
665
+ finally:
666
+ self.root.after(50, self._drain_ui)
667
+
668
+ def _tray_menu(self) -> list:
669
+ """Built on the tray thread: reads state, never touches Tk."""
670
+ M = traymod.MenuItem
671
+ running = any(m.running for n, m in self._monitors.items() if n not in self._loaded)
672
+ items = [M("Open PingerPlot", lambda: self._post(self._show_window), default=True), M(),
673
+ M("Stop all", lambda: self._post(self._stop_all), enabled=running)]
674
+ if winplatform.IS_WINDOWS:
675
+ items.append(M("Start with Windows", lambda: self._post(self._tray_toggle_autostart),
676
+ checked=winplatform.autostart_enabled()))
677
+ items += self.updates.tray_items(M)
678
+ if winplatform.can_elevate():
679
+ items.append(M("Restart as administrator", lambda: self._post(self._restart_elevated)))
680
+ items += [M(), M("Quit", lambda: self._post(self._quit))]
681
+ return items
682
+
683
+ def _restart_elevated(self) -> None:
684
+ """Start again as administrator (for full TCP/UDP traceroute): save,
685
+ ask Windows to start this copy elevated, and on its way, close. The
686
+ new copy waits for this one to let go of the single-instance lock and
687
+ resumes the same targets."""
688
+ self._save_settings()
689
+ why = winplatform.relaunch_elevated()
690
+ if why:
691
+ messagebox.showwarning("PingerPlot", why, parent=self.root)
692
+ return
693
+ self._quit()
694
+
695
+ def _tray_toggle_autostart(self) -> None:
696
+ self.autostart_var.set(not winplatform.autostart_enabled())
697
+ self._toggle_autostart()
698
+
699
+ def _show_window(self) -> None:
700
+ self.root.deiconify()
701
+ if self.root.state() == "iconic":
702
+ self.root.state("normal")
703
+ self.root.lift()
704
+ self.root.focus_force()
705
+ self._draw_ver = None
706
+
707
+ def _on_system_theme(self) -> None:
708
+ if self.theme_var.get() == "system":
709
+ self._theme_checked = 0.0
710
+ self._follow_system_theme()
711
+
712
+ def _notifier(self):
713
+ """What shows notifications: the tray icon (Windows), notify-send
714
+ (Linux), or nothing."""
715
+ return self.tray if self.tray is not None else self._desktop_notifier
716
+
717
+ def _update_tray(self) -> None:
718
+ live = [(n, m) for n, m in self._monitors.items() if n not in self._loaded]
719
+ if self.tray is not None:
720
+ running = sum(1 for _n, m in live if m.running and not m.paused)
721
+ alerting = sum(1 for _n, m in live if m.running and m.active_alerts())
722
+ state = "alert" if alerting else ("normal" if running else "idle")
723
+ tip = "PingerPlot" + (f" · {alerting} alerting" if alerting else "") + (
724
+ f" · monitoring {running}" if running else " · not monitoring")
725
+ if (state, tip) != self._tray_state:
726
+ self._tray_state = (state, tip)
727
+ self.tray.set_state(state, tip)
728
+ notifier = self._notifier() if self.notify_var.get() else None
729
+ # Every new event is consumed whether or not it's shown, so turning
730
+ # notifications on later doesn't replay old ones.
731
+ for name, mon in live:
732
+ new, last = mon.events_after(self._notify_seq.get(name, -1))
733
+ self._notify_seq[name] = last
734
+ for e in new:
735
+ if e.kind not in ("alert", "clear"):
736
+ continue
737
+ if e.kind == "alert" and not winplatform.IS_WINDOWS \
738
+ and getattr(mon, "alert_sound", False):
739
+ self.root.bell() # the engine's beep is Windows' winsound
740
+ if notifier is None:
741
+ continue
742
+ text = e.text.split(": ", 1)[1] if e.kind == "alert" and ": " in e.text else e.text
743
+ notifier.notify(f"{name}: {'alert' if e.kind == 'alert' else 'back to normal'}",
744
+ text, on_click=lambda n=name: self._post(lambda: self._open_target(n)))
745
+
746
+ def _open_target(self, name: str) -> None:
747
+ self._show_window()
748
+ self.nav.select("targets", notify=True)
749
+ if name in self._monitors:
750
+ self._select_card(name)
751
+
752
+ def report_url(self) -> str:
753
+ """The bug-report form, with the version filled in (an issue form
754
+ takes a field's value from the query string by the field's id)."""
755
+ return f"{REPO_URL}/issues/new?" + urllib.parse.urlencode(
756
+ {"template": "bug_report.yml", "version": __version__})
757
+
758
+ # --- defaults and starting ---------------------------------------------------
759
+ def _default_options(self) -> Optional[dict]:
760
+ """start() options from the Settings page, or None (after saying
761
+ why) when a number field doesn't parse."""
762
+ try:
763
+ return self.defaults.to_options()
764
+ except ValueError as exc:
765
+ messagebox.showwarning("Check the settings", str(exc))
766
+ return None
767
+
768
+ def _focus_add(self) -> None:
769
+ self.nav.select("targets", notify=True)
770
+ self.add_entry.focus_set()
771
+ self.add_entry.select_range(0, "end")
772
+
773
+ def _save_soon(self) -> None:
774
+ """Save once, a second from now, however many changes come together
775
+ (typing a number in Settings writes its variable on every key)."""
776
+ if self._save_job is not None:
777
+ self.root.after_cancel(self._save_job)
778
+ self._save_job = self.root.after(1000, self._save_now)
779
+
780
+ def _save_now(self) -> None:
781
+ self._save_job = None
782
+ self._save_settings()
783
+
784
+ def _start(self, target: Optional[str] = None, options: Optional[dict] = None) -> None:
785
+ self._save_soon()
786
+ """Start (or restart) ``target`` -- the Add box by default.
787
+
788
+ Without ``options``: a target already in the list that's running is
789
+ just selected; one that's stopped starts again with its own settings;
790
+ a new one gets the Settings page's defaults. With ``options`` (Edit
791
+ settings, a restored session) it (re)starts with exactly those."""
792
+ from_box = target is None
793
+ target = (self.target_var.get() if target is None else target).strip()
794
+ if not target:
795
+ messagebox.showwarning("No target", "Enter a host name or IP address.")
796
+ return
797
+ mon = self._monitors.get(target)
798
+ if options is None:
799
+ if mon is not None and target not in self._loaded:
800
+ if mon.running:
801
+ self._activate(target)
802
+ return
803
+ options = mon.start_options()
804
+ else:
805
+ options = self._default_options()
806
+ if options is None:
807
+ return
808
+ options = dict(options)
809
+ # One log setting, many targets: each gets its own file, or their rows
810
+ # interleave in a CSV that has no target column.
811
+ # text_option, not str(): {"a": 1} from a hand-edited settings.json
812
+ # became a log file called "{'a': 1}" in the working folder; refused,
813
+ # the target falls back to the defaults instead.
814
+ options["log_path"] = monitor.per_target_log_path(
815
+ monitor.text_option(options.get("log_path"), "log_path"), target)
816
+
817
+ if mon is None:
818
+ mon = Monitor(recorder=self.recorder)
819
+ self._monitors[target] = mon
820
+ mon.start(target, **options)
821
+ self._notify_seq[target] = -1 # a restart numbers its events from 0 again
822
+ if from_box:
823
+ self.target_var.set("")
824
+ self._activate(target)
825
+
826
+ def _activate(self, name: Optional[str]) -> None:
827
+ """Show ``name`` in the detail views, from a clean slate."""
828
+ self._active = name
829
+ self._selected_ttl = None
830
+ self._last_ttl = None
831
+ self._pinned = False
832
+ self._last_event_seq = -1
833
+ self._draw_ver = None
834
+ self.tree.delete(*self.tree.get_children())
835
+ self.events_tree.delete(*self.events_tree.get_children())
836
+ self._refresh_once()
837
+
838
+ def _active_monitor(self) -> Optional[Monitor]:
839
+ return self._monitors.get(self._active) if self._active else None
840
+
841
+ def _toggle_pause(self) -> None:
842
+ mon = self._active_monitor()
843
+ if mon is not None and mon.running:
844
+ (mon.resume if mon.paused else mon.pause)()
845
+ self._refresh_once()
846
+
847
+ def _toggle_run(self) -> None:
848
+ mon = self._active_monitor()
849
+ if mon is None or self._active in self._loaded:
850
+ return
851
+ if mon.running:
852
+ mon.stop()
853
+ self._refresh_once()
854
+ else:
855
+ self._start(self._active, mon.start_options())
856
+
857
+ def _edit_active(self) -> None:
858
+ if self._active and self._active not in self._loaded:
859
+ self._edit_target(self._active)
860
+
861
+ def _edit_target(self, name: str) -> None:
862
+ EditTargetDialog(self, name)
863
+
864
+ def _stop(self) -> None:
865
+ mon = self._active_monitor()
866
+ if mon is not None:
867
+ mon.stop()
868
+
869
+ def _stop_all(self) -> None:
870
+ # Signal every monitor before waiting on any: each stop() can wait up
871
+ # to a reply timeout for a round in flight, and one at a time those
872
+ # waits added up into a frozen window.
873
+ mons = list(self._monitors.values())
874
+ for mon in mons:
875
+ mon.request_stop()
876
+ for mon in mons:
877
+ mon.stop()
878
+ self._refresh_once()
879
+
880
+ def _remove_target(self) -> None:
881
+ self._remove_named(self._active)
882
+
883
+ def _remove_named(self, name: Optional[str]) -> None:
884
+ self._save_soon()
885
+ if not name or name not in self._monitors:
886
+ return
887
+ self._monitors.pop(name).shutdown()
888
+ self._loaded.discard(name)
889
+ card = self._cards.pop(name, None)
890
+ if card is not None:
891
+ card.destroy()
892
+ if self._active == name:
893
+ self._activate(next(iter(self._monitors), None))
894
+ else:
895
+ self._refresh_once()
896
+
897
+ def _select_card(self, name: str) -> None:
898
+ if name != self._active:
899
+ self._activate(name)
900
+
901
+ def _on_user_select(self, _event: object) -> None:
902
+ sel = self.tree.selection()
903
+ if sel:
904
+ try:
905
+ self._selected_ttl = int(sel[0])
906
+ self._pinned = True
907
+ except ValueError:
908
+ pass
909
+ self._draw_graph()
910
+
911
+ # --- menus --------------------------------------------------------------------
912
+ def _menu(self, parent) -> tk.Menu:
913
+ return tk.Menu(parent, tearoff=0, **self.look.menu_colours())
914
+
915
+ def _popup(self, menu: tk.Menu, x: int, y: int) -> None:
916
+ try:
917
+ menu.tk_popup(x, y)
918
+ finally:
919
+ menu.grab_release()
920
+
921
+ def _check_for_updates(self) -> None:
922
+ """From the ⋯ menu: check, on the Settings page, where the answer
923
+ shows."""
924
+ self.nav.select("settings", notify=True)
925
+ self.updates.check()
926
+
927
+ def _header_menu(self, button) -> None:
928
+ m = self._menu(self.root)
929
+ m.add_command(label="Export hops as CSV…", command=self._export)
930
+ m.add_command(label="Save session…", command=self._save_session)
931
+ m.add_command(label="Open a saved session…", command=self._load_session)
932
+ m.add_command(label="Compare with a saved session…", command=self._compare_with_baseline)
933
+ m.add_separator()
934
+ if winplatform.can_elevate():
935
+ m.add_command(label="Restart as administrator", command=self._restart_elevated)
936
+ m.add_command(label="Check for updates", command=self._check_for_updates)
937
+ m.add_command(label="Report a problem…", command=lambda: webbrowser.open(self.report_url()))
938
+ m.add_command(label="Project page", command=lambda: webbrowser.open(REPO_URL))
939
+ m.add_separator()
940
+ m.add_command(label="Quit", command=self._quit)
941
+ self._popup(m, button.winfo_rootx(), button.winfo_rooty() + button.winfo_height())
942
+
943
+ def _target_menu(self, name: str, x: int, y: int) -> None:
944
+ if name not in self._monitors:
945
+ return
946
+ self._select_card(name)
947
+ mon = self._monitors[name]
948
+ loaded = name in self._loaded
949
+ m = self._menu(self.root)
950
+ if not loaded:
951
+ m.add_command(label="Edit settings…", command=lambda: self._edit_target(name))
952
+ m.add_command(label="Show history", command=lambda: self._show_history(name))
953
+ m.add_separator()
954
+ if mon.running:
955
+ m.add_command(label="Resume" if mon.paused else "Pause",
956
+ command=lambda: ((mon.resume if mon.paused else mon.pause)(),
957
+ self._refresh_once()))
958
+ m.add_command(label="Stop", command=lambda: (mon.stop(), self._refresh_once()))
959
+ else:
960
+ m.add_command(label="Start", command=lambda: self._start(name, mon.start_options()))
961
+ m.add_separator()
962
+ m.add_command(label="Remove" if not loaded else "Close", command=lambda: self._remove_named(name))
963
+ self._popup(m, x, y)
964
+
965
+ def _on_hop_menu(self, event) -> None:
966
+ iid = self.tree.identify_row(event.y)
967
+ if not iid:
968
+ return
969
+ self.tree.selection_set(iid)
970
+ self._on_user_select(event)
971
+ vals = self.tree.item(iid, "values")
972
+ ip = str(vals[1]) if len(vals) > 1 else ""
973
+ host = str(vals[2]) if len(vals) > 2 else ""
974
+ m = self._menu(self.tree)
975
+ ttl = int(vals[0]) if vals else 0
976
+ if ttl and self._active not in self._loaded:
977
+ m.add_command(label="Details…", command=lambda: self._hop_details(ttl, ip, host))
978
+ m.add_separator()
979
+ if ip and ip != "*":
980
+ m.add_command(label=f"Copy address {ip}", command=lambda: self._clip(ip))
981
+ if host and host not in ("", "(resolving…)"):
982
+ m.add_command(label=f"Copy hostname {host}", command=lambda: self._clip(host))
983
+ m.add_command(label="Copy row", command=lambda: self._clip("\t".join(str(v) for v in vals)))
984
+ self._popup(m, event.x_root, event.y_root)
985
+
986
+ def _clip(self, text: str) -> None:
987
+ if not text:
988
+ return
989
+ self.root.clipboard_clear()
990
+ self.root.clipboard_append(text)
991
+ self._note("Copied")
992
+
993
+ def _note(self, text: str, seconds: float = 5.0) -> None:
994
+ """A passing confirmation in the header (copied, exported, saved)."""
995
+ self.note_label.configure(text=text)
996
+ self._note_until = time.monotonic() + seconds
997
+
998
+ def _on_close(self) -> None:
999
+ """The window's close button: to the tray if it's there and wanted,
1000
+ otherwise quit."""
1001
+ if self.tray is not None and self.keep_tray_var.get():
1002
+ self._save_settings() # a crash later shouldn't cost the target list
1003
+ self.root.withdraw()
1004
+ if not self._settings.get("told_hidden"):
1005
+ self._settings["told_hidden"] = True
1006
+ self.tray.notify("PingerPlot is still running",
1007
+ "Your targets are still being monitored. Quit from this icon's menu.",
1008
+ on_click=lambda: self._post(self._show_window))
1009
+ return
1010
+ self._quit()
1011
+
1012
+ def _quit(self) -> None:
1013
+ if self._save_job is not None:
1014
+ self.root.after_cancel(self._save_job)
1015
+ self._save_job = None
1016
+ self._save_settings()
1017
+ if self.tray is not None:
1018
+ self.tray.stop()
1019
+ self.tray = None
1020
+ self.geo.stop()
1021
+ mons = list(self._monitors.values())
1022
+ for mon in mons:
1023
+ mon.request_stop() # all at once, as in _stop_all
1024
+ for mon in mons:
1025
+ mon.shutdown()
1026
+ self._empty.shutdown()
1027
+ if self.recorder is not None:
1028
+ self.recorder.close() # after the monitors: their last minutes too
1029
+ tkthreads.drain()
1030
+ self.root.destroy()
1031
+
1032
+ # --- settings persistence ---------------------------------------------------
1033
+ def _apply_saved_settings(self) -> None:
1034
+ """The saved defaults and app options, into their controls."""
1035
+ s = self._settings
1036
+ self.defaults.load_settings(s)
1037
+ for var, key in ((self.resume_var, "resume_on_launch"), (self.keep_tray_var, "keep_in_tray"),
1038
+ (self.notify_var, "notify"), (self.lookup_var, "lookup_hops")):
1039
+ if isinstance(s.get(key), bool):
1040
+ var.set(s[key])
1041
+ self.updates.load(s)
1042
+
1043
+ def _save_settings(self) -> None:
1044
+ """Persist the defaults, app options and the target list."""
1045
+ data = {"theme": self.theme_var.get(),
1046
+ "resume_on_launch": bool(self.resume_var.get()),
1047
+ "keep_in_tray": bool(self.keep_tray_var.get()),
1048
+ "notify": bool(self.notify_var.get()),
1049
+ "lookup_hops": bool(self.lookup_var.get()),
1050
+ "told_hidden": bool(self._settings.get("told_hidden", False))}
1051
+ self.defaults.save_settings(data)
1052
+ self.updates.save(data)
1053
+ data["recording"] = self.recording.options()
1054
+ # Live targets only. A loaded session lives in the same dict so the
1055
+ # detail views can render it, but its key is "<name> (loaded)" -- not
1056
+ # a hostname. Saving it meant _restore_targets called _start() on it
1057
+ # next launch, leaving a permanently dead "Cannot resolve" target.
1058
+ data["targets"] = [n for n in self._monitors if n not in self._loaded]
1059
+ # Each target's own configuration: restoring from the defaults alone
1060
+ # gave every target the same values.
1061
+ data["target_options"] = {n: m.start_options() for n, m in self._monitors.items()
1062
+ if n not in self._loaded}
1063
+ settings.save(data)
1064
+
1065
+ # --- the history -------------------------------------------------------
1066
+ def _apply_recording_soon(self) -> None:
1067
+ # Typing "30" into a days box is two changes; open or close nothing
1068
+ # until the typing stops.
1069
+ if self._recording_job is not None:
1070
+ self.root.after_cancel(self._recording_job)
1071
+ self._recording_job = self.root.after(800, self._apply_recording)
1072
+
1073
+ def _apply_recording(self) -> None:
1074
+ """Make the recorder match the Recording section, live: turning it
1075
+ on records running targets from now, off closes their runs."""
1076
+ self._recording_job = None
1077
+ opts = self.recording.options()
1078
+ live = [m for n, m in self._monitors.items() if n not in self._loaded]
1079
+ if opts["enabled"]:
1080
+ if self.recorder is None:
1081
+ self.recorder = history.Recorder(options=opts, program="gui").start()
1082
+ for mon in live:
1083
+ mon.set_recorder(self.recorder)
1084
+ else:
1085
+ self.recorder.set_options(opts)
1086
+ elif self.recorder is not None:
1087
+ old, self.recorder = self.recorder, None
1088
+ for mon in live:
1089
+ mon.set_recorder(None)
1090
+ # close() waits for the last writes; not on the window's thread.
1091
+ threading.Thread(target=old.close, name="history-close", daemon=True).start()
1092
+
1093
+ def clear_history(self) -> None:
1094
+ gui_recording.clear_history(self)
1095
+
1096
+ # --- where routers are ----------------------------------------------------
1097
+ def _apply_lookups(self) -> None:
1098
+ """On: look routers up while monitoring. Off: stop, and the Map goes
1099
+ back to asking only while it's open."""
1100
+ if self.lookup_var.get():
1101
+ if not self._geo_started:
1102
+ self.geo.start()
1103
+ self._geo_started = True
1104
+ elif self._geo_started:
1105
+ self.geo.stop()
1106
+ self._geo_started = False
1107
+
1108
+ def _feed_lookups(self) -> None:
1109
+ """Queue every running target's routers, every few seconds. Each is
1110
+ asked about once a month at most (the resolver remembers)."""
1111
+ now = time.monotonic()
1112
+ if not self.lookup_var.get() or now - self._geo_fed < 5.0:
1113
+ return
1114
+ self._geo_fed = now
1115
+ for name, mon in self._monitors.items():
1116
+ if name not in self._loaded:
1117
+ for addr in mon.hop_addresses():
1118
+ self.geo.request(addr)
1119
+
1120
+ ANCHORS_EVERY = 10.0 # seconds between rebuilding the live anchors
1121
+
1122
+ def _locator(self, name: Optional[str] = None, views=None) -> locating.Locator:
1123
+ """Where the routers of target ``name`` (the active one by default)
1124
+ are, checked against every live target's routers placed by name: the
1125
+ check needs round trips from this computer at about the same time, so
1126
+ a saved session is checked only against its own routers."""
1127
+ name = self._active if name is None else name
1128
+ if views is None:
1129
+ mon = self._monitors.get(name) if name else None
1130
+ views = mon.snapshot()[0] if mon is not None else []
1131
+ if name in self._loaded:
1132
+ found = locating.anchors((v.hostname, v.best_here) for v in views)
1133
+ else:
1134
+ now = time.monotonic()
1135
+ if now - self._anchors_at >= self.ANCHORS_EVERY:
1136
+ self._anchors = locating.anchors(
1137
+ r for n, m in self._monitors.items() if n not in self._loaded for r in m.routers())
1138
+ self._anchors_at = now
1139
+ found = self._anchors
1140
+ return locating.Locator(self.geo, found, locating.path_of(views))
1141
+
1142
+ def _hop_details(self, ttl: int, address: str, hostname: str) -> None:
1143
+ name = self._active
1144
+ if name is None:
1145
+ return
1146
+ gui_hopinfo.HopDetails(self, name, ttl, address if address != "*" else None,
1147
+ hostname or None)
1148
+
1149
+ def _restore_targets(self, force: bool = False) -> None:
1150
+ """If enabled (or ``force``d), re-add and start the last session's
1151
+ targets, each with the options it was running with."""
1152
+ if not (force or self.resume_var.get()):
1153
+ return
1154
+ saved = self._settings.get("target_options")
1155
+ saved = saved if isinstance(saved, dict) else {}
1156
+ for name in self._settings.get("targets", []) or []:
1157
+ if not (isinstance(name, str) and name.strip()):
1158
+ continue
1159
+ opts = saved.get(name)
1160
+ if isinstance(opts, dict):
1161
+ opts = {k: v for k, v in opts.items() if k in monitor.START_OPTION_KEYS
1162
+ and not (self._elevated and k == "log_path")}
1163
+ else:
1164
+ opts = None # 1.3.x settings: names only
1165
+ try:
1166
+ self._start(name, opts)
1167
+ except (ValueError, TypeError, OverflowError):
1168
+ # A hand-edited or corrupt entry. This runs inside __init__, so
1169
+ # raising would stop the app opening at all; the defaults are
1170
+ # the 1.3.x behaviour.
1171
+ self._start(name, self._default_options())
1172
+ self.target_var.set("")
1173
+
1174
+ # --- export, sessions, comparison ------------------------------------------
1175
+ def _export(self) -> None:
1176
+ views, _status, target_ip, target_input = self.monitor.snapshot()
1177
+ if not views:
1178
+ messagebox.showinfo("Nothing to export", "No hop data yet.")
1179
+ return
1180
+ path = filedialog.asksaveasfilename(
1181
+ title="Export hop statistics", defaultextension=".csv",
1182
+ initialfile=f"pingerplot_{target_input or 'route'}.csv",
1183
+ filetypes=[("CSV files", "*.csv"), ("All files", "*.*")])
1184
+ if not path:
1185
+ return
1186
+ info = self.monitor.run_summary()
1187
+ mode = info["packet_type"].upper()
1188
+ if info["packet_type"] != "icmp":
1189
+ mode += f":{info['port']}"
1190
+
1191
+ def _iso(t):
1192
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t)) if t else "?"
1193
+
1194
+ ws, we = info["window_start"], info["window_end"]
1195
+ window = f"{we - ws:.0f}s ({_iso(ws)} to {_iso(we)})" if ws and we else "?"
1196
+ try:
1197
+ with open(path, "w", newline="", encoding="utf-8") as fh:
1198
+ # Self-documenting header: records exactly how this run was made,
1199
+ # so two exports can actually be compared after the fact.
1200
+ # Through csv.writer, each line one cell, with the strings a
1201
+ # loaded session supplies (untrusted) stripped of line breaks
1202
+ # and defanged: a target with a newline and "=WEBSERVICE(...)"
1203
+ # in it was a live formula when the export opened in Excel.
1204
+ def clean(v) -> str:
1205
+ return csv_safe("".join(" " if c in "\r\n\t\x0b\x0c" else c for c in str(v)))
1206
+ w = csv.writer(fh)
1207
+ for line in (
1208
+ f"# PingerPlot {info['version']} export - {_iso(time.time())}",
1209
+ f"# target={clean(info['target_input'])} [{clean(info['target_ip'])}] "
1210
+ f"mode={mode}",
1211
+ f"# interval={info['interval']}s timeout={info['timeout_ms']}ms "
1212
+ f"packet_size={info['packet_size']}B send_delay={info['send_delay_ms']}ms "
1213
+ f"max_hops={info['max_hops']} "
1214
+ f"final_hop_only={'yes' if info['final_hop_only'] else 'no'} "
1215
+ f"dscp={info['dscp']} source={clean(info['source_ip']) or 'auto'}",
1216
+ f"# samples={info['samples']} window={window}"):
1217
+ w.writerow([line])
1218
+ w.writerow(["hop", "ip", "hostname", "sent", "received", "loss_pct",
1219
+ "current_ms", "avg_ms", "min_ms", "max_ms", "jitter_ms", "status", "mos",
1220
+ "location", "network"])
1221
+ last_ttl = views[-1].ttl
1222
+ where = self._locator(views=views)
1223
+ for v in views:
1224
+ m = mos(v.avg, v.jitter, v.loss_pct) if v.ttl == last_ttl else None
1225
+ w.writerow([
1226
+ v.ttl, csv_safe(v.address or ""), csv_safe(v.hostname or ""),
1227
+ v.sent, v.received,
1228
+ f"{v.loss_pct:.1f}", _csv_num(v.current), _csv_num(v.avg),
1229
+ _csv_num(v.best), _csv_num(v.worst), _csv_num(v.jitter),
1230
+ icmp.status_text(v.last_status) if v.last_status is not None else "",
1231
+ f"{m:.2f}" if m is not None else "",
1232
+ csv_safe(where.view(v).text),
1233
+ csv_safe(gui_hopinfo.network(v.address, self.geo)),
1234
+ ])
1235
+ except OSError as exc:
1236
+ messagebox.showerror("Export failed", str(exc))
1237
+ return
1238
+ self._note(f"Exported {len(views)} hops")
1239
+
1240
+ def _save_session(self) -> None:
1241
+ data = self.monitor.to_dict()
1242
+ if not data.get("hops"):
1243
+ messagebox.showinfo("Nothing to save", "No hop data yet.")
1244
+ return
1245
+ path = filedialog.asksaveasfilename(
1246
+ title="Save session", defaultextension=".json",
1247
+ initialfile=f"pingerplot_{data.get('target_input') or 'session'}.json",
1248
+ filetypes=[("PingerPlot session", "*.json"), ("All files", "*.*")])
1249
+ if not path:
1250
+ return
1251
+ try:
1252
+ tmp = path + ".tmp"
1253
+ with open(tmp, "w", encoding="utf-8") as fh:
1254
+ json.dump(data, fh)
1255
+ os.replace(tmp, path) # atomic: never leave a truncated session file
1256
+ except OSError as exc:
1257
+ messagebox.showerror("Save failed", str(exc))
1258
+ return
1259
+ self._note(f"Saved session ({len(data['hops'])} hops)")
1260
+
1261
+ def _load_session(self) -> None:
1262
+ path = filedialog.askopenfilename(
1263
+ title="Open a saved session",
1264
+ filetypes=[("PingerPlot session", "*.json"), ("All files", "*.*")])
1265
+ if not path:
1266
+ return
1267
+ try:
1268
+ with open(path, "r", encoding="utf-8-sig") as fh:
1269
+ data = json.load(fh)
1270
+ except (OSError, ValueError) as exc:
1271
+ messagebox.showerror("Load failed", str(exc))
1272
+ return
1273
+ if not isinstance(data, dict) or "hops" not in data:
1274
+ messagebox.showerror("Load failed", "Not a PingerPlot session file.")
1275
+ return
1276
+ name = f"{data.get('target_input') or 'loaded session'} (loaded)"
1277
+ # Loaded into a fresh Monitor and only then registered: registering
1278
+ # first left an empty "(loaded)" row behind whenever the load raised.
1279
+ mon = Monitor()
1280
+ try:
1281
+ mon.load_dict(data)
1282
+ except (ValueError, TypeError) as exc:
1283
+ messagebox.showerror("Load failed", f"Could not load that session: {exc}")
1284
+ return
1285
+ old = self._monitors.get(name)
1286
+ if old is not None:
1287
+ old.shutdown()
1288
+ self._monitors[name] = mon
1289
+ self._loaded.add(name)
1290
+ self.nav.select("targets", notify=True)
1291
+ self._activate(name)
1292
+
1293
+ def _compare_with_baseline(self) -> None:
1294
+ """Diff the selected target against a session saved earlier: what says
1295
+ whether today's path differs from last Tuesday's."""
1296
+ views, _status, _ip, target_input = self.monitor.snapshot()
1297
+ if not views:
1298
+ messagebox.showinfo("Nothing to compare",
1299
+ "Select a target with data first: there is nothing to compare yet.")
1300
+ return
1301
+ path = filedialog.askopenfilename(
1302
+ title="Choose a saved session to compare against",
1303
+ filetypes=[("PingerPlot session", "*.json"), ("All files", "*.*")])
1304
+ if not path:
1305
+ return
1306
+ try:
1307
+ with open(path, "r", encoding="utf-8-sig") as fh:
1308
+ data = json.load(fh)
1309
+ except (OSError, ValueError) as exc:
1310
+ messagebox.showerror("Compare failed", str(exc))
1311
+ return
1312
+ if not isinstance(data, dict):
1313
+ messagebox.showerror("Compare failed", "Not a PingerPlot session file.")
1314
+ return
1315
+ base = cmpmod.stats_from_session(data)
1316
+ if not base:
1317
+ messagebox.showerror("Compare failed", "That session has no hop data to compare against.")
1318
+ return
1319
+ base_target = str(data.get("target_input") or os.path.basename(path))
1320
+ if base_target and target_input and base_target != target_input:
1321
+ # Comparing two different destinations is almost always a mis-click,
1322
+ # and the per-hop numbers would be meaningless. Warn, but allow it:
1323
+ # the same host is legitimately reachable under two names.
1324
+ if not messagebox.askyesno(
1325
+ "Different target",
1326
+ f"The saved session is for '{base_target}' but this target is "
1327
+ f"'{target_input}'.\n\nCompare anyway?"):
1328
+ return
1329
+ now = cmpmod.stats_from_views(views)
1330
+ self._show_comparison(cmpmod.compare(base, now, target=target_input), base_target)
1331
+
1332
+ def _show_comparison(self, cmp_, baseline_label: str) -> None:
1333
+ S = self.s
1334
+ win = tk.Toplevel(self.root)
1335
+ win.title(f"Compare: now and {baseline_label}")
1336
+ win.transient(self.root)
1337
+ win.geometry(f"{S(920)}x{S(480)}")
1338
+ self.look.style_window(win)
1339
+ body = ttk.Frame(win, padding=(S(20), S(16)))
1340
+ body.pack(fill="both", expand=True)
1341
+ ttk.Label(body, text=cmp_.summary(), style="Strong.TLabel").pack(side="top", anchor="w")
1342
+ foot = ttk.Frame(body, padding=(0, S(12), 0, 0))
1343
+ foot.pack(side="bottom", fill="x")
1344
+ ttk.Button(foot, text="Copy as text", command=lambda: self._clip(
1345
+ "\n".join(cmpmod.format_comparison(cmp_, baseline_label)))).pack(side="left")
1346
+ ttk.Button(foot, text="Close", command=win.destroy).pack(side="right")
1347
+ card = self._card(body)
1348
+ card.pack(side="top", fill="both", expand=True, pady=(S(10), 0))
1349
+ cols = ("ttl", "address", "loss", "d_loss", "avg", "d_avg", "verdict")
1350
+ tree = ttk.Treeview(card, columns=cols, show="headings", selectmode="browse")
1351
+ for key, title, width, anchor in (
1352
+ ("ttl", "Hop", 44, "center"), ("address", "Address", 150, "w"),
1353
+ ("loss", "Loss", 62, "e"), ("d_loss", "Δ Loss", 74, "e"),
1354
+ ("avg", "Avg ms", 70, "e"), ("d_avg", "Δ Avg", 74, "e"),
1355
+ ("verdict", "Change", 260, "w"),
1356
+ ):
1357
+ tree.heading(key, text=title)
1358
+ tree.column(key, width=S(width), anchor=anchor, stretch=(key == "verdict"))
1359
+ for tag in ("bad", "warn", "ok", "dest"):
1360
+ tree.tag_configure(tag, background=COLORS[tag], foreground=COLORS["fg"])
1361
+ for r in cmp_.rows:
1362
+ side = r.now or r.base
1363
+ note = r.verdict
1364
+ if r.verdict == cmpmod.REROUTED and r.base and r.now:
1365
+ note = f"rerouted {r.base.address} → {r.now.address}"
1366
+ tree.insert("", "end", values=(
1367
+ r.ttl, r.address or "*",
1368
+ "—" if side is None else f"{side.loss_pct:.0f}%",
1369
+ "" if r.d_loss is None else f"{r.d_loss:+.0f}%",
1370
+ "—" if side is None or side.avg is None else _ms(side.avg),
1371
+ "" if r.d_avg is None else f"{r.d_avg:+.1f}",
1372
+ note,
1373
+ ), tags=(self._verdict_tag(r.verdict),))
1374
+ vsb = ttk.Scrollbar(card, orient="vertical", command=tree.yview, style="Card.Vertical.TScrollbar")
1375
+ tree.configure(yscrollcommand=vsb.set)
1376
+ vsb.pack(side="right", fill="y")
1377
+ tree.pack(side="left", fill="both", expand=True)
1378
+
1379
+ @staticmethod
1380
+ def _verdict_tag(verdict: str) -> str:
1381
+ """Red for a regression, amber for anything that moved, plain for the
1382
+ rest - so the eye lands on the hops that got worse."""
1383
+ if verdict == cmpmod.WORSE:
1384
+ return "bad"
1385
+ if verdict in (cmpmod.REROUTED, cmpmod.NEW, cmpmod.GONE):
1386
+ return "warn"
1387
+ if verdict == cmpmod.BETTER:
1388
+ return "dest"
1389
+ return "ok"
1390
+
1391
+ # --- refresh loop -------------------------------------------------------------
1392
+ def _refresh(self) -> None:
1393
+ # Re-arm first-and-always: an exception in one redraw is reported by
1394
+ # Tk and must not also end the timer, which froze every target's
1395
+ # display while the monitors carried on probing behind it.
1396
+ try:
1397
+ tkthreads.drain()
1398
+ self._refresh_once()
1399
+ finally:
1400
+ self.root.after(REFRESH_MS, self._refresh)
1401
+
1402
+ def _refresh_once(self) -> None:
1403
+ self._follow_system_theme()
1404
+ self._update_header()
1405
+ self._update_tray()
1406
+ if self.root.state() == "withdrawn":
1407
+ return # in the tray: nothing on screen to update
1408
+ self._feed_lookups()
1409
+ self._update_cards()
1410
+ views, status, target_ip, _target_input = self.monitor.snapshot()
1411
+ self._update_detail(views, status, target_ip)
1412
+ self._update_elevate_button()
1413
+ self._update_table(views)
1414
+ self._update_events()
1415
+ # Redraw the visible canvas only when its data changed since the last
1416
+ # tick (probes arrive every `interval`, but we tick faster). Resize and
1417
+ # view changes redraw through their own bindings.
1418
+ ver = draw_version(self._active, self._active_monitor(), self._selected_ttl,
1419
+ self.theme, self.geo.count())
1420
+ if ver != self._draw_ver:
1421
+ self._draw_ver = ver
1422
+ self._draw_active_view()
1423
+
1424
+ def _state_of(self, name: str, mon: Monitor) -> str:
1425
+ if name in self._loaded or not mon.running:
1426
+ return "idle"
1427
+ if mon.paused:
1428
+ return "paused"
1429
+ if mon.active_alerts():
1430
+ return "alert"
1431
+ n, loss, avg, _j, _reached = mon.summary()
1432
+ if n and loss is not None and (loss > 0 or (avg is not None and avg >= BAD_MS)):
1433
+ return "warn"
1434
+ return "ok"
1435
+
1436
+ def _update_header(self) -> None:
1437
+ live = [(n, m) for n, m in self._monitors.items() if n not in self._loaded]
1438
+ running = sum(1 for _n, m in live if m.running and not m.paused)
1439
+ alerting = sum(1 for _n, m in live if m.running and m.active_alerts())
1440
+ c = self.look.c
1441
+ if alerting:
1442
+ dot, text = c["red"], f"{alerting} alerting · monitoring {running}"
1443
+ elif running:
1444
+ dot, text = c["green"], f"Monitoring {running} target{'s' if running != 1 else ''}"
1445
+ elif live:
1446
+ dot, text = c["text3"], "Stopped"
1447
+ else:
1448
+ dot, text = c["text3"], "Not monitoring"
1449
+ self.status_dot.configure(foreground=dot)
1450
+ self.status_text.configure(text=text)
1451
+ title = "PingerPlot" + (" (Administrator)" if self._elevated else "") + (
1452
+ f" · {alerting} alerting" if alerting else "")
1453
+ if self.root.title() != title:
1454
+ self.root.title(title)
1455
+ if self._note_until and time.monotonic() > self._note_until:
1456
+ self.note_label.configure(text="")
1457
+ self._note_until = 0.0
1458
+
1459
+ def _update_cards(self) -> None:
1460
+ for name in list(self._cards):
1461
+ if name not in self._monitors:
1462
+ self._cards.pop(name).destroy()
1463
+ S = self.s
1464
+ for name, mon in self._monitors.items():
1465
+ card = self._cards.get(name)
1466
+ if card is None:
1467
+ card = TargetCard(self.cards_scroll.inner, self.look, name,
1468
+ self._select_card, self._target_menu)
1469
+ card.pack(side="top", fill="x", pady=(0, S(8)))
1470
+ self._cards[name] = card
1471
+ state = self._state_of(name, mon)
1472
+ n, loss, avg, jitter, reached = mon.summary()
1473
+ if name in self._loaded:
1474
+ stats = "Saved session" + (f" · {n} hops" if n else "")
1475
+ elif not mon.running:
1476
+ stats = "Stopped"
1477
+ elif mon.paused:
1478
+ stats = "Paused"
1479
+ elif not n:
1480
+ stats = "Tracing the route…"
1481
+ else:
1482
+ score = mos(avg, jitter, loss) if reached else None
1483
+ parts = [f"{n} hop{'s' if n != 1 else ''}",
1484
+ f"{loss:.0f}% loss" if loss is not None else "",
1485
+ f"{fmt_ms(avg)} ms" if avg is not None else "no reply",
1486
+ f"MOS {score:.1f}" if score is not None else ""]
1487
+ stats = " · ".join(p for p in parts if p)
1488
+ card.update_card(state, name, stats, selected=(name == self._active))
1489
+ live = sum(1 for n in self._monitors if n not in self._loaded)
1490
+ self.targets_caption.configure(text=f"TARGETS · {live}" if live else "TARGETS")
1491
+ if self._monitors:
1492
+ self.cards_empty.pack_forget()
1493
+ elif not self.cards_empty.winfo_ismapped():
1494
+ self.cards_empty.pack(side="top", anchor="w")
1495
+
1496
+ def _update_elevate_button(self) -> None:
1497
+ want = bool(getattr(self.monitor, "needs_admin", False)) and winplatform.can_elevate()
1498
+ if want != self._elevate_shown:
1499
+ self._elevate_shown = want
1500
+ if want:
1501
+ self.elevate_btn.pack(side="left", padx=(self.s(6), 0))
1502
+ else:
1503
+ self.elevate_btn.pack_forget()
1504
+
1505
+ def _update_detail(self, views: List[HopView], status: str, target_ip: Optional[str]) -> None:
1506
+ mon = self._active_monitor()
1507
+ name = self._active
1508
+ loaded = name in self._loaded if name else False
1509
+ if mon is None:
1510
+ self.detail_title.configure(text="No target selected")
1511
+ self.detail_status.configure(text="Add one on the left, or choose one from the list.")
1512
+ for b in (self.pause_btn, self.stop_btn, self.edit_btn):
1513
+ b.state(["disabled"])
1514
+ self.mos_label_w.configure(text="")
1515
+ self.detail_stats.configure(text="")
1516
+ self._set_banner([])
1517
+ return
1518
+ shown = name if not target_ip or target_ip == name else f"{name} ({target_ip})"
1519
+ self.detail_title.configure(text=shown)
1520
+ self.detail_status.configure(text=self._describe(mon, status))
1521
+ self.pause_btn.configure(text="Resume" if mon.paused else "Pause")
1522
+ self.pause_btn.state(["!disabled"] if (mon.running and not loaded) else ["disabled"])
1523
+ self.stop_btn.configure(text="Stop" if mon.running else "Start")
1524
+ self.stop_btn.state(["disabled"] if loaded else ["!disabled"])
1525
+ self.edit_btn.state(["disabled"] if loaded else ["!disabled"])
1526
+
1527
+ c = self.look.c
1528
+ dest = views[-1] if views else None
1529
+ score = mos(dest.avg, dest.jitter, dest.loss_pct) if (dest and mon.reached_target) else None
1530
+ if score is None:
1531
+ self.mos_label_w.configure(text="")
1532
+ else:
1533
+ colour = c["green"] if score >= 4.0 else c["amber"] if score >= 3.1 else c["red"]
1534
+ self.mos_label_w.configure(text=f"MOS {score:.1f} · {mos_label(score)}", foreground=colour)
1535
+ if dest is not None:
1536
+ jit = f" · jitter {fmt_ms(dest.jitter)} ms" if dest.jitter is not None else ""
1537
+ avg = f"{fmt_ms(dest.avg)} ms average" if dest.avg is not None else "no reply yet"
1538
+ self.detail_stats.configure(
1539
+ text=f"Destination: {dest.loss_pct:.0f}% loss · {avg}{jit} · {dest.sent} probes")
1540
+ else:
1541
+ self.detail_stats.configure(text="")
1542
+ self._set_banner(mon.active_alerts())
1543
+
1544
+ @staticmethod
1545
+ def _describe(mon: Monitor, status: str) -> str:
1546
+ """How a monitoring target runs, in one line; the engine's own status
1547
+ for everything else (resolving, tracing, paused, stopped and why).
1548
+ The engine's monitoring line repeats the name and address the title
1549
+ already shows, and the alert count the banner already shows."""
1550
+ if not mon.running or mon.paused or not status.startswith("Monitoring"):
1551
+ return status
1552
+ proto = mon.packet_type.upper() + (f" port {mon.port}" if mon.packet_type != "icmp" else "")
1553
+ parts = [proto, f"every {mon.interval:g} s",
1554
+ "destination only" if mon.final_hop_only
1555
+ else f"{mon.route_len} hop{'s' if mon.route_len != 1 else ''}"]
1556
+ if mon.dscp:
1557
+ parts.append(f"DSCP {mon.dscp}")
1558
+ if mon.source_ip:
1559
+ parts.append(f"from {mon.source_ip}")
1560
+ if not mon.reached_target:
1561
+ parts.append("the destination isn't answering")
1562
+ return " · ".join(parts)
1563
+
1564
+ def _set_banner(self, alerts: List[str]) -> None:
1565
+ if alerts:
1566
+ self.banner_label.configure(text="\n".join(alerts))
1567
+ if not self._banner_shown:
1568
+ self.banner.pack(side="top", fill="x", pady=(self.s(10), 0), before=self._banner_anchor)
1569
+ self._banner_shown = True
1570
+ elif self._banner_shown:
1571
+ self.banner.pack_forget()
1572
+ self._banner_shown = False
1573
+
1574
+ _row_tag = staticmethod(row_tag)
1575
+
1576
+ def _update_table(self, views: List[HopView]) -> None:
1577
+ desired = {str(v.ttl) for v in views}
1578
+ for iid in self.tree.get_children():
1579
+ if iid not in desired:
1580
+ self.tree.delete(iid)
1581
+ last_ttl = views[-1].ttl if views else None
1582
+ where = self._locator(views=views)
1583
+ for v in views:
1584
+ iid = str(v.ttl)
1585
+ hostname = v.hostname if v.hostname else ("(resolving…)" if v.address and v.hostname is None else "")
1586
+ values = (v.ttl, v.address or "*", hostname,
1587
+ where.view(v).text,
1588
+ gui_hopinfo.network(v.address, self.geo), f"{v.loss_pct:.0f}%", v.sent,
1589
+ _ms(v.current), _ms(v.avg), _ms(v.best), _ms(v.worst), _ms(v.jitter))
1590
+ tag = row_tag(v, is_dest=(v.ttl == last_ttl))
1591
+ if self.tree.exists(iid):
1592
+ self.tree.item(iid, values=values, tags=(tag,))
1593
+ else:
1594
+ self.tree.insert("", "end", iid=iid, values=values, tags=(tag,))
1595
+ self._last_ttl = last_ttl
1596
+ if not self._pinned and last_ttl is not None:
1597
+ self._selected_ttl = last_ttl
1598
+ if self.tree.exists(str(last_ttl)):
1599
+ self.tree.selection_set(str(last_ttl))
1600
+
1601
+ def _update_events(self) -> None:
1602
+ new, last = self.monitor.events_after(self._last_event_seq)
1603
+ for e in new:
1604
+ ts = time.strftime("%H:%M:%S", time.localtime(e.t))
1605
+ tag = e.kind if e.kind in ("alert", "clear", "route", "warn") else "info"
1606
+ self.events_tree.insert("", "end", values=(ts, e.kind.title(), e.text), tags=(tag,))
1607
+ if new:
1608
+ # As many rows as the monitor keeps events. Unbounded, an ECMP hop
1609
+ # whose responder alternates each round added a route event per
1610
+ # round: about 35,000 rows a day, for a Treeview to carry.
1611
+ rows = self.events_tree.get_children()
1612
+ if len(rows) > MAX_EVENT_ROWS:
1613
+ self.events_tree.delete(*rows[:len(rows) - MAX_EVENT_ROWS])
1614
+ self.events_tree.yview_moveto(1.0)
1615
+ self._last_event_seq = last
1616
+
1617
+ # --- drawing (see gui_charts) ------------------------------------------------
1618
+ def _draw_active_view(self) -> None:
1619
+ if not self.targets_page.winfo_ismapped() and self.settings_page is not None:
1620
+ return
1621
+ view = self.detail_nav.current
1622
+ if view == "hops":
1623
+ self._draw_graph()
1624
+ elif view == "timeline":
1625
+ self._draw_timeline()
1626
+ elif view == "map":
1627
+ self._draw_map()
1628
+
1629
+ def _draw_graph(self) -> None:
1630
+ ttl = self._selected_ttl
1631
+ samples = self.monitor.samples_for(ttl) if ttl is not None else []
1632
+ draw_graph(self.canvas, self._ink(), ttl, samples)
1633
+
1634
+ def _draw_timeline(self) -> None:
1635
+ views, _s, _ip, _in = self.monitor.snapshot()
1636
+ caption = draw_timeline(self.timeline_canvas, self._ink(), views, self.monitor.all_samples())
1637
+ if caption:
1638
+ self.timeline_header.configure(text=caption)
1639
+
1640
+ def _draw_map(self) -> None:
1641
+ if self.detail_nav.current != "map":
1642
+ return
1643
+ if not self._geo_started: # lookups off: talk to ipwho.is only while
1644
+ self.geo.start() # the Map view is open
1645
+ self._geo_started = True
1646
+ views, _s, _ip, _in = self.monitor.snapshot()
1647
+ where = self._locator(views=views)
1648
+ caption = draw_map(self.map_canvas, self._ink(), views, self.geo,
1649
+ locator=where, past=self._past_route_points(where))
1650
+ if caption:
1651
+ self.map_header.configure(text=caption)
1652
+ self._fill_trouble(views, where)
1653
+
1654
+ def _fill_trouble(self, views, where: Optional[locating.Locator] = None) -> None:
1655
+ """Rank the places on the path: the delay each adds, and where loss
1656
+ that reaches the destination begins."""
1657
+ tree = self.trouble_tree
1658
+ tree.delete(*tree.get_children())
1659
+ where = where or self._locator(views=views)
1660
+ def place(v):
1661
+ w = where.view(v)
1662
+ return w.text, w.point
1663
+
1664
+ rows = trouble.rank(views, place)
1665
+ self.trouble_label.configure(
1666
+ text=trouble.verdict(rows, trouble.destination_silent(views))
1667
+ or "Where the trouble is shows once hops have answered "
1668
+ "and been placed.")
1669
+ for r in rows[:8]:
1670
+ hops = ", ".join(str(t) for t in r.ttls)
1671
+ tree.insert("", "end", values=(
1672
+ r.place, f"hop{'s' if len(r.ttls) > 1 else ''} {hops}",
1673
+ f"+{r.delay_added:.0f} ms" if r.delay_added >= 0.5 else "",
1674
+ f"{r.loss_starts:.0f}%" if r.loss_starts >= 0.5 else ""))
1675
+
1676
+ # --- earlier routes, for the map --------------------------------------------
1677
+ def _past_route_points(self, where: Optional[locating.Locator] = None) -> list:
1678
+ """The active target's other routes from the last day, as points to
1679
+ draw faded: located like the current route's routers (``where`` gives
1680
+ the anchors), at draw time, so a lookup that lands later moves them
1681
+ too. Loaded off the window's thread, at most once a minute."""
1682
+ name = self._active
1683
+ if not name or name in self._loaded:
1684
+ return []
1685
+ entry = self._past_routes.get(name)
1686
+ if (entry is None or time.monotonic() - entry[0] > 60) and name not in self._past_loading:
1687
+ self._past_loading.add(name)
1688
+ threading.Thread(target=self._load_past_routes, args=(name,), name="past-routes",
1689
+ daemon=True).start()
1690
+ found = (where or self._locator()).anchors
1691
+ out = []
1692
+ for route in (entry[1] if entry else []):
1693
+ pts = []
1694
+ loc = locating.Locator(self.geo, found, route)
1695
+ for ttl, addr, host, best in route:
1696
+ # Routers only an earlier route used were never in the hop
1697
+ # table, so nothing asked about them; the map needs them too.
1698
+ self.geo.request(addr)
1699
+ point = loc.where(addr, host, best, ttl).point
1700
+ if point is not None:
1701
+ pts.append(point)
1702
+ if len(pts) >= 2:
1703
+ out.append(pts)
1704
+ return out
1705
+
1706
+ def _load_past_routes(self, name: str) -> None:
1707
+ routes = []
1708
+ reader = history.Reader()
1709
+ try:
1710
+ now = time.time()
1711
+ rows = investigate.routes(reader, name, now - 86400, now, now=now)
1712
+ if len(rows) > 1:
1713
+ current = max(rows, key=lambda r: max(b for _a, b in r.spans))
1714
+ others = sorted((r for r in rows if r is not current),
1715
+ key=lambda r: -max(b for _a, b in r.spans))[:3]
1716
+ names = reader.names(a for r in others for hop in r.hops for a in hop)
1717
+ best = {r.addr: r.rtt_min for hop in investigate.hops(reader, name, now - 86400, now)
1718
+ for r in hop.routers}
1719
+ for r in others:
1720
+ routes.append([(ttl, hop[0], names.get(hop[0]), best.get(hop[0]))
1721
+ for ttl, hop in enumerate(r.hops, 1) if hop])
1722
+ except Exception:
1723
+ routes = [] # a locked or damaged history: no earlier routes, no fuss
1724
+ finally:
1725
+ reader.close()
1726
+
1727
+ def done():
1728
+ self._past_routes[name] = (time.monotonic(), routes)
1729
+ self._past_loading.discard(name)
1730
+ if routes:
1731
+ self._draw_ver = None
1732
+ self._post(done)
1733
+
1734
+
1735
+ def _enable_windows_dpi_awareness() -> None:
1736
+ """Kept for callers of the 1.3 name; see winplatform.enable_dpi_awareness."""
1737
+ winplatform.enable_dpi_awareness()
1738
+
1739
+
1740
+ def main() -> None:
1741
+ argv = sys.argv[1:]
1742
+ if "--finish-update" in argv:
1743
+ # The staged copy of a portable update: swap it into the program
1744
+ # folder, start it there, exit. No window, no settings of its own.
1745
+ i = argv.index("--finish-update")
1746
+ raise SystemExit(updater.finish_update(argv[i + 1], argv[i + 2]))
1747
+ if "--version" in argv:
1748
+ # Exits before Tk is touched, which makes this the one way to run the
1749
+ # windowed build without a display -- and therefore the way CI proves a
1750
+ # frozen binary's import graph is intact. gui imports geoip imports
1751
+ # urllib.request imports email, so a bad PyInstaller exclude fails here
1752
+ # rather than in a message box on a user's desktop. That is not
1753
+ # hypothetical: it is exactly how the first build of this was broken.
1754
+ print(f"PingerPlot {__version__}")
1755
+ return
1756
+ if "--self-test" in argv:
1757
+ # Before the single-instance check: a copy already running on the
1758
+ # machine mustn't stop a build being tested.
1759
+ from . import selfcheck
1760
+ winplatform.enable_dpi_awareness()
1761
+ raise SystemExit(selfcheck.run())
1762
+ winplatform.enable_dpi_awareness()
1763
+ winplatform.set_app_id()
1764
+ # One copy at a time: two would each restore and save the same target list
1765
+ # and probe every target twice. A second launch shows the first instead.
1766
+ restarted = winplatform.RESTARTED in argv
1767
+ # Restarted as administrator: the copy that started this one is closing,
1768
+ # so wait for its lock rather than show it and leave.
1769
+ instance = winplatform.wait_for_instance() if restarted else winplatform.SingleInstance()
1770
+ if instance.already_running and instance.signal_existing():
1771
+ return
1772
+ updated, failed = "--updated" in argv, "--update-failed" in argv
1773
+ if updated or failed:
1774
+ updater.cleanup_after_update(remove_old=updated)
1775
+ updater.ulog(f"update: {__version__} started" + (" after a failed update" if failed else ""))
1776
+ # The X11 window class, so a Linux desktop matches the window to its
1777
+ # menu entry (StartupWMClass) and its icon in the dock.
1778
+ root = tk.Tk(className=xdg.WM_CLASS)
1779
+ app = App(root, use_tray=True, start_minimized="--minimized" in argv,
1780
+ resume=updated or failed or restarted)
1781
+ if updated:
1782
+ app._note(f"Updated to {__version__}", seconds=30)
1783
+ if failed:
1784
+ root.after(800, lambda: messagebox.showerror(
1785
+ "PingerPlot", "The update couldn't be installed, so this version was started again. "
1786
+ f"Details are in {settings.config_dir() / updater.LOG_NAME}.", parent=root))
1787
+ root.mainloop()
1788
+ instance.release()
1789
+
1790
+
1791
+ if __name__ == "__main__":
1792
+ main()