diff --git a/.reuse/dep5 b/.reuse/dep5 index b3fb2094..4cd3d22b 100644 --- a/.reuse/dep5 +++ b/.reuse/dep5 @@ -18,6 +18,11 @@ Files: *.toml *.json *conf *.yaml *.sh *.xml *.pc.in Copyright: None License: CC0-1.0 +# assets +Files: assets/* +Copyright: UnionTech Software Technology Co., Ltd. +License: GPL-3.0-or-later + # debian Files: debian/* Copyright: None diff --git a/CMakeLists.txt b/CMakeLists.txt index 45492771..857a172a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,3 +59,32 @@ if(DOTEST) endif() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/config.h) + +#安装日志收集工具配置 +set(journel_system_monitor_main assets/logconfig/org.deepin.system-monitor.json) +install(FILES ${journel_system_monitor_main} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/deepin-log-viewer/deepin-log.conf.d/) + +#安装DConfig配置 +set(APPID org.deepin.system-monitor) +set(system_monitor_main assets/configs/org.deepin.system-monitor.json) +set(system_monitor_daemon assets/configs/org.deepin.system-monitor.daemon.json) +set(system_monitor_plugin assets/configs/org.deepin.system-monitor.plugin.json) +set(system_monitor_plugin_popup assets/configs/org.deepin.system-monitor.plugin.popup.json) +set(system_monitor_plugin_server assets/configs/org.deepin.system-monitor.server.json) + +if (DEFINED DSG_DATA_DIR) + dconfig_meta_files(APPID ${APPID} FILES ${system_monitor_main}) + dconfig_meta_files(APPID ${APPID} FILES ${system_monitor_daemon}) + dconfig_meta_files(APPID ${APPID} FILES ${system_monitor_plugin}) + dconfig_meta_files(APPID ${APPID} FILES ${system_monitor_plugin_popup}) + dconfig_meta_files(APPID ${APPID} FILES ${system_monitor_plugin_server}) + message("-- DConfig is supported by DTK") +else() + install(FILES ${system_monitor_main} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/dsg/configs/${APPID}/) + install(FILES ${system_monitor_daemon} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/dsg/configs/${APPID}/) + install(FILES ${system_monitor_plugin} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/dsg/configs/${APPID}/) + install(FILES ${system_monitor_plugin_popup} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/dsg/configs/${APPID}/) + install(FILES ${system_monitor_plugin_server} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/dsg/configs/${APPID}/) + + message("-- DConfig is not supported by DTK") +endif() diff --git a/assets/configs/org.deepin.system-monitor.daemon.json b/assets/configs/org.deepin.system-monitor.daemon.json new file mode 100644 index 00000000..a95c790d --- /dev/null +++ b/assets/configs/org.deepin.system-monitor.daemon.json @@ -0,0 +1,19 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "log_rules": { + "value": "*.debug=false;*.info=false;*.warning=true", + "serial": 0, + "flags": [ + "global" + ], + "name": "log rules", + "name[zh_CN]": "日志规则", + "description": "log rules", + "description[zh_CN]": "日志规则", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/assets/configs/org.deepin.system-monitor.json b/assets/configs/org.deepin.system-monitor.json new file mode 100644 index 00000000..a95c790d --- /dev/null +++ b/assets/configs/org.deepin.system-monitor.json @@ -0,0 +1,19 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "log_rules": { + "value": "*.debug=false;*.info=false;*.warning=true", + "serial": 0, + "flags": [ + "global" + ], + "name": "log rules", + "name[zh_CN]": "日志规则", + "description": "log rules", + "description[zh_CN]": "日志规则", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/assets/configs/org.deepin.system-monitor.plugin.json b/assets/configs/org.deepin.system-monitor.plugin.json new file mode 100644 index 00000000..a95c790d --- /dev/null +++ b/assets/configs/org.deepin.system-monitor.plugin.json @@ -0,0 +1,19 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "log_rules": { + "value": "*.debug=false;*.info=false;*.warning=true", + "serial": 0, + "flags": [ + "global" + ], + "name": "log rules", + "name[zh_CN]": "日志规则", + "description": "log rules", + "description[zh_CN]": "日志规则", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/assets/configs/org.deepin.system-monitor.plugin.popup.json b/assets/configs/org.deepin.system-monitor.plugin.popup.json new file mode 100644 index 00000000..a95c790d --- /dev/null +++ b/assets/configs/org.deepin.system-monitor.plugin.popup.json @@ -0,0 +1,19 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "log_rules": { + "value": "*.debug=false;*.info=false;*.warning=true", + "serial": 0, + "flags": [ + "global" + ], + "name": "log rules", + "name[zh_CN]": "日志规则", + "description": "log rules", + "description[zh_CN]": "日志规则", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/assets/configs/org.deepin.system-monitor.server.json b/assets/configs/org.deepin.system-monitor.server.json new file mode 100644 index 00000000..a95c790d --- /dev/null +++ b/assets/configs/org.deepin.system-monitor.server.json @@ -0,0 +1,19 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "log_rules": { + "value": "*.debug=false;*.info=false;*.warning=true", + "serial": 0, + "flags": [ + "global" + ], + "name": "log rules", + "name[zh_CN]": "日志规则", + "description": "log rules", + "description[zh_CN]": "日志规则", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/assets/logconfig/org.deepin.system-monitor.json b/assets/logconfig/org.deepin.system-monitor.json new file mode 100644 index 00000000..d68741f5 --- /dev/null +++ b/assets/logconfig/org.deepin.system-monitor.json @@ -0,0 +1,43 @@ +{ + "name": "deepin-system-monitor", + "group": "", + "submodules": [ + { + "name": "deepin-system-monitor-daemon", + "filter": "", + "exec": "/usr/lib/x86_64-linux-gnu/deepin-service-manager/libdeepin-system-monitor-daemon.so", + "logType": "journal", + "logPath": "" + }, + { + "name": "deepin-system-monitor", + "filter": "", + "exec": "/usr/bin/deepin-system-monitor", + "logType": "journal", + "logPath": "" + }, + { + "name": "deepin-system-monitor-plugin", + "filter": "", + "exec": "/usr/lib/dde-dock/plugins/libdeepin-system-monitor-plugin.so", + "logType": "journal", + "logPath": "" + }, + { + "name": "deepin-system-monitor-plugin-popup", + "filter": "", + "exec": "/usr/bin/deepin-system-monitor-plugin-popup", + "logType": "journal", + "logPath": "" + }, + { + "name": "deepin-system-monitor-server", + "filter": "", + "exec": "/usr/bin/deepin-system-monitor-server", + "logType": "journal", + "logPath": "" + } + ], + "visible": true, + "version": "V1.0" +} diff --git a/deepin-system-monitor-daemon/src/cpuprofile.cpp b/deepin-system-monitor-daemon/src/cpuprofile.cpp index 7d51ab3c..ffb54052 100644 --- a/deepin-system-monitor-daemon/src/cpuprofile.cpp +++ b/deepin-system-monitor-daemon/src/cpuprofile.cpp @@ -1,17 +1,17 @@ // SPDX-FileCopyrightText: 2011 ~ 2023 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "cpuprofile.h" #include #include +using namespace DDLog; #define PROC_CPU_STAT_PATH "/proc/stat" #define PROC_CPU_INFO_PATH "/proc/cpuinfo" CpuProfile::CpuProfile(QObject *parent) - : QObject(parent) - , mCpuUsage(0.0) + : QObject(parent), mCpuUsage(0.0) { // mLastCpuStat用于记录Cpu状态 // 各项数值是开机后各项工作的时间片总数 @@ -47,7 +47,7 @@ double CpuProfile::updateSystemCpuUsage() // |user|nice|sys|idle|iowait|hardqirq|softirq|steal|guest|guest_nice| // 分割行数据 - QStringList cpuStatus = QString(lineData).split(" ", QString::SkipEmptyParts); + QStringList cpuStatus = QString(lineData).split(" ", QString::SkipEmptyParts); // CPU状态应包含10个数据片段,有效数据 1-10,位置0不使用 if (cpuStatus.size() < 11) { @@ -80,10 +80,10 @@ double CpuProfile::updateSystemCpuUsage() // 通过对当前系统Cpu时间片使用情况和上一次获取的系统Cpu时间片使用情况,来计算上一个时间段内的Cpu使用情况 double calcCpuTotal = curCpuStat["total"] - mLastCpuStat["total"]; double calcCpuIdle = - (curCpuStat["idle"] + curCpuStat["iowait"]) - (mLastCpuStat["idle"] + mLastCpuStat["iowait"]); + (curCpuStat["idle"] + curCpuStat["iowait"]) - (mLastCpuStat["idle"] + mLastCpuStat["iowait"]); if (calcCpuTotal == 0.0) { - qWarning() << " cpu total usage calc result equal 0 ! cpu stat [" << curCpuStat << "]"; + qCWarning(app) << " cpu total usage calc result equal 0 ! cpu stat [" << curCpuStat << "]"; return cpuUsage; } // 上一个时间段内的Cpu使用情况 @@ -95,7 +95,7 @@ double CpuProfile::updateSystemCpuUsage() // 更新上一次CPU状态 mLastCpuStat = curCpuStat; } else { - qWarning() << QString(" file %1 open fail !").arg(PROC_CPU_STAT_PATH); + qCWarning(app) << QString(" file %1 open fail !").arg(PROC_CPU_STAT_PATH); } return cpuUsage; diff --git a/deepin-system-monitor-daemon/src/ddlog.h b/deepin-system-monitor-daemon/src/ddlog.h new file mode 100644 index 00000000..a4b69aef --- /dev/null +++ b/deepin-system-monitor-daemon/src/ddlog.h @@ -0,0 +1,15 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef DDLOG_H +#define DDLOG_H +#include +#include +DCORE_USE_NAMESPACE + +namespace DDLog { +inline Q_LOGGING_CATEGORY(app, "org.deepin.system-monitor.daemon") +} + +#endif // DDLOG_H diff --git a/deepin-system-monitor-daemon/src/logger.cpp b/deepin-system-monitor-daemon/src/logger.cpp new file mode 100644 index 00000000..14f92b0a --- /dev/null +++ b/deepin-system-monitor-daemon/src/logger.cpp @@ -0,0 +1,68 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include "logger.h" +#include "dtkcore_global.h" +#include "qglobal.h" +#include "ddlog.h" +#include +#include + +#include +using namespace DDLog; + +DCORE_USE_NAMESPACE + +MLogger::MLogger(QObject *parent) + : QObject(parent), m_rules(""), m_config(nullptr) +{ + QByteArray logRules = qgetenv("QT_LOGGING_RULES"); + // qunsetenv 之前一定不要有任何日志打印,否则取消环境变量设置不会生效 + qunsetenv("QT_LOGGING_RULES"); + + // set env + m_rules = logRules; + + // set dconfig + m_config = DConfig::create("org.deepin.system-monitor", "org.deepin.system-monitor.daemon"); + logRules = m_config->value("log_rules").toByteArray(); + appendRules(logRules); + setRules(m_rules); + + // watch dconfig + connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) { + qCritical(app) << "value changed:" << key; + if (key == "log_rules") { + setRules(m_config->value(key).toByteArray()); + } + }); +} + +MLogger::~MLogger() +{ + m_config->deleteLater(); +} + +void MLogger::setRules(const QString &rules) +{ + auto tmpRules = rules; + m_rules = tmpRules.replace(";", "\n"); + QLoggingCategory::setFilterRules(m_rules); +} + +void MLogger::appendRules(const QString &rules) +{ + QString tmpRules = rules; + tmpRules = tmpRules.replace(";", "\n"); + auto tmplist = tmpRules.split('\n'); + for (int i = 0; i < tmplist.count(); i++) + if (m_rules.contains(tmplist.at(i))) { + tmplist.removeAt(i); + i--; + } + if (tmplist.isEmpty()) + return; + m_rules.isEmpty() ? m_rules = tmplist.join("\n") + : m_rules += "\n" + tmplist.join("\n"); +} diff --git a/deepin-system-monitor-daemon/src/logger.h b/deepin-system-monitor-daemon/src/logger.h new file mode 100644 index 00000000..946fa7a3 --- /dev/null +++ b/deepin-system-monitor-daemon/src/logger.h @@ -0,0 +1,28 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include + +DCORE_BEGIN_NAMESPACE +class DConfig; +DCORE_END_NAMESPACE + +class MLogger : public QObject +{ + Q_OBJECT +public: + explicit MLogger(QObject *parent = nullptr); + ~MLogger(); + + inline QString rules() const { return m_rules; } + void setRules(const QString &rules); + +private: + void appendRules(const QString &rules); + +private: + QString m_rules; + Dtk::Core::DConfig *m_config; +}; diff --git a/deepin-system-monitor-daemon/src/memoryprofile.cpp b/deepin-system-monitor-daemon/src/memoryprofile.cpp index bc373113..f23aed0d 100644 --- a/deepin-system-monitor-daemon/src/memoryprofile.cpp +++ b/deepin-system-monitor-daemon/src/memoryprofile.cpp @@ -3,15 +3,14 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "memoryprofile.h" - +#include "ddlog.h" #include #include #define PROC_MEM_INFOI_PATH "/proc/meminfo" - +using namespace DDLog; MemoryProfile::MemoryProfile(QObject *parent) - : QObject(parent) - , mMemUsage(0) + : QObject(parent), mMemUsage(0) { } @@ -32,7 +31,7 @@ double MemoryProfile::updateSystemMemoryUsage() // MemFree: 1455488 kB // MemAvailable: 5931304 kB if (lineData1.size() == 0 || lineData2.size() == 0 || lineData3.size() == 0) { - qWarning() << QString(" read %1 file fail !").arg(PROC_MEM_INFOI_PATH) << lineData1 << lineData2 << lineData3; + qCWarning(app) << QString(" read %1 file fail !").arg(PROC_MEM_INFOI_PATH) << lineData1 << lineData2 << lineData3; return memUsage; } @@ -42,7 +41,7 @@ double MemoryProfile::updateSystemMemoryUsage() QStringList list3 = QString(lineData3).split(" ", QString::SkipEmptyParts); if (list1.size() < 3 || list2.size() < 3 || list3.size() < 3) { - qWarning() << QString(" parse %1 file fail !").arg(PROC_MEM_INFOI_PATH) << list1 << list2 << list3; + qCWarning(app) << QString(" parse %1 file fail !").arg(PROC_MEM_INFOI_PATH) << list1 << list2 << list3; return memUsage; } @@ -52,14 +51,14 @@ double MemoryProfile::updateSystemMemoryUsage() memDataMap[list3.at(0)] = list3.at(1).toInt(); // 为返回值赋值,计算内存占用率 - if (memDataMap.contains("MemTotal:") && memDataMap.contains("MemAvailable:") && memDataMap["MemTotal:"] != 0) { + if (memDataMap.contains("MemTotal:") && memDataMap.contains("MemAvailable:") && memDataMap["MemTotal:"] != 0) { memUsage = (memDataMap["MemTotal:"] - memDataMap["MemAvailable:"]) * 100.0 / memDataMap["MemTotal:"]; mMemUsage = memUsage; } else { - qWarning() << QString(" extract mem data fail !") << memDataMap; + qCWarning(app) << QString(" extract mem data fail !") << memDataMap; } } else { - qWarning() << QString(" file %1 open fail !").arg(PROC_MEM_INFOI_PATH); + qCWarning(app) << QString(" file %1 open fail !").arg(PROC_MEM_INFOI_PATH); } return memUsage; @@ -69,4 +68,3 @@ double MemoryProfile::getMemUsage() { return mMemUsage; } - diff --git a/deepin-system-monitor-daemon/src/settinghandler.cpp b/deepin-system-monitor-daemon/src/settinghandler.cpp index c8d2aade..502f1a0c 100644 --- a/deepin-system-monitor-daemon/src/settinghandler.cpp +++ b/deepin-system-monitor-daemon/src/settinghandler.cpp @@ -3,7 +3,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "settinghandler.h" - +#include "ddlog.h" #include #include @@ -13,6 +13,8 @@ #include #include +using namespace DDLog; + // 警报数据,由产品定义 const static int MinAlarmCpuUsage = 30; const static int MaxAlarmCpuUsage = 100; @@ -22,9 +24,7 @@ const static int MinAlarmInterval = 5; const static int MaxAlarmInterval = 60; SettingHandler::SettingHandler(QObject *parent) - : QObject(parent) - , mSettings(nullptr) - , mBackend(nullptr) + : QObject(parent), mSettings(nullptr), mBackend(nullptr) { QString orgName = qApp->organizationName(); if (orgName.isEmpty()) { @@ -33,9 +33,9 @@ SettingHandler::SettingHandler(QObject *parent) //配置文件路径: ~/.config/deepin/deepin-system-monitor/protection.conf QString strConfigPath = QString("%1/%2/%3/protection.conf") - .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) - .arg(orgName) - .arg("deepin-system-monitor"); + .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) + .arg(orgName) + .arg("deepin-system-monitor"); mBackend = new Dtk::Core::QSettingBackend(strConfigPath); mSettings = DSettings::fromJsonFile(":/resources/settings.json"); @@ -49,7 +49,7 @@ SettingHandler::SettingHandler(QObject *parent) auto keys = mValueRange.keys(); foreach (auto it, keys) { - qDebug() << __FUNCTION__ << __LINE__ << ",key: " << it << ", range: " << mValueRange[it]; + qCDebug(app) << __FUNCTION__ << __LINE__ << ",key: " << it << ", range: " << mValueRange[it]; } if (mSettings != nullptr) { @@ -78,7 +78,7 @@ QVariant SettingHandler::getOptionValue(const QString key) if (isCompelted() && mSettings->keys().contains(key)) { return mSettings->getOption(key); } else { - qWarning() << __FUNCTION__ << __LINE__ << QString("can not find conf[%1]!").arg(key) + qCWarning(app) << __FUNCTION__ << __LINE__ << QString("can not find conf[%1]!").arg(key) << ", compeletd:" << isCompelted() << ", avalid keys:" << mSettings->keys(); } @@ -94,7 +94,7 @@ bool SettingHandler::changedOptionValue(const QString key, const QVariant value) mSettings->sync(); return true; } else { - qWarning() << __FUNCTION__ << __LINE__ << QString("change conf[%1,%2] fail !").arg(key).arg(value.toString()) + qCWarning(app) << __FUNCTION__ << __LINE__ << QString("change conf[%1,%2] fail !").arg(key).arg(value.toString()) << ", compeletd:" << isCompelted() << ", avalid keys:" << mSettings->keys(); } @@ -122,7 +122,7 @@ QPair SettingHandler::getValueRange(const QString key) if (mValueRange.contains(key)) { range = mValueRange[key]; } - return range; + return range; } QList SettingHandler::itemKeys() diff --git a/deepin-system-monitor-daemon/src/systemmonitorservice.cpp b/deepin-system-monitor-daemon/src/systemmonitorservice.cpp index 44a8db54..9aeefe93 100644 --- a/deepin-system-monitor-daemon/src/systemmonitorservice.cpp +++ b/deepin-system-monitor-daemon/src/systemmonitorservice.cpp @@ -3,7 +3,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "systemmonitorservice.h" - +#include "ddlog.h" #include #include @@ -14,16 +14,21 @@ #include #include +using namespace DDLog; + // 打印DBus调用者信息 -#define PrintDBusCaller() { \ - if(calledFromDBus()) { \ - QDBusConnection conn = connection(); \ - QDBusMessage msg = message(); \ - pid_t callerPid = static_cast(conn.interface()->servicePid(msg.service()).value()); \ - qDebug() << "DBus service caller:" << conn.interface()->serviceOwner(msg.service()).value() \ - << ",Uid:" << conn.interface()->serviceUid(msg.service()).value() \ - << ",Pid:" << callerPid \ - << ",Process name:" << getNameByPid(callerPid); } } +#define PrintDBusCaller() \ + { \ + if (calledFromDBus()) { \ + QDBusConnection conn = connection(); \ + QDBusMessage msg = message(); \ + pid_t callerPid = static_cast(conn.interface()->servicePid(msg.service()).value()); \ + qCDebug(app) << "DBus service caller:" << conn.interface()->serviceOwner(msg.service()).value() \ + << ",Uid:" << conn.interface()->serviceUid(msg.service()).value() \ + << ",Pid:" << callerPid \ + << ",Process name:" << getNameByPid(callerPid); \ + } \ + } // 通过PID获取进程名称 QString getNameByPid(pid_t pid) @@ -45,18 +50,12 @@ QString getNameByPid(pid_t pid) #define AlarmMessageTimeOut 10000 SystemMonitorService::SystemMonitorService(const char *name, QObject *parent) - : QObject(parent) - , mProtectionStatus(InitAlarmOn) - , mAlarmInterval(InitAlarmInterval) - , mAlarmCpuUsage(InitAlarmCpuUsage) - , mAlarmMemoryUsage(InitAlarmMemUsage) - , mCpuUsage(0) - , mMemoryUsage(0) - , mMoniterTimer(this) -// , mLastAlarmTimeStamp(0) - , mSettings(this) - , mCpu(this) - , mMem(this) + : QObject(parent), mProtectionStatus(InitAlarmOn), mAlarmInterval(InitAlarmInterval), mAlarmCpuUsage(InitAlarmCpuUsage), mAlarmMemoryUsage(InitAlarmMemUsage), mCpuUsage(0), mMemoryUsage(0), mMoniterTimer(this) + // , mLastAlarmTimeStamp(0) + , + mSettings(this), + mCpu(this), + mMem(this) { if (mSettings.isCompelted()) { mProtectionStatus = mSettings.getOptionValue(AlarmStatusOptionName).toBool(); @@ -64,7 +63,6 @@ SystemMonitorService::SystemMonitorService(const char *name, QObject *parent) mAlarmMemoryUsage = mSettings.getOptionValue(AlarmMemUsageOptionName).toInt(); mAlarmInterval = mSettings.getOptionValue(AlarmIntervalOptionName).toInt(); mLastAlarmTimeStamp = mSettings.getOptionValue(AlarmLastTimeOptionName).toLongLong(); - } // 初始化Cpu占用率 @@ -80,11 +78,10 @@ SystemMonitorService::SystemMonitorService(const char *name, QObject *parent) mMoniterTimer.start(); QDBusConnection::RegisterOptions opts = - QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals | - QDBusConnection::ExportAllProperties; + QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals | QDBusConnection::ExportAllProperties; QDBusConnection::connectToBus(QDBusConnection::SessionBus, QString(name)) - .registerObject("/org/deepin/SystemMonitorDaemon", this, opts); + .registerObject("/org/deepin/SystemMonitorDaemon", this, opts); } SystemMonitorService::~SystemMonitorService() @@ -94,14 +91,16 @@ SystemMonitorService::~SystemMonitorService() bool SystemMonitorService::getSystemProtectionStatus() { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Get Protection Status:" << mProtectionStatus; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Get Protection Status:" << mProtectionStatus; return mProtectionStatus; } void SystemMonitorService::setSystemProtectionStatus(bool status) { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Set Protection Status:" << status; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Set Protection Status:" << status; if (mProtectionStatus != status) { mProtectionStatus = status; @@ -115,28 +114,32 @@ void SystemMonitorService::setSystemProtectionStatus(bool status) int SystemMonitorService::getCpuUsage() { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Get Cpu Usage:" << mCpuUsage; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Get Cpu Usage:" << mCpuUsage; return mCpuUsage; } int SystemMonitorService::getMemoryUsage() { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Get Memory Usage:" << mMemoryUsage; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Get Memory Usage:" << mMemoryUsage; return mMemoryUsage; } int SystemMonitorService::getAlarmMsgInterval() { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Get Alarm Msg Interval:" << mAlarmInterval; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Get Alarm Msg Interval:" << mAlarmInterval; return mAlarmInterval; } void SystemMonitorService::setAlarmMsgInterval(int interval) { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Set Alarm Msg Interval:" << interval; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Set Alarm Msg Interval:" << interval; // 根据需求 if (mSettings.isVaildValue(AlarmIntervalOptionName, interval)) { @@ -154,14 +157,16 @@ void SystemMonitorService::setAlarmMsgInterval(int interval) qint64 SystemMonitorService::getAlaramLastTimeInterval() { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Get Alarm Last Time:" << mLastAlarmTimeStamp; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Get Alarm Last Time:" << mLastAlarmTimeStamp; return mLastAlarmTimeStamp; } void SystemMonitorService::setAlaramLastTimeInterval(qint64 lastTime) { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Set Alarm Last Time:" << lastTime; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Set Alarm Last Time:" << lastTime; // 根据需求 if (mSettings.isVaildValue(AlarmLastTimeOptionName, lastTime)) { @@ -179,14 +184,16 @@ void SystemMonitorService::setAlaramLastTimeInterval(qint64 lastTime) int SystemMonitorService::getAlarmUsageOfCpu() { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Get Alarm Usage Of Cpu:" << mAlarmCpuUsage; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Get Alarm Usage Of Cpu:" << mAlarmCpuUsage; return mAlarmCpuUsage; } void SystemMonitorService::setAlarmUsageOfCpu(int usage) { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Set Alarm Usage Of Cpu:" << usage; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Set Alarm Usage Of Cpu:" << usage; // 根据需求 if (mSettings.isVaildValue(AlarmCpuUsageOptionName, usage)) { @@ -204,14 +211,16 @@ void SystemMonitorService::setAlarmUsageOfCpu(int usage) int SystemMonitorService::getAlarmUsageOfMemory() { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Get Alarm Usage Of Memory:" << mAlarmMemoryUsage; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Get Alarm Usage Of Memory:" << mAlarmMemoryUsage; return mAlarmMemoryUsage; } void SystemMonitorService::setAlarmUsageOfMemory(int usage) { PrintDBusCaller() - qDebug() << __FUNCTION__ << __LINE__ << " Set Alarm Usage Of Memory:" << usage; + qCDebug(app) + << __FUNCTION__ << __LINE__ << " Set Alarm Usage Of Memory:" << usage; // 根据需求 if (mSettings.isVaildValue(AlarmMemUsageOptionName, usage)) { @@ -230,13 +239,13 @@ void SystemMonitorService::showDeepinSystemMoniter() { PrintDBusCaller() - QString cmd("gdbus call -e -d com.deepin.SystemMonitorServer -o /com/deepin/SystemMonitorServer -m com.deepin.SystemMonitorServer.showDeepinSystemMoniter"); - QTimer::singleShot(100, this, [ = ]() { QProcess::startDetached(cmd); }); + QString cmd("gdbus call -e -d com.deepin.SystemMonitorServer -o /com/deepin/SystemMonitorServer -m com.deepin.SystemMonitorServer.showDeepinSystemMoniter"); + QTimer::singleShot(100, this, [=]() { QProcess::startDetached(cmd); }); } void SystemMonitorService::changeAlarmItem(const QString &item, const QDBusVariant &value) { - qDebug() << __FUNCTION__ << __LINE__ << ", item:" << item << ", value:" << value.variant(); + qCDebug(app) << __FUNCTION__ << __LINE__ << ", item:" << item << ", value:" << value.variant(); if (mSettings.itemKeys().contains(item) && mSettings.isVaildValue(item, value.variant())) { if (mSettings.isVaildValue(item, value.variant())) { if (item == AlarmStatusOptionName) { @@ -268,7 +277,7 @@ bool SystemMonitorService::checkCpuAlarm() if (mCpuUsage >= mAlarmCpuUsage && diffTime >= timeGap) { mLastAlarmTimeStamp = curTimeStamp; QString cmd = QString("gdbus call -e -d com.deepin.SystemMonitorServer -o /com/deepin/SystemMonitorServer -m com.deepin.SystemMonitorServer.showCpuAlarmNotify \"%1\" ").arg(QString::number(mCpuUsage)); - QTimer::singleShot(100, this, [ = ]() { QProcess::startDetached(cmd); }); + QTimer::singleShot(100, this, [=]() { QProcess::startDetached(cmd); }); } return false; @@ -283,7 +292,7 @@ bool SystemMonitorService::checkMemoryAlarm() if (mMemoryUsage >= mAlarmMemoryUsage && diffTime > timeGap) { mLastAlarmTimeStamp = curTimeStamp; QString cmd = QString("gdbus call -e -d com.deepin.SystemMonitorServer -o /com/deepin/SystemMonitorServer -m com.deepin.SystemMonitorServer.showMemoryAlarmNotify \"%1\" ").arg(QString::number(mMemoryUsage)); - QTimer::singleShot(100, this, [ = ]() { QProcess::startDetached(cmd); }); + QTimer::singleShot(100, this, [=]() { QProcess::startDetached(cmd); }); } return false; diff --git a/deepin-system-monitor-main/CMakeLists.txt b/deepin-system-monitor-main/CMakeLists.txt index eac42467..2b0baa5a 100644 --- a/deepin-system-monitor-main/CMakeLists.txt +++ b/deepin-system-monitor-main/CMakeLists.txt @@ -107,6 +107,8 @@ set(HPP_GLOBAL smooth_curve_generator.h settings.h detailwidgetmanager.h + logger.h + ddlog.h ) set(CPP_GLOBAL main.cpp @@ -121,6 +123,7 @@ set(CPP_GLOBAL smooth_curve_generator.cpp settings.cpp detailwidgetmanager.cpp + logger.cpp ) set(HPP_COMMON @@ -604,6 +607,7 @@ set(LIBS ${LIB_NL3_ROUTE_LIBRARIES} ${LIB_UDEV_LIBRARIES} # ${DFrameworkDBus_LIBRARIES} # chinalife + Dtk::Core ) if (USE_DEEPIN_WAYLAND) diff --git a/deepin-system-monitor-main/common/common.h b/deepin-system-monitor-main/common/common.h index d127272f..5701effb 100644 --- a/deepin-system-monitor-main/common/common.h +++ b/deepin-system-monitor-main/common/common.h @@ -18,9 +18,9 @@ #include #include #include - +#include "ddlog.h" class QPainter; - +using namespace DDLog; namespace common { namespace compat { @@ -29,7 +29,8 @@ template struct Callback; template -struct Callback { +struct Callback +{ template static Ret callback(Args... args) { @@ -40,25 +41,28 @@ struct Callback { template std::function Callback::func; -} // namespace compat +} // namespace compat namespace alloc { -struct uFDClose { +struct uFDClose +{ void operator()(int *fd) { close(*fd); } }; -struct uFileClose { +struct uFileClose +{ void operator()(FILE *fp) { fclose(fp); } }; -struct uCloseDir { +struct uCloseDir +{ void operator()(DIR *dir) { closedir(dir); @@ -69,7 +73,7 @@ using uFD = std::unique_ptr; using uFile = std::unique_ptr; using uDir = std::unique_ptr; -} // namespace alloc +} // namespace alloc namespace init { @@ -92,8 +96,8 @@ extern unsigned long HZ; #define CPU_AVERAGE_MAX_FREQUENCY 2300 //CPU最大主频 enum CPUMaxFreq { - High, //>=2.3GHz - Low //>=2.3GHz + High, //>=2.3GHz + Low //>=2.3GHz }; extern CPUMaxFreq CPUPerformance; @@ -101,25 +105,25 @@ extern CPUMaxFreq CPUPerformance; void global_init(); void WaylandSearchCentered(); -} // namespace init +} // namespace init namespace format { enum SizeUnit { - B, // 1024 ^ 0 - KB, // 1024 ^ 1 - MB, // 1024 ^ 2 - GB, // 1024 ^ 3 - TB, // 1024 ^ 4 - PB, // 1024 ^ 5 - EB // 1024 ^ 6 + B, // 1024 ^ 0 + KB, // 1024 ^ 1 + MB, // 1024 ^ 2 + GB, // 1024 ^ 3 + TB, // 1024 ^ 4 + PB, // 1024 ^ 5 + EB // 1024 ^ 6 }; -const char *const UnitSuffix[] = {"B", "K", "M", "G", "T", "P", "E"}; +const char *const UnitSuffix[] = { "B", "K", "M", "G", "T", "P", "E" }; //网络使用单位bite -const char *const UnitSuffixnet[] = {"b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb"}; +const char *const UnitSuffixnet[] = { "b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb" }; //内存、磁盘使用单位Byte -const char *const UnitSuffixother[] = {"B", "KB", "MB", "GB", "TB", "PB", "EB"}; +const char *const UnitSuffixother[] = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //内存、磁盘统一单位 QString formatUnit_memory_disk(QVariant size, SizeUnit base = B, int prec = 1, bool isSpeed = false); @@ -127,40 +131,42 @@ QString formatUnit_memory_disk(QVariant size, SizeUnit base = B, int prec = 1, b QString formatUnit_net(QVariant size, SizeUnit base = B, int prec = 1, bool isSpeed = false); enum HzUnit { - KHz, // 10 ^ 3 - MHz, // 10 ^ 6 - GHz, // 10 ^ 9 - THz, // 10 ^ 12 - PHz, // 10 ^ 15 - EHz, // 10 ^ 18 - ZHz // 10 ^ 21 + KHz, // 10 ^ 3 + MHz, // 10 ^ 6 + GHz, // 10 ^ 9 + THz, // 10 ^ 12 + PHz, // 10 ^ 15 + EHz, // 10 ^ 18 + ZHz // 10 ^ 21 }; -const char *const HzUnitSuffix[] = {"KHz", "MHz", "GHz", "THz", "PHz", "EHz", "ZHz"}; +const char *const HzUnitSuffix[] = { "KHz", "MHz", "GHz", "THz", "PHz", "EHz", "ZHz" }; QString formatHz(quint32 freq, HzUnit base = KHz, int prec = 2); -} // namespace format +} // namespace format namespace error { inline void print_errno(decltype(errno) e, const QString msg) { - qWarning() << QString("Error: [%1] %2, ").arg(e).arg(strerror(e)) << msg; + qCWarning(app) << QString("Error: [%1] %2, ").arg(e).arg(strerror(e)) << msg; } -} // namespace error +} // namespace error namespace time { inline const struct timeval operator-(const struct timeval &lhs, const struct timeval &rhs) { - struct timeval res { + struct timeval res + { }; timersub(&lhs, &rhs, &res); return res; } inline const struct timeval operator+(const struct timeval &lhs, const struct timeval &rhs) { - struct timeval res { + struct timeval res + { }; timeradd(&lhs, &rhs, &res); return res; @@ -176,9 +182,9 @@ inline struct timeval &operator+=(struct timeval &lhs, const struct timeval &rhs return lhs; } -} // namespace time +} // namespace time -int getStatusBarMaxWidth(); +int getStatusBarMaxWidth(); void displayShortcutHelpDialog(const QRect &rect); void drawLoadingRing(QPainter &painter, int centerX, int centerY, int radius, int penWidth, int loadingAngle, int rotationAngle, QColor foregroundColor, @@ -189,6 +195,6 @@ void drawRing(QPainter &painter, int centerX, int centerY, int radius, int penWi void openFilePathItem(const QString &path); bool startWithHanzi(const QString &text); -} // namespace common +} // namespace common #endif diff --git a/deepin-system-monitor-main/common/han_latin.cpp b/deepin-system-monitor-main/common/han_latin.cpp index ef73a370..3d0e6915 100644 --- a/deepin-system-monitor-main/common/han_latin.cpp +++ b/deepin-system-monitor-main/common/han_latin.cpp @@ -4,7 +4,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "han_latin.h" - +#include "ddlog.h" #include #include #include @@ -20,7 +20,7 @@ using namespace std; using namespace icu; - +using namespace DDLog; namespace util { namespace common { @@ -33,15 +33,15 @@ static QString parseError(const QString &words, UErrorCode &ec, const UParseErro #undef u_errorName #define UERRORNAME U_DEF2_ICU_ENTRY_POINT_RENAME(u_errorName, U_ICU_VERSION_SUFFIX) errbuf = QString( - "Error[%1]: %2 convert %3 to PINYIN failed. [line:%4 offset:%5 " - "preContext: %6 postContext: %7]") - .arg(ec) - .arg(UERRORNAME(ec)) - .arg(words) - .arg(pe.line) - .arg(pe.offset) - .arg(QString::fromStdString(UnicodeString(pe.preContext).toUTF8String(pre))) - .arg(QString::fromStdString(UnicodeString(pe.postContext).toUTF8String(post))); + "Error[%1]: %2 convert %3 to PINYIN failed. [line:%4 offset:%5 " + "preContext: %6 postContext: %7]") + .arg(ec) + .arg(UERRORNAME(ec)) + .arg(words) + .arg(pe.line) + .arg(pe.offset) + .arg(QString::fromStdString(UnicodeString(pe.preContext).toUTF8String(pre))) + .arg(QString::fromStdString(UnicodeString(pe.postContext).toUTF8String(post))); return errbuf; } @@ -52,25 +52,25 @@ QString convHanToLatin(const QString &words) UErrorCode ec = U_ZERO_ERROR; UParseError pe {}; unique_ptr tr(Transliterator::createInstance( - TRANSLITERATION_HAN_LATIN, UTransDirection::UTRANS_FORWARD, pe, ec)); + TRANSLITERATION_HAN_LATIN, UTransDirection::UTRANS_FORWARD, pe, ec)); UnicodeString ubuf = UnicodeString::fromUTF8(StringPiece(words.toStdString())); // from hanzi to latin tr->transliterate(ubuf); if (U_FAILURE(ec)) { - qDebug() << parseError(words, ec, pe); + qCDebug(app) << parseError(words, ec, pe); result = words; } else { ec = U_ZERO_ERROR; pe = {}; unique_ptr tr2(Transliterator::createInstance( - TRANSLITERATION_LATIN_ASCII, UTransDirection::UTRANS_FORWARD, pe, ec)); + TRANSLITERATION_LATIN_ASCII, UTransDirection::UTRANS_FORWARD, pe, ec)); // from latin to ascii (pinyin) tr2->transliterate(ubuf); if (U_FAILURE(ec)) { - qDebug() << parseError(words, ec, pe); + qCDebug(app) << parseError(words, ec, pe); result = words; } else { std::string buffer; @@ -81,5 +81,5 @@ QString convHanToLatin(const QString &words) return result; } -} // namespace common -} // namespace util +} // namespace common +} // namespace util diff --git a/deepin-system-monitor-main/common/hash.cpp b/deepin-system-monitor-main/common/hash.cpp index 59c26429..7f8a4a19 100644 --- a/deepin-system-monitor-main/common/hash.cpp +++ b/deepin-system-monitor-main/common/hash.cpp @@ -14,9 +14,9 @@ #include #include #if defined HAVE_SYS_RANDOM_H -#include -#elif defined HAVE_SYS_CALL && defined HAVE_SYS_GETRANDOM -#include +# include +#elif defined HAVE_SYS_CALL && defined HAVE_SYS_GETRANDOM +# include #endif #include @@ -38,8 +38,8 @@ inline uint64_t rotl64(uint64_t x, int8_t r) return (x << r) | (x >> (64 - r)); } -#define ROTL32(x,y) rotl32(x,y) -#define ROTL64(x,y) rotl64(x,y) +#define ROTL32(x, y) rotl32(x, y) +#define ROTL64(x, y) rotl64(x, y) #define BIG_CONSTANT(x) (x##LLU) @@ -121,10 +121,18 @@ void hash_x86_32(const void *key, int len, uint32_t seed, uint32_t *out) uint32_t k1 = 0; switch (len & 3) { - case 3: k1 ^= uint32_t(tail[2] << 16); [[clang::fallthrough]]; - case 2: k1 ^= uint32_t(tail[1] << 8); [[clang::fallthrough]]; - case 1: k1 ^= tail[0]; - k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; + case 3: + k1 ^= uint32_t(tail[2] << 16); + [[clang::fallthrough]]; + case 2: + k1 ^= uint32_t(tail[1] << 8); + [[clang::fallthrough]]; + case 1: + k1 ^= tail[0]; + k1 *= c1; + k1 = ROTL32(k1, 15); + k1 *= c2; + h1 ^= k1; }; //---------- @@ -165,21 +173,41 @@ void hash_x86_128(const void *key, const int len, uint32_t seed, uint64_t out[2] uint32_t k3 = getblock32(blocks, i * 4 + 2); uint32_t k4 = getblock32(blocks, i * 4 + 3); - k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; + k1 *= c1; + k1 = ROTL32(k1, 15); + k1 *= c2; + h1 ^= k1; - h1 = ROTL32(h1, 19); h1 += h2; h1 = h1 * 5 + 0x561ccd1b; + h1 = ROTL32(h1, 19); + h1 += h2; + h1 = h1 * 5 + 0x561ccd1b; - k2 *= c2; k2 = ROTL32(k2, 16); k2 *= c3; h2 ^= k2; + k2 *= c2; + k2 = ROTL32(k2, 16); + k2 *= c3; + h2 ^= k2; - h2 = ROTL32(h2, 17); h2 += h3; h2 = h2 * 5 + 0x0bcaa747; + h2 = ROTL32(h2, 17); + h2 += h3; + h2 = h2 * 5 + 0x0bcaa747; - k3 *= c3; k3 = ROTL32(k3, 17); k3 *= c4; h3 ^= k3; + k3 *= c3; + k3 = ROTL32(k3, 17); + k3 *= c4; + h3 ^= k3; - h3 = ROTL32(h3, 15); h3 += h4; h3 = h3 * 5 + 0x96cd1c35; + h3 = ROTL32(h3, 15); + h3 += h4; + h3 = h3 * 5 + 0x96cd1c35; - k4 *= c4; k4 = ROTL32(k4, 18); k4 *= c1; h4 ^= k4; + k4 *= c4; + k4 = ROTL32(k4, 18); + k4 *= c1; + h4 ^= k4; - h4 = ROTL32(h4, 13); h4 += h1; h4 = h4 * 5 + 0x32ac3b17; + h4 = ROTL32(h4, 13); + h4 += h1; + h4 = h4 * 5 + 0x32ac3b17; } //---------- @@ -193,45 +221,94 @@ void hash_x86_128(const void *key, const int len, uint32_t seed, uint64_t out[2] uint32_t k4 = 0; switch (len & 15) { - case 15: k4 ^= uint32_t(tail[14] << 16); [[clang::fallthrough]]; - case 14: k4 ^= uint32_t(tail[13] << 8); [[clang::fallthrough]]; - case 13: k4 ^= uint32_t(tail[12] << 0); - k4 *= c4; k4 = ROTL32(k4, 18); k4 *= c1; h4 ^= k4; + case 15: + k4 ^= uint32_t(tail[14] << 16); + [[clang::fallthrough]]; + case 14: + k4 ^= uint32_t(tail[13] << 8); + [[clang::fallthrough]]; + case 13: + k4 ^= uint32_t(tail[12] << 0); + k4 *= c4; + k4 = ROTL32(k4, 18); + k4 *= c1; + h4 ^= k4; [[clang::fallthrough]]; - case 12: k3 ^= uint32_t(tail[11] << 24); [[clang::fallthrough]]; - case 11: k3 ^= uint32_t(tail[10] << 16); [[clang::fallthrough]]; - case 10: k3 ^= uint32_t(tail[ 9] << 8); [[clang::fallthrough]]; - case 9: k3 ^= uint32_t(tail[ 8] << 0); - k3 *= c3; k3 = ROTL32(k3, 17); k3 *= c4; h3 ^= k3; + case 12: + k3 ^= uint32_t(tail[11] << 24); [[clang::fallthrough]]; - case 8: k2 ^= uint32_t(tail[ 7] << 24); [[clang::fallthrough]]; - case 7: k2 ^= uint32_t(tail[ 6] << 16); [[clang::fallthrough]]; - case 6: k2 ^= uint32_t(tail[ 5] << 8); [[clang::fallthrough]]; - case 5: k2 ^= uint32_t(tail[ 4] << 0); - k2 *= c2; k2 = ROTL32(k2, 16); k2 *= c3; h2 ^= k2; + case 11: + k3 ^= uint32_t(tail[10] << 16); [[clang::fallthrough]]; - case 4: k1 ^= uint32_t(tail[ 3] << 24); [[clang::fallthrough]]; - case 3: k1 ^= uint32_t(tail[ 2] << 16); [[clang::fallthrough]]; - case 2: k1 ^= uint32_t(tail[ 1] << 8); [[clang::fallthrough]]; - case 1: k1 ^= uint32_t(tail[ 0] << 0); - k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; + case 10: + k3 ^= uint32_t(tail[9] << 8); + [[clang::fallthrough]]; + case 9: + k3 ^= uint32_t(tail[8] << 0); + k3 *= c3; + k3 = ROTL32(k3, 17); + k3 *= c4; + h3 ^= k3; + [[clang::fallthrough]]; + case 8: + k2 ^= uint32_t(tail[7] << 24); + [[clang::fallthrough]]; + case 7: + k2 ^= uint32_t(tail[6] << 16); + [[clang::fallthrough]]; + case 6: + k2 ^= uint32_t(tail[5] << 8); + [[clang::fallthrough]]; + case 5: + k2 ^= uint32_t(tail[4] << 0); + k2 *= c2; + k2 = ROTL32(k2, 16); + k2 *= c3; + h2 ^= k2; + [[clang::fallthrough]]; + case 4: + k1 ^= uint32_t(tail[3] << 24); + [[clang::fallthrough]]; + case 3: + k1 ^= uint32_t(tail[2] << 16); + [[clang::fallthrough]]; + case 2: + k1 ^= uint32_t(tail[1] << 8); + [[clang::fallthrough]]; + case 1: + k1 ^= uint32_t(tail[0] << 0); + k1 *= c1; + k1 = ROTL32(k1, 15); + k1 *= c2; + h1 ^= k1; }; //---------- // finalization - h1 ^= uint32_t(len); h2 ^= uint32_t(len); h3 ^= uint32_t(len); h4 ^= uint32_t(len); + h1 ^= uint32_t(len); + h2 ^= uint32_t(len); + h3 ^= uint32_t(len); + h4 ^= uint32_t(len); - h1 += h2; h1 += h3; h1 += h4; - h2 += h1; h3 += h1; h4 += h1; + h1 += h2; + h1 += h3; + h1 += h4; + h2 += h1; + h3 += h1; + h4 += h1; h1 = fmix32(h1); h2 = fmix32(h2); h3 = fmix32(h3); h4 = fmix32(h4); - h1 += h2; h1 += h3; h1 += h4; - h2 += h1; h3 += h1; h4 += h1; + h1 += h2; + h1 += h3; + h1 += h4; + h2 += h1; + h3 += h1; + h4 += h1; out[0] = uint64_t(h2) << 32 | h1; out[1] = uint64_t(h4) << 32 | h3; @@ -259,13 +336,23 @@ void hash_x64_128(const void *key, const int len, uint32_t seed, uint64_t out[2] uint64_t k1 = getblock64(blocks, i * 2 + 0); uint64_t k2 = getblock64(blocks, i * 2 + 1); - k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1; + k1 *= c1; + k1 = ROTL64(k1, 31); + k1 *= c2; + h1 ^= k1; - h1 = ROTL64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; + h1 = ROTL64(h1, 27); + h1 += h2; + h1 = h1 * 5 + 0x52dce729; - k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2; + k2 *= c2; + k2 = ROTL64(k2, 33); + k2 *= c1; + h2 ^= k2; - h2 = ROTL64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; + h2 = ROTL64(h2, 31); + h2 += h1; + h2 = h2 * 5 + 0x38495ab5; } //---------- @@ -277,30 +364,65 @@ void hash_x64_128(const void *key, const int len, uint32_t seed, uint64_t out[2] uint64_t k2 = 0; switch (len & 15) { - case 15: k2 ^= (uint64_t(tail[14])) << 48; [[clang::fallthrough]]; - case 14: k2 ^= (uint64_t(tail[13])) << 40; [[clang::fallthrough]]; - case 13: k2 ^= (uint64_t(tail[12])) << 32; [[clang::fallthrough]]; - case 12: k2 ^= (uint64_t(tail[11])) << 24; [[clang::fallthrough]]; - case 11: k2 ^= (uint64_t(tail[10])) << 16; [[clang::fallthrough]]; - case 10: k2 ^= (uint64_t(tail[ 9])) << 8; [[clang::fallthrough]]; - case 9: k2 ^= (uint64_t(tail[ 8])) << 0; - k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2; + case 15: + k2 ^= (uint64_t(tail[14])) << 48; + [[clang::fallthrough]]; + case 14: + k2 ^= (uint64_t(tail[13])) << 40; + [[clang::fallthrough]]; + case 13: + k2 ^= (uint64_t(tail[12])) << 32; + [[clang::fallthrough]]; + case 12: + k2 ^= (uint64_t(tail[11])) << 24; + [[clang::fallthrough]]; + case 11: + k2 ^= (uint64_t(tail[10])) << 16; [[clang::fallthrough]]; - case 8: k1 ^= (uint64_t(tail[ 7])) << 56; [[clang::fallthrough]]; - case 7: k1 ^= (uint64_t(tail[ 6])) << 48; [[clang::fallthrough]]; - case 6: k1 ^= (uint64_t(tail[ 5])) << 40; [[clang::fallthrough]]; - case 5: k1 ^= (uint64_t(tail[ 4])) << 32; [[clang::fallthrough]]; - case 4: k1 ^= (uint64_t(tail[ 3])) << 24; [[clang::fallthrough]]; - case 3: k1 ^= (uint64_t(tail[ 2])) << 16; [[clang::fallthrough]]; - case 2: k1 ^= (uint64_t(tail[ 1])) << 8; [[clang::fallthrough]]; - case 1: k1 ^= (uint64_t(tail[ 0])) << 0; - k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1; + case 10: + k2 ^= (uint64_t(tail[9])) << 8; + [[clang::fallthrough]]; + case 9: + k2 ^= (uint64_t(tail[8])) << 0; + k2 *= c2; + k2 = ROTL64(k2, 33); + k2 *= c1; + h2 ^= k2; + [[clang::fallthrough]]; + case 8: + k1 ^= (uint64_t(tail[7])) << 56; + [[clang::fallthrough]]; + case 7: + k1 ^= (uint64_t(tail[6])) << 48; + [[clang::fallthrough]]; + case 6: + k1 ^= (uint64_t(tail[5])) << 40; + [[clang::fallthrough]]; + case 5: + k1 ^= (uint64_t(tail[4])) << 32; + [[clang::fallthrough]]; + case 4: + k1 ^= (uint64_t(tail[3])) << 24; + [[clang::fallthrough]]; + case 3: + k1 ^= (uint64_t(tail[2])) << 16; + [[clang::fallthrough]]; + case 2: + k1 ^= (uint64_t(tail[1])) << 8; + [[clang::fallthrough]]; + case 1: + k1 ^= (uint64_t(tail[0])) << 0; + k1 *= c1; + k1 = ROTL64(k1, 31); + k1 *= c2; + h1 ^= k1; }; //---------- // finalization - h1 ^= uint64_t(len); h2 ^= uint64_t(len); + h1 ^= uint64_t(len); + h2 ^= uint64_t(len); h1 += h2; h2 += h1; @@ -345,17 +467,17 @@ void init_seed() if (!ok) { int fd = open("/dev/urandom", O_RDONLY); if (fd == -1) { - qCritical() << "init seed from /dev/urandom failed"; + qCCritical(app) << "init seed from /dev/urandom failed"; abort(); } auto nr = read(fd, &global_seed, sizeof(uint32_t)); if (nr <= 0 || ulong(nr) < sizeof(uint32_t)) { - qCritical() << "init seed from /dev/urandom failed"; + qCCritical(app) << "init seed from /dev/urandom failed"; abort(); } close(fd); } } -} // namespace common -} // namespace util +} // namespace common +} // namespace util diff --git a/deepin-system-monitor-main/common/hash.h b/deepin-system-monitor-main/common/hash.h index 9e6ada75..e51ec70e 100644 --- a/deepin-system-monitor-main/common/hash.h +++ b/deepin-system-monitor-main/common/hash.h @@ -8,7 +8,8 @@ #include #include - +#include "ddlog.h" +using namespace DDLog; namespace util { namespace common { @@ -46,7 +47,7 @@ inline void hash(const void *key, int len, uint32_t seed, uint64_t out[2]) #endif } -} // namespace common -} // namespace util +} // namespace common +} // namespace util -#endif // HASH_H +#endif // HASH_H diff --git a/deepin-system-monitor-main/common/perf.cpp b/deepin-system-monitor-main/common/perf.cpp index f550a88f..fe463156 100644 --- a/deepin-system-monitor-main/common/perf.cpp +++ b/deepin-system-monitor-main/common/perf.cpp @@ -2,12 +2,13 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "perf.h" #include #include #include +using namespace DDLog; DebugTimeManager *DebugTimeManager::s_Instance = nullptr; @@ -36,6 +37,6 @@ void DebugTimeManager::endPointLinux(const QString &point) struct timeval tv; gettimeofday(&tv, nullptr); m_MapPoint[point].time = tv.tv_sec * 1000 + tv.tv_usec / 1000 - m_MapPoint[point].time; - qInfo() << QString("[GRABPOINT] %1 %2 time=%3ms").arg(point).arg(m_MapPoint[point].desc).arg(m_MapPoint[point].time); + qCInfo(app) << QString("[GRABPOINT] %1 %2 time=%3ms").arg(point).arg(m_MapPoint[point].desc).arg(m_MapPoint[point].time); } } diff --git a/deepin-system-monitor-main/dbus/dbus_object.cpp b/deepin-system-monitor-main/dbus/dbus_object.cpp index a77c75f5..4a3b3032 100644 --- a/deepin-system-monitor-main/dbus/dbus_object.cpp +++ b/deepin-system-monitor-main/dbus/dbus_object.cpp @@ -6,20 +6,19 @@ #include "dbus_object.h" #include "gui/main_window.h" #include "application.h" - +#include "ddlog.h" #include #include -#define DBUS_SERVER "com.deepin.systemMonitor" -#define DBUS_SERVER_PATH "/com/deepin/systemMonitor" - +#define DBUS_SERVER "com.deepin.systemMonitor" +#define DBUS_SERVER_PATH "/com/deepin/systemMonitor" +using namespace DDLog; QMutex DBusObject::mutex; QAtomicPointer DBusObject::instance; DBusObject &DBusObject::getInstance() { - if (instance.testAndSetOrdered(nullptr, nullptr)) - { + if (instance.testAndSetOrdered(nullptr, nullptr)) { QMutexLocker locker(&mutex); instance.testAndSetOrdered(nullptr, new DBusObject); @@ -35,7 +34,7 @@ bool DBusObject::registerOrNotify() QList args; QString error = notification.callWithArgumentList(QDBus::Block, "handleWindow", args).errorMessage(); if (!error.isEmpty()) - qInfo() << error; + qCInfo(app) << error; return false; } @@ -62,12 +61,11 @@ void DBusObject::handleWindow() internalMutex.unlock(); } -DBusObject::DBusObject(QObject *parent) : QObject(parent) +DBusObject::DBusObject(QObject *parent) + : QObject(parent) { - } DBusObject::~DBusObject() { - } diff --git a/deepin-system-monitor-main/dbus/dbusalarmnotify.cpp b/deepin-system-monitor-main/dbus/dbusalarmnotify.cpp index 640944e0..38eba532 100644 --- a/deepin-system-monitor-main/dbus/dbusalarmnotify.cpp +++ b/deepin-system-monitor-main/dbus/dbusalarmnotify.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "dbusalarmnotify.h" #include "helper.hpp" @@ -12,6 +12,8 @@ #include #include +using namespace DDLog; + #define AlarmMessageTimeOut 10000 QMutex DBusAlarmNotify::mutex; QAtomicPointer DBusAlarmNotify::instance = nullptr; @@ -47,7 +49,6 @@ void DBusAlarmNotify::showAlarmNotify(const QStringList &allArguments) showAlarmNotify(topic, msg, timeout); } } - } void DBusAlarmNotify::showAlarmNotify(QString topic, QString msg, int timeout) @@ -57,8 +58,8 @@ void DBusAlarmNotify::showAlarmNotify(QString topic, QString msg, int timeout) common::systemInfo().NotificationInterface, "Notify"); QStringList action; - action << "_open1" << tr("View"); //添加按钮 - QVariantMap inform; //按钮的点击操作 + action << "_open1" << tr("View"); //添加按钮 + QVariantMap inform; //按钮的点击操作 // 操作打开系统监视器 QString openSystemMonitor = QString("qdbus,org.deepin.SystemMonitorDaemon," "/org/deepin/SystemMonitorDaemon," @@ -67,26 +68,26 @@ void DBusAlarmNotify::showAlarmNotify(QString topic, QString msg, int timeout) inform.insert(QString("x-deepin-action-_open1"), openSystemMonitor); QList ddeArgs; - ddeArgs << QString("deepin-system-monitor"); // app name - ddeArgs << uint(0); // id = 0 不指定窗口 id - ddeArgs << QString("deepin-system-monitor"); // icon - ddeArgs << topic; // notify topic - ddeArgs << msg; // notify msg body - ddeArgs << action; // button - ddeArgs << inform; // button operation - ddeArgs << timeout; // notify timeout + ddeArgs << QString("deepin-system-monitor"); // app name + ddeArgs << uint(0); // id = 0 不指定窗口 id + ddeArgs << QString("deepin-system-monitor"); // icon + ddeArgs << topic; // notify topic + ddeArgs << msg; // notify msg body + ddeArgs << action; // button + ddeArgs << inform; // button operation + ddeArgs << timeout; // notify timeout ddeNotify.setArguments(ddeArgs); QDBusMessage replyMsg = QDBusConnection::sessionBus().call(ddeNotify); if (replyMsg.type() == QDBusMessage::ErrorMessage) { - qWarning() << __FUNCTION__ << __LINE__ << ", dde notify dbus method call fail , error name :" - << replyMsg.errorName() << " , error msg :" << replyMsg.errorMessage(); + qCWarning(app) << __FUNCTION__ << __LINE__ << ", dde notify dbus method call fail , error name :" + << replyMsg.errorName() << " , error msg :" << replyMsg.errorMessage(); QString cmd = QString("gdbus call -e -d org.deepin.SystemMonitorDaemon -o /org/deepin/SystemMonitorDaemon -m org.deepin.SystemMonitorDaemon.setAlaramLastTimeInterval 0"); QProcess::startDetached(cmd); } else { - qint64 lastAlarmTimeStamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); + qint64 lastAlarmTimeStamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); QString cmd = QString("gdbus call -e -d org.deepin.SystemMonitorDaemon -o /org/deepin/SystemMonitorDaemon -m org.deepin.SystemMonitorDaemon.setAlaramLastTimeInterval %1").arg(lastAlarmTimeStamp); QProcess::startDetached(cmd); } @@ -95,5 +96,4 @@ void DBusAlarmNotify::showAlarmNotify(QString topic, QString msg, int timeout) DBusAlarmNotify::DBusAlarmNotify(QObject *parent) : QObject(parent) { - } diff --git a/deepin-system-monitor-main/ddlog.h b/deepin-system-monitor-main/ddlog.h new file mode 100644 index 00000000..fad4bea8 --- /dev/null +++ b/deepin-system-monitor-main/ddlog.h @@ -0,0 +1,15 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef DDLOG_H +#define DDLOG_H +#include +#include +DCORE_USE_NAMESPACE + +namespace DDLog { +inline Q_LOGGING_CATEGORY(app, "org.deepin.system-monitor") +} + +#endif // DDLOG_H diff --git a/deepin-system-monitor-main/gui/accounts_widget.cpp b/deepin-system-monitor-main/gui/accounts_widget.cpp index fd017dcb..01b52a97 100644 --- a/deepin-system-monitor-main/gui/accounts_widget.cpp +++ b/deepin-system-monitor-main/gui/accounts_widget.cpp @@ -1,5 +1,5 @@ #include "accounts_widget.h" - +#include "ddlog.h" #include #include #include @@ -11,20 +11,18 @@ const QMargins ScrollAreaMargins(0, 0, 0, 0); const QString LogoutDescription = "Log out the user may cause data loss, log out or not?"; +using namespace DDLog; + AccountsWidget::AccountsWidget(QWidget *parent) - : QWidget(parent) - , m_userModel(new AccountsInfoModel(this)) - , m_userItemModel(new QStandardItemModel(this)) - , m_userlistView(new UserListView(this)) + : QWidget(parent), m_userModel(new AccountsInfoModel(this)), m_userItemModel(new QStandardItemModel(this)), m_userlistView(new UserListView(this)) { m_currentUserType = m_userModel->getCurrentUserType(); - qInfo() << "AccountsWidget Constructor line 20:" << "current user type:" << m_currentUserType; + qCInfo(app) << "AccountsWidget Constructor line 20:" + << "current user type:" << m_currentUserType; initUI(); initConnection(); addInfo(m_userModel); m_userlistView->resetStatus(m_userItemModel->index(0, 0)); - - } AccountsWidget::~AccountsWidget() @@ -37,16 +35,14 @@ AccountsWidget::~AccountsWidget() if (m_onlineIconList.size() > 0) { m_onlineIconList.clear(); } - } - void AccountsWidget::initUI() { // disable auto fill frame background setAutoFillBackground(false); // set frame background role -// setBackgroundRole(DPalette::Window); + // setBackgroundRole(DPalette::Window); // 禁用横向滚动条,防止内容被截断 QVBoxLayout *mainContentLayout = new QVBoxLayout(this); mainContentLayout->setMargin(0); @@ -73,8 +69,6 @@ void AccountsWidget::initUI() setFixedWidth(250); m_contextMenu = new DMenu(this); - - } void AccountsWidget::initConnection() @@ -84,30 +78,27 @@ void AccountsWidget::initConnection() connect(m_userlistView, &UserListView::signalRightButtonClicked, this, &AccountsWidget::onRightButtonClicked); connect(m_userlistView, &DListView::activated, m_userlistView, &QListView::clicked); - - /******************************* User Operation Menu on right Button Clicked******************************/ -// auto *connectAction = m_contextMenu->addAction("Connect"); -// connect(connectAction, &QAction::triggered, this, &AccountsWidget::onConnectTriggered); + // auto *connectAction = m_contextMenu->addAction("Connect"); + // connect(connectAction, &QAction::triggered, this, &AccountsWidget::onConnectTriggered); -// auto *disconnectAction = m_contextMenu->addAction("Disconnect"); -// connect(disconnectAction, &QAction::triggered, this, &AccountsWidget::onDisconnectTriggered); + // auto *disconnectAction = m_contextMenu->addAction("Disconnect"); + // connect(disconnectAction, &QAction::triggered, this, &AccountsWidget::onDisconnectTriggered); -// auto *logoutAction = m_contextMenu->addAction("log out"); -// connect(logoutAction, &QAction::triggered, this, &AccountsWidget::onLogoutTriggered); + // auto *logoutAction = m_contextMenu->addAction("log out"); + // connect(logoutAction, &QAction::triggered, this, &AccountsWidget::onLogoutTriggered); -// m_contextMenu->addSeparator(); + // m_contextMenu->addSeparator(); auto *EditAction = m_contextMenu->addAction(DApplication::translate("User.Account.Operation", "Edit account information")); connect(EditAction, &QAction::triggered, this, &AccountsWidget::onEditAccountTriggered); - -// //判断当前用户是否为管理员用户,非管理员用户不展示连接和注销功能 -// if (!(m_currentUserType == User::UserType::Administrator)) { -// connectAction->setVisible(false); -// logoutAction->setVisible(false); -// } + // //判断当前用户是否为管理员用户,非管理员用户不展示连接和注销功能 + // if (!(m_currentUserType == User::UserType::Administrator)) { + // connectAction->setVisible(false); + // logoutAction->setVisible(false); + // } /******************************* User Operation Menu on right Button Clicked******************************/ } @@ -122,37 +113,36 @@ void AccountsWidget::onUpdateUserList() } } //新增连接的用户 - qInfo() << m_userList.size() << m_userModel->userList().size(); + qCInfo(app) << m_userList.size() << m_userModel->userList().size(); for (auto user : m_userModel->userList()) { if (!m_userList.contains(user)) { addUser(user); } } - } void AccountsWidget::addInfo(AccountsInfoModel *model) { - qInfo() << "AccountsWidget addInfo line 130:" << "add info from list:" << model->userList(); + qCInfo(app) << "AccountsWidget addInfo line 130:" + << "add info from list:" << model->userList(); //给账户列表添加用户 for (auto user : model->userList()) { - qInfo() << "AccountsWidget addInfo line 132:" << "add user to listview:" << user->name(); + qCInfo(app) << "AccountsWidget addInfo line 132:" + << "add user to listview:" << user->name(); addUser(user); } - } void AccountsWidget::addUser(User *user) { //active - qInfo() << "AccountsWidget addUser line 141:" << "addUser begins:" << user->name(); + qCInfo(app) << "AccountsWidget addUser line 141:" + << "addUser begins:" << user->name(); m_userList << user; DStandardItem *item = new DStandardItem; item->setData(0, AccountsWidget::ItemDataRole); - - auto setTitelFunc = [ = ](int userType, DViewItemAction * subTitleAction) { - + auto setTitelFunc = [=](int userType, DViewItemAction *subTitleAction) { subTitleAction->setText(userType == User::UserType::Administrator ? DApplication::translate("User.Account.Type", "Administrator") : DApplication::translate("User.Account.Type", "Standard User")); }; @@ -160,31 +150,29 @@ void AccountsWidget::addUser(User *user) auto *subTitleAction = new DViewItemAction; setTitelFunc(user->userType(), subTitleAction); - qInfo() << "AccountsWidget addUser line 156:" << "subTitleAction text:" << subTitleAction->text(); - - + qCInfo(app) << "AccountsWidget addUser line 156:" + << "subTitleAction text:" << subTitleAction->text(); subTitleAction->setFontSize(DFontSizeManager::T8); subTitleAction->setTextColorRole(DPalette::TextTips); - item->setTextActionList({subTitleAction}); + item->setTextActionList({ subTitleAction }); -// DViewItemAction *onlineFlag = new DViewItemAction(Qt::AlignCenter | Qt::AlignRight, QSize(), QSize(), true); + // DViewItemAction *onlineFlag = new DViewItemAction(Qt::AlignCenter | Qt::AlignRight, QSize(), QSize(), true); -// OnlineIcon *onlineIcon = new OnlineIcon(m_userlistView->viewport()); -// onlineIcon->setFixedSize(8, 8); -// onlineFlag->setWidget(onlineIcon); -// item->setActionList(Qt::Edge::RightEdge, {onlineFlag}); -// if (!user->online()) { -// onlineIcon->setColor(QColor(Qt::gray)); -// } + // OnlineIcon *onlineIcon = new OnlineIcon(m_userlistView->viewport()); + // onlineIcon->setFixedSize(8, 8); + // onlineFlag->setWidget(onlineIcon); + // item->setActionList(Qt::Edge::RightEdge, {onlineFlag}); + // if (!user->online()) { + // onlineIcon->setColor(QColor(Qt::gray)); + // } -// onlineFlag->setVisible(true); -// if (onlineFlag->widget()) { -// onlineFlag->widget()->setVisible(true); -// } - -// m_onlineIconList << onlineIcon; + // onlineFlag->setVisible(true); + // if (onlineFlag->widget()) { + // onlineFlag->widget()->setVisible(true); + // } + // m_onlineIconList << onlineIcon; m_userItemModel->appendRow(item); @@ -206,7 +194,6 @@ void AccountsWidget::addUser(User *user) m_userList.push_front(user); m_userList.pop_back(); - } } @@ -216,16 +203,14 @@ void AccountsWidget::removeUser(User *user) m_userList.removeOne(user); -// //对于删除的用户Item,不显示小圆点 -// for (int i = m_userItemModel->rowCount(); i < m_onlineIconList.size(); i++) { -// m_onlineIconList.at(i)->setVisible(false); -// } + // //对于删除的用户Item,不显示小圆点 + // for (int i = m_userItemModel->rowCount(); i < m_onlineIconList.size(); i++) { + // m_onlineIconList.at(i)->setVisible(false); + // } m_userlistView->update(); } - - QPixmap AccountsWidget::pixmapToRound(const QPixmap &src) { if (src.isNull()) { @@ -248,7 +233,6 @@ QPixmap AccountsWidget::pixmapToRound(const QPixmap &src) return mask; } - QString AccountsWidget::getCurrentItemUserName() { //判断是否是全名 @@ -260,46 +244,35 @@ QString AccountsWidget::getCurrentItemUserName() return m_userlistView->currentIndex().data().toString(); } - void AccountsWidget::onItemClicked(const QModelIndex &index) { m_userlistView->resetStatus(index); Q_EMIT signalCurrentChanged(); } - - // show process table view context menu on specified positon void AccountsWidget::onRightButtonClicked(const QPoint &p) { QPoint point = mapToGlobal(p); + // QString name = m_userlistView->indexAt(p).data().toString(); + // //获取当前操作的用户对象 + // getUserToBeOperated(name); + // //判断是否为当前用户,当前用户展示断开连接, + // if (m_userToBeOperated->isCurrentUser()) { + // m_contextMenu->actions().at(0)->setVisible(false); + // m_contextMenu->actions().at(1)->setVisible(true); + // } else { + // if (m_currentUserType == User::UserType::Administrator) { + // m_contextMenu->actions().at(0)->setVisible(true); + // } -// QString name = m_userlistView->indexAt(p).data().toString(); -// //获取当前操作的用户对象 -// getUserToBeOperated(name); - -// //判断是否为当前用户,当前用户展示断开连接, -// if (m_userToBeOperated->isCurrentUser()) { -// m_contextMenu->actions().at(0)->setVisible(false); -// m_contextMenu->actions().at(1)->setVisible(true); -// } else { -// if (m_currentUserType == User::UserType::Administrator) { -// m_contextMenu->actions().at(0)->setVisible(true); -// } - -// m_contextMenu->actions().at(1)->setVisible(false); -// } + // m_contextMenu->actions().at(1)->setVisible(false); + // } m_contextMenu->popup(point); - - - - - - } void AccountsWidget::getUserToBeOperated(const QString &userName) { @@ -336,7 +309,6 @@ void AccountsWidget::onLogoutTriggered() } else { return; } - } void AccountsWidget::onEditAccountTriggered() diff --git a/deepin-system-monitor-main/gui/base/base_table_view.cpp b/deepin-system-monitor-main/gui/base/base_table_view.cpp index 373c3e00..071318ea 100644 --- a/deepin-system-monitor-main/gui/base/base_table_view.cpp +++ b/deepin-system-monitor-main/gui/base/base_table_view.cpp @@ -100,7 +100,7 @@ void BaseTableView::setModel(QAbstractItemModel *model) m_pressed = {}; }); // connect(model, &QAbstractItemModel::rowsRemoved, this, [ = ]() { -// qWarning()<<(model->rowCount()==0); +// qCWarning(app)<<(model->rowCount()==0); // }); } } diff --git a/deepin-system-monitor-main/gui/dialog/systemprotectionsetting.cpp b/deepin-system-monitor-main/gui/dialog/systemprotectionsetting.cpp index a9ff515e..a6d20bd1 100644 --- a/deepin-system-monitor-main/gui/dialog/systemprotectionsetting.cpp +++ b/deepin-system-monitor-main/gui/dialog/systemprotectionsetting.cpp @@ -5,7 +5,7 @@ #include "systemprotectionsetting.h" #include "helper.hpp" - +#include "ddlog.h" #include #include #include @@ -29,11 +29,11 @@ #include #ifndef AlarmStatusOptionName -#define AlarmStatusOptionName "setting.systemprotection.alarm_switch" -#define AlarmCpuUsageOptionName "setting.systemprotection.alarm_cpu_usage" -#define AlarmMemUsageOptionName "setting.systemprotection.alarm_memory_usage" -#define AlarmIntervalOptionName "setting.systemprotection.alarm_interval" -#define AlarmLastTimeOptionName "setting.systemprotection.alarm_last_time" +# define AlarmStatusOptionName "setting.systemprotection.alarm_switch" +# define AlarmCpuUsageOptionName "setting.systemprotection.alarm_cpu_usage" +# define AlarmMemUsageOptionName "setting.systemprotection.alarm_memory_usage" +# define AlarmIntervalOptionName "setting.systemprotection.alarm_interval" +# define AlarmLastTimeOptionName "setting.systemprotection.alarm_last_time" #endif // 与系统字体大小的偏移值,-1.5为小于系统字体大小1.5字号 @@ -43,7 +43,7 @@ int SystemProtectionSetting::m_lastValidMemoryValue = 0; int SystemProtectionSetting::m_lastValidInternalValue = 0; Q_GLOBAL_STATIC(SystemProtectionSetting, theInstance) - +using namespace DDLog; // 修改控件字体大小 bool changeWidgetFontSizeByDiffWithSystem(QWidget *widget, double diff) { @@ -81,12 +81,7 @@ bool changeWidgetFontSizeByDiffWithSystem(QWidget *widget, double diff) } SystemProtectionSetting::SystemProtectionSetting(QObject *parent) - : QObject(parent) - , mBackend(nullptr) - , mDsettings(nullptr) - , mDaemonInterface("org.deepin.SystemMonitorDaemon", - "/org/deepin/SystemMonitorDaemon", - "org.deepin.SystemMonitorDaemon") + : QObject(parent), mBackend(nullptr), mDsettings(nullptr), mDaemonInterface("org.deepin.SystemMonitorDaemon", "/org/deepin/SystemMonitorDaemon", "org.deepin.SystemMonitorDaemon") { mDaemonInterface.setParent(this); // json文件加载setting基本结构 @@ -135,8 +130,8 @@ QPair SystemProtectionSetting::createSettingLinkButtonHand // 获取初始值 option->setValue(option->defaultValue()); - option->connect(button, &DCommandLinkButton::clicked, option, [ = ]() { - qDebug() << __FUNCTION__ << __LINE__ << ",will jump to dde setting center notification page!"; + option->connect(button, &DCommandLinkButton::clicked, option, [=]() { + qCDebug(app) << __FUNCTION__ << __LINE__ << ",will jump to dde setting center notification page!"; SystemProtectionSetting::instance()->onMessgaeSetting(""); }); if (widget != nullptr) @@ -169,15 +164,15 @@ QPair SystemProtectionSetting::createProtectionSwitchHandl QPair optionWidget = DSettingsWidgetFactory::createStandardItem(QByteArray(), option, widget); // Item操作修改Setting值 - option->connect(button, &DSwitchButton::clicked, option, [ = ](bool checked) { - qDebug() << __FUNCTION__ << __LINE__ << ", new protection swich :" << checked; + option->connect(button, &DSwitchButton::clicked, option, [=](bool checked) { + qCDebug(app) << __FUNCTION__ << __LINE__ << ", new protection swich :" << checked; if (checked != option->value().toBool()) { option->setValue(checked); } }); // 用于恢复默认时,Item的数据更新 - button->connect(option, &DSettingsOption::valueChanged, button, [ = ]() { + button->connect(option, &DSettingsOption::valueChanged, button, [=]() { if (option->value().toBool() != button->isChecked()) { button->setChecked(option->value().toBool()); } @@ -202,7 +197,6 @@ void SystemProtectionSetting::setLastValidAlarm(DLineEdit *lineEdit, DTK_CORE_NA else if (option->key() == AlarmIntervalOptionName) lineEdit->setText(QString::number(m_lastValidInternalValue)); } - } void SystemProtectionSetting::lineEditChanged(bool focus, DLineEdit *edit, DSettingsOption *option, int maxValue, int minValue) @@ -231,7 +225,7 @@ void SystemProtectionSetting::lineEditChanged(bool focus, DLineEdit *edit, DSett option->setValue(m_lastValidInternalValue); } } -// SystemProtectionSetting::instance()->regularNumber(edit); + // SystemProtectionSetting::instance()->regularNumber(edit); } QPair SystemProtectionSetting::createAlarmUsgaeSettingHandle(QObject *obj) @@ -256,7 +250,7 @@ QPair SystemProtectionSetting::createAlarmUsgaeSettingHand edit->lineEdit()->setValidator(validator); // 规范输入的文字信息(数字) -// SystemProtectionSetting::instance()->regularNumber(edit); + // SystemProtectionSetting::instance()->regularNumber(edit); // 构建提示语 DLabel *label = new DLabel(widget); @@ -285,29 +279,29 @@ QPair SystemProtectionSetting::createAlarmUsgaeSettingHand m_lastValidMemoryValue = option->value().toInt(); // 修改Item同步修改Setting数据 - option->connect(edit, &DLineEdit::focusChanged, option, [ = ](bool onFocus) { + option->connect(edit, &DLineEdit::focusChanged, option, [=](bool onFocus) { lineEditChanged(onFocus, edit, option, 100, 30); }); - option->connect(edit, &DLineEdit::textChanged, option, [ = ]() { + option->connect(edit, &DLineEdit::textChanged, option, [=]() { QString text = edit->text(); int number = text.toInt(); edit->setText(QString::number(number)); }); - option->connect(edit, &DLineEdit::returnPressed, option, [ = ]() { + option->connect(edit, &DLineEdit::returnPressed, option, [=]() { lineEditChanged(false, edit, option, 100, 30); }); // 用于恢复默认时,Item的数据更新 - edit->connect(option, &DSettingsOption::valueChanged, edit, [ = ]() { + edit->connect(option, &DSettingsOption::valueChanged, edit, [=]() { if (option->value().toInt() != edit->text().toInt()) { edit->setText(option->value().toString()); // 恢复默认时,需要更新默认设置值 if (option->key() == AlarmCpuUsageOptionName) - m_lastValidCPUValue = option->value().toInt(); + m_lastValidCPUValue = option->value().toInt(); if (option->key() == AlarmMemUsageOptionName) - m_lastValidMemoryValue = option->value().toInt(); + m_lastValidMemoryValue = option->value().toInt(); } }); @@ -322,7 +316,7 @@ QPair SystemProtectionSetting::createAlarmUsgaeSettingHand // 初始控件的disable状态 widget->setDisabled(!swtich_value.toBool()); // 连接监控开关变化信号 - widget->connect(settingPtr, &DSettings::valueChanged, widget, [ = ](const QString & key, const QVariant & value) { + widget->connect(settingPtr, &DSettings::valueChanged, widget, [=](const QString &key, const QVariant &value) { if (key == AlarmStatusOptionName) { widget->setDisabled(!value.toBool()); } @@ -332,7 +326,7 @@ QPair SystemProtectionSetting::createAlarmUsgaeSettingHand // 初始控件的disable状态 leftWidget->setDisabled(!swtich_value.toBool()); // 连接监控开关变化信号 - leftWidget->connect(settingPtr, &DSettings::valueChanged, leftWidget, [ = ](const QString & key, const QVariant & value) { + leftWidget->connect(settingPtr, &DSettings::valueChanged, leftWidget, [=](const QString &key, const QVariant &value) { if (key == AlarmStatusOptionName) { leftWidget->setDisabled(!value.toBool()); } @@ -367,7 +361,7 @@ QPair SystemProtectionSetting::createAlarmIntervalSettingH edit->lineEdit()->setValidator(validator); // 规范输入的文字信息(数字) -// SystemProtectionSetting::instance()->regularNumber(edit); + // SystemProtectionSetting::instance()->regularNumber(edit); // 构建提示语 DLabel *label = new DLabel(widget); @@ -393,26 +387,26 @@ QPair SystemProtectionSetting::createAlarmIntervalSettingH // 获取初始值时同步更新静态变量 m_lastValidInternalValue = option->value().toInt(); // 修改Item同步修改Setting数据 - option->connect(edit, &DLineEdit::focusChanged, option, [ = ](bool onFocus) { + option->connect(edit, &DLineEdit::focusChanged, option, [=](bool onFocus) { lineEditChanged(onFocus, edit, option, 60, 5); }); - option->connect(edit, &DLineEdit::textChanged, option, [ = ]() { + option->connect(edit, &DLineEdit::textChanged, option, [=]() { QString text = edit->text(); int number = text.toInt(); edit->setText(QString::number(number)); }); - option->connect(edit, &DLineEdit::returnPressed, option, [ = ]() { + option->connect(edit, &DLineEdit::returnPressed, option, [=]() { lineEditChanged(false, edit, option, 60, 5); }); // 用于恢复默认时,Item的数据更新 - edit->connect(option, &DSettingsOption::valueChanged, edit, [ = ]() { + edit->connect(option, &DSettingsOption::valueChanged, edit, [=]() { if (option->value().toInt() != edit->text().toInt()) { edit->setText(option->value().toString()); if (option->key() == AlarmIntervalOptionName) - m_lastValidInternalValue = option->value().toInt(); + m_lastValidInternalValue = option->value().toInt(); } }); @@ -427,7 +421,7 @@ QPair SystemProtectionSetting::createAlarmIntervalSettingH // 初始控件的disable状态 widget->setDisabled(!swtich_value.toBool()); // 连接监控开关变化信号 - widget->connect(settingPtr, &DSettings::valueChanged, widget, [ = ](const QString & key, const QVariant & value) { + widget->connect(settingPtr, &DSettings::valueChanged, widget, [=](const QString &key, const QVariant &value) { if (key == AlarmStatusOptionName) { widget->setDisabled(!value.toBool()); } @@ -437,7 +431,7 @@ QPair SystemProtectionSetting::createAlarmIntervalSettingH // 初始控件的disable状态 leftWidget->setDisabled(!swtich_value.toBool()); // 连接监控开关变化信号 - leftWidget->connect(settingPtr, &DSettings::valueChanged, leftWidget, [ = ](const QString & key, const QVariant & value) { + leftWidget->connect(settingPtr, &DSettings::valueChanged, leftWidget, [=](const QString &key, const QVariant &value) { if (key == AlarmStatusOptionName) { leftWidget->setDisabled(!value.toBool()); } @@ -492,7 +486,7 @@ void SystemProtectionSetting::onMessgaeSetting(QVariant value) QDBusMessage replyMsg = QDBusConnection::sessionBus().call(showDDEControlCenterPage); if (replyMsg.type() == QDBusMessage::ErrorMessage) { - qWarning() << __FUNCTION__ << __LINE__ << ", dde control center dbus method call fail , error name :" + qCWarning(app) << __FUNCTION__ << __LINE__ << ", dde control center dbus method call fail , error name :" << replyMsg.errorName() << " , error msg :" << replyMsg.errorMessage(); } @@ -503,17 +497,16 @@ void SystemProtectionSetting::onMessgaeSetting(QVariant value) QDBusMessage showDDEControlCenter; if (!common::systemInfo().isOldVersion()) { showDDEControlCenter = QDBusMessage::createMethodCall(common::systemInfo().ControlCenterService, - common::systemInfo().ControlCenterPath, - common::systemInfo().ControlCenterInterface, - "ShowPage"); + common::systemInfo().ControlCenterPath, + common::systemInfo().ControlCenterInterface, + "ShowPage"); } else { showDDEControlCenter = QDBusMessage::createMethodCall("com.deepin.dde.ControlCenter", - "/com/deepin/dde/ControlCenter", - "com.deepin.dde.ControlCenter", - "ShowModule"); + "/com/deepin/dde/ControlCenter", + "com.deepin.dde.ControlCenter", + "ShowModule"); } - QList args; args << "notification"; showDDEControlCenter.setArguments(args); @@ -521,7 +514,7 @@ void SystemProtectionSetting::onMessgaeSetting(QVariant value) QDBusMessage replyMsg = QDBusConnection::sessionBus().call(showDDEControlCenter); if (replyMsg.type() == QDBusMessage::ErrorMessage) { - qWarning() << __FUNCTION__ << __LINE__ << ", dde control center dbus method call fail , error name :" + qCWarning(app) << __FUNCTION__ << __LINE__ << ", dde control center dbus method call fail , error name :" << replyMsg.errorName() << " , error msg :" << replyMsg.errorMessage(); } } @@ -529,7 +522,7 @@ void SystemProtectionSetting::onMessgaeSetting(QVariant value) void SystemProtectionSetting::onSettingItemChanged(const QString &key, const QVariant &value) { - qDebug() << __FUNCTION__ << __LINE__ << ", key:" << key << ", value:" << value; + qCDebug(app) << __FUNCTION__ << __LINE__ << ", key:" << key << ", value:" << value; // 使用QProcess执行dbus操作, 此操作是为了通知daemon进程,监测功能设置数据更改 // 在执行 DSettingsDialog "恢复默认"按钮操作时,QDBusInterFace QDBusConnection 等操作会发生调用错误 // 错误提示 org.freedesktop.DBus.Error.UnknownMethod @@ -542,30 +535,30 @@ void SystemProtectionSetting::onSettingItemChanged(const QString &key, const QVa // 拼接dbus调用命令字串 if (key == AlarmStatusOptionName) { - cmd.append("setSystemProtectionStatus "); // Method Name - cmd.append(value.toString()); // value + cmd.append("setSystemProtectionStatus "); // Method Name + cmd.append(value.toString()); // value needCall = true; } else if (key == AlarmCpuUsageOptionName) { - cmd.append("setAlarmUsageOfCpu "); // Method Name - cmd.append(value.toString()); // value + cmd.append("setAlarmUsageOfCpu "); // Method Name + cmd.append(value.toString()); // value needCall = true; } else if (key == AlarmMemUsageOptionName) { - cmd.append("setAlarmUsageOfMemory "); // Method Name - cmd.append(value.toString()); // value + cmd.append("setAlarmUsageOfMemory "); // Method Name + cmd.append(value.toString()); // value needCall = true; } else if (key == AlarmIntervalOptionName) { - cmd.append("setAlarmMsgInterval "); // Method Name - cmd.append(value.toString()); // value + cmd.append("setAlarmMsgInterval "); // Method Name + cmd.append(value.toString()); // value needCall = true; } else if (key == AlarmLastTimeOptionName) { - cmd.append("setAlarmLastTimeInterval "); // Mehthod Name + cmd.append("setAlarmLastTimeInterval "); // Mehthod Name cmd.append(value.toString()); needCall = true; } - if (needCall) { - qDebug() << __FUNCTION__ << __LINE__ << ",dbus cmd:" << cmd; - QTimer::singleShot(100, this, [ = ]() { QProcess::startDetached(cmd); }); + if (needCall) { + qCDebug(app) << __FUNCTION__ << __LINE__ << ",dbus cmd:" << cmd; + QTimer::singleShot(100, this, [=]() { QProcess::startDetached(cmd); }); } } @@ -577,7 +570,7 @@ DSettings *SystemProtectionSetting::getDSettingPointor() void SystemProtectionSetting::regularNumber(DLineEdit *lineEdit) { // 失去焦点时 - connect(lineEdit, &DLineEdit::focusChanged, SystemProtectionSetting::instance(), [ = ]() { + connect(lineEdit, &DLineEdit::focusChanged, SystemProtectionSetting::instance(), [=]() { if (lineEdit) { QString text = lineEdit->text(); int number = text.toInt(); @@ -586,7 +579,7 @@ void SystemProtectionSetting::regularNumber(DLineEdit *lineEdit) }); // 回车按下时 - connect(lineEdit, &DLineEdit::returnPressed, SystemProtectionSetting::instance(), [ = ]() { + connect(lineEdit, &DLineEdit::returnPressed, SystemProtectionSetting::instance(), [=]() { if (lineEdit) { QString text = lineEdit->text(); int number = text.toInt(); @@ -599,9 +592,9 @@ void SystemProtectionSetting::onUpdateNewBackend() { // 创建新的数据后端,应对可能的设置数据变化 QString strConfigPath = QString("%1/%2/%3/protection.conf") - .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) - .arg(qApp->organizationName()) - .arg(qApp->applicationName()); + .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) + .arg(qApp->organizationName()) + .arg(qApp->applicationName()); Dtk::Core::QSettingBackend *newBackend = new QSettingBackend(strConfigPath); // 为DSetting更新数据后端 diff --git a/deepin-system-monitor-main/gui/main_window.cpp b/deepin-system-monitor-main/gui/main_window.cpp index 3958bf7b..022f8d5e 100644 --- a/deepin-system-monitor-main/gui/main_window.cpp +++ b/deepin-system-monitor-main/gui/main_window.cpp @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "main_window.h" #include "user_page_widget.h" #include "application.h" @@ -20,7 +20,7 @@ #include #include #ifdef DTKCORE_CLASS_DConfigFile -#include +# include #endif #include #include @@ -30,6 +30,7 @@ using namespace core::process; using namespace common::init; +using namespace DDLog; const int WINDOW_MIN_HEIGHT = 760; const int WINDOW_MIN_WIDTH = 1080; @@ -37,8 +38,7 @@ const QString SERVICE_NAME = "com.deepin.SystemMonitorMain"; const QString SERVICE_PATH = "/com/deepin/SystemMonitorMain"; MainWindow::MainWindow(QWidget *parent) - : DMainWindow(parent) - , m_pDbusService(new DBusForSystemoMonitorPluginServce) + : DMainWindow(parent), m_pDbusService(new DBusForSystemoMonitorPluginServce) { m_settings = Settings::instance(); setMinimumSize(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGHT); @@ -46,9 +46,9 @@ MainWindow::MainWindow(QWidget *parent) connect(this, &MainWindow::loadingStatusChanged, this, &MainWindow::onLoadStatusChanged); #ifdef DTKCORE_CLASS_DConfigFile //需要查询是否支持特殊机型静音恢复,例如hw机型 - DConfig *dconfig = DConfig::create("org.deepin.system-monitor","org.deepin.system-monitor.main"); + DConfig *dconfig = DConfig::create("org.deepin.system-monitor", "org.deepin.system-monitor.main"); //需要判断Dconfig文件是否合法 - if(dconfig && dconfig->isValid() && dconfig->keyList().contains("specialComType")){ + if (dconfig && dconfig->isValid() && dconfig->keyList().contains("specialComType")) { specialComType = dconfig->value("specialComType").toInt(); } #endif @@ -71,10 +71,10 @@ void MainWindow::raiseWindow() void MainWindow::initDisplay() { - QJsonObject obj{ - {"tid", EventLogUtils::Start}, - {"version", QCoreApplication::applicationVersion()}, - {"mode", 1} + QJsonObject obj { + { "tid", EventLogUtils::Start }, + { "version", QCoreApplication::applicationVersion() }, + { "mode", 1 } }; EventLogUtils::get().writeLogs(obj); @@ -115,7 +115,7 @@ void MainWindow::initUI() // control + alt + k killAction->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_K)); // emit process kill requested signal if kill process menu item triggered - connect(killAction, &QAction::triggered, this, [ = ]() { Q_EMIT killProcessPerformed(); }); + connect(killAction, &QAction::triggered, this, [=]() { Q_EMIT killProcessPerformed(); }); // display mode menu item DMenu *modeMenu = new DMenu(DApplication::translate("Title.Bar.Context.Menu", "View"), menu); @@ -141,11 +141,11 @@ void MainWindow::initUI() } // emit display mode changed signal if ether expand or compact menu item triggered - connect(expandModeAction, &QAction::triggered, this, [ = ]() { + connect(expandModeAction, &QAction::triggered, this, [=]() { m_settings->setOption(kSettingKeyDisplayMode, kDisplayModeExpand); Q_EMIT displayModeChanged(kDisplayModeExpand); }); - connect(compactModeAction, &QAction::triggered, this, [ = ]() { + connect(compactModeAction, &QAction::triggered, this, [=]() { m_settings->setOption(kSettingKeyDisplayMode, kDisplayModeCompact); Q_EMIT displayModeChanged(kDisplayModeCompact); }); @@ -193,7 +193,7 @@ void MainWindow::initUI() // initialize connections void MainWindow::initConnections() { - connect(m_toolbar, &Toolbar::procTabButtonClicked, this, [ = ]() { + connect(m_toolbar, &Toolbar::procTabButtonClicked, this, [=]() { PERF_PRINT_BEGIN("POINT-05", QString("switch(%1->%2)").arg(DApplication::translate("Title.Bar.Switch", "Services")).arg(DApplication::translate("Title.Bar.Switch", "Processes"))); m_toolbar->clearSearchText(); m_pages->setCurrentWidget(m_procPage); @@ -203,7 +203,7 @@ void MainWindow::initConnections() PERF_PRINT_END("POINT-05"); }); - connect(m_toolbar, &Toolbar::serviceTabButtonClicked, this, [ = ]() { + connect(m_toolbar, &Toolbar::serviceTabButtonClicked, this, [=]() { PERF_PRINT_BEGIN("POINT-05", QString("switch(%1->%2)").arg(DApplication::translate("Title.Bar.Switch", "Processes")).arg(DApplication::translate("Title.Bar.Switch", "Services"))); m_toolbar->clearSearchText(); m_pages->setCurrentWidget(m_svcPage); @@ -212,7 +212,7 @@ void MainWindow::initConnections() m_tbShadow->show(); PERF_PRINT_END("POINT-05"); }); - connect(m_toolbar, &Toolbar::accountProcTabButtonClicked, this, [ = ]() { + connect(m_toolbar, &Toolbar::accountProcTabButtonClicked, this, [=]() { PERF_PRINT_BEGIN("POINT-05", QString("switch(%1->%2)").arg(DApplication::translate("Title.Bar.Switch", "Users")).arg(DApplication::translate("Title.Bar.Switch", "Services"))); m_toolbar->clearSearchText(); m_pages->setCurrentWidget(m_accountProcPage); @@ -221,7 +221,7 @@ void MainWindow::initConnections() m_tbShadow->show(); PERF_PRINT_END("POINT-05"); }); - connect(gApp, &Application::backgroundTaskStateChanged, this, [ = ](Application::TaskState state) { + connect(gApp, &Application::backgroundTaskStateChanged, this, [=](Application::TaskState state) { if (state == Application::kTaskStarted) { // save last focused widget inside main window m_focusedWidget = gApp->mainWindow()->focusWidget(); @@ -242,7 +242,7 @@ void MainWindow::initConnections() if (QDBusConnection::sessionBus().isConnected()) { if (QDBusConnection::sessionBus().registerService(SERVICE_NAME)) { if (!QDBusConnection::sessionBus().registerObject(SERVICE_PATH, m_pDbusService, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) { - qInfo() << "dbus init failed"; + qCInfo(app) << "dbus init failed"; } } } @@ -335,11 +335,10 @@ void MainWindow::onDetailInfoByDbus(QString msgCode) m_toolbar->clearSearchText(); m_toolbar->setProcessButtonChecked(true); m_pages->setCurrentWidget(m_procPage); -// m_procPage->switchProcessPage(); + // m_procPage->switchProcessPage(); m_tbShadow->raise(); m_tbShadow->show(); } - } void MainWindow::popupSettingsDialog() diff --git a/deepin-system-monitor-main/gui/process_page_widget.cpp b/deepin-system-monitor-main/gui/process_page_widget.cpp index 20d382ca..2772156c 100644 --- a/deepin-system-monitor-main/gui/process_page_widget.cpp +++ b/deepin-system-monitor-main/gui/process_page_widget.cpp @@ -43,13 +43,12 @@ #define NORMAL_PERFORMANCE_CPU_LOADING_TIME 100 #define CPU_FREQUENCY_STANDARD "2.30GHz" - DWIDGET_USE_NAMESPACE using namespace core::process; using namespace common::init; // process context summary text static const char *kProcSummaryTemplateText = - QT_TRANSLATE_NOOP("Process.Summary", "(%1 applications and %2 processes are running)"); + QT_TRANSLATE_NOOP("Process.Summary", "(%1 applications and %2 processes are running)"); // application context text static const char *appText = QT_TRANSLATE_NOOP("Process.Show.Mode", "Applications"); @@ -111,7 +110,7 @@ void ProcessPageWidget::initUI() // process context instance m_procViewMode = new DLabel(tw); - m_procViewMode->setText(DApplication::translate("Process.Show.Mode", appText)); // default text + m_procViewMode->setText(DApplication::translate("Process.Show.Mode", appText)); // default text DFontSizeManager::instance()->bind(m_procViewMode, DFontSizeManager::T7, QFont::Medium); // text aligment m_procViewMode->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); @@ -194,7 +193,7 @@ void ProcessPageWidget::initUI() QHBoxLayout *loadingLayout = new QHBoxLayout(this); loadingLayout->addStretch(); loadingLayout->addWidget(m_spinner, Qt::AlignCenter); - loadingLayout->addWidget(m_loadingLabel, Qt::AlignCenter); + loadingLayout->addWidget(m_loadingLabel, Qt::AlignCenter); loadingLayout->addStretch(); m_spinnerWidget->setLayout(loadingLayout); //loading 和 进程列表 @@ -227,44 +226,44 @@ void ProcessPageWidget::initUI() int index = vindex.toInt(); switch (index) { case kFilterCurrentUser: { -// //打开时也显示loading -// m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); + // //打开时也显示loading + // m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); // show my process view m_myProcButton->setChecked(true); m_procTable->switchDisplayMode(kFilterCurrentUser); m_procViewMode->setText( - DApplication::translate("Process.Show.Mode", myProcText)); // default text + DApplication::translate("Process.Show.Mode", myProcText)); // default text //记录当前选中按钮 m_procBtnCheckedType = USER_PROCESS; } break; case kNoFilter: { -// //打开时也显示loading -// m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); + // //打开时也显示loading + // m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); // show all process view m_allProcButton->setChecked(true); m_procTable->switchDisplayMode(kNoFilter); m_procViewMode->setText( - DApplication::translate("Process.Show.Mode", allProcText)); // default text + DApplication::translate("Process.Show.Mode", allProcText)); // default text //记录当前选中按钮 m_procBtnCheckedType = ALL_PROCESSS; } break; default: { -// //打开时也显示loading -// m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); + // //打开时也显示loading + // m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); // show my application view by default m_appButton->setChecked(true); m_procTable->switchDisplayMode(kFilterApps); m_procViewMode->setText( - DApplication::translate("Process.Show.Mode", appText)); // default text + DApplication::translate("Process.Show.Mode", appText)); // default text //记录当前选中按钮 m_procBtnCheckedType = MY_APPS; } - } // ::switch(index) + } // ::switch(index) connect(m_rightStackView, &DetailViewStackedWidget::currentChanged, this, &ProcessPageWidget::onDetailWidgetChanged); QTimer::singleShot(5, this, SLOT(onLoadLeftDataWidgetDelay())); // this->layout()->setSizeConstraint(QLayout::SetMinAndMaxSize); -// m_loadingAndProcessTB->setCurrentWidget(m_procTable); + // m_loadingAndProcessTB->setCurrentWidget(m_procTable); } void ProcessPageWidget::initConnections() @@ -293,7 +292,7 @@ void ProcessPageWidget::initConnections() auto *dAppHelper = DApplicationHelper::instance(); // change text color dynamically on theme type change, if not do this way, text color wont synchronize with theme type - connect(dAppHelper, &DApplicationHelper::themeTypeChanged, this, [ = ]() { + connect(dAppHelper, &DApplicationHelper::themeTypeChanged, this, [=]() { if (m_procViewMode) { auto palette = DApplicationHelper::instance()->applicationPalette(); palette.setColor(DPalette::Text, palette.color(DPalette::TextTitle)); @@ -391,10 +390,8 @@ void ProcessPageWidget::paintEvent(QPaintEvent *) DPalette palette = dAppHelper->applicationPalette(); QColor bgColor = palette.color(DPalette::Background); -// // 显示0.1s -// QTimer::singleShot(NORMAL_PERFORMANCE_CPU_LOADING_TIME, this, [ = ]() {m_loadingAndProcessTB->setCurrentWidget(m_procTable);}); - - + // // 显示0.1s + // QTimer::singleShot(NORMAL_PERFORMANCE_CPU_LOADING_TIME, this, [ = ]() {m_loadingAndProcessTB->setCurrentWidget(m_procTable);}); } // create application kill preview widget @@ -472,10 +469,10 @@ void ProcessPageWidget::popupKillConfirmDialog(pid_t pid) dialog.exec(); if (dialog.result() == QMessageBox::Ok) { QString name = m_procTable->getProcessName(pid); - QJsonObject obj{ - {"tid", EventLogUtils::ProcessKilled}, - {"version", QCoreApplication::applicationVersion()}, - {"process_name", name} + QJsonObject obj { + { "tid", EventLogUtils::ProcessKilled }, + { "version", QCoreApplication::applicationVersion() }, + { "process_name", name } }; EventLogUtils::get().writeLogs(obj); @@ -500,7 +497,7 @@ void ProcessPageWidget::onAllProcButtonClicked() //若已选中,再次点击不会加载数据 if (m_procBtnCheckedType != ALL_PROCESSS) { PERF_PRINT_BEGIN("POINT-04", QString("switch(%1->%2)").arg(m_procViewMode->text()).arg(DApplication::translate("Process.Show.Mode", allProcText))); -// m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); + // m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); m_procViewMode->setText(DApplication::translate("Process.Show.Mode", allProcText)); m_procViewMode->adjustSize(); m_procTable->switchDisplayMode(kNoFilter); @@ -517,11 +514,11 @@ void ProcessPageWidget::onAllProcButtonClicked() void ProcessPageWidget::onUserProcButtonClicked() { -// qInfo() << CPUPerformance << "CPUPerformance"; + // qCInfo(app) << CPUPerformance << "CPUPerformance"; //若已选中,再次点击不会加载数据 if (m_procBtnCheckedType != USER_PROCESS) { PERF_PRINT_BEGIN("POINT-04", QString("switch(%1->%2)").arg(m_procViewMode->text()).arg(DApplication::translate("Process.Show.Mode", myProcText))); -// m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); + // m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); m_procViewMode->setText(DApplication::translate("Process.Show.Mode", myProcText)); m_procViewMode->adjustSize(); m_procTable->switchDisplayMode(kFilterCurrentUser); @@ -541,7 +538,7 @@ void ProcessPageWidget::onAppButtonClicked() //若已选中,再次点击不会加载数据 if (m_procBtnCheckedType != MY_APPS) { PERF_PRINT_BEGIN("POINT-04", QString("switch(%1->%2)").arg(m_procViewMode->text()).arg(DApplication::translate("Process.Show.Mode", appText))); -// m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); + // m_loadingAndProcessTB->setCurrentWidget(m_spinnerWidget); m_procViewMode->setText(DApplication::translate("Process.Show.Mode", appText)); m_procViewMode->adjustSize(); m_procTable->switchDisplayMode(kFilterApps); diff --git a/deepin-system-monitor-main/gui/process_table_view.cpp b/deepin-system-monitor-main/gui/process_table_view.cpp index 581a9bf2..2806f9c6 100644 --- a/deepin-system-monitor-main/gui/process_table_view.cpp +++ b/deepin-system-monitor-main/gui/process_table_view.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "process_table_view.h" #include "application.h" @@ -47,7 +47,7 @@ #include #include - +using namespace DDLog; using namespace common::init; // process table view backup setting key @@ -59,8 +59,7 @@ static const char *kSettingsOption_ProcessTableHeaderStateOfUserMode = "process_ */ static QMetaObject::Connection m_pControlConnection = QMetaObject::Connection(); ProcessTableView::ProcessTableView(DWidget *parent, QString userName) - : BaseTableView(parent) - , m_useModeName(userName) + : BaseTableView(parent), m_useModeName(userName) { // install event filter for table view to handle key events installEventFilter(this); @@ -72,8 +71,7 @@ ProcessTableView::ProcessTableView(DWidget *parent, QString userName) // setModel must be called before calling loadSettings(); setModel(m_proxyModel); // load process table view backup settings - bool settingsLoaded = userName.isNull() ? loadSettings(kSettingsOption_ProcessTableHeaderState) : - loadSettings(kSettingsOption_ProcessTableHeaderStateOfUserMode); + bool settingsLoaded = userName.isNull() ? loadSettings(kSettingsOption_ProcessTableHeaderState) : loadSettings(kSettingsOption_ProcessTableHeaderStateOfUserMode); // initialize ui components & connections initUI(settingsLoaded); initConnections(settingsLoaded); @@ -90,7 +88,6 @@ ProcessTableView::ProcessTableView(DWidget *parent, QString userName) m_diskread = m_model->getTotalDiskRead(); m_diskwrite = m_model->getTotalDiskWrite(); } - } // destructor @@ -126,12 +123,12 @@ bool ProcessTableView::eventFilter(QObject *obj, QEvent *event) if (selectedIndexes().size() > 0) { auto index = selectedIndexes()[0]; auto rect = visualRect(index); - displayProcessTableContextMenu({rect.x() + rect.width() / 2, rect.y() + rect.height() / 2}); + displayProcessTableContextMenu({ rect.x() + rect.width() / 2, rect.y() + rect.height() / 2 }); return true; } } else if (header()->hasFocus()) { // if header view has focus, then show context menu for header view - displayProcessTableHeaderContextMenu({header()->sectionSize(header()->logicalIndexAt(0)) / 2, header()->height() / 2}); + displayProcessTableHeaderContextMenu({ header()->sectionSize(header()->logicalIndexAt(0)) / 2, header()->height() / 2 }); return true; } } @@ -155,7 +152,7 @@ void ProcessTableView::endProcess() "loss.\nAre you sure you want to continue?"); KillProcessConfirmDialog dialog(this); -// dialog.setTitle(title); + // dialog.setTitle(title); dialog.setMessage(description); dialog.addButton(DApplication::translate("Kill.Process.Dialog", "Cancel", "button"), false); dialog.addButton(DApplication::translate("Kill.Process.Dialog", "End", "button"), true, @@ -163,10 +160,10 @@ void ProcessTableView::endProcess() dialog.exec(); if (dialog.result() == QMessageBox::Ok) { Process proc = m_model->getProcess(qvariant_cast(m_selectedPID)); - QJsonObject obj{ - {"tid", EventLogUtils::ProcessKilled}, - {"version", QCoreApplication::applicationVersion()}, - {"process_name", proc.name()} + QJsonObject obj { + { "tid", EventLogUtils::ProcessKilled }, + { "version", QCoreApplication::applicationVersion() }, + { "process_name", proc.name() } }; EventLogUtils::get().writeLogs(obj); @@ -206,12 +203,12 @@ void ProcessTableView::openExecDirWithFM() if (m_selectedPID.isValid()) { pid_t pid = qvariant_cast(m_selectedPID); const Process &proc = ProcessDB::instance()->processSet()->getProcessById(pid); - QString cmdline = proc.cmdlineString(); + QString cmdline = proc.cmdlineString(); if (cmdline.size() > 0) { // Found wine program location if cmdline starts with c://. if (cmdline.startsWith("c:")) { - QString winePrefix = proc.environ().value("WINEPREFIX"); + QString winePrefix = proc.environ().value("WINEPREFIX"); cmdline = cmdline.replace("\\", "/").replace("c:/", "/drive_c/"); const QString &path = QString(winePrefix + cmdline).trimmed(); @@ -230,50 +227,50 @@ void ProcessTableView::openExecDirWithFM() QString path; if (!common::systemInfo().isOldVersion()) { - path = QString(output.split("\n")[0]).trimmed(); - // 读取persistent目录 - if (path.isEmpty()) { - char nsPath[PATH_MAX] = {0}, nsSelfPath[PATH_MAX] = {0}; - auto nsSize = readlink(QString("/proc/%1/ns/pid").arg(pid).toStdString().c_str(), nsPath, PATH_MAX); - auto nsSelfSize = readlink(QString("/proc/self/ns/pid").toStdString().c_str(), nsSelfPath, PATH_MAX); - if (nsSize > 0 && nsSelfSize > 0) { - QString nsPathStr(nsPath), nsSelfPathStr(nsSelfPath); - if (nsPathStr != nsSelfPathStr) { - Process preProc = proc, curProc = proc; - int count = 0; - // 100次循环 - while (curProc.name() != "ll-box" && curProc.pid() != 0 && count != 100) { - preProc = curProc; - curProc = ProcessDB::instance()->processSet()->getProcessById(preProc.ppid()); - count++; - } - if (curProc.pid() != 0 || count != 100) { - pid = preProc.pid(); - } - char exePath[PATH_MAX] = {0}; - auto exeSize = readlink(QString("/proc/%1/exe").arg(pid).toStdString().c_str(), exePath, PATH_MAX); - if (exeSize > 0) { - QString exeStr(exePath); - QFile file(QString("/proc/%1/mountinfo").arg(pid)); - if (file.open(QIODevice::ReadOnly)) { - QString devStr; - do { - QString line = file.readLine(); - auto works = line.split(" ", QString::SkipEmptyParts); - if (works.size() > 9 && exeStr.startsWith(works[4]) && works[9].startsWith("/dev")) { - devStr = works[9]; - if (!devStr.isEmpty()) { - path = "/persistent" + works[3] + exeStr.right(exeStr.size() - works[4].size()); + path = QString(output.split("\n")[0]).trimmed(); + // 读取persistent目录 + if (path.isEmpty()) { + char nsPath[PATH_MAX] = { 0 }, nsSelfPath[PATH_MAX] = { 0 }; + auto nsSize = readlink(QString("/proc/%1/ns/pid").arg(pid).toStdString().c_str(), nsPath, PATH_MAX); + auto nsSelfSize = readlink(QString("/proc/self/ns/pid").toStdString().c_str(), nsSelfPath, PATH_MAX); + if (nsSize > 0 && nsSelfSize > 0) { + QString nsPathStr(nsPath), nsSelfPathStr(nsSelfPath); + if (nsPathStr != nsSelfPathStr) { + Process preProc = proc, curProc = proc; + int count = 0; + // 100次循环 + while (curProc.name() != "ll-box" && curProc.pid() != 0 && count != 100) { + preProc = curProc; + curProc = ProcessDB::instance()->processSet()->getProcessById(preProc.ppid()); + count++; + } + if (curProc.pid() != 0 || count != 100) { + pid = preProc.pid(); + } + char exePath[PATH_MAX] = { 0 }; + auto exeSize = readlink(QString("/proc/%1/exe").arg(pid).toStdString().c_str(), exePath, PATH_MAX); + if (exeSize > 0) { + QString exeStr(exePath); + QFile file(QString("/proc/%1/mountinfo").arg(pid)); + if (file.open(QIODevice::ReadOnly)) { + QString devStr; + do { + QString line = file.readLine(); + auto works = line.split(" ", QString::SkipEmptyParts); + if (works.size() > 9 && exeStr.startsWith(works[4]) && works[9].startsWith("/dev")) { + devStr = works[9]; + if (!devStr.isEmpty()) { + path = "/persistent" + works[3] + exeStr.right(exeStr.size() - works[4].size()); + } + break; } - break; - } - } while (!file.atEnd()); - file.close(); + } while (!file.atEnd()); + file.close(); + } } } } } - } } else { path = QString(output.split("\n")[0]).trimmed(); } @@ -298,8 +295,8 @@ void ProcessTableView::openExecDirWithFM() } } } - } // ::if(cmdline) - } // ::if(selectedPID) + } // ::if(cmdline) + } // ::if(selectedPID) } // show process attribute dialog @@ -344,10 +341,10 @@ void ProcessTableView::killProcess() dialog.exec(); if (dialog.result() == QMessageBox::Ok) { Process proc = m_model->getProcess(qvariant_cast(m_selectedPID)); - QJsonObject obj{ - {"tid", EventLogUtils::ProcessKilled}, - {"version", QCoreApplication::applicationVersion()}, - {"process_name", proc.name()} + QJsonObject obj { + { "tid", EventLogUtils::ProcessKilled }, + { "version", QCoreApplication::applicationVersion() }, + { "process_name", proc.name() } }; EventLogUtils::get().writeLogs(obj); ProcessDB::instance()->killProcess(qvariant_cast(m_selectedPID)); @@ -370,7 +367,6 @@ void ProcessTableView::switchDisplayMode(FilterType type) { m_proxyModel->setFilterType(type); - } // change process priority @@ -543,96 +539,96 @@ void ProcessTableView::initConnections(bool settingsLoaded) &ProcessTableView::displayProcessTableContextMenu); // end process auto *endProcAction = m_contextMenu->addAction( - DApplication::translate("Process.Table.Context.Menu", "End process")); + DApplication::translate("Process.Table.Context.Menu", "End process")); // ALT + E endProcAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_E)); connect(endProcAction, &QAction::triggered, this, &ProcessTableView::endProcess); // pause process auto *pauseProcAction = m_contextMenu->addAction( - DApplication::translate("Process.Table.Context.Menu", "Suspend process")); + DApplication::translate("Process.Table.Context.Menu", "Suspend process")); // ALT + P pauseProcAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_P)); connect(pauseProcAction, &QAction::triggered, this, &ProcessTableView::pauseProcess); // resume process auto *resumeProcAction = m_contextMenu->addAction( - DApplication::translate("Process.Table.Context.Menu", "Resume process")); + DApplication::translate("Process.Table.Context.Menu", "Resume process")); // ALT + C resumeProcAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_C)); connect(resumeProcAction, &QAction::triggered, this, &ProcessTableView::resumeProcess); // change priority dialog auto *chgProcPrioMenu = m_contextMenu->addMenu( - DApplication::translate("Process.Table.Context.Menu", "Change priority")); + DApplication::translate("Process.Table.Context.Menu", "Change priority")); QActionGroup *prioGroup = new QActionGroup(chgProcPrioMenu); prioGroup->setExclusive(true); // very high priority action auto *setVeryHighPrioAction = - chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Very high")); + chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Very high")); setVeryHighPrioAction->setCheckable(true); setVeryHighPrioAction->setActionGroup(prioGroup); connect(setVeryHighPrioAction, &QAction::triggered, - [ = ]() { changeProcessPriority(kVeryHighPriority); }); + [=]() { changeProcessPriority(kVeryHighPriority); }); // high priority action auto *setHighPrioAction = - chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "High")); + chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "High")); setHighPrioAction->setCheckable(true); setHighPrioAction->setActionGroup(prioGroup); connect(setHighPrioAction, &QAction::triggered, - [ = ]() { changeProcessPriority(kHighPriority); }); + [=]() { changeProcessPriority(kHighPriority); }); // normal priority action auto *setNormalPrioAction = - chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Normal")); + chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Normal")); setNormalPrioAction->setCheckable(true); setNormalPrioAction->setActionGroup(prioGroup); connect(setNormalPrioAction, &QAction::triggered, - [ = ]() { changeProcessPriority(kNormalPriority); }); + [=]() { changeProcessPriority(kNormalPriority); }); // low priority action auto *setLowPrioAction = - chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Low")); + chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Low")); setLowPrioAction->setCheckable(true); setLowPrioAction->setActionGroup(prioGroup); connect(setLowPrioAction, &QAction::triggered, - [ = ]() { changeProcessPriority(kLowPriority); }); + [=]() { changeProcessPriority(kLowPriority); }); // very low priority action auto *setVeryLowPrioAction = - chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Very low")); + chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Very low")); setVeryLowPrioAction->setCheckable(true); setVeryLowPrioAction->setActionGroup(prioGroup); connect(setVeryLowPrioAction, &QAction::triggered, - [ = ]() { changeProcessPriority(kVeryLowPriority); }); + [=]() { changeProcessPriority(kVeryLowPriority); }); // custom priority action auto *setCustomPrioAction = - chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Custom")); + chgProcPrioMenu->addAction(DApplication::translate("Process.Priority", "Custom")); setCustomPrioAction->setCheckable(true); setCustomPrioAction->setActionGroup(prioGroup); - connect(setCustomPrioAction, &QAction::triggered, [ = ]() { customizeProcessPriority(); }); + connect(setCustomPrioAction, &QAction::triggered, [=]() { customizeProcessPriority(); }); // show exec location action auto *openExecDirAction = m_contextMenu->addAction( - DApplication::translate("Process.Table.Context.Menu", "View command location")); + DApplication::translate("Process.Table.Context.Menu", "View command location")); connect(openExecDirAction, &QAction::triggered, this, &ProcessTableView::openExecDirWithFM); // show property action auto *showAttrAction = m_contextMenu->addAction( - DApplication::translate("Process.Table.Context.Menu", "Properties")); + DApplication::translate("Process.Table.Context.Menu", "Properties")); // ALt + ENTER showAttrAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Enter)); connect(showAttrAction, &QAction::triggered, this, &ProcessTableView::showProperties); m_contextMenu->addSeparator(); // kill process auto *killProcAction = m_contextMenu->addAction( - DApplication::translate("Process.Table.Context.Menu", "Kill process")); + DApplication::translate("Process.Table.Context.Menu", "Kill process")); // ALT + K killProcAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_K)); connect(killProcAction, &QAction::triggered, this, &ProcessTableView::killProcess); // change menu item checkable state before context menu popup - connect(m_contextMenu, &DMenu::aboutToShow, this, [ = ]() { + connect(m_contextMenu, &DMenu::aboutToShow, this, [=]() { // process running or not flag if (m_selectedPID.isValid()) { @@ -681,16 +677,16 @@ void ProcessTableView::initConnections(bool settingsLoaded) // backup table view settings if any of the header view state changes auto *h = header(); - connect(h, &QHeaderView::sectionResized, this, [ = ]() { saveSettings(); }); - connect(h, &QHeaderView::sectionMoved, this, [ = ]() { saveSettings(); }); - connect(h, &QHeaderView::sortIndicatorChanged, this, [ = ]() { saveSettings(); }); + connect(h, &QHeaderView::sectionResized, this, [=]() { saveSettings(); }); + connect(h, &QHeaderView::sectionMoved, this, [=]() { saveSettings(); }); + connect(h, &QHeaderView::sortIndicatorChanged, this, [=]() { saveSettings(); }); connect(h, &QHeaderView::customContextMenuRequested, this, &ProcessTableView::displayProcessTableHeaderContextMenu); // header context menu // cpu action auto *cpuHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessCPU)); + DApplication::translate("Process.Table.Header", kProcessCPU)); cpuHeaderAction->setCheckable(true); connect(cpuHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessCPUColumn, !b); @@ -699,7 +695,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // process user action auto *userHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessUser)); + DApplication::translate("Process.Table.Header", kProcessUser)); userHeaderAction->setCheckable(true); connect(userHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessUserColumn, !b); @@ -707,7 +703,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // memory action auto *memHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessMemory)); + DApplication::translate("Process.Table.Header", kProcessMemory)); memHeaderAction->setCheckable(true); connect(memHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessMemoryColumn, !b); @@ -716,7 +712,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // share memory action auto *sharememHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessShareMemory)); + DApplication::translate("Process.Table.Header", kProcessShareMemory)); sharememHeaderAction->setCheckable(true); connect(sharememHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessShareMemoryColumn, !b); @@ -725,7 +721,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); //vtr memory action auto *vtrmemHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessVtrMemory)); + DApplication::translate("Process.Table.Header", kProcessVtrMemory)); vtrmemHeaderAction->setCheckable(true); connect(vtrmemHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessVTRMemoryColumn, !b); @@ -734,7 +730,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // upload rate action auto *uploadHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessUpload)); + DApplication::translate("Process.Table.Header", kProcessUpload)); uploadHeaderAction->setCheckable(true); connect(uploadHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessUploadColumn, !b); @@ -743,7 +739,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // download rate action auto *downloadHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessDownload)); + DApplication::translate("Process.Table.Header", kProcessDownload)); downloadHeaderAction->setCheckable(true); connect(downloadHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessDownloadColumn, !b); @@ -752,7 +748,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // disk read rate action auto *dreadHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessDiskRead)); + DApplication::translate("Process.Table.Header", kProcessDiskRead)); dreadHeaderAction->setCheckable(true); connect(dreadHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessDiskReadColumn, !b); @@ -761,7 +757,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // disk write rate action auto *dwriteHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessDiskWrite)); + DApplication::translate("Process.Table.Header", kProcessDiskWrite)); dwriteHeaderAction->setCheckable(true); connect(dwriteHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessDiskWriteColumn, !b); @@ -770,7 +766,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // pid action auto *pidHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessPID)); + DApplication::translate("Process.Table.Header", kProcessPID)); pidHeaderAction->setCheckable(true); connect(pidHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessPIDColumn, !b); @@ -778,7 +774,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // nice value action auto *niceHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessNice)); + DApplication::translate("Process.Table.Header", kProcessNice)); niceHeaderAction->setCheckable(true); connect(niceHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessNiceColumn, !b); @@ -786,7 +782,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) }); // priority value action auto *priorityHeaderAction = m_headerContextMenu->addAction( - DApplication::translate("Process.Table.Header", kProcessPriority)); + DApplication::translate("Process.Table.Header", kProcessPriority)); priorityHeaderAction->setCheckable(true); connect(priorityHeaderAction, &QAction::triggered, this, [this](bool b) { header()->setSectionHidden(ProcessTableModel::kProcessPriorityColumn, !b); @@ -808,7 +804,7 @@ void ProcessTableView::initConnections(bool settingsLoaded) priorityHeaderAction->setChecked(true); } // set header context menu checkable state based on current header section's visible state before popup - connect(m_headerContextMenu, &QMenu::aboutToShow, this, [ = ]() { + connect(m_headerContextMenu, &QMenu::aboutToShow, this, [=]() { bool b; b = header()->isSectionHidden(ProcessTableModel::kProcessCPUColumn); cpuHeaderAction->setChecked(!b); @@ -842,7 +838,8 @@ void ProcessTableView::initConnections(bool settingsLoaded) if (m_selectedPID.isValid()) { for (int i = 0; i < m_proxyModel->rowCount(); i++) { if (m_proxyModel->data(m_proxyModel->index(i, ProcessTableModel::kProcessPIDColumn), - Qt::UserRole) == m_selectedPID) + Qt::UserRole) + == m_selectedPID) this->setCurrentIndex(m_proxyModel->index(i, 0)); } } @@ -877,22 +874,22 @@ void ProcessTableView::initConnections(bool settingsLoaded) //show error dialog if change priority failed connect(ProcessDB::instance(), &ProcessDB::priorityPromoteResultReady, this, - [ = ](const ErrorContext & ec) { - if (ec) { - ErrorDialog::show(this, ec.getErrorName(), ec.getErrorMessage()); - } - }); - qInfo() << "'processControlResultReady' signal is connect?" << m_pControlConnection; + [=](const ErrorContext &ec) { + if (ec) { + ErrorDialog::show(this, ec.getErrorName(), ec.getErrorMessage()); + } + }); + qCInfo(app) << "'processControlResultReady' signal is connect?" << m_pControlConnection; //The singleton object only needs to connect to the signal slot once. //show error dialog if sending signals to process failed - if(!m_pControlConnection) - m_pControlConnection = connect(ProcessDB::instance(), &ProcessDB::processControlResultReady, this, - [ = ](const ErrorContext & ec) { - if (ec) { - ErrorDialog::show(this, ec.getErrorName(), ec.getErrorMessage()); - qWarning() << "ErrorName: " << ec.getErrorName() << ",ErrorMessage: " << ec.getErrorMessage(); - } - }); + if (!m_pControlConnection) + m_pControlConnection = connect(ProcessDB::instance(), &ProcessDB::processControlResultReady, this, + [=](const ErrorContext &ec) { + if (ec) { + ErrorDialog::show(this, ec.getErrorName(), ec.getErrorMessage()); + qCWarning(app) << "ErrorName: " << ec.getErrorName() << ",ErrorMessage: " << ec.getErrorMessage(); + } + }); } // show process table view context menu on specified positon @@ -973,7 +970,7 @@ void ProcessTableView::customizeProcessPriority() prioDialog->setIcon(QIcon::fromTheme("dialog-warning")); prioDialog->setAttribute(Qt::WA_DeleteOnClose); prioDialog->setTitle( - DApplication::translate("Process.Table.Custom.Priority.Dialog", "Custom Priority")); + DApplication::translate("Process.Table.Custom.Priority.Dialog", "Custom Priority")); prioDialog->addSpacing(20); PrioritySlider *slider = new PrioritySlider(Qt::Horizontal, prioDialog); slider->slider()->setInvertedAppearance(true); @@ -983,13 +980,13 @@ void ProcessTableView::customizeProcessPriority() slider->setPageStep(1); slider->slider()->setTracking(true); slider->setMouseWheelEnabled(true); - slider->setBelowTicks({QString("%1").arg(kVeryLowPriorityMin), - QString("%1").arg(kVeryHighPriorityMax)}); + slider->setBelowTicks({ QString("%1").arg(kVeryLowPriorityMin), + QString("%1").arg(kVeryHighPriorityMax) }); // change tip value dynamically when slider value changed connect(slider, &DSlider::valueChanged, - [ = ](int value) { slider->setTipValue(QString("%1").arg(value)); }); + [=](int value) { slider->setTipValue(QString("%1").arg(value)); }); // set initial slider & tip value based on current process priority - QString prio {"0"}; + QString prio { "0" }; if (m_selectedPID.isValid()) { pid_t pid = qvariant_cast(m_selectedPID); slider->setValue(m_model->getProcessPriorityValue(pid)); @@ -1010,7 +1007,7 @@ void ProcessTableView::customizeProcessPriority() true, DDialog::ButtonRecommend); // clear focus first, otherwise we wont get the tab order we want prioDialog->clearFocus(); - connect(prioDialog, &DDialog::buttonClicked, this, [ = ](int index, QString text) { + connect(prioDialog, &DDialog::buttonClicked, this, [=](int index, QString text) { Q_UNUSED(text); if (index == 1) { changeProcessPriority(slider->value()); @@ -1028,5 +1025,4 @@ void ProcessTableView::setUserModeName(const QString &userName) m_useModeName = userName; m_model->setUserModeName(m_useModeName); } - } diff --git a/deepin-system-monitor-main/gui/user_page_widget.cpp b/deepin-system-monitor-main/gui/user_page_widget.cpp index e80477a0..1de8a60d 100644 --- a/deepin-system-monitor-main/gui/user_page_widget.cpp +++ b/deepin-system-monitor-main/gui/user_page_widget.cpp @@ -17,7 +17,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - +#include "ddlog.h" #include "user_page_widget.h" #include "process_table_view.h" #include "model/process_table_model.h" @@ -28,17 +28,17 @@ DWIDGET_USE_NAMESPACE using namespace common::format; - +using namespace DDLog; UserPageWidget::UserPageWidget(DWidget *parent) : DFrame(parent) { struct passwd *pws; pws = getpwuid(getuid()); m_currentUser = QString(pws->pw_name); - qInfo() << "UserPageWidget Construction:" << "currentuser:" << m_currentUser; + qCInfo(app) << "UserPageWidget Construction:" + << "currentuser:" << m_currentUser; initUI(); initConnections(); - } // destructor @@ -98,7 +98,6 @@ void UserPageWidget::initUI() m_DiskReadLabel->setToolTip(QApplication::translate("Process.Table.Header", kProcessDiskRead)); m_DiskWriteLabel->setToolTip(QApplication::translate("Process.Table.Header", kProcessDiskWrite)); - m_CPUUsageSummary = new DLabel(usageSummaryWidget); m_MemeryUsageSummary = new DLabel(usageSummaryWidget); m_SMemUsageSummary = new DLabel(usageSummaryWidget); @@ -152,7 +151,6 @@ void UserPageWidget::initUI() usageSummaryWidget->setLayout(usageLayout); /***********************************************usage Labels**************************************************/ - QWidget *userInfoWideget = new QWidget(this); auto *contentlayout = new QVBoxLayout(userInfoWideget); @@ -175,7 +173,7 @@ void UserPageWidget::initConnections() { connect(m_accountListWidget, &AccountsWidget::signalCurrentChanged, this, &UserPageWidget::onUserChanged); connect(m_procTable, &ProcessTableView::signalModelUpdated, this, &UserPageWidget::onTextContentChanged); - connect(m_dAppHelper, &DApplicationHelper::themeTypeChanged, this, &UserPageWidget::onThemeChanged); + connect(m_dAppHelper, &DApplicationHelper::themeTypeChanged, this, &UserPageWidget::onThemeChanged); connect(m_procTable, &ProcessTableView::signalHeadchanged, this, &UserPageWidget::onHeaderChanged); } @@ -191,20 +189,16 @@ void UserPageWidget::paintEvent(QPaintEvent *) DApplicationHelper *dAppHelper = DApplicationHelper::instance(); DPalette palette = dAppHelper->applicationPalette(); QColor bgColor = palette.color(DPalette::Background); - - - } void UserPageWidget::onUserChanged() { QString userName = m_accountListWidget->getCurrentItemUserName(); - qInfo() << userName << "user changed"; + qCInfo(app) << userName << "user changed"; m_procTable->setUserModeName(userName); onTextContentChanged(); update(); } - void UserPageWidget::onTextContentChanged() { @@ -331,7 +325,6 @@ void UserPageWidget::onThemeChanged() m_DiskWriteLabel->setPalette(palette); } - if (m_CPUUsageSummary) { auto palette = DApplicationHelper::instance()->applicationPalette(); palette.setColor(DPalette::Text, palette.color(DPalette::TextTips)); @@ -372,6 +365,4 @@ void UserPageWidget::onThemeChanged() palette.setColor(DPalette::Text, palette.color(DPalette::TextTips)); m_DiskWriteSummary->setPalette(palette); } - - } diff --git a/deepin-system-monitor-main/gui/xwin_kill_preview_widget.cpp b/deepin-system-monitor-main/gui/xwin_kill_preview_widget.cpp index 915134c7..3c536d26 100644 --- a/deepin-system-monitor-main/gui/xwin_kill_preview_widget.cpp +++ b/deepin-system-monitor-main/gui/xwin_kill_preview_widget.cpp @@ -11,9 +11,9 @@ #include "main_window.h" #include "ui_common.h" #include "common/common.h" - +#include "ddlog.h" #ifdef USE_DEEPIN_WAYLAND -#include "3rdparty/displayjack/wayland_client.h" +# include "3rdparty/displayjack/wayland_client.h" #endif #include @@ -35,6 +35,7 @@ using namespace std; using namespace core::wm; using namespace common::init; +using namespace DDLog; typedef int (*InitDtkWmDisplayPtr)(); typedef void (*DestoryDtkWmDisplayPtr)(); @@ -46,7 +47,8 @@ static DestoryDtkWmDisplayPtr DestoryDtkWmDisplay = nullptr; static GetAllWindowStatesListPtr GetAllWindowStatesList = nullptr; // constructor -XWinKillPreviewWidget::XWinKillPreviewWidget(QWidget *parent) : QWidget(parent) +XWinKillPreviewWidget::XWinKillPreviewWidget(QWidget *parent) + : QWidget(parent) { // new window manager instance m_wminfo = new WMInfo(); @@ -65,7 +67,7 @@ XWinKillPreviewWidget::XWinKillPreviewWidget(QWidget *parent) : QWidget(parent) if (InitDtkWmDisplay) InitDtkWmDisplay(); } -#endif // USE_DEEPIN_WAYLAND +#endif // USE_DEEPIN_WAYLAND // init ui components & connections initUI(); @@ -99,7 +101,7 @@ XWinKillPreviewWidget::~XWinKillPreviewWidget() if (DestoryDtkWmDisplay) DestoryDtkWmDisplay(); } -#endif // USE_DEEPIN_WAYLAND +#endif // USE_DEEPIN_WAYLAND } // mouse press event @@ -113,7 +115,7 @@ void XWinKillPreviewWidget::mousePressEvent(QMouseEvent *event) auto pos = QCursor::pos(); #ifdef USE_DEEPIN_WAYLAND if (WaylandCentered) { - double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 + double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 QRect screenRect; for (auto screen : QApplication::screens()) { // screen geometry @@ -124,11 +126,11 @@ void XWinKillPreviewWidget::mousePressEvent(QMouseEvent *event) } } for (QVector::iterator it = m_windowStates.end() - 1; - it != m_windowStates.begin(); --it) { + it != m_windowStates.begin(); --it) { // if the window is created by ourself, then ignore it if (getpid() == it->pid || QString::fromStdString(it->resourceName) == "dde-desktop" || it->isMinimized - || QString::fromStdString(it->resourceName) == "deepin-deepinid-client" - || QString::fromStdString(it->resourceName) == "dde-dock") + || QString::fromStdString(it->resourceName) == "deepin-deepinid-client" + || QString::fromStdString(it->resourceName) == "dde-dock") continue; // if such window exists, we emit window clicked signal to notify kill application performed action @@ -150,10 +152,10 @@ void XWinKillPreviewWidget::mousePressEvent(QMouseEvent *event) } } } -#endif // USE_DEEPIN_WAYLAND +#endif // USE_DEEPIN_WAYLAND if (!WaylandCentered) { - double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 + double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 QRect screenRect; for (auto screen : QApplication::screens()) { // screen geometry @@ -163,8 +165,8 @@ void XWinKillPreviewWidget::mousePressEvent(QMouseEvent *event) break; } } - QPoint windowPos(static_cast(screenRect.x() + (pos.x() - screenRect.x())*ratio), - static_cast(screenRect.y() + (pos.y() - screenRect.y())*ratio)); + QPoint windowPos(static_cast(screenRect.x() + (pos.x() - screenRect.x()) * ratio), + static_cast(screenRect.y() + (pos.y() - screenRect.y()) * ratio)); auto list = m_wminfo->selectWindow(windowPos); // fix cursor not update issue while moved to areas covered by intersected area of dock & normal windows @@ -200,7 +202,7 @@ void XWinKillPreviewWidget::mouseMoveEvent(QMouseEvent *) { #ifdef USE_DEEPIN_WAYLAND if (WaylandCentered) { - double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 + double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 auto pos = QCursor::pos(); QRect screenRect; for (auto screen : QApplication::screens()) { @@ -212,15 +214,15 @@ void XWinKillPreviewWidget::mouseMoveEvent(QMouseEvent *) } } // get the list of windows under cursor from cache in stacked order - bool found {false}; + bool found { false }; for (QVector::iterator it = m_windowStates.end() - 1; - it != m_windowStates.begin(); --it) { + it != m_windowStates.begin(); --it) { // if the window is created by ourself, then ignore it // wayland环境下增加桌面窗口和dock栏的屏蔽 if (getpid() == it->pid || QString::fromStdString(it->resourceName) == "dde-desktop" || it->isMinimized - || QString::fromStdString(it->resourceName) == "deepin-deepinid-client" - || QString::fromStdString(it->resourceName) == "dde-dock") + || QString::fromStdString(it->resourceName) == "deepin-deepinid-client" + || QString::fromStdString(it->resourceName) == "dde-dock") continue; auto selRect = QRect(static_cast(screenRect.x() + (it->geometry.x - screenRect.x()) / ratio), static_cast(screenRect.y() + (it->geometry.y - screenRect.y()) / ratio), @@ -230,12 +232,12 @@ void XWinKillPreviewWidget::mouseMoveEvent(QMouseEvent *) // find all windows hovered above, if any clip out the intersected region - QRegion region {selRect}; + QRegion region { selRect }; //对于所选窗口上方存在堆叠的窗口情况,对所选窗口进行区域裁剪。 for (QVector::iterator iter = m_windowStates.end() - 1; - iter != it; --iter) { + iter != it; --iter) { if (QString::fromStdString(iter->resourceName) == "dde-desktop" || iter->isMinimized || QString::fromStdString(iter->resourceName) == "deepin-deepinid-client" - || QString::fromStdString(iter->resourceName) == "dde-dock" || getpid() == iter->pid) + || QString::fromStdString(iter->resourceName) == "dde-dock" || getpid() == iter->pid) continue; else { @@ -246,10 +248,8 @@ void XWinKillPreviewWidget::mouseMoveEvent(QMouseEvent *) region = region.subtracted(upRegion); } - } - // if current selected window is crossing screens, we need update each sub part on each screen for (auto &bg : m_backgroundList) { if (bg->geometry().intersects(selRect)) { @@ -271,9 +271,9 @@ void XWinKillPreviewWidget::mouseMoveEvent(QMouseEvent *) emit cursorUpdated(m_defaultCursor); } } -#endif // USE_DEEPIN_WAYLAND +#endif // USE_DEEPIN_WAYLAND if (!WaylandCentered) { - double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 + double ratio = QGuiApplication::primaryScreen()->devicePixelRatio(); // 获得当前的缩放比例 auto pos = QCursor::pos(); QRect screenRect; for (auto screen : QApplication::screens()) { @@ -284,11 +284,11 @@ void XWinKillPreviewWidget::mouseMoveEvent(QMouseEvent *) break; } } - QPoint windowPos(static_cast(screenRect.x() + (pos.x() - screenRect.x())*ratio), - static_cast(screenRect.y() + (pos.y() - screenRect.y())*ratio)); + QPoint windowPos(static_cast(screenRect.x() + (pos.x() - screenRect.x()) * ratio), + static_cast(screenRect.y() + (pos.y() - screenRect.y()) * ratio)); // get the list of windows under cursor from cache in stacked order auto list = m_wminfo->selectWindow(windowPos); - bool found {false}; + bool found { false }; // fix cursor not update issue while moved to areas covered by intersected area of dock & normal windows if (m_wminfo->isCursorHoveringDocks(windowPos)) { @@ -309,7 +309,7 @@ void XWinKillPreviewWidget::mouseMoveEvent(QMouseEvent *) // find all windows hovered above, if any clip out the intersected region auto hoveredBy = m_wminfo->getHoveredByWindowList(select->wid, select->rect); - QRegion region {selRect}; + QRegion region { selRect }; for (auto &hover : hoveredBy) { QRect hoverrect(static_cast(screenRect.x() + (hover->rect.x() - screenRect.x()) / ratio), static_cast(screenRect.y() + (hover->rect.y() - screenRect.y()) / ratio), @@ -378,10 +378,9 @@ void XWinKillPreviewWidget::initUI() // default forbid style cursor m_defaultCursor = QCursor(Qt::ForbiddenCursor); - QTimer::singleShot(500, this, [ = ] { + QTimer::singleShot(500, this, [=] { // show background window in all screens - for (auto screen : QApplication::screens()) - { + for (auto screen : QApplication::screens()) { // screen geometry auto geom = screen->geometry(); // snapshot current scree @@ -389,7 +388,7 @@ void XWinKillPreviewWidget::initUI() #ifdef USE_DEEPIN_WAYLAND if (WaylandCentered) pixmap = screen->grabWindow(m_windowStates.end()->windowId); -#endif // USE_DEEPIN_WAYLAND +#endif // USE_DEEPIN_WAYLAND pixmap = pixmap.copy(geom.x(), geom.y(), static_cast(geom.width() * devicePixelRatioF()), static_cast(geom.height() * devicePixelRatioF())); // create preview background widget for each screen auto *background = new XWinKillPreviewBackgroundWidget(pixmap, this); @@ -417,21 +416,20 @@ void XWinKillPreviewWidget::initConnections() #ifdef USE_DEEPIN_WAYLAND if (WaylandCentered) { connect(m_connectionThreadObject, &ConnectionThread::connected, this, - [this] { - m_eventQueue = new EventQueue(this); - m_eventQueue->setup(m_connectionThreadObject); - - Registry *registry = new Registry(this); - setupRegistry(registry); - }, - Qt::QueuedConnection - ); + [this] { + m_eventQueue = new EventQueue(this); + m_eventQueue->setup(m_connectionThreadObject); + + Registry *registry = new Registry(this); + setupRegistry(registry); + }, + Qt::QueuedConnection); m_connectionThreadObject->moveToThread(m_connectionThread); m_connectionThread->start(); m_connectionThreadObject->initConnection(); } -#endif // USE_DEEPIN_WAYLAND +#endif // USE_DEEPIN_WAYLAND } //打印当前窗口信息接口 @@ -440,20 +438,20 @@ void XWinKillPreviewWidget::print_window_states(const QVectorcreateCompositor(name, version, this); - } - ); + [this, registry](quint32 name, quint32 version) { + m_compositor = registry->createCompositor(name, version, this); + }); connect(registry, &Registry::clientManagementAnnounced, this, - [this, registry](quint32 name, quint32 version) { - m_clientManagement = registry->createClientManagement(name, version, this); - connect(m_clientManagement, &ClientManagement::windowStatesChanged, this, - [this] { - m_windowStates = getAllWindowStates(); - } - ); - } - ); + [this, registry](quint32 name, quint32 version) { + m_clientManagement = registry->createClientManagement(name, version, this); + connect(m_clientManagement, &ClientManagement::windowStatesChanged, this, + [this] { + m_windowStates = getAllWindowStates(); + }); + }); connect(registry, &Registry::interfacesAnnounced, this, - [this] { - Q_ASSERT(m_compositor); - Q_ASSERT(m_clientManagement); - m_windowStates = getAllWindowStates(); - } - ); + [this] { + Q_ASSERT(m_compositor); + Q_ASSERT(m_clientManagement); + m_windowStates = getAllWindowStates(); + }); registry->setEventQueue(m_eventQueue); registry->create(m_connectionThreadObject); @@ -498,13 +492,12 @@ QVector XWinKillPreviewWidget::getAllWindowStates // 能解析到displayjack的接口,优先使用dispalayjack接口获取窗口状态 if (GetAllWindowStatesList) { // 使用displayjack库接口获取窗口状态 - WindowState * pStates = nullptr; + WindowState *pStates = nullptr; int nCount = GetAllWindowStatesList(&pStates); if (nCount <= 0) return vWindowStates; - for (int i = 0; i < nCount; i++) - { + for (int i = 0; i < nCount; i++) { WindowState *p = &pStates[i]; ClientManagement::WindowState windowState; windowState.pid = p->pid; @@ -530,5 +523,4 @@ QVector XWinKillPreviewWidget::getAllWindowStates return vWindowStates; } -#endif // USE_DEEPIN_WAYLAND - +#endif // USE_DEEPIN_WAYLAND diff --git a/deepin-system-monitor-main/logger.cpp b/deepin-system-monitor-main/logger.cpp new file mode 100644 index 00000000..9be9fcc8 --- /dev/null +++ b/deepin-system-monitor-main/logger.cpp @@ -0,0 +1,67 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include "logger.h" +#include "dtkcore_global.h" +#include "qglobal.h" +#include "ddlog.h" +#include +#include + +#include +using namespace DDLog; +DCORE_USE_NAMESPACE + +MLogger::MLogger(QObject *parent) + : QObject(parent), m_rules(""), m_config(nullptr) +{ + QByteArray logRules = qgetenv("QT_LOGGING_RULES"); + // qunsetenv 之前一定不要有任何日志打印,否则取消环境变量设置不会生效 + qunsetenv("QT_LOGGING_RULES"); + + // set env + m_rules = logRules; + + // set dconfig + m_config = DConfig::create("org.deepin.system-monitor", "org.deepin.system-monitor"); + logRules = m_config->value("log_rules").toByteArray(); + appendRules(logRules); + setRules(m_rules); + + // watch dconfig + connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) { + qCCritical(app) << "value changed:" << key; + if (key == "log_rules") { + setRules(m_config->value(key).toByteArray()); + } + }); +} + +MLogger::~MLogger() +{ + m_config->deleteLater(); +} + +void MLogger::setRules(const QString &rules) +{ + auto tmpRules = rules; + m_rules = tmpRules.replace(";", "\n"); + QLoggingCategory::setFilterRules(m_rules); +} + +void MLogger::appendRules(const QString &rules) +{ + QString tmpRules = rules; + tmpRules = tmpRules.replace(";", "\n"); + auto tmplist = tmpRules.split('\n'); + for (int i = 0; i < tmplist.count(); i++) + if (m_rules.contains(tmplist.at(i))) { + tmplist.removeAt(i); + i--; + } + if (tmplist.isEmpty()) + return; + m_rules.isEmpty() ? m_rules = tmplist.join("\n") + : m_rules += "\n" + tmplist.join("\n"); +} diff --git a/deepin-system-monitor-main/logger.h b/deepin-system-monitor-main/logger.h new file mode 100644 index 00000000..946fa7a3 --- /dev/null +++ b/deepin-system-monitor-main/logger.h @@ -0,0 +1,28 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include + +DCORE_BEGIN_NAMESPACE +class DConfig; +DCORE_END_NAMESPACE + +class MLogger : public QObject +{ + Q_OBJECT +public: + explicit MLogger(QObject *parent = nullptr); + ~MLogger(); + + inline QString rules() const { return m_rules; } + void setRules(const QString &rules); + +private: + void appendRules(const QString &rules); + +private: + QString m_rules; + Dtk::Core::DConfig *m_config; +}; diff --git a/deepin-system-monitor-main/main.cpp b/deepin-system-monitor-main/main.cpp index d7ea76fe..69e83b5c 100644 --- a/deepin-system-monitor-main/main.cpp +++ b/deepin-system-monitor-main/main.cpp @@ -24,7 +24,7 @@ #include #include #include - +#include "logger.h" DWIDGET_USE_NAMESPACE DCORE_USE_NAMESPACE @@ -32,6 +32,18 @@ using namespace common::init; int main(int argc, char *argv[]) { + MLogger(); // 日志处理要放在app之前,否则QApplication + // 内部可能进行了日志打印,导致环境变量设置不生效 +// 为了兼容性 +#if (DTK_VERSION >= DTK_VERSION_CHECK(5, 6, 8, 0)) + Dtk::Core::DLogManager::registerJournalAppender(); +#else + Dtk::Core::DLogManager::registerFileAppender(); +#endif +#ifdef QT_DEBUG + Dtk::Core::DLogManager::registerConsoleAppender(); +#endif + //Judge if Wayland WaylandSearchCentered(); if (!QString(qgetenv("XDG_CURRENT_DESKTOP")).toLower().startsWith("deepin")) { @@ -54,7 +66,7 @@ int main(int argc, char *argv[]) return 0; //获取dmidecode中CPU频率信息 - char *const cmd[] = {"dmidecode", "-t", "4"}; + char *const cmd[] = { "dmidecode", "-t", "4" }; get_cpuinfo_from_dmi(3, cmd); PERF_PRINT_BEGIN("POINT-01", ""); @@ -66,12 +78,12 @@ int main(int argc, char *argv[]) app.loadTranslator(); const QString descriptionText = DApplication::translate( - "App.About", - "System Monitor is a tool to monitor realtime system load, " - "view and control processes and services running on your system."); + "App.About", + "System Monitor is a tool to monitor realtime system load, " + "view and control processes and services running on your system."); const QString acknowledgementLink = - "https://www.deepin.org/acknowledgments/deepin-system-monitor#thanks"; + "https://www.deepin.org/acknowledgments/deepin-system-monitor#thanks"; app.setOrganizationName("deepin"); app.setApplicationName("deepin-system-monitor"); diff --git a/deepin-system-monitor-main/model/accounts_info_model.cpp b/deepin-system-monitor-main/model/accounts_info_model.cpp index 29412ebb..88fbe134 100644 --- a/deepin-system-monitor-main/model/accounts_info_model.cpp +++ b/deepin-system-monitor-main/model/accounts_info_model.cpp @@ -1,5 +1,6 @@ #include "accounts_info_model.h" #include "helper.hpp" +#include "ddlog.h" #include #include #include @@ -8,6 +9,8 @@ #include #include +using namespace DDLog; + #define PKEXEC_PATH "/usr/bin/pkexec" #define PKILL_PATH "/usr/bin/pkill" @@ -15,25 +18,25 @@ const QString LoginService = "org.freedesktop.login1"; const QString LoginPath = "/org/freedesktop/login1"; const QString LoginInterface = "org.freedesktop.login1.Manager"; -AccountsInfoModel::AccountsInfoModel(QObject *parent): QObject(parent) - , m_accountsInter(new QDBusInterface(common::systemInfo().AccountsService, common::systemInfo().AccountsPath, common::systemInfo().AccountsInterface, QDBusConnection::systemBus(), this)) - , m_LoginInter(new QDBusInterface(LoginService, LoginPath, LoginInterface, QDBusConnection::systemBus(), this)) - , m_controlInter(new QDBusInterface(common::systemInfo().ControlCenterService, common::systemInfo().ControlCenterPath, common::systemInfo().ControlCenterInterface, QDBusConnection::sessionBus(), this)) - , m_currentUserType(-1) +AccountsInfoModel::AccountsInfoModel(QObject *parent) + : QObject(parent), m_accountsInter(new QDBusInterface(common::systemInfo().AccountsService, common::systemInfo().AccountsPath, common::systemInfo().AccountsInterface, QDBusConnection::systemBus(), this)), m_LoginInter(new QDBusInterface(LoginService, LoginPath, LoginInterface, QDBusConnection::systemBus(), this)), m_controlInter(new QDBusInterface(common::systemInfo().ControlCenterService, common::systemInfo().ControlCenterPath, common::systemInfo().ControlCenterInterface, QDBusConnection::sessionBus(), this)), m_currentUserType(-1) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); struct passwd *pws; pws = getpwuid(getuid()); m_currentUserName = QString(pws->pw_name); - qInfo() << "AccountsInfoModel constructor line 26" << "m_currentUserName:" << m_currentUserName; + qCInfo(app) << "AccountsInfoModel constructor line 26" + << "m_currentUserName:" << m_currentUserName; //获取online userList updateUserOnlineStatus(); - qInfo() << "AccountsInfoModel constructor line 29" << "online user list:" << m_onlineUsers; + qCInfo(app) << "AccountsInfoModel constructor line 29" + << "online user list:" << m_onlineUsers; QStringList userList = m_accountsInter->property("UserList").toStringList(); updateUserList(userList); - qInfo() << "AccountsInfoModel constructor line 31" << "Accounts user list:" << userList; + qCInfo(app) << "AccountsInfoModel constructor line 31" + << "Accounts user list:" << userList; QDBusConnection::systemBus().connect(common::systemInfo().AccountsService, common::systemInfo().AccountsPath, common::systemInfo().AccountsInterface, "UserListChanged", this, SLOT(onUserListChanged(QStringList))); @@ -52,7 +55,7 @@ AccountsInfoModel::~AccountsInfoModel() void AccountsInfoModel::onUserListChanged(const QStringList &userPathList) { updateUserList(userPathList); - qInfo() << "get update:" << userPathList; + qCInfo(app) << "get update:" << userPathList; } void AccountsInfoModel::onSessionNew(const QString &in0, const QDBusObjectPath &in1) @@ -71,7 +74,8 @@ void AccountsInfoModel::onSessionRemoved(const QString &in0, const QDBusObjectPa void AccountsInfoModel::updateUserList(const QStringList &userPathList) { - qInfo() << "AccountsInfoModel updateUserList line 61" << "updateUserList begins!" ; + qCInfo(app) << "AccountsInfoModel updateUserList line 61" + << "updateUserList begins!"; // 释放构造对象 qDeleteAll(m_userMap.values()); m_userMap.clear(); @@ -91,7 +95,8 @@ void AccountsInfoModel::updateUserList(const QStringList &userPathList) newUser->setIsCurrentUser(true); m_currentUserType = newUser->userType(); } - qInfo() << "AccountsInfoModel updateUserList line 78" << "get user info of :" << newUser->name(); + qCInfo(app) << "AccountsInfoModel updateUserList line 78" + << "get user info of :" << newUser->name(); m_userMap.insert(newUser->name(), newUser); delete userDBus; @@ -100,11 +105,12 @@ void AccountsInfoModel::updateUserList(const QStringList &userPathList) void AccountsInfoModel::updateUserOnlineStatus() { - qInfo() << "AccountsInfoModel updateUserOnlineStatus line 88" << "updateUserOnlineStatus begins!" ; + qCInfo(app) << "AccountsInfoModel updateUserOnlineStatus line 88" + << "updateUserOnlineStatus begins!"; m_onlineUsers.clear(); //异步获取SessionList - QDBusMessage message = m_LoginInter->call("ListSessions"); + QDBusMessage message = m_LoginInter->call("ListSessions"); QDBusPendingReply reply = m_LoginInter->asyncCall(QStringLiteral("ListSessions")); reply.waitForFinished(); if (reply.isValid()) { @@ -118,7 +124,6 @@ void AccountsInfoModel::updateUserOnlineStatus() Q_EMIT signalUserOnlineStatusUpdated(); } - QList AccountsInfoModel::userList() const { QList onlineUsers; @@ -129,7 +134,8 @@ QList AccountsInfoModel::userList() const onlineUsers << user; } } - qInfo() << "AccountsInfoModel userList" << "get online users:" << m_onlineUsers; + qCInfo(app) << "AccountsInfoModel userList" + << "get online users:" << m_onlineUsers; return onlineUsers; } @@ -154,16 +160,14 @@ bool AccountsInfoModel::lockSessionByUserName(const QString &userName) return true; } } - qDebug() << "cannot find session with this username!"; + qCDebug(app) << "cannot find session with this username!"; return false; } else { - qDebug() << "no session found!"; + qCDebug(app) << "no session found!"; return false; } - } - bool AccountsInfoModel::activateSessionByUserName(const QString &userName) { @@ -175,45 +179,41 @@ bool AccountsInfoModel::activateSessionByUserName(const QString &userName) m_LoginInter->call("ActivateSession", si.sessionId); return true; } - } - qDebug() << "cannot find session with this username!"; + qCDebug(app) << "cannot find session with this username!"; return false; } else { - qDebug() << "no session found!"; + qCDebug(app) << "no session found!"; return false; } - } bool AccountsInfoModel::LogoutByUserName(const QString &userName) { if (userName == m_currentUserName) { if (m_sessionList.size() > 0) { - qInfo() << "m_sessionList is OK"; + qCInfo(app) << "m_sessionList is OK"; for (SessionInfo si : m_sessionList) { if (si.userName == userName) { - qInfo() << "found" << userName << si.sessionId; -// qInfo() << m_LoginInter->TerminateSession(si.sessionId).error(); + qCInfo(app) << "found" << userName << si.sessionId; + // qCInfo(app) << m_LoginInter->TerminateSession(si.sessionId).error(); return true; } - } - qDebug() << "cannot find session with current username!"; + qCDebug(app) << "cannot find session with current username!"; } else { - qDebug() << "no session found!"; - + qCDebug(app) << "no session found!"; } } else { QStringList params; // check pkexec existance - if (!QFile::exists({PKEXEC_PATH})) { + if (!QFile::exists({ PKEXEC_PATH })) { return false; } // check kill existance - if (!QFile::exists({PKILL_PATH})) { + if (!QFile::exists({ PKILL_PATH })) { return false; } @@ -221,20 +221,15 @@ bool AccountsInfoModel::LogoutByUserName(const QString &userName) QProcess proc; - proc.start({PKEXEC_PATH}, params); + proc.start({ PKEXEC_PATH }, params); proc.waitForFinished(); return true; } return false; - } void AccountsInfoModel::EditAccount() { if (m_controlInter) m_controlInter->call("ShowPage", "accounts", "Accounts Detail"); - } - - - diff --git a/deepin-system-monitor-main/model/process_table_model.cpp b/deepin-system-monitor-main/model/process_table_model.cpp index 4bc24110..0d764091 100644 --- a/deepin-system-monitor-main/model/process_table_model.cpp +++ b/deepin-system-monitor-main/model/process_table_model.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "process_table_model.h" #include "process/process_db.h" #include "common/common.h" @@ -15,14 +15,16 @@ #include using namespace common; using namespace common::format; -DGUI_USE_NAMESPACE // using namespace Dtk::Gui; +using namespace DDLog; +DGUI_USE_NAMESPACE // using namespace Dtk::Gui; // model constructor ProcessTableModel::ProcessTableModel(QObject *parent, const QString &username) : QAbstractTableModel(parent) { setUserModeName(username); - qInfo() << "ProcessTableModel Constructor line 41:" << "new model with name" << username; + qCInfo(app) << "ProcessTableModel Constructor line 41:" + << "new model with name" << username; //update model's process list cache on process list updated signal auto *monitor = ThreadManager::instance()->thread(BaseThread::kSystemMonitorThread)->systemMonitorInstance(); connect(monitor, &SystemMonitor::statInfoUpdated, this, &ProcessTableModel::updateProcessList); @@ -47,7 +49,7 @@ ProcessTableModel::ProcessTableModel(QObject *parent, const QString &username) if (!theme) { theme = DGuiApplicationHelper::instance()->applicationTheme(); - connect(theme, &DPlatformTheme::iconThemeNameChanged, this, [ = ]() { + connect(theme, &DPlatformTheme::iconThemeNameChanged, this, [=]() { updateProcessList(); }); } @@ -236,13 +238,13 @@ QVariant ProcessTableModel::data(const QModelIndex &index, int role) const switch (proc.state()) { case 'Z': name = QString("(%1) %2") - .arg(QApplication::translate("Process.Table", "No response")) - .arg(name); + .arg(QApplication::translate("Process.Table", "No response")) + .arg(name); break; case 'T': name = QString("(%1) %2") - .arg(QApplication::translate("Process.Table", "Suspend")) - .arg(name); + .arg(QApplication::translate("Process.Table", "Suspend")) + .arg(name); break; } return name; @@ -389,7 +391,7 @@ int ProcessTableModel::getProcessPriorityValue(pid_t pid) const // remove process entry from model with specified pid void ProcessTableModel::removeProcess(pid_t pid) { - qWarning()<= 0) { beginRemoveRows(QModelIndex(), row, row); @@ -419,7 +421,6 @@ void ProcessTableModel::updateProcessPriority(pid_t pid, int priority) } } - void ProcessTableModel::setUserModeName(const QString &userName) { if (userName != m_userModeName) { @@ -461,8 +462,6 @@ qreal ProcessTableModel::getTotalUpload() return upload; } - - qreal ProcessTableModel::getTotalVirtualMemoryUsage() { qlonglong vtmem = 0; diff --git a/deepin-system-monitor-main/process/process_db.cpp b/deepin-system-monitor-main/process/process_db.cpp index a2cfbb77..3a3454b4 100644 --- a/deepin-system-monitor-main/process/process_db.cpp +++ b/deepin-system-monitor-main/process/process_db.cpp @@ -220,7 +220,7 @@ void ProcessDB::sendSignalToProcess(pid_t pid, int signal) } else if (signal == SIGKILL) { Q_EMIT processKilled(pid); } else { - qWarning() << "Unexpected signal in this case:" << signal; + qCWarning(app) << "Unexpected signal in this case:" << signal; } }; auto fmsg = [ = ](int signal) -> QString { @@ -290,7 +290,7 @@ void ProcessDB::sendSignalToProcess(pid_t pid, int signal) errno, QApplication::translate("Process.Signal", "Failed in sending signal to process"), pid, SIGCONT, ec); - qWarning() << "Failed in sending signal to process! process id:" << pid; + qCWarning(app) << "Failed in sending signal to process! process id:" << pid; Q_EMIT processControlResultReady(ec); return; } diff --git a/deepin-system-monitor-main/service/service_manager.cpp b/deepin-system-monitor-main/service/service_manager.cpp index e862a450..4f05be1e 100644 --- a/deepin-system-monitor-main/service/service_manager.cpp +++ b/deepin-system-monitor-main/service/service_manager.cpp @@ -3,7 +3,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "service_manager.h" - +#include "ddlog.h" #include "application.h" #include "dbus/dbus_common.h" #include "dbus/dbus_properties_interface.h" @@ -39,7 +39,7 @@ DCORE_USE_NAMESPACE using namespace dbus::common; - +using namespace DDLog; std::atomic ServiceManager::m_instance; std::mutex ServiceManager::m_mutex; @@ -61,10 +61,10 @@ static bool setServiceEnable(const QString &servieName, bool enable, QString &er } if (!errorString.isEmpty()) { - qWarning() << QString("Set service %1 failed, error %1").arg(enable ? "enable" : "disable").arg(errorString); + qCWarning(app) << QString("Set service %1 failed, error %1").arg(enable ? "enable" : "disable").arg(errorString); return false; } else { - qDebug() << QString("Set service %1 ret: %2").arg(enable ? "enable" : "disable").arg(retMsg.value()); + qCDebug(app) << QString("Set service %1 ret: %2").arg(enable ? "enable" : "disable").arg(retMsg.value()); return true; } } @@ -77,7 +77,7 @@ CustomTimer::CustomTimer(ServiceManager *mgr, QObject *parent) void CustomTimer::start(const QString &path) { - connect(m_timer, &QTimer::timeout, this, [ = ]() { + connect(m_timer, &QTimer::timeout, this, [=]() { SystemServiceEntry e = m_mgr->updateServiceEntry(path); if (m_cnt >= 6 || isFinalState(e.getActiveState().toLocal8Bit())) { m_timer->stop(); @@ -126,9 +126,9 @@ QString ServiceManager::normalizeServiceId(const QString &id, const QString &par if (buf.lastIndexOf('@') > 0) { if (!param.isEmpty()) buf = QString("%1%2%3") - .arg(buf.left(buf.lastIndexOf('@') + 1)) - .arg(param) - .arg(UnitTypeServiceSuffix); + .arg(buf.left(buf.lastIndexOf('@') + 1)) + .arg(param) + .arg(UnitTypeServiceSuffix); } } else { if (buf.endsWith('@') && !param.isEmpty()) { @@ -155,7 +155,7 @@ ErrorContext ServiceManager::startService(const QString &id, auto oResult = iface.StartUnit(buf, mode); ec = oResult.first; if (ec) { - qDebug() << "StartUnit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "StartUnit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); return ec; } QDBusObjectPath o = oResult.second; @@ -171,7 +171,7 @@ ErrorContext ServiceManager::startService(const QString &id, auto o1 = Systemd1UnitInterface::normalizeUnitPath(buf); entry = updateServiceEntry(o1.path()); } else { - qDebug() << "GetUnit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "GetUnit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); return ec; } } else { @@ -180,7 +180,7 @@ ErrorContext ServiceManager::startService(const QString &id, } if (!isFinalState(entry.getActiveState().toLocal8Bit())) { - auto *timer = new CustomTimer {this}; + auto *timer = new CustomTimer { this }; timer->start(o.path()); } @@ -200,7 +200,7 @@ ErrorContext ServiceManager::stopService(const QString &id) auto oResult = iface.StopUnit(buf, mode); ec = oResult.first; if (ec) { - qDebug() << "Stop Unit failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "Stop Unit failed:" << ec.getErrorName() << ec.getErrorMessage(); return ec; } QDBusObjectPath o = oResult.second; @@ -216,7 +216,7 @@ ErrorContext ServiceManager::stopService(const QString &id) auto o1 = Systemd1UnitInterface::normalizeUnitPath(buf); entry = updateServiceEntry(o1.path()); } else { - qDebug() << "Get Unit failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "Get Unit failed:" << ec.getErrorName() << ec.getErrorMessage(); return ec; } } else { @@ -225,7 +225,7 @@ ErrorContext ServiceManager::stopService(const QString &id) } if (!isFinalState(entry.getActiveState().toLocal8Bit())) { - auto *timer = new CustomTimer {this}; + auto *timer = new CustomTimer { this }; timer->start(o.path()); } @@ -245,7 +245,7 @@ ErrorContext ServiceManager::restartService(const QString &id, const QString &pa auto oResult = iface.RestartUnit(buf, mode); ec = oResult.first; if (ec) { - qDebug() << "Restart Unit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "Restart Unit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); return ec; } QDBusObjectPath o = oResult.second; @@ -261,7 +261,7 @@ ErrorContext ServiceManager::restartService(const QString &id, const QString &pa auto o1 = Systemd1UnitInterface::normalizeUnitPath(buf); entry = updateServiceEntry(o1.path()); } else { - qDebug() << "Get Unit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "Get Unit failed:" << buf << ec.getErrorName() << ec.getErrorMessage(); return ec; } } else { @@ -270,7 +270,7 @@ ErrorContext ServiceManager::restartService(const QString &id, const QString &pa } if (!isFinalState(entry.getActiveState().toLocal8Bit())) { - auto *timer = new CustomTimer {this}; + auto *timer = new CustomTimer { this }; timer->start(o.path()); } @@ -288,30 +288,29 @@ ErrorContext ServiceManager::setServiceStartupMode(const QString &id, bool autoS Systemd1ManagerInterface mgrIf(DBUS_SYSTEMD1_SERVICE, kSystemDObjectPath.path(), QDBusConnection::systemBus()); if (autoStart) { - auto re = mgrIf.EnableUnitFiles({entry.getId()}); + auto re = mgrIf.EnableUnitFiles({ entry.getId() }); ec = re.first; if (ec) { - qDebug() << "call EnableUnitFiles failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "call EnableUnitFiles failed:" << ec.getErrorName() << ec.getErrorMessage(); return ec; } auto eResult = re.second; } else { - auto re = mgrIf.DisableUnitFiles({entry.getId()}); + auto re = mgrIf.DisableUnitFiles({ entry.getId() }); ec = re.first; if (ec) { - qDebug() << "call DisableUnitFiles failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "call DisableUnitFiles failed:" << ec.getErrorName() << ec.getErrorMessage(); return ec; } auto dResult = re.second; } #else - auto errfmt = [ = ](ErrorContext & pe, decltype(errno) err, const QString & title, const QString &message = {}) -> ErrorContext & { + auto errfmt = [=](ErrorContext &pe, decltype(errno) err, const QString &title, const QString &message = {}) -> ErrorContext & { pe.setCode(ErrorContext::kErrorTypeSystem); pe.setSubCode(err); pe.setErrorName(title); auto errmsg = (err != 0 ? QString("Error: [%1] %2").arg(err).arg(strerror(err)) : QString("Error: ")); - if (!message.isEmpty()) - { + if (!message.isEmpty()) { errmsg = QString("%1 - %2").arg(errmsg).arg(message); } pe.setErrorMessage(errmsg); @@ -327,7 +326,7 @@ ErrorContext ServiceManager::setServiceStartupMode(const QString &id, bool autoS sbuf = {}; rc = stat(BIN_PKEXEC_PATH, &sbuf); if (rc == -1) { - qDebug() << "check pkexec existence failed"; + qCDebug(app) << "check pkexec existence failed"; ec = errfmt(ec, errno, title, BIN_PKEXEC_PATH); return ec; } @@ -337,7 +336,7 @@ ErrorContext ServiceManager::setServiceStartupMode(const QString &id, bool autoS sbuf = {}; rc = stat(BIN_SYSTEMCTL_PATH, &sbuf); if (rc == -1) { - qDebug() << "check systemctl existence failed"; + qCDebug(app) << "check systemctl existence failed"; ec = errfmt(ec, errno, title, BIN_SYSTEMCTL_PATH); return ec; } @@ -354,7 +353,7 @@ ErrorContext ServiceManager::setServiceStartupMode(const QString &id, bool autoS QString action = autoStart ? "enable" : "disable"; bool useProcess = true; if (developerMode) { - proc.start(BIN_PKEXEC_PATH, {BIN_SYSTEMCTL_PATH, action, id}); + proc.start(BIN_PKEXEC_PATH, { BIN_SYSTEMCTL_PATH, action, id }); } else { // Bug 241793 非开发者模式,使用后端DBus服务设置启动方式 #if 0 @@ -387,8 +386,7 @@ ErrorContext ServiceManager::setServiceStartupMode(const QString &id, bool autoS // !0 (systemctl) - systemctl error, read stdout from child process if (exitStatus == QProcess::CrashExit) { errno = 0; - le = errfmt(le, errno, title, QApplication::translate("Service.Action.Set.Startup.Mode", - "Error: Failed to set service startup type due to the crashed sub process.")); + le = errfmt(le, errno, title, QApplication::translate("Service.Action.Set.Startup.Mode", "Error: Failed to set service startup type due to the crashed sub process.")); return le; } else { auto exitCode = proc.exitCode(); @@ -453,7 +451,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) QString id = idResult.second; auto sname = id; if (ec) { - qDebug() << "getId failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "getId failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { if (sname.endsWith(UnitTypeServiceSuffix)) { sname.chop(strlen(UnitTypeServiceSuffix)); @@ -465,7 +463,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto loadStateResult = unitIf.getLoadState(); ec = loadStateResult.first; if (ec) { - qDebug() << "getLoadState failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "getLoadState failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setLoadState(loadStateResult.second); } @@ -473,7 +471,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto activeStateResult = unitIf.getActiveState(); ec = activeStateResult.first; if (ec) { - qDebug() << "getActiveState failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "getActiveState failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setActiveState(activeStateResult.second); } @@ -481,7 +479,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto subStateResult = unitIf.getSubState(); ec = subStateResult.first; if (ec) { - qDebug() << "getSubState failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "getSubState failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setSubState(subStateResult.second); } @@ -489,19 +487,19 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto unitFileStateResult = mgrIf.GetUnitFileState(id); ec = unitFileStateResult.first; if (ec) { - qDebug() << "getUnitFileState failed:" << entry.getId() << ec.getErrorName() - << ec.getErrorMessage(); + qCDebug(app) << "getUnitFileState failed:" << entry.getId() << ec.getErrorName() + << ec.getErrorMessage(); } else { entry.setState(unitFileStateResult.second); entry.setStartupType(ServiceManager::getServiceStartupType( - entry.getSName(), - entry.getState())); + entry.getSName(), + entry.getState())); } auto descResult = unitIf.getDescription(); ec = descResult.first; if (ec) { - qDebug() << "getDescription failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "getDescription failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setDescription(descResult.second); } @@ -509,7 +507,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto mainPIDResult = svcIf.getMainPID(); ec = mainPIDResult.first; if (ec) { - qDebug() << "getMainPID failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "getMainPID failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setMainPID(mainPIDResult.second); } @@ -517,7 +515,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto canStartResult = unitIf.canStart(); ec = canStartResult.first; if (ec) { - qDebug() << "canStart failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "canStart failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setCanStart(canStartResult.second); } @@ -525,7 +523,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto canStopResult = unitIf.canStop(); ec = canStopResult.first; if (ec) { - qDebug() << "canStop failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "canStop failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setCanStop(canStopResult.second); } @@ -533,7 +531,7 @@ SystemServiceEntry ServiceManager::updateServiceEntry(const QString &opath) auto canReloadResult = unitIf.canReload(); ec = canReloadResult.first; if (ec) { - qDebug() << "canReload failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "canReload failed:" << ec.getErrorName() << ec.getErrorMessage(); } else { entry.setCanReload(canReloadResult.second); } diff --git a/deepin-system-monitor-main/service/service_manager_worker.cpp b/deepin-system-monitor-main/service/service_manager_worker.cpp index a5744a7d..d18a9ed8 100644 --- a/deepin-system-monitor-main/service/service_manager_worker.cpp +++ b/deepin-system-monitor-main/service/service_manager_worker.cpp @@ -3,7 +3,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "service_manager_worker.h" - +#include "ddlog.h" #include "dbus/dbus_common.h" #include "dbus/dbus_properties_interface.h" #include "dbus/environment_file.h" @@ -18,7 +18,9 @@ #include #include -ServiceManagerWorker::ServiceManagerWorker(QObject *parent) : QObject(parent) +using namespace DDLog; +ServiceManagerWorker::ServiceManagerWorker(QObject *parent) + : QObject(parent) { } @@ -36,14 +38,14 @@ void ServiceManagerWorker::startJob() auto unitFilesResult = mgrIf.ListUnitFiles(); ec = unitFilesResult.first; if (ec) { - qDebug() << "ListUnitFiles failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "ListUnitFiles failed:" << ec.getErrorName() << ec.getErrorMessage(); } UnitFileInfoList unitFiles = unitFilesResult.second; auto unitsResult = mgrIf.ListUnits(); ec = unitsResult.first; if (ec) { - qDebug() << "ListUnits failed:" << ec.getErrorName() << ec.getErrorMessage(); + qCDebug(app) << "ListUnits failed:" << ec.getErrorName() << ec.getErrorMessage(); } UnitInfoList units = unitsResult.second; for (auto u : units) { @@ -54,12 +56,12 @@ void ServiceManagerWorker::startJob() // filter-out non service type units std::function fltUnits; - fltUnits = [](const UnitInfo & unit) -> bool { + fltUnits = [](const UnitInfo &unit) -> bool { return unit.getName().endsWith(UnitTypeServiceSuffix); }; - std::function mapUnit = [&mgrIf](const UnitInfo & unit) { - ErrorContext ec1{}; - SystemServiceEntry entry{}; + std::function mapUnit = [&mgrIf](const UnitInfo &unit) { + ErrorContext ec1 {}; + SystemServiceEntry entry {}; // SName entry.setSName(unit.getName().left(unit.getName().lastIndexOf('.'))); // LoadState @@ -79,7 +81,7 @@ void ServiceManagerWorker::startJob() auto id = unitIf.getId(); ec1 = id.first; if (ec1) { - qDebug() << "call getId failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "call getId failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setId(id.second); } @@ -87,7 +89,7 @@ void ServiceManagerWorker::startJob() auto bStart = unitIf.canStart(); ec1 = bStart.first; if (ec1) { - qDebug() << "call canStart failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "call canStart failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setCanStart(bStart.second); } @@ -95,7 +97,7 @@ void ServiceManagerWorker::startJob() auto bStop = unitIf.canStop(); ec1 = bStop.first; if (ec1) { - qDebug() << "call canStart failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "call canStart failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setCanStop(bStop.second); } @@ -103,7 +105,7 @@ void ServiceManagerWorker::startJob() auto bReload = unitIf.canReload(); ec1 = bReload.first; if (ec1) { - qDebug() << "call canStart failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "call canStart failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setCanReload(bReload.second); } @@ -115,7 +117,7 @@ void ServiceManagerWorker::startJob() auto pid = svcIf.getMainPID(); ec1 = pid.first; if (ec1) { - qDebug() << "getMainPID failed" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "getMainPID failed" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setMainPID(pid.second); } @@ -124,48 +126,46 @@ void ServiceManagerWorker::startJob() auto state = mgrIf.GetUnitFileState(unit.getName()); ec1 = state.first; if (ec1) { - qDebug() << "getUnitFileState failed" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "getUnitFileState failed" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setState(state.second); } // startupType entry.setStartupType(ServiceManager::getServiceStartupType( - entry.getSName(), - entry.getState())); + entry.getSName(), + entry.getState())); return entry; }; - std::function &elist, const SystemServiceEntry &entry)> addServiceEntryFromUnitInfo; - addServiceEntryFromUnitInfo = [](QList &elist, const SystemServiceEntry & entry) { + std::function & elist, const SystemServiceEntry &entry)> addServiceEntryFromUnitInfo; + addServiceEntryFromUnitInfo = [](QList &elist, const SystemServiceEntry &entry) { elist << entry; }; auto fltufe = QtConcurrent::filter(units, fltUnits); fltufe.waitForFinished(); auto ufe = QtConcurrent::mappedReduced>(units, mapUnit, addServiceEntryFromUnitInfo); - std::function &elist, const SystemServiceEntry &entry)> addServiceEntryFromUnitFileInfo; - addServiceEntryFromUnitFileInfo = [&hash](QList &elist, const SystemServiceEntry & entry) { + std::function & elist, const SystemServiceEntry &entry)> addServiceEntryFromUnitFileInfo; + addServiceEntryFromUnitFileInfo = [&hash](QList &elist, const SystemServiceEntry &entry) { if (!hash.contains(entry.getId())) { elist << entry; } }; // filter-out non service type unit-files std::function fltUnitFiles; - fltUnitFiles = [&hash](const UnitFileInfo & unitFile) -> bool { + fltUnitFiles = [&hash](const UnitFileInfo &unitFile) -> bool { auto id = unitFile.getName().mid(unitFile.getName().lastIndexOf('/') + 1); - if (hash.contains(id)) - { + if (hash.contains(id)) { return false; - } else - { + } else { return unitFile.getName().endsWith(UnitTypeServiceSuffix); } }; - std::function mapUnitFiles; - mapUnitFiles = [](const UnitFileInfo & unf) { - SystemServiceEntry entry{}; - ErrorContext ec1{}; + std::function mapUnitFiles; + mapUnitFiles = [](const UnitFileInfo &unf) { + SystemServiceEntry entry {}; + ErrorContext ec1 {}; auto id = unf.getName().mid(unf.getName().lastIndexOf('/') + 1); auto sname = id; @@ -174,8 +174,8 @@ void ServiceManagerWorker::startJob() entry.setSName(sname); entry.setState(unf.getStatus()); entry.setStartupType(ServiceManager::getServiceStartupType( - entry.getSName(), - entry.getState())); + entry.getSName(), + entry.getState())); if (sname.endsWith('@')) { // read description from unit file auto desc = readUnitDescriptionFromUnitFile(unf.getName()); @@ -193,7 +193,7 @@ void ServiceManagerWorker::startJob() auto id1 = unitIf.getId(); ec1 = id1.first; if (ec1) { - qDebug() << "call getId failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "call getId failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setId(id1.second); } @@ -201,7 +201,7 @@ void ServiceManagerWorker::startJob() auto desc = unitIf.getDescription(); ec1 = desc.first; if (ec1) { - qDebug() << "getDescription failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "getDescription failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setDescription(desc.second); } @@ -209,7 +209,7 @@ void ServiceManagerWorker::startJob() auto actState = unitIf.getActiveState(); ec1 = actState.first; if (ec1) { - qDebug() << "getActiveState failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "getActiveState failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setActiveState(actState.second); } @@ -217,7 +217,7 @@ void ServiceManagerWorker::startJob() auto loadState = unitIf.getLoadState(); ec1 = loadState.first; if (ec1) { - qDebug() << "getLoadState failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "getLoadState failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setLoadState(loadState.second); } @@ -225,7 +225,7 @@ void ServiceManagerWorker::startJob() auto subState = unitIf.getSubState(); ec1 = subState.first; if (ec1) { - qDebug() << "getSubState failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "getSubState failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setSubState(subState.second); } @@ -233,7 +233,7 @@ void ServiceManagerWorker::startJob() auto mainPID = svcIf.getMainPID(); ec1 = mainPID.first; if (ec1) { - qDebug() << "getMainPID failed:" << ec1.getErrorName() << ec1.getErrorMessage(); + qCDebug(app) << "getMainPID failed:" << ec1.getErrorName() << ec1.getErrorMessage(); } else { entry.setMainPID(mainPID.second); } @@ -255,19 +255,18 @@ void ServiceManagerWorker::startJob() QString ServiceManagerWorker::readUnitDescriptionFromUnitFile(const QString &path) { - FILE *fp {nullptr}; - const int BLEN {2048}; - QByteArray buf {BLEN, 0}; - QByteArray desc {BLEN, 0}; - bool b {false}; + FILE *fp { nullptr }; + const int BLEN { 2048 }; + QByteArray buf { BLEN, 0 }; + QByteArray desc { BLEN, 0 }; + bool b { false }; fp = fopen(path.toLocal8Bit(), "r"); QString descStr; - if (fp) - { + if (fp) { while ((fgets(buf.data(), BLEN, fp))) { descStr = QString("Description=%1").arg(buf.data()); - QStringList descStrList = descStr.split(QRegExp("[\n]"),QString::SkipEmptyParts); + QStringList descStrList = descStr.split(QRegExp("[\n]"), QString::SkipEmptyParts); if (descStrList.size() > 0) { descStr = descStrList.at(0); b = true; diff --git a/deepin-system-monitor-main/system/block_device_info_db.cpp b/deepin-system-monitor-main/system/block_device_info_db.cpp index 01220e5a..0b77c399 100644 --- a/deepin-system-monitor-main/system/block_device_info_db.cpp +++ b/deepin-system-monitor-main/system/block_device_info_db.cpp @@ -5,7 +5,7 @@ #include "block_device_info_db.h" #include "block_device.h" - +#include "ddlog.h" #include #include #include @@ -20,6 +20,8 @@ #include +using namespace DDLog; + #define SYSFS_PATH_VIRTUAL_BLOCK "/sys/devices/virtual/block" namespace core { @@ -97,7 +99,6 @@ BlockDeviceInfoDB::BlockDeviceInfoDB() BlockDeviceInfoDB::~BlockDeviceInfoDB() { - } void BlockDeviceInfoDB::readDiskInfo() @@ -115,21 +116,20 @@ void BlockDeviceInfoDB::readDiskInfo() int index = -1; // 查找当前的device是否存在 for (int si = 0; si < m_deviceList.size(); ++si) { - if (m_deviceList[si].deviceName() == list[i].fileName().toLocal8Bit()) { // 存在 + if (m_deviceList[si].deviceName() == list[i].fileName().toLocal8Bit()) { // 存在 index = si; break; } } - if (index == -1) { // 不存在的话将该disk存储起来 + if (index == -1) { // 不存在的话将该disk存储起来 BlockDevice bd; if (bd.readDeviceSize(list[i].fileName()) > 0) { bd.setDeviceName(list[i].fileName().toLocal8Bit()); m_deviceList << bd; } } else { - m_deviceList[index].setDeviceName(list[i].fileName().toLocal8Bit()); // 更新disk数据 + m_deviceList[index].setDeviceName(list[i].fileName().toLocal8Bit()); // 更新disk数据 } - } } @@ -140,21 +140,20 @@ void BlockDeviceInfoDB::readDiskInfo() int index = -1; // 查找当前的device是否存在 for (int si = 0; si < m_deviceList.size(); ++si) { - if (m_deviceList[si].deviceName() == list[i].fileName().toLocal8Bit()) { // 存在 + if (m_deviceList[si].deviceName() == list[i].fileName().toLocal8Bit()) { // 存在 index = si; break; } } - if (index == -1) { // 不存在的话将该disk存储起来 + if (index == -1) { // 不存在的话将该disk存储起来 BlockDevice bd; if (bd.readDeviceSize(list[i].fileName()) > 0) { bd.setDeviceName(list[i].fileName().toLocal8Bit()); m_deviceList << bd; } } else { - m_deviceList[index].setDeviceName(list[i].fileName().toLocal8Bit()); // 更新disk数据 + m_deviceList[index].setDeviceName(list[i].fileName().toLocal8Bit()); // 更新disk数据 } - } } @@ -170,10 +169,8 @@ void BlockDeviceInfoDB::readDiskInfo() m_deviceList.removeAt(i); } } - } - //static void enum_block() //{ // struct udev *udev; @@ -213,18 +210,18 @@ void BlockDeviceInfoDB::readDiskInfo() // path = udev_list_entry_get_name(dev_list_entry); // dev = udev_device_new_from_syspath(udev, path); -//// qDebug() << "devNode" << udev_device_get_devnode(dev); -//// qDebug() << "devType" << udev_device_get_devtype(dev); -//// qDebug() << "sysName" << udev_device_get_sysname(dev); -//// qDebug() << "devPath" << udev_device_get_devpath(dev); -//// qDebug() << "sysPath" << udev_device_get_syspath(dev); -//// qDebug() << "sysnum" << udev_device_get_sysnum(dev); -//// qDebug() << "subsystem" << udev_device_get_subsystem(dev); +//// qCDebug(app) << "devNode" << udev_device_get_devnode(dev); +//// qCDebug(app) << "devType" << udev_device_get_devtype(dev); +//// qCDebug(app) << "sysName" << udev_device_get_sysname(dev); +//// qCDebug(app) << "devPath" << udev_device_get_devpath(dev); +//// qCDebug(app) << "sysPath" << udev_device_get_syspath(dev); +//// qCDebug(app) << "sysnum" << udev_device_get_sysnum(dev); +//// qCDebug(app) << "subsystem" << udev_device_get_subsystem(dev); //// auto *parent = udev_device_get_parent(dev); -//// qDebug() << "parent sysname: " << udev_device_get_sysname(parent); -//// qDebug() << "parent devpath: " << udev_device_get_devpath(parent); -//// qDebug() << "parent syspath: " << udev_device_get_syspath(parent); +//// qCDebug(app) << "parent sysname: " << udev_device_get_sysname(parent); +//// qCDebug(app) << "parent devpath: " << udev_device_get_devpath(parent); +//// qCDebug(app) << "parent syspath: " << udev_device_get_syspath(parent); // // /* skip if device/disk is a partition or loop device */ // // if (strncmp(udev_device_get_devtype(dev), "partition", 9) != 0 && @@ -266,18 +263,18 @@ void BlockDeviceInfoDB::update() // TODO: enum device in /sys/block => phy & virtual // TEST begin (move udev logic to udev & udevice) -// enum_block(); + // enum_block(); -// struct udev *udev = udev_new(); + // struct udev *udev = udev_new(); -// enumerate_usb_mass_storage(udev); + // enumerate_usb_mass_storage(udev); -// udev_unref(udev); -// // TEST end + // udev_unref(udev); + // // TEST end -// QWriteLocker lock(&m_rwlock); + // QWriteLocker lock(&m_rwlock); // update device list } -} // namespace system -} // namespace core +} // namespace system +} // namespace core diff --git a/deepin-system-monitor-main/system/cpu_set.cpp b/deepin-system-monitor-main/system/cpu_set.cpp index adc3c205..ca550f95 100644 --- a/deepin-system-monitor-main/system/cpu_set.cpp +++ b/deepin-system-monitor-main/system/cpu_set.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "cpu_set.h" #include "private/cpu_set_p.h" @@ -17,7 +17,6 @@ extern "C" { #include "../3rdparty/include/xalloc.h" } - #include #include #include @@ -34,6 +33,7 @@ extern "C" { using namespace common::error; using namespace common::alloc; using namespace common::init; +using namespace DDLog; static bool read_dmi_cache = false; @@ -310,7 +310,6 @@ CPUSet &CPUSet::operator=(const CPUSet &rhs) CPUSet::~CPUSet() { - } QString CPUSet::modelName() const @@ -362,11 +361,8 @@ QString CPUSet::minFreq() const QString CPUSet::maxFreq() const { //获取最大CPU频率数值,单位MHz - qreal MaxFreq = mIsEmptyModelName ? - d->m_info.value(QStringLiteral("CPU 最大 MHz")).toDouble() : - d->m_info.value("CPU max MHz").toDouble(); + qreal MaxFreq = mIsEmptyModelName ? d->m_info.value(QStringLiteral("CPU 最大 MHz")).toDouble() : d->m_info.value("CPU max MHz").toDouble(); return common::format::formatHz(static_cast(MaxFreq), common::format::MHz); - } QString CPUSet::l1dCache() const @@ -475,7 +471,7 @@ void CPUSet::read_stats() if (!(fp = fopen(PROC_PATH_STAT, "r"))) { print_errno(errno, QString("open %1 failed").arg(PROC_PATH_STAT)); return; - } // ::if(fopen) + } // ::if(fopen) fPtr.reset(fp); while (fgets(line.data(), BUFSIZ, fp)) { @@ -501,7 +497,7 @@ void CPUSet::read_stats() if (nr == 10) { // usage calc - QByteArray cpu {"cpu"}; + QByteArray cpu { "cpu" }; d->m_stat->cpu = cpu; if (!d->m_usage) { @@ -513,10 +509,10 @@ void CPUSet::read_stats() d->m_usage->cpu = cpu; d->m_usage->total = d->m_stat->user + d->m_stat->nice + d->m_stat->sys + d->m_stat->idle + d->m_stat->iowait + d->m_stat->hardirq + d->m_stat->softirq + d->m_stat->steal; d->m_usage->idle = d->m_stat->idle + d->m_stat->iowait; - } // ::if(usage) + } // ::if(usage) } else print_errno(errno, QString("read %1 failed, cpu").arg(PROC_PATH_STAT)); - } // ::if(m_stat) + } // ::if(m_stat) } else if (!strncmp(line.data(), "cpu", 3)) { // per cpu stat in jiffies auto stat = std::make_shared(); @@ -537,7 +533,7 @@ void CPUSet::read_stats() &stat->guest_nice); if (nr == 11) { - QByteArray cpu {"cpu"}; + QByteArray cpu { "cpu" }; cpu.append(QByteArray::number(ncpu)); stat->cpu = cpu; @@ -551,14 +547,15 @@ void CPUSet::read_stats() d->m_statDB[stat->cpu] = stat; d->m_usageDB[usage->cpu] = usage; - } //::if(usage) + } //::if(usage) } else print_errno(errno, QString("read %1 failed, cpu%2").arg(PROC_PATH_STAT).arg(ncpu)); - } // ::if(stat) + } // ::if(stat) } else if (!strncmp(line.data(), "btime", 5)) { // read boot time in seconds since epoch - struct timeval btime { + struct timeval btime + { }; long nsec {}; int nm = sscanf(line.data() + 5, "%ld", &nsec); @@ -569,9 +566,9 @@ void CPUSet::read_stats() // set sysinfo btime auto *monitor = ThreadManager::instance()->thread(BaseThread::kSystemMonitorThread)->systemMonitorInstance(); monitor->sysInfo()->set_btime(btime); - } // ::if(nm == 1) - } // ::if(btime) - } // ::while(fgets) + } // ::if(nm == 1) + } // ::if(btime) + } // ::while(fgets) if (ferror(fp)) print_errno(errno, QString("read %1 failed").arg(PROC_PATH_STAT)); @@ -608,41 +605,40 @@ void CPUSet::read_overall_info() infos.append(info); } -// if (!cpuinfo.contains("model name")) { -// mIsEmptyModelName = true; -// infos.clear(); -// // 根据lscpu源码实现获取CPU信息 -// process.start("lscpu"); -// process.waitForFinished(3000); -// QString lscpu = process.readAllStandardOutput(); - -// QStringList lscpuList = lscpu.split("\n", QString::SkipEmptyParts); -// d->m_info.clear(); -// for (QString lscpuLine : lscpuList) { -// QStringList keyValue {}; -// if (lscpuLine.contains(":")){ -// keyValue = lscpuLine.split(":", QString::SkipEmptyParts); -// } else if (lscpuLine.contains(":")) { -// keyValue = lscpuLine.split(":", QString::SkipEmptyParts); -// } - -// if (keyValue.count() > 1) -// d->m_info[keyValue.value(0).trimmed()] = keyValue.value(1).trimmed(); -// } -// } -// else { -// mIsEmptyModelName = false; -// read_lscpu(); -// d->m_infos = infos; -// } + // if (!cpuinfo.contains("model name")) { + // mIsEmptyModelName = true; + // infos.clear(); + // // 根据lscpu源码实现获取CPU信息 + // process.start("lscpu"); + // process.waitForFinished(3000); + // QString lscpu = process.readAllStandardOutput(); + + // QStringList lscpuList = lscpu.split("\n", QString::SkipEmptyParts); + // d->m_info.clear(); + // for (QString lscpuLine : lscpuList) { + // QStringList keyValue {}; + // if (lscpuLine.contains(":")){ + // keyValue = lscpuLine.split(":", QString::SkipEmptyParts); + // } else if (lscpuLine.contains(":")) { + // keyValue = lscpuLine.split(":", QString::SkipEmptyParts); + // } + + // if (keyValue.count() > 1) + // d->m_info[keyValue.value(0).trimmed()] = keyValue.value(1).trimmed(); + // } + // } + // else { + // mIsEmptyModelName = false; + // read_lscpu(); + // d->m_infos = infos; + // } read_lscpu(); d->m_infos = infos; } void CPUSet::read_dmi_cache_info() { - if (read_dmi_cache || (d->m_info.contains("L1d cache") && d->m_info.contains("L1i cache") - && d->m_info.contains("L2 cache") && d->m_info.contains("L3 cache"))) { + if (read_dmi_cache || (d->m_info.contains("L1d cache") && d->m_info.contains("L1i cache") && d->m_info.contains("L2 cache") && d->m_info.contains("L3 cache"))) { read_dmi_cache = true; return; } @@ -652,37 +648,40 @@ void CPUSet::read_dmi_cache_info() //(specialComType=0)如果不是特殊机型直接返回; //(specialComType<=-1)如果是未知类型,则使用之前的判断; //(specialComType>=1)如果是hw机型,略过之前的判断 - qInfo() << "common::specialComType value is:" << specialComType; - if(specialComType == 0){ + qCInfo(app) << "common::specialComType value is:" << specialComType; + if (specialComType == 0) { return; - }else if(specialComType <= -1){ - qInfo() << "use dmidecode check board type!"; - process.start("dmidecode", QStringList() << "-s" << "system-product-name"); + } else if (specialComType <= -1) { + qCInfo(app) << "use dmidecode check board type!"; + process.start("dmidecode", QStringList() << "-s" + << "system-product-name"); process.waitForFinished(-1); QString spnInfo = process.readAllStandardOutput(); if (!spnInfo.contains("KLVV", Qt::CaseInsensitive) && !spnInfo.contains("L540", Qt::CaseInsensitive) && !spnInfo.contains("KLVU", Qt::CaseInsensitive) - && !spnInfo.contains("PGUV", Qt::CaseInsensitive) && !spnInfo.contains("PGUW", Qt::CaseInsensitive) && !spnInfo.contains("W585", Qt::CaseInsensitive)) { + && !spnInfo.contains("PGUV", Qt::CaseInsensitive) && !spnInfo.contains("PGUW", Qt::CaseInsensitive) && !spnInfo.contains("W585", Qt::CaseInsensitive)) { - process.start("bash", QStringList() << "-c" << "dmidecode | grep -i \"String 4\""); + process.start("bash", QStringList() << "-c" + << "dmidecode | grep -i \"String 4\""); process.waitForStarted(); process.waitForFinished(); QString result = process.readAll(); - if(!result.contains("PWC30", Qt::CaseInsensitive) //w525 - && !result.contains("PGUX", Qt::CaseInsensitive)){ + if (!result.contains("PWC30", Qt::CaseInsensitive) //w525 + && !result.contains("PGUX", Qt::CaseInsensitive)) { process.close(); return; } } } - qInfo() << "Current is special computer type!"; + qCInfo(app) << "Current is special computer type!"; - process.start("dmidecode", QStringList() << "-t" << "cache"); + process.start("dmidecode", QStringList() << "-t" + << "cache"); process.waitForFinished(-1); QString cacheinfo = process.readAllStandardOutput(); QStringList caches = cacheinfo.split("\n\n", QString::SkipEmptyParts); process.close(); - QList > mapInfos; + QList> mapInfos; foreach (const QString &item, caches) { if (item.isEmpty()) continue; @@ -695,13 +694,13 @@ void CPUSet::read_dmi_cache_info() continue; QStringList words = line.split(": "); - if (1 == words.size() && words[0].endsWith(":")) { + if (1 == words.size() && words[0].endsWith(":")) { lasKey = words[0].replace(QRegExp(":$"), ""); mapInfo.insert(lasKey.trimmed(), " "); - } else if (1 == words.size() && !lasKey.isEmpty()) { + } else if (1 == words.size() && !lasKey.isEmpty()) { mapInfo[lasKey.trimmed()] += words[0]; mapInfo[lasKey.trimmed()] += " / "; - } else if (2 == words.size()) { + } else if (2 == words.size()) { lasKey = ""; mapInfo.insert(words[0].trimmed(), words[1].trimmed()); } @@ -748,10 +747,10 @@ void CPUSet::read_dmi_cache_info() // 获取CPU信息 ut001987 void CPUSet::read_lscpu() { - struct lscpu_cxt *cxt; // CPU信息 - cxt = reinterpret_cast< struct lscpu_cxt *>(xcalloc(1, sizeof(struct lscpu_cxt))); // 初始化信息 + struct lscpu_cxt *cxt; // CPU信息 + cxt = reinterpret_cast(xcalloc(1, sizeof(struct lscpu_cxt))); // 初始化信息 if (!cxt) { - qWarning() << __FUNCTION__ << " lscpu_cxt Init Faild!"; + qCWarning(app) << __FUNCTION__ << " lscpu_cxt Init Faild!"; return; } /* set default cpu display mode if none was specified */ @@ -762,14 +761,14 @@ void CPUSet::read_lscpu() cxt->syscpu = ul_new_path(_PATH_SYS_CPU); if (!cxt->syscpu) { - qWarning() << __FUNCTION__ << "failed to initialize CPUs sysfs handler"; + qCWarning(app) << __FUNCTION__ << "failed to initialize CPUs sysfs handler"; return; } if (cxt->prefix) ul_path_set_prefix(cxt->syscpu, cxt->prefix); cxt->procfs = ul_new_path("/proc"); if (!cxt->procfs) { - qWarning() << __FUNCTION__ << "failed to initialize procfs handler!"; + qCWarning(app) << __FUNCTION__ << "failed to initialize procfs handler!"; return; } if (cxt->prefix) @@ -785,9 +784,9 @@ void CPUSet::read_lscpu() lscpu_read_numas(cxt); lscpu_read_topology(cxt); lscpu_decode_arm(cxt); - cxt->virt = lscpu_read_virtualization(cxt); // 获取CPU的虚拟化信息 + cxt->virt = lscpu_read_virtualization(cxt); // 获取CPU的虚拟化信息 struct lscpu_cputype *ct; - ct = lscpu_cputype_get_default(cxt); // 获取CPU类型信息 + ct = lscpu_cputype_get_default(cxt); // 获取CPU类型信息 if (ct) { if (cxt->arch) d->m_info.insert("Architecture", cxt->arch->name); @@ -814,7 +813,7 @@ void CPUSet::read_lscpu() d->m_info.insert("Byte Order", "Big Endian"); #endif d->m_info.insert("CPU(s)", QString::number(cxt->npresents)); - if (cxt->online) { // 当前活动CPU信息 + if (cxt->online) { // 当前活动CPU信息 QString key = cxt->hex ? "On-line CPU(s) mask" : "On-line CPU(s) list"; QString value = ""; size_t setbuflen = static_cast(7 * cxt->maxcpus); @@ -828,7 +827,7 @@ void CPUSet::read_lscpu() } // CPU厂商信息 - if (ct->vendor) { // CPU厂商信息 + if (ct->vendor) { // CPU厂商信息 QString strVendor = ct->vendor; strVendor = strVendor.simplified(); strVendor = strVendor.trimmed(); @@ -839,28 +838,28 @@ void CPUSet::read_lscpu() } else d->m_info.insert("Vendor ID", "-"); - if (ct && ct->bios_vendor) { // BIOS厂商信息 + if (ct && ct->bios_vendor) { // BIOS厂商信息 d->m_info.insert("BIOS Vendor ID", ct->bios_vendor); } - if (ct->modelname) {// CPU型号名称 + if (ct->modelname) { // CPU型号名称 d->m_info.insert("Model name", ct->modelname); } - if (ct->bios_modelname) {// bios 型号名称 + if (ct->bios_modelname) { // bios 型号名称 d->m_info.insert("BIOS Model name", ct->bios_modelname); } - if (ct->bios_family) { // bios系列 + if (ct->bios_family) { // bios系列 d->m_info.insert("BIOS CPU family", ct->bios_family); } - if (ct->machinetype) {// 机器类型 + if (ct->machinetype) { // 机器类型 d->m_info.insert("Machine type", ct->machinetype); } - if (ct->family) { // CPU系列 + if (ct->family) { // CPU系列 d->m_info.insert("CPU family", ct->family); } if (ct->model || ct->revision) { d->m_info.insert("Model", ct->revision ? ct->revision : ct->model); } - d->m_info.insert("Thread(s) per core", QString::number(ct->nthreads_per_core)); // 单核线程数 + d->m_info.insert("Thread(s) per core", QString::number(ct->nthreads_per_core)); // 单核线程数 if (cxt->is_cluster) { d->m_info.insert("Core(s) per cluster", QString::number(ct->ncores_per_socket)); } else { @@ -890,8 +889,7 @@ void CPUSet::read_lscpu() d->m_info.insert("Stepping", ct->stepping); } if (ct->freqboost >= 0) { - d->m_info.insert("Frequency boost", ct->freqboost ? - _("enabled") : _("disabled")); + d->m_info.insert("Frequency boost", ct->freqboost ? _("enabled") : _("disabled")); } if (ct->dynamic_mhz) { @@ -907,7 +905,7 @@ void CPUSet::read_lscpu() QString minMHz = QString::number(static_cast(lsblk_cputype_get_minmhz(cxt, ct)), 'f', 4); d->m_info.insert("CPU min MHz", minMHz); // 取首个CPU频率有效值 - QString nowMHz = QString::number(static_cast(first_avaliable_cur_freq(cxt, ct)), 'f', 4); + QString nowMHz = QString::number(static_cast(first_avaliable_cur_freq(cxt, ct)), 'f', 4); if (scal == 0.0f) { nowMHz = "-"; } @@ -933,7 +931,7 @@ void CPUSet::read_lscpu() d->m_info.insert("Flags", ct->flags); } } else { - qWarning() << __FUNCTION__ << "ct init failed!"; + qCWarning(app) << __FUNCTION__ << "ct init failed!"; return; } @@ -963,11 +961,10 @@ void CPUSet::read_lscpu() if (!sz) continue; if (!cxt->bytes) { - char *tmp = size_to_human_string( // 获取当前cache的值 - SIZE_SUFFIX_3LETTER | - SIZE_SUFFIX_SPACE, - sz); - QString value = QString(tmp);//.replace("MiB","MB"); + char *tmp = size_to_human_string( // 获取当前cache的值 + SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE, + sz); + QString value = QString(tmp); //.replace("MiB","MB"); if (tmp) { free(tmp); tmp = nullptr; @@ -977,7 +974,6 @@ void CPUSet::read_lscpu() d->m_info.insert(QString(name) + " cache", value); } last = name; - } } read_dmi_cache_info(); @@ -1000,9 +996,8 @@ void CPUSet::read_lscpu() continue; if (!cxt->bytes) { char *tmp = size_to_human_string( - SIZE_SUFFIX_3LETTER | - SIZE_SUFFIX_SPACE, - ca->size); + SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE, + ca->size); d->m_info.insert(ca->name, tmp); if (tmp) { free(tmp); @@ -1021,5 +1016,5 @@ qulonglong CPUSet::getUsageTotalDelta() const return d->cpusageTotal[kCurrentStat] - d->cpusageTotal[kLastStat]; } -} // namespace system -} // namespace core +} // namespace system +} // namespace core diff --git a/deepin-system-monitor-main/system/netif_packet_capture.cpp b/deepin-system-monitor-main/system/netif_packet_capture.cpp index d6026aec..ef59de45 100644 --- a/deepin-system-monitor-main/system/netif_packet_capture.cpp +++ b/deepin-system-monitor-main/system/netif_packet_capture.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "netif_packet_capture.h" #include "netif_packet_parser.h" #include "common/hash.h" @@ -21,31 +21,26 @@ #include #ifndef IFNAMESZ -#define IFNAMESZ 16 +# define IFNAMESZ 16 #endif - //#define PACKET_DISPATCH_IDLE_TIME 200 // pcap dispatch interval -#define PACKET_DISPATCH_IDLE_TIME 50 // pcap dispatch interval -#define PACKET_DISPATCH_BATCH_COUNT 64 // packets to process in a batch -#define PACKET_DISPATCH_QUEUE_LWAT 64 // queue low water mark -#define PACKET_DISPATCH_QUEUE_HWAT 256 // queue high water mark +#define PACKET_DISPATCH_IDLE_TIME 50 // pcap dispatch interval +#define PACKET_DISPATCH_BATCH_COUNT 64 // packets to process in a batch +#define PACKET_DISPATCH_QUEUE_LWAT 64 // queue low water mark +#define PACKET_DISPATCH_QUEUE_HWAT 256 // queue high water mark -#define SOCKSTAT_REFRESH_INTERVAL 2 // socket stat refresh interval (2 seconds) -#define IFADDRS_HASH_CACHE_REFRESH_INTERVAL 10 // socket ifaddrs cache refresh interval (10 seconds) -#define DEVICE_CHANGE_JUDGEMENT_TIME 5000 //判断网卡是否变更时间间隔 +#define SOCKSTAT_REFRESH_INTERVAL 2 // socket stat refresh interval (2 seconds) +#define IFADDRS_HASH_CACHE_REFRESH_INTERVAL 10 // socket ifaddrs cache refresh interval (10 seconds) +#define DEVICE_CHANGE_JUDGEMENT_TIME 5000 //判断网卡是否变更时间间隔 using namespace std; - +using namespace DDLog; namespace core { namespace system { - - - NetifPacketCapture::NetifPacketCapture(NetifMonitor *netIfmontor, QObject *parent) - : QObject(parent) - , m_netifMonitor(netIfmontor) + : QObject(parent), m_netifMonitor(netIfmontor) { m_timer = new QTimer(this); m_timer->setSingleShot(true); @@ -57,7 +52,6 @@ NetifPacketCapture::NetifPacketCapture(NetifMonitor *netIfmontor, QObject *paren m_timerChangeDev->start(DEVICE_CHANGE_JUDGEMENT_TIME); } - void NetifPacketCapture::whetherDevChanged() { if (m_devName.isEmpty()) { @@ -81,12 +75,14 @@ bool NetifPacketCapture::hasDevIP() } struct sockaddr_in *addr {}; - struct ifreq ifr {}; + struct ifreq ifr + { + }; char *address {}; int sockfd; //设备名称过长 if (m_devName.size() >= IFNAMSIZ) { - //qDebug()<<"Device name too long! Invalid device Name!"; + //qCDebug(app)<<"Device name too long! Invalid device Name!"; return false; } @@ -97,11 +93,11 @@ bool NetifPacketCapture::hasDevIP() //获取网络IP(IPv4) if (ioctl(sockfd, SIOCGIFADDR, &ifr) == -1) { close(sockfd); - //qDebug()<<"ioctl error!"; + //qCDebug(app)<<"ioctl error!"; return false; } - addr = (struct sockaddr_in *) & (ifr.ifr_addr); + addr = (struct sockaddr_in *)&(ifr.ifr_addr); address = inet_ntoa(addr->sin_addr); if (address) { close(sockfd); @@ -111,8 +107,6 @@ bool NetifPacketCapture::hasDevIP() close(sockfd); return false; } - - } bool NetifPacketCapture::getCurrentDevName() @@ -133,7 +127,7 @@ bool NetifPacketCapture::getCurrentDevName() // 设备和优先级列编号 int metricColNum = 0; int devColNum = 0; - QList > metricList = {}; + QList> metricList = {}; QString devName = ""; if (totalList.size() > 0) { QStringList firstLine = totalList[0]; @@ -184,7 +178,6 @@ bool NetifPacketCapture::getCurrentDevName() return false; } return true; - } // void NetifPacketCapture::startNetifMonitorJob() @@ -200,7 +193,7 @@ void NetifPacketCapture::startNetifMonitorJob() // create pcap handler m_handle = pcap_create(m_devName.toLocal8Bit().data(), errbuf); if (!m_handle) { - qDebug() << "pcap_create failed: " << errbuf; + qCDebug(app) << "pcap_create failed: " << errbuf; return; } @@ -211,13 +204,13 @@ void NetifPacketCapture::startNetifMonitorJob() rc = pcap_compile(m_handle, &pgm, pattern, 1, PCAP_NETMASK_UNKNOWN); if (rc == -1) { - qDebug() << "pcap_compile failed: " << pcap_geterr(m_handle); + qCDebug(app) << "pcap_compile failed: " << pcap_geterr(m_handle); pcap_close(m_handle); return; } rc = pcap_setfilter(m_handle, &pgm); if (rc == -1) { - qDebug() << "pcap_setfilter failed: " << pcap_geterr(m_handle); + qCDebug(app) << "pcap_setfilter failed: " << pcap_geterr(m_handle); pcap_close(m_handle); return; } @@ -226,9 +219,9 @@ void NetifPacketCapture::startNetifMonitorJob() // activate pcap handler rc = pcap_activate(m_handle); if (rc > 0) { - qDebug() << "pcap_activate warning: " << pcap_statustostr(rc); + qCDebug(app) << "pcap_activate warning: " << pcap_statustostr(rc); } else if (rc < 0) { - qDebug() << "pcap_setnonblock failed: " << pcap_statustostr(rc); + qCDebug(app) << "pcap_setnonblock failed: " << pcap_statustostr(rc); pcap_close(m_handle); return; } @@ -432,7 +425,7 @@ void NetifPacketCapture::dispatchPackets() return; } else if (nr == -1) { // error occurred while processing packets - qDebug() << "pcap_dispatch failed: " << pcap_geterr(m_handle); + qCDebug(app) << "pcap_dispatch failed: " << pcap_geterr(m_handle); m_timer->stop(); break; } else if (nr == -2) { @@ -452,7 +445,7 @@ bool readNetIfAddrs(NetIFAddrsMap &addrsMap) errno = 0; if (getifaddrs(&addr_hdr) == -1) { - qWarning() << QString("getifaddrs failed: [%1] %2").arg(errno).arg(strerror(errno)); + qCWarning(app) << QString("getifaddrs failed: [%1] %2").arg(errno).arg(strerror(errno)); return false; } @@ -519,7 +512,5 @@ void NetifPacketCapture::refreshIfAddrsHashCache() } } - - -} // namespace system -} // namespace core +} // namespace system +} // namespace core diff --git a/deepin-system-monitor-main/system/netlink.cpp b/deepin-system-monitor-main/system/netlink.cpp index cad125c0..d06fba83 100644 --- a/deepin-system-monitor-main/system/netlink.cpp +++ b/deepin-system-monitor-main/system/netlink.cpp @@ -4,7 +4,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "netlink.h" - +#include "ddlog.h" #include "nl_addr.h" #include "nl_link.h" @@ -14,7 +14,7 @@ #include #include #include - +using namespace DDLog; namespace core { namespace system { @@ -23,25 +23,25 @@ Netlink::Netlink() int rc = 0; m_sock = nl_socket_alloc(); if (!m_sock) { - qWarning() << "Error: nl_socket_alloc failed"; + qCWarning(app) << "Error: nl_socket_alloc failed"; return; } rc = nl_connect(m_sock, NETLINK_ROUTE); if (rc) { - qWarning() << "Error: nl_connect failed"; + qCWarning(app) << "Error: nl_connect failed"; return; } rc = rtnl_link_alloc_cache(m_sock, AF_UNSPEC, &m_linkCache); if (rc) { - qWarning() << "Error: rtnl_link_alloc_cache failed"; + qCWarning(app) << "Error: rtnl_link_alloc_cache failed"; return; } rc = rtnl_addr_alloc_cache(m_sock, &m_addrCache); if (rc) { - qWarning() << "Error: rtnl_addr_alloc_cache failed"; + qCWarning(app) << "Error: rtnl_addr_alloc_cache failed"; } } @@ -64,5 +64,5 @@ AddrIterator Netlink::addrIterator() return it; } -} // namespace system -} // namespace core +} // namespace system +} // namespace core diff --git a/deepin-system-monitor-main/wm/wm_connection.cpp b/deepin-system-monitor-main/wm/wm_connection.cpp index 2802f0bb..93892445 100644 --- a/deepin-system-monitor-main/wm/wm_connection.cpp +++ b/deepin-system-monitor-main/wm/wm_connection.cpp @@ -4,8 +4,9 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "wm_connection.h" - +#include "ddlog.h" #include +using namespace DDLog; namespace core { namespace wm { @@ -15,7 +16,7 @@ WMConnection::WMConnection(const QByteArray &display) m_conn = XConnection(xcb_connect(display.isEmpty() ? nullptr : display.constData(), &m_screenNumber)); auto *conn = m_conn.get(); if (conn && xcb_connection_has_error(conn)) { - qDebug() << "Unable to connect to X server"; + qCDebug(app) << "Unable to connect to X server"; return; } m_atoms.initialize(conn); @@ -24,7 +25,7 @@ WMConnection::WMConnection(const QByteArray &display) auto iter = xcb_setup_roots_iterator(m_setup); auto screenCount = xcb_setup_roots_length(m_setup); if (screenCount < m_screenNumber) { - qDebug() << QString("Unable to access to screen %1, max is %2").arg(m_screenNumber).arg(screenCount - 1); + qCDebug(app) << QString("Unable to access to screen %1, max is %2").arg(m_screenNumber).arg(screenCount - 1); return; } @@ -40,5 +41,5 @@ WMConnection::~WMConnection() { } -} // namespace wm -} // namespace core +} // namespace wm +} // namespace core diff --git a/deepin-system-monitor-main/wm/wm_info.cpp b/deepin-system-monitor-main/wm/wm_info.cpp index 8e2715d6..343eb948 100644 --- a/deepin-system-monitor-main/wm/wm_info.cpp +++ b/deepin-system-monitor-main/wm/wm_info.cpp @@ -4,17 +4,18 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "wm_info.h" - +#include "ddlog.h" #include #include using namespace core::wm; using namespace std; +using namespace DDLog; enum wm_window_type_t { - kUnknownWindowType = -1, - kNormalWindowType = 0, + kUnknownWindowType = -1, + kNormalWindowType = 0, kDesktopWindowType, kDockWindowType, kToolbarWindowType, @@ -31,8 +32,8 @@ enum wm_window_type_t { }; enum wm_state_t { - kUnknownState = -1, - kModalState = 0, + kUnknownState = -1, + kModalState = 0, kStickyState, kMaximizedVertState, kMaximizedHorzState, @@ -48,77 +49,85 @@ enum wm_state_t { }; enum wm_window_class_t { - kUnknownClass = -1, - kInputOutputClass = XCB_WINDOW_CLASS_INPUT_OUTPUT, - kInputOnlyClass = XCB_WINDOW_CLASS_INPUT_ONLY + kUnknownClass = -1, + kInputOutputClass = XCB_WINDOW_CLASS_INPUT_OUTPUT, + kInputOnlyClass = XCB_WINDOW_CLASS_INPUT_ONLY }; enum wm_window_map_state_t { - kUnknownMapState = -1, - kUnMappedState = XCB_MAP_STATE_UNMAPPED, - kUnViewableState = XCB_MAP_STATE_UNVIEWABLE, - kViewableState = XCB_MAP_STATE_VIEWABLE + kUnknownMapState = -1, + kUnMappedState = XCB_MAP_STATE_UNMAPPED, + kUnViewableState = XCB_MAP_STATE_UNVIEWABLE, + kViewableState = XCB_MAP_STATE_VIEWABLE }; -struct core::wm::wm_request_t { - xcb_get_property_cookie_t netNameCookie; - xcb_get_property_cookie_t nameCookie; - xcb_get_geometry_cookie_t geomCookie; - xcb_translate_coordinates_cookie_t transCoordsCookie; - xcb_get_window_attributes_cookie_t attrCookie; - xcb_get_property_cookie_t desktopCookie; - xcb_get_property_cookie_t windowTypeCookie; - xcb_get_property_cookie_t stateCookie; - xcb_get_property_cookie_t pidCookie; - xcb_get_property_cookie_t frameExtentsCookie; - xcb_query_tree_cookie_t treeCookie; +struct core::wm::wm_request_t +{ + xcb_get_property_cookie_t netNameCookie; + xcb_get_property_cookie_t nameCookie; + xcb_get_geometry_cookie_t geomCookie; + xcb_translate_coordinates_cookie_t transCoordsCookie; + xcb_get_window_attributes_cookie_t attrCookie; + xcb_get_property_cookie_t desktopCookie; + xcb_get_property_cookie_t windowTypeCookie; + xcb_get_property_cookie_t stateCookie; + xcb_get_property_cookie_t pidCookie; + xcb_get_property_cookie_t frameExtentsCookie; + xcb_query_tree_cookie_t treeCookie; }; -struct core::wm::wm_frame_extents_t { +struct core::wm::wm_frame_extents_t +{ uint left; uint right; uint top; uint bottom; }; -struct core::wm::wm_window_ext_t { - WMWId windowId; // window id - WMWId parent {}; // window tree schema - QList children {}; - - pid_t pid; // _NET_WM_PID - int desktop {}; // desktop - enum wm_window_class_t wclass {}; // class: InputOutput || InputOnly && win attrs: XCB_WINDOW_CLASS_INPUT_OUTPUT || XCB_WINDOW_CLASS_INPUT_ONLY - enum wm_window_map_state_t map_state {}; // map state: unmapped || unviewable || viewable && win attrs: XCB_MAP_STATE_UNMAPPED || XCB_MAP_STATE_UNVIEWABLE || XCB_MAP_STATE_VIEWABLE - QList states {}; // window states && // _NET_WM_STATE - QList types {}; // window types (in order of preference) && _NET_WM_WINDOW_TYPE - struct wm_frame_extents_t extents {}; // window extents && //_NET_FRAME_EXTENTS - QRect rect {}; // geometry - - std::unique_ptr request; +struct core::wm::wm_window_ext_t +{ + WMWId windowId; // window id + WMWId parent {}; // window tree schema + QList children {}; + + pid_t pid; // _NET_WM_PID + int desktop {}; // desktop + enum wm_window_class_t wclass {}; // class: InputOutput || InputOnly && win attrs: XCB_WINDOW_CLASS_INPUT_OUTPUT || XCB_WINDOW_CLASS_INPUT_ONLY + enum wm_window_map_state_t map_state {}; // map state: unmapped || unviewable || viewable && win attrs: XCB_MAP_STATE_UNMAPPED || XCB_MAP_STATE_UNVIEWABLE || XCB_MAP_STATE_VIEWABLE + QList states {}; // window states && // _NET_WM_STATE + QList types {}; // window types (in order of preference) && _NET_WM_WINDOW_TYPE + struct wm_frame_extents_t extents + { + }; // window extents && //_NET_FRAME_EXTENTS + QRect rect {}; // geometry + + std::unique_ptr request; }; // tree schema in bottom to top stacking order -struct core::wm::wm_tree_t { - struct wm_window_ext_t *root; // root window - std::map cache; // [windowId : window extended info] mapping +struct core::wm::wm_tree_t +{ + struct wm_window_ext_t *root; // root window + std::map cache; // [windowId : window extended info] mapping }; -struct XReplyDeleter { +struct XReplyDeleter +{ void operator()(void *p) { free(p); } }; -using XGetPropertyReply = std::unique_ptr; -using XGetGeometryReply = std::unique_ptr; -using XGetWindowAttributeReply = std::unique_ptr; -using XQueryTreeReply = std::unique_ptr; -using XTransCoordsReply = std::unique_ptr; -using XGetAtomNameReply = std::unique_ptr; -using XInternAtomReply = std::unique_ptr; - -struct XDisconnector { +using XGetPropertyReply = std::unique_ptr; +using XGetGeometryReply = std::unique_ptr; +using XGetWindowAttributeReply = std::unique_ptr; +using XQueryTreeReply = std::unique_ptr; +using XTransCoordsReply = std::unique_ptr; +using XGetAtomNameReply = std::unique_ptr; +using XInternAtomReply = std::unique_ptr; + +struct XDisconnector +{ void operator()(xcb_connection_t *c) { xcb_disconnect(c); @@ -143,7 +152,6 @@ std::list WMInfo::selectWindow(const QPoint &pos) const std::function scan_tree; scan_tree = [&](const struct wm_window_ext_t *parent) { - for (auto &childWindowId : parent->children) { auto &child = m_tree->cache[childWindowId]; @@ -164,7 +172,7 @@ std::list WMInfo::selectWindow(const QPoint &pos) const // window type if (child->types.startsWith(kDockWindowType) - || child->types.startsWith(kDesktopWindowType)) + || child->types.startsWith(kDesktopWindowType)) continue; // window state @@ -174,24 +182,23 @@ std::list WMInfo::selectWindow(const QPoint &pos) const WMWindowArea warea(new struct wm_window_area_t()); // rect & extents - QRect rect{child->rect}; - rect = rect.marginsAdded({int(child->extents.left), - int(child->extents.top), - int(child->extents.right), - int(child->extents.bottom)}); + QRect rect { child->rect }; + rect = rect.marginsAdded({ int(child->extents.left), + int(child->extents.top), + int(child->extents.right), + int(child->extents.bottom) }); if (!rect.contains(pos)) continue; // window adjusted rect (including bounding frame) warea->rect = rect; - // pid - warea->pid = child->pid; + // pid + warea->pid = child->pid; warea->wid = child->windowId; walist.push_back(std::move(warea)); - } }; @@ -222,10 +229,10 @@ bool WMInfo::isCursorHoveringDocks(const QPoint &pos) const std::list WMInfo::getHoveredByWindowList(WMWId wid, QRect &area) const { std::list list {}; - bool done {false}; + bool done { false }; std::function scan_tree; - scan_tree = [&](const struct wm_window_ext_t *parent, const QRect & area) { + scan_tree = [&](const struct wm_window_ext_t *parent, const QRect &area) { for (auto &childWindowId : parent->children) { if (childWindowId == wid) { done = true; @@ -262,11 +269,11 @@ std::list WMInfo::getHoveredByWindowList(WMWId wid, QRect &area) c // adjust child rect with frame extents auto adjusted = child->rect; - adjusted = adjusted.marginsAdded(QMargins{ - int(child->extents.left), - int(child->extents.top), - int(child->extents.right), - int(child->extents.bottom)}); + adjusted = adjusted.marginsAdded(QMargins { + int(child->extents.left), + int(child->extents.top), + int(child->extents.right), + int(child->extents.bottom) }); // translate child geom if (!adjusted.intersects(area)) @@ -296,7 +303,7 @@ void WMInfo::buildWindowTreeSchema() auto *conn = connection.get(); err = xcb_connection_has_error(conn); if (err) { - qDebug() << "Unable to connect to X server"; + qCDebug(app) << "Unable to connect to X server"; return; } @@ -307,7 +314,7 @@ void WMInfo::buildWindowTreeSchema() xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup); int screenCount = xcb_setup_roots_length(setup); if (screenCount < screenNumber) { - qDebug() << QString("Unable to access to screen %1, max is %2").arg(screenNumber).arg(screenCount - 1); + qCDebug(app) << QString("Unable to access to screen %1, max is %2").arg(screenNumber).arg(screenCount - 1); return; } // get the screen we want from a list of screens in linked list structure @@ -430,35 +437,35 @@ void WMInfo::initAtomCache(xcb_connection_t *conn) buffer = frameExtentsAtomMeta->name; auto frameExtentsAtomCookie = xcb_intern_atom(conn, false, uint16_t(buffer.length()), buffer.data()); - auto nameAtom = getAtom(conn, nameAtomCookie); - nameAtomMeta->atom = nameAtom; - auto utf8StringAtom = getAtom(conn, utf8StringAtomCookie); - utf8StringAtomMeta->atom = utf8StringAtom; - auto desktopAtom = getAtom(conn, desktopAtomCookie); - desktopAtomMeta->atom = desktopAtom; - auto windowTypeAtom = getAtom(conn, windowTypeAtomCookie); - windowTypeAtomMeta->atom = windowTypeAtom; - auto stateAtom = getAtom(conn, stateAtomCookie); - stateAtomMeta->atom = stateAtom; - auto pidAtom = getAtom(conn, pidAtomCookie); - pidAtomMeta->atom = pidAtom; - auto frameExtentsAtom = getAtom(conn, frameExtentsAtomCookie); - frameExtentsAtomMeta->atom = frameExtentsAtom; - - m_internAtomCache[kNetNameAtom] = nameAtom; - m_internAtomCache[kUTF8StringAtom] = utf8StringAtom; - m_internAtomCache[kNetDesktopAtom] = desktopAtom; - m_internAtomCache[kNetWindowTypeAtom] = windowTypeAtom; - m_internAtomCache[kNetStateAtom] = stateAtom; - m_internAtomCache[kNetPIDAtom] = pidAtom; + auto nameAtom = getAtom(conn, nameAtomCookie); + nameAtomMeta->atom = nameAtom; + auto utf8StringAtom = getAtom(conn, utf8StringAtomCookie); + utf8StringAtomMeta->atom = utf8StringAtom; + auto desktopAtom = getAtom(conn, desktopAtomCookie); + desktopAtomMeta->atom = desktopAtom; + auto windowTypeAtom = getAtom(conn, windowTypeAtomCookie); + windowTypeAtomMeta->atom = windowTypeAtom; + auto stateAtom = getAtom(conn, stateAtomCookie); + stateAtomMeta->atom = stateAtom; + auto pidAtom = getAtom(conn, pidAtomCookie); + pidAtomMeta->atom = pidAtom; + auto frameExtentsAtom = getAtom(conn, frameExtentsAtomCookie); + frameExtentsAtomMeta->atom = frameExtentsAtom; + + m_internAtomCache[kNetNameAtom] = nameAtom; + m_internAtomCache[kUTF8StringAtom] = utf8StringAtom; + m_internAtomCache[kNetDesktopAtom] = desktopAtom; + m_internAtomCache[kNetWindowTypeAtom] = windowTypeAtom; + m_internAtomCache[kNetStateAtom] = stateAtom; + m_internAtomCache[kNetPIDAtom] = pidAtom; m_internAtomCache[kNetFrameExtentsAtom] = frameExtentsAtom; - m_atomCache[nameAtom] = std::move(nameAtomMeta); - m_atomCache[utf8StringAtom] = std::move(utf8StringAtomMeta); - m_atomCache[desktopAtom] = std::move(desktopAtomMeta); - m_atomCache[windowTypeAtom] = std::move(windowTypeAtomMeta); - m_atomCache[stateAtom] = std::move(stateAtomMeta); - m_atomCache[pidAtom] = std::move(pidAtomMeta); + m_atomCache[nameAtom] = std::move(nameAtomMeta); + m_atomCache[utf8StringAtom] = std::move(utf8StringAtomMeta); + m_atomCache[desktopAtom] = std::move(desktopAtomMeta); + m_atomCache[windowTypeAtom] = std::move(windowTypeAtomMeta); + m_atomCache[stateAtom] = std::move(stateAtomMeta); + m_atomCache[pidAtom] = std::move(pidAtomMeta); m_atomCache[frameExtentsAtom] = std::move(frameExtentsAtomMeta); } @@ -483,7 +490,7 @@ QByteArray WMInfo::getAtomName(xcb_connection_t *conn, xcb_atom_t atom) if (reply) { auto len = xcb_get_atom_name_name_length(reply.get()); auto name = xcb_get_atom_name_name(reply.get()); - meta->name = QByteArray{name, len}; + meta->name = QByteArray { name, len }; } m_atomCache[atom] = std::move(meta); } @@ -493,7 +500,7 @@ QByteArray WMInfo::getAtomName(xcb_connection_t *conn, xcb_atom_t atom) WMWindowExt WMInfo::requestWindowExtInfo(xcb_connection_t *conn, xcb_window_t window) { - WMWindowExt winfo(new wm_window_ext_t{}); + WMWindowExt winfo(new wm_window_ext_t {}); std::unique_ptr req(new wm_request_t {}); winfo->request = std::move(req); @@ -690,8 +697,8 @@ WMWindowExt WMInfo::requestWindowExtInfo(xcb_connection_t *conn, xcb_window_t wi winfo->types << kDNDWindowType; } else { winfo->types << kUnknownWindowType; - } // !if - } // !for + } // !if + } // !for } // state XGetPropertyReply stateReply(xcb_get_property_reply(conn, stateCookie, nullptr)); @@ -726,8 +733,8 @@ WMWindowExt WMInfo::requestWindowExtInfo(xcb_connection_t *conn, xcb_window_t wi winfo->states << kDemandsAttentionState; } else { winfo->states << kUnknownState; - } // !if - } // !for + } // !if + } // !for } // PID XGetPropertyReply pidReply(xcb_get_property_reply(conn, pidCookie, nullptr)); @@ -741,9 +748,9 @@ WMWindowExt WMInfo::requestWindowExtInfo(xcb_connection_t *conn, xcb_window_t wi XGetPropertyReply frameExtentsReply(xcb_get_property_reply(conn, frameExtentsCookie, nullptr)); if (frameExtentsReply && frameExtentsReply->type == XCB_ATOM_CARDINAL && frameExtentsReply->value_len == 4) { auto *frameExtents = reinterpret_cast(xcb_get_property_value(frameExtentsReply.get())); - winfo->extents.left = frameExtents[0]; - winfo->extents.right = frameExtents[1]; - winfo->extents.top = frameExtents[2]; + winfo->extents.left = frameExtents[0]; + winfo->extents.right = frameExtents[1]; + winfo->extents.top = frameExtents[2]; winfo->extents.bottom = frameExtents[3]; } else { winfo->extents = {}; diff --git a/deepin-system-monitor-plugin-popup/CMakeLists.txt b/deepin-system-monitor-plugin-popup/CMakeLists.txt index 3a46cfaa..6dcfb6c1 100644 --- a/deepin-system-monitor-plugin-popup/CMakeLists.txt +++ b/deepin-system-monitor-plugin-popup/CMakeLists.txt @@ -247,6 +247,8 @@ SET(CPP_PROCESS set(APP_HPP ${CMAKE_HOME_DIRECTORY}/config.h application.h + ddlog.h + logger.h ${HPP_MODEL} ${HPP_SYSTEM} ${HPP_GLOBAL} @@ -259,6 +261,7 @@ set(APP_HPP set(APP_CPP application.cpp main.cpp + logger.cpp ${CPP_MODEL} ${CPP_SYSTEM} ${CPP_GLOBAL} @@ -271,7 +274,7 @@ set(APP_CPP add_executable(${PROJECT_NAME} ${APP_HPP} ${APP_CPP} - ${PROJECT_SOURCE_DIR}/${APP_RESOURCES} + ${PROJECT_SOURCE_DIR}/${APP_RESOURCES} ) target_include_directories(${PROJECT_NAME} PUBLIC @@ -280,6 +283,7 @@ target_include_directories(${PROJECT_NAME} PUBLIC ${DtkCore_INCLUDE_DIRS} ${DtkGui_INCLUDE_DIRS} ${DdeDockInterface_INCLUDE_DIRS} + Dtk::Core ) target_link_libraries(${PROJECT_NAME} Qt5::Core @@ -302,6 +306,7 @@ target_link_libraries(${PROJECT_NAME} ${LIB_UDEV_LIBRARIES} ${LIB_DDEDOCK} # gsettings-qt + Dtk::Core ) diff --git a/deepin-system-monitor-plugin-popup/ddlog.h b/deepin-system-monitor-plugin-popup/ddlog.h new file mode 100644 index 00000000..5821c6fa --- /dev/null +++ b/deepin-system-monitor-plugin-popup/ddlog.h @@ -0,0 +1,16 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef DDLOG_H +#define DDLOG_H +#include +#include +DCORE_USE_NAMESPACE + +namespace DDLog { +inline Q_LOGGING_CATEGORY(app, "org.deepin.system-monitor.plugin.popup") +} + +#endif // DDLOG_H diff --git a/deepin-system-monitor-plugin-popup/gui/cpu_widget.cpp b/deepin-system-monitor-plugin-popup/gui/cpu_widget.cpp index 96c5f255..d9def2a5 100644 --- a/deepin-system-monitor-plugin-popup/gui/cpu_widget.cpp +++ b/deepin-system-monitor-plugin-popup/gui/cpu_widget.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "cpu_widget.h" #include "common/datacommon.h" #include "datadealsingleton.h" @@ -26,7 +26,7 @@ const int cpuTxtWidth = 96; DWIDGET_USE_NAMESPACE - +using namespace DDLog; CpuWidget::CpuWidget(QWidget *parent) : QWidget(parent) { @@ -47,7 +47,8 @@ CpuWidget::CpuWidget(QWidget *parent) this->installEventFilter(this); } -CpuWidget::~CpuWidget() { +CpuWidget::~CpuWidget() +{ delete downloadSpeeds; } @@ -63,17 +64,19 @@ void CpuWidget::initConnection() void CpuWidget::getPainterPathByData(QList *listData, QPainterPath &path, qreal maxVlaue) { qreal offsetX = 0; - qreal distance = (this->width() - cpuTxtWidth-10) * 1.0 / pointsNumber; + qreal distance = (this->width() - cpuTxtWidth - 10) * 1.0 / pointsNumber; int dataCount = listData->size(); if (maxVlaue < 0.000001) maxVlaue = 1; - for (int i = 0; i < dataCount - 1; i++) { + for (int i = 0; i < dataCount - 1; i++) { //sp 为线段的起始点,ep 为线段的终点 //c1,c2 为贝塞尔曲线的控制点 - QPointF sp = QPointF(offsetX, 20 * listData->at(i) / maxVlaue);; - QPointF ep = QPointF(offsetX + distance, 20 * listData->at(i + 1) / maxVlaue);; + QPointF sp = QPointF(offsetX, 20 * listData->at(i) / maxVlaue); + ; + QPointF ep = QPointF(offsetX + distance, 20 * listData->at(i + 1) / maxVlaue); + ; offsetX += distance; @@ -81,14 +84,14 @@ void CpuWidget::getPainterPathByData(QList *listData, QPainterPath &path QPointF c2 = QPointF((sp.x() + ep.x()) / 2.0, ep.y()); path.cubicTo(c1, c2, ep); -// qInfo()<<"sp, x:"<at(i) / maxVlaue; + // qCInfo(app)<<"sp, x:"<at(i) / maxVlaue; } } void CpuWidget::updateStatus() { if (!DataDealSingleton::getInstance().readCpuPer(m_cpuPer)) - qInfo()<<"false: "<append(m_cpuPer); @@ -161,74 +164,74 @@ void CpuWidget::paintEvent(QPaintEvent *e) //标题栏背景 QRect titleRect(rect().x(), rect().y(), m_width, 36); painter.fillRect(titleRect, QBrush(QColor(255, 255, 255, m_titleTrans))); - QRect contentRect(rect().x(), rect().y()+36, m_width, 75); - painter.fillRect(contentRect, QBrush(QColor(255, 255, 255,m_contentTrans))); + QRect contentRect(rect().x(), rect().y() + 36, m_width, 75); + painter.fillRect(contentRect, QBrush(QColor(255, 255, 255, m_contentTrans))); //标题 QString cpuTitle = DApplication::translate("Cpu.Widget", "CPU"); painter.setFont(m_TitleFont); -// QFontMetrics fmTitle = painter.fontMetrics(); + // QFontMetrics fmTitle = painter.fontMetrics(); int widthTitle = fmTitleContent.width(cpuTitle); - int heightTitle = fmTitleContent.descent()+fmTitleContent.ascent(); + int heightTitle = fmTitleContent.descent() + fmTitleContent.ascent(); QRect cpuTitleRect(titleRect.x(), titleRect.y(), widthTitle, heightTitle); painter.drawText(titleRect, Qt::AlignHCenter | Qt::AlignVCenter, cpuTitle); //图标 int iconSize = 20; - QRect iconRect(titleRect.x()+(titleRect.width()-widthTitle)/2-iconSize, titleRect.y() + qCeil((titleRect.height() - iconSize) / 2.) + 2,iconSize, iconSize); + QRect iconRect(titleRect.x() + (titleRect.width() - widthTitle) / 2 - iconSize, titleRect.y() + qCeil((titleRect.height() - iconSize) / 2.) + 2, iconSize, iconSize); m_icon.paint(&painter, iconRect); //cpu使用率长宽 painter.setFont(m_contentFont); QString cpuStatText = QString::number(m_cpuPer, 'f', 1); int widthCpu = fmContent.size(Qt::TextSingleLine, cpuStatText).width(); - int heightCpu = fmContent.descent()+fmContent.ascent(); + int heightCpu = fmContent.descent() + fmContent.ascent(); //cpu使用率百分号长宽 int widthCpuper = fmContentUnit.size(Qt::TextSingleLine, "%").width(); - int heightCpuper = fmContentUnit.descent()+fmContentUnit.ascent(); + int heightCpuper = fmContentUnit.descent() + fmContentUnit.ascent(); //写cpu使用率和百分号 - QRect cpuUsageRect(contentRect.x()+(cpuTxtWidth - widthCpu-widthCpuper)/2, contentRect.y()+10, widthCpu, heightCpu); + QRect cpuUsageRect(contentRect.x() + (cpuTxtWidth - widthCpu - widthCpuper) / 2, contentRect.y() + 10, widthCpu, heightCpu); painter.drawText(cpuUsageRect, Qt::AlignLeft | Qt::AlignBottom, cpuStatText); painter.setFont(m_contentUnitFont); - QRect cpuperUsageRect(cpuUsageRect.x() + cpuUsageRect.width(), cpuUsageRect.y()+ heightCpu/4, widthCpuper, heightCpuper); + QRect cpuperUsageRect(cpuUsageRect.x() + cpuUsageRect.width(), cpuUsageRect.y() + heightCpu / 4, widthCpuper, heightCpuper); painter.drawText(cpuperUsageRect, Qt::AlignLeft | Qt::AlignBottom, "%"); //总使用率 文本 painter.setOpacity(0.6); painter.setFont(m_subContentFont); int widthcpuText = fmSubContent.size(Qt::TextSingleLine, tr("Utilization")).width(); - QRect cpuTextRect(contentRect.x()+(cpuTxtWidth - widthcpuText)/2, cpuUsageRect.y()+cpuUsageRect.height(), + QRect cpuTextRect(contentRect.x() + (cpuTxtWidth - widthcpuText) / 2, cpuUsageRect.y() + cpuUsageRect.height(), fmSubContent.size(Qt::TextSingleLine, tr("Utilization")).width(), fmSubContent.height()); - painter.drawText(cpuTextRect, Qt::AlignLeft | Qt::AlignTop,tr("Utilization")); + painter.drawText(cpuTextRect, Qt::AlignLeft | Qt::AlignTop, tr("Utilization")); painter.setOpacity(1); //分隔符 int sepheight = 50; - int sepwidth =(contentRect.width() - 92-10)/2; - int rightMax = contentRect.x()+contentRect.width()-10; + int sepwidth = (contentRect.width() - 92 - 10) / 2; + int rightMax = contentRect.x() + contentRect.width() - 10; painter.setFont(m_contentFont); - QRect separatorRect1(contentRect.x()+cpuTxtWidth, contentRect.y()+10, 1, sepheight); - painter.fillRect(separatorRect1, QBrush(QColor(0, 0, 0,20))); - QRect separatorRect2(contentRect.x()+cpuTxtWidth+sepwidth, contentRect.y()+10, 1, sepheight); - painter.fillRect(separatorRect2, QBrush(QColor(0, 0, 0,20))); - QRect separatorRect3(rightMax, contentRect.y()+10, 1, sepheight); - painter.fillRect(separatorRect3, QBrush(QColor(0, 0, 0,20))); + QRect separatorRect1(contentRect.x() + cpuTxtWidth, contentRect.y() + 10, 1, sepheight); + painter.fillRect(separatorRect1, QBrush(QColor(0, 0, 0, 20))); + QRect separatorRect2(contentRect.x() + cpuTxtWidth + sepwidth, contentRect.y() + 10, 1, sepheight); + painter.fillRect(separatorRect2, QBrush(QColor(0, 0, 0, 20))); + QRect separatorRect3(rightMax, contentRect.y() + 10, 1, sepheight); + painter.fillRect(separatorRect3, QBrush(QColor(0, 0, 0, 20))); //走势图 QPainterPath framePath; - QRect chartRect(separatorRect1.x(), separatorRect1.y(), contentRect.width()-cpuTxtWidth-10, sepheight*2); -// framePath.addRect(chartRect); + QRect chartRect(separatorRect1.x(), separatorRect1.y(), contentRect.width() - cpuTxtWidth - 10, sepheight * 2); + // framePath.addRect(chartRect); - QColor Color {"#004EEF"}; + QColor Color { "#004EEF" }; QBrush recvBrush(Color); qreal networkCurveWidth = 1.2; QPainterPath clip; clip.addRect(chartRect); painter.setClipPath(clip); - painter.setRenderHint(QPainter::Antialiasing, true);//反锯齿 + painter.setRenderHint(QPainter::Antialiasing, true); //反锯齿 painter.translate(chartRect.x() + 2, chartRect.y() + chartRect.height() / 2 - 2); painter.scale(1, -1); @@ -271,11 +274,11 @@ void CpuWidget::changeFont(const QFont &font) m_contentFont = font; m_contentFont.setWeight(QFont::Normal); - m_contentFont.setPointSizeF(Globals::ContentFont+3); + m_contentFont.setPointSizeF(Globals::ContentFont + 3); m_contentUnitFont = font; m_contentUnitFont.setWeight(QFont::Normal); - m_contentUnitFont.setPointSizeF(Globals::ContentUnitFont+3); + m_contentUnitFont.setPointSizeF(Globals::ContentUnitFont + 3); m_subContentFont = font; m_subContentFont.setWeight(QFont::ExtraLight); diff --git a/deepin-system-monitor-plugin-popup/gui/datadealsingleton.cpp b/deepin-system-monitor-plugin-popup/gui/datadealsingleton.cpp index 4a58b42a..c8591f36 100644 --- a/deepin-system-monitor-plugin-popup/gui/datadealsingleton.cpp +++ b/deepin-system-monitor-plugin-popup/gui/datadealsingleton.cpp @@ -16,6 +16,7 @@ #include "dbus/dbuscallmaininterface.h" #include "config.h" #include "helper.hpp" +#include "ddlog.h" //Qt #include @@ -23,19 +24,18 @@ #include #ifdef IS_LOONGARCH_TYPE -#define POPUP_WAITING_TIME 1000 +# define POPUP_WAITING_TIME 1000 #else -#define POPUP_WAITING_TIME 500 +# define POPUP_WAITING_TIME 500 #endif - +using namespace DDLog; QMutex DataDealSingleton::mutex; QAtomicPointer DataDealSingleton::instance; DataDealSingleton &DataDealSingleton::getInstance() { - if (instance.testAndSetOrdered(nullptr, nullptr)) - { + if (instance.testAndSetOrdered(nullptr, nullptr)) { QMutexLocker locker(&mutex); instance.testAndSetOrdered(nullptr, new DataDealSingleton); @@ -128,9 +128,8 @@ bool DataDealSingleton::sendJumpWidgetMessage(const QString &dbusMessage) } DataDealSingleton::DataDealSingleton(QObject *parent) - :QObject (parent) - , m_popupTrickTimer(new QTimer(this)) - { + : QObject(parent), m_popupTrickTimer(new QTimer(this)) +{ m_popupTrickTimer->setInterval(1000); m_popupTrickTimer->setSingleShot(true); @@ -139,26 +138,24 @@ DataDealSingleton::DataDealSingleton(QObject *parent) DataDealSingleton::~DataDealSingleton() { - } bool DataDealSingleton::launchMainProcessByAM() const { QDBusMessage message = QDBusMessage::createMethodCall( - "org.desktopspec.ApplicationManager1", - "/org/desktopspec/ApplicationManager1/deepin_2dsystem_2dmonitor", - "org.desktopspec.ApplicationManager1.Application", - "Launch" - ); + "org.desktopspec.ApplicationManager1", + "/org/desktopspec/ApplicationManager1/deepin_2dsystem_2dmonitor", + "org.desktopspec.ApplicationManager1.Application", + "Launch"); message << QString("") << QStringList() << QVariantMap(); QDBusMessage reply = QDBusConnection::sessionBus().call(message); if (reply.type() == QDBusMessage::ReplyMessage) { - qDebug() << "Method call successful!"; + qCDebug(app) << "Method call successful!"; return true; } else { - qWarning() << "Launch deepin-system-monitor main process error:" << reply.errorMessage(); + qCWarning(app) << "Launch deepin-system-monitor main process error:" << reply.errorMessage(); return false; } -} \ No newline at end of file +} diff --git a/deepin-system-monitor-plugin-popup/gui/mainwindow.cpp b/deepin-system-monitor-plugin-popup/gui/mainwindow.cpp index 1f2ed502..d0a6666e 100644 --- a/deepin-system-monitor-plugin-popup/gui/mainwindow.cpp +++ b/deepin-system-monitor-plugin-popup/gui/mainwindow.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "mainwindow.h" #include "common/datacommon.h" //#include "itemwidget.h" @@ -31,17 +31,17 @@ #include #include -#define DOCK_TOP 0 -#define DOCK_RIGHT 1 -#define DOCK_BOTTOM 2 -#define DOCK_LEFT 3 +#define DOCK_TOP 0 +#define DOCK_RIGHT 1 +#define DOCK_BOTTOM 2 +#define DOCK_LEFT 3 #define SCREEN_HEIGHT_MAX 1080 -#define NOT_USE_QUIT_TIME_INTERVAL 5*60*1000 +#define NOT_USE_QUIT_TIME_INTERVAL 5 * 60 * 1000 const QString KILL_DBUS_COMMAND = "killall deepin-system-monitor-plugin-popup"; - +using namespace DDLog; MainWindow::MainWindow(QWidget *parent) #ifdef DTKWIDGET_CLASS_DBlurEffectWithBorderWidget @@ -49,22 +49,23 @@ MainWindow::MainWindow(QWidget *parent) #else : DBlurEffectWidget(parent) #endif - , m_displayInter(new QDBusInterface(common::systemInfo().DISPLAY_SERVICE, + , + m_displayInter(new QDBusInterface(common::systemInfo().DISPLAY_SERVICE, common::systemInfo().DISPLAY_PATH, common::systemInfo().DISPLAY_INTERFACE, - QDBusConnection::sessionBus(), this)) - , m_daemonDockInter(new QDBusInterface(common::systemInfo().DOCK_SERVICE, + QDBusConnection::sessionBus(), this)), + m_daemonDockInter(new QDBusInterface(common::systemInfo().DOCK_SERVICE, common::systemInfo().DOCK_PATH, common::systemInfo().DOCK_INTERFACE, - QDBusConnection::sessionBus(), this)) - , m_dockInter(new DBusDockInterface) - , m_systemMonitorDbusAdaptor(new SystemMonitorDBusAdaptor) - , m_regionMonitor(nullptr) - , m_xAni(new QPropertyAnimation(this, "x")) - , m_widthAni(new QPropertyAnimation(this, "width")) - , m_aniGroup(new QSequentialAnimationGroup(this)) - , m_trickTimer(new QTimer(this)) - , m_processEndTimer(new QTimer(this)) + QDBusConnection::sessionBus(), this)), + m_dockInter(new DBusDockInterface), + m_systemMonitorDbusAdaptor(new SystemMonitorDBusAdaptor), + m_regionMonitor(nullptr), + m_xAni(new QPropertyAnimation(this, "x")), + m_widthAni(new QPropertyAnimation(this, "width")), + m_aniGroup(new QSequentialAnimationGroup(this)), + m_trickTimer(new QTimer(this)), + m_processEndTimer(new QTimer(this)) { m_trickTimer->setInterval(300); m_trickTimer->setSingleShot(true); @@ -73,7 +74,7 @@ MainWindow::MainWindow(QWidget *parent) m_processEndTimer->start(); //在构造函数中存储m_displayInter->monitor()中的内容,解决内存泄漏的问题 - if(m_displayInter->isValid()){ + if (m_displayInter->isValid()) { auto ss = m_displayInter->property("Monitors"); QDBusInterface busInterface(common::systemInfo().DISPLAY_SERVICE, @@ -101,7 +102,6 @@ MainWindow::MainWindow(QWidget *parent) MainWindow::~MainWindow() { - } void MainWindow::Toggle() @@ -147,7 +147,7 @@ void MainWindow::showAni() if (!m_hasComposite) { int dockPos = DOCK_TOP; int displayMode = 0; - if(m_daemonDockInter->isValid()){ + if (m_daemonDockInter->isValid()) { dockPos = m_daemonDockInter->property("Position").toInt(); displayMode = m_daemonDockInter->property("DisplayMode").toInt(); } @@ -193,7 +193,7 @@ void MainWindow::hideAni() m_aniGroup->setDirection(QAbstractAnimation::Forward); m_aniGroup->start(); - QTimer::singleShot(m_aniGroup->duration(), this, [ = ] {setVisible(false);}); + QTimer::singleShot(m_aniGroup->duration(), this, [=] { setVisible(false); }); } void MainWindow::startLoader() @@ -256,7 +256,7 @@ void MainWindow::registerMonitor() } m_regionMonitor = new DRegionMonitor(this); m_regionMonitor->registerRegion(QRegion(QRect())); - connect(m_regionMonitor, &DRegionMonitor::buttonPress, this, [ = ](const QPoint & p, const int flag) { + connect(m_regionMonitor, &DRegionMonitor::buttonPress, this, [=](const QPoint &p, const int flag) { Q_UNUSED(flag); if (!geometry().contains(p)) if (!isHidden()) { @@ -267,7 +267,7 @@ void MainWindow::registerMonitor() void MainWindow::initUI() { - setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint); + setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint); setAttribute(Qt::WA_TranslucentBackground); setFixedWidth(Globals::WindowWidth); @@ -331,7 +331,7 @@ void MainWindow::initAni() void MainWindow::initConnect() { - QDBusConnection::sessionBus().connect(m_displayInter->service(),m_displayInter->path(),"org.freedesktop.DBus.Properties","PropertiesChanged",this,SLOT(dbusPropertiesChanged(QString,QVariantMap,QStringList))); + QDBusConnection::sessionBus().connect(m_displayInter->service(), m_displayInter->path(), "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dbusPropertiesChanged(QString, QVariantMap, QStringList))); connect(m_dockInter, &DBusDockInterface::geometryChanged, this, &MainWindow::geometryChanged, Qt::UniqueConnection); connect(this, SIGNAL(signal_geometry(int)), m_processWidget, SLOT(autoHeight(int))); @@ -344,38 +344,37 @@ void MainWindow::initConnect() connect(DWindowManagerHelper::instance(), &DWindowManagerHelper::hasCompositeChanged, this, &MainWindow::CompositeChanged, Qt::QueuedConnection); - connect(m_widthAni, &QVariantAnimation::valueChanged, this, [ = ](const QVariant & value) { + connect(m_widthAni, &QVariantAnimation::valueChanged, this, [=](const QVariant &value) { int width = value.toInt(); -// move(int(std::round(qreal(m_rect.x() + m_rect.width() + Globals::WindowMargin - width)) / qApp->primaryScreen()->devicePixelRatio()), m_rect.y()); - move(int(std::round(qreal(m_rect.x() + m_rect.width() + Globals::WindowMargin - width))), m_rect.y()); + // move(int(std::round(qreal(m_rect.x() + m_rect.width() + Globals::WindowMargin - width)) / qApp->primaryScreen()->devicePixelRatio()), m_rect.y()); + move(int(std::round(qreal(m_rect.x() + m_rect.width() + Globals::WindowMargin - width))), m_rect.y()); }); QDBusServiceWatcher *m_watcher = new QDBusServiceWatcher(common::systemInfo().MONITOR_SERVICE, QDBusConnection::sessionBus()); - connect(m_watcher, &QDBusServiceWatcher::serviceRegistered, this, [ = ](const QString & service) { + connect(m_watcher, &QDBusServiceWatcher::serviceRegistered, this, [=](const QString &service) { if (common::systemInfo().MONITOR_SERVICE != service) return; registerMonitor(); }); - connect(m_watcher, &QDBusServiceWatcher::serviceUnregistered, this, [ = ](const QString & service) { + connect(m_watcher, &QDBusServiceWatcher::serviceUnregistered, this, [=](const QString &service) { if (common::systemInfo().MONITOR_SERVICE != service) return; disconnect(m_regionMonitor); }); // 设置窗口透明度调节 - QDBusConnection::sessionBus().connect(m_daemonDockInter->service(),m_daemonDockInter->path(),"org.freedesktop.DBus.Properties","PropertiesChanged",this,SLOT(dbusPropertiesChanged(QString,QVariantMap,QStringList))); + QDBusConnection::sessionBus().connect(m_daemonDockInter->service(), m_daemonDockInter->path(), "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dbusPropertiesChanged(QString, QVariantMap, QStringList))); // 去除通过智能语音助手唤醒时关闭系统监视器窗口 -// connect(DBusAyatanaInterface::getInstance(), &DBusAyatanaInterface::sigSendCloseWidget, this, [=]() { QTimer::singleShot(0, this, &MainWindow::hideAni); }); + // connect(DBusAyatanaInterface::getInstance(), &DBusAyatanaInterface::sigSendCloseWidget, this, [=]() { QTimer::singleShot(0, this, &MainWindow::hideAni); }); //5分钟没人使用,结束popup进程 connect(m_processEndTimer, &QTimer::timeout, this, []() { - qInfo() << "time is up! end process!"; + qCInfo(app) << "time is up! end process!"; QProcess::startDetached(KILL_DBUS_COMMAND); }); - } void MainWindow::changeTheme(DApplicationHelper::ColorType themeType) @@ -405,10 +404,9 @@ void MainWindow::changeTheme(DApplicationHelper::ColorType themeType) void MainWindow::dbusPropertiesChanged(QString interface, QVariantMap maps, QStringList strs) { - if((interface == common::systemInfo().DISPLAY_INTERFACE && maps.contains("PrimaryRect")) || - (interface == common::systemInfo().DOCK_INTERFACE && (maps.contains("Position") || maps.contains("DisplayMode")))){ + if ((interface == common::systemInfo().DISPLAY_INTERFACE && maps.contains("PrimaryRect")) || (interface == common::systemInfo().DOCK_INTERFACE && (maps.contains("Position") || maps.contains("DisplayMode")))) { geometryChanged(); - } else if(m_daemonDockInter->isValid() && interface == common::systemInfo().DOCK_INTERFACE && maps.contains("Opacity")){ + } else if (m_daemonDockInter->isValid() && interface == common::systemInfo().DOCK_INTERFACE && maps.contains("Opacity")) { this->setMaskAlpha(static_cast(m_daemonDockInter->property("Opacity").toDouble() * 255)); } } @@ -431,7 +429,7 @@ void MainWindow::adjustPosition() rect -= QMargins(0, Globals::WindowMargin, Globals::WindowMargin, Globals::WindowMargin); // 初始化弹出框位置 - if(m_daemonDockInter->isValid()){ + if (m_daemonDockInter->isValid()) { int dockPos = m_daemonDockInter->property("Position").toInt(); int displayMode = m_daemonDockInter->property("DisplayMode").toInt(); switch (dockPos) { @@ -475,7 +473,7 @@ void MainWindow::adjustPosition() // 针对时尚模式的特殊处理 // 只有任务栏显示的时候, 才额外偏移 - if(m_daemonDockInter->isValid()){ + if (m_daemonDockInter->isValid()) { int dockPos = m_daemonDockInter->property("Position").toInt(); int displayMode = m_daemonDockInter->property("DisplayMode").toInt(); if (displayMode == 0 && dockRect.width() * dockRect.height() > 0) { @@ -520,8 +518,8 @@ QRect MainWindow::getDisplayScreen() { QRect dockRect = m_dockInter->geometry(); for (const auto &monitorPath : m_dbusPathList) { - QDBusInterface monitor(common::systemInfo().DISPLAY_INTERFACE, monitorPath.path(), common::systemInfo().DISPLAYMONITOR_INTERFACE,QDBusConnection::sessionBus()); - if(monitor.isValid()){ + QDBusInterface monitor(common::systemInfo().DISPLAY_INTERFACE, monitorPath.path(), common::systemInfo().DISPLAYMONITOR_INTERFACE, QDBusConnection::sessionBus()); + if (monitor.isValid()) { int curX = m_displayInter->property("X").toInt(); int curY = m_displayInter->property("X").toInt(); int curWidth = m_displayInter->property("X").toInt(); @@ -531,7 +529,7 @@ QRect MainWindow::getDisplayScreen() return screenRect; } } - if(m_displayInter->isValid()){ + if (m_displayInter->isValid()) { QDBusInterface busInterface(common::systemInfo().DISPLAY_SERVICE, common::systemInfo().DISPLAY_PATH, "org.freedesktop.DBus.Properties", QDBusConnection::sessionBus()); QDBusMessage reply = busInterface.call("Get", common::systemInfo().DISPLAY_INTERFACE, "PrimaryRect"); @@ -542,7 +540,7 @@ QRect MainWindow::getDisplayScreen() while (!argument.atEnd()) { argument >> primaryRect; } - return QRect(primaryRect.x,primaryRect.y,primaryRect.width,primaryRect.height); + return QRect(primaryRect.x, primaryRect.y, primaryRect.width, primaryRect.height); } return dockRect; } @@ -560,9 +558,8 @@ bool MainWindow::initDBus() } // 在挂载的服务上注册一个执行服务的对象 - if (!QDBusConnection::sessionBus().registerObject(Globals::SERVICE_PATH, m_systemMonitorDbusAdaptor, QDBusConnection::ExportAllSlots | - QDBusConnection::ExportAllSignals)) { - qInfo() << QDBusConnection::sessionBus().lastError(); + if (!QDBusConnection::sessionBus().registerObject(Globals::SERVICE_PATH, m_systemMonitorDbusAdaptor, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) { + qCInfo(app) << QDBusConnection::sessionBus().lastError(); return false; } @@ -610,4 +607,3 @@ void MainWindow::hideEvent(QHideEvent *event) Q_EMIT sysMonPopVisibleChanged(false); QWidget::hideEvent(event); } - diff --git a/deepin-system-monitor-plugin-popup/gui/memory_widget.cpp b/deepin-system-monitor-plugin-popup/gui/memory_widget.cpp index 148bf705..e083a818 100644 --- a/deepin-system-monitor-plugin-popup/gui/memory_widget.cpp +++ b/deepin-system-monitor-plugin-popup/gui/memory_widget.cpp @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later - +#include "ddlog.h" #include "memory_widget.h" #include "../common/utils.h" #include "common/datacommon.h" @@ -27,7 +27,7 @@ DWIDGET_USE_NAMESPACE using namespace Utils; - +using namespace DDLog; MemoryWidget::MemoryWidget(QWidget *parent) : QWidget(parent) { @@ -49,25 +49,22 @@ MemoryWidget::MemoryWidget(QWidget *parent) } MemoryWidget::~MemoryWidget() {} - void MemoryWidget::updateStatus() { QString memUsage, memTotal, memPercent, swapUsage, swapTotal, swapPercent; if (!DataDealSingleton::getInstance().readMemInfo(memUsage, memTotal, memPercent, swapUsage, swapTotal, swapPercent)) - qInfo()<<"failed"; -// qInfo()<<"swapUsage: "< +#include + +#include +using namespace DDLog; +DCORE_USE_NAMESPACE + +MLogger::MLogger(QObject *parent) + : QObject(parent), m_rules(""), m_config(nullptr) +{ + QByteArray logRules = qgetenv("QT_LOGGING_RULES"); + // qunsetenv 之前一定不要有任何日志打印,否则取消环境变量设置不会生效 + qunsetenv("QT_LOGGING_RULES"); + + // set env + m_rules = logRules; + + // set dconfig + m_config = DConfig::create("deepin-system-monitor-plugin-popup", "deepin-system-monitor-plugin-popup"); + logRules = m_config->value("log_rules").toByteArray(); + appendRules(logRules); + setRules(m_rules); + + // watch dconfig + connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) { + qCCritical(app) << "value changed:" << key; + if (key == "log_rules") { + setRules(m_config->value(key).toByteArray()); + } + }); +} + +MLogger::~MLogger() +{ + m_config->deleteLater(); +} + +void MLogger::setRules(const QString &rules) +{ + auto tmpRules = rules; + m_rules = tmpRules.replace(";", "\n"); + QLoggingCategory::setFilterRules(m_rules); +} + +void MLogger::appendRules(const QString &rules) +{ + QString tmpRules = rules; + tmpRules = tmpRules.replace(";", "\n"); + auto tmplist = tmpRules.split('\n'); + for (int i = 0; i < tmplist.count(); i++) + if (m_rules.contains(tmplist.at(i))) { + tmplist.removeAt(i); + i--; + } + if (tmplist.isEmpty()) + return; + m_rules.isEmpty() ? m_rules = tmplist.join("\n") + : m_rules += "\n" + tmplist.join("\n"); +} diff --git a/deepin-system-monitor-plugin-popup/logger.h b/deepin-system-monitor-plugin-popup/logger.h new file mode 100644 index 00000000..946fa7a3 --- /dev/null +++ b/deepin-system-monitor-plugin-popup/logger.h @@ -0,0 +1,28 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include + +DCORE_BEGIN_NAMESPACE +class DConfig; +DCORE_END_NAMESPACE + +class MLogger : public QObject +{ + Q_OBJECT +public: + explicit MLogger(QObject *parent = nullptr); + ~MLogger(); + + inline QString rules() const { return m_rules; } + void setRules(const QString &rules); + +private: + void appendRules(const QString &rules); + +private: + QString m_rules; + Dtk::Core::DConfig *m_config; +}; diff --git a/deepin-system-monitor-plugin-popup/main.cpp b/deepin-system-monitor-plugin-popup/main.cpp index 291d6ffb..b0729f39 100644 --- a/deepin-system-monitor-plugin-popup/main.cpp +++ b/deepin-system-monitor-plugin-popup/main.cpp @@ -6,23 +6,39 @@ #include "gui/mainwindow.h" #include "dde-dock/constants.h" #include "application.h" +#include "ddlog.h" //#include "clipboard_adaptor.h" - +#include "logger.h" #include #include #include #include #include - - DGUI_USE_NAMESPACE DWIDGET_USE_NAMESPACE DCORE_USE_NAMESPACE +using namespace DDLog; + int main(int argc, char *argv[]) { +#ifdef DTKCORE_CLASS_DConfigFile + MLogger(); // 日志处理要放在app之前,否则QApplication + // 内部可能进行了日志打印,导致环境变量设置不生效 +#endif + +// 为了兼容性 +#if (DTK_VERSION >= DTK_VERSION_CHECK(5, 6, 8, 0)) + Dtk::Core::DLogManager::registerJournalAppender(); +#else + Dtk::Core::DLogManager::registerFileAppender(); +#endif +#ifdef QT_DEBUG + Dtk::Core::DLogManager::registerConsoleAppender(); +#endif + // 前置wayland环境变量 if (!qgetenv("WAYLAND_DISPLAY").isEmpty()) { qputenv("QT_QPA_PLATFORM", "wayland"); @@ -32,7 +48,7 @@ int main(int argc, char *argv[]) DGuiApplicationHelper::setUseInactiveColorGroup(false); DGuiApplicationHelper::setColorCompositingEnabled(true); -// DApplication *app = DApplication::globalApplication(argc, argv); + // DApplication *app = DApplication::globalApplication(argc, argv); Application::setAttribute(Qt::AA_UseHighDpiPixmaps, true); Application ac(argc, argv); @@ -43,9 +59,8 @@ int main(int argc, char *argv[]) ac.setApplicationDisplayName("deepin-system-monitor-plugin-popup"); ac.setApplicationVersion("1.0"); - if (!DGuiApplicationHelper::setSingleInstance(QString("deepin-system-monitor-plugin-popup"))) { - qDebug() << "set single instance failed!"; + qCDebug(app) << "set single instance failed!"; return -1; } @@ -55,10 +70,10 @@ int main(int argc, char *argv[]) gApp->setMainWindow(&w); QDBusInterface interface("com.deepin.SystemMonitorPluginPopup", "/com/deepin/SystemMonitorPluginPopup", - "com.deepin.SystemMonitorPluginPopup", - QDBusConnection::sessionBus()); + "com.deepin.SystemMonitorPluginPopup", + QDBusConnection::sessionBus()); if (!interface.isValid()) { - qDebug() << "start loader..."; + qCDebug(app) << "start loader..."; w.startLoader(); } #ifdef QT_DEBUG diff --git a/deepin-system-monitor-plugin-popup/process/process_db.cpp b/deepin-system-monitor-plugin-popup/process/process_db.cpp index eb56e63b..8a3e021f 100644 --- a/deepin-system-monitor-plugin-popup/process/process_db.cpp +++ b/deepin-system-monitor-plugin-popup/process/process_db.cpp @@ -148,7 +148,7 @@ void ProcessDB::sendSignalToProcess(pid_t pid, int signal) } else if (signal == SIGKILL) { Q_EMIT processKilled(pid); } else { - qWarning() << "Unexpected signal in this case:" << signal; + qCWarning(app) << "Unexpected signal in this case:" << signal; } }; auto fmsg = [ = ](int signal) -> QString { diff --git a/deepin-system-monitor-plugin/CMakeLists.txt b/deepin-system-monitor-plugin/CMakeLists.txt index 1fab2de1..3f814dbe 100644 --- a/deepin-system-monitor-plugin/CMakeLists.txt +++ b/deepin-system-monitor-plugin/CMakeLists.txt @@ -76,4 +76,3 @@ INSTALL(FILES com.deepin.dde.dock.module.system-monitor.gschema.xml DESTINATION INSTALL(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION lib/dde-dock/plugins) #安装翻译文件 install(FILES ${APP_QM_FILES} DESTINATION ${CMAKE_INSTALL_DATADIR}/deepin-system-monitor-plugin/translations) - diff --git a/deepin-system-monitor-plugin/ddlog.h b/deepin-system-monitor-plugin/ddlog.h new file mode 100644 index 00000000..b4de84c3 --- /dev/null +++ b/deepin-system-monitor-plugin/ddlog.h @@ -0,0 +1,15 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef DDLOG_H +#define DDLOG_H +#include +#include +DCORE_USE_NAMESPACE + +namespace DDLog { +inline Q_LOGGING_CATEGORY(app, "org.deepin.system-monitor.plugin") +} + +#endif // DDLOG_H diff --git a/deepin-system-monitor-plugin/gui/monitor_plugin.cpp b/deepin-system-monitor-plugin/gui/monitor_plugin.cpp index 77dd3b14..791c6e87 100644 --- a/deepin-system-monitor-plugin/gui/monitor_plugin.cpp +++ b/deepin-system-monitor-plugin/gui/monitor_plugin.cpp @@ -5,7 +5,7 @@ #include "monitor_plugin.h" #include "helper.hpp" - +#include "ddlog.h" // Qt #include #include @@ -23,19 +23,17 @@ const QString PLUGIN_STATE_KEY = "enable"; } DWIDGET_USE_NAMESPACE - +using namespace DDLog; MonitorPlugin::MonitorPlugin(QObject *parent) - : QObject(parent) - , m_pluginLoaded(false) - , m_dataTipsLabel(nullptr) - , m_refershTimer(new QTimer(this)) + : QObject(parent), m_pluginLoaded(false), m_dataTipsLabel(nullptr), m_refershTimer(new QTimer(this)) #ifdef USE_API_QUICKPANEL20 - , m_quickPanelWidget(new QuickPanelWidget) - ,m_messageCallback(nullptr) + , + m_quickPanelWidget(new QuickPanelWidget), + m_messageCallback(nullptr) #endif { connect(m_refershTimer, &QTimer::timeout, this, &MonitorPlugin::udpateTipsInfo); - qInfo() <<__FUNCTION__ << __LINE__ << "[-MonitorPlugin-]" ; + qCInfo(app) << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-]"; } const QString MonitorPlugin::pluginName() const @@ -67,32 +65,32 @@ void MonitorPlugin::init(PluginProxyInterface *proxyInter) m_proxyInter->itemAdded(this, pluginName()); m_quickPanelWidget->setDescription(pluginDisplayName()); QString plugIcon = DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::LightType ? "status-system-monitor-dark" : "status-system-monitor"; - QIcon fallbackIcon = QIcon::fromTheme(DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::LightType? "dsm_pluginicon_dark" : "dsm_pluginicon_light"); + QIcon fallbackIcon = QIcon::fromTheme(DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::LightType ? "dsm_pluginicon_dark" : "dsm_pluginicon_light"); m_quickPanelWidget->setIcon(QIcon::fromTheme(plugIcon, fallbackIcon)); - connect(m_quickPanelWidget,&QuickPanelWidget::clicked,this,&MonitorPlugin::onClickQuickPanel); - qInfo() << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] QUICKPANEL20"; + connect(m_quickPanelWidget, &QuickPanelWidget::clicked, this, &MonitorPlugin::onClickQuickPanel); + qCInfo(app) << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] QUICKPANEL20"; QDBusConnection::sessionBus().connect("com.deepin.SystemMonitorPluginPopup", "/com/deepin/SystemMonitorPluginPopup", "com.deepin.SystemMonitorPluginPopup", "sysMonPopVisibleChanged", this, SLOT(onSysMonPopVisibleChanged(bool))); #endif calcCpuRate(m_totalCPU, m_availableCPU); calcNetRate(m_down, m_upload); #ifdef DDE_DOCK_NEW_VERSION - qInfo() << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] V23"; + qCInfo(app) << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] V23"; #endif } QWidget *MonitorPlugin::itemWidget(const QString &itemKey) { - qInfo() << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-]" << itemKey; + qCInfo(app) << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-]" << itemKey; #ifdef DDE_DOCK_NEW_VERSION // if (itemKey == "system-monitor") // return m_itemWidget; #else -#ifdef USE_API_QUICKPANEL20 +# ifdef USE_API_QUICKPANEL20 if (itemKey == Dock::QUICK_ITEM_KEY) { return m_quickPanelWidget; } -#endif +# endif if (itemKey == "system-monitor") return m_itemWidget; #endif @@ -119,11 +117,11 @@ void MonitorPlugin::pluginStateSwitched() #ifndef DDE_DOCK_NEW_VERSION bool MonitorPlugin::pluginIsDisable() { -#ifdef USE_API_QUICKPANEL20 +# ifdef USE_API_QUICKPANEL20 return false; -#else +# else return m_proxyInter->getValue(this, "disabled", true).toBool(); -#endif +# endif } #endif @@ -143,7 +141,7 @@ const QString MonitorPlugin::itemCommand(const QString &itemKey) } return ""; -// return "dbus-send --print-reply --dest=com.deepin.SystemMonitorPluginPopup /com/deepin/SystemMonitorPluginPopup com.deepin.SystemMonitorPluginPopup.showOrHideDeepinSystemMonitorPluginPopupWidget"; + // return "dbus-send --print-reply --dest=com.deepin.SystemMonitorPluginPopup /com/deepin/SystemMonitorPluginPopup com.deepin.SystemMonitorPluginPopup.showOrHideDeepinSystemMonitorPluginPopupWidget"; } void MonitorPlugin::displayModeChanged(const Dock::DisplayMode displayMode) @@ -209,11 +207,11 @@ QIcon MonitorPlugin::icon(const DockPart &dockPart, DGuiApplicationHelper::Color // 最小尺寸时,不画背景,采用深色图标 iconName = "dsm_pluginicon_dark"; } - QSize size = QSize(16,16); + QSize size = QSize(16, 16); if (dockPart == DockPart::DCCSetting) { - size = QSize(20,20); + size = QSize(20, 20); } else if (dockPart == DockPart::QuickPanel) { - size = QSize(24,24); + size = QSize(24, 24); } QIcon icon = QIcon::fromTheme(iconName); if (!icon.isNull()) { @@ -222,14 +220,14 @@ QIcon MonitorPlugin::icon(const DockPart &dockPart, DGuiApplicationHelper::Color QPixmap pixmap = icon.pixmap(pixmapSize); pixmap.setDevicePixelRatio(ratio); if (dockPart == DockPart::QuickShow) { - QPixmap curPixmap(size*ratio); + QPixmap curPixmap(size * ratio); pixmap.setDevicePixelRatio(ratio); curPixmap.fill(Qt::transparent); QPainter painter; painter.begin(&curPixmap); painter.setRenderHint(QPainter::SmoothPixmapTransform); - int pixmapMargin = ceil(1*ratio); - painter.drawPixmap(QRect(pixmapMargin, pixmapMargin, curPixmap.width()-pixmapMargin, curPixmap.height()-pixmapMargin), pixmap); + int pixmapMargin = ceil(1 * ratio); + painter.drawPixmap(QRect(pixmapMargin, pixmapMargin, curPixmap.width() - pixmapMargin, curPixmap.height() - pixmapMargin), pixmap); painter.end(); return QIcon(curPixmap); } else { @@ -297,14 +295,17 @@ void MonitorPlugin::loadPlugin() m_dataTipsLabel->setObjectName("systemmonitorpluginlabel"); m_refershTimer->setInterval(1000); -// m_refershTimer->start(); + // m_refershTimer->start(); - connect(m_dataTipsLabel.get(),&SystemMonitorTipsWidget::visibleChanged,this,[=](bool visible){ + connect(m_dataTipsLabel.get(), &SystemMonitorTipsWidget::visibleChanged, this, [=](bool visible) { if (!visible) { m_refershTimer->stop(); } else { udpateInfo(); - m_dataTipsLabel->setSystemMonitorTipsText(QStringList() << "..." << "..." << "..." << "..."); + m_dataTipsLabel->setSystemMonitorTipsText(QStringList() << "..." + << "..." + << "..." + << "..."); m_refershTimer->start(); } }); @@ -346,7 +347,7 @@ void MonitorPlugin::calcMemRate(qlonglong &memory, qlonglong &memoryAll) return; QTextStream stream(&file); - qlonglong buff[16] = {0}; + qlonglong buff[16] = { 0 }; for (int i = 0; i <= 15; ++i) { QString line = stream.readLine(); QStringList list = line.split(QRegExp("\\s{1,}")); @@ -375,7 +376,7 @@ void MonitorPlugin::calcNetRate(qlonglong &netDown, qlonglong &netUpload) line = stream.readLine(); while (!line.isNull()) { line = line.trimmed(); - QStringList list = line.split(QRegExp("\\s{1,}")); // match number >= 1 space character + QStringList list = line.split(QRegExp("\\s{1,}")); // match number >= 1 space character if (!list.isEmpty()) { down = list.at(1).toLongLong(); @@ -443,7 +444,7 @@ double MonitorPlugin::autoRateUnits(qlonglong speed, RateUnit &unit) sp = static_cast(speed / qPow(2, 40) * 1.0); } else { unit = RateUnknow; - qDebug() << "本设备网络速率单位传输超过 TB, 或者低于 0 Byte."; + qCDebug(app) << "本设备网络速率单位传输超过 TB, 或者低于 0 Byte."; sp = -1; } @@ -456,9 +457,9 @@ void MonitorPlugin::openSystemMonitor() //QString cmd("qdbus com.deepin.SystemMonitorMain /com/deepin/SystemMonitorMain com.deepin.SystemMonitorMain.slotRaiseWindow"); QString cmd("gdbus call -e -d com.deepin.SystemMonitorMain -o /com/deepin/SystemMonitorMain -m com.deepin.SystemMonitorMain.slotRaiseWindow"); - QTimer::singleShot(200, this, [ = ]() { QProcess::startDetached(cmd); }); + QTimer::singleShot(200, this, [=]() { QProcess::startDetached(cmd); }); #ifdef USE_API_QUICKPANEL20 - qInfo() << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] right ClickQuickPanel"; + qCInfo(app) << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] right ClickQuickPanel"; m_proxyInter->requestSetAppletVisible(this, pluginName(), false); #endif } @@ -474,7 +475,7 @@ MonitorPlugin::~MonitorPlugin() void MonitorPlugin::onClickQuickPanel() { - qInfo() << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] ClickQuickPanel"; + qCInfo(app) << __FUNCTION__ << __LINE__ << "[-MonitorPlugin-] ClickQuickPanel"; m_proxyInter->requestSetAppletVisible(this, pluginName(), false); // Task 30767: 暂时调整为打开系统监视器,隐藏系统监视器插件 @@ -483,9 +484,10 @@ void MonitorPlugin::onClickQuickPanel() } //系统监视器弹窗显示状态改变 -void MonitorPlugin::onSysMonPopVisibleChanged(bool visible){ +void MonitorPlugin::onSysMonPopVisibleChanged(bool visible) +{ if (!m_messageCallback) { - qWarning() << "Message callback function is nullptr"; + qCWarning(app) << "Message callback function is nullptr"; return; } QJsonObject msg; diff --git a/deepin-system-monitor-plugin/gui/systemmonitortipswidget.cpp b/deepin-system-monitor-plugin/gui/systemmonitortipswidget.cpp index 51228638..1414c439 100644 --- a/deepin-system-monitor-plugin/gui/systemmonitortipswidget.cpp +++ b/deepin-system-monitor-plugin/gui/systemmonitortipswidget.cpp @@ -4,14 +4,14 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "systemmonitortipswidget.h" - +#include "ddlog.h" #include #include #include #include DWIDGET_USE_NAMESPACE - +using namespace DDLog; SystemMonitorTipsWidget::SystemMonitorTipsWidget(QWidget *parent) : QFrame(parent) { @@ -19,7 +19,7 @@ SystemMonitorTipsWidget::SystemMonitorTipsWidget(QWidget *parent) void SystemMonitorTipsWidget::setSystemMonitorTipsText(QStringList strList) { - m_textList = strList; + m_textList = strList; // [ CPU: 100.0% ↓ 1000kb/s ] // 获取strList字符串,并存入cpu,mem,upLoad,download中 @@ -37,7 +37,7 @@ void SystemMonitorTipsWidget::setSystemMonitorTipsText(QStringList strList) else if (i == 3) upLoad = m_textList.at(i); else - qDebug() << "do not set the text"; + qCDebug(app) << "do not set the text"; } // 设置左侧字符串宽度 @@ -62,13 +62,11 @@ void SystemMonitorTipsWidget::setSystemMonitorTipsText(QStringList strList) // 设置右侧字符串宽度预留20个像素 m_rightWidth += 20; - // 设置当前窗体固定大小 setFixedSize(5 + 5 + m_leftWidth + m_rightWidth, fontMetrics().boundingRect(m_textList.at(0)).height() * 2 + 20); update(); } - void SystemMonitorTipsWidget::paintEvent(QPaintEvent *event) { QFrame::paintEvent(event); @@ -99,7 +97,7 @@ void SystemMonitorTipsWidget::paintEvent(QPaintEvent *event) else if (i == 3) upLoad = m_textList.at(i); else - qDebug() << "do not set the text"; + qCDebug(app) << "do not set the text"; } // 当没有数据更新时,设置默认的悬浮框内容 @@ -110,7 +108,7 @@ void SystemMonitorTipsWidget::paintEvent(QPaintEvent *event) downLoad = "0KB/s"; } -// int specialCharaWidth = fontMetrics().width(QString("↓")); + // int specialCharaWidth = fontMetrics().width(QString("↓")); int specialCharaWidth = 10; int specialCharaHeight = fontMetrics().width(QString("1")) + 5; @@ -127,7 +125,6 @@ void SystemMonitorTipsWidget::paintEvent(QPaintEvent *event) // 绘制CPU文字信息 painter.drawText(QRectF(leftMargin, 0.0, m_leftWidth, rectHeight / 2.0), QString(" ") + DApplication::translate("Plugin.cpu", "CPU") + QString(": ") + cpu, optionLeft); - // 绘制下箭头 painter.save(); painter.setPen(QPen(palette().brightText(), 2)); @@ -139,11 +136,11 @@ void SystemMonitorTipsWidget::paintEvent(QPaintEvent *event) painter.drawLines(vecDown); painter.restore(); -// painter.drawText(QRectF(m_leftWidth, 0.0, specialCharaWidth, rectHeight / 2.0), QString("↓"), optionMid); + // painter.drawText(QRectF(m_leftWidth, 0.0, specialCharaWidth, rectHeight / 2.0), QString("↓"), optionMid); // 绘值下载文字信息 painter.drawText(QRectF(leftMargin + m_leftWidth + specialCharaWidth + 5, 0, m_rightWidth, rectHeight / 2.0), downLoad, optionLeft); -// specialCharaWidth = fontMetrics().width(QString("↑")); + // specialCharaWidth = fontMetrics().width(QString("↑")); // 绘制左侧空白矩形区域 painter.save(); painter.setPen(QColor(Qt::transparent)); @@ -159,10 +156,10 @@ void SystemMonitorTipsWidget::paintEvent(QPaintEvent *event) QVector vecUp; vecUp.append(QLineF(QPointF(leftMargin + m_leftWidth, rectHeight / 2.0 + rectHeight / 4.0), QPointF(leftMargin + m_leftWidth + specialCharaWidth / 2, rectHeight / 2.0 + rectHeight / 4.0 - specialCharaHeight / 2.0))); vecUp.append(QLineF(QPointF(leftMargin + m_leftWidth + specialCharaWidth / 2, rectHeight / 2.0 + rectHeight / 4.0 - specialCharaHeight / 2.0), QPointF(leftMargin + m_leftWidth + specialCharaWidth, rectHeight / 2.0 + rectHeight / 4.0))); - vecUp.append(QLineF(QPointF(leftMargin + m_leftWidth + specialCharaWidth / 2, rectHeight / 2.0 + rectHeight / 4.0 - specialCharaHeight / 2.0), QPointF(leftMargin + m_leftWidth + specialCharaWidth / 2,rectHeight / 2.0 + rectHeight / 4.0 + specialCharaHeight / 2.0))); + vecUp.append(QLineF(QPointF(leftMargin + m_leftWidth + specialCharaWidth / 2, rectHeight / 2.0 + rectHeight / 4.0 - specialCharaHeight / 2.0), QPointF(leftMargin + m_leftWidth + specialCharaWidth / 2, rectHeight / 2.0 + rectHeight / 4.0 + specialCharaHeight / 2.0))); painter.drawLines(vecUp); painter.restore(); -// painter.drawText(QRectF(m_leftWidth, rectHeight / 2.0, specialCharaWidth, rectHeight / 2.0), QString("↑"), optionMid); + // painter.drawText(QRectF(m_leftWidth, rectHeight / 2.0, specialCharaWidth, rectHeight / 2.0), QString("↑"), optionMid); // 绘制上传文字信息 painter.setPen(QPen(palette().brightText(), 1)); @@ -176,7 +173,10 @@ bool SystemMonitorTipsWidget::event(QEvent *event) if (m_textList.size() > 0) setSystemMonitorTipsText(m_textList); else - setSystemMonitorTipsText(QStringList() << "0.0" << "0.0" << "0KB/s" << "0KB/s"); + setSystemMonitorTipsText(QStringList() << "0.0" + << "0.0" + << "0KB/s" + << "0KB/s"); } else if (event->type() == QEvent::Hide) { Q_EMIT visibleChanged(false); } else if (event->type() == QEvent::Show) { diff --git a/deepin-system-monitor-plugin/logger.cpp b/deepin-system-monitor-plugin/logger.cpp new file mode 100644 index 00000000..9a06baf6 --- /dev/null +++ b/deepin-system-monitor-plugin/logger.cpp @@ -0,0 +1,67 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include "logger.h" +#include "dtkcore_global.h" +#include "qglobal.h" +#include "ddlog.h" +#include +#include + +#include +using namespace DDLog; +DCORE_USE_NAMESPACE + +MLogger::MLogger(QObject *parent) + : QObject(parent), m_rules(""), m_config(nullptr) +{ + QByteArray logRules = qgetenv("QT_LOGGING_RULES"); + // qunsetenv 之前一定不要有任何日志打印,否则取消环境变量设置不会生效 + qunsetenv("QT_LOGGING_RULES"); + + // set env + m_rules = logRules; + + // set dconfig + m_config = DConfig::create("org.deepin.system-monitor", "org.deepin.system-monitor.plugin"); + logRules = m_config->value("log_rules").toByteArray(); + appendRules(logRules); + setRules(m_rules); + + // watch dconfig + connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) { + qCCritical(app) << "value changed:" << key; + if (key == "log_rules") { + setRules(m_config->value(key).toByteArray()); + } + }); +} + +MLogger::~MLogger() +{ + m_config->deleteLater(); +} + +void MLogger::setRules(const QString &rules) +{ + auto tmpRules = rules; + m_rules = tmpRules.replace(";", "\n"); + QLoggingCategory::setFilterRules(m_rules); +} + +void MLogger::appendRules(const QString &rules) +{ + QString tmpRules = rules; + tmpRules = tmpRules.replace(";", "\n"); + auto tmplist = tmpRules.split('\n'); + for (int i = 0; i < tmplist.count(); i++) + if (m_rules.contains(tmplist.at(i))) { + tmplist.removeAt(i); + i--; + } + if (tmplist.isEmpty()) + return; + m_rules.isEmpty() ? m_rules = tmplist.join("\n") + : m_rules += "\n" + tmplist.join("\n"); +} diff --git a/deepin-system-monitor-plugin/logger.h b/deepin-system-monitor-plugin/logger.h new file mode 100644 index 00000000..946fa7a3 --- /dev/null +++ b/deepin-system-monitor-plugin/logger.h @@ -0,0 +1,28 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include + +DCORE_BEGIN_NAMESPACE +class DConfig; +DCORE_END_NAMESPACE + +class MLogger : public QObject +{ + Q_OBJECT +public: + explicit MLogger(QObject *parent = nullptr); + ~MLogger(); + + inline QString rules() const { return m_rules; } + void setRules(const QString &rules); + +private: + void appendRules(const QString &rules); + +private: + QString m_rules; + Dtk::Core::DConfig *m_config; +}; diff --git a/deepin-system-monitor-server/CMakeLists.txt b/deepin-system-monitor-server/CMakeLists.txt index a50b9be0..51ddfc83 100644 --- a/deepin-system-monitor-server/CMakeLists.txt +++ b/deepin-system-monitor-server/CMakeLists.txt @@ -32,20 +32,24 @@ file(GLOB_RECURSE SRC_CPP ${CMAKE_CURRENT_LIST_DIR}/src/*.cpp) file(GLOB_RECURSE SRC_H ${CMAKE_CURRENT_LIST_DIR}/src/*.h) find_package(Qt5 COMPONENTS Core DBus REQUIRED) +find_package(Dtk REQUIRED COMPONENTS Core) add_executable(${BIN_NAME} ${SRC_CPP} ${SRC_H} + src ) target_include_directories(${BIN_NAME} PUBLIC Qt5::Core Qt5::DBus + Dtk::Core ) target_link_libraries(${BIN_NAME} PRIVATE Qt5::Core Qt5::DBus + Dtk::Core ) install(TARGETS ${BIN_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR}) diff --git a/deepin-system-monitor-server/src/ddlog.h b/deepin-system-monitor-server/src/ddlog.h new file mode 100644 index 00000000..9f1f5230 --- /dev/null +++ b/deepin-system-monitor-server/src/ddlog.h @@ -0,0 +1,15 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef DDLOG_H +#define DDLOG_H +#include +#include +DCORE_USE_NAMESPACE + +namespace DDLog { +inline Q_LOGGING_CATEGORY(app, "org.deepin.system-monitor.server") +} + +#endif // DDLOG_H diff --git a/deepin-system-monitor-server/src/logger.cpp b/deepin-system-monitor-server/src/logger.cpp new file mode 100644 index 00000000..09f0f10c --- /dev/null +++ b/deepin-system-monitor-server/src/logger.cpp @@ -0,0 +1,67 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include "logger.h" +#include "dtkcore_global.h" +#include "qglobal.h" +#include "ddlog.h" +#include +#include + +#include +using namespace DDLog; +DCORE_USE_NAMESPACE + +MLogger::MLogger(QObject *parent) + : QObject(parent), m_rules(""), m_config(nullptr) +{ + QByteArray logRules = qgetenv("QT_LOGGING_RULES"); + // qunsetenv 之前一定不要有任何日志打印,否则取消环境变量设置不会生效 + qunsetenv("QT_LOGGING_RULES"); + + // set env + m_rules = logRules; + + // set dconfig + m_config = DConfig::create("deepin-system-monitor-server", "org.deepin.system-monitor.server"); + logRules = m_config->value("log_rules").toByteArray(); + appendRules(logRules); + setRules(m_rules); + + // watch dconfig + connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) { + qCCritical(app) << "value changed:" << key; + if (key == "log_rules") { + setRules(m_config->value(key).toByteArray()); + } + }); +} + +MLogger::~MLogger() +{ + m_config->deleteLater(); +} + +void MLogger::setRules(const QString &rules) +{ + auto tmpRules = rules; + m_rules = tmpRules.replace(";", "\n"); + QLoggingCategory::setFilterRules(m_rules); +} + +void MLogger::appendRules(const QString &rules) +{ + QString tmpRules = rules; + tmpRules = tmpRules.replace(";", "\n"); + auto tmplist = tmpRules.split('\n'); + for (int i = 0; i < tmplist.count(); i++) + if (m_rules.contains(tmplist.at(i))) { + tmplist.removeAt(i); + i--; + } + if (tmplist.isEmpty()) + return; + m_rules.isEmpty() ? m_rules = tmplist.join("\n") + : m_rules += "\n" + tmplist.join("\n"); +} diff --git a/deepin-system-monitor-server/src/logger.h b/deepin-system-monitor-server/src/logger.h new file mode 100644 index 00000000..946fa7a3 --- /dev/null +++ b/deepin-system-monitor-server/src/logger.h @@ -0,0 +1,28 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include + +DCORE_BEGIN_NAMESPACE +class DConfig; +DCORE_END_NAMESPACE + +class MLogger : public QObject +{ + Q_OBJECT +public: + explicit MLogger(QObject *parent = nullptr); + ~MLogger(); + + inline QString rules() const { return m_rules; } + void setRules(const QString &rules); + +private: + void appendRules(const QString &rules); + +private: + QString m_rules; + Dtk::Core::DConfig *m_config; +}; diff --git a/deepin-system-monitor-server/src/main.cpp b/deepin-system-monitor-server/src/main.cpp index de9fec23..c15eaf3e 100644 --- a/deepin-system-monitor-server/src/main.cpp +++ b/deepin-system-monitor-server/src/main.cpp @@ -4,11 +4,27 @@ #include #include +#include +#include +#include "dtkcore_global.h" #include "dbusserver.h" +#include "logger.h" int main(int argc, char *argv[]) { + MLogger(); // 日志处理要放在app之前,否则QApplication + // 内部可能进行了日志打印,导致环境变量设置不生效 +// 为了兼容性 +#if (DTK_VERSION >= DTK_VERSION_CHECK(5, 6, 8, 0)) + Dtk::Core::DLogManager::registerJournalAppender(); +#else + Dtk::Core::DLogManager::registerFileAppender(); +#endif +#ifdef QT_DEBUG + Dtk::Core::DLogManager::registerConsoleAppender(); +#endif + QCoreApplication a(argc, argv); DBusServer dbusServer; diff --git a/deepin-system-monitor-system-server/CMakeLists.txt b/deepin-system-monitor-system-server/CMakeLists.txt index ec46e746..d701efd7 100644 --- a/deepin-system-monitor-system-server/CMakeLists.txt +++ b/deepin-system-monitor-system-server/CMakeLists.txt @@ -33,6 +33,7 @@ file(GLOB_RECURSE SRC_H ${CMAKE_CURRENT_LIST_DIR}/src/*.h) find_package(Qt5 COMPONENTS Core DBus REQUIRED) find_package(PolkitQt5-1 REQUIRED) +find_package(Dtk REQUIRED COMPONENTS Core) add_executable(${BIN_NAME} ${SRC_CPP} @@ -43,12 +44,14 @@ target_include_directories(${BIN_NAME} PUBLIC Qt5::Core Qt5::DBus PolkitQt5-1::Agent + Dtk::Core ) target_link_libraries(${BIN_NAME} PRIVATE Qt5::Core Qt5::DBus PolkitQt5-1::Agent + Dtk::Core ) # Use deepin-service-manager mange DBus servicde diff --git a/deepin-system-monitor-system-server/src/ddlog.h b/deepin-system-monitor-system-server/src/ddlog.h new file mode 100644 index 00000000..9f1f5230 --- /dev/null +++ b/deepin-system-monitor-system-server/src/ddlog.h @@ -0,0 +1,15 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef DDLOG_H +#define DDLOG_H +#include +#include +DCORE_USE_NAMESPACE + +namespace DDLog { +inline Q_LOGGING_CATEGORY(app, "org.deepin.system-monitor.server") +} + +#endif // DDLOG_H diff --git a/deepin-system-monitor-system-server/src/logger.cpp b/deepin-system-monitor-system-server/src/logger.cpp new file mode 100644 index 00000000..09f0f10c --- /dev/null +++ b/deepin-system-monitor-system-server/src/logger.cpp @@ -0,0 +1,67 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include "logger.h" +#include "dtkcore_global.h" +#include "qglobal.h" +#include "ddlog.h" +#include +#include + +#include +using namespace DDLog; +DCORE_USE_NAMESPACE + +MLogger::MLogger(QObject *parent) + : QObject(parent), m_rules(""), m_config(nullptr) +{ + QByteArray logRules = qgetenv("QT_LOGGING_RULES"); + // qunsetenv 之前一定不要有任何日志打印,否则取消环境变量设置不会生效 + qunsetenv("QT_LOGGING_RULES"); + + // set env + m_rules = logRules; + + // set dconfig + m_config = DConfig::create("deepin-system-monitor-server", "org.deepin.system-monitor.server"); + logRules = m_config->value("log_rules").toByteArray(); + appendRules(logRules); + setRules(m_rules); + + // watch dconfig + connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) { + qCCritical(app) << "value changed:" << key; + if (key == "log_rules") { + setRules(m_config->value(key).toByteArray()); + } + }); +} + +MLogger::~MLogger() +{ + m_config->deleteLater(); +} + +void MLogger::setRules(const QString &rules) +{ + auto tmpRules = rules; + m_rules = tmpRules.replace(";", "\n"); + QLoggingCategory::setFilterRules(m_rules); +} + +void MLogger::appendRules(const QString &rules) +{ + QString tmpRules = rules; + tmpRules = tmpRules.replace(";", "\n"); + auto tmplist = tmpRules.split('\n'); + for (int i = 0; i < tmplist.count(); i++) + if (m_rules.contains(tmplist.at(i))) { + tmplist.removeAt(i); + i--; + } + if (tmplist.isEmpty()) + return; + m_rules.isEmpty() ? m_rules = tmplist.join("\n") + : m_rules += "\n" + tmplist.join("\n"); +} diff --git a/deepin-system-monitor-system-server/src/logger.h b/deepin-system-monitor-system-server/src/logger.h new file mode 100644 index 00000000..946fa7a3 --- /dev/null +++ b/deepin-system-monitor-system-server/src/logger.h @@ -0,0 +1,28 @@ +// Copyright (C) 2019 ~ 2020 Uniontech Software Technology Co.,Ltd +// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include + +DCORE_BEGIN_NAMESPACE +class DConfig; +DCORE_END_NAMESPACE + +class MLogger : public QObject +{ + Q_OBJECT +public: + explicit MLogger(QObject *parent = nullptr); + ~MLogger(); + + inline QString rules() const { return m_rules; } + void setRules(const QString &rules); + +private: + void appendRules(const QString &rules); + +private: + QString m_rules; + Dtk::Core::DConfig *m_config; +}; diff --git a/deepin-system-monitor-system-server/src/systemdbusserver.cpp b/deepin-system-monitor-system-server/src/systemdbusserver.cpp index 19719859..617ac36e 100644 --- a/deepin-system-monitor-system-server/src/systemdbusserver.cpp +++ b/deepin-system-monitor-system-server/src/systemdbusserver.cpp @@ -3,6 +3,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "systemdbusserver.h" +#include "ddlog.h" #include #include @@ -16,6 +17,8 @@ #include #include +using namespace DDLog; + const QString s_PolkitActionSet = "org.deepin.systemmonitor.systemserver.set"; /** @@ -24,7 +27,7 @@ const QString s_PolkitActionSet = "org.deepin.systemmonitor.systemserver.set"; bool checkAuthorization(qint64 pid, const QString &action) { PolkitQt1::Authority::Result ret = PolkitQt1::Authority::instance()->checkAuthorizationSync( - action, PolkitQt1::UnixProcessSubject(pid), PolkitQt1::Authority::AllowUserInteraction); + action, PolkitQt1::UnixProcessSubject(pid), PolkitQt1::Authority::AllowUserInteraction); if (PolkitQt1::Authority::Yes == ret) { return true; } else { @@ -55,7 +58,7 @@ SystemDBusServer::SystemDBusServer(QObject *parent) QDBusConnection dbus = QDBusConnection::systemBus(); if (dbus.registerService("org.deepin.SystemMonitorSystemServer")) { QDBusConnection::RegisterOptions opts = - QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals | QDBusConnection::ExportAllProperties; + QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals | QDBusConnection::ExportAllProperties; if (!dbus.registerObject("/org/deepin/SystemMonitorSystemServer", this, opts)) { qWarning() << qPrintable("Register dbus object failed") << dbus.lastError().message(); } @@ -104,7 +107,7 @@ QString SystemDBusServer::setServiceEnableImpl(const QString &serviceName, bool // 判断服务是否存在 QProcess listPorcess; - listPorcess.start("systemctl", {"list-unit-files", "--type=service", "--no-pager"}); + listPorcess.start("systemctl", { "list-unit-files", "--type=service", "--no-pager" }); listPorcess.waitForFinished(); QByteArray serviceList = listPorcess.readAll(); if (!serviceList.contains(serviceName.toUtf8())) { @@ -120,12 +123,12 @@ QString SystemDBusServer::setServiceEnableImpl(const QString &serviceName, bool // 执行设置 QProcess process; - process.start("systemctl", {enable ? "enable" : "disable", serviceName}); + process.start("systemctl", { enable ? "enable" : "disable", serviceName }); process.waitForFinished(); QString errorRet = process.readAll(); // 检测是否执行成功 - process.start("systemctl", {"is-enabled", serviceName}); + process.start("systemctl", { "is-enabled", serviceName }); process.waitForFinished(); QString checkRet = process.readAll(); if (enable && ("enabled" == checkRet)) { @@ -166,14 +169,14 @@ bool SystemDBusServer::checkCaller() const qint64 callerPid = dbusCallerPid(); QString callerExe = getProcIdExe(callerPid); - QString dbmExe = QStandardPaths::findExecutable("deepin-system-monitor", {"/usr/bin"}); + QString dbmExe = QStandardPaths::findExecutable("deepin-system-monitor", { "/usr/bin" }); - qDebug() << qPrintable("callerPid is: ") << callerPid << qPrintable("callerExe is:") << callerExe; + qCDebug(app) << qPrintable("callerPid is: ") << callerPid << qPrintable("callerExe is:") << callerExe; if (callerExe != dbmExe) { - qDebug() << qPrintable("caller not authorized"); + qCDebug(app) << qPrintable("caller not authorized"); return false; } - qDebug() << qPrintable("caller authorized"); + qCDebug(app) << qPrintable("caller authorized"); return true; }