File size: 40,036 Bytes
bad179a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | """Theme, hand-drawn widgets (gauges, time charts, bars, tiles, core grid, weekly heatmap, table)
and small builders for labels, buttons, panels, forms and dialogs."""
import functools, math, time, tkinter as tk
from bisect import bisect_left, bisect_right
from collections import namedtuple
from tkinter import font as tkfont, ttk
from types import SimpleNamespace
from metrics import num
from model import fmt_bytes
C = SimpleNamespace( # palette
bg='#0d111c', side='#10151f', panel='#161c2b', card='#1a2133', hover='#20293f', border='#27314a', line='#232c41', grid='#242d42',
field='#111727', select='#17304a', text='#e6ebf5', muted='#8b95ab', faint='#5a657d', accent='#38bdf8', green='#22c55e', amber='#f59e0b',
red='#ef4444', violet='#a78bfa', pink='#f472b6', teal='#2dd4bf', orange='#fb923c', blue='#60a5fa')
def level(p, warn=70, crit=90): return C.red if p >= crit else C.amber if p >= warn else C.green
def severity(s): return {'critical': C.red, 'warning': C.amber, 'resolved': C.green, 'action': C.violet}.get(s, C.accent)
def health(h): return C.green if h >= 90 else C.teal if h >= 75 else C.amber if h >= 60 else C.orange if h >= 40 else C.red
def mix(a, b, t):
"""Colour between a and b (t = 0..1). A Tk canvas has no transparency, so tints are mixed with the background."""
t = min(max(t, 0), 1)
return '#%02x%02x%02x' % tuple(round(int(a[i:i + 2], 16) * (1 - t) + int(b[i:i + 2], 16) * t) for i in (1, 3, 5))
@functools.lru_cache(None)
def F(px, bold=False, mono=False):
"""Font by pixel size."""
family = tkfont.nametofont('TkFixedFont' if mono else 'TkDefaultFont').actual('family')
return tkfont.Font(family=family, size=-px, weight='bold' if bold else 'normal')
def elide(s, font, width):
"""Text shortened to fit the width."""
if font.measure(s) <= width: return s
s = s[:int(len(s) * width / font.measure(s)) + 2]
while s and font.measure(s + '…') > width: s = s[:-1]
return s + '…'
def pct0(v): return f'{v:.0f}%'
def decimals(prec): return lambda v: f'{v:.{prec}f}'
def theme(root):
"""Dark colours for the classic and the ttk widgets."""
root.configure(bg=C.bg)
for k, v in {'*font': F(13), '*background': C.bg, '*foreground': C.text, '*selectBackground': '#0e7ab8', '*selectForeground': C.text,
'*Menu.background': C.panel, '*Menu.activeBackground': C.select, '*Menu.activeForeground': C.text, '*Menu.borderWidth': 1,
'*Menu.activeBorderWidth': 0, '*Menu.relief': 'flat', '*TCombobox*Listbox.background': C.panel, '*TCombobox*Listbox.font': F(13),
'*TCombobox*Listbox.selectBackground': C.select}.items():
root.option_add(k, v)
s, edge = ttk.Style(root), '#2a3449'
s.theme_use('clam')
s.configure('.', font=F(13), background=C.bg, foreground=C.text)
s.configure('TCombobox', fieldbackground=C.field, background=C.card, foreground=C.text, arrowcolor=C.muted, bordercolor=edge,
lightcolor=C.field, darkcolor=C.field, padding=5)
s.map('TCombobox', fieldbackground=[('readonly', C.field)], selectbackground=[('readonly', C.field)], selectforeground=[('readonly', C.text)],
bordercolor=[('focus', C.accent)], background=[('active', C.hover)])
s.layout('Vertical.TScrollbar', [('Vertical.Scrollbar.trough', {'sticky': 'ns', 'children': [('Vertical.Scrollbar.thumb', {'expand': '1', 'sticky': 'nswe'})]})])
trough = mix(C.bg, C.panel, .5)
s.configure('TScrollbar', troughcolor=trough, bordercolor=trough, gripcount=0, width=9)
for part in ('background', 'lightcolor', 'darkcolor'): # the thumb; invisible while there is nothing to scroll
s.map('TScrollbar', **{part: [('disabled', trough), ('active', '#3b4866'), ('', edge)]})
# ---- hand-drawn widgets ---------------------------------------------------------------------
class Paint(tk.Canvas):
"""Canvas that repaints itself in draw() after a resize or a redraw() call."""
def __init__(self, parent, width, height, bg=None, **kw):
super().__init__(parent, width=width, height=height, bg=bg or parent['bg'], highlightthickness=0, bd=0, **kw)
self.bind('<Configure>', lambda e: self.redraw())
def redraw(self):
self.w, self.h = self.winfo_width(), self.winfo_height()
if self.w > 1:
self.delete('all')
self.draw()
def need_height(self, h): # for widgets whose height follows their content
if h != self.winfo_reqheight(): self.config(height=h)
def rrect(self, x0, y0, x1, y1, r, fill='', outline='', **kw):
"""Rounded rectangle."""
r = max(0, min(r, (x1 - x0) / 2, (y1 - y0) / 2))
p = (x0 + r, y0, x0 + r, y0, x1 - r, y0, x1 - r, y0, x1, y0, x1, y0 + r, x1, y0 + r, x1, y1 - r, x1, y1 - r, x1, y1,
x1 - r, y1, x1 - r, y1, x0 + r, y1, x0 + r, y1, x0, y1, x0, y1 - r, x0, y1 - r, x0, y0 + r, x0, y0 + r, x0, y0)
return self.create_polygon(p, smooth=True, fill=fill, outline=outline, **kw)
def text(self, x, y, s, fill=C.text, px=13, bold=False, anchor='w', **kw):
return self.create_text(x, y, text=s, fill=fill, font=F(px, bold), anchor=anchor, **kw)
def ring(self, x, y, size, pct, color, thick, glow=True):
"""270-degree gauge arc with round ends inside the square at (x, y)."""
r, cx, cy = (size - thick) / 2, x + size / 2, y + size / 2
def arc(extent, c, width):
self.create_arc(cx - r, cy - r, cx + r, cy + r, start=225, extent=-extent, style='arc', outline=c, width=width)
for angle in (225, 225 - extent):
ex, ey = cx + r * math.cos(math.radians(angle)), cy - r * math.sin(math.radians(angle))
self.create_oval(ex - width / 2, ey - width / 2, ex + width / 2, ey + width / 2, fill=c, width=0)
arc(270, C.grid, thick)
extent = 270 * min(max(pct, 0), 100) / 100
if extent > 0.2:
if glow: arc(extent, mix(self['bg'], color, .2), thick * 2)
arc(extent, color, thick)
class Gauge(Paint):
"""Ring gauge with a centre value, a sub text and a title; glides to new values."""
def __init__(self, parent, title, crit=90):
super().__init__(parent, 150, 190)
self.title, self.crit, self.target, self.shown, self.center, self.sub, self.color, self.gliding = title, crit, 0, 0, '', '', None, False
def set(self, pct, center='', sub='', color=None):
self.center, self.sub, self.color = center, sub, color
pct = 0 if pct != pct else pct
if abs(pct - self.target) > 0.05:
self.target, self.start, self.t0 = pct, self.shown, time.monotonic()
if not self.gliding: self.glide()
self.redraw()
def glide(self):
k = min(1, (time.monotonic() - self.t0) / .45)
self.shown = self.start + (self.target - self.start) * (1 - (1 - k) ** 3)
self.gliding = k < 1
self.redraw()
if self.gliding: self.after(30, self.glide)
def draw(self):
s = min(self.w - 8, self.h - 28)
x, mid = (self.w - s) / 2, self.w / 2
self.ring(x, 4, s, self.shown, self.color or level(self.target, 70, self.crit), max(7, s * .085))
self.text(mid, 4 + s * .43, self.center or f'{self.shown:.0f}%', px=int(s * .2), bold=True, anchor='center')
sub = F(max(10, int(s * .075)))
self.create_text(mid, 4 + s * .63, text=elide(self.sub, sub, s * .76), fill=C.muted, font=sub)
self.text(mid, s + 15, self.title, bold=True, anchor='center')
class Chart(Paint):
"""Time chart: grid, legend with the latest values, stacked or overlaid areas, gaps where data is missing, hover read-out."""
def __init__(self, parent, title, fmt=pct0, ymax=0, height=230, stacked=False, empty='Waiting for data…'): # ymax 0 = auto
super().__init__(parent, 260, height)
self.title, self.fmt, self.ymax, self.stacked, self.empty, self.subtitle = title, fmt, ymax, stacked, empty, ''
self.t, self.series, self.span, self.hover, self.geo = [], [], 0, -1, None
self.bind('<Motion>', lambda e: self.point(e.x))
self.bind('<Leave>', lambda e: self.point(-1))
def set(self, t, series, span=0):
"""t: times in ms; series: (name, colour, values[, fill[, dashed]]); span: visible ms before the last time, 0 = all."""
n = len(t)
self.t, self.span = list(t), span
self.series = [(s[0], s[1], (list(s[2]) + [math.nan] * n)[:n], *s[3:], *(True, False)[len(s) - 3:]) for s in series]
self.redraw()
def draw(self):
w, h, fmt, t, self.geo = self.w, self.h, self.fmt, self.t, None
self.rrect(.5, .5, w - 1, h - 1, 12, C.panel, C.border)
self.text(16, 20, self.title, bold=True)
title_w = F(13, True).measure(self.title)
lx = w - 16
for name, color, v, *_ in reversed(self.series): # legend with the latest values, right-aligned
last = next((x for x in v[:-6:-1] if x == x), None)
label = name if last is None else f'{name} {fmt(last)}'
lx -= F(11).measure(label)
if lx < 40 + title_w: break
self.text(lx, 20, label, C.muted, 11)
self.rrect(lx - 14, 16, lx - 5, 25, 2, color)
lx -= 28
if 24 + title_w + F(11).measure(self.subtitle) < lx: self.text(24 + title_w, 20, self.subtitle, C.muted, 11) # where the legend leaves room
n = len(t)
first = bisect_left(t, t[-1] - self.span) if n and self.span else 0
left, top, right, bottom = 56, 40, w - 16, h - 30
if n - first < 2 or bottom - top < 20: return self.text((left + right) / 2, (top + bottom) / 2, self.empty, C.faint, anchor='center')
ymax = self.ymax
if ymax <= 0:
clean = [[x if x == x else 0 for x in v[first:]] for _, _, v, *_ in self.series]
ymax = nice_ceil(max(map(sum if self.stacked else max, zip(*clean)), default=0) * 1.12)
left = max(40, max(F(10).measure(fmt(ymax * g / 4)) for g in range(5)) + 18)
t1 = t[-1]
t0 = t1 - self.span if self.span else t[first]
tr = max(1, t1 - t0)
def X(ms): return left + (ms - t0) / tr * (right - left)
def Y(v): return bottom - min(max(v, 0), ymax) / ymax * (bottom - top)
when = '%H:%M' if tr <= 72e5 else '%a %H:%M' if tr <= 2.6e8 else '%d %b' if tr <= 3.5e10 else '%b %Y'
for g in range(5): # grid, y labels, time labels
y, at = Y(ymax * g / 4), t0 + tr * g / 4
self.create_line(left, y, right, y, fill=C.grid, dash=(4, 3) if g else '')
self.text(left - 8, y, fmt(ymax * g / 4), C.faint, 10, anchor='e')
self.text(X(at), bottom + 14, time.strftime(when, time.localtime(at / 1000)), C.faint, 10, anchor=('w', 'center', 'center', 'center', 'e')[g])
step = max(1, (n - first) // max(50, int((right - left) * 1.5))) # about 1.5 points per pixel
base, lines = [0.0] * n, []
for name, color, v, fill, dashed in self.series:
runs = [[]] # (x, y, y of the base) runs, split at gaps
for i in range(first, n, step):
ok = [(x, b) for x, b in zip(v[i:i + step], base[i:i + step]) if x == x]
if ok:
b = sum(b for _, b in ok) / len(ok)
runs[-1].append((X(t[min(n - 1, i + step // 2)]), Y(sum(x for x, _ in ok) / len(ok) + b), Y(b)))
elif runs[-1]:
runs.append([])
if self.stacked: base = [b + (x if x == x else 0) for b, x in zip(base, v)]
for run in runs:
if len(run) < 2: continue
if fill:
area = [(x, y) for x, y, _ in run] + [(x, yb) for x, _, yb in reversed(run)]
self.create_polygon(area, fill=mix(C.panel, color, .38 if self.stacked else .16), width=0)
lines.append(([(x, y) for x, y, _ in run], color, dashed))
for points, color, dashed in lines: # lines above all areas: an area must not hide another series
self.create_line(points, fill=color, width=1.3 if dashed else 2, dash=(5, 3) if dashed else '', joinstyle='round', capstyle='round')
self.geo = (left, top, right, bottom, t0, tr, X, Y, first)
self.mark()
def point(self, x):
self.hover = x
self.delete('hover')
self.mark()
def mark(self):
"""Crosshair and values at the hovered time."""
if not self.geo or not self.geo[0] <= self.hover <= self.geo[2]: return
left, top, right, bottom, t0, tr, X, Y, first = self.geo
t = self.t
best = min(bisect_left(t, t0 + (self.hover - left) / (right - left) * tr, first), len(t) - 1)
x, stack = X(t[best]), 0
self.create_line(x, top, x, bottom, fill='#565b68', dash=(4, 3), tags='hover')
rows = [time.strftime('%a %d %b %H:%M' if tr > 864e5 else '%H:%M:%S', time.localtime(t[best] / 1000))]
for name, color, v, *_ in self.series:
rows.append(f'{name}: ' + ('—' if v[best] != v[best] else self.fmt(v[best])))
if v[best] == v[best]:
stack = stack + v[best] if self.stacked else v[best]
self.create_oval(x - 4, Y(stack) - 4, x + 4, Y(stack) + 4, fill=color, outline=C.panel, width=2, tags='hover')
width = max(F(11).measure(r) for r in rows)
tx = min(x + 12, right - width - 20)
self.rrect(tx, top + 4, tx + width + 18, top + 14 + len(rows) * 16, 7, C.bg, C.border, tags='hover')
for i, r in enumerate(rows): self.text(tx + 9, top + 17 + i * 16, r, C.text if i else C.muted, 11, tags='hover')
def nice_ceil(v):
if v <= 0: return 1
e = 10 ** math.floor(math.log10(v))
return next((k for k in (1, 2, 2.5, 5) if v / e <= k), 10) * e
class SegmentBar(Paint):
"""Stacked horizontal bar with a legend: (value, colour, label) segments of a total, in bytes."""
def __init__(self, parent):
super().__init__(parent, 300, 58)
self.segments, self.total = [], 1
def set(self, segments, total):
self.segments, self.total = segments, total if total > 0 else 1
self.redraw()
def draw(self):
x = lx = 0
ly, f = 26, F(11)
self.create_rectangle(0, 2, self.w, 16, fill=C.grid, width=0)
for value, color, _ in self.segments:
width = max(0, value / self.total * self.w)
self.create_rectangle(x, 2, x + width, 16, fill=color, width=0)
x += width
self.rrect(-3, -1, self.w + 3, 19, 10, outline=self['bg'], width=6) # rounds the ends of the bar
for value, color, name in self.segments:
label = f'{name} {fmt_bytes(value)}'
if lx + f.measure(label) + 26 > self.w: lx, ly = 0, ly + 18
self.rrect(lx, ly + 3, lx + 9, ly + 12, 2, color)
self.text(lx + 14, ly + 8, label, C.muted, 11)
lx += f.measure(label) + 26
class Tile(Paint):
"""Stat tile: title, large value, sub text and an accent stripe."""
def __init__(self, parent, title, accent):
super().__init__(parent, 150, 84)
self.title, self.accent, self.shown = title.upper(), accent, ('—', '', None)
def set(self, value, sub='', color=None):
if (value, sub, color) != self.shown:
self.shown = (value, sub, color)
self.redraw()
def draw(self):
value, sub, color = self.shown
self.rrect(.5, .5, self.w - 1, self.h - 1, 12, C.card, C.border)
self.rrect(0, 14, 4, self.h - 14, 2, self.accent)
self.text(16, 20, elide(self.title, F(11, True), self.w - 28), C.muted, 11, True)
px = next((p for p in (21, 17, 14) if F(p, True).measure(value) <= self.w - 28), 14) # a narrow tile gets smaller digits
self.text(16, 44 if sub else 50, elide(value, F(px, True), self.w - 28), color or C.text, px, True)
self.text(16, 68, elide(sub, F(11), self.w - 28), C.muted, 11)
class CoreGrid(Paint):
"""One cell per CPU core: usage, bar and frequency."""
def __init__(self, parent):
super().__init__(parent, 300, 66)
self.cores = []
def set(self, cores):
self.cores = cores
self.redraw()
def draw(self):
cols = max(1, self.w // 92)
cw = self.w / cols
self.need_height(-(-max(1, len(self.cores)) // cols) * 66)
for i, core in enumerate(self.cores):
u, c, x, y = core.usage, level(core.usage, 60, 85), cw * (i % cols) + 3, i // cols * 66 + 3
self.rrect(x, y, x + cw - 6, y + 60, 8, mix(C.card, c, u / 420), mix(C.border, c, u / 160))
self.rrect(x + 8, y + 50, x + cw - 14, y + 54, 2, C.grid)
if u >= 1: self.rrect(x + 8, y + 50, x + 8 + (cw - 22) * u / 100, y + 54, 2, c)
self.text(x + 8, y + 12, f'CPU {i}', C.muted, 10)
if core.mhz > 0: self.text(x + cw - 14, y + 12, f'{core.mhz / 1000:.1f}G', C.muted, 10, anchor='e')
self.text(x + 8, y + 32, f'{u:.0f}%', px=16, bold=True)
class Heatmap(Paint):
"""Weekly pattern: average value per weekday and hour, with a tooltip."""
DAYS = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
def __init__(self, parent):
super().__init__(parent, 560, 230)
self.v, self.n, self.unit, self.hot, self.at = [[math.nan] * 24] * 7, [[0] * 24] * 7, '', C.accent, None
self.bind('<Motion>', lambda e: self.point(int((e.y - 6) // ((self.h - 30) / 7)), int((e.x - 40) // ((self.w - 44) / 24))))
self.bind('<Leave>', lambda e: self.point(-1, -1))
def set(self, v, n, unit, hot):
self.v, self.n, self.unit, self.hot = v, n, unit, hot
self.redraw()
def cell(self, d, h):
cw, ch = (self.w - 44) / 24, (self.h - 30) / 7
return 40 + h * cw + 1.5, 6 + d * ch + 1.5, 40 + (h + 1) * cw - 1.5, 6 + (d + 1) * ch - 1.5
def draw(self):
for d in range(7):
self.text(34, (self.cell(d, 0)[1] + self.cell(d, 0)[3]) / 2, self.DAYS[d][:3], C.muted, 10, anchor='e')
for h in range(24):
v = self.v[d][h]
self.rrect(*self.cell(d, h), 3, C.card if v != v else mix('#1b2a44', self.hot, .15 + .85 * min(max(v / 100, 0), 1)))
for h in range(0, 24, 3): self.text(self.cell(6, h)[0] - 4, self.cell(6, h)[3] + 11, f'{h:02d}:00', C.faint, 10)
if all(v != v for row in self.v for v in row):
x0, y0, x1, y1 = self.cell(2, 3)[:2] + self.cell(4, 20)[2:]
self.create_rectangle(x0, y0, x1, y1, fill=C.bg, width=0)
self.text((x0 + x1) / 2, (y0 + y1) / 2, 'Collecting hourly history… the weekly pattern fills in over time', px=12, anchor='center')
def point(self, d, h):
at = (d, h) if 0 <= d < 7 and 0 <= h < 24 else None
if at != self.at:
self.at, v = at, at and self.v[d][h]
show_tip(self, at and f'{self.DAYS[d]} {h}:00 — ' + ('no data' if v != v else f'avg {v:.1f}{self.unit} ({self.n[d][h]} samples)'))
class KeyValues(Paint):
"""List of (key, value) rows; long values wrap."""
def __init__(self, parent, key_width=110):
super().__init__(parent, 200, 20)
self.rows, self.key_width = [], key_width
def set(self, rows):
if rows != self.rows:
self.rows = rows
self.redraw()
def draw(self):
y = 2
for key, value in self.rows:
self.text(0, y, key, C.muted, anchor='nw')
y = self.bbox(self.text(self.key_width, y, value or ' ', anchor='nw', width=max(60, self.w - self.key_width)))[3] + 7
self.need_height(y)
class Chips(Paint):
"""Row of small rounded (text, colour) labels that wraps."""
def __init__(self, parent):
super().__init__(parent, 200, 22)
self.chips = []
def set(self, chips):
if chips != self.chips:
self.chips = chips
self.redraw()
def draw(self):
x = y = 0
for label, color in self.chips:
width = F(12).measure(label) + 18
if x and x + width > self.w: x, y = 0, y + 26
self.rrect(x, y, x + width, y + 22, 6, '#1f2a40')
self.text(x + 9, y + 11, label, color, 12)
x += width + 8
self.need_height(y + 22)
Cell = namedtuple('Cell', 'text color right pct key', defaults=('', False, -1, None)) # pct = bar, key = sort value
class Table(tk.Frame):
"""Hand-drawn table: coloured cells, bar cells, sortable columns and a selected row; only the visible rows are drawn.
A row is a list of cells (Cell or text); its first cell identifies it (by key, or else by text)."""
ROW, HEAD = 30, 32
def __init__(self, parent, headers, widths=(), bars=(), sort=None, height=220): # sort: (column, descending), None = keep the order
super().__init__(parent, bg=C.line, padx=1, pady=1)
self.headers, self.widths, self.bars, self.sort, self.rows, self.top, self.selected = headers, widths, bars, sort, [], 0, None
self.on_open = self.on_menu = self.on_click = None # double click, right click (event), click (row index, column)
self.bar = ttk.Scrollbar(self, command=self.drag)
self.cv = Paint(self, 200, height, bg='#131929')
self.cv.draw = self.draw
self.cv.pack(side='left', fill='both', expand=True)
self.cv.bind('<Button-1>', self.click)
self.cv.bind('<Double-Button-1>', lambda e: e.y > self.HEAD and self.on_open and self.on_open())
self.cv.bind('<Button-3>', lambda e: self.click(e) or (self.on_menu and self.row() and self.on_menu(e)))
def set(self, rows):
self.rows = [[c if isinstance(c, Cell) else Cell(c) for c in r] for r in rows]
if not self.row(): self.selected = None # its entry is gone: the selection must not pass to a later one with the same key
if self.sort:
self.rows.sort(key=lambda r: r[self.sort[0]].text.lower() if r[self.sort[0]].key is None else r[self.sort[0]].key, reverse=self.sort[1])
self.cv.redraw()
@staticmethod
def ident(row): return row[0].text if row[0].key is None else row[0].key
def row(self):
"""The selected row, if it is still listed."""
return next((r for r in self.rows if self.ident(r) == self.selected), None)
def visible(self): return max(1, (self.cv.winfo_height() - self.HEAD) // self.ROW)
def scroll(self, step, to=None):
"""Scrolls by rows (or to a row); False when it cannot move any further."""
top = min(max(self.top + step if to is None else to, 0), max(0, len(self.rows) - self.visible()))
moved, self.top = top != self.top, top
if moved: self.cv.redraw()
return moved
def drag(self, kind, value, unit=None): # scrollbar: ('moveto', fraction) or ('scroll', n, 'units' | 'pages')
if kind == 'moveto': self.scroll(0, round(float(value) * len(self.rows)))
else: self.scroll(int(value) * (self.visible() if unit == 'pages' else 1))
def edges(self):
"""Column x positions: given widths (100 when not given), the last column takes the rest; all shrink in a narrow table."""
ws = [self.widths[i] if i < len(self.widths) else 100 for i in range(len(self.headers) - 1)]
xs, k = [0], min(1, self.cv.w / (sum(ws) + 90))
for w in ws: xs.append(xs[-1] + w * k)
return xs + [self.cv.w]
def click(self, e):
col, i = bisect_right(self.edges(), e.x) - 1, self.top + (e.y - self.HEAD) // self.ROW
if e.y < self.HEAD:
if self.sort is not None and e.num == 1:
self.sort = (col, self.sort[0] == col and not self.sort[1])
self.set(self.rows)
elif i < len(self.rows):
self.selected = self.ident(self.rows[i])
self.cv.redraw()
if self.on_click and e.num == 1: self.on_click(i, col)
def draw(self):
cv, xs, n, shown = self.cv, self.edges(), len(self.rows), self.visible()
self.top = min(self.top, max(0, n - shown))
for i in range(self.top, min(n, self.top + shown + 1)):
row, y = self.rows[i], self.HEAD + (i - self.top) * self.ROW + self.ROW / 2
cv.create_rectangle(0, y - 15, cv.w, y + 15, width=0, fill=C.select if self.ident(row) == self.selected else '#161d2e' if i % 2 else '#131929')
for c, cell in enumerate(row):
x0, x1 = xs[c] + 8, (xs[c + 1] if len(row) > 1 else cv.w) - 8
if c in self.bars and cell.pct >= 0:
p = min(max(cell.pct, 0), 100)
cv.rrect(x0 - 2, y - 7, x1 + 2, y + 7, 4, C.grid)
if p >= 1: cv.rrect(x0 - 2, y - 7, x0 - 2 + (x1 - x0 + 4) * p / 100, y + 7, 4, mix(C.grid, level(p), .78))
cv.text((x0 + x1) / 2, y, cell.text, px=11, bold=True, anchor='center')
else:
cv.text(x1 if cell.right else x0, y, elide(cell.text, F(13), x1 - x0), cell.color or C.text, anchor='e' if cell.right else 'w')
cv.create_rectangle(0, 0, cv.w, self.HEAD, fill='#182033', width=0)
cv.create_line(0, self.HEAD, cv.w, self.HEAD, fill=C.border)
for c, title in enumerate(self.headers):
arrow = (' ▾' if self.sort[1] else ' ▴') if self.sort and self.sort[0] == c else ''
cv.text(xs[c] + 8, self.HEAD / 2, title + arrow, C.muted, 12, True)
self.bar.set(self.top / max(1, n), min(1, (self.top + shown) / max(1, n)))
if (n > shown) != bool(self.bar.winfo_manager()): self.bar.pack(side='right', fill='y', before=cv) if n > shown else self.bar.pack_forget()
# ---- containers ------------------------------------------------------------------------------
class Scroll(tk.Frame):
"""Vertically scrollable area; the content goes into .body."""
def __init__(self, parent):
super().__init__(parent, bg=parent['bg'])
self.cv = tk.Canvas(self, bg=parent['bg'], highlightthickness=0, yscrollincrement=20)
bar = ttk.Scrollbar(self, command=self.cv.yview)
self.body = tk.Frame(self.cv, bg=parent['bg'])
window = self.cv.create_window(0, 0, window=self.body, anchor='nw')
self.cv.config(yscrollcommand=bar.set)
bar.pack(side='right', fill='y')
self.cv.pack(side='left', fill='both', expand=True)
self.body.bind('<Configure>', lambda e: self.cv.config(scrollregion=(0, 0, e.width, e.height)))
self.cv.bind('<Configure>', lambda e: self.cv.itemconfig(window, width=e.width))
def scroll(self, step):
before = self.cv.yview()
self.cv.yview_scroll(step, 'units')
return self.cv.yview() != before
def on_wheel(e):
"""Mouse wheel: scrolls the innermost Table / Scroll under the pointer that can still move."""
w, step = e.widget, -3 if e.num == 4 or e.delta > 0 else 3
while isinstance(w, tk.Misc) and not isinstance(w, tk.Text):
if hasattr(w, 'scroll') and w.scroll(step): break
w = w.master
class Tabs(tk.Frame):
"""Tab bar (the current tab is underlined) above a stack of pages; pages are created with the Tabs as parent."""
def __init__(self, parent, on_change):
super().__init__(parent, bg=parent['bg'])
self.bar, self.pages, self.marks, self.current, self.on_change = down(box(self), 0), [], [], 0, on_change
down(tk.Frame(self, bg=C.line, height=1), 0)
self.bind('<Configure>', lambda e: self.fit(e.width))
def fit(self, width): # a narrow window gets tighter tabs
pad = min(13, max(2, (width - sum(F(13, True).measure(text['text']) for text, _ in self.marks)) // (2 * len(self.marks)) - 1))
for text, _ in self.marks: text.config(padx=pad)
def add(self, title, page):
i, f = len(self.pages), right(box(self.bar), 0)
text = down(tk.Label(f, text=title, bg=self['bg'], fg=C.muted, font=F(13, True), padx=13, pady=9, cursor='hand2'), 0)
text.bind('<Button-1>', lambda e: self.show(i))
self.marks.append((text, down(tk.Frame(f, height=2, bg=self['bg']), 0)))
self.pages.append(page)
def show(self, i):
self.pages[self.current].pack_forget()
self.current = i
self.pages[i].pack(fill='both', expand=True)
for k, (text, underline) in enumerate(self.marks):
text.config(fg='#7dd3fc' if k == i else C.muted)
underline.config(bg=C.accent if k == i else self['bg'])
self.on_change()
# ---- small builders ----------------------------------------------------------------------------
def down(w, gap=14, **kw):
"""Packs w below its siblings (full width, gap underneath) and returns it."""
w.pack(**{'side': 'top', 'fill': 'x', 'pady': (0, gap), **kw})
return w
def right(w, gap=10, grow=False, **kw):
"""Packs w to the right of its siblings (gap after it) and returns it."""
w.pack(**{'side': 'left', 'fill': 'both', 'expand': grow, 'padx': (0, gap), **kw})
return w
def spread(widgets, cols=99, weights=None, gap=14):
"""Grids the children of one frame into columns of equal (or weighted) width."""
for i, w in enumerate(widgets):
w.grid(row=i // cols, column=i % cols, sticky='nsew', padx=(gap if i % cols else 0, 0), pady=(gap if i >= cols else 0, 0))
w.master.columnconfigure(i % cols, weight=weights[i] if weights else 1, uniform='columns')
def box(parent, **kw): return tk.Frame(parent, bg=parent['bg'], **kw)
def panel(parent, title='', width=0):
"""Bordered panel with an optional title and minimum width."""
f = tk.Frame(parent, bg=C.panel, padx=16, pady=14, highlightthickness=1, highlightbackground=C.line)
if width: tk.Frame(f, bg=C.panel, width=width - 34, height=0).pack()
if title: down(label(f, title.upper(), 'Section'), 10)
return f
def tiles(parent, defs, cols=99):
"""Row(s) of stat tiles from (title, colour) pairs."""
f = down(box(parent))
made = [Tile(f, *d) for d in defs]
spread(made, cols)
return made
STYLES = {'H1': (22, True, C.text), 'H2': (16, True, C.text), 'Muted': (13, False, C.muted), 'Section': (11, True, C.muted), 'Small': (11, False, C.muted)}
def label(parent, text='', kind=None, wrap=0, **kw):
"""Text label; wrap = pixels, or True to wrap at the width the layout gives it."""
px, bold, color = STYLES.get(kind, (13, False, C.text))
w = tk.Label(parent, **{'text': text, 'bg': parent['bg'], 'fg': color, 'font': F(px, bold), 'justify': 'left', 'anchor': 'w',
'wraplength': 300 if wrap is True else wrap, **kw})
if wrap is True: w.bind('<Configure>', lambda e: w.config(wraplength=e.width))
return w
# background, text, hover background, border (None = like the parent)
BUTTONS = {None: ('#1d2538', C.text, '#253049', '#2c3650'), 'Primary': ('#0e7ab8', '#ffffff', '#1190d8', C.accent),
'Danger': ('#3a1820', '#ffb4bd', '#55202b', '#7f2a36'), 'Side': ('#1d2538', C.text, '#253049', '#2c3650'),
'Flat': (None, C.muted, None, None), 'Nav': (None, C.text, C.card, None)}
def button(parent, text, command=None, kind=None, **kw):
bg, fg, over, border = (x or parent['bg'] for x in BUTTONS[kind])
b = tk.Button(parent, **{'text': text, 'command': command, 'bg': bg, 'fg': fg, 'activebackground': over, 'cursor': 'hand2',
'activeforeground': C.text if kind == 'Flat' else fg, 'disabledforeground': C.faint, 'relief': 'flat', 'bd': 0,
'highlightthickness': 1, 'highlightbackground': border, 'padx': 13, 'pady': 5, 'takefocus': 0,
'font': F(14 if kind == 'Nav' else 13, kind in (None, 'Primary', 'Danger')),
'anchor': 'w' if kind in ('Nav', 'Side') else 'center', **kw})
b.kind, b.colors = kind, (bg, fg)
b.bind('<Enter>', lambda e: b['state'] != 'disabled' and b.config(bg=b['activebackground']))
b.bind('<Leave>', lambda e: b.config(bg=b.colors[0]))
return b
def press(b, on):
"""Shows a button as checked or not."""
normal = [x or b.master['bg'] for x in BUTTONS[b.kind][:2]]
b.colors = ((C.select, '#7dd3fc') if b.kind == 'Nav' else BUTTONS['Primary'][:2]) if on else normal
b.config(bg=b.colors[0], fg=b.colors[1])
FIELD = {'bg': C.field, 'fg': C.text, 'insertbackground': C.text, 'relief': 'flat', 'bd': 5, 'highlightthickness': 1,
'highlightbackground': '#2a3449', 'highlightcolor': C.accent}
OFF = {'disabledbackground': C.bg, 'disabledforeground': C.faint} # look of disabled entry fields
class Entry(tk.Entry):
"""Text field with a placeholder (hint); text() is '' while the hint shows."""
def __init__(self, parent, text='', hint='', width=20, show='', mono=False):
super().__init__(parent, width=width, font=F(13, mono=mono), **FIELD, **OFF)
self.hint, self.mask, self.hinting = hint, show, False
self.insert(0, text)
self.bind('<FocusIn>', lambda e: self.blur(False))
self.bind('<FocusOut>', lambda e: self.blur(True))
self.blur(True)
def blur(self, away):
if self.hinting and not away:
self.hinting = False
self.delete(0, 'end')
elif away and not self.get() and self.hint:
self.hinting = True
self.insert(0, self.hint)
self.config(fg=C.faint if self.hinting else C.text, show='' if self.hinting else self.mask)
def text(self): return '' if self.hinting else self.get()
def put(self, text, hint=None):
self.blur(False)
self.hint = self.hint if hint is None else hint
self.delete(0, 'end')
self.insert(0, text)
self.blur(self.focus_get() is not self)
class Spin(tk.Spinbox):
"""Number field; value() is clamped to the range (an int when the step is whole)."""
def __init__(self, parent, lo, hi, value=0, step=1, width=7, command=None):
super().__init__(parent, from_=lo, to=hi, increment=step, width=width, font=F(13), buttonbackground=C.card, command=command, **FIELD, **OFF)
self.lo, self.hi, self.step = lo, hi, step
self.put(value)
if command:
self.bind('<FocusOut>', lambda e: command())
self.bind('<Return>', lambda e: command())
def put(self, value):
self.delete(0, 'end')
self.insert(0, f'{value:.12g}')
def value(self):
v = min(max(num(self.get()), self.lo), self.hi)
return v if self.step % 1 else int(v)
def combo(parent, values, width=18, command=None, edit=False):
c = ttk.Combobox(parent, values=values, width=width, state='normal' if edit else 'readonly', font=F(13))
if values and not edit: c.current(0)
c.bind('<<ComboboxSelected>>', lambda e: (c.selection_clear(), command and command()))
return c
def check(parent, text, on=False, command=None):
"""Check box; .var holds the state."""
var = tk.BooleanVar(value=on)
c = tk.Checkbutton(parent, text=text, variable=var, command=command, bg=parent['bg'], fg=C.text, activebackground=parent['bg'],
activeforeground=C.text, selectcolor=C.field, anchor='w', font=F(13), cursor='hand2', highlightthickness=0, bd=0)
c.var = var
return c
def textbox(parent, mono=True, **kw):
"""Read-only text area with a scrollbar; pack its .frame. Fill it with write()."""
frame = box(parent)
t = tk.Text(frame, **{'bg': '#080b12', 'fg': '#cfe3ff', 'font': F(12, mono=mono), 'relief': 'flat', 'bd': 0, 'padx': 10, 'pady': 10, 'wrap': 'none',
'state': 'disabled', 'width': 1, 'height': 1, 'highlightthickness': 0, **kw})
bar = ttk.Scrollbar(frame, command=t.yview)
t.config(yscrollcommand=bar.set)
bar.pack(side='right', fill='y')
t.pack(side='left', fill='both', expand=True)
t.frame = frame
return t
def write(t, text, color=None, clear=False):
"""Appends text (optionally coloured) to a read-only text area and scrolls to the end."""
t.config(state='normal')
if clear: t.delete('1.0', 'end')
t.insert('end', text, color or ())
t.delete('1.0', 'end - 20000 lines')
if color: t.tag_config(color, foreground=color)
t.config(state='disabled')
t.see('end')
def field(form, text, widget):
"""Adds a labelled row to a form frame and returns the widget."""
r = form.grid_size()[1]
label(form, text, 'Muted').grid(row=r, column=0, sticky='w', padx=(0, 14), pady=5)
widget.grid(row=r, column=1, sticky='ew', pady=5)
form.columnconfigure(1, weight=1)
return widget
def popup(widget, event, items):
"""Context menu from (text, command) pairs; None = separator."""
if getattr(popup, 'menu', None): popup.menu.destroy() # the previous one
popup.menu = m = tk.Menu(widget, tearoff=0)
for item in items: m.add_command(label=item[0], command=item[1]) if item else m.add_separator()
m.tk_popup(event.x_root, event.y_root)
def show_tip(widget, text):
"""Shows a tooltip near the pointer; an empty text hides it."""
tip = getattr(show_tip, 'window', None)
if tip: tip.destroy()
show_tip.window = None
if text:
show_tip.window = tip = tk.Toplevel(widget, bg=C.accent, padx=1, pady=1)
tip.overrideredirect(True)
tk.Label(tip, text=text, bg=C.card, fg=C.text, padx=8, pady=5, justify='left', wraplength=560, font=F(11)).pack()
tip.geometry(f'+{widget.winfo_pointerx() + 14}+{widget.winfo_pointery() + 18}')
def tip(widget, text):
widget.bind('<Enter>', lambda e: show_tip(widget, text), add='+')
widget.bind('<Leave>', lambda e: show_tip(widget, ''), add='+')
return widget
class Dialog(tk.Toplevel):
"""Dark dialog window; run() shows it modally and returns what close() was given."""
def __init__(self, parent, title):
super().__init__(parent, bg=C.bg, padx=24, pady=20)
self.title(title)
self.transient(parent.winfo_toplevel())
self.result = None
self.protocol('WM_DELETE_WINDOW', self.close)
self.bind('<Escape>', lambda e: self.close())
def buttons(self, *defs):
"""Row of (text, command[, kind]) buttons at the bottom right."""
row = down(box(self), 0)
for d in reversed(defs): button(row, *d).pack(side='right', padx=(8, 0))
def close(self, result=None):
self.result = result
self.destroy()
def run(self):
self.update_idletasks()
top = self.master.winfo_toplevel()
self.geometry(f'+{top.winfo_rootx() + max(0, (top.winfo_width() - self.winfo_reqwidth()) // 2)}+{top.winfo_rooty() + 120}')
self.wait_visibility()
self.grab_set()
self.wait_window()
return self.result
def choose(parent, title, text, options):
"""Modal question with (text, kind) buttons; returns the text of the chosen one, None when dismissed."""
d = Dialog(parent, title)
down(label(d, text, wrap=460), 18)
d.buttons(*((name, lambda name=name: d.close(name), kind) for name, kind in options))
return d.run()
def ask(parent, title, text, danger=False): return choose(parent, title, text, [('No', None), ('Yes', 'Danger' if danger else 'Primary')]) == 'Yes'
def app_icon(size):
"""App icon: gradient tile with a pulse line."""
line = [(.12, .56), (.34, .56), (.44, .28), (.56, .78), (.66, .48), (.88, .48)]
def near(x, y, a, b): # distance from (x, y) to the segment a-b
(ax, ay), (bx, by) = a, b
k = min(max(((x - ax) * (bx - ax) + (y - ay) * (by - ay)) / ((bx - ax) ** 2 + (by - ay) ** 2), 0), 1)
return math.hypot(x - ax - k * (bx - ax), y - ay - k * (by - ay))
image = tk.PhotoImage(width=size, height=size)
cells = [[(x + .5) / size, (y + .5) / size] for y in range(size) for x in range(size)]
colors = ['#ffffff' if min(near(x, y, a, b) for a, b in zip(line, line[1:])) < .042 else mix('#0ea5e9', '#7c3aed', (x + y) / 2) for x, y in cells]
image.put(' '.join('{' + ' '.join(colors[r * size:(r + 1) * size]) + '}' for r in range(size)))
return image
|