Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@
#include "mainjob.h"

#include <QDBusConnection>
#include <QDBusMessage>

Check warning on line 10 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QDBusMessage> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QProcess>

Check warning on line 11 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QProcess> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QDebug>

Check warning on line 12 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QDebug> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QFile>

Check warning on line 13 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QFile> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QRegularExpression>

Check warning on line 14 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QRegularExpression> not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <polkit-qt5-1/PolkitQt1/Authority>

Check warning on line 16 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <polkit-qt5-1/PolkitQt1/Authority> not found. Please note: Cppcheck does not need standard library headers to get proper results.

constexpr char kGraphicsMemory[] { "Graphics Memory" };

using namespace PolkitQt1;
bool DeviceInterface::getUserAuthorPasswd()
{
Expand All @@ -24,6 +29,52 @@
return result == Authority::Yes;
}

bool DeviceInterface::getGpuMemInfoForFTDTM(QMap<QString, QString> &mapInfo)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider refactoring the method by extracting helpers, using a unit conversion map, and simplifying formatting with join().

Here are a few low-risk refactorings you can apply to keep the exact same behaviour but break that monster method into bite-sized helpers, remove the deep if/else, and collapse your formatting loop into a single join().

  1. pull the file-read and empty-check out into its own helper:
static QString readFileContent(const QString& path) {
    QFile f(path);
    if (!f.open(QIODevice::ReadOnly|QIODevice::Text)) {
        qCritical() << "Error opening" << path << ":" << f.errorString();
        return {};
    }
    return QString::fromUtf8(f.readAll()).trimmed();
}
  1. pull the regex match into a helper + make the regex static const so it isn’t reallocated every call:
namespace {
static const QRegularExpression kMemRx{
    R"((\d+(?:\.\d+)?)\s*\(?(MB|GB|KB|B)\)?)",
    QRegularExpression::CaseInsensitiveOption
};
}

bool parseMemInfo(const QString& content, double& outValue, QString& outUnit) {
    auto m = kMemRx.match(content);
    if (!m.hasMatch()) {
        qCritical() << "Error: no memory info in:" << content;
        return false;
    }
    outValue = m.captured(1).toDouble();
    outUnit  = m.captured(2).toUpper();
    return true;
}
  1. replace the big if/else chain with a simple unit→factor map:
static const QHash<QString,double> kUnitToGb {
    { "B",  1.0/(1024*1024*1024) },
    { "KB", 1.0/(1024*1024)     },
    { "MB", 1.0/1024.0           },
    { "GB", 1.0                  }
};

QString convertToGbString(double value, const QString& unit) {
    double factor = kUnitToGb.value(unit, 0);
    if (factor == 0) {
        qCritical() << "Unknown unit:" << unit;
        return {};
    }
    return QString::number(value * factor, 'f', 2) + "GB";
}
  1. re-write getGpuMemInfoForFTDTM() as a simple orchestrator, and replace your manual loop in getGpuInfoForFTDTM() with a join():
bool DeviceInterface::getGpuMemInfoForFTDTM(QMap<QString,QString>& mapInfo) {
    const QString c = readFileContent("/sys/kernel/debug/gc/total_mem");
    if (c.isEmpty()) return false;

    double value;
    QString unit;
    if (!parseMemInfo(c, value, unit)) return false;

    const QString totalGb = convertToGbString(value, unit);
    if (totalGb.isEmpty()) return false;

    mapInfo.insert(kGraphicsMemory, totalGb);
    return true;
}

QString DeviceInterface::getGpuInfoForFTDTM() {
    static const QString info = []{
        QMap<QString,QString> m;
        if (!DeviceInterface{}.getGpuMemInfoForFTDTM(m))
            return QString{};
        QStringList lines;
        for (auto it = m.constBegin(); it != m.constEnd(); ++it)
            lines << QStringLiteral("%1: %2").arg(it.key(), it.value());
        return lines.join(QLatin1Char('\n')) + QLatin1Char('\n');
    }();
    return info;
}

— now each helper does one job, the conversion is driven by a table instead of four branches, and your final formatting is a single join().

{
const QString filePath = "/sys/kernel/debug/gc/total_mem";
QString totalValue;

QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCritical() << "Error opening /sys/kernel/debug/gc/total_mem:" << file.errorString();
return false;
}

QString content = QString::fromUtf8(file.readAll());
file.close();

if (content.isEmpty()) {
qCritical() << "Error: /sys/kernel/debug/gc/total_mem File is empty!";
return false;
}

