Publish tool cleanup and Framework monitoring refinements

This commit is contained in:
ajp_anton committed 2026-09-12 05:17:02 +00:00
1 parent db352083cf
commit 7f56368674
51 files changed
+1487 -341

No files matched your search

+125 -43
View File
@@ -2,9 +2,10 @@
#include "chart.h"
#include "graphdata.h"
#include <QPainter>
#include <QPainterPath>
#include <QMouseEvent>
#include <QToolTip>
#include <QGuiApplication>
#include <QScreen>
#include <QVector3D>
#include <algorithm>
#include <cmath>
@@ -56,17 +57,15 @@ AxisTicks AxisTicks::covering(double minimum, double maximum, int intervals)
}
double timeTickStep(double spanMs, int intervals)
{
const double target = spanMs / 1000 / std::max(1, intervals);
for (double seconds : {1., 2., 5., 10., 15., 30., 60., 120., 300., 600., 900., 1800., 3600., 7200., 10800., 21600., 43200., 86400.})
if (seconds >= target) return seconds * 1000;
return niceStep(target / 86400) * 86400000;
const double unit = spanMs >= 3600000 ? 3600000 : spanMs >= 60000 ? 60000 : 1000;
return niceStep(spanMs / unit / std::max(1, intervals)) * unit;
}
QString ageLabel(double milliseconds)
QString ageLabel(double milliseconds, double spanMs)
{
const qint64 seconds = qRound64(milliseconds / 1000);
const double seconds = milliseconds / 1000;
if (!seconds) return "Now";
if (seconds % 3600 == 0) return QString::number(seconds / 3600) + "h";
if (seconds % 60 == 0) return QString::number(seconds / 60) + "min";
if (spanMs >= 3600000) return QString::number(seconds / 3600, 'g', 3) + "h";
if (spanMs >= 60000) return QString::number(seconds / 60, 'g', 3) + "min";
return QString::number(seconds) + "s";
}
Chart::Chart(const QString &unit, QWidget *parent) : QWidget(parent), m_unit(unit)
@@ -74,11 +73,21 @@ Chart::Chart(const QString &unit, QWidget *parent) : QWidget(parent), m_unit(uni
setMinimumHeight(175);
setMouseTracking(true);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_popup = new QLabel(this, Qt::ToolTip | Qt::WindowTransparentForInput | Qt::WindowDoesNotAcceptFocus);
m_popup->setObjectName("chartReadingPopup");
m_popup->setTextFormat(Qt::PlainText);
m_popup->setPalette(QToolTip::palette());
m_popup->setBackgroundRole(QPalette::ToolTipBase);
m_popup->setForegroundRole(QPalette::ToolTipText);
m_popup->setAutoFillBackground(true);
m_popup->setMargin(6);
m_popup->setFrameStyle(QFrame::Box | QFrame::Plain);
}
void Chart::addSeries(const QString &id, const QString &name, const QString &unit)
{
m_series.insert(id, {QColor(),
name.isEmpty() ? id : name, unit.isEmpty() ? m_unit : unit, {}});
invalidatePlot();
}
void Chart::setSelected(const QString &id, bool selected)
{
@@ -89,7 +98,7 @@ void Chart::setSelected(const QString &id, bool selected)
m_series[id].color = nextColour(used);
m_selected.insert(id);
} else m_selected.remove(id);
update();
invalidatePlot();
}
QColor Chart::color(const QString &id) const
{
@@ -103,7 +112,7 @@ QVector<QPointF> Chart::history(const QString &id, double since) const
if (series == m_series.cend()) return points;
for (auto it = historyStart(series->points, since); it != series->points.cend(); ++it) {
const auto &point = *it;
if (!points.isEmpty() && (point.x() - points.last().x() > m_interval * 3 || crossesSleep(points.last().x(), point.x())))
if (!points.isEmpty() && !connectedSamples(points.last().x(), point.x()))
points.append({point.x(), NAN});
points.append(point);
}
@@ -111,7 +120,8 @@ QVector<QPointF> Chart::history(const QString &id, double since) const
}
void Chart::sample(const QMap<QString, double> &values, int intervalMs, qint64 now)
{
m_interval = intervalMs;
// Keep cadence changes with the history, not one current interval for all samples.
if (m_intervals.isEmpty() || m_intervals.last() != intervalMs) m_intervals.insert(now, intervalMs);
m_sampleTime = now;
double oldest = now;
for (auto it = m_series.begin(); it != m_series.end(); ++it) {
@@ -119,19 +129,22 @@ void Chart::sample(const QMap<QString, double> &values, int intervalMs, qint64 n
oldest = std::min(oldest, it->points.front().x());
}
m_bands.removeIf([oldest](const Band &band) { return band.end && band.end < oldest; });
update();
while (m_intervals.size() > 1 && std::next(m_intervals.cbegin()).key() <= oldest)
m_intervals.erase(m_intervals.begin());
invalidatePlot();
}
void Chart::setPowerState(bool sleeping, std::optional<bool> plugged, qint64 now)
{
// Charger state cannot be observed during suspend; don't extend AC bands through it.
const std::optional<BandType> next = sleeping ? std::optional(BandType::Sleep)
: plugged.value_or(false) ? std::optional(BandType::Plugged) : std::nullopt;
if (!next && (m_bands.isEmpty() || m_bands.last().end)) return;
if (!m_bands.isEmpty() && !m_bands.last().end) {
if (next == m_bands.last().type) return;
m_bands.last().end = now;
}
if (next) m_bands.append({now, 0, *next});
update();
invalidatePlot();
}
bool Chart::crossesSleep(double from, double to) const
{
@@ -139,11 +152,22 @@ bool Chart::crossesSleep(double from, double to) const
if (band.type == BandType::Sleep && band.begin < to && (!band.end || band.end > from)) return true;
return false;
}
int Chart::intervalAt(double time) const
{
const auto next = m_intervals.upperBound(qint64(time));
Q_ASSERT(next != m_intervals.cbegin()); // Every retained sample has a cadence entry.
return std::prev(next).value();
}
bool Chart::connectedSamples(double from, double to) const
{
const int interval = std::max(intervalAt(from), intervalAt(to));
return to - from <= interval * 3 && !crossesSleep(from, to);
}
void Chart::setHistoryWindow(qint64 spanMs, bool stretch)
{
m_historyMs = std::clamp(spanMs, qint64(300000), historyRetentionMs);
m_stretch = stretch;
update();
invalidatePlot();
}
QPair<double, double> Chart::timeRange() const
{
@@ -179,7 +203,10 @@ Chart::Frame Chart::frame() const
}
const int timeTextWidth = fm.horizontalAdvance("100min");
const int margin = std::max(fm.horizontalAdvance("−99999") + 10, unitWidth + timeTextWidth / 2 + 8);
const QRectF area(margin, fm.height() / 2 + 4, width() - margin - (secondary ? margin : 25), height() - 2 * fm.height() - 20);
QRectF area(margin, fm.height() / 2 + 4, width() - margin - (secondary ? margin : 25), height() - 2 * fm.height() - 20);
const double ratio = devicePixelRatioF();
area.setLeft(std::ceil(area.left() * ratio) / ratio);
area.setRight(std::floor(area.right() * ratio) / ratio);
const int intervals = std::max(2, int(area.height()) / (fm.height() * 2));
return {area, first, now, AxisTicks::covering(low, high, intervals),
AxisTicks::covering(low2, high2, intervals), secondary};
@@ -198,7 +225,10 @@ QString Chart::readingAt(qint64 time) const
auto next = std::lower_bound(points.cbegin(), points.cend(), double(time), [](const QPointF &p, double t) { return p.x() < t; });
const QPointF *closest = next != points.cend() ? &*next : nullptr;
if (next != points.cbegin() && (!closest || time - (next - 1)->x() < closest->x() - time)) closest = &*(next - 1);
const bool valid = !sleeping && closest && std::abs(closest->x() - time) <= m_interval * 1.5
int interval = closest ? intervalAt(closest->x()) : 0;
if (next != points.cend()) interval = std::max(interval, intervalAt(next->x()));
if (next != points.cbegin()) interval = std::max(interval, intervalAt((next - 1)->x()));
const bool valid = !sleeping && closest && std::abs(closest->x() - time) <= interval * 1.5
&& std::isfinite(closest->y()) && !crossesSleep(std::min(closest->x(), double(time)), std::max(closest->x(), double(time)));
lines.append(it->name + ": " + (valid ? number(closest->y()) + " " + it->unit : "—"));
}
@@ -206,17 +236,78 @@ QString Chart::readingAt(qint64 time) const
}
void Chart::mouseMoveEvent(QMouseEvent *event)
{
const auto f = frame();
if (!f.area.contains(event->position())) { setHoverTime(-1); Q_EMIT hovered(-1); QToolTip::hideText(); return; }
const qint64 time = qRound64(f.first + (event->position().x() - f.area.left()) / f.area.width() * (f.last - f.first));
m_hoverPosition = event->position();
refreshHover();
}
void Chart::refreshHover()
{
if (!m_hoverPosition || !isVisible()) return;
ensurePlot();
const auto &f = m_frame;
if (!f.area.contains(*m_hoverPosition)) { clearHover(); return; }
const qint64 time = qRound64(f.first + (m_hoverPosition->x() - f.area.left()) / f.area.width() * (f.last - f.first));
setHoverTime(time); Q_EMIT hovered(time);
QToolTip::showText(event->globalPosition().toPoint() + QPoint(12, 16), readingAt(time), this);
m_popup->setText(readingAt(time));
m_popup->adjustSize();
const auto cursor = mapToGlobal(m_hoverPosition->toPoint());
auto position = cursor + QPoint(12, 16);
const auto *screen = QGuiApplication::screenAt(cursor);
if (screen) {
const auto bounds = screen->availableGeometry();
position.setX(std::max(bounds.left(), std::min(position.x(), bounds.right() - m_popup->width() + 1)));
if (position.y() + m_popup->height() > bounds.bottom()) position.setY(cursor.y() - m_popup->height() - 8);
position.setY(std::max(bounds.top(), position.y()));
}
m_popup->move(position);
m_popup->show();
}
void Chart::clearHover()
{
m_hoverPosition.reset(); setHoverTime(-1); Q_EMIT hovered(-1); m_popup->hide();
}
void Chart::leaveEvent(QEvent *event) { clearHover(); QWidget::leaveEvent(event); }
void Chart::hideEvent(QHideEvent *event) { clearHover(); QWidget::hideEvent(event); }
void Chart::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); invalidatePlot(); }
void Chart::changeEvent(QEvent *event)
{
QWidget::changeEvent(event);
if (event->type() == QEvent::FontChange || event->type() == QEvent::PaletteChange
|| event->type() == QEvent::StyleChange) invalidatePlot();
}
void Chart::invalidatePlot()
{
m_plot = QPixmap();
refreshHover();
update();
}
void Chart::ensurePlot()
{
const auto pixels = size() * devicePixelRatioF();
if (!m_plot.isNull() && m_plot.size() == pixels && m_plot.devicePixelRatio() == devicePixelRatioF()) return;
m_frame = frame();
m_plot = QPixmap(pixels);
m_plot.setDevicePixelRatio(devicePixelRatioF());
m_plot.fill(Qt::transparent);
QPainter painter(&m_plot);
drawPlot(painter, m_frame);
}
void Chart::leaveEvent(QEvent *event) { setHoverTime(-1); Q_EMIT hovered(-1); QToolTip::hideText(); QWidget::leaveEvent(event); }
void Chart::paintEvent(QPaintEvent *)
{
QPainter p(this); p.setRenderHint(QPainter::Antialiasing);
const auto f = frame(); const auto area = f.area;
// Hover moves only the overlay, not the potentially 24-hour history underneath.
ensurePlot();
QPainter p(this);
p.drawPixmap(0, 0, m_plot);
const auto &f = m_frame;
if (m_hoverTime && *m_hoverTime >= f.first && *m_hoverTime <= f.last && f.area.isValid()) {
const double x = f.area.left() + (*m_hoverTime - f.first) / (f.last - f.first) * f.area.width();
p.setPen(QPen(palette().color(QPalette::Text), 1, Qt::DashLine));
p.drawLine(QPointF(x, f.area.top()), QPointF(x, f.area.bottom()));
}
}
void Chart::drawPlot(QPainter &p, const Frame &f)
{
p.setRenderHint(QPainter::Antialiasing);
const auto area = f.area;
if (area.width() <= 0 || area.height() <= 0) return;
const auto x = [&](double time) { return area.left() + (time - f.first) / (f.last - f.first) * area.width(); };
const auto y = [&](double value, const AxisTicks &axis) { return area.bottom() - (value - axis.minimum) / (axis.maximum - axis.minimum) * area.height(); };
@@ -261,34 +352,25 @@ void Chart::paintEvent(QPaintEvent *)
const double pos = x(f.last - age);
p.setPen(grid); p.drawLine(QPointF(pos, area.top()), QPointF(pos, area.bottom()));
p.setPen(text); p.drawLine(QPointF(pos, area.bottom()), QPointF(pos, area.bottom() + 6));
p.setPen(text); p.drawText(QRectF(pos - labelWidth / 2., area.bottom() + 7, labelWidth, h), Qt::AlignHCenter, ageLabel(age));
p.setPen(text); p.drawText(QRectF(pos - labelWidth / 2., area.bottom() + 7, labelWidth, h), Qt::AlignHCenter, ageLabel(age, f.last - f.first));
}
p.save(); p.setClipRect(area.adjusted(-1, -1, 1, 1));
p.save(); p.setClipRect(area.adjusted(0, -1, 0, 1));
p.setRenderHint(QPainter::Antialiasing, false);
bool hasValues = false;
for (auto it = m_series.cbegin(); it != m_series.cend(); ++it) {
if (!selected(it.key())) continue;
const auto columns = timeAverages(historyStart(it->points, f.first), it->points.cend(),
f.first, f.last, std::ceil(area.width() * devicePixelRatioF()), [this](const QPointF &a, const QPointF &b) {
return b.x() - a.x() <= m_interval * 3 && !crossesSleep(a.x(), b.x());
f.first, f.last, qRound(area.width() * devicePixelRatioF()), [this](const QPointF &a, const QPointF &b) {
return connectedSamples(a.x(), b.x());
});
const auto &scale = it->unit == m_unit ? f.left : f.right;
QColor shade = it->color; shade.setAlphaF(.20);
for (const auto &column : columns)
p.fillRect(QRectF(QPointF(x(column.begin), y(column.maximum, scale)),
QPointF(x(column.end), y(column.mean, scale))), shade);
QPainterPath line; bool connected = false;
for (const auto &point : averageLine(columns)) {
if (!std::isfinite(point.y())) { connected = false; continue; }
const QPointF position(x(point.x()), y(point.y(), scale));
if (connected) line.lineTo(position); else line.moveTo(position);
connected = true; hasValues = true;
for (const auto &column : columns) {
const double left = area.left() + column.index / devicePixelRatioF();
p.fillRect(columnBand(left, left + 1 / devicePixelRatioF(), y(column.maximum, scale),
y(column.lower(), scale), 2, devicePixelRatioF()), it->color);
}
p.setPen(QPen(it->color, 2)); p.drawPath(line);
hasValues |= !columns.isEmpty();
}
p.restore();
if (m_hoverTime && *m_hoverTime >= f.first && *m_hoverTime <= f.last) {
p.setPen(QPen(text, 1, Qt::DashLine));
p.drawLine(QPointF(x(*m_hoverTime), area.top()), QPointF(x(*m_hoverTime), area.bottom()));
}
if (!hasValues) { p.setPen(text); p.drawText(area, Qt::AlignCenter, "No selected readings available"); }
}
+18 -2
View File
@@ -5,6 +5,8 @@
#include <QMap>
#include <QSet>
#include <optional>
#include <QLabel>
#include <QPixmap>
#include "history.h"
struct AxisTicks {
@@ -12,7 +14,7 @@ struct AxisTicks {
static AxisTicks covering(double minimum, double maximum, int intervals);
};
double timeTickStep(double spanMs, int intervals);
QString ageLabel(double milliseconds);
QString ageLabel(double milliseconds, double spanMs);
class Chart : public QWidget {
Q_OBJECT
@@ -38,20 +40,34 @@ protected:
void paintEvent(QPaintEvent *) override;
void mouseMoveEvent(QMouseEvent *event) override;
void leaveEvent(QEvent *event) override;
void hideEvent(QHideEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void changeEvent(QEvent *event) override;
private:
struct Series { QColor color; QString name, unit; Samples points; };
enum class BandType { Sleep, Plugged };
struct Band { qint64 begin, end; BandType type; };
struct Frame { QRectF area; double first, last; AxisTicks left, right; bool secondary; };
Frame frame() const;
void invalidatePlot();
void ensurePlot();
void drawPlot(QPainter &painter, const Frame &frame);
void refreshHover();
void clearHover();
bool crossesSleep(double from, double to) const;
int intervalAt(double time) const;
bool connectedSamples(double from, double to) const;
QMap<QString, Series> m_series;
QSet<QString> m_selected;
QVector<Band> m_bands;
QString m_unit;
int m_interval = 1000;
QMap<qint64, int> m_intervals;
qint64 m_historyMs = historyRetentionMs;
bool m_stretch = true;
qint64 m_sampleTime = QDateTime::currentMSecsSinceEpoch();
std::optional<qint64> m_hoverTime;
std::optional<QPointF> m_hoverPosition;
QLabel *m_popup;
QPixmap m_plot;
Frame m_frame;
};
+2 -1
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MIT
#include "cpupage.h"
#include "widgets.h"
#include <QFormLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
@@ -33,7 +34,7 @@ void CpuPage::Editor::setValue(const QVariantMap &value)
}
CpuPage::Editor CpuPage::makeEditor(const QString &name)
{
Editor editor{new QGroupBox(name), new QCheckBox("Override frequency bounds"),
Editor editor{sectionGroup(name), new QCheckBox("Override frequency bounds"),
new ValueControl, new ValueControl, new QComboBox, new QComboBox, new QLabel};
editor.frequency->setObjectName("overrideFrequency");
editor.governor->setObjectName("cpuGovernor"); editor.preference->setObjectName("cpuPreference");
+19 -17
View File
@@ -1,13 +1,16 @@
// SPDX-License-Identifier: MIT
#pragma once
#include <QPointF>
#include <QRectF>
#include <QVector>
#include <algorithm>
#include <cmath>
struct AverageColumn {
double begin, end, mean, maximum;
bool startsRun;
double begin, end, mean, maximum, minimum;
bool compressed;
int index;
double lower() const { return compressed ? mean : minimum; }
};
// Integrate the piecewise-linear signal over each pixel's time interval.
@@ -35,31 +38,30 @@ QVector<AverageColumn> timeAverages(Iterator begin, Iterator end, double first,
if (stop <= left) continue; // A boundary can round back to the preceding column.
const auto valueAt = [&](double t) { return a.y() + (b.y() - a.y()) * ((t - a.x()) / (b.x() - a.x())); };
const double low = valueAt(left), high = valueAt(stop);
const double mean = (low + high) / 2, maximum = std::max(low, high);
const double mean = (low + high) / 2, maximum = std::max(low, high), minimum = std::min(low, high);
// Choose locally so histories with changing sampling intervals also work.
const bool compressed = b.x() - a.x() < step;
if (!startsRun && previousColumn == column) {
auto &bucket = result.last();
bucket.mean += (mean - bucket.mean) * ((stop - left) / (stop - bucket.begin));
bucket.maximum = std::max(bucket.maximum, maximum);
bucket.minimum = std::min(bucket.minimum, minimum);
bucket.compressed |= compressed;
bucket.end = stop;
} else result.append({left, stop, mean, maximum, startsRun});
} else result.append({left, stop, mean, maximum, minimum, compressed, column});
startsRun = false; previousColumn = column; left = stop;
}
}
return result;
}
inline QVector<QPointF> averageLine(const QVector<AverageColumn> &columns)
// Fill the covered vertical pixels, padding short bands equally above and below.
// X boundaries are untouched: neither slope nor thickness widens a column.
inline QRectF columnBand(double left, double right, double top, double bottom,
double minimumHeight = 2, double pixelRatio = 1)
{
QVector<QPointF> points;
for (int i = 0; i < columns.size(); ++i) {
const auto &column = columns[i];
if (column.startsRun) {
if (!points.isEmpty()) points.append({column.begin, NAN});
points.append({column.begin, column.mean});
}
points.append({(column.begin + column.end) / 2, column.mean});
if (i + 1 == columns.size() || columns[i + 1].startsRun)
points.append({column.end, column.mean});
}
return points;
const double padding = std::max(0., minimumHeight - (bottom - top)) / 2;
top = std::floor((top - padding) * pixelRatio) / pixelRatio;
bottom = std::ceil((bottom + padding) * pixelRatio) / pixelRatio;
return QRectF(QPointF(left, top), QPointF(right, bottom));
}
+22 -19
View File
@@ -10,6 +10,19 @@
#include <QProcess>
#include <QSaveFile>
namespace {
QString saveConfig(const QString &path, const QVariantMap &config)
{
if (!QDir().mkpath(QFileInfo(path).absolutePath())) return "Cannot create settings directory.";
QSaveFile file(path);
if (!file.open(QIODevice::WriteOnly)
|| !file.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) return file.errorString();
const auto data = QJsonDocument::fromVariant(config).toJson(QJsonDocument::Compact);
if (file.write(data) != data.size() || !file.commit()) return file.errorString();
return {};
}
}
class Helper : public QObject {
Q_OBJECT
KAuth::ActionReply reply(const QString &error, const QVariantMap &data = {}) {
@@ -20,7 +33,9 @@ class Helper : public QObject {
QProcess process;
process.start("/usr/bin/systemctl", {verb, unit});
if (!process.waitForFinished(25000)) { process.kill(); process.waitForFinished(); return "Service did not respond."; }
return process.exitCode() == 0 ? QString() : QString::fromUtf8(process.readAllStandardError());
if (process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0) return {};
const auto error = QString::fromUtf8(process.readAllStandardError()).trimmed();
return error.isEmpty() ? "Service operation failed: " + verb + " " + unit : error;
}
public Q_SLOTS:
KAuth::ActionReply inspect(const QVariantMap &) {
@@ -50,7 +65,6 @@ public Q_SLOTS:
}
}
}
data["fanPersistent"] = QFile::exists(savedFanConfigPath);
return reply({}, data);
}
KAuth::ActionReply configure(const QVariantMap &args) {
@@ -80,12 +94,8 @@ public Q_SLOTS:
const auto config = normalizeCpuConfig(args.value("config").toMap());
error = validateCpuConfig(config);
if (!error.isEmpty()) return reply(error);
if (!QDir().mkpath("/etc/framework-laptop-tools")) return reply("Cannot create CPU configuration directory.");
QSaveFile file(cpuConfigPath);
if (!file.open(QIODevice::WriteOnly)) return reply(file.errorString());
file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
const auto data = QJsonDocument::fromVariant(config).toJson();
if (file.write(data) != data.size() || !file.commit()) return reply(file.errorString());
error = saveConfig(cpuConfigPath, config);
if (!error.isEmpty()) return reply(error);
const QString unit = "framework-laptop-tools-cpu.service";
if (hasCpuOverrides(config)) {
error = service("enable", unit);
@@ -101,23 +111,16 @@ public Q_SLOTS:
// Restore the old worker before replacing its configuration.
error = service("stop");
if (!error.isEmpty()) return reply(error);
if (QFile::exists(savedFanConfigPath) && !QFile::remove(savedFanConfigPath)) return reply("Cannot remove saved fan settings.");
const bool persistent = args.value("mode") != "auto";
if (!persistent && QFile::exists(savedFanConfigPath) && !QFile::remove(savedFanConfigPath))
return reply("Cannot remove saved fan settings.");
error = service(persistent ? "enable" : "disable");
if (error.isEmpty()) error = service(persistent ? "enable" : "disable", "framework-laptop-tools-fan-resume.service");
if (!error.isEmpty()) return reply(error);
if (args.value("mode") == "auto") error = restoreFan();
else {
const QString path = persistent ? savedFanConfigPath : fanConfigPath;
if (!QDir().mkpath(QFileInfo(path).absolutePath())) error = "Cannot create fan settings directory.";
if (error.isEmpty()) {
QSaveFile file(path);
if (!file.open(QIODevice::WriteOnly)) return reply(file.errorString());
file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
const auto data = QJsonDocument::fromVariant(args).toJson(QJsonDocument::Compact);
if (file.write(data) != data.size() || !file.commit()) return reply(file.errorString());
error = service("start");
}
error = saveConfig(savedFanConfigPath, args);
if (error.isEmpty()) error = service("start");
}
} else if (operation == "powerAuto") error = setFirmwareValue(operation, 0);
else if (value >= 0) error = setFirmwareValue(operation, value);
+83
View File
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: MIT
#include "power.h"
#include <QDir>
#include <QFileInfo>
#include <QSet>
std::optional<double> EnergyCounter::sample(quint64 energy, quint64 range, qint64 timeMs, int maxGapMs)
{
const auto previous = m_previous;
m_previous = Reading{energy, range, timeMs};
if (!range || energy > range) { m_previous.reset(); return {}; }
if (!previous || previous->range != range) return {};
const qint64 elapsed = timeMs - previous->time;
if (elapsed <= 0 || elapsed > maxGapMs) return {};
quint64 delta;
if (energy >= previous->energy) delta = energy - previous->energy;
else {
// A small backwards jump is a reset, not a nearly full counter's worth of energy.
if (previous->energy - energy < range / 2) return {};
delta = range - previous->energy + energy;
}
return double(delta) / (1000. * elapsed); // microjoules / milliseconds -> watts
}
PowerMonitor::PowerMonitor(const QString &sys)
{
m_clock.start();
const QDir powercap(sys + "/class/powercap");
auto zones = powercap.entryList({"intel-rapl:*"}, QDir::Dirs | QDir::NoDotAndDotDot);
QString prefix = "intel-rapl:";
// MSR and MMIO interfaces can expose the same domains. Use one, not both.
if (zones.isEmpty()) {
prefix = "intel-rapl-mmio:";
zones = powercap.entryList({prefix + "*"}, QDir::Dirs | QDir::NoDotAndDotDot);
}
const QMap<QString, QString> names{{"core", "CPU cores"}, {"uncore", "Uncore"},
{"dram", "Memory (RAPL)"}};
for (const auto &zone : zones) {
const QString name = readText(powercap.filePath(zone + "/name"));
// PSYS watts contradicted battery draw on the tested hardware; do not expose them.
if (name == "psys" || name.startsWith("psys-")) continue;
const QString path = powercap.filePath(zone + "/energy_uj");
if (name.isEmpty() || !QFileInfo::exists(path)) continue;
const QString label = name == "package-0" ? "CPU package" : names.value(name, name);
m_sensors.append({"power/rapl/" + zone.mid(prefix.size()), label, path, "W"});
}
const QDir hwmon(sys + "/class/hwmon");
for (const auto &entry : hwmon.entryList({"hwmon*"}, QDir::Dirs | QDir::NoDotAndDotDot)) {
const QDir dir(hwmon.filePath(entry));
const QString chip = readText(dir.filePath("name"));
// ACPI fan power is a firmware table entry, often absent, not live telemetry.
if (chip == "acpi_fan") continue;
QSet<QString> added;
for (const auto &file : dir.entryList({"power*_input", "power*_average"}, QDir::Files)) {
const QString stem = file.section('_', 0, 0);
if (added.contains(stem)) continue;
added.insert(stem);
const QString input = dir.filePath(stem + "_input");
const QString path = QFileInfo::exists(input) ? input : dir.filePath(file);
const QString raw = readText(dir.filePath(stem + "_label"));
const QString label = chip + " — " + (raw.isEmpty() ? stem : raw);
m_sensors.append({"power/" + chip + "/" + stem, label, path, "W", 1e-6});
}
}
}
QMap<QString, double> PowerMonitor::sample(int intervalMs, qint64 timeMs)
{
if (timeMs < 0) timeMs = m_clock.elapsed();
QMap<QString, double> values;
for (const auto &sensor : m_sensors) {
std::optional<double> watts;
if (sensor.path.endsWith("/energy_uj")) {
bool energyOk, rangeOk;
const quint64 energy = readText(sensor.path).toULongLong(&energyOk);
const quint64 range = readText(QFileInfo(sensor.path).dir().filePath("max_energy_range_uj")).toULongLong(&rangeOk);
if (energyOk && rangeOk) watts = m_counters[sensor.id].sample(energy, range, timeMs, 3 * intervalMs);
else m_counters.remove(sensor.id); // Don't bridge a failed read with the next sample.
} else watts = sensorValue(sensor);
if (watts && *watts >= 0) values[sensor.id] = *watts;
}
return values;
}
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: MIT
#pragma once
#include "hardware.h"
#include <QElapsedTimer>
class EnergyCounter {
public:
std::optional<double> sample(quint64 energy, quint64 range, qint64 timeMs, int maxGapMs);
private:
struct Reading { quint64 energy, range; qint64 time; };
std::optional<Reading> m_previous;
};
class PowerMonitor {
public:
explicit PowerMonitor(const QString &sys = QStringLiteral("/sys"));
const QVector<Sensor> &sensors() const { return m_sensors; }
QMap<QString, double> sample(int intervalMs, qint64 timeMs = -1);
void reset() { m_counters.clear(); }
private:
QVector<Sensor> m_sensors;
QMap<QString, EnergyCounter> m_counters;
QElapsedTimer m_clock;
};
+3 -2
View File
@@ -76,9 +76,10 @@ QVector<BusyApp> ProcessUsage::sample(std::optional<quint64> totalDelta, const Q
QVector<BusyApp> apps;
for (auto it = usage.cbegin(); it != usage.cend(); ++it)
apps.append({names[it.key()], std::min(100., 100. * *it / *totalDelta)});
std::stable_sort(apps.begin(), apps.end(), [](const BusyApp &a, const BusyApp &b) {
const auto count = std::min(qsizetype(3), apps.size());
std::partial_sort(apps.begin(), apps.begin() + count, apps.end(), [](const BusyApp &a, const BusyApp &b) {
return a.percent == b.percent ? a.name < b.name : a.percent > b.percent;
});
if (apps.size() > 3) apps.resize(3);
apps.resize(count);
return apps;
}
+19 -37
View File
@@ -2,7 +2,6 @@
#include "tray.h"
#include "graphdata.h"
#include <QPainter>
#include <QPainterPath>
#include <cmath>
#include <algorithm>
@@ -28,12 +27,12 @@ std::optional<double> CpuUsage::sample(const QString &procStat)
}
QRectF trayPlotRect(bool border)
{
// Two-pixel border; leave room for the graph's two-pixel stroke inside it.
// Two-pixel border; reserve space for the graph's vertical padding inside it.
return border ? QRectF(3, 3, 58, 58) : QRectF(1, 1, 62, 62);
}
QIcon telemetryIcon(bool graph, const QVector<QPointF> &values, const QString &unit, const TrayStyle &style, qint64 now)
{
QPixmap pixmap(64, 64); pixmap.fill(style.transparent ? Qt::transparent : style.backgroundColor);
QPixmap pixmap(64, 64); pixmap.fill(style.backgroundColor);
QPainter p(&pixmap); p.setRenderHint(QPainter::Antialiasing);
if (style.border) { p.setPen(QPen(style.borderColor, 2)); p.drawRect(QRectF(1, 1, 62, 62)); }
const auto area = trayPlotRect(style.border);
@@ -42,47 +41,30 @@ QIcon telemetryIcon(bool graph, const QVector<QPointF> &values, const QString &u
if (graph && !values.isEmpty() && style.maximum > style.minimum) {
const double last = now;
const double first = last - style.historyMs;
const double span = std::max(1., last - first);
p.save(); p.setClipRect(area.adjusted(-1, -1, 1, 1));
const auto position = [&](const QPointF &point) {
const double fraction = std::clamp((point.y() - style.minimum) / (style.maximum - style.minimum), 0., 1.);
return QPointF(area.left() + (point.x() - first) / span * area.width(), area.bottom() - fraction * area.height());
p.save(); p.setClipRect(area.adjusted(0, -1, 0, 1));
p.setRenderHint(QPainter::Antialiasing, false);
const auto y = [&](double value) {
const double fraction = std::clamp((value - style.minimum) / (style.maximum - style.minimum), 0., 1.);
return area.bottom() - fraction * area.height();
};
const auto outside = [&](double y) { return y < style.minimum || y > style.maximum; };
const auto color = [&](bool out) { return out && style.overflowColor ? style.outsideColor : style.lineColor; };
const auto columns = timeAverages(values.cbegin(), values.cend(), first, last, std::ceil(area.width()),
[](const QPointF &, const QPointF &) { return true; });
for (const auto &column : columns) {
QColor shade = style.lineColor; shade.setAlphaF(shade.alphaF() * .20);
p.fillRect(QRectF(position({column.begin, column.maximum}), position({column.end, column.mean})), shade);
}
const auto averages = averageLine(columns);
QPainterPath line, overflow, fill;
for (int i = 1; i < averages.size(); ++i) {
const auto a = averages[i - 1], b = averages[i];
if (b.x() < first || a.x() > last) continue;
if (!std::isfinite(a.y()) || !std::isfinite(b.y())) continue;
QVector<double> cuts{0, 1};
if (a.y() != b.y()) for (double boundary : {style.minimum, style.maximum}) {
const double t = (boundary - a.y()) / (b.y() - a.y());
if (t > 0 && t < 1) cuts.append(t);
}
std::sort(cuts.begin(), cuts.end());
for (int j = 1; j < cuts.size(); ++j) {
const bool out = outside(a.y() + (b.y() - a.y()) * (cuts[j - 1] + cuts[j]) / 2);
if (out && !style.clamp) continue;
const auto left = position(a + (b - a) * cuts[j - 1]), right = position(a + (b - a) * cuts[j]);
if (style.fill) {
fill.moveTo(left); fill.lineTo(right);
fill.lineTo(right.x(), area.bottom()); fill.lineTo(left.x(), area.bottom()); fill.closeSubpath();
}
auto &path = out ? overflow : line;
path.moveTo(left); path.lineTo(right);
const double left = area.left() + column.index, right = left + 1;
const double top = y(column.maximum), bottom = y(column.lower());
const bool visible = column.maximum >= style.minimum && column.lower() <= style.maximum;
if (style.fill && (visible || style.clamp))
p.fillRect(QRectF(left, bottom, 1, area.bottom() - bottom), style.fillColor);
if (visible)
p.fillRect(columnBand(left, right, top, bottom), style.lineColor);
if (style.clamp) {
if (column.maximum > style.maximum)
p.fillRect(columnBand(left, right, area.top(), area.top()), color(true));
if (column.lower() < style.minimum)
p.fillRect(columnBand(left, right, area.bottom(), area.bottom()), color(true));
}
}
if (style.fill) p.fillPath(fill, style.fillColor);
p.setPen(QPen(color(false), 2, Qt::SolidLine, Qt::RoundCap)); p.drawPath(line);
p.setPen(QPen(color(true), 2, Qt::SolidLine, Qt::RoundCap)); p.drawPath(overflow);
p.restore();
} else {
const QString value = !std::isfinite(latest) ? "—" : unit == "MHz"
+1 -1
View File
@@ -17,7 +17,7 @@ private:
std::optional<quint64> m_delta;
};
struct TrayStyle {
bool border = true, transparent = false, fill = true, clamp = true, overflowColor = true;
bool border = true, fill = true, clamp = true, overflowColor = true;
QColor borderColor, backgroundColor, fillColor, lineColor, outsideColor;
double minimum = 0, maximum = 100;
qint64 historyMs = 60000;
+189 -11
View File
@@ -2,6 +2,7 @@
#include "traypage.h"
#include "colorbutton.h"
#include "tooltip.h"
#include "widgets.h"
#include <QGroupBox>
#include <QSpinBox>
#include <QVBoxLayout>
@@ -9,11 +10,36 @@
#include <QColorDialog>
#include <QLabel>
#include <QSignalBlocker>
#include <QSlider>
#include <QGridLayout>
#include <QResizeEvent>
#include <QToolButton>
namespace {
QVariantMap trayValues(QSettings &settings)
{
QVariantMap values;
for (const auto &key : settings.allKeys()) if (key.startsWith("tray/")) values[key] = settings.value(key);
return values;
}
QVariantMap migrateBackground(QVariantMap values, const QColor &fallback)
{
if (values.value("tray/transparent").toBool()) {
QColor colour(values.value("tray/backgroundColor", fallback.name(QColor::HexArgb)).toString());
if (!colour.isValid()) colour = fallback;
colour.setAlpha(0); values["tray/backgroundColor"] = colour.name(QColor::HexArgb);
}
values.remove("tray/transparent");
return values;
}
}
TrayPage::TrayPage(QSettings &settings, const QVector<Sensor> &sensors, QWidget *parent)
: QWidget(parent), m_sensors(sensors)
: TrayPage(trayValues(settings), sensors, parent) {}
TrayPage::TrayPage(const QVariantMap &values, const QVector<Sensor> &sensors, QWidget *parent)
: QWidget(parent), m_values(migrateBackground(values, palette().color(QPalette::Window))), m_sensors(sensors)
{
for (const auto &key : settings.allKeys()) if (key.startsWith("tray/")) m_values[key] = settings.value(key);
auto *layout = new QVBoxLayout(this);
auto *form = new QFormLayout; form->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint); layout->addLayout(form);
m_mode = new QComboBox; m_mode->setObjectName("trayDisplayMode");
@@ -56,10 +82,11 @@ TrayPage::TrayPage(QSettings &settings, const QVector<Sensor> &sensors, QWidget
};
m_border = check(colors, "Show border", "border", true);
auto *borderColor = colorRow(colors, "Border colour:", "borderColor", palette().color(QPalette::WindowText));
borderColor->setEnabled(m_border->isChecked()); connect(m_border, &QCheckBox::toggled, borderColor, &QWidget::setEnabled);
m_transparent = check(colors, "Transparent background", "transparent", false);
auto *background = colorRow(colors, "Background colour:", "backgroundColor", palette().color(QPalette::Window));
background->setDisabled(m_transparent->isChecked()); connect(m_transparent, &QCheckBox::toggled, background, &QWidget::setDisabled);
colors->setRowVisible(borderColor, m_border->isChecked());
connect(m_border, &QCheckBox::toggled, this, [colors, borderColor](bool enabled) {
colors->setRowVisible(borderColor, enabled);
});
colorRow(colors, "Background colour:", "backgroundColor", palette().color(QPalette::Window), true);
colorRow(colors, "Line / number colour:", "lineColor", QColor("#3daee9"));
layout->addWidget(appearance);
m_graphSettings = new QWidget; m_scaleLayout = new QFormLayout(m_graphSettings); m_scaleLayout->setContentsMargins(0, 0, 0, 0);
@@ -132,7 +159,10 @@ TrayPage::TrayPage(QSettings &settings, const QVector<Sensor> &sensors, QWidget
m_outside->setCurrentIndex(std::max(0, m_outside->findData(m_values.value("tray/outside", "clamp"))));
syncMode(); syncOutside();
});
auto *hover = new QGroupBox("Hover information"); auto *hoverForm = new QFormLayout(hover);
auto *hoverTitle = new QLabel("Hover information"); hoverTitle->setObjectName("trayHoverTitle");
layout->addWidget(hoverTitle);
auto *hover = new QWidget; hover->setObjectName("trayHoverSettings");
auto *hoverForm = new QFormLayout(hover); hoverForm->setContentsMargins(24, 0, 0, 0);
auto *cpu = check(hoverForm, "CPU usage", "hover/cpu", true);
auto *appOptions = new QWidget; auto *appForm = new QHBoxLayout(appOptions); appForm->setContentsMargins(24, 0, 0, 0);
auto *topApps = new QSpinBox; topApps->setObjectName("hover/topApps"); topApps->setRange(0, 3);
@@ -161,9 +191,11 @@ TrayPage::TrayPage(QSettings &settings, const QVector<Sensor> &sensors, QWidget
}
void TrayPage::load(const QVariantMap &values)
{
m_loading = true; m_values = values;
m_loading = true;
const auto migrated = migrateBackground(values, palette().color(QPalette::Window));
m_values = migrated;
for (const auto &reload : m_reload) reload();
m_values = values; loadScale(); m_loading = false;
m_values = migrated; loadScale(); m_loading = false;
}
QString TrayPage::scaleKey(const QString &suffix) const { return "tray/scales/" + metric().id + "/" + suffix; }
void TrayPage::loadScale()
@@ -174,7 +206,7 @@ void TrayPage::loadScale()
m_scaleLayout->setRowVisible(m_minimum, temperature || rate); m_scaleLayout->setRowVisible(m_maximum, temperature || frequency || rate);
for (auto *spin : {m_minimum, m_maximum}) { spin->setDecimals(0); spin->setRange(rate ? -300 : temperature ? -50 : 0, frequency ? 20000 : 300); spin->setSuffix(" " + unit); }
double maximum = frequency ? (metric().id == "cpu" ? cpuLimits().value("high", 5000).toDouble() : 3000) : rate ? 75 : 100;
const double low = m_values.value(scaleKey("minimum"), rate ? -75 : 0).toDouble();
const double low = m_values.value(scaleKey("minimum"), rate && !metric().id.startsWith("power/") ? -75 : 0).toDouble();
maximum = m_values.value(scaleKey("maximum"), maximum).toDouble();
m_minimum->setValue(low); m_maximum->setMinimum(m_minimum->value() + 1); m_maximum->setValue(maximum);
m_minimum->setMaximum(m_maximum->value() - 1);
@@ -187,7 +219,7 @@ TrayStyle TrayPage::iconStyle() const
};
TrayStyle s;
s.historyMs = m_history->currentData().toLongLong();
s.border = m_border->isChecked(); s.transparent = m_transparent->isChecked(); s.fill = m_fill->isChecked();
s.border = m_border->isChecked(); s.fill = m_fill->isChecked();
s.clamp = m_outside->currentData() == "clamp"; s.overflowColor = m_overflowColor->isChecked();
s.borderColor = color("borderColor", palette().color(QPalette::WindowText));
s.backgroundColor = color("backgroundColor", palette().color(QPalette::Window));
@@ -197,3 +229,149 @@ TrayStyle TrayPage::iconStyle() const
else if (metric().unit == "°C" || metric().unit == "W") { s.minimum = m_minimum->value(); s.maximum = m_maximum->value(); }
return s;
}
TrayIconsPage::TrayIconsPage(QSettings &settings, const QVector<Sensor> &sensors, QWidget *parent)
: QWidget(parent), m_sensors(sensors)
{
auto *layout = new QVBoxLayout(this);
layout->setSizeConstraint(QLayout::SetNoConstraint);
auto *countRow = new QHBoxLayout;
m_count = new JumpSlider(Qt::Horizontal); m_count->setObjectName("trayIconCount");
m_count->setRange(1, 10); m_count->setTickInterval(1); m_count->setTickPosition(QSlider::TicksBelow);
auto *label = new QLabel("Number of icons:"); label->setBuddy(m_count);
auto *number = new QLabel; number->setMinimumWidth(fontMetrics().horizontalAdvance("10"));
countRow->addWidget(label); countRow->addWidget(m_count); countRow->addWidget(number);
layout->addLayout(countRow);
m_grid = new QGridLayout; layout->addLayout(m_grid); layout->addStretch();
connect(m_count, &QSlider::valueChanged, this, [this, number](int count) {
number->setNum(count); setCount(count);
if (!m_loading) Q_EMIT settingsChanged();
});
load(trayValues(settings)); number->setNum(m_count->value());
}
void TrayIconsPage::setCount(int count)
{
while (m_pages.size() < count) {
const int index = m_pages.size();
auto *group = sectionGroup({}, this);
group->setAccessibleName(QString("Icon %1").arg(index + 1));
auto *layout = new QVBoxLayout(group);
auto *heading = new QHBoxLayout;
auto *title = new QLabel(group->accessibleName()); title->setObjectName("trayIconTitle");
auto font = title->font(); font.setPointSizeF(font.pointSizeF() + 2); title->setFont(font);
heading->addWidget(title); heading->addSpacing(12);
auto *left = new QToolButton; left->setObjectName("moveIconLeft"); left->setArrowType(Qt::LeftArrow);
auto *right = new QToolButton; right->setObjectName("moveIconRight"); right->setArrowType(Qt::RightArrow);
left->setToolTip("Move to the previous icon position"); right->setToolTip("Move to the next icon position");
left->setAccessibleName("Move icon left"); right->setAccessibleName("Move icon right");
heading->addWidget(left); heading->addWidget(new QLabel("Move icon")); heading->addWidget(right); heading->addStretch();
layout->addLayout(heading);
m_moveLeft.append(left); m_moveRight.append(right);
connect(left, &QToolButton::clicked, this, [this, index] { moveIcon(index, index - 1); });
connect(right, &QToolButton::clicked, this, [this, index] { moveIcon(index, index + 1); });
auto *page = new TrayPage(QVariantMap{}, m_sensors);
layout->addWidget(page);
// Measure the full editor, including graph controls, before hiding them again.
auto *mode = page->findChild<QComboBox *>("trayDisplayMode");
mode->setCurrentIndex(mode->findData("graph"));
group->setMinimumWidth(group->sizeHint().width());
mode->setCurrentIndex(mode->findData("icon"));
m_groups.append(group); m_pages.append(page);
connect(page, &TrayPage::settingsChanged, this, [this] {
if (!m_loading) Q_EMIT settingsChanged();
});
}
for (int i = 0; i < m_groups.size(); ++i) {
m_groups[i]->setVisible(i < count);
m_moveLeft[i]->setEnabled(i > 0 && i < count);
m_moveRight[i]->setEnabled(i + 1 < count);
}
m_columns = 0; arrange();
}
void TrayIconsPage::moveIcon(int from, int to)
{
if (to < 0 || to >= m_count->value()) return;
const auto moving = m_pages[from]->draft();
m_pages[from]->load(m_pages[to]->draft());
m_pages[to]->load(moving);
Q_EMIT settingsChanged();
}
void TrayIconsPage::arrange()
{
if (m_groups.isEmpty()) return;
const int spacing = m_grid->horizontalSpacing();
const int available = contentsRect().width() - layout()->contentsMargins().left() - layout()->contentsMargins().right();
int cardWidth = 0;
for (int i = 0; i < m_count->value(); ++i) cardWidth = std::max(cardWidth, m_groups[i]->minimumWidth());
const int columns = std::clamp((available + spacing) / (cardWidth + spacing), 1, m_count->value());
if (columns == m_columns) return;
for (int column = 0; column < m_grid->columnCount(); ++column) m_grid->setColumnStretch(column, 0);
while (auto *item = m_grid->takeAt(0)) delete item;
for (int i = 0; i < m_count->value(); ++i) m_grid->addWidget(m_groups[i], i / columns, i % columns, Qt::AlignTop);
for (int column = 0; column < columns; ++column) m_grid->setColumnStretch(column, 1);
m_columns = columns;
}
void TrayIconsPage::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event); arrange();
}
QSize TrayIconsPage::minimumSizeHint() const
{
// Multiple columns must not prevent the containing scroll area shrinking to one.
int width = m_count->minimumSizeHint().width();
for (const auto *group : m_groups) width = std::max(width, group->minimumWidth());
const auto margins = layout()->contentsMargins();
return {width + margins.left() + margins.right(), layout()->minimumSize().height()};
}
QVariantMap TrayIconsPage::draft() const
{
QVariantMap result{{"tray/count", m_count->value()}};
for (int i = 0; i < m_count->value(); ++i) {
const auto values = m_pages[i]->draft();
const QString prefix = QString("tray/icons/%1/").arg(i + 1);
for (auto it = values.cbegin(); it != values.cend(); ++it) result[prefix + it.key().mid(5)] = it.value();
}
return result;
}
QVector<TrayConfiguration> TrayIconsPage::configurations() const
{
QVector<TrayConfiguration> result;
for (int i = 0; i < m_count->value(); ++i) {
const auto *page = m_pages[i];
result.append({page->mode(), page->metric(), page->iconStyle(), page->draft()});
}
return result;
}
void TrayIconsPage::load(const QVariantMap &values)
{
m_loading = true;
const int count = std::clamp(values.value("tray/count", 1).toInt(), 1, 10);
m_count->setValue(count); setCount(count);
for (int i = 0; i < count; ++i) {
QVariantMap icon;
const bool legacy = i == 0 && !values.contains("tray/count");
const QString prefix = legacy ? "tray/" : QString("tray/icons/%1/").arg(i + 1);
for (auto it = values.cbegin(); it != values.cend(); ++it)
if (it.key().startsWith(prefix)) icon["tray/" + it.key().mid(prefix.size())] = it.value();
// Normalise defaults and legacy values through the same single-icon editor.
TrayPage defaults(icon, m_sensors);
m_pages[i]->load(defaults.draft());
}
discardHidden(); m_loading = false;
}
void TrayIconsPage::discardHidden()
{
while (m_pages.size() > m_count->value()) {
m_moveLeft.removeLast(); m_moveRight.removeLast();
m_pages.removeLast(); delete m_groups.takeLast();
}
}
+40 -1
View File
@@ -9,11 +9,23 @@
#include <QCheckBox>
#include <QFormLayout>
#include <functional>
class QSlider;
class QGridLayout;
class QGroupBox;
class QToolButton;
struct TrayConfiguration {
QString mode;
Sensor metric;
TrayStyle style;
QVariantMap values;
};
class TrayPage : public QWidget {
Q_OBJECT
public:
TrayPage(QSettings &settings, const QVector<Sensor> &sensors, QWidget *parent = nullptr);
TrayPage(const QVariantMap &values, const QVector<Sensor> &sensors, QWidget *parent = nullptr);
QString mode() const { return m_mode->currentData().toString(); }
Sensor metric() const { return m_sensors[m_metric->currentIndex()]; }
TrayStyle iconStyle() const;
@@ -32,5 +44,32 @@ private:
QDoubleSpinBox *m_minimum, *m_maximum;
QFormLayout *m_scaleLayout;
QWidget *m_graphSettings;
QCheckBox *m_border, *m_transparent, *m_fill, *m_overflowColor;
QCheckBox *m_border, *m_fill, *m_overflowColor;
};
class TrayIconsPage : public QWidget {
Q_OBJECT
public:
TrayIconsPage(QSettings &settings, const QVector<Sensor> &sensors, QWidget *parent = nullptr);
QVariantMap draft() const;
QVector<TrayConfiguration> configurations() const;
void load(const QVariantMap &values);
void discardHidden();
QSize minimumSizeHint() const override;
Q_SIGNALS:
void settingsChanged();
protected:
void resizeEvent(QResizeEvent *event) override;
private:
void setCount(int count);
void arrange();
void moveIcon(int from, int to);
QVector<Sensor> m_sensors;
QVector<TrayPage *> m_pages;
QVector<QGroupBox *> m_groups;
QVector<QToolButton *> m_moveLeft, m_moveRight;
QSlider *m_count;
QGridLayout *m_grid;
bool m_loading = false;
int m_columns = 0;
};
+2 -1
View File
@@ -1,11 +1,12 @@
// SPDX-License-Identifier: MIT
#include "valuecontrol.h"
#include "widgets.h"
#include <QHBoxLayout>
#include <QSignalBlocker>
#include <algorithm>
ValueControl::ValueControl(QWidget *parent) : QWidget(parent),
m_slider(new QSlider(Qt::Horizontal, this)), m_number(new QSpinBox(this))
m_slider(new JumpSlider(Qt::Horizontal, this)), m_number(new QSpinBox(this))
{
auto *layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
+39
View File
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: MIT
#pragma once
#include <QApplication>
#include <QGroupBox>
#include <QProxyStyle>
#include <QSlider>
inline QGroupBox *sectionGroup(const QString &title, QWidget *parent = nullptr)
{
auto *group = new QGroupBox(title, parent);
group->setObjectName("settingsSection");
group->setProperty("sectionTitle", true);
group->setStyleSheet(QString("QGroupBox[sectionTitle=\"true\"] { font-size: %1pt; }")
.arg(group->font().pointSizeF() + 2));
return group;
}
class SliderStyle : public QProxyStyle {
public:
using QProxyStyle::QProxyStyle;
int styleHint(StyleHint hint, const QStyleOption *option = nullptr,
const QWidget *widget = nullptr, QStyleHintReturn *data = nullptr) const override
{
if (hint == SH_Slider_AbsoluteSetButtons)
return QProxyStyle::styleHint(hint, option, widget, data) | Qt::LeftButton;
if (hint == SH_Slider_PageSetButtons)
return QProxyStyle::styleHint(hint, option, widget, data) & ~Qt::LeftButton;
return QProxyStyle::styleHint(hint, option, widget, data);
}
};
class JumpSlider : public QSlider {
public:
explicit JumpSlider(Qt::Orientation orientation, QWidget *parent = nullptr) : QSlider(orientation, parent)
{
auto *proxy = new SliderStyle(QApplication::style()->name());
proxy->setParent(this); setStyle(proxy);
}
};
+70 -37
View File
@@ -3,6 +3,7 @@
#include "legend.h"
#include "fan.h"
#include "tooltip.h"
#include "widgets.h"
#include <QMessageBox>
#include <KAuth/Action>
#include <KAuth/ExecuteJob>
@@ -61,7 +62,6 @@ Window::Window() : m_settings("fedora-tools", "framework-laptop-tools"),
addPage(trayPage(), "Tray icon");
addPage(preferencesPage(), "Preferences");
m_savedTray = m_trayPage->draft(); m_savedPreferences = preferenceValues();
m_trayMetric = m_trayPage->metric(); m_trayMode = m_trayPage->mode(); m_trayStyle = m_trayPage->iconStyle();
for (const auto &key : {"keyboard", "power", "chargeLimit", "chargeWatts", "fan"}) m_savedControls[key] = controlValue(key);
m_pendingBar = new QWidget; m_pendingBar->setObjectName("pendingChanges");
auto *bar = new QHBoxLayout(m_pendingBar);
@@ -92,16 +92,7 @@ Window::Window() : m_settings("fedora-tools", "framework-laptop-tools"),
if (isVisible() && !m_sleeping && m_tabs->currentIndex() >= 1 && m_tabs->currentIndex() <= 3) refreshControls();
});
m_controlsTimer.start(2000);
m_tray = new QSystemTrayIcon(windowIcon(), this);
auto *menu = new QMenu(this);
menu->addAction("Open Framework Laptop Tools", this, [this] { show(); raise(); activateWindow(); });
menu->addSeparator();
menu->addAction("Quit", qApp, &QApplication::quit);
m_tray->setContextMenu(menu);
connect(m_tray, &QSystemTrayIcon::activated, this, [this](auto reason) {
if (reason == QSystemTrayIcon::Trigger || reason == QSystemTrayIcon::DoubleClick) { show(); raise(); activateWindow(); }
});
m_tray->show();
applyTray();
if (!QDBusConnection::systemBus().connect("org.freedesktop.login1", "/org/freedesktop/login1",
"org.freedesktop.login1.Manager", "PrepareForSleep", this, SLOT(sleepChanged(bool))))
m_message->setText("Sleep notifications unavailable; sleep intervals cannot be marked on the battery graph.");
@@ -117,11 +108,13 @@ QGroupBox *Window::sensorGroup(const QString &title, Chart *chart, const QVector
auto *heading = new QHBoxLayout;
auto *label = new QLabel(title); label->setObjectName("chartTitle");
auto font = label->font(); font.setPointSizeF(font.pointSizeF() + 2); label->setFont(font);
heading->addStretch();
heading->addWidget(label);
if (title == "Fan speed" || title == "Battery") {
auto *details = new QLabel; details->setWordWrap(true); heading->addWidget(details, 1);
auto *details = new QLabel; details->setWordWrap(true); heading->addWidget(details);
if (title == "Fan speed") m_fanDetails = details; else m_batteryDetails = details;
} else heading->addStretch();
}
heading->addStretch();
layout->addLayout(heading);
QVector<Sensor> main, extra;
for (const auto &sensor : sensors) {
@@ -156,7 +149,7 @@ QWidget *Window::monitorPage()
{
auto *page = new QWidget; auto *layout = new QVBoxLayout(page);
auto *historyRow = new QHBoxLayout;
auto *history = new QSlider(Qt::Horizontal); history->setObjectName("monitorHistory");
auto *history = new JumpSlider(Qt::Horizontal); history->setObjectName("monitorHistory");
// Logarithmic spacing, rounded to whole minutes for a readable selection.
history->setRange(0, 1000);
const auto savedMinutes = std::clamp(m_settings.value("monitor/historyMinutes", 1440).toInt(), 5, 1440);
@@ -169,6 +162,8 @@ QWidget *Window::monitorPage()
layout->addLayout(historyRow); layout->addWidget(stretch);
m_frequencyChart = new Chart("MHz"); m_temperatureChart = new Chart("°C"); m_batteryChart = new Chart("%");
layout->addWidget(sensorGroup("CPU and GPU frequency", m_frequencyChart, m_frequencies, false));
m_powerChart = new Chart("W"); m_powerChart->setObjectName("powerChart");
layout->addWidget(sensorGroup("Power usage", m_powerChart, m_powerMonitor.sensors(), false));
m_fanChart = new Chart("RPM");
auto *fanGroup = sensorGroup("Fan speed", m_fanChart, {{"fan", "Fan speed", {}, "RPM"}}, false);
layout->addWidget(fanGroup);
@@ -176,7 +171,7 @@ QWidget *Window::monitorPage()
auto *batteryGroup = sensorGroup("Battery", m_batteryChart,
{{"battery", "Charge level", {}, "%"}, {"battery-rate", "Charge / discharge rate", {}, "W"}}, false);
layout->addWidget(batteryGroup);
const QList<Chart *> charts{m_frequencyChart, m_fanChart, m_temperatureChart, m_batteryChart};
const QList<Chart *> charts{m_frequencyChart, m_powerChart, m_fanChart, m_temperatureChart, m_batteryChart};
auto updateHistory = [this, charts, history, stretch, span] {
const int minutes = qRound(5 * std::pow(288., history->value() / 1000.));
span->setText(minutes < 60 ? QString("%1 min").arg(minutes)
@@ -197,12 +192,12 @@ QWidget *Window::monitorPage()
QWidget *Window::lightingPage()
{
auto *page = new QWidget; auto *layout = new QVBoxLayout(page);
auto *keyboard = new QGroupBox("Keyboard"); auto *keys = new QFormLayout(keyboard);
auto *keyboard = sectionGroup("Keyboard"); auto *keys = new QFormLayout(keyboard);
m_keyboard = spin(0, 100, "%"); m_keyboard->setObjectName("keyboardBrightness");
keys->addRow("Keyboard brightness:", m_keyboard);
keys->addRow(note("The current firmware interface does not expose setting or detecting automatic brightness. If Auto is set using Fn+Space, any manual brightness here will be overridden."));
layout->addWidget(keyboard);
auto *power = new QGroupBox("Power button"); auto *lights = new QFormLayout(power);
auto *power = sectionGroup("Power button"); auto *lights = new QFormLayout(power);
m_power = spin(1, 100, "%"); m_power->setObjectName("powerBrightness");
m_powerAuto = new QCheckBox("Automatic brightness"); m_powerAuto->setObjectName("powerAuto");
lights->addRow(m_powerAuto); lights->addRow("Power-button brightness:", m_power);
@@ -243,7 +238,7 @@ QWidget *Window::coolingPage()
QWidget *Window::batteryPage()
{
auto *page = new QWidget; auto *layout = new QVBoxLayout(page);
auto *group = new QGroupBox("Battery"); auto *form = new QFormLayout(group);
auto *group = sectionGroup("Battery"); auto *form = new QFormLayout(group);
m_charge = spin(50, 100, "%"); m_charge->setValue(100); m_charge->setObjectName("chargeLimit");
form->addRow("Limit battery:", m_charge);
m_watts = spin(0, 75, " W"); m_watts->setSpecialValueText("Firmware default"); m_watts->setObjectName("chargeWatts");
@@ -273,27 +268,58 @@ QWidget *Window::preferencesPage()
QWidget *Window::trayPage()
{
QVector<Sensor> sensors{{"cpu-usage", "CPU usage", {}, "%"}};
sensors += m_frequencies; sensors += m_temperatures;
sensors += m_frequencies; sensors += m_temperatures; sensors += m_powerMonitor.sensors();
sensors += QVector<Sensor>{{"battery", "Battery charge", {}, "%"}, {"battery-rate", "Battery rate", {}, "W"}};
m_trayPage = new TrayPage(m_settings, sensors);
connect(m_trayPage, &TrayPage::settingsChanged, this, &Window::updatePendingBar);
m_trayPage = new TrayIconsPage(m_settings, sensors);
connect(m_trayPage, &TrayIconsPage::settingsChanged, this, &Window::updatePendingBar);
return m_trayPage;
}
void Window::applyTray()
{
const auto configurations = m_trayPage->configurations();
while (m_trays.size() > configurations.size()) {
const auto tray = m_trays.takeLast();
delete tray.icon;
delete tray.menu;
}
for (int i = 0; i < configurations.size(); ++i) {
if (i == m_trays.size()) {
auto *icon = new QSystemTrayIcon(windowIcon(), this);
// KDE's native tray backend owns its menu: sharing one across icons
// makes their cleanup delete the same native menu more than once.
auto *menu = new QMenu(this);
menu->addAction("Open Framework Laptop Tools", this, [this] { show(); raise(); activateWindow(); });
menu->addSeparator();
menu->addAction("Quit", qApp, &QApplication::quit);
icon->setContextMenu(menu);
connect(icon, &QSystemTrayIcon::activated, this, [this](auto reason) {
if (reason == QSystemTrayIcon::Trigger || reason == QSystemTrayIcon::DoubleClick) { show(); raise(); activateWindow(); }
});
m_trays.append({icon, menu, configurations[i]}); icon->show();
} else m_trays[i].config = configurations[i];
}
updateTray();
}
void Window::updateTray()
{
const auto metric = m_trayMetric;
if (m_trayMode == "icon") m_tray->setIcon(windowIcon());
else {
const auto now = QDateTime::currentMSecsSinceEpoch();
const double since = now - (m_trayMode == "graph" ? m_trayStyle.historyMs : 0);
QVector<QPointF> history;
if (metric.id == "cpu-usage")
for (auto it = historyStart(m_usageHistory, since); it != m_usageHistory.cend(); ++it) history.append(*it);
else if (metric.id == "battery" || metric.id == "battery-rate") history = m_batteryChart->history(metric.id, since);
else history = (metric.unit == "MHz" ? m_frequencyChart : m_temperatureChart)->history(metric.id, since);
m_tray->setIcon(telemetryIcon(m_trayMode == "graph", history, metric.unit, m_trayStyle, now));
const auto now = QDateTime::currentMSecsSinceEpoch();
const auto temperatures = tooltipSensors(m_temperatures);
for (const auto &tray : m_trays) {
const auto &config = tray.config;
const auto &metric = config.metric;
if (config.mode == "icon") tray.icon->setIcon(windowIcon());
else {
const double since = now - (config.mode == "graph" ? config.style.historyMs : 0);
QVector<QPointF> history;
if (metric.id == "cpu-usage")
for (auto it = historyStart(m_usageHistory, since); it != m_usageHistory.cend(); ++it) history.append(*it);
else if (metric.id == "battery" || metric.id == "battery-rate") history = m_batteryChart->history(metric.id, since);
else if (metric.id.startsWith("power/")) history = m_powerChart->history(metric.id, since);
else history = (metric.unit == "MHz" ? m_frequencyChart : m_temperatureChart)->history(metric.id, since);
tray.icon->setIcon(telemetryIcon(config.mode == "graph", history, metric.unit, config.style, now));
}
tray.icon->setToolTip(trayTooltip(config.values, m_values, temperatures, m_batteryText, m_topAppText));
}
m_tray->setToolTip(trayTooltip(m_savedTray, m_values, tooltipSensors(m_temperatures), m_batteryText, m_topAppText));
}
QVariantMap Window::controlValue(const QString &key) const
{
@@ -407,7 +433,7 @@ QString Window::saveLocalSettings()
if (m_settings.status() != QSettings::NoError) return "Could not save application settings.";
m_savedTray = tray; m_savedPreferences = preferences;
m_fastTimer.start(preferences["sampling/fast"].toInt()); m_batteryTimer.start(preferences["sampling/battery"].toInt());
m_trayMetric = m_trayPage->metric(); m_trayMode = m_trayPage->mode(); m_trayStyle = m_trayPage->iconStyle(); updateTray();
m_trayPage->discardHidden(); applyTray();
return {};
}
void Window::finishSave()
@@ -493,7 +519,7 @@ void Window::sample()
{
if (m_sleeping) return;
m_values.clear();
m_cpuPage->refreshStatus();
if (m_cpuPage->isVisible()) m_cpuPage->refreshStatus();
auto sampleSensors = [&](const QVector<Sensor> &sensors, Chart *chart) {
QMap<QString, double> values;
for (const auto &sensor : sensors) {
@@ -503,6 +529,9 @@ void Window::sample()
chart->sample(values, m_fastTimer.interval());
};
sampleSensors(m_frequencies, m_frequencyChart); sampleSensors(m_temperatures, m_temperatureChart);
const auto power = m_powerMonitor.sample(m_fastTimer.interval());
m_powerChart->sample(power, m_fastTimer.interval());
m_values.insert(power);
const QString ec = ecHwmon();
const auto rpm = readNumber(ec + "/fan1_input");
const auto mode = readNumber(ec + "/pwm1_enable");
@@ -518,7 +547,10 @@ void Window::sample()
const auto battery = batteryStatus();
const auto usage = m_cpuUsage.sample(readText("/proc/stat"));
if (usage) m_values["cpu-usage"] = *usage;
if (tooltipEnabled(m_savedTray, "cpu") && tooltipAppCount(m_savedTray) > 0) {
const bool showApps = std::any_of(m_trays.cbegin(), m_trays.cend(), [](const auto &tray) {
return tooltipEnabled(tray.config.values, "cpu") && tooltipAppCount(tray.config.values) > 0;
});
if (showApps) {
m_topAppText.clear();
for (const auto &app : m_processUsage.sample(m_cpuUsage.totalDelta()))
m_topAppText << app.name + QString(": %1 %").arg(app.percent, 0, 'f', 1);
@@ -551,9 +583,10 @@ void Window::sampleBattery()
void Window::sleepChanged(bool sleeping)
{
m_sleeping = sleeping;
for (auto *chart : {m_frequencyChart, m_temperatureChart, m_batteryChart, m_fanChart})
for (auto *chart : {m_frequencyChart, m_powerChart, m_temperatureChart, m_batteryChart, m_fanChart})
chart->setPowerState(sleeping, sleeping || chart != m_batteryChart ? std::nullopt : onAcPower());
m_cpuUsage.reset();
m_powerMonitor.reset();
m_processUsage.reset(); m_topAppText.clear();
if (!sleeping) { sample(); sampleBattery(); }
}
+8 -6
View File
@@ -5,6 +5,7 @@
#include "tray.h"
#include "traypage.h"
#include "processusage.h"
#include "power.h"
#include <QMainWindow>
#include <QSettings>
#include <QTimer>
@@ -15,6 +16,7 @@
class QGroupBox;
class QTabWidget;
class QPushButton;
class QMenu;
class Window : public QMainWindow {
Q_OBJECT
@@ -30,6 +32,7 @@ private:
QWidget *preferencesPage();
QWidget *trayPage();
void updateTray();
void applyTray();
void sample();
void sampleBattery();
void request(const QVariantMap &arguments, bool inspect = false);
@@ -48,18 +51,20 @@ private:
QTimer m_fastTimer, m_batteryTimer, m_controlsTimer;
QTabWidget *m_tabs;
QVector<Sensor> m_temperatures, m_frequencies;
PowerMonitor m_powerMonitor;
QMap<QString, double> m_values;
CpuUsage m_cpuUsage;
ProcessUsage m_processUsage;
QStringList m_topAppText;
Samples m_usageHistory;
Chart *m_frequencyChart, *m_temperatureChart, *m_batteryChart, *m_fanChart;
Chart *m_frequencyChart, *m_powerChart, *m_temperatureChart, *m_batteryChart, *m_fanChart;
QLabel *m_batteryDetails, *m_fanDetails;
QLabel *m_message, *m_fanReadout, *m_firmwareReadout;
QString m_batteryText;
QVector<QWidget *> m_controlPages;
CpuPage *m_cpuPage;
QSystemTrayIcon *m_tray;
struct TrayIcon { QSystemTrayIcon *icon; QMenu *menu; TrayConfiguration config; };
QVector<TrayIcon> m_trays;
ValueControl *m_keyboard, *m_power, *m_charge, *m_watts, *m_duty;
QCheckBox *m_powerAuto;
QLabel *m_fanWarning;
@@ -75,11 +80,8 @@ private:
QWidget *m_pendingBar = nullptr;
QPushButton *m_saveButton, *m_undoButton;
bool m_saving = false;
Sensor m_trayMetric;
QString m_trayMode;
TrayStyle m_trayStyle;
QComboBox *m_fanMode;
TrayPage *m_trayPage;
TrayIconsPage *m_trayPage;
int m_chargeLimit = 100;
bool m_chargeOverride = false;
bool m_busy = false;