mchuca's picture
Server Monitor: six editions (C++/Qt, Python, web for Linux and Windows), requirements and developer kit
bad179a
Raw History Blame Contribute Delete
26.4 kB
#include "Widgets.h"
#include <QDateTime>
#include <QFontDatabase>
#include <QGridLayout>
#include <QHeaderView>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPainterPath>
#include <QToolTip>
#include <QVBoxLayout>
#include <cmath>
// ---- theme --------------------------------------------------------------------------------
QColor C::level(double p, double w, double c) { return p >= c ? red : p >= w ? amber : green; }
QColor C::severity(const QString &s) { return s == "critical" ? red : s == "warning" ? amber : s == "resolved" ? green : s == "action" ? violet : accent; }
QColor C::health(int h) { return h >= 90 ? green : h >= 75 ? teal : h >= 60 ? amber : h >= 40 ? orange : red; }
QColor C::mix(const QColor &a, const QColor &b, double t)
{
t = qBound(0.0, t, 1.0);
return QColor::fromRgbF(a.redF() + (b.redF() - a.redF()) * t, a.greenF() + (b.greenF() - a.greenF()) * t, a.blueF() + (b.blueF() - a.blueF()) * t);
}
QString C::mono() { return QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); }
QString C::styleSheet()
{
return R"(
* { color: #e6ebf5; font-size: 13px; }
QMainWindow, QDialog, #Page { background: #0d111c; }
#Sidebar { background: #10151f; border-right: 1px solid #1f2738; }
QToolTip { background: #1a2133; border: 1px solid #38bdf8; padding: 6px; border-radius: 6px; }
QLabel#H1 { font-size: 22px; font-weight: 700; } QLabel#H2 { font-size: 16px; font-weight: 600; }
QLabel#Muted { color: #8b95ab; } QLabel#Section { color: #8b95ab; font-size: 11px; font-weight: 700; letter-spacing: 1px; }
QFrame#Panel { background: #161c2b; border: 1px solid #232c41; border-radius: 12px; }
QPushButton { background: #1d2538; border: 1px solid #2c3650; border-radius: 8px; padding: 7px 14px; font-weight: 600; }
QPushButton:hover { background: #253049; border-color: #38bdf8; } QPushButton:pressed { background: #18324a; }
QPushButton:disabled { color: #5a657d; border-color: #222a3c; }
QPushButton:checked, QPushButton#Primary { background: #0e7ab8; border-color: #38bdf8; color: white; } QPushButton#Primary:hover { background: #1190d8; }
QPushButton#Danger { background: #3a1820; border-color: #7f2a36; color: #ffb4bd; } QPushButton#Danger:hover { background: #55202b; border-color: #ef4444; }
QPushButton#Nav { text-align: left; padding: 10px 14px; border: none; background: transparent; font-size: 14px; }
QPushButton#Nav:hover { background: #1a2133; } QPushButton#Nav:checked { background: #17304a; color: #7dd3fc; }
QPushButton#Flat { background: transparent; border: none; padding: 4px 8px; color: #8b95ab; } QPushButton#Flat:hover { color: #e6ebf5; }
QPushButton#Side { text-align: left; padding: 6px 12px; }
QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox, QPlainTextEdit { background: #111727; border: 1px solid #2a3449; border-radius: 7px; padding: 6px 8px; selection-background-color: #0e7ab8; }
QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus, QPlainTextEdit:focus { border-color: #38bdf8; }
QComboBox::drop-down { border: none; width: 22px; }
QComboBox QAbstractItemView { background: #161c2b; border: 1px solid #2a3449; selection-background-color: #17304a; }
QCheckBox::indicator { width: 16px; height: 16px; border-radius: 4px; border: 1px solid #3a4662; background: #111727; }
QCheckBox::indicator:checked { background: #0ea5e9; border-color: #38bdf8; }
QTabWidget::pane { border: none; }
QTabBar::tab { background: transparent; color: #8b95ab; padding: 10px 14px; border-bottom: 2px solid transparent; }
QTabBar::tab:hover { color: #e6ebf5; } QTabBar::tab:selected { color: #7dd3fc; border-bottom: 2px solid #38bdf8; }
QTableView, QListView { background: #131929; alternate-background-color: #161d2e; border: 1px solid #232c41; border-radius: 10px;
selection-background-color: #17304a; selection-color: #e6ebf5; outline: none; }
QTableView::item { padding: 4px; }
QHeaderView::section { background: #182033; color: #8b95ab; border: none; border-bottom: 1px solid #27314a; padding: 7px 8px; font-weight: 700; font-size: 12px; }
QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; } QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; }
QScrollBar::handle { background: #2a3449; border-radius: 4px; min-height: 30px; min-width: 30px; } QScrollBar::handle:hover { background: #3b4866; }
QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; } QScrollBar::add-page, QScrollBar::sub-page { background: none; }
QScrollArea { border: none; background: transparent; } QScrollArea > QWidget > QWidget { background: transparent; }
QMenu { background: #161c2b; border: 1px solid #2a3449; border-radius: 8px; padding: 6px; }
QMenu::item { padding: 7px 22px; border-radius: 5px; } QMenu::item:selected { background: #17304a; }
QMenu::separator { height: 1px; background: #27314a; margin: 4px 8px; }
)";
}
QIcon C::appIcon()
{
QIcon icon;
for (int s : {16, 32, 64, 128, 256}) {
QPixmap pm(s, s);
pm.fill(Qt::transparent);
QPainter p(&pm);
p.setRenderHint(QPainter::Antialiasing);
QLinearGradient g(0, 0, s, s);
g.setColorAt(0, 0x0ea5e9), g.setColorAt(1, 0x7c3aed);
p.setBrush(g), p.setPen(Qt::NoPen);
p.drawRoundedRect(QRectF(0, 0, s, s), s * .22, s * .22);
p.setPen(QPen(Qt::white, qMax(1.5, s * .075), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
p.drawPolyline(QPolygonF({{s * .12, s * .56}, {s * .34, s * .56}, {s * .44, s * .28}, {s * .56, s * .78}, {s * .66, s * .48}, {s * .88, s * .48}}));
icon.addPixmap(pm);
}
return icon;
}
QFont pxFont(QFont f, int px, bool bold) { return f.setPixelSize(px), f.setBold(bold), f; }
static double niceCeil(double v)
{
if (v <= 0) return 1;
const double e = std::pow(10, std::floor(std::log10(v))), f = v / e;
return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e;
}
static void roundedPanel(QPainter &p, const QRectF &r, const QBrush &b, const QColor &border = C::border, double rad = 12)
{
p.setPen(QPen(border, 1)), p.setBrush(b);
p.drawRoundedRect(r.adjusted(.5, .5, -.5, -.5), rad, rad);
}
void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double t, bool glow)
{
p.save();
p.setRenderHint(QPainter::Antialiasing);
const QRectF rr = r.adjusted(t / 2, t / 2, -t / 2, -t / 2);
p.setPen(QPen(C::grid, t, Qt::SolidLine, Qt::RoundCap));
p.drawArc(rr, 225 * 16, -270 * 16);
const int span = int(-270 * 16 * qBound(0.0, pct, 100.0) / 100);
if (span < -3) {
if (glow) p.setPen(QPen(C::tint(c, 45), t * 2, Qt::SolidLine, Qt::RoundCap)), p.drawArc(rr, 225 * 16, span);
p.setPen(QPen(c, t, Qt::SolidLine, Qt::RoundCap));
p.drawArc(rr, 225 * 16, span);
}
p.restore();
}
// ---- RingGauge ------------------------------------------------------------------------------
RingGauge::RingGauge(const QString &title) : m_title(title)
{
m_anim.setDuration(450), m_anim.setEasingCurve(QEasingCurve::OutCubic);
connect(&m_anim, &QVariantAnimation::valueChanged, this, [this](const QVariant &v) { m_shown = v.toDouble(), update(); });
}
void RingGauge::setValue(double pct, const QString &center, const QString &sub, const QColor &color)
{
m_center = center, m_sub = sub, m_color = color;
pct = std::isnan(pct) ? 0 : pct;
if (qAbs(pct - m_target) > 0.05) m_anim.stop(), m_anim.setStartValue(m_shown), m_anim.setEndValue(m_target = pct), m_anim.start();
update();
}
void RingGauge::paintEvent(QPaintEvent *)
{
AA p(this);
const double s = qMin(width() - 8.0, height() - 28.0);
const QRectF r((width() - s) / 2, 4, s, s);
paintRing(p, r, m_shown, m_color.isValid() ? m_color : C::level(m_target, warn, crit), qMax(7.0, s * .085));
p.setFont(pxFont(font(), int(s * .2), true)), p.setPen(C::text);
p.drawText(QRectF(r.left(), r.top() + s * .3, s, s * .26), Qt::AlignCenter, m_center.isEmpty() ? QString::number(m_shown, 'f', 0) + "%" : m_center);
p.setFont(pxFont(font(), qMax(10, int(s * .075)))), p.setPen(C::muted);
p.drawText(QRectF(r.left() + s * .12, r.top() + s * .56, s * .76, s * .14), Qt::AlignCenter, p.fontMetrics().elidedText(m_sub, Qt::ElideRight, int(s * .76)));
p.setFont(pxFont(font(), 13, true)), p.setPen(C::text);
p.drawText(QRectF(0, r.bottom() - s * .06, width(), 22), Qt::AlignHCenter, m_title);
}
// ---- TimeChart --------------------------------------------------------------------------------
TimeChart::TimeChart(const QString &t, FmtFn fmt, double yMax) : title(t), m_fmt(fmt), m_yMax(yMax)
{
setMouseTracking(true), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
void TimeChart::setData(const QVector<qint64> &t, const QVector<Series> &s, qint64 span) { m_t = t, m_s = s, m_span = span, update(); }
void TimeChart::mouseMoveEvent(QMouseEvent *e) { m_hover = e->pos().x(), update(); }
void TimeChart::paintEvent(QPaintEvent *)
{
AA p(this);
roundedPanel(p, rect(), C::panel);
p.setFont(pxFont(font(), 13, true)), p.setPen(C::text);
p.drawText(16, 10, width(), 20, Qt::AlignVCenter, title);
const int titleW = p.fontMetrics().horizontalAdvance(title);
p.setFont(pxFont(font(), 11)), p.setPen(C::muted);
p.drawText(24 + titleW, 10, width(), 20, Qt::AlignVCenter, subtitle);
double lx = width() - 16; // legend with latest values, right-aligned
for (int i = m_s.size() - 1; i >= 0; --i) {
const Series &s = m_s[i];
double last = NAN;
for (int k = s.v.size() - 1; k >= qMax(0, s.v.size() - 5) && std::isnan(last); --k) last = s.v[k];
const QString txt = s.name + (std::isnan(last) ? "" : " " + m_fmt(last));
const int w = p.fontMetrics().horizontalAdvance(txt);
if ((lx -= w) < 40 + titleW) break;
p.setPen(C::muted), p.drawText(QRectF(lx, 10, w, 20), Qt::AlignVCenter, txt);
p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx -= 14, 16, 9, 9), 2, 2);
lx -= 14;
}
const int n = m_t.size();
int first = 0;
if (n && m_span)
while (first < n && m_t[first] < m_t.last() - m_span) ++first;
QRectF plot(56, 40, width() - 72, height() - 70);
if (n - first < 2 || plot.height() < 20) return p.setPen(C::faint), p.drawText(plot, Qt::AlignCenter, empty);
double yMax = m_yMax;
if (yMax <= 0) {
for (int i = first; i < n; ++i) {
double sum = 0;
for (const Series &s : m_s)
if (i < s.v.size() && !std::isnan(s.v[i])) sum = stacked ? sum + s.v[i] : qMax(sum, s.v[i]);
yMax = qMax(yMax, sum);
}
yMax = niceCeil(yMax * 1.12);
}
p.setFont(pxFont(font(), 10));
int lw = 0;
for (int g = 0; g <= 4; ++g) lw = qMax(lw, p.fontMetrics().horizontalAdvance(m_fmt(yMax * g / 4)));
plot.setLeft(qMax(40, lw + 18));
const qint64 t1 = m_t.last(), t0 = m_span ? t1 - m_span : m_t[first];
const double tr = qMax<qint64>(1, t1 - t0);
auto X = [&](qint64 t) { return plot.left() + (t - t0) / tr * plot.width(); };
auto Y = [&](double v) { return plot.bottom() - qBound(0.0, v, yMax) / yMax * plot.height(); };
const QString tf = tr <= 72e5 ? "HH:mm" : tr <= 2.6e8 ? "ddd HH:mm" : tr <= 3.5e10 ? "dd MMM" : "MMM yyyy";
for (int g = 0; g <= 4; ++g) { // grid, y labels, time labels
const double y = Y(yMax * g / 4), x = X(t0 + qint64(tr * g / 4));
p.setPen(QPen(C::grid, 1, g ? Qt::DashLine : Qt::SolidLine)), p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y));
p.setPen(C::faint);
p.drawText(QRectF(0, y - 8, plot.left() - 8, 16), Qt::AlignRight | Qt::AlignVCenter, m_fmt(yMax * g / 4));
p.drawText(QRectF(g == 0 ? x : g == 4 ? x - 120 : x - 60, plot.bottom() + 6, 120, 16), (g == 0 ? Qt::AlignLeft : g == 4 ? Qt::AlignRight : Qt::AlignHCenter),
QDateTime::fromMSecsSinceEpoch(t0 + qint64(tr * g / 4)).toString(tf));
}
const int step = qMax(1, (n - first) / qMax(50, int(plot.width() * 1.5))); // ~1.5 points per pixel
QVector<double> base(n, 0.0);
p.setClipRect(plot.adjusted(-2, -4, 2, 2));
for (const Series &s : m_s) {
QVector<QPolygonF> top(1), bot(1); // runs split at gaps (NaN)
for (int i = first; i < n; i += step) {
double sum = 0, bs = 0;
int c = 0;
for (int k = i; k < qMin(n, i + step); ++k)
if (k < s.v.size() && !std::isnan(s.v[k])) sum += s.v[k], bs += base[k], ++c;
if (!c) { if (!top.last().isEmpty()) top << QPolygonF(), bot << QPolygonF(); continue; }
const double x = X(m_t[qMin(n - 1, i + step / 2)]), b = stacked ? bs / c : 0;
top.last() << QPointF(x, Y(sum / c + b)), bot.last() << QPointF(x, Y(b));
}
if (stacked)
for (int k = first; k < qMin(n, s.v.size()); ++k) base[k] += std::isnan(s.v[k]) ? 0 : s.v[k];
for (int r = 0; r < top.size(); ++r) {
if (top[r].size() < 2) continue;
if (s.fill) {
QPolygonF area = top[r];
for (int i = bot[r].size() - 1; i >= 0; --i) area << bot[r][i];
QLinearGradient g(0, plot.top(), 0, plot.bottom());
g.setColorAt(0, C::tint(s.color, stacked ? 120 : 95)), g.setColorAt(1, C::tint(s.color, stacked ? 60 : 4));
p.setPen(Qt::NoPen), p.setBrush(g), p.drawPolygon(area);
}
p.setBrush(Qt::NoBrush), p.setPen(QPen(s.color, s.dashed ? 1.3 : 2, s.dashed ? Qt::DashLine : Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
p.drawPolyline(top[r]);
}
}
p.setClipping(false);
if (m_hover < plot.left() || m_hover > plot.right()) return;
const qint64 ht = t0 + qint64((m_hover - plot.left()) / plot.width() * tr); // crosshair + tooltip
const int best = std::lower_bound(m_t.begin() + first, m_t.end(), ht) - m_t.begin() - (m_t.last() < ht);
const double x = X(m_t[best]);
p.setPen(QPen(QColor(255, 255, 255, 70), 1, Qt::DashLine)), p.drawLine(QPointF(x, plot.top()), QPointF(x, plot.bottom()));
QStringList lines{QDateTime::fromMSecsSinceEpoch(m_t[best]).toString(tr > 864e5 ? "ddd dd MMM HH:mm" : "HH:mm:ss")};
double stack = 0;
for (const Series &s : m_s) {
const double v = best < s.v.size() ? s.v[best] : NAN;
lines << s.name + ": " + (std::isnan(v) ? "—" : m_fmt(v));
if (std::isnan(v)) continue;
stack = stacked ? stack + v : v;
p.setPen(QPen(C::panel, 2)), p.setBrush(s.color), p.drawEllipse(QPointF(x, Y(stack)), 4, 4);
}
p.setFont(pxFont(font(), 11));
int tw = 0;
for (const QString &l : lines) tw = qMax(tw, p.fontMetrics().horizontalAdvance(l));
const QRectF tip(qMin(x + 12, plot.right() - tw - 20), plot.top() + 4, tw + 18, lines.size() * 16 + 10);
roundedPanel(p, tip, QColor(13, 17, 28, 235), C::border, 7);
for (int i = 0; i < lines.size(); ++i) p.setPen(i ? C::text : C::muted), p.drawText(QRectF(tip.left() + 9, tip.top() + 5 + i * 16, tw + 4, 16), Qt::AlignVCenter, lines[i]);
}
// ---- SegmentBar --------------------------------------------------------------------------------
SegmentBar::SegmentBar() { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), setFixedHeight(58); }
void SegmentBar::setSegments(const QVector<Segment> &s, double total) { m_s = s, m_total = total > 0 ? total : 1, update(); }
void SegmentBar::paintEvent(QPaintEvent *)
{
AA p(this);
QPainterPath clip;
clip.addRoundedRect(QRectF(0, 2, width(), 14), 7, 7);
p.setClipPath(clip);
p.fillRect(rect(), C::grid);
double x = 0, lx = 0, ly = 26;
for (const Segment &s : m_s) p.fillRect(QRectF(x, 2, s.value / m_total * width(), 14), s.color), x += qMax(0.0, s.value / m_total * width());
p.setClipping(false);
p.setFont(pxFont(font(), 11));
for (const Segment &s : m_s) {
const QString t = s.label + " " + Fmt::bytes(s.value);
const int w = p.fontMetrics().horizontalAdvance(t) + 26;
if (lx + w > width()) lx = 0, ly += 18;
p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx, ly + 3, 9, 9), 2, 2);
p.setPen(C::muted), p.drawText(QRectF(lx + 14, ly, w, 16), Qt::AlignVCenter, t);
lx += w;
}
}
// ---- StatTile ------------------------------------------------------------------------------------
StatTile::StatTile(const QString &title, const QColor &accent) : m_accent(accent)
{
auto *l = new QVBoxLayout(this);
l->setContentsMargins(16, 12, 14, 12), l->setSpacing(2);
l->addWidget(label(title.toUpper(), "Section"));
l->addWidget(m_value = new QLabel("—"));
l->addWidget(m_sub = label({}, "Muted"));
m_sub->setStyleSheet("font-size: 11px;");
setMinimumHeight(84), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), set("—");
}
void StatTile::set(const QString &v, const QString &sub, const QColor &c)
{
m_value->setText(v), m_sub->setText(sub), m_sub->setVisible(!sub.isEmpty());
m_value->setStyleSheet(QString("font-size: 21px; font-weight: 700; color: %1;").arg((c.isValid() ? c : C::text).name()));
}
void StatTile::paintEvent(QPaintEvent *)
{
AA p(this);
QLinearGradient g(0, 0, width(), height());
g.setColorAt(0, C::card), g.setColorAt(1, C::panel);
roundedPanel(p, rect(), g);
p.setPen(Qt::NoPen), p.setBrush(m_accent), p.drawRoundedRect(QRectF(0, 14, 4, height() - 28), 2, 2);
}
QVector<StatTile *> addTiles(QGridLayout *g, const QVector<QPair<QString, QColor>> &defs, int cols)
{
QVector<StatTile *> out;
g->setSpacing(14);
for (const auto &d : defs) out << new StatTile(d.first, d.second), g->addWidget(out.last(), (out.size() - 1) / cols, (out.size() - 1) % cols);
return out;
}
// ---- CoreGrid ---------------------------------------------------------------------------------------
CoreGrid::CoreGrid()
{
QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Preferred);
sp.setHeightForWidth(true);
setSizePolicy(sp);
}
void CoreGrid::setCores(const QVector<CoreStat> &c)
{
if (c.size() != m_c.size()) updateGeometry();
m_c = c, update();
}
void CoreGrid::paintEvent(QPaintEvent *)
{
AA p(this);
const int cols = qMax(1, width() / 92);
const double cw = double(width()) / cols;
for (int i = 0; i < m_c.size(); ++i) {
const double u = m_c[i].usage;
const QColor c = C::level(u, 60, 85);
const QRectF r(cw * (i % cols) + 3, i / cols * 66 + 3, cw - 6, 60), bar(r.left() + 8, r.bottom() - 10, r.width() - 16, 4);
roundedPanel(p, r, C::mix(C::card, c, u / 420), C::mix(C::border, c, u / 160), 8);
p.setPen(Qt::NoPen), p.setBrush(C::grid), p.drawRoundedRect(bar, 2, 2);
p.setBrush(c), p.drawRoundedRect(QRectF(bar.left(), bar.top(), bar.width() * u / 100, 4), 2, 2);
p.setFont(pxFont(font(), 10)), p.setPen(C::muted);
p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignLeft, QString("CPU %1").arg(i));
if (m_c[i].mhz > 0) p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignRight, QString::number(m_c[i].mhz / 1000, 'f', 1) + "G");
p.setFont(pxFont(font(), 16, true)), p.setPen(C::text);
p.drawText(r.adjusted(8, 18, -8, -14), Qt::AlignVCenter, QString::number(u, 'f', 0) + "%");
}
}
// ---- WeekHeatmap ---------------------------------------------------------------------------------------
static const QStringList kDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
WeekHeatmap::WeekHeatmap() : m_hot(C::accent)
{
std::fill(&m_v[0][0], &m_v[0][0] + 168, NAN), std::fill(&m_n[0][0], &m_n[0][0] + 168, 0);
setMouseTracking(true), setMinimumHeight(230);
}
void WeekHeatmap::setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot)
{
std::copy(&v[0][0], &v[0][0] + 168, &m_v[0][0]);
std::copy(&n[0][0], &n[0][0] + 168, &m_n[0][0]);
m_unit = unit, m_hot = hot, update();
}
QRectF WeekHeatmap::cell(int d, int h) const
{
const double cw = (width() - 44) / 24.0, ch = (height() - 30) / 7.0;
return QRectF(40 + h * cw + 1.5, 6 + d * ch + 1.5, cw - 3, ch - 3);
}
void WeekHeatmap::paintEvent(QPaintEvent *)
{
AA p(this);
p.setFont(pxFont(font(), 10));
bool any = false;
for (int d = 0; d < 7; ++d) {
p.setPen(C::muted), p.drawText(QRectF(0, cell(d, 0).top(), 34, cell(d, 0).height()), Qt::AlignRight | Qt::AlignVCenter, kDays[d].left(3));
for (int h = 0; h < 24; ++h) {
const double v = m_v[d][h];
any |= !std::isnan(v);
p.setPen(Qt::NoPen), p.setBrush(std::isnan(v) ? C::card : C::mix(0x1b2a44, m_hot, .15 + .85 * qBound(0.0, v / 100, 1.0)));
p.drawRoundedRect(cell(d, h), 3, 3);
}
}
p.setPen(C::faint);
for (int h = 0; h < 24; h += 3) p.drawText(QRectF(cell(6, h).left() - 4, cell(6, h).bottom() + 4, 40, 14), Qt::AlignLeft, QString("%1:00").arg(h, 2, 10, QChar('0')));
if (any) return;
const QRectF box(cell(2, 3).topLeft(), cell(4, 20).bottomRight());
p.fillRect(box, QColor(13, 17, 28, 200)), p.setPen(C::text), p.setFont(pxFont(font(), 12));
p.drawText(box, Qt::AlignCenter, "Collecting hourly history… the weekly pattern fills in over time");
}
void WeekHeatmap::mouseMoveEvent(QMouseEvent *e)
{
for (int d = 0; d < 7; ++d)
for (int h = 0; h < 24; ++h)
if (cell(d, h).contains(e->pos()))
return QToolTip::showText(e->globalPos(), std::isnan(m_v[d][h]) ? QString("%1 %2:00 — no data").arg(kDays[d]).arg(h)
: QString("%1 %2:00 — avg %3%4 (%5 samples)").arg(kDays[d]).arg(h).arg(m_v[d][h], 0, 'f', 1).arg(m_unit).arg(m_n[d][h]), this);
QToolTip::hideText();
}
// ---- table helpers --------------------------------------------------------------------------------------
void BarDelegate::paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const
{
const QVariant pv = i.data(Qt::UserRole);
if (!pv.isValid()) return QStyledItemDelegate::paint(p, o, i);
p->save();
p->setRenderHint(QPainter::Antialiasing);
if (o.state & QStyle::State_Selected) p->fillRect(o.rect, o.palette.highlight());
const double pct = qBound(0.0, pv.toDouble(), 100.0);
const QRectF r = QRectF(o.rect).adjusted(6, o.rect.height() / 2.0 - 7, -6, -(o.rect.height() / 2.0 - 7));
const QColor c = C::level(pct);
p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(r, 4, 4);
p->setBrush(C::tint(c, 200)), p->drawRoundedRect(QRectF(r.left(), r.top(), r.width() * pct / 100, r.height()), 4, 4);
p->setFont(pxFont(o.font, 11, true)), p->setPen(C::text), p->drawText(r, Qt::AlignCenter, i.data().toString());
p->restore();
}
int FlowLayout::place(const QRect &r, bool apply) const
{
if (m_items.isEmpty()) return 0;
const int sp = 16, minW = m_items[0]->minimumSize().width(), cols = qMax(1, (r.width() + sp) / (minW + sp)), w = (r.width() - (cols - 1) * sp) / cols;
int y = r.y(), rowH = 0, col = 0;
for (QLayoutItem *it : m_items) {
if (it->widget() && it->widget()->isHidden()) continue;
if (apply) it->setGeometry(QRect(r.x() + col * (w + sp), y, w, it->sizeHint().height()));
rowH = qMax(rowH, it->sizeHint().height());
if (++col == cols) col = 0, y += rowH + sp, rowH = 0;
}
return y + rowH - r.y();
}
// ---- builders ----------------------------------------------------------------------------------------
QLabel *label(const QString &text, const char *name, bool wrap)
{
auto *l = new QLabel(text);
if (name) l->setObjectName(name);
l->setWordWrap(wrap);
return l;
}
QPushButton *button(const QString &text, const char *style, std::function<void()> onClick)
{
auto *b = new QPushButton(text);
if (style) b->setObjectName(style);
if (onClick) QObject::connect(b, &QPushButton::clicked, b, onClick);
return b;
}
QFrame *panel(const QString &title, std::initializer_list<QWidget *> content)
{
auto *f = new QFrame;
f->setObjectName("Panel");
auto *l = new QVBoxLayout(f);
l->setContentsMargins(16, 14, 16, 14), l->setSpacing(10);
if (!title.isEmpty()) l->addWidget(label(title.toUpper(), "Section"));
for (QWidget *w : content) w ? l->addWidget(w) : l->addStretch();
return f;
}
bool ask(QWidget *parent, const QString &title, const QString &text) { return QMessageBox::question(parent, title, text) == QMessageBox::Yes; }
namespace {
struct SortItem : QTableWidgetItem { // sorts by Qt::UserRole+1 when set (numbers sort numerically)
bool operator<(const QTableWidgetItem &o) const override
{
const QVariant a = data(Qt::UserRole + 1), b = o.data(Qt::UserRole + 1);
if (!a.isValid() || !b.isValid()) return text() < o.text();
return a.type() == QVariant::String ? a.toString() < b.toString() : a.toDouble() < b.toDouble();
}
};
}
QTableWidget *table(const QStringList &headers, const QVector<int> &widths, const QVector<int> &bars)
{
auto *t = new QTableWidget(0, headers.size());
t->setHorizontalHeaderLabels(headers);
t->verticalHeader()->hide(), t->verticalHeader()->setDefaultSectionSize(30);
t->setAlternatingRowColors(true), t->setShowGrid(false), t->setWordWrap(false);
t->setSelectionBehavior(QAbstractItemView::SelectRows), t->setSelectionMode(QAbstractItemView::SingleSelection);
t->setEditTriggers(QAbstractItemView::NoEditTriggers), t->setFocusPolicy(Qt::NoFocus), t->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
t->horizontalHeader()->setHighlightSections(false), t->horizontalHeader()->setStretchLastSection(true);
t->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
for (int i = 0; i < widths.size(); ++i) t->setColumnWidth(i, widths[i]);
for (int c : bars) t->setItemDelegateForColumn(c, new BarDelegate(t));
return t;
}
void cell(QTableWidget *t, int r, int c, const Cell &x)
{
QTableWidgetItem *it = t->item(r, c);
if (!it) t->setItem(r, c, it = new SortItem);
if (it->text() != x.text) it->setText(x.text);
it->setTextAlignment(int(x.right ? Qt::AlignRight : Qt::AlignLeft) | Qt::AlignVCenter);
it->setForeground(x.color.isValid() ? x.color : C::text);
if (x.pct >= 0) it->setData(Qt::UserRole, x.pct);
if (x.key.isValid()) it->setData(Qt::UserRole + 1, x.key);
}