QRegularExpression regex(R"((\d+(?:\.\d+)?)\s*\(?(MB|GB|KB|B)\)?)",
QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch memInfoMatch = regex.match(content);

if (!memInfoMatch.hasMatch()) {
qCritical() << "Error: Failed to find memory info";
return false;
}

double value = memInfoMatch.captured(1).toDouble();
QString unit = memInfoMatch.captured(2).toUpper();

if (unit == "MB") {
totalValue = QString("%1GB").arg(value / 1024.0, 0, 'f', 2);
} else if (unit == "GB") {
totalValue = QString("%1GB").arg(value, 0, 'f', 2);
} else if (unit == "KB") {
totalValue = QString("%1GB").arg(value / (1024.0 * 1024.0), 0, 'f', 2);
} else if (unit == "B") {
totalValue = QString("%1GB").arg(value / (1024.0 * 1024.0 * 1024.0), 0, 'f', 2);
}

mapInfo.insert(kGraphicsMemory, totalValue);

return true;
}

DeviceInterface::DeviceInterface(const char *name, QObject *parent)
: QObject(parent)
{
Expand Down Expand Up @@ -59,24 +110,17 @@
}
}

QString DeviceInterface::getGpuInfoByCustom(const QString &cmd, const QStringList &arguments)
QString DeviceInterface::getGpuInfoForFTDTM()
{
QString gpuinfo;
QProcess process;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
if (arguments.size() > 1) {
env.insert("DISPLAY", arguments[0]);
env.insert("XAUTHORITY", arguments[1]);
}
process.setProcessEnvironment(env);
process.start(cmd, arguments);
if (!process.waitForFinished()) {
qCritical() << QString("Error executing %1 :").arg(cmd) << process.errorString();
return gpuinfo;
static QString gpuMemInfo { "" };
if (gpuMemInfo.isEmpty()) {
QMap<QString, QString> mapInfo;
if (getGpuMemInfoForFTDTM(mapInfo)) {
for (auto it = mapInfo.begin(); it != mapInfo.end(); ++it) {
QString tmpInfo = it.key() + ": " + it.value() + "\n";
gpuMemInfo.append(tmpInfo);
}
}
}

if (process.exitCode() == 0)
gpuinfo = QString::fromLocal8Bit(process.readAllStandardOutput());

return gpuinfo;
return gpuMemInfo;
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ public slots:
*/
Q_SCRIPTABLE void setMonitorDeviceFlag(bool flag);

Q_SCRIPTABLE QString getGpuInfoByCustom(const QString &cmd, const QStringList &arguments);
Q_SCRIPTABLE QString getGpuInfoForFTDTM();

private:
bool getUserAuthorPasswd();
bool getGpuMemInfoForFTDTM(QMap<QString, QString> &mapInfo);
};

#endif // DEVICEINTERFACE_H
8 changes: 1 addition & 7 deletions deepin-devicemanager/src/GenerateDevice/CustomGenerator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,9 @@ CustomGenerator::CustomGenerator(QObject *parent)

void CustomGenerator::generatorGpuDevice()
{
QString cmd = CommonTools::getGpuInfoCommandFromDConfig();
if (cmd.isEmpty()) {
DeviceGenerator::generatorGpuDevice();
return;
}

QString tmpGpuInfo = CommonTools::preGenerateGpuInfo();
if (tmpGpuInfo.isEmpty()) {
qCritical() << "Failed to get gpu info by commad " << cmd;
qCritical() << "Error: Failed to get gpu info!";
return;
}

Expand Down
12 changes: 0 additions & 12 deletions deepin-devicemanager/src/GenerateDevice/DBusInterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,6 @@ void DBusInterface::refreshInfo()
mp_Iface->asyncCall("refreshInfo");
}

bool DBusInterface::getGpuInfoByCustom(const QString &cmd, const QStringList &arguments, QString &gpuInfo)
{
QDBusReply<QString> replyList = mp_Iface->call("getGpuInfoByCustom", cmd, arguments);
if (replyList.isValid()) {
gpuInfo = replyList.value();
return true;
} else {
qCritical() << "Error: failed to call dbus to get gpu memery info! ";
return false;
}
}

void DBusInterface::init()
{
// 1. 连接到dbus
Expand Down
2 changes: 0 additions & 2 deletions deepin-devicemanager/src/GenerateDevice/DBusInterface.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,6 @@ class DBusInterface
*/
void refreshInfo();

bool getGpuInfoByCustom(const QString &cmd, const QStringList &arguments, QString &gpuInfo);

protected:
DBusInterface();

Expand Down
42 changes: 20 additions & 22 deletions deepin-devicemanager/src/Tool/commontools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -268,42 +268,40 @@ QString CommonTools::getGpuInfoCommandFromDConfig()

QString CommonTools::preGenerateGpuInfo()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider refactoring preGenerateGpuInfo() by extracting caching and formatting logic into helper functions for clarity and maintainability.

Here’s one way to split retrieval/formatting out and collapse the nested logic in preGenerateGpuInfo():

// helper to format a map into “key: value\n…”
static QString formatInfoMap(const QMap<QString,QString>& m) {
    QString s;
    for (auto it = m.begin(); it != m.end(); ++it)
        s += it.key() + ": " + it.value() + "\n";
    return s;
}

// caches/returns GPU‐base info
static QString getCachedGpuBaseInfo() {
    static QString base;
    if (base.isEmpty()) {
        QMap<QString,QString> m;
        if (!CommonTools::getGpuBaseInfo(m)) {
            qCritical() << "Error: failed to get gpu base info!";
            return {};
        }
        base = formatInfoMap(m);
    }
    return base;
}

// caches/returns GPU‐mem info
static QString getCachedGpuMemInfo() {
    static QString mem;
    if (mem.isEmpty()) {
        QDBusInterface iface("org.deepin.DeviceInfo",
                             "/org/deepin/DeviceInfo",
                             "org.deepin.DeviceInfo",
                             QDBusConnection::systemBus());
        if (!iface.isValid()) {
            qCritical() << "Error: GPU mem DBus interface invalid";
        } else {
            auto reply = iface.call("getGpuInfoForFTDTM");
            if (reply.isValid()) mem = reply.value();
            else                qCritical() << "Error: failed to call getGpuInfoForFTDTM";
        }
    }
    return mem;
}

// simplified preGenerateGpuInfo()
QString CommonTools::preGenerateGpuInfo() {
    auto base = getCachedGpuBaseInfo();
    if (base.isEmpty()) return {};  // already logged
    return base + getCachedGpuMemInfo();
}

– Moves string‐building into formatInfoMap
– Moves each cache into its own function
– Makes preGenerateGpuInfo() a straight-line composition of those two calls

{
static QString gpuInfo { "" };

if (gpuInfo.isEmpty()) {
QStringList arguments;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QString display = env.value("DISPLAY");
QString xauthority = env.value("XAUTHORITY");
if (display.isEmpty() || xauthority.isEmpty()) {
qCritical() << "DISPLAY or XAUTHORITY is not set!";
} else {
arguments << display << xauthority;
static QString gpuBaseInfo { "" };
static QString gpuMemInfo { "" };

if (gpuBaseInfo.isEmpty()) {
QMap<QString, QString> mapInfo;
if (getGpuBaseInfo(mapInfo)) {
for (auto it = mapInfo.begin(); it != mapInfo.end(); ++it) {
QString tmpInfo = it.key() + ": " + it.value() + "\n";
gpuBaseInfo.append(tmpInfo);
}
}
}

if (gpuBaseInfo.isEmpty()) {
qCritical() << "Error: failed to get gpu base info!";
return "";
}

if (gpuMemInfo.isEmpty()) {
QDBusInterface iface("org.deepin.DeviceInfo",
"/org/deepin/DeviceInfo",
"org.deepin.DeviceInfo",
QDBusConnection::systemBus());
if (iface.isValid()) {
QDBusReply<QString> replyList = iface.call("getGpuInfoByCustom", arguments, gpuInfo);
QDBusReply<QString> replyList = iface.call("getGpuInfoForFTDTM");
if (replyList.isValid()) {
gpuInfo = replyList.value();
gpuMemInfo = replyList.value();
} else {
qCritical() << "Error: failed to call dbus to get gpu memery info! ";
}
}

QMap<QString, QString> mapInfo;
if (getGpuBaseInfo(mapInfo)) {
for (auto it = mapInfo.begin(); it != mapInfo.end(); ++it) {
QString tmpInfo = it.key() + ": " + it.value() + "\n";
gpuInfo.append(tmpInfo);
}
}
}

return gpuInfo;
return (gpuBaseInfo + gpuMemInfo);
}

bool CommonTools::getGpuBaseInfo(QMap<QString, QString> &mapInfo)
Expand Down
6 changes: 0 additions & 6 deletions deepin-devicemanager/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,6 @@ int main(int argc, char *argv[])
if (dbus.registerService("com.deepin.DeviceManagerNotify")) {
dbus.registerObject("/com/deepin/DeviceManagerNotify", &app, QDBusConnection::ExportScriptableSlots);
app.parseCmdLine();

QString cmd = CommonTools::getGpuInfoCommandFromDConfig();
if (!cmd.isEmpty()) {
CommonTools::preGenerateGpuInfo();
}

app.activateWindow();
return app.exec();
} else {
Expand Down