diff --git a/tools/chatgui/CMakeLists.txt b/tools/chatgui/CMakeLists.txt index af7415d6c..e45d82a98 100644 --- a/tools/chatgui/CMakeLists.txt +++ b/tools/chatgui/CMakeLists.txt @@ -649,7 +649,8 @@ target_include_directories(test_radio_mute_bridge PRIVATE ${UTUN_INCLUDE_DIRS}) target_link_libraries(test_radio_mute_bridge PRIVATE ${QT_LIBS} ${QT_TEST_LIB} utun_voice utun pthread) add_test(NAME test_radio_mute_bridge COMMAND test_radio_mute_bridge) set_tests_properties(test_radio_mute_bridge PROPERTIES TIMEOUT 15 ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -add_executable(test_utun_node tests/test_utun_node.cpp transport/utun_node.cpp transport/gui_bridge_impl.cpp transport/stream_bridge.cpp) +add_executable(test_utun_node tests/test_utun_node.cpp src/statuspage.cpp transport/utun_node.cpp transport/gui_bridge_impl.cpp + transport/stream_bridge.cpp) target_include_directories(test_utun_node PRIVATE ${UTUN_INCLUDE_DIRS}) target_link_libraries(test_utun_node PRIVATE ${QT_LIBS} ${QT_TEST_LIB} utun_voice utun pthread) if(CMAKE_SYSTEM_NAME STREQUAL "Linux") diff --git a/tools/chatgui/src/statuspage.cpp b/tools/chatgui/src/statuspage.cpp index e9bf547eb..848905d17 100644 --- a/tools/chatgui/src/statuspage.cpp +++ b/tools/chatgui/src/statuspage.cpp @@ -6,6 +6,7 @@ extern "C" { #include "../transport/gui_bridge.h" #include "chat/chat_core.h" +#include "debug_config.h" } #include @@ -91,11 +92,9 @@ StatusPage::~StatusPage() { } void StatusPage::updateClock() { - if (!m_node) return; - qint64 nowMs = QDateTime::currentMSecsSinceEpoch(); - int64_t offsetUs = m_node->ntpOffsetUs(); - bool synced = m_node->ntpSynced(); + int64_t offsetUs = m_node ? m_node->ntpOffsetUs() : 0; + bool synced = m_node && m_node->ntpSynced(); qint64 correctedMs = nowMs - (offsetUs / 1000); QDateTime corrected = QDateTime::fromMSecsSinceEpoch(correctedMs).toLocalTime(); @@ -113,8 +112,24 @@ void StatusPage::updateClock() { void StatusPage::refreshStatus() { updateClock(); + auto* inst = gui_bridge_get_inst(); + if (!m_node || !m_node->isRunning() || !gui_bridge_is_uasync_ready() || !inst) { + DEBUG_WARN(DEBUG_CATEGORY_GENERAL, "status refresh: core unavailable"); + m_textEdit->setPlainText(QCoreApplication::translate("ChatGui", "Node is not running.")); + return; + } m_textEdit->setPlainText(QCoreApplication::translate("ChatGui", "Loading...")); - gui_bridge_post_uasync_fn(chat_core_collect_status_trampoline, gui_bridge_get_inst()); + DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "status refresh: requesting snapshot instance=%p", (void*)inst); + gui_bridge_post_uasync_fn(chat_core_collect_status_trampoline, inst); +} + +/* Поздний ответ не должен заменять сообщение об остановке ядра старым снимком. */ +void StatusPage::setText(const QString& text) { + if (!m_node || !m_node->isRunning() || !gui_bridge_get_inst()) { + DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "status refresh: late snapshot ignored after core stop"); return; + } + DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "status refresh: snapshot received chars=%d", (int)text.size()); + m_textEdit->setPlainText(text); } void StatusPage::onRefreshClicked() { diff --git a/tools/chatgui/src/statuspage.h b/tools/chatgui/src/statuspage.h index be1c157b7..bb90fcc61 100644 --- a/tools/chatgui/src/statuspage.h +++ b/tools/chatgui/src/statuspage.h @@ -1,4 +1,9 @@ -// statuspage.h — Status page (NTP + connections + live clock) in settings +/* Страница диагностики настроек: ручной снимок NTP/ETCP и часы с поправкой UtunNode. + * Все методы и callbacks работают в GUI. Одновременно используется одна страница: + * конструктор регистрирует её как получателя глобального callback статуса gui_bridge. + * refreshStatus запускает часы и асинхронный запрос в uasync; готовый текст копируется в Qt. + * Без работающего ядра показывает явное состояние, поздние ответы после stop игнорируются. + * Часы обновляются по границе секунды до уничтожения страницы, в том числе при скрытой странице. */ #pragma once #include @@ -7,16 +12,18 @@ #include #include #include +#include class UtunNode; class StatusPage : public QWidget { Q_OBJECT public: + // node заимствован через QPointer; может быть NULL/удалён раньше страницы. parent владеет виджетами. explicit StatusPage(UtunNode* node, QWidget* parent = nullptr); ~StatusPage() override; - void refreshStatus(); - void setText(const QString& text) { m_textEdit->setPlainText(text); } + void refreshStatus(); // Запросить снимок активного ядра; при недоступности не оставлять Loading. + void setText(const QString& text); // Применить ответ живого ядра; text копируется в документ Qt. private slots: void onRefreshClicked(); @@ -24,11 +31,11 @@ private slots: private: void updateClock(); - QPlainTextEdit* m_textEdit; - QPushButton* m_refreshBtn; - QLabel* m_clockLabel; - QFrame* m_clockFrame; - QTimer* m_clockTimer; - UtunNode* m_node; + QPlainTextEdit* m_textEdit; // Только чтение; полный текст последнего снимка/состояния ядра. + QPushButton* m_refreshBtn; // Ручной запрос снимка. + QLabel* m_clockLabel; // Локальное время с NTP-поправкой, если узел ещё существует. + QFrame* m_clockFrame; // Рамка часов; принадлежит странице. + QTimer* m_clockTimer; // Одноразовый precise timer до следующей секунды; принадлежит странице. + QPointer m_node; // Автоматически обнуляется при удалении владельца ядра. }; diff --git a/tools/chatgui/tests/test_utun_node.cpp b/tools/chatgui/tests/test_utun_node.cpp index 3bc96f0eb..45c31b307 100644 --- a/tools/chatgui/tests/test_utun_node.cpp +++ b/tools/chatgui/tests/test_utun_node.cpp @@ -1,6 +1,7 @@ /* Desktop по умолчанию запускает core/chat; явный UTUN независим от создания TUN. */ #include "../transport/utun_node.h" #include "../transport/gui_bridge.h" +#include "../src/statuspage.h" #include #include #include @@ -219,6 +220,41 @@ private slots: QVERIFY(node.nodeIdHex().isEmpty() && !node.ntpSynced()); } + void statusPageRefreshBeforeStartWhileRunningAndAfterStop() { + QTemporaryDir directory; QVERIFY(directory.isValid()); + const QString path = directory.filePath("node.cfg"); + QFile config(path); QVERIFY(config.open(QIODevice::WriteOnly)); + const QByteArray text = "[global]\n" + identity + + "[chatserver]\ngroup_autoconnect=0\nstorage_autoload=0\n[ntp]\nenabled=no\n"; + QCOMPARE(config.write(text), text.size()); config.close(); + UtunNode node; + node.setDbPath(directory.filePath("db")); node.setDebugFile(directory.filePath("node.log")); + StatusPage page(&node); + auto* status = page.findChild(); QVERIFY(status); + page.refreshStatus(); QCOMPARE(status->toPlainText(), QStringLiteral("Node is not running.")); + QVERIFY(node.start(path)); + page.refreshStatus(); + QTRY_VERIFY_WITH_TIMEOUT(status->toPlainText().contains("=== NTP ==="), 3000); + QVERIFY(status->toPlainText().contains("=== Connections (0) ===")); + node.stop(); + page.refreshStatus(); QCOMPARE(status->toPlainText(), QStringLiteral("Node is not running.")); + page.setText(QStringLiteral("late snapshot from stopped core")); + QCoreApplication::processEvents(); + QCOMPARE(status->toPlainText(), QStringLiteral("Node is not running.")); + } + + void statusPageSurvivesDeletedNodeAndUsesLocalClock() { + auto* node = new UtunNode; + StatusPage page(node); + delete node; + page.refreshStatus(); + auto* status = page.findChild(); QVERIFY(status); + QCOMPARE(status->toPlainText(), QStringLiteral("Node is not running.")); + bool local = false; + for (auto* label : page.findChildren()) local |= label->text().contains("[LOCAL]"); + QVERIFY(local); + } + #ifdef UTUN_TEST_NODE_STREAM_FAILURES void streamFailureRollsBackAndAllowsRetry_data() { QTest::addColumn("stage");