Measure uasync CPU load and display it in desktop and Android GUIs

Sample thread CPU usage without waking idle loops, expose a one-second moving average, and refresh compact GUI indicators at 3 Hz while visible on Android. Add load and bridge regression coverage, streaming notes, and task list cleanup.
This commit is contained in:
evgeny committed 2026-10-10 12:31:13 +02:00
1 parent bcfe7ca4c1
commit 71d19013c0
25 files changed
+692 -587

No files matched your search

+40 -1
View File
@@ -24,6 +24,38 @@ extern "C" {
#include "dm/dm_core.h"
}
/* Секундное среднее CPU: фиксированный градиент, заполнение по проценту. */
class CpuLoadIndicator : public QWidget {
public:
explicit CpuLoadIndicator(QWidget* parent) : QWidget(parent) {
setObjectName(QStringLiteral("cpuLoadIndicator"));
setFixedSize(60, 24);
setAccessibleName(QStringLiteral("CPU"));
}
void setValue(int percent) {
percent = qBound(0, percent, 100);
if (m_percent == percent) return;
m_percent = percent; update();
}
protected:
void paintEvent(QPaintEvent*) override {
QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing);
QPainterPath path; path.addRoundedRect(QRectF(rect()), 5, 5);
painter.setClipPath(path);
painter.fillRect(rect(), QColor("#E4E9E6"));
QLinearGradient gradient(0, 0, width(), 0);
gradient.setColorAt(0, QColor("#66BB6A"));
gradient.setColorAt(0.5, QColor("#FFCA28"));
gradient.setColorAt(1, QColor("#EF5350"));
painter.fillRect(QRectF(0, 0, width() * m_percent / 100.0, height()), gradient);
painter.setPen(QColor("#172019"));
QFont f = font(); f.setBold(true); painter.setFont(f);
painter.drawText(rect(), Qt::AlignCenter, QString::number(m_percent) + '%');
}
private:
int m_percent = 0;
};
/* Пустое место и заголовки секций не сбрасывают выбор канала. */
class ChannelListView : public QListView {
public:
@@ -106,7 +138,12 @@ ChannelList::ChannelList(DbManager* db, QWidget *parent)
auto *header = new QLabel(QCoreApplication::translate("ChatGui", "Channels"), this);
header->setAlignment(Qt::AlignCenter);
header->setStyleSheet("font-weight: bold; padding: 8px; background: palette(window);");
layout->addWidget(header);
auto* headerRow = new QHBoxLayout;
headerRow->setContentsMargins(0, 0, 8, 0);
headerRow->addWidget(header, 1);
m_cpuLoad = new CpuLoadIndicator(this);
headerRow->addWidget(m_cpuLoad);
layout->addLayout(headerRow);
m_listView->setModel(m_model);
m_listView->setItemDelegate(new ChannelDelegate(this));
@@ -266,6 +303,8 @@ void ChannelList::onDmCallRoute(const uint8_t* data, int len) {
}
}
void ChannelList::setCpuLoad(int percent) { m_cpuLoad->setValue(percent); }
void ChannelList::loadChannels() {
refreshDmPresence();
QString selectedCid;
+3
View File
@@ -12,6 +12,7 @@
class DbManager;
class QLabel;
class CpuLoadIndicator;
class ChannelList : public QWidget {
Q_OBJECT
@@ -25,6 +26,7 @@ public:
void selectChannel(const QString& channelId);
void setChannelPeersOnline(const QString& channelId, int count);
void setAutoConnectActive(bool active);
void setCpuLoad(int percent);
void setChannelUnreadCount(const QString& channelId, int count);
int getChannelUnreadCount(const QString& channelId) const;
@@ -49,4 +51,5 @@ private:
bool m_autoConnectActive = false;
QHash<QString, bool> m_dmOnline;
QTimer* m_dmPresenceTimer;
CpuLoadIndicator* m_cpuLoad;
};
+22
View File
@@ -171,6 +171,18 @@ MainWindow::MainWindow(QWidget *parent, DbManager* db, const QString& cfgPath,
setupConnects();
}
connect(m_autoPlayTimer, &QTimer::timeout, this, &MainWindow::autoPlayTimerTick);
m_cpuLoadTimer = new QTimer(this);
m_cpuLoadTimer->setTimerType(Qt::PreciseTimer);
connect(m_cpuLoadTimer, &QTimer::timeout, this, [this] {
auto* inst = gui_bridge_get_inst();
if (!m_node || !m_node->isRunning() || !inst || !gui_bridge_is_uasync_ready()) {
m_cpuLoadPending = false; m_channelList->setCpuLoad(0); return;
}
if (m_cpuLoadPending) return;
m_cpuLoadPending = gui_bridge_request_cpu_load() != 0;
});
m_cpuLoadTimer->start(333);
DEBUG_DEBUG(DEBUG_CATEGORY_SYS, "desktop CPU indicator polling started: period=333ms");
#ifndef _WIN32
std::signal(SIGINT, unixSignalHandler);
@@ -183,6 +195,9 @@ MainWindow::MainWindow(QWidget *parent, DbManager* db, const QString& cfgPath,
MainWindow::~MainWindow() {
s_mainWindow = nullptr;
m_cpuLoadTimer->stop();
gui_bridge_set_cpu_load_cb(nullptr);
DEBUG_DEBUG(DEBUG_CATEGORY_SYS, "desktop CPU indicator polling stopped");
if (m_messageNotification) m_messageNotification->dismiss("shutdown");
m_messageNotification.reset();
delete AvatarManager::instance();
@@ -407,6 +422,11 @@ void MainWindow::setupSoundFromConfig() {
void MainWindow::setupBridgeCallbacks() {
s_mainWindow = this;
gui_bridge_set_cpu_load_cb([](int percent) {
if (!s_mainWindow) return;
s_mainWindow->m_cpuLoadPending = false;
s_mainWindow->m_channelList->setCpuLoad(percent);
});
gui_bridge_set_member_files_response_cb([](const uint8_t* data, int length) {
DEBUG_DEBUG(DEBUG_CATEGORY_DEBUG, "member_files: GUI response route bytes=%d browser=%d",
length, (int)(s_mainWindow && s_mainWindow->m_fileBrowser));
@@ -554,6 +574,8 @@ void MainWindow::setupBridgeCallbacks() {
gui_bridge_set_network_changed_cb([](int type) {
if (!s_mainWindow) return;
if (type == 13) {
s_mainWindow->m_cpuLoadPending = false;
s_mainWindow->m_channelList->setCpuLoad(0);
s_mainWindow->m_accountList->model()->setRadioState(0, false, false);
s_mainWindow->m_messageList->clearDmCallRoute();
s_mainWindow->m_channelList->clearDmPresence();
+2
View File
@@ -129,6 +129,8 @@ private:
QQueue<AutoPlayItem> m_autoPlayQueue;
QTimer* m_autoPlayTimer = nullptr;
QTimer* m_cpuLoadTimer = nullptr;
bool m_cpuLoadPending = false;
QTimer* m_shutdownTimer = nullptr;
QSet<int64_t> m_autoPlayDownloading; /* msgIds with download in progress */
+30 -1
View File
@@ -1,8 +1,10 @@
/* Формат канального события: live/history сохраняются при передаче в GUI, битые события отбрасываются. */
#include "../transport/gui_bridge.h"
#include "../../../lib/debug_config.h"
#include "../../../src/chat/chat_event.h"
#include <QtTest>
#include <cstring>
#include <thread>
struct ReceivedMessage {
QString channel;
@@ -11,6 +13,13 @@ struct ReceivedMessage {
bool guiThread;
};
static QList<ReceivedMessage> received;
static QList<int> cpuLoads;
static bool cpuOnGuiThread = true;
static void cpu_received(int percent) {
cpuLoads.append(percent);
cpuOnGuiThread &= QThread::currentThread() == qApp->thread();
}
static void message_received(const char* channel, int length, uint64_t author, int initial_sync) {
received.append({QString::fromUtf8(channel, length), author, initial_sync != 0, QThread::currentThread() == qApp->thread()});
@@ -39,7 +48,7 @@ private slots:
gui_bridge_init();
gui_bridge_set_msg_received_cb(message_received);
}
void cleanupTestCase() { gui_bridge_set_msg_received_cb(nullptr); }
void cleanupTestCase() { gui_bridge_set_msg_received_cb(nullptr); gui_bridge_set_cpu_load_cb(nullptr); }
void init() { received.clear(); }
void liveAndHistory() {
@@ -69,6 +78,26 @@ private slots:
QTest::qWait(100);
QVERIFY(received.isEmpty());
}
void cpuLoadDeliveredToGuiThread() {
cpuLoads.clear(); cpuOnGuiThread = true;
gui_bridge_set_cpu_load_cb(cpu_received);
std::thread worker([] {
const uint8_t samples[][2] = {{1, 0}, {1, 50}, {1, 100}, {0, 90}, {1, 101}};
for (const auto& sample : samples) gui_bridge_post(CHAT_EVT_CPU_LOAD, sample, sizeof(sample));
gui_bridge_post(CHAT_EVT_CPU_LOAD, nullptr, 0);
});
worker.join();
QVERIFY(cpuLoads.isEmpty()); // Worker не вызывает UI напрямую.
QTRY_COMPARE(cpuLoads.size(), 6);
QCOMPARE(cpuLoads, QList<int>({0, 50, 100, 0, 0, 0}));
QVERIFY(cpuOnGuiThread);
gui_bridge_set_cpu_load_cb(nullptr);
const uint8_t sample[] = {1, 75};
gui_bridge_post(CHAT_EVT_CPU_LOAD, sample, sizeof(sample));
QCoreApplication::processEvents();
QCOMPARE(cpuLoads.size(), 6);
}
};
QTEST_MAIN(MessageEventTest)
+5
View File
@@ -121,6 +121,11 @@ void gui_bridge_set_db_ready_cb(gui_db_ready_fn cb);
typedef void (*gui_status_refresh_fn)(const char* text, int len);
void gui_bridge_set_status_refresh_cb(gui_status_refresh_fn cb);
/* Секундное среднее CPU uasync, 0..100; callback выполняется в GUI-потоке. */
typedef void (*gui_cpu_load_fn)(int percent);
void gui_bridge_set_cpu_load_cb(gui_cpu_load_fn cb);
int gui_bridge_request_cpu_load(void); // 1 = запрос поставлен в очередь; 0 = ядро недоступно/ошибка
/* Callback для завершения загрузки медиа-аттача */
typedef void (*gui_attachment_downloaded_fn)(const char* ch_id, int ch_id_len, int64_t msg_id);
void gui_bridge_set_attachment_downloaded_cb(gui_attachment_downloaded_fn cb);
@@ -14,6 +14,7 @@ extern "C" {
#include "../../../src/routing_layer/topo_group.h"
#include "../../../src/member_files/protocol.h"
#include "../../../src/chat/chat_member.h"
#include "../../../src/chat/chat_core.h"
}
/* ── Внутренний объект-приёмник в GUI-потоке ── */
@@ -37,6 +38,7 @@ static gui_auto_connect_status_fn g_auto_connect_status_cb = nullptr;
static gui_channel_peers_online_fn g_channel_peers_online_cb = nullptr;
static gui_db_ready_fn g_db_ready_cb = nullptr;
static gui_status_refresh_fn g_status_refresh_cb = nullptr;
static gui_cpu_load_fn g_cpu_load_cb = nullptr;
static gui_attachment_downloaded_fn g_attachment_downloaded_cb = nullptr;
static gui_download_progress_fn g_download_progress_cb = nullptr;
static gui_nodeinfo_update_fn g_nodeinfo_update_cb = nullptr;
@@ -89,6 +91,12 @@ void GuiBridgeReceiver::processPost(int eventType, QByteArray data) {
eventType == 16 || eventType == 17 || eventType == 24 || eventType == 25 || eventType == 31 || eventType == 33))
g_network_changed_cb(eventType);
switch (eventType) {
case CHAT_EVT_CPU_LOAD:
if (dlen != 2 || d[0] > 1 || d[1] > 100) {
DEBUG_WARN(DEBUG_CATEGORY_SYS, "invalid CPU load response bytes=%d", dlen);
if (g_cpu_load_cb) g_cpu_load_cb(0);
} else if (g_cpu_load_cb) g_cpu_load_cb(d[0] ? d[1] : 0);
break;
case CHAT_EVT_MSG_SUBMITTED:
if (dlen != 9 || d[8] > 1) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT, "invalid submission result bytes=%d", dlen); break; }
if (g_msg_submitted_cb) g_msg_submitted_cb(d, dlen);
@@ -497,6 +505,19 @@ void gui_bridge_set_status_refresh_cb(gui_status_refresh_fn cb) {
g_status_refresh_cb = cb;
}
void gui_bridge_set_cpu_load_cb(gui_cpu_load_fn cb) {
g_cpu_load_cb = cb;
}
int gui_bridge_request_cpu_load(void) {
if (!g_ua || !g_inst) return 0;
auto* task = (struct posted_task*)u_calloc(1, sizeof(struct posted_task));
if (!task) { DEBUG_ERROR(DEBUG_CATEGORY_SYS, "CPU load request allocation failed"); return 0; }
task->callback = chat_core_collect_cpu_load_trampoline; task->arg = g_inst;
uasync_post_reserved(g_ua, task);
return 1;
}
void gui_bridge_set_attachment_downloaded_cb(gui_attachment_downloaded_fn cb) {
g_attachment_downloaded_cb = cb;
}