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
|
# sb-builder - Dashboard tab
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Dashboard tab: KPI tiles, VM meters, slackrepo results bar, recent jobs."""
import collections
import html
import time
from PyQt6.QtCore import QEvent, QPointF, QRectF, Qt, pyqtSignal
from PyQt6.QtGui import QColor, QFont, QPainter, QPalette
from PyQt6.QtWidgets import (QFrame, QGridLayout, QHBoxLayout, QLabel, QToolTip, QVBoxLayout,
QWidget)
from .fmt import ICON, NA, fmt_age, fmt_bytes, fmt_duration, fmt_time, job_title
from .ui import SP, action
# reserved status colors (dataviz reference palette); always shown with a text label
STATUS = {"ok": "#0ca30c", "aborted": "#fab219", "bad": "#ec835a", "failed": "#d03b3b",
"killed": "#fab219", "lost": "#ec835a"}
GAP = 2 # px of surface between bar segments
SPARK_POINTS = 60 # ~30 min at the default 30 s dashboard refresh
def upgrade_color(ts, now=None):
"""Status color for the last upgrade: green within a day, yellow, red after two."""
if ts is None:
return None
age = (now or time.time()) - ts
return STATUS["failed"] if age > 2 * 86400 else STATUS["aborted"] if age > 86400 else STATUS["ok"]
def meter_color(pct, accent):
"""Fill color by severity: accent, then warning from 80%, critical from 90%."""
if pct >= 90:
return QColor(STATUS["failed"])
if pct >= 80:
return QColor(STATUS["aborted"])
return accent
def num(n):
return NA if n is None else f"{n:,}"
def muted(label):
label.setForegroundRole(QPalette.ColorRole.PlaceholderText)
return label
class Card(QFrame):
"""Rounded panel with a muted title; content goes into self.body."""
clicked = pyqtSignal()
def __init__(self, title):
super().__init__(objectName="card")
self.body = QVBoxLayout(self)
self.body.setContentsMargins(16, 12, 16, 14)
self.body.addWidget(muted(QLabel(title)))
def link(self, slot):
"""Make the whole card open something."""
self.clicked.connect(slot)
self.setCursor(Qt.CursorShape.PointingHandCursor)
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit()
super().mouseReleaseEvent(event)
class Tile(Card):
"""Stat tile: title, one large value, a muted detail line."""
def __init__(self, title):
super().__init__(title)
self.value = QLabel(NA)
f = self.value.font()
f.setPointSizeF(f.pointSizeF() * 2.2)
f.setWeight(QFont.Weight.DemiBold)
self.value.setFont(f)
self.detail = muted(QLabel())
self.detail.setWordWrap(True)
self.body.addWidget(self.value)
self.body.addWidget(self.detail)
self.body.addStretch()
def set(self, value, detail=""):
self.value.setText(value)
self.detail.setText(detail)
class StackedBar(QWidget):
"""Horizontal part-to-whole bar; hover a segment for its count, click to open it."""
clicked = pyqtSignal(str)
def __init__(self):
super().__init__()
self.parts = [] # (label, count, QColor)
self.setFixedHeight(14)
def set_parts(self, parts):
self.parts = [p for p in parts if p[1]]
self.update()
def rects(self):
total = sum(c for _, c, _ in self.parts)
if not total:
return []
room = self.width() - GAP * (len(self.parts) - 1)
out, x = [], 0.0
for label, count, color in self.parts:
w = max(2.0, room * count / total)
out.append((QRectF(x, 0, w, self.height()), label, count, color))
x += w + GAP
return out
def paintEvent(self, _event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
for rect, _label, _count, color in self.rects():
p.setBrush(color)
p.drawRoundedRect(rect, 4, 4)
def label_at(self, pos):
return next((label for rect, label, _c, _col in self.rects() if rect.contains(pos)), None)
def mouseReleaseEvent(self, e):
label = self.label_at(e.position())
if label and e.button() == Qt.MouseButton.LeftButton:
self.clicked.emit(label)
def event(self, e):
if e.type() == QEvent.Type.ToolTip:
hit = next((f"{label}: {count:,}" for rect, label, count, _ in self.rects()
if rect.contains(e.position())), None)
if hit:
QToolTip.showText(e.globalPosition().toPoint(), hit, self)
else:
QToolTip.hideText()
return True
return super().event(e)
class MeterBar(QWidget):
"""Horizontal meter; the track is a faint step of the fill's own color."""
def __init__(self):
super().__init__()
self.pct = None
self.setFixedHeight(10)
def paintEvent(self, _event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
fill = meter_color(self.pct or 0, self.palette().color(QPalette.ColorRole.Highlight))
track = QColor(fill)
track.setAlphaF(0.22)
p.setBrush(track)
p.drawRoundedRect(QRectF(self.rect()), 4, 4)
if self.pct:
p.setBrush(fill)
p.drawRoundedRect(QRectF(0, 0, self.width() * min(self.pct, 100) / 100, self.height()), 4, 4)
class Sparkline(QWidget):
"""Recent values as a thin line, newest point marked; this session's polls only."""
def __init__(self):
super().__init__()
# ponytail: in-memory, filled only while the dashboard is polled (visible)
self.points = collections.deque(maxlen=SPARK_POINTS)
self.setFixedHeight(30)
def add(self, value):
self.points.append(value)
self.update()
def paintEvent(self, _event):
if len(self.points) < 2:
return
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
w, h = self.width() - 4, self.height() - 4
step = w / (SPARK_POINTS - 1)
x0 = 2 + w - step * (len(self.points) - 1) # newest at the right edge
pts = [QPointF(x0 + i * step, 2 + h - h * min(v, 100) / 100)
for i, v in enumerate(self.points)]
pen = p.pen()
pen.setColor(self.palette().color(QPalette.ColorRole.PlaceholderText))
pen.setWidthF(2)
p.setPen(pen)
p.drawPolyline(pts)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(self.palette().color(QPalette.ColorRole.Highlight))
p.drawEllipse(pts[-1], 3, 3)
class Meter(QWidget):
"""Label and percentage, meter bar, muted detail, optional sparkline."""
def __init__(self, label, spark=False):
super().__init__()
self.value = QLabel(NA)
f = self.value.font()
f.setWeight(QFont.Weight.DemiBold)
self.value.setFont(f)
self.bar = MeterBar()
self.detail = muted(QLabel())
self.spark = Sparkline() if spark else None
head = QHBoxLayout()
head.addWidget(QLabel(label))
head.addStretch()
head.addWidget(self.value)
col = QVBoxLayout()
col.setSpacing(4)
col.addLayout(head)
col.addWidget(self.bar)
col.addWidget(self.detail)
if self.spark:
col.addWidget(self.spark)
col.addStretch()
col.setContentsMargins(0, 0, 0, 0)
self.setLayout(col)
def set(self, pct, detail):
self.bar.pct = pct
self.bar.update()
self.value.setText(NA if pct is None else f"{pct:.0f}%")
self.detail.setText(detail)
if self.spark and pct is not None:
self.spark.add(pct)
class Dashboard(QWidget):
result_clicked = pyqtSignal(str) # a slackrepo result kind, from the bar or legend
def __init__(self, parent=None):
super().__init__(parent)
self.setStyleSheet("QFrame#card { background: palette(base);"
" border: 1px solid palette(mid); border-radius: 10px; }")
self.tiles = {name: Tile(name) for name in ("Packages", "Built", "Last pull", "slackpkg")}
self.vm = Card("VM")
self.cpu, self.ram, self.disk = Meter("CPU", spark=True), Meter("RAM", spark=True), Meter("Disk /")
meters = QHBoxLayout()
meters.setSpacing(28)
for m in (self.cpu, self.ram, self.disk):
meters.addWidget(m, 1)
self.vm.body.addLayout(meters)
self.results = Card("slackrepo results")
self.bar = StackedBar()
self.legend = QLabel(NA)
self.legend.setTextFormat(Qt.TextFormat.RichText)
self.legend.setWordWrap(True)
self.legend.linkActivated.connect(self.result_clicked)
self.bar.clicked.connect(self.result_clicked)
self.bar.setCursor(Qt.CursorShape.PointingHandCursor)
self.results.body.addWidget(self.bar)
self.results.body.addWidget(self.legend)
self.results.body.addStretch()
self.orphans = Card("SBo orphans")
self.orphans.body.addWidget(muted(QLabel("coming in phase 5")))
self.orphans.body.addStretch()
self.jobs = Card("Recent jobs")
self.jobs_list = QLabel("no jobs yet")
self.jobs_list.setTextFormat(Qt.TextFormat.RichText)
self.jobs.body.addWidget(self.jobs_list)
self.jobs.body.addStretch()
self.stale = muted(QLabel())
self.refresh = action(self, "Refresh", "view-refresh", SP.SP_BrowserReload)
self.actions, self.view_actions = [self.refresh], []
top = QHBoxLayout()
top.addWidget(self.stale)
top.addStretch()
grid = QGridLayout()
grid.setSpacing(12)
for i, tile in enumerate(self.tiles.values()):
grid.addWidget(tile, 0, i)
grid.addWidget(self.vm, 1, 0, 1, 3)
grid.addWidget(self.orphans, 1, 3)
grid.addWidget(self.results, 2, 0, 1, 4)
grid.addWidget(self.jobs, 3, 0, 1, 4)
grid.setRowStretch(3, 1)
layout = QVBoxLayout(self)
layout.setContentsMargins(16, 12, 16, 16)
layout.addLayout(top)
layout.addLayout(grid)
def cards(self):
return [*self.tiles.values(), self.vm, self.results, self.orphans, self.jobs]
def show_stats(self, s):
p, sr, sync = s.get("packages"), s.get("slackrepo"), s.get("sync") or {}
t = self.tiles
if p is None:
t["Packages"].set(NA)
else:
extra = " · ".join(f"{num(v)}\u00a0{k}" for k, v in p.items() if k != "total")
t["Packages"].set(num(p["total"]), extra)
if sr is None:
t["Built"].set(NA, "no slackrepo database")
else:
never = "" if p is None else f" · {num(p['total'] - sr['built'])} never built"
t["Built"].set(num(sr["built"]), f"of {num(p and p['total'])}{never}")
known = [ts for ts in sync.values() if ts is not None]
t["Last pull"].set(fmt_age(min(known)) if known else NA,
" · ".join(f"{o} {fmt_duration(None if ts is None else time.time() - ts)}"
for o, ts in sync.items()))
pkg = s.get("slackpkg") or {}
dot = upgrade_color(pkg.get("upgrade"))
t["slackpkg"].set(f'<span style="color:{dot}">●</span> {fmt_age(pkg["upgrade"])}'
if dot else NA,
"last upgrade · lists updated " + fmt_duration(
None if pkg.get("update") is None else time.time() - pkg["update"]))
load, mem, disk = s.get("load"), s.get("mem"), s.get("disk") or {}
self.cpu.set(s.get("cpu"), f"load {NA if load is None else f'{load[0]:.2f}'}"
f" · up {fmt_duration(s.get('uptime'))}")
if mem:
used = mem["total"] - mem["available"]
self.ram.set(100 * used / mem["total"],
f"{fmt_bytes(used)} used of {fmt_bytes(mem['total'])}")
else:
self.ram.set(None, "")
if disk.get("total"):
self.disk.set(100 * (disk["total"] - disk["free"]) / disk["total"],
f"{fmt_bytes(disk['free'])} free of {fmt_bytes(disk['total'])}")
else:
self.disk.set(None, "")
self._show_results(sr)
def _show_results(self, sr):
if sr is None:
self.bar.set_parts([])
self.legend.setText(NA)
return
gray = self.palette().color(QPalette.ColorRole.PlaceholderText) # Mid can match the background
ink = self.palette().color(QPalette.ColorRole.WindowText).name() # links in text color
order = sorted(sr["results"].items(),
key=lambda kv: (list(STATUS).index(kv[0]) if kv[0] in STATUS else 99, kv[0]))
self.bar.set_parts([(k, v, QColor(STATUS.get(k)) if k in STATUS else gray) for k, v in order])
self.legend.setText(" ".join(
f'<span style="color:{STATUS.get(k, gray.name())}">■</span> '
f'<a href="{html.escape(k)}" style="color:{ink}; text-decoration:none">'
f'{html.escape(k)} {num(v)}</a>'
for k, v in order))
def show_jobs(self, jobs):
rows = []
for j in jobs[:10]:
color = STATUS.get(j["status"])
icon = ICON.get(j["status"], "?")
if color:
icon = f'<span style="color:{color}">{icon}</span>'
dur = None if "start" not in j else j.get("end", time.time()) - j["start"]
rows.append(f"<tr><td>{icon} </td><td>{html.escape(job_title(j))} </td>"
f"<td>{j['status']} </td>"
f"<td>{fmt_time(j.get('start', j['created']))} </td>"
f"<td>{fmt_duration(dur)}</td></tr>")
self.jobs_list.setText(f"<table>{''.join(rows)}</table>" if rows else "no jobs yet")
def set_stale(self, since):
"""Grey the cards when the VM stopped answering; None clears it."""
for card in self.cards():
card.setEnabled(since is None)
self.stale.setText("" if since is None else
f"stale since {fmt_time(since)}")
|