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/theme.py ADDED
@@ -0,0 +1,576 @@
1
+ """The look: Windows 11-style light and dark themes for ttk, in any accent.
2
+
3
+ ttk's own themes look dated on Windows 11, and image themes bake one accent
4
+ colour into their PNGs. Here every rounded element is drawn at start-up by
5
+ gfx.py - in the current palette, at the screen's scale - and a theme change
6
+ redraws the same PhotoImages in place, which every element picks up without
7
+ being recreated.
8
+
9
+ ttk fills an image element's transparent pixels with the style's background,
10
+ so each style that sits on a card has a "Card." twin whose background is the
11
+ card's colour; the rounded corners then blend into whatever is behind them.
12
+
13
+ Adapted from UniFi Stock Watcher, a sibling project with the same conventions,
14
+ plus PingerPlot's own colour roles (graphs, hop rows, events, MOS): see
15
+ ``legacy_colours``.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import tkinter as tk
21
+ import tkinter.font as tkfont
22
+ from tkinter import ttk
23
+
24
+ from . import gfx, winplatform
25
+ from .gfx import Raster, contrast, mix, sd_circle, sd_polyline, sd_rrect
26
+
27
+ LIGHT = {
28
+ "bg": "#f3f3f3", "surface": "#ffffff", "surface2": "#f7f7f7",
29
+ "border": "#e3e3e3", "divider": "#e5e5e5",
30
+ "text": "#1b1b1b", "text2": "#5c5c5c", "text3": "#9b9b9b",
31
+ "control": "#fdfdfd", "control_hover": "#f6f6f6", "control_pressed": "#efefef",
32
+ "control_border": "#d6d6d6", "control_border_bottom": "#c2c2c2",
33
+ "strong_border": "#8a8a8a",
34
+ "field": "#ffffff", "field_border": "#d6d6d6", "field_bottom": "#8a8a8a",
35
+ "subtle_hover": "#ebebeb", "subtle_pressed": "#e1e1e1",
36
+ "green": "#0f7b0f", "green_bg": "#dff6dd",
37
+ "red": "#c42b1c", "red_bg": "#fde7e9",
38
+ "amber": "#8a5300", "amber_bg": "#fff4ce",
39
+ "neutral_bg": "#ececec",
40
+ "scroll": "#a0a0a0", "scroll_hover": "#808080",
41
+ "loss": "#d13438",
42
+ "default_accent": "#0067c0",
43
+ }
44
+
45
+ DARK = {
46
+ "bg": "#202020", "surface": "#2b2b2b", "surface2": "#323232",
47
+ "border": "#363636", "divider": "#3a3a3a",
48
+ "text": "#ffffff", "text2": "#bdbdbd", "text3": "#7c7c7c",
49
+ "control": "#2f2f2f", "control_hover": "#353535", "control_pressed": "#2a2a2a",
50
+ "control_border": "#3d3d3d", "control_border_bottom": "#353535",
51
+ "strong_border": "#9c9c9c",
52
+ "field": "#2d2d2d", "field_border": "#3d3d3d", "field_bottom": "#9c9c9c",
53
+ "subtle_hover": "#383838", "subtle_pressed": "#303030",
54
+ "green": "#6ccb5f", "green_bg": "#203a1f",
55
+ "red": "#ff99a4", "red_bg": "#442726",
56
+ "amber": "#f2c94c", "amber_bg": "#3d3218",
57
+ "neutral_bg": "#3a3a3a",
58
+ "scroll": "#8a8a8a", "scroll_hover": "#a8a8a8",
59
+ "loss": "#ff5a67",
60
+ "default_accent": "#4cc2ff",
61
+ }
62
+
63
+ THEMES = ("system", "dark", "light")
64
+
65
+ # Segoe Fluent Icons (Windows 11) and Segoe MDL2 Assets (Windows 10) share
66
+ # these code points; elsewhere the plain symbol stands in.
67
+ ICONS = {
68
+ "more": ("", "⋯"),
69
+ "add": ("", "+"),
70
+ "pause": ("", "‖"),
71
+ "play": ("", "▶"),
72
+ "stop": ("", "■"),
73
+ "delete": ("", "✕"),
74
+ "edit": ("", "✎"),
75
+ "close": ("\ue711", "✕"),
76
+ }
77
+
78
+
79
+ def resolve_dark(theme_setting: str) -> bool:
80
+ """dark/light as chosen; "system" follows Windows, and is dark where
81
+ there is no system setting to follow (PingerPlot's look before 1.4)."""
82
+ if theme_setting == "dark":
83
+ return True
84
+ if theme_setting == "light":
85
+ return False
86
+ pref = winplatform.system_prefers_dark()
87
+ return True if pref is None else pref
88
+
89
+
90
+ def _fit_accent(colour, dark, bg):
91
+ """Shade a chosen colour until it reads against the theme: dark enough
92
+ for white text in light mode, light enough against the dark background."""
93
+ c = colour
94
+ for _ in range(20):
95
+ if dark and contrast(c, bg) >= 4.0:
96
+ break
97
+ if not dark and contrast(c, "#ffffff") >= 4.5:
98
+ break
99
+ c = mix(c, "#ffffff" if dark else "#000000", 0.12)
100
+ return c
101
+
102
+
103
+ def build_palette(dark: bool, accent_setting: str = "") -> dict:
104
+ p = dict(DARK if dark else LIGHT)
105
+ if accent_setting:
106
+ accent = _fit_accent(accent_setting, dark, p["bg"])
107
+ else:
108
+ accent = winplatform.system_accent(dark) or p["default_accent"]
109
+ p["accent"] = accent
110
+ p["on_accent"] = "#000000" if contrast(accent, "#000000") > contrast(accent, "#ffffff") else "#ffffff"
111
+ toward = "#000000" if dark else "#ffffff"
112
+ p["accent_hover"] = mix(accent, toward, 0.10)
113
+ p["accent_pressed"] = mix(accent, toward, 0.22)
114
+ p["accent_disabled"] = mix(accent, p["bg"], 0.55)
115
+ p["accent_subtle"] = mix(accent, p["surface"], 0.72 if dark else 0.86)
116
+ p["accent_text"] = accent
117
+ p["dark"] = dark
118
+ return p
119
+
120
+
121
+ def legacy_colours(p: dict) -> dict:
122
+ """The palette under the keys PingerPlot's drawing code reads (graphs,
123
+ hop and event rows, the MOS label, the alert banner)."""
124
+ return {
125
+ "ok": p["surface"], "warn": p["amber_bg"], "bad": p["red_bg"], "dest": p["accent_subtle"],
126
+ "graph_bg": p["surface"], "graph_border": p["border"], "grid": p["divider"],
127
+ "line": p["accent"], "fill": mix(p["accent"], p["surface"], 0.78), "loss": p["loss"],
128
+ "axis_text": p["text3"], "title": p["text"],
129
+ "strip_sep": p["divider"], "strip_border": p["border"],
130
+ "banner_bg": p["red_bg"], "banner_fg": p["red"],
131
+ "fg_bad": p["red"], "fg_warn": p["amber"], "fg_dest": p["accent_text"], "fg_ok": p["text"],
132
+ "ev_alert": p["red_bg"], "ev_clear": p["green_bg"], "ev_route": p["accent_subtle"],
133
+ "ev_warn": p["amber_bg"],
134
+ "mos_good": p["green"], "mos_mid": p["amber"], "mos_bad": p["red"],
135
+ "win_bg": p["bg"], "panel": p["surface"], "field": p["field"], "fg": p["text"],
136
+ "sel_bg": p["accent_subtle"], "sel_fg": p["text"], "active": p["subtle_hover"],
137
+ "border": p["border"], "hint": p["text3"], "status_bg": p["bg"],
138
+ }
139
+
140
+
141
+ class Theme:
142
+ """Owns the palette, fonts, scale, generated images and ttk styles."""
143
+
144
+ def __init__(self, root, settings: dict) -> None:
145
+ self.root = root
146
+ self.scale = max(1.0, root.winfo_fpixels("1i") / 96.0)
147
+ self._images = {}
148
+ self._elements_made = False
149
+ families = set(tkfont.families(root))
150
+ self.family = next((f for f in ("Segoe UI Variable Text", "Segoe UI") if f in families),
151
+ tkfont.nametofont("TkDefaultFont").actual("family"))
152
+ self.semibold = next((f for f in ("Segoe UI Semibold",) if f in families), None)
153
+ self.mono = next((f for f in ("Cascadia Mono", "Consolas") if f in families),
154
+ tkfont.nametofont("TkFixedFont").actual("family"))
155
+ self.icon_family = next((f for f in ("Segoe Fluent Icons", "Segoe MDL2 Assets")
156
+ if f in families), None)
157
+ self.apply(settings)
158
+
159
+ # Helpers ------------------------------------------------------------------
160
+
161
+ def S(self, px: float) -> int:
162
+ """Logical pixels (at 100 %) to screen pixels."""
163
+ return int(round(px * self.scale))
164
+
165
+ def font(self, delta: int = 0, weight: str = "normal"):
166
+ size = max(8, self.size + delta)
167
+ if weight == "semibold":
168
+ return (self.semibold, size) if self.semibold else (self.family, size, "bold")
169
+ return (self.family, size, weight)
170
+
171
+ def mono_font(self, delta: int = 0):
172
+ return (self.mono, max(8, self.size + delta))
173
+
174
+ def icon_font(self, delta: int = 0):
175
+ return (self.icon_family, max(8, self.size + delta)) if self.icon_family else self.font(delta)
176
+
177
+ def icon(self, name: str) -> str:
178
+ glyph, fallback = ICONS[name]
179
+ return glyph if self.icon_family else fallback
180
+
181
+ # Theme --------------------------------------------------------------------
182
+
183
+ def apply(self, settings: dict) -> None:
184
+ self.size = int(settings.get("font_size", 10) or 10)
185
+ self.setting = settings.get("theme", "system")
186
+ self.dark = resolve_dark(self.setting)
187
+ self.c = build_palette(self.dark, settings.get("accent", "") or "")
188
+ self._render_images()
189
+ self._configure_styles()
190
+ winplatform.set_menu_theme(self.dark)
191
+
192
+ def style_window(self, win) -> None:
193
+ """Title bar and default colours for a Toplevel (or the root)."""
194
+ win.configure(bg=self.c["bg"])
195
+ winplatform.style_title_bar(win, self.dark, caption=self.c["bg"], text=self.c["text"])
196
+
197
+ # Images -------------------------------------------------------------------
198
+
199
+ def _put(self, name, raster, grow=None):
200
+ """Store ``raster`` as the PhotoImage ``name``, redrawing it in place if
201
+ it exists. grow=(border_x, border_y, middle) widens a 9-slice image's
202
+ middle to ``middle`` pixels (see gfx.expand9)."""
203
+ rgba, w, h = raster.rgba_bytes(), raster.w, raster.h
204
+ if grow:
205
+ bx, by, m = grow
206
+ rgba, w, h = gfx.expand9(rgba, w, h, bx, by, 2 * bx + m, 2 * by + m)
207
+ data = base64.b64encode(gfx.png_bytes(w, h, rgba)).decode("ascii")
208
+ img = self._images.get(name)
209
+ if img is None:
210
+ self._images[name] = tk.PhotoImage(master=self.root, data=data, format="png")
211
+ else:
212
+ img.configure(data=data, format="png")
213
+
214
+ def image(self, name):
215
+ return self._images[name]
216
+
217
+ def _rrect_img(self, w, h, r, fill, border=None, bottom=None, bw=None, alpha=1.0):
218
+ """A rounded rectangle, optionally with a 1px border and a different
219
+ bottom edge (Windows 11 controls are a shade darker along the bottom)."""
220
+ R = Raster(w, h)
221
+ bw = bw or max(1.0, round(self.scale))
222
+ if border:
223
+ R.draw(sd_rrect(0, 0, w, h, r), border, alpha)
224
+ if bottom:
225
+ R.draw(sd_rrect(0, 0, w, h, r), bottom, alpha, bbox=(0, h - bw - 1, w, h))
226
+ R.draw(sd_rrect(0, 0, w, h - bw, r), border, alpha, bbox=(0, h - bw - r - 2, w, h))
227
+ R.draw(sd_rrect(bw, bw, w - bw, h - bw, max(0.5, r - bw)), fill, alpha)
228
+ elif fill:
229
+ R.draw(sd_rrect(0, 0, w, h, r), fill, alpha)
230
+ return R
231
+
232
+ def _render_images(self):
233
+ c, S = self.c, self.S
234
+ r = S(4)
235
+ self._slice = {"ctl": r + 1, "card": S(8) + 1, "pill": S(10)}
236
+ n = 2 * self._slice["ctl"] + 2
237
+ g_ctl = (self._slice["ctl"], self._slice["ctl"], S(96))
238
+ g_card = (self._slice["card"], self._slice["card"], S(240))
239
+ g_pill = (self._slice["pill"], self._slice["pill"], S(64))
240
+
241
+ def ctl(fill, b=c["control_border"], bb=c["control_border_bottom"]):
242
+ return self._rrect_img(n, n, r, fill, b, bb)
243
+ self._put("btn", ctl(c["control"]), g_ctl)
244
+ self._put("btn_hover", ctl(c["control_hover"]), g_ctl)
245
+ self._put("btn_pressed", ctl(c["control_pressed"], c["control_border"], c["control_border"]), g_ctl)
246
+ self._put("btn_disabled", ctl(c["control"], c["divider"], c["divider"]), g_ctl)
247
+ for name, fill in (("acc", c["accent"]), ("acc_hover", c["accent_hover"]),
248
+ ("acc_pressed", c["accent_pressed"]), ("acc_disabled", c["accent_disabled"])):
249
+ self._put(name, self._rrect_img(n, n, r, fill), g_ctl)
250
+ self._put("subtle", Raster(n, n), g_ctl)
251
+ self._put("subtle_hover", self._rrect_img(n, n, r, c["subtle_hover"]), g_ctl)
252
+ self._put("subtle_pressed", self._rrect_img(n, n, r, c["subtle_pressed"]), g_ctl)
253
+
254
+ # Fields: the bottom edge is the strong line, accent and 2px on focus.
255
+ def field(bottom, thick=1.0, fill=c["field"]):
256
+ R = self._rrect_img(n, n, r, fill, c["field_border"])
257
+ t = max(1.0, round(self.scale * thick))
258
+ R.draw(sd_rrect(0, 0, n, n, r), bottom, bbox=(0, n - t, n, n))
259
+ return R
260
+ self._put("field", field(c["field_bottom"]), g_ctl)
261
+ self._put("field_hover", field(c["field_bottom"], fill=c["control_hover"]), g_ctl)
262
+ self._put("field_focus", field(c["accent"], 2.0), g_ctl)
263
+ self._put("field_disabled", self._rrect_img(n, n, r, c["control"], c["divider"]), g_ctl)
264
+
265
+ # Cards.
266
+ cr = S(8)
267
+ cn = 2 * self._slice["card"] + 2
268
+ self._put("card", self._rrect_img(cn, cn, cr, c["surface"], c["border"]), g_card)
269
+ self._put("card_sel", self._rrect_img(cn, cn, cr, c["surface"], c["accent"],
270
+ bw=max(1.0, round(self.scale * 1.5))), g_card)
271
+ self._put("card_alert", self._rrect_img(cn, cn, cr, c["surface"], c["red"],
272
+ bw=max(1.0, round(self.scale * 1.5))), g_card)
273
+ self._put("banner", self._rrect_img(cn, cn, cr, c["red_bg"], mix(c["red"], c["surface"], 0.5)),
274
+ g_card)
275
+
276
+ # Status pills.
277
+ pr = S(10)
278
+ pn = 2 * self._slice["pill"] + 2
279
+ for name, fill in (("green", c["green_bg"]), ("red", c["red_bg"]),
280
+ ("amber", c["amber_bg"]), ("neutral", c["neutral_bg"])):
281
+ self._put(f"pill_{name}", self._rrect_img(pn, pn, pr, fill), g_pill)
282
+
283
+ # Check boxes.
284
+ cb, cbr = S(18), S(4)
285
+ tick = [(cb * 0.27, cb * 0.52), (cb * 0.44, cb * 0.68), (cb * 0.74, cb * 0.34)]
286
+ stroke = max(1.4, self.scale * 1.35)
287
+
288
+ def checkbox(on, hover=False, disabled=False):
289
+ if disabled:
290
+ R = self._rrect_img(cb, cb, cbr, c["neutral_bg"], c["divider"])
291
+ if on:
292
+ R.draw(sd_polyline(tick, stroke), c["text3"])
293
+ return R
294
+ if on:
295
+ R = self._rrect_img(cb, cb, cbr, c["accent_hover"] if hover else c["accent"])
296
+ R.draw(sd_polyline(tick, stroke), c["on_accent"])
297
+ return R
298
+ return self._rrect_img(cb, cb, cbr, c["subtle_hover"] if hover else c["field"],
299
+ c["strong_border"])
300
+ self._put("check_off", checkbox(False))
301
+ self._put("check_off_hover", checkbox(False, True))
302
+ self._put("check_on", checkbox(True))
303
+ self._put("check_on_hover", checkbox(True, True))
304
+ self._put("check_disabled", checkbox(False, disabled=True))
305
+ self._put("check_on_disabled", checkbox(True, disabled=True))
306
+
307
+ # Switches.
308
+ sw, sh = S(40), S(20)
309
+
310
+ def switch(on, hover=False):
311
+ R = Raster(sw, sh)
312
+ rad = sh / 2
313
+ knob = rad - S(4) + (S(1) if hover else 0)
314
+ if on:
315
+ R.draw(sd_rrect(0, 0, sw, sh, rad), c["accent_hover"] if hover else c["accent"])
316
+ R.draw(sd_circle(sw - rad, rad, knob), c["on_accent"])
317
+ else:
318
+ bw = max(1.0, round(self.scale))
319
+ R.draw(sd_rrect(0, 0, sw, sh, rad), c["strong_border"])
320
+ R.draw(sd_rrect(bw, bw, sw - bw, sh - bw, rad - bw),
321
+ c["subtle_hover"] if hover else c["field"])
322
+ R.draw(sd_circle(rad, rad, knob), c["text2"])
323
+ return R
324
+ self._put("switch_off", switch(False))
325
+ self._put("switch_off_hover", switch(False, True))
326
+ self._put("switch_on", switch(True))
327
+ self._put("switch_on_hover", switch(True, True))
328
+
329
+ # Combobox and spinbox chevrons.
330
+ aw = S(24)
331
+
332
+ def chevron(col):
333
+ R = Raster(aw, aw)
334
+ m = aw / 2
335
+ R.draw(sd_polyline([(m - S(4), m - S(2)), (m, m + S(2)), (m + S(4), m - S(2))],
336
+ max(1.2, self.scale)), col)
337
+ return R
338
+ self._put("chevron", chevron(c["text2"]))
339
+ self._put("chevron_disabled", chevron(c["text3"]))
340
+
341
+ # Scrollbar thumb: a thin pill.
342
+ tw, th = S(12), S(28)
343
+
344
+ def thumb(col, wide):
345
+ return Raster(tw, th).draw(
346
+ sd_rrect(tw / 2 - wide / 2, S(2), tw / 2 + wide / 2, th - S(2), wide / 2), col)
347
+ self._put("thumb", thumb(c["scroll"], S(4)), (tw // 2, S(8), S(160)))
348
+ self._put("thumb_hover", thumb(c["scroll_hover"], S(6)), (tw // 2, S(8), S(160)))
349
+ self._put("hthumb", Raster(th, tw).draw(
350
+ sd_rrect(S(2), tw / 2 - S(2), th - S(2), tw / 2 + S(2), S(2)), c["scroll"]))
351
+
352
+ # Styles -------------------------------------------------------------------
353
+
354
+ def _make_elements(self):
355
+ st, I, S = self.style, self.image, self.S
356
+ # Sliced images are drawn large (see _put's grow), so each says how
357
+ # small it may be: an image element otherwise asks for its image's
358
+ # whole size, and every button would be 150 px tall.
359
+ b = self._slice["ctl"]
360
+ small = dict(border=b, sticky="nsew", width=2 * b, height=2 * b)
361
+ st.element_create("Pp.btn", "image", I("btn"),
362
+ ("disabled", I("btn_disabled")), ("pressed", I("btn_pressed")),
363
+ ("active", I("btn_hover")), **small)
364
+ st.element_create("Pp.acc", "image", I("acc"),
365
+ ("disabled", I("acc_disabled")), ("pressed", I("acc_pressed")),
366
+ ("active", I("acc_hover")), **small)
367
+ st.element_create("Pp.subtle", "image", I("subtle"),
368
+ ("pressed", I("subtle_pressed")), ("active", I("subtle_hover")), **small)
369
+ st.element_create("Pp.field", "image", I("field"),
370
+ ("disabled", I("field_disabled")), ("focus", I("field_focus")),
371
+ ("hover", I("field_hover")), **small)
372
+ cb = self._slice["card"]
373
+ card = dict(border=cb, sticky="nsew", width=2 * cb, height=2 * cb)
374
+ st.element_create("Pp.card", "image", I("card"), **card)
375
+ st.element_create("Pp.cardsel", "image", I("card_sel"), **card)
376
+ st.element_create("Pp.cardalert", "image", I("card_alert"), **card)
377
+ st.element_create("Pp.banner", "image", I("banner"), **card)
378
+ pb = self._slice["pill"]
379
+ for name in ("green", "red", "amber", "neutral"):
380
+ st.element_create(f"Pp.pill.{name}", "image", I(f"pill_{name}"),
381
+ border=pb, sticky="nsew", width=2 * pb, height=2 * pb)
382
+ st.element_create("Pp.check", "image", I("check_off"),
383
+ ("disabled selected", I("check_on_disabled")),
384
+ ("disabled", I("check_disabled")),
385
+ ("selected active", I("check_on_hover")),
386
+ ("selected", I("check_on")),
387
+ ("active", I("check_off_hover")), sticky="")
388
+ st.element_create("Pp.switch", "image", I("switch_off"),
389
+ ("selected active", I("switch_on_hover")),
390
+ ("selected", I("switch_on")),
391
+ ("active", I("switch_off_hover")), sticky="")
392
+ st.element_create("Pp.chevron", "image", I("chevron"),
393
+ ("disabled", I("chevron_disabled")), sticky="")
394
+ st.element_create("Pp.thumb", "image", I("thumb"), ("active", I("thumb_hover")),
395
+ ("pressed", I("thumb_hover")), border=(S(6), S(8)), sticky="nsew",
396
+ width=S(12), height=2 * S(8))
397
+ st.element_create("Pp.hthumb", "image", I("hthumb"), border=(S(8), S(6)), sticky="nsew")
398
+
399
+ def button(el):
400
+ return [(el, {"sticky": "nsew", "children": [
401
+ ("Button.padding", {"sticky": "nsew", "children": [
402
+ ("Button.label", {"sticky": "nsew"})]})]})]
403
+ st.layout("TButton", button("Pp.btn"))
404
+ st.layout("Accent.TButton", button("Pp.acc"))
405
+ st.layout("Subtle.TButton", button("Pp.subtle"))
406
+ st.layout("TEntry", [("Pp.field", {"sticky": "nsew", "children": [
407
+ ("Entry.padding", {"sticky": "nsew", "children": [
408
+ ("Entry.textarea", {"sticky": "nsew"})]})]})])
409
+ st.layout("TCombobox", [("Pp.field", {"sticky": "nsew", "children": [
410
+ ("Pp.chevron", {"side": "right", "sticky": "ns"}),
411
+ ("Combobox.padding", {"expand": "1", "sticky": "nsew", "children": [
412
+ ("Combobox.textarea", {"sticky": "nsew"})]})]})])
413
+ st.layout("TSpinbox", [("Pp.field", {"sticky": "nsew", "children": [
414
+ ("null", {"side": "right", "sticky": "ns", "children": [
415
+ ("Spinbox.uparrow", {"side": "top", "sticky": "e"}),
416
+ ("Spinbox.downarrow", {"side": "bottom", "sticky": "e"})]}),
417
+ ("Spinbox.padding", {"sticky": "nsew", "children": [
418
+ ("Spinbox.textarea", {"sticky": "nsew"})]})]})])
419
+ st.layout("Tile.TFrame", [("Pp.card", {"sticky": "nsew"})])
420
+ st.layout("Selected.Tile.TFrame", [("Pp.cardsel", {"sticky": "nsew"})])
421
+ st.layout("Alert.Tile.TFrame", [("Pp.cardalert", {"sticky": "nsew"})])
422
+ st.layout("Banner.TFrame", [("Pp.banner", {"sticky": "nsew"})])
423
+ for name in ("green", "red", "amber", "neutral"):
424
+ st.layout(f"{name.title()}.Pill.TLabel", [(f"Pp.pill.{name}", {"sticky": "nsew", "children": [
425
+ ("Label.padding", {"sticky": "nsew", "children": [
426
+ ("Label.label", {"sticky": "nsew"})]})]})])
427
+
428
+ def check(el):
429
+ return [("Checkbutton.padding", {"sticky": "nsew", "children": [
430
+ (el, {"side": "left", "sticky": ""}),
431
+ ("Checkbutton.label", {"side": "left", "sticky": "nsew"})]})]
432
+ st.layout("TCheckbutton", check("Pp.check"))
433
+ st.layout("Switch.TCheckbutton", check("Pp.switch"))
434
+ st.layout("Vertical.TScrollbar", [("Vertical.Scrollbar.trough", {"sticky": "ns", "children": [
435
+ ("Pp.thumb", {"expand": "1", "sticky": "nswe"})]})])
436
+ st.layout("Horizontal.TScrollbar", [("Horizontal.Scrollbar.trough", {"sticky": "ew", "children": [
437
+ ("Pp.hthumb", {"expand": "1", "sticky": "nswe"})]})])
438
+ st.layout("Treeview", [("Treeview.treearea", {"sticky": "nsew"})])
439
+ self._elements_made = True
440
+
441
+ def _configure_styles(self):
442
+ c, S = self.c, self.S
443
+ if not self._elements_made:
444
+ self.style = ttk.Style(self.root)
445
+ self.style.theme_use("clam")
446
+ self._make_elements()
447
+ st = self.style
448
+ body, small, caption = self.font(), self.font(-1), self.font(-2)
449
+
450
+ st.configure(".", background=c["bg"], foreground=c["text"], font=body,
451
+ bordercolor=c["divider"], darkcolor=c["bg"], lightcolor=c["bg"],
452
+ troughcolor=c["bg"], focuscolor=c["accent"],
453
+ selectbackground=c["accent"], selectforeground=c["on_accent"],
454
+ insertcolor=c["text"], fieldbackground=c["field"],
455
+ insertwidth=max(1, S(1)))
456
+ st.map(".", foreground=[("disabled", c["text3"])])
457
+
458
+ for prefix, surface in (("", c["bg"]), ("Card.", c["surface"])):
459
+ st.configure(f"{prefix}TFrame", background=surface)
460
+ st.configure(f"{prefix}TLabel", background=surface, foreground=c["text"])
461
+ st.configure(f"{prefix}Muted.TLabel", background=surface, foreground=c["text2"], font=small)
462
+ st.configure(f"{prefix}Faint.TLabel", background=surface, foreground=c["text3"], font=caption)
463
+ st.configure(f"{prefix}Strong.TLabel", background=surface, foreground=c["text"],
464
+ font=self.font(0, "semibold"))
465
+ st.configure(f"{prefix}Heading.TLabel", background=surface, foreground=c["text"],
466
+ font=self.font(1, "semibold"))
467
+ st.configure(f"{prefix}Caps.TLabel", background=surface, foreground=c["text2"],
468
+ font=self.font(-2, "semibold"))
469
+ st.configure(f"{prefix}Link.TLabel", background=surface, foreground=c["accent_text"],
470
+ font=small)
471
+ st.configure(f"{prefix}Amber.TLabel", background=surface, foreground=c["amber"], font=small)
472
+ st.configure(f"{prefix}Green.TLabel", background=surface, foreground=c["green"], font=small)
473
+ st.configure(f"{prefix}Red.TLabel", background=surface, foreground=c["red"], font=small)
474
+ st.configure(f"{prefix}Dot.TLabel", background=surface, font=self.font(2))
475
+ pad = (S(12), S(5))
476
+ st.configure(f"{prefix}TButton", background=surface, foreground=c["text"],
477
+ padding=pad, anchor="center", font=body)
478
+ st.configure(f"{prefix}Accent.TButton", background=surface, foreground=c["on_accent"],
479
+ padding=pad, anchor="center", font=body)
480
+ st.map(f"{prefix}Accent.TButton",
481
+ foreground=[("disabled", mix(c["on_accent"], c["accent"], 0.4))])
482
+ # clam gives every TButton a minimum width of 11 characters; an
483
+ # icon button is one glyph wide.
484
+ st.configure(f"{prefix}Subtle.TButton", background=surface, foreground=c["text"],
485
+ padding=(S(8), S(5)), anchor="center", font=body, width=0)
486
+ st.configure(f"{prefix}Icon.Subtle.TButton", background=surface, foreground=c["text2"],
487
+ padding=(S(6), S(5)), font=self.icon_font(0))
488
+ st.configure(f"{prefix}TCheckbutton", background=surface, foreground=c["text"],
489
+ padding=(0, S(2)), font=body)
490
+ st.map(f"{prefix}TCheckbutton", background=[("active", surface)])
491
+ st.configure(f"{prefix}Switch.TCheckbutton", background=surface, foreground=c["text"],
492
+ padding=(0, S(2)), font=body)
493
+ st.map(f"{prefix}Switch.TCheckbutton", background=[("active", surface)])
494
+ st.configure(f"{prefix}TEntry", background=surface, foreground=c["text"],
495
+ padding=(S(10), S(6)), font=body)
496
+ st.configure(f"{prefix}TSpinbox", background=surface, foreground=c["text"],
497
+ padding=(S(10), S(5), S(4), S(5)), arrowsize=S(10), font=body)
498
+ st.configure(f"{prefix}TCombobox", background=surface, foreground=c["text"],
499
+ padding=(S(10), S(5), 0, S(5)), arrowsize=S(12), font=body)
500
+ st.map(f"{prefix}TCombobox",
501
+ fieldbackground=[("readonly", c["field"])],
502
+ foreground=[("disabled", c["text3"]), ("readonly", c["text"])],
503
+ selectbackground=[("readonly", c["field"])],
504
+ selectforeground=[("readonly", c["text"])])
505
+ st.configure(f"{prefix}Vertical.TScrollbar", troughcolor=surface, background=surface,
506
+ bordercolor=surface, arrowsize=S(12))
507
+ st.configure(f"{prefix}Horizontal.TScrollbar", troughcolor=surface, background=surface,
508
+ bordercolor=surface)
509
+
510
+ for name, fg in (("Green", c["green"]), ("Red", c["red"]),
511
+ ("Amber", c["amber"]), ("Neutral", c["text2"])):
512
+ st.configure(f"{name}.Pill.TLabel", background=c["surface"], foreground=fg,
513
+ font=self.font(-2, "semibold"), padding=(S(9), S(2)), anchor="center")
514
+
515
+ for tile in ("Tile.TFrame", "Selected.Tile.TFrame", "Alert.Tile.TFrame", "Banner.TFrame"):
516
+ st.configure(tile, background=c["bg"])
517
+ st.configure("Banner.TLabel", background=c["red_bg"], foreground=c["red"],
518
+ font=self.font(0, "semibold"))
519
+
520
+ st.configure("Title.TLabel", background=c["bg"], foreground=c["text"],
521
+ font=self.font(3, "semibold"))
522
+ st.configure("Nav.TLabel", background=c["bg"], foreground=c["text2"],
523
+ font=body, padding=(S(2), S(6)))
524
+ st.configure("NavActive.TLabel", background=c["bg"], foreground=c["text"],
525
+ font=self.font(0, "semibold"), padding=(S(2), S(6)))
526
+ st.configure("NavBar.TFrame", background=c["accent"])
527
+ st.configure("Divider.TFrame", background=c["divider"])
528
+
529
+ st.configure("Treeview", background=c["surface"], fieldbackground=c["surface"],
530
+ foreground=c["text"], rowheight=S(28), borderwidth=0, font=body)
531
+ st.map("Treeview",
532
+ background=[("selected", c["accent_subtle"])],
533
+ foreground=[("selected", c["text"])])
534
+ st.configure("Treeview.Heading", background=c["surface"], foreground=c["text2"],
535
+ relief="flat", borderwidth=0, font=self.font(-1, "semibold"),
536
+ padding=(S(8), S(6)))
537
+ st.map("Treeview.Heading", background=[("active", c["surface2"])],
538
+ relief=[("pressed", "flat")])
539
+
540
+ # Classic ttk.Notebook, restyled as underlined tabs on the window's
541
+ # background (the house style's navigation).
542
+ st.configure("TNotebook", background=c["bg"], borderwidth=0, tabmargins=(0, 0, 0, 0))
543
+ st.configure("TNotebook.Tab", background=c["bg"], foreground=c["text2"], borderwidth=0,
544
+ padding=(S(12), S(6)), font=body, focuscolor=c["bg"])
545
+ st.map("TNotebook.Tab",
546
+ background=[("selected", c["bg"]), ("active", c["bg"])],
547
+ foreground=[("selected", c["text"]), ("active", c["text"])],
548
+ font=[("selected", self.font(0, "semibold"))],
549
+ lightcolor=[("selected", c["accent"])], bordercolor=[("selected", c["accent"])])
550
+
551
+ st.configure("Horizontal.TProgressbar", troughcolor=c["neutral_bg"], background=c["accent"],
552
+ bordercolor=c["neutral_bg"], lightcolor=c["accent"], darkcolor=c["accent"],
553
+ thickness=S(3))
554
+ st.configure("TPanedwindow", background=c["bg"])
555
+ st.configure("Sash", sashthickness=S(6), gripcount=0, background=c["bg"])
556
+ st.configure("TSeparator", background=c["divider"])
557
+ st.configure("TLabelframe", background=c["bg"], bordercolor=c["divider"])
558
+ st.configure("TLabelframe.Label", background=c["bg"], foreground=c["text2"],
559
+ font=self.font(-1, "semibold"))
560
+
561
+ # The combobox's drop-down list is a classic Tk listbox.
562
+ r = self.root
563
+ r.option_add("*TCombobox*Listbox.background", c["surface"])
564
+ r.option_add("*TCombobox*Listbox.foreground", c["text"])
565
+ r.option_add("*TCombobox*Listbox.selectBackground", c["accent_subtle"])
566
+ r.option_add("*TCombobox*Listbox.selectForeground", c["text"])
567
+ r.option_add("*TCombobox*Listbox.font", body)
568
+ r.option_add("*TCombobox*Listbox.borderWidth", 0)
569
+ r.option_add("*TCombobox*Listbox.relief", "flat")
570
+ r.option_add("*Menu.font", body)
571
+
572
+ def menu_colours(self) -> dict:
573
+ c = self.c
574
+ return dict(bg=c["surface"], fg=c["text"], activebackground=c["accent_subtle"],
575
+ activeforeground=c["text"], disabledforeground=c["text3"],
576
+ relief="flat", bd=0, font=self.font())
@@ -0,0 +1,68 @@
1
+ """Tk objects must be finalised on the main thread.
2
+
3
+ tkinter's Variable and Image have finalisers (``__del__``) that call into Tcl
4
+ to unset the variable or delete the image. Python's cyclic garbage collector
5
+ runs in whichever thread happens to allocate when a generation fills up --
6
+ here, as often as not, a probe or DNS worker. A Tcl call from a thread other
7
+ than Tk's waits for the main loop to take it, for about a second, and then
8
+ fails with "main thread is not in main loop".
9
+
10
+ Most of the window's Tk objects sit in reference cycles (a widget and its
11
+ parent refer to each other), so whenever any of them becomes garbage -- a
12
+ closed Edit dialog's form variables, the theme's images in a test -- the
13
+ collector decides which thread finalises them. Measured: one torn-down window
14
+ collected on a worker thread took 68 s, a second per image and variable; a
15
+ closed dialog's twenty variables would stall a probe round for twenty seconds.
16
+
17
+ ``install()`` wraps both finalisers: off the main thread, the object is kept
18
+ on a queue instead (resurrecting it is allowed, and Python still runs its
19
+ original finaliser exactly once: here, when ``drain()`` does). The window's
20
+ refresh timer drains the queue on the main thread.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import queue
25
+ import threading
26
+ import tkinter as tk
27
+
28
+ _pending: "queue.SimpleQueue" = queue.SimpleQueue()
29
+ _installed = False
30
+
31
+
32
+ def install() -> None:
33
+ """Idempotent; call before the first Tk object is made."""
34
+ global _installed
35
+ if _installed:
36
+ return
37
+ _installed = True
38
+ main = threading.main_thread()
39
+ for cls in (tk.Variable, tk.Image):
40
+ original = cls.__dict__.get("__del__")
41
+ if original is None:
42
+ continue
43
+
44
+ def __del__(self, _original=original):
45
+ if threading.current_thread() is main:
46
+ _original(self)
47
+ else:
48
+ _pending.put((_original, self))
49
+ cls.__del__ = __del__
50
+
51
+
52
+ def drain() -> int:
53
+ """Run the finalisers queued by other threads. Main thread only."""
54
+ n = 0
55
+ while True:
56
+ try:
57
+ fn, obj = _pending.get_nowait()
58
+ except queue.Empty:
59
+ return n
60
+ try:
61
+ fn(obj)
62
+ except (tk.TclError, RuntimeError):
63
+ pass # its interpreter is gone already: nothing left to undo
64
+ n += 1
65
+
66
+
67
+ def pending() -> int:
68
+ return _pending.qsize()