From 6f1a16de645883f621bddfad39d1819dd3c344a0 Mon Sep 17 00:00:00 2001 From: zhanghongyuan Date: Thu, 22 Oct 2026 11:23:23 +0800 Subject: [PATCH 1/3] feat(log): categorize logging and support dynamic log rules via DConfig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categorize all qDebug/qInfo/qWarning calls into qCDebug/qCInfo/qCWarning with the org.deepin.editor category, add MLogger to read log_rules from DConfig (org.deepin.editor) and watch changes at runtime, and add the log_rules key to the DConfig meta file. This enables the deepin debug mode (deepin-debug-config) to dynamically switch log levels. Note: the daemon/ directory is legacy unpackaged qmake code (built for Qt5 with polkit-qt5, not shipped in the deb) and is left unchanged. 日志分类化改造:存量 qDebug/qInfo/qWarning 全部改为带 org.deepin.editor 分类的 qCDebug/qCInfo/qCWarning;新增 MLogger 从 DConfig 读取 log_rules 并监听变更,支持调试模式运行中动态调整日志级别;DConfig meta 增加 log_rules 配置项。 Log: 调试模式适配——日志分类化与动态日志级别 Influence: 应用日志可按 org.deepin.editor 分类过滤,日志级别可动态切换 --- misc/configs/org.deepin.editor.json | 11 + src/common/CSyntaxHighlighter.cpp | 13 +- src/common/config.cpp | 63 +- src/common/dbusinterface.cpp | 7 +- src/common/encoding.cpp | 229 +-- src/common/eventlogutils.cpp | 11 +- src/common/fileloadthread.cpp | 37 +- src/common/iflytek_ai_assistant.cpp | 99 +- src/common/performancemonitor.cpp | 23 +- src/common/settings.cpp | 307 ++-- src/common/text_file_saver.cpp | 77 +- src/common/utils.cpp | 479 +++--- src/controls/findbar.cpp | 85 +- src/controls/fontitemdelegate.cpp | 17 +- src/controls/jumplinebar.cpp | 73 +- src/controls/linebar.cpp | 27 +- src/controls/replacebar.cpp | 97 +- src/controls/settingsdialog.cpp | 5 +- src/controls/tabbar.cpp | 297 ++-- src/controls/toolbar.cpp | 13 +- src/controls/warningnotices.cpp | 47 +- src/ddlog.h | 14 + src/editor/FlashTween.cpp | 39 +- src/editor/bookmarkwidget.cpp | 7 +- src/editor/changemarkcommand.cpp | 19 +- src/editor/codeflodarea.cpp | 9 +- src/editor/deletebackcommond.cpp | 47 +- src/editor/deletetextundocommand.cpp | 87 +- src/editor/dtextedit.cpp | 2097 ++++++++++++----------- src/editor/editwrapper.cpp | 497 +++--- src/editor/endlineformatcommond.cpp | 11 +- src/editor/indenttextcommond.cpp | 45 +- src/editor/insertblockbytextcommond.cpp | 47 +- src/editor/inserttextundocommand.cpp | 79 +- src/editor/leftareaoftextedit.cpp | 51 +- src/editor/linenumberarea.cpp | 9 +- src/editor/markdown/markdownview.cpp | 13 +- src/editor/replaceallcommond.cpp | 11 +- src/editor/showflodcodewidget.cpp | 47 +- src/editor/uncommentselection.cpp | 23 +- src/editor/undolist.cpp | 25 +- src/editorapplication.cpp | 61 +- src/encodes/detectcode.cpp | 257 +-- src/logger.cpp | 76 + src/logger.h | 39 + src/main.cpp | 70 +- src/startmanager.cpp | 319 ++-- src/thememodule/themeitemdelegate.cpp | 17 +- src/thememodule/themelistmodel.cpp | 33 +- src/thememodule/themelistview.cpp | 15 +- src/thememodule/themepanel.cpp | 31 +- src/widgets/ColorSelectWdg.cpp | 65 +- src/widgets/bottombar.cpp | 17 +- src/widgets/ddropdownmenu.cpp | 151 +- src/widgets/pathsettintwgt.cpp | 59 +- src/widgets/window.cpp | 1201 ++++++------- 56 files changed, 3901 insertions(+), 3704 deletions(-) create mode 100644 src/ddlog.h create mode 100644 src/logger.cpp create mode 100644 src/logger.h diff --git a/misc/configs/org.deepin.editor.json b/misc/configs/org.deepin.editor.json index ec2698eeb..77d49748d 100644 --- a/misc/configs/org.deepin.editor.json +++ b/misc/configs/org.deepin.editor.json @@ -34,6 +34,17 @@ "description": "Default text encoding, ASCII and unknown encoding will use the configured default encoding,the default is UTF-8", "permissions": "readwrite", "visibility": "private" + }, + "log_rules": { + "value": "org.deepin.editor*.debug=false;org.deepin.editor*.info=false;org.deepin.editor*.warning=true", + "serial": 0, + "flags": ["global"], + "name": "log rules", + "name[zh_CN]": "日志规则", + "description": "log rules", + "description[zh_CN]": "日志规则", + "permissions": "readwrite", + "visibility": "public" } } } \ No newline at end of file diff --git a/src/common/CSyntaxHighlighter.cpp b/src/common/CSyntaxHighlighter.cpp index bb5be7aae..2df0a880d 100644 --- a/src/common/CSyntaxHighlighter.cpp +++ b/src/common/CSyntaxHighlighter.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "CSyntaxHighlighter.h" #include @@ -9,18 +10,18 @@ CSyntaxHighlighter::CSyntaxHighlighter(QObject *parent): SyntaxHighlighter (parent), m_bHighlight(false) { - qDebug() << "CSyntaxHighlighter constructor"; + qCDebug(appLog) << "CSyntaxHighlighter constructor"; } CSyntaxHighlighter::CSyntaxHighlighter(QTextDocument *pDocument): SyntaxHighlighter (pDocument),m_bHighlight(false) { - qDebug() << "CSyntaxHighlighter constructor with QTextDocument*"; + qCDebug(appLog) << "CSyntaxHighlighter constructor with QTextDocument*"; } void CSyntaxHighlighter::setEnableHighlight(bool isEnable) { - qDebug() << "CSyntaxHighlighter::setEnableHighlight()" << isEnable; + qCDebug(appLog) << "CSyntaxHighlighter::setEnableHighlight()" << isEnable; m_bHighlight = isEnable; // 开关变更后重新高亮,避免旧格式残留至下次文档变更, // 与 setInvalidCharHighlight 的自动 rehighlight 行为保持一致 @@ -29,7 +30,7 @@ void CSyntaxHighlighter::setEnableHighlight(bool isEnable) void CSyntaxHighlighter::setInvalidCharHighlight(bool enable) { - qDebug() << "CSyntaxHighlighter::setInvalidCharHighlight()" << enable; + qCDebug(appLog) << "CSyntaxHighlighter::setInvalidCharHighlight()" << enable; m_bInvalidCharHighlight = enable; if (enable) { setEnableHighlight(true); @@ -40,11 +41,11 @@ void CSyntaxHighlighter::setInvalidCharHighlight(bool enable) void CSyntaxHighlighter::highlightBlock(const QString &text) { if (!m_bHighlight) { - qDebug() << "CSyntaxHighlighter::highlightBlock() is disabled"; + qCDebug(appLog) << "CSyntaxHighlighter::highlightBlock() is disabled"; return; } - qDebug() << "CSyntaxHighlighter::highlightBlock()"; + qCDebug(appLog) << "CSyntaxHighlighter::highlightBlock()"; KSyntaxHighlighting::SyntaxHighlighter::highlightBlock(text); // 叠加 \00 无效字符高亮:红色背景 + 白色文字 diff --git a/src/common/config.cpp b/src/common/config.cpp index fe137b715..15d0bacd5 100644 --- a/src/common/config.cpp +++ b/src/common/config.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2023-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "config.h" #include @@ -25,10 +26,10 @@ const QString g_keyEnablePatchedIconv = "enablePatchedIconv"; */ bool detectIconvUse2005Standard() { - qDebug() << "Detecting iconv use GB18030-2005 standard"; + qCDebug(appLog) << "Detecting iconv use GB18030-2005 standard"; iconv_t handle = iconv_open("UTF-8", "GB18030"); if (handle == reinterpret_cast(-1)) { - qWarning() << "Failed to open iconv handle for GB18030"; + qCWarning(appLog) << "Failed to open iconv handle for GB18030"; return true; } @@ -43,16 +44,16 @@ bool detectIconvUse2005Standard() iconv_close(handle); if (ret == static_cast(-1)) { - qWarning() << "Failed to convert GB18030 to UTF-8"; + qCWarning(appLog) << "Failed to convert GB18030 to UTF-8"; return true; } if (!output.contains("\uE816")) { - qInfo() << "Current iconv uses GB18030-2005 standard"; + qCInfo(appLog) << "Current iconv uses GB18030-2005 standard"; return true; } - qInfo() << "Current iconv uses GB18030-2022 standard"; + qCInfo(appLog) << "Current iconv uses GB18030-2022 standard"; return false; } @@ -67,67 +68,67 @@ Config::Config(QObject *parent) : QObject(parent) , encoding("UTF-8") { - qDebug() << "Initializing Config instance"; + qCDebug(appLog) << "Initializing Config instance"; #ifdef DTKCORE_CLASS_DConfigFile dconfig = DConfig::create("org.deepin.editor", "org.deepin.editor"); if (dconfig->isValid()) { - qDebug() << "DConfig is valid"; + qCDebug(appLog) << "DConfig is valid"; // 默认提高GB18030识别率 improveGB18030 = !dconfig->value(g_keyDisableImproveGB18030).toBool(); - qInfo() << qPrintable("DConfig::ImproveGB18030:") << improveGB18030; + qCInfo(appLog) << qPrintable("DConfig::ImproveGB18030:") << improveGB18030; patchedIconv = dconfig->value(g_keyEnablePatchedIconv).toBool(); - qInfo() << qPrintable("DConfig::enablePatchedIconv:") << patchedIconv; + qCInfo(appLog) << qPrintable("DConfig::enablePatchedIconv:") << patchedIconv; encoding = dconfig->value(g_keyDefaultEncoding).toByteArray().toUpper(); - qInfo() << qPrintable("DConfig::defaultEncoding") << encoding; + qCInfo(appLog) << qPrintable("DConfig::defaultEncoding") << encoding; connect(dconfig, &DConfig::valueChanged, this, [this](const QString &key) { - qDebug() << "Config value changed for key:" << key; + qCDebug(appLog) << "Config value changed for key:" << key; if (key == g_keyDisableImproveGB18030) { this->improveGB18030 = !this->dconfig->value(g_keyDisableImproveGB18030).toBool(); - qInfo() << qPrintable("DConfig::ImproveGB18030 changed:") << improveGB18030; - qDebug() << "improveGB18030 changed to" << this->improveGB18030; + qCInfo(appLog) << qPrintable("DConfig::ImproveGB18030 changed:") << improveGB18030; + qCDebug(appLog) << "improveGB18030 changed to" << this->improveGB18030; } else if (key == g_keyEnablePatchedIconv) { this->patchedIconv = dconfig->value(g_keyEnablePatchedIconv).toBool(); - qInfo() << qPrintable("DConfig::enablePatchedIconv changed:") << patchedIconv; - qDebug() << "patchedIconv changed to" << this->patchedIconv; + qCInfo(appLog) << qPrintable("DConfig::enablePatchedIconv changed:") << patchedIconv; + qCDebug(appLog) << "patchedIconv changed to" << this->patchedIconv; } else if (key == g_keyDefaultEncoding) { this->encoding = dconfig->value(g_keyDefaultEncoding).toByteArray().toUpper(); - qInfo() << qPrintable("DConfig::defaultEncoding changed:") << encoding; - qDebug() << "encoding changed to" << this->encoding; + qCInfo(appLog) << qPrintable("DConfig::defaultEncoding changed:") << encoding; + qCDebug(appLog) << "encoding changed to" << this->encoding; } }); } else { - qWarning() << qPrintable("org.deepin.editor DConfig not valid!"); + qCWarning(appLog) << qPrintable("org.deepin.editor DConfig not valid!"); } #else - qWarning() << "DConfig is not supported by DTK!"; + qCWarning(appLog) << "DConfig is not supported by DTK!"; #endif // 检测当前iconv使用的GB18030编码是否为2005标准(2005标准强制使用上层补丁版本) iocnvUse2005Standard = detectIconvUse2005Standard(); - qDebug() << "Leaving Config::Config"; + qCDebug(appLog) << "Leaving Config::Config"; } Config::~Config() { - qDebug() << "Destroying Config instance"; + qCDebug(appLog) << "Destroying Config instance"; #ifdef DTKCORE_CLASS_DConfigFile if (dconfig) { - qDebug() << "Deleting dconfig"; + qCDebug(appLog) << "Deleting dconfig"; delete dconfig; } #endif - qDebug() << "Leaving Config::~Config"; + qCDebug(appLog) << "Leaving Config::~Config"; } Config *Config::instance() { - qDebug() << "Getting Config singleton instance"; + qCDebug(appLog) << "Getting Config singleton instance"; static Config config; - qDebug() << "Leaving Config::instance"; + qCDebug(appLog) << "Leaving Config::instance"; return &config; } @@ -136,7 +137,7 @@ Config *Config::instance() */ bool Config::enableImproveGB18030() const { - qDebug() << "Entering Config::enableImproveGB18030, returning" << improveGB18030; + qCDebug(appLog) << "Entering Config::enableImproveGB18030, returning" << improveGB18030; return improveGB18030; } @@ -146,7 +147,7 @@ bool Config::enableImproveGB18030() const */ bool Config::enablePatchedIconv() const { - qDebug() << "Entering Config::enablePatchedIconv, returning" << (patchedIconv || iocnvUse2005Standard); + qCDebug(appLog) << "Entering Config::enablePatchedIconv, returning" << (patchedIconv || iocnvUse2005Standard); return patchedIconv || iocnvUse2005Standard; } @@ -155,11 +156,11 @@ bool Config::enablePatchedIconv() const */ QByteArray Config::defaultEncoding() const { - qDebug() << "Entering Config::defaultEncoding"; + qCDebug(appLog) << "Entering Config::defaultEncoding"; if (encoding.isEmpty()) { - qDebug() << "Encoding is empty, returning UTF-8"; + qCDebug(appLog) << "Encoding is empty, returning UTF-8"; return QByteArray("UTF-8"); } - qDebug() << "Returning configured encoding:" << encoding; + qCDebug(appLog) << "Returning configured encoding:" << encoding; return encoding; } diff --git a/src/common/dbusinterface.cpp b/src/common/dbusinterface.cpp index 9f654d510..b92761773 100644 --- a/src/common/dbusinterface.cpp +++ b/src/common/dbusinterface.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2011-2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2011-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "dbusinterface.h" #include @@ -9,10 +10,10 @@ SaveFileInterface::SaveFileInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) : QDBusAbstractInterface(service, path, staticInterfaceName(), connection, parent) { - qDebug() << "SaveFileInterface created for" << service << path; + qCDebug(appLog) << "SaveFileInterface created for" << service << path; } SaveFileInterface::~SaveFileInterface() { - qDebug() << "SaveFileInterface destroyed for" << service() << path(); + qCDebug(appLog) << "SaveFileInterface destroyed for" << service() << path(); } diff --git a/src/common/encoding.cpp b/src/common/encoding.cpp index 2f5f05e5a..e413e7fea 100644 --- a/src/common/encoding.cpp +++ b/src/common/encoding.cpp @@ -25,6 +25,7 @@ * Homepage: http://tarot.freeshell.org/leafpad/ */ +#include "ddlog.h" #include #include // getenv (not used but, maybe, for *BSD) #include // CODESET, nl_langinfo @@ -117,19 +118,19 @@ static const std::string encodingTable[TOTAL_NUM][ENCODING_MAX_ITEM_NUM] = /*************************/ static unsigned int getLocaleNum() { - qDebug() << "Entering getLocaleNum"; + qCDebug(appLog) << "Entering getLocaleNum"; static unsigned int code = 0; // for me QStringList langs (QLocale::system().uiLanguages()); if (!langs.isEmpty()) { - qDebug() << "System UI languages found:" << langs; + qCDebug(appLog) << "System UI languages found:" << langs; QString lang = langs.first().replace ('-', '_'); if (lang.length() >= 2) { std::string env = lang.toStdString(); if (!env.empty() && env.length() >= 2) { - qDebug() << "Detecting locale number for env:" << env.c_str(); + qCDebug(appLog) << "Detecting locale number for env:" << env.c_str(); int j = 1; while (code == 0 && j < TOTAL_NUM) { @@ -140,7 +141,7 @@ static unsigned int getLocaleNum() if (env.compare (0, countryTable[j][i].length(), countryTable[j][i]) == 0) { code = j; - qDebug() << "Found matching country table, code:" << code; + qCDebug(appLog) << "Found matching country table, code:" << code; break; } } @@ -149,9 +150,9 @@ static unsigned int getLocaleNum() } } } else { - qDebug() << "No system UI languages found."; + qCDebug(appLog) << "No system UI languages found."; } - qDebug() << "Leaving getLocaleNum, returning code:" << code; + qCDebug(appLog) << "Leaving getLocaleNum, returning code:" << code; return code; } /*************************/ @@ -162,7 +163,7 @@ static const std::string encodingItem[ENCODING_MAX_ITEM_NUM] = {encodingTable[lo /*************************/ static const std::string detectCharsetLatin (const char *text) { - qDebug() << "Entering detectCharsetLatin"; + qCDebug(appLog) << "Entering detectCharsetLatin"; uint8_t c = *text; bool noniso = false; bool noniso15 = false; @@ -174,57 +175,57 @@ static const std::string detectCharsetLatin (const char *text) { if (c >= 0x41 && c <= 0x7A) { - qDebug() << "Ordinary Latin letters"; + qCDebug(appLog) << "Ordinary Latin letters"; /* ordinary Latin letters */ xl ++; } else if (c >= 0x80 && c <= 0x9F) { - qDebug() << "Non-ISO letters"; + qCDebug(appLog) << "Non-ISO letters"; noniso = true; } else if (c >= 0xC0) { - qDebug() << "Arabic or Cyrillic letters"; + qCDebug(appLog) << "Arabic or Cyrillic letters"; /* Arabic or Cyrillic letters */ xac ++; if (c >= 0xC0 && c <= 0xCF) { - qDebug() << "Cyrillic capital letters"; + qCDebug(appLog) << "Cyrillic capital letters"; /* Cyrillic capital letters */ xcC++; } else if (c >= 0xD0 && c <= 0xDF) { - qDebug() << "Cyrillic capital letters again"; + qCDebug(appLog) << "Cyrillic capital letters again"; /* Cyrillic capital letters again */ xcC1++; if (c == 0xDE || c == 0xDF) { - qDebug() << "Not used in ISO-8859-15 (Icelandic or German)"; + qCDebug(appLog) << "Not used in ISO-8859-15 (Icelandic or German)"; /* not used in ISO-8859-15 (Icelandic or German) */ noniso15 = true; } } else if (c >= 0xE0) { - qDebug() << "Cyrillic small letters"; + qCDebug(appLog) << "Cyrillic small letters"; /* Cyrillic small letters */ xcS++; /* Cyrillic but not Arabic letters */ - qDebug() << "Cyrillic but not Arabic letters"; + qCDebug(appLog) << "Cyrillic but not Arabic letters"; if (c == 0xE0 || c == 0xE2 || (c >= 0xE7 && c <= 0xEB) || c == 0xEE || c == 0xEF || c == 0xF4 || c == 0xF9 || c == 0xFB || c == 0xFC) { - qDebug() << "Arabic LAM to HEH"; + qCDebug(appLog) << "Arabic LAM to HEH"; xcna ++; } /* Arabic LAM to HEH */ else if (c == 0xE1 || c == 0xE3 || c == 0xE4 || c == 0xE5 || c == 0xE6) { - qDebug() << "Arabic LAM to HEH"; + qCDebug(appLog) << "Arabic LAM to HEH"; xa++; } } @@ -238,54 +239,54 @@ static const std::string detectCharsetLatin (const char *text) if (noniso && xl >= xac && (xcC1 + xcS >= xcC || xcna == 0)) { charset = "CP1252"; // Windows-1252 - qDebug() << "Charset detected as CP1252"; + qCDebug(appLog) << "Charset detected as CP1252"; } else // if (xl < xac) { if (!noniso && xcC + xcS < xcC1) { charset = "ISO-8859-15"; // FIXME: ISO-8859-5 ? - qDebug() << "Charset detected as ISO-8859-15 (case 1)"; + qCDebug(appLog) << "Charset detected as ISO-8859-15 (case 1)"; } /* this is very tricky and I added it later */ else if (!noniso && xcC + xcC1 + xa >= xcS - xa && !(xcC1 + xcS < xcC && xcna > 0)) { charset = "ISO-8859-1"; - qDebug() << "Charset detected as ISO-8859-1"; + qCDebug(appLog) << "Charset detected as ISO-8859-1"; } else if (xcC + xcC1 < xcS && xcna > 0) { if (noniso || noniso15) // FIXME: this is very inefficient { charset = "CP1251"; // Cyrillic-1251 - qDebug() << "Charset detected as CP1251"; + qCDebug(appLog) << "Charset detected as CP1251"; } else { charset = "ISO-8859-15"; - qDebug() << "Charset detected as ISO-8859-15 (case 2)"; + qCDebug(appLog) << "Charset detected as ISO-8859-15 (case 2)"; } } else if (xcC1 + xcS < xcC && xcna > 0) { charset = "KOI8-U"; // Cyrillic-KOI - qDebug() << "Charset detected as KOI8-U"; + qCDebug(appLog) << "Charset detected as KOI8-U"; } /* this should cover most cases */ else if (noniso || xcC + xcC1 + xa >= xcS - xa) { charset = "CP1256"; // MS Windows Arabic - qDebug() << "Charset detected as CP1256"; + qCDebug(appLog) << "Charset detected as CP1256"; } } - qDebug() << "Leaving detectCharsetLatin, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving detectCharsetLatin, returning charset:" << charset.c_str(); return charset; } /*************************/ static const std::string detectCharsetCyrillic (const char *text) { - qDebug() << "Entering detectCharsetCyrillic"; + qCDebug(appLog) << "Entering detectCharsetCyrillic"; uint8_t c = *text; bool noniso = false; uint32_t xl = 0, xa = 0, xac = 0, xcC = 0, xcC1 = 0, xcS = 0, xcna = 0; @@ -325,7 +326,7 @@ static const std::string detectCharsetCyrillic (const char *text) if (xl < xac) { - qDebug() << "Cyrillic letters are more than Latin ones"; + qCDebug(appLog) << "Cyrillic letters are more than Latin ones"; if (!noniso && (xcC + xcS < xcC1)) charset = "ISO-8859-5"; else if (xcC + xcC1 < xcS && xcna > 0) @@ -336,13 +337,13 @@ static const std::string detectCharsetCyrillic (const char *text) charset = "CP1256"; } - qDebug() << "Leaving detectCharsetCyrillic, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving detectCharsetCyrillic, returning charset:" << charset.c_str(); return charset; } /*************************/ static const std::string detectCharsetWinArabic (const char *text) { - qDebug() << "Entering detectCharsetWinArabic"; + qCDebug(appLog) << "Entering detectCharsetWinArabic"; uint8_t c = *text; uint32_t xl = 0, xa = 0; std::string charset = encodingItem[IANA]; @@ -359,13 +360,13 @@ static const std::string detectCharsetWinArabic (const char *text) if (xl < xa) charset = "CP1256"; - qDebug() << "Leaving detectCharsetWinArabic, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving detectCharsetWinArabic, returning charset:" << charset.c_str(); return charset; } /*************************/ static const std::string detectCharsetChinese (const char *text) { - qDebug() << "Entering detectCharsetChinese"; + qCDebug(appLog) << "Entering detectCharsetChinese"; uint8_t c = *text; std::string charset = encodingItem[IANA]; @@ -373,57 +374,57 @@ static const std::string detectCharsetChinese (const char *text) { if (c >= 0x81 && c <= 0x87) { - qDebug() << "c >= 0x81 && c <= 0x87"; + qCDebug(appLog) << "c >= 0x81 && c <= 0x87"; charset = "GB18030"; break; } else if (c >= 0x88 && c <= 0xA0) { - qDebug() << "c >= 0x88 && c <= 0xA0"; + qCDebug(appLog) << "c >= 0x88 && c <= 0xA0"; c = *text++; if ((c >= 0x30 && c <= 0x39) || (c >= 0x80 && c <= 0xA0)) { - qDebug() << "c >= 0x30 && c <= 0x39 || c >= 0x80 && c <= 0xA0"; + qCDebug(appLog) << "c >= 0x30 && c <= 0x39 || c >= 0x80 && c <= 0xA0"; charset = "GB18030"; break; } //else GBK/Big5-HKSCS cannot determine } else if ((c >= 0xA1 && c <= 0xC6) || (c >= 0xC9 && c <= 0xF9)) { - qDebug() << "c >= 0xA1 && c <= 0xC6 || c >= 0xC9 && c <= 0xF9"; + qCDebug(appLog) << "c >= 0xA1 && c <= 0xC6 || c >= 0xC9 && c <= 0xF9"; c = *text++; if (c >= 0x40 && c <= 0x7E) { - qDebug() << "c >= 0x40 && c <= 0x7E"; + qCDebug(appLog) << "c >= 0x40 && c <= 0x7E"; charset = "BIG5"; } else if ((c >= 0x30 && c <= 0x39) || (c >= 0x80 && c <= 0xA0)) { - qDebug() << "c >= 0x30 && c <= 0x39 || c >= 0x80 && c <= 0xA0"; + qCDebug(appLog) << "c >= 0x30 && c <= 0x39 || c >= 0x80 && c <= 0xA0"; charset = "GB18030"; break; } } else if (c >= 0xC7) { - qDebug() << "c >= 0xC7"; + qCDebug(appLog) << "c >= 0xC7"; c = *text++; if ((c >= 0x30 && c <= 0x39) || (c >= 0x80 && c <= 0xA0)) { - qDebug() << "c >= 0x30 && c <= 0x39 || c >= 0x80 && c <= 0xA0"; + qCDebug(appLog) << "c >= 0x30 && c <= 0x39 || c >= 0x80 && c <= 0xA0"; charset = "GB18030"; break; } } } - qDebug() << "Leaving detectCharsetChinese, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving detectCharsetChinese, returning charset:" << charset.c_str(); return charset; } /*************************/ static const std::string detectCharsetJapanese (const char *text) { - qDebug() << "Entering detectCharsetJapanese"; + qCDebug(appLog) << "Entering detectCharsetJapanese"; uint8_t c = *text; std::string charset = ""; @@ -431,26 +432,26 @@ static const std::string detectCharsetJapanese (const char *text) { if (c >= 0x81 && c <= 0x9F) { - qDebug() << "c >= 0x81 && c <= 0x9F"; + qCDebug(appLog) << "c >= 0x81 && c <= 0x9F"; if (c == 0x8E) /* SS2 */ { - qDebug() << "c == 0x8E"; + qCDebug(appLog) << "c == 0x8E"; c = *text++; if ((c >= 0x40 && c <= 0xA0) || (c >= 0xE0 && c <= 0xFC)) charset = "CP932"; } else if (c == 0x8F) /* SS3 */ { - qDebug() << "c == 0x8F"; + qCDebug(appLog) << "c == 0x8F"; c = *text++; if (c >= 0x40 && c <= 0xA0) { - qDebug() << "c >= 0x40 && c <= 0xA0"; + qCDebug(appLog) << "c >= 0x40 && c <= 0xA0"; charset = "CP932"; } else if (c >= 0xFD) { - qDebug() << "c >= 0xFD"; + qCDebug(appLog) << "c >= 0xFD"; break; } } @@ -459,48 +460,48 @@ static const std::string detectCharsetJapanese (const char *text) } else if (c >= 0xA1 && c <= 0xDF) { - qDebug() << "c >= 0xA1 && c <= 0xDF"; + qCDebug(appLog) << "c >= 0xA1 && c <= 0xDF"; c = *text++; if (c <= 0x9F) { - qDebug() << "c <= 0x9F"; + qCDebug(appLog) << "c <= 0x9F"; charset = "CP932"; } else if (c >= 0xFD) { - qDebug() << "c >= 0xFD"; + qCDebug(appLog) << "c >= 0xFD"; break; } } else if (c >= 0xE0 && c <= 0xEF) { - qDebug() << "c >= 0xE0 && c <= 0xEF"; + qCDebug(appLog) << "c >= 0xE0 && c <= 0xEF"; c = *text++; if (c >= 0x40 && c <= 0xA0) { - qDebug() << "c >= 0x40 && c <= 0xA0"; + qCDebug(appLog) << "c >= 0x40 && c <= 0xA0"; charset = "CP932"; } else if (c >= 0xFD) { - qDebug() << "c >= 0xFD"; + qCDebug(appLog) << "c >= 0xFD"; break; } } else if (c >= 0xF0) { - qDebug() << "c >= 0xF0"; + qCDebug(appLog) << "c >= 0xF0"; break; } } if (charset.empty()) { - qDebug() << "charset is empty"; + qCDebug(appLog) << "charset is empty"; charset = "EUC-JP"; } - qDebug() << "Leaving detectCharsetJapanese, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving detectCharsetJapanese, returning charset:" << charset.c_str(); return charset; } /*************************/ @@ -511,107 +512,107 @@ static const std::string detectCharsetKorean (const char *text) bool nonjohab = false; std::string charset = ""; - qDebug() << "Entering detectCharsetKorean"; + qCDebug(appLog) << "Entering detectCharsetKorean"; while (charset.empty() && (c = *text++) != '\0') { if (c >= 0x81 && c < 0x84) { - qDebug() << "c >= 0x81 && c < 0x84"; + qCDebug(appLog) << "c >= 0x81 && c < 0x84"; charset = "CP949"; } else if (c >= 0x84 && c < 0xA1) { - qDebug() << "c >= 0x84 && c < 0xA1"; + qCDebug(appLog) << "c >= 0x84 && c < 0xA1"; noneuc = true; c = *text++; if ((c > 0x5A && c < 0x61) || (c > 0x7A && c < 0x81)) { - qDebug() << "c > 0x5A && c < 0x61 || c > 0x7A && c < 0x81"; + qCDebug(appLog) << "c > 0x5A && c < 0x61 || c > 0x7A && c < 0x81"; charset = "CP1361"; } else if (c == 0x52 || c == 0x72 || c == 0x92 || (c > 0x9D && c < 0xA1) || c == 0xB2 || (c > 0xBD && c < 0xC1) || c == 0xD2 || (c > 0xDD && c < 0xE1) || c == 0xF2 || c == 0xFE) { - qDebug() << "c == 0x52 || c == 0x72 || c == 0x92 || (c > 0x9D && c < 0xA1) || c == 0xB2 || (c > 0xBD && c < 0xC1) || c == 0xD2 || (c > 0xDD && c < 0xE1) || c == 0xF2 || c == 0xFE"; + qCDebug(appLog) << "c == 0x52 || c == 0x72 || c == 0x92 || (c > 0x9D && c < 0xA1) || c == 0xB2 || (c > 0xBD && c < 0xC1) || c == 0xD2 || (c > 0xDD && c < 0xE1) || c == 0xF2 || c == 0xFE"; charset = "CP949"; } } else if (c >= 0xA1 && c <= 0xC6) { - qDebug() << "c > 0xC6 && c <= 0xD3"; + qCDebug(appLog) << "c > 0xC6 && c <= 0xD3"; c = *text++; if (c < 0xA1) { - qDebug() << "c < 0xA1"; + qCDebug(appLog) << "c < 0xA1"; noneuc = true; if ((c > 0x5A && c < 0x61) || (c > 0x7A && c < 0x81)) { - qDebug() << "c > 0x5A && c < 0x61 || c > 0x7A && c < 0x81"; + qCDebug(appLog) << "c > 0x5A && c < 0x61 || c > 0x7A && c < 0x81"; charset = "CP1361"; } else if (c == 0x52 || c == 0x72 || c == 0x92 || (c > 0x9D && c < 0xA1)) { - qDebug() << "c == 0x52 || c == 0x72 || c == 0x92 || (c > 0x9D && c < 0xA1)"; + qCDebug(appLog) << "c == 0x52 || c == 0x72 || c == 0x92 || (c > 0x9D && c < 0xA1)"; charset = "CP949"; } else if (c == 0xB2 || (c > 0xBD && c < 0xC1) || c == 0xD2 || (c > 0xDD && c < 0xE1) || c == 0xF2 || c == 0xFE) { - qDebug() << "c == 0xB2 || (c > 0xBD && c < 0xC1) || c == 0xD2 || (c > 0xDD && c < 0xE1) || c == 0xF2 || c == 0xFE"; + qCDebug(appLog) << "c == 0xB2 || (c > 0xBD && c < 0xC1) || c == 0xD2 || (c > 0xDD && c < 0xE1) || c == 0xF2 || c == 0xFE"; nonjohab = true; } } } else if (c > 0xC6 && c <= 0xD3) { - qDebug() << "c > 0xD3 && c < 0xD8"; + qCDebug(appLog) << "c > 0xD3 && c < 0xD8"; c = *text++; if (c < 0xA1) { - qDebug() << "c < 0xA1"; + qCDebug(appLog) << "c < 0xA1"; charset = "CP1361"; } } else if (c > 0xD3 && c < 0xD8) { - qDebug() << "c >= 0xD8"; + qCDebug(appLog) << "c >= 0xD8"; nonjohab = true; c = *text++; } else if (c >= 0xD8) { - qDebug() << "c >= 0xD8"; + qCDebug(appLog) << "c >= 0xD8"; c = *text++; if (c < 0xA1) { - qDebug() << "c < 0xA1"; + qCDebug(appLog) << "c < 0xA1"; charset = "CP1361"; } } if (noneuc && nonjohab) { - qDebug() << "noneuc && nonjohab"; + qCDebug(appLog) << "noneuc && nonjohab"; charset = "CP949"; } } if (charset.empty()) { - qDebug() << "charset is empty"; + qCDebug(appLog) << "charset is empty"; if (noneuc) { - qDebug() << "noneuc"; + qCDebug(appLog) << "noneuc"; charset = "CP949"; } else { - qDebug() << "nonjohab"; + qCDebug(appLog) << "nonjohab"; charset = "EUC-KR"; } } - qDebug() << "Leaving detectCharsetKorean, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving detectCharsetKorean, returning charset:" << charset.c_str(); return charset; } /*************************/ @@ -619,31 +620,31 @@ static const std::string detectCharsetKorean (const char *text) // ("UTF-8" for me) static const std::string getDefaultCharset() { - qDebug() << "Entering getDefaultCharset"; + qCDebug(appLog) << "Entering getDefaultCharset"; if (setlocale (LC_ALL, "") == NULL) { - qDebug() << "setlocale (LC_ALL, \"\") == NULL"; + qCDebug(appLog) << "setlocale (LC_ALL, \"\") == NULL"; return "UTF-8"; // something's wrong; fall back to UTF-8 } const std::string charset = nl_langinfo (CODESET); - qDebug() << "Leaving getDefaultCharset, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving getDefaultCharset, returning charset:" << charset.c_str(); return charset; } /*************************/ static bool detect_noniso (const char *text) { - qDebug() << "Entering detect_noniso"; + qCDebug(appLog) << "Entering detect_noniso"; uint8_t c = *text; while ((c = *text++) != '\0') { if (c >= 0x80 && c <= 0x9F) { - qDebug() << "Non-ISO character detected. Leaving detect_noniso, returning true."; + qCDebug(appLog) << "Non-ISO character detected. Leaving detect_noniso, returning true."; return true; } } - qDebug() << "No Non-ISO characters detected. Leaving detect_noniso, returning false."; + qCDebug(appLog) << "No Non-ISO characters detected. Leaving detect_noniso, returning false."; return false; } /*************************/ @@ -653,7 +654,7 @@ static bool detect_noniso (const char *text) with QTextCodec::toUnicode(), which may give incorrect results. */ bool validateUTF8 (const QByteArray byteArray) { - qDebug() << "Entering validateUTF8"; + qCDebug(appLog) << "Entering validateUTF8"; const char *string = byteArray.constData(); if (!string) return true; @@ -667,31 +668,31 @@ bool validateUTF8 (const QByteArray byteArray) we find the code point and the number of bytes */ if ((*bytes & 0x80) == 0x00) { // 0xxxxxxx, all ASCII characters (0-127) - qDebug() << "(*bytes & 0x80) == 0x00"; + qCDebug(appLog) << "(*bytes & 0x80) == 0x00"; cp = (*bytes & 0x7F); bn = 1; } else if ((*bytes & 0xE0) == 0xC0) { // 110xxxxx 10xxxxxx - qDebug() << "(*bytes & 0xE0) == 0xC0"; + qCDebug(appLog) << "(*bytes & 0xE0) == 0xC0"; cp = (*bytes & 0x1F); bn = 2; } else if ((*bytes & 0xF0) == 0xE0) { // 1110xxxx 10xxxxxx 10xxxxxx - qDebug() << "(*bytes & 0xF0) == 0xE0"; + qCDebug(appLog) << "(*bytes & 0xF0) == 0xE0"; cp = (*bytes & 0x0F); bn = 3; } else if ((*bytes & 0xF8) == 0xF0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - qDebug() << "(*bytes & 0xF8) == 0xF0"; + qCDebug(appLog) << "(*bytes & 0xF8) == 0xF0"; cp = (*bytes & 0x07); bn = 4; } else { - qDebug() << "else"; + qCDebug(appLog) << "else"; return false; } @@ -701,7 +702,7 @@ bool validateUTF8 (const QByteArray byteArray) /* all the other bytes should be of the form 10xxxxxx */ if ((*bytes & 0xC0) != 0x80) { - qDebug() << "(*bytes & 0xC0) != 0x80"; + qCDebug(appLog) << "(*bytes & 0xC0) != 0x80"; return false; } cp = (cp << 6) | (*bytes & 0x3F); @@ -718,49 +719,49 @@ bool validateUTF8 (const QByteArray byteArray) || (cp >= 0x0800 && cp <= 0xFFFF && bn != 3) || (cp >= 0x10000 && cp <= 0x1FFFFF && bn != 4)) { - qDebug() << "cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) || (cp <= 0x007F && bn != 1) || (cp >= 0x0080 && cp <= 0x07FF && bn != 2) || (cp >= 0x0800 && cp <= 0xFFFF && bn != 3) || (cp >= 0x10000 && cp <= 0x1FFFFF && bn != 4)"; + qCDebug(appLog) << "cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) || (cp <= 0x007F && bn != 1) || (cp >= 0x0080 && cp <= 0x07FF && bn != 2) || (cp >= 0x0800 && cp <= 0xFFFF && bn != 3) || (cp >= 0x10000 && cp <= 0x1FFFFF && bn != 4)"; return false; } } - qDebug() << "UTF-8 validation successful. Leaving validateUTF8, returning true."; + qCDebug(appLog) << "UTF-8 validation successful. Leaving validateUTF8, returning true."; return true; } /*************************/ const QString detectCharset (const QByteArray& byteArray) { - qDebug() << "Entering detectCharset"; + qCDebug(appLog) << "Entering detectCharset"; const char* text = byteArray.constData(); uint8_t c = *text; std::string charset; if (validateUTF8 (byteArray)) { - qDebug() << "validateUTF8 is true"; + qCDebug(appLog) << "validateUTF8 is true"; while ((c = *text++) != '\0') { if (c > 0x7F) { - qDebug() << "c > 0x7F"; + qCDebug(appLog) << "c > 0x7F"; charset = "UTF-8"; break; } if (c == 0x1B) /* ESC */ { - qDebug() << "c == 0x1B"; + qCDebug(appLog) << "c == 0x1B"; c = *text++; if (c == '$') { - qDebug() << "c == '$'"; + qCDebug(appLog) << "c == '$'"; c = *text++; switch (c) { case 'B': // JIS X 0208-1983 case '@': // JIS X 0208-1978 - qDebug() << "c == 'B' || c == '@'"; + qCDebug(appLog) << "c == 'B' || c == '@'"; charset = "ISO-2022-JP"; continue; case 'A': // GB2312-1980 - qDebug() << "c == 'A'"; + qCDebug(appLog) << "c == 'A'"; charset = "ISO-2022-JP-2"; break; case '(': @@ -769,7 +770,7 @@ const QString detectCharset (const QByteArray& byteArray) { case 'C': // KSC5601-1987 case 'D': // JIS X 0212-1990 - qDebug() << "c == 'C' || c == 'D'"; + qCDebug(appLog) << "c == 'C' || c == 'D'"; charset = "ISO-2022-JP-2"; } break; @@ -777,7 +778,7 @@ const QString detectCharset (const QByteArray& byteArray) c = *text++; if (c == 'C') { - qDebug() << "c == 'C'"; + qCDebug(appLog) << "c == 'C'"; charset = "ISO-2022-KR"; // KSC5601-1987 } } @@ -787,79 +788,79 @@ const QString detectCharset (const QByteArray& byteArray) } if (charset.empty()) { - qDebug() << "charset is empty"; + qCDebug(appLog) << "charset is empty"; charset = getDefaultCharset(); } } if (charset.empty()) { - qDebug() << "charset is empty"; + qCDebug(appLog) << "charset is empty"; switch (localeNum) { case LATIN1: /* Windows-1252 */ - qDebug() << "LATIN1"; + qCDebug(appLog) << "LATIN1"; charset = detectCharsetLatin (text); break; case LATINC: case LATINC_UA: case LATINC_TJ: /* Cyrillic */ - qDebug() << "Cyrillic"; + qCDebug(appLog) << "Cyrillic"; charset = detectCharsetCyrillic (text); break; case LATINA: /* MS Windows Arabic */ - qDebug() << "MS Windows Arabic"; + qCDebug(appLog) << "MS Windows Arabic"; charset = detectCharsetWinArabic (text); break; case CHINESE_CN: case CHINESE_TW: case CHINESE_HK: - qDebug() << "Chinese"; + qCDebug(appLog) << "Chinese"; charset = detectCharsetChinese (text); break; case JAPANESE: - qDebug() << "Japanese"; + qCDebug(appLog) << "Japanese"; charset = detectCharsetJapanese (text); break; case KOREAN: - qDebug() << "Korean"; + qCDebug(appLog) << "Korean"; charset = detectCharsetKorean (text); break; case VIETNAMESE: case THAI: case GEORGIAN: - qDebug() << "Vietnamese, Thai, Georgian"; + qCDebug(appLog) << "Vietnamese, Thai, Georgian"; charset = encodingItem[OPENI18N]; break; default: - qDebug() << "default"; + qCDebug(appLog) << "default"; if (getDefaultCharset() != "UTF-8") { - qDebug() << "getDefaultCharset() != 'UTF-8'"; + qCDebug(appLog) << "getDefaultCharset() != 'UTF-8'"; charset = getDefaultCharset(); } else if (detect_noniso (text)) { - qDebug() << "detect_noniso is true"; + qCDebug(appLog) << "detect_noniso is true"; charset = encodingItem[CODEPAGE]; } else { - qDebug() << "detect_noniso is false"; + qCDebug(appLog) << "detect_noniso is false"; charset = encodingItem[OPENI18N]; } if (charset.empty()) { - qDebug() << "charset is empty"; + qCDebug(appLog) << "charset is empty"; charset = encodingItem[IANA]; } } } - qDebug() << "Leaving detectCharset, returning charset:" << charset.c_str(); + qCDebug(appLog) << "Leaving detectCharset, returning charset:" << charset.c_str(); return QString::fromStdString (charset); } diff --git a/src/common/eventlogutils.cpp b/src/common/eventlogutils.cpp index fda4f71ae..397e80c62 100644 --- a/src/common/eventlogutils.cpp +++ b/src/common/eventlogutils.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2022-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "eventlogutils.h" #include #include @@ -12,7 +13,7 @@ Eventlogutils *Eventlogutils::m_pInstance = nullptr; Eventlogutils *Eventlogutils::GetInstance() { - qDebug() << "Eventlogutils::GetInstance()"; + qCDebug(appLog) << "Eventlogutils::GetInstance()"; if (m_pInstance == nullptr) { m_pInstance = new Eventlogutils(); } @@ -22,7 +23,7 @@ Eventlogutils *Eventlogutils::GetInstance() void Eventlogutils::writeLogs(QJsonObject &data) { if (!writeEventLogFunc) { - qWarning() << "writeEventLogFunc is not initialized"; + qCWarning(appLog) << "writeEventLogFunc is not initialized"; return; } @@ -31,13 +32,13 @@ void Eventlogutils::writeLogs(QJsonObject &data) Eventlogutils::Eventlogutils() { - qDebug() << "Eventlogutils::Eventlogutils()"; + qCDebug(appLog) << "Eventlogutils::Eventlogutils()"; QLibrary library("libdeepin-event-log.so"); initFunc = reinterpret_cast(library.resolve("Initialize")); writeEventLogFunc = reinterpret_cast(library.resolve("WriteEventLog")); if (!initFunc) { - qWarning() << "Failed to load libdeepin-event-log.so"; + qCWarning(appLog) << "Failed to load libdeepin-event-log.so"; return; } diff --git a/src/common/fileloadthread.cpp b/src/common/fileloadthread.cpp index 78c42b2a2..9ba50fe88 100644 --- a/src/common/fileloadthread.cpp +++ b/src/common/fileloadthread.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "fileloadthread.h" #include "utils.h" #include "../encodes/detectcode.h" @@ -12,12 +13,12 @@ FileLoadThread::FileLoadThread(const QString &filepath, QObject *parent) : QThread(parent), m_strFilePath(filepath) { - qDebug() << "Creating FileLoadThread for file:" << filepath; + qCDebug(appLog) << "Creating FileLoadThread for file:" << filepath; } FileLoadThread::~FileLoadThread() { - qDebug() << "Destroying FileLoadThread for file:" << m_strFilePath; + qCDebug(appLog) << "Destroying FileLoadThread for file:" << m_strFilePath; } void FileLoadThread::setEncodeHint(const QByteArray &encode) @@ -27,7 +28,7 @@ void FileLoadThread::setEncodeHint(const QByteArray &encode) void FileLoadThread::run() { - qDebug() << "Starting file load thread for:" << m_strFilePath; + qCDebug(appLog) << "Starting file load thread for:" << m_strFilePath; QFile file(m_strFilePath); if (file.open(QIODevice::ReadOnly)) { @@ -37,7 +38,7 @@ void FileLoadThread::run() // 判断文件大小是否超过40MB, 超过40MB的文件过大,需要调整读取策略,优先加载头部文件 static const int s_maxDirectReadLen = 40 * DATA_SIZE_1024 * DATA_SIZE_1024; if (file.size() > s_maxDirectReadLen) { - qDebug() << "Large file detected (" << file.size() << " bytes), using optimized loading strategy"; + qCDebug(appLog) << "Large file detected (" << file.size() << " bytes), using optimized loading strategy"; // 先读取1MB数据 indata = file.read(DATA_SIZE_1024 * DATA_SIZE_1024); if (!m_encodeHint.isEmpty()) { @@ -45,7 +46,7 @@ void FileLoadThread::run() } else { encode = DetectCode::GetFileEncodingFormat(m_strFilePath, indata); } - qDebug() << "Initial encoding detection result:" << encode; + qCDebug(appLog) << "Initial encoding detection result:" << encode; // 发送文件头信息,用于预先加载数据 QString textEncode = QString::fromLocal8Bit(encode); @@ -69,7 +70,7 @@ void FileLoadThread::run() // 读取申请开辟内存空间时,捕获可能出现的 std::bad_alloc() 异常,防止闪退。 try { - qDebug() << "Reading remaining file content"; + qCDebug(appLog) << "Reading remaining file content"; // reads all remaining data from the file. // 对于 /proc、/sys 等虚拟文件,file.size() 返回 0 但实际有内容, // 需要使用 readAll() 来正确读取。 @@ -79,9 +80,9 @@ void FileLoadThread::run() indata += file.read(file.size()); } file.close(); - qDebug() << "Total bytes read:" << indata.size(); + qCDebug(appLog) << "Total bytes read:" << indata.size(); } catch (const std::exception &e) { - qWarning() << "FileLoadThread read error:" << e.what() << "at" << m_strFilePath; + qCWarning(appLog) << "FileLoadThread read error:" << e.what() << "at" << m_strFilePath; file.close(); emit sigLoadFinished(encode, indata, true, false); @@ -95,15 +96,15 @@ void FileLoadThread::run() // NUL 字节检测与转义:将每个 \x00 替换为三个 ASCII 字符 \00 bool hasNul = indata.contains('\x00'); if (hasNul) { - qDebug() << "NUL bytes detected in file, escaping to \\00"; + qCDebug(appLog) << "NUL bytes detected in file, escaping to \\00"; indata.replace('\x00', "\\00"); } if (!m_encodeHint.isEmpty()) { - qDebug() << "Using encoding hint:" << m_encodeHint; + qCDebug(appLog) << "Using encoding hint:" << m_encodeHint; encode = m_encodeHint; } else if (encode.isEmpty()) { - qDebug() << "Performing full encoding detection"; + qCDebug(appLog) << "Performing full encoding detection"; //编码识别,如果文件数据大于1M,则只裁剪出1M文件数据去做编码探测 QByteArray dateUsedForCodeIdentify; if (indata.length() > DATA_SIZE_1024 * DATA_SIZE_1024) { @@ -115,24 +116,24 @@ void FileLoadThread::run() } QString textEncode = QString::fromLocal8Bit(encode); - qDebug() << "Final encoding detected:" << textEncode; + qCDebug(appLog) << "Final encoding detected:" << textEncode; if (textEncode.contains("ASCII", Qt::CaseInsensitive) || textEncode.contains("UTF-8", Qt::CaseInsensitive)) { - qDebug() << "Using original encoding, no conversion needed"; + qCDebug(appLog) << "Using original encoding, no conversion needed"; emit sigLoadFinished(encode, indata, false, hasNul); } else { - qDebug() << "Converting from" << textEncode << "to UTF-8"; + qCDebug(appLog) << "Converting from" << textEncode << "to UTF-8"; QByteArray outData; DetectCode::ChangeFileEncodingFormat(indata, outData, textEncode, QString("UTF-8")); emit sigLoadFinished(encode, outData, false, hasNul); - qDebug() << "Encoding conversion completed, output size:" << outData.size(); + qCDebug(appLog) << "Encoding conversion completed, output size:" << outData.size(); } } else { - qWarning() << "Failed to open file:" << m_strFilePath << "error:" << file.errorString(); + qCWarning(appLog) << "Failed to open file:" << m_strFilePath << "error:" << file.errorString(); emit sigLoadFinished("", "", true, false); } - qDebug() << "FileLoadThread finished processing:" << m_strFilePath; + qCDebug(appLog) << "FileLoadThread finished processing:" << m_strFilePath; this->quit(); this->deleteLater(); - qDebug() << "FileLoadThread resources cleaned up"; + qCDebug(appLog) << "FileLoadThread resources cleaned up"; } diff --git a/src/common/iflytek_ai_assistant.cpp b/src/common/iflytek_ai_assistant.cpp index c9f37ca7f..fb02d8281 100644 --- a/src/common/iflytek_ai_assistant.cpp +++ b/src/common/iflytek_ai_assistant.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "iflytek_ai_assistant.h" #include @@ -53,29 +54,29 @@ class AudioDeviceDetector { * @return 是否有可用设备 */ static bool hasEnabledPorts(PortDirection direction) { - qDebug() << "Checking audio device availability for direction:" << direction; + qCDebug(appLog) << "Checking audio device availability for direction:" << direction; QDBusInterface audioInter(AUDIO_SERVICE, AUDIO_PATH, AUDIO_INTERFACE, QDBusConnection::sessionBus()); if (!audioInter.isValid()) { - qWarning() << "Failed to connect to DDE Audio service:" << audioInter.lastError().message(); + qCWarning(appLog) << "Failed to connect to DDE Audio service:" << audioInter.lastError().message(); return false; } // 获取声卡信息 QVariant cardsVariant = audioInter.property("CardsWithoutUnavailable"); if (!cardsVariant.isValid()) { - qWarning() << "Failed to get CardsWithoutUnavailable property"; + qCWarning(appLog) << "Failed to get CardsWithoutUnavailable property"; return false; } QString cardsJson = cardsVariant.toString(); - qDebug() << "Cards JSON:" << cardsJson; + qCDebug(appLog) << "Cards JSON:" << cardsJson; QJsonParseError parseError; QJsonDocument cardsDoc = QJsonDocument::fromJson(cardsJson.toUtf8(), &parseError); if (parseError.error != QJsonParseError::NoError) { - qWarning() << "Failed to parse cards JSON:" << parseError.errorString(); + qCWarning(appLog) << "Failed to parse cards JSON:" << parseError.errorString(); return false; } @@ -101,12 +102,12 @@ class AudioDeviceDetector { QJsonValue portsValue = cardObj["Ports"]; if (portsValue.isNull()) { - qDebug() << "Card" << cardName << "has no ports, skipping"; + qCDebug(appLog) << "Card" << cardName << "has no ports, skipping"; continue; } QJsonArray portsArray = portsValue.toArray(); - qDebug() << "Checking card:" << cardName << "(ID:" << cardId << ") with" << portsArray.size() << "ports"; + qCDebug(appLog) << "Checking card:" << cardName << "(ID:" << cardId << ") with" << portsArray.size() << "ports"; // 遍历该声卡的所有端口 for (const QJsonValue &portValue : portsArray) { @@ -117,13 +118,13 @@ class AudioDeviceDetector { // 检查是否为目标方向且启用的端口 if (portDirection == direction && enabled) { - qDebug() << "Found enabled" << directionName << "port:" << portId << "on card:" << cardName; + qCDebug(appLog) << "Found enabled" << directionName << "port:" << portId << "on card:" << cardName; enabledPorts++; } } } - qDebug() << "Total enabled" << directionName << "ports:" << enabledPorts; + qCDebug(appLog) << "Total enabled" << directionName << "ports:" << enabledPorts; return enabledPorts; } }; @@ -141,7 +142,7 @@ IflytekAiAssistant::IflytekAiAssistant(QObject *parent) : QObject(parent) , m_copilot{new QDBusInterface(kCopilotService, kCopilotPath, kCopilotInterface)} { - qDebug() << "IflytekAiAssistant created"; + qCDebug(appLog) << "IflytekAiAssistant created"; m_copilot->setTimeout(2000); } @@ -167,12 +168,12 @@ IflytekAiAssistant *IflytekAiAssistant::instance() */ IflytekAiAssistant::CallStatus IflytekAiAssistant::checkValid() { - qDebug() << "checkValid status:" << m_status; + qCDebug(appLog) << "checkValid status:" << m_status; switch (m_status) { case NotInstalled: m_status = copilotInstalled(m_copilot); if (Enable != m_status) { - qDebug() << "status is not enable!";; + qCDebug(appLog) << "status is not enable!";; break; } // If detect installed first, detect the user argreement is valid. @@ -181,10 +182,10 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::checkValid() // Detect current state every call m_status = isCopilotEnabled(m_copilot); if (NoUserAgreement == m_status) { - qDebug() << "user agreement not agreed!"; + qCDebug(appLog) << "user agreement not agreed!"; // 感知拉起结果,失败时输出告警日志,便于问题定位 if (launchCopilotChat(m_copilot) != Enable) { - qWarning() << "Launch copilot chat window failed!"; + qCWarning(appLog) << "Launch copilot chat window failed!"; } } } break; @@ -192,14 +193,14 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::checkValid() break; } - qDebug() << "checkValid status, return:" << m_status; + qCDebug(appLog) << "checkValid status, return:" << m_status; return m_status; } IflytekAiAssistant::CallStatus IflytekAiAssistant::isTtsInWorking() const { if (Enable != status()) { - qDebug() << "status is not enable!"; + qCDebug(appLog) << "status is not enable!"; return status(); } @@ -208,7 +209,7 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::isTtsInWorking() const QDBusReply ret = interface.call("isTTSInWorking"); if (ret.isValid()) { - qDebug() << "isTtsInWorking ret:" << ret.value(); + qCDebug(appLog) << "isTtsInWorking ret:" << ret.value(); return ret.value() ? Enable : Disable; } return Invalid; @@ -217,13 +218,13 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::isTtsInWorking() const IflytekAiAssistant::CallStatus IflytekAiAssistant::isTtsEnable() const { if (Enable != status()) { - qDebug() << "status is not enable!"; + qCDebug(appLog) << "status is not enable!"; return status(); } // 首先检查音频输出设备是否存在 if (!hasAudioOutputDevice()) { - qDebug() << "No audio output device available"; + qCDebug(appLog) << "No audio output device available"; return NoOutputDevice; } @@ -232,7 +233,7 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::isTtsEnable() const QDBusReply ret = interface.call("getTTSEnable"); if (ret.isValid()) { - qDebug() << "getTTSEnable ret:" << ret.value(); + qCDebug(appLog) << "getTTSEnable ret:" << ret.value(); return ret.value() ? Enable : Disable; } return Invalid; @@ -241,20 +242,20 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::isTtsEnable() const IflytekAiAssistant::CallStatus IflytekAiAssistant::textToSpeech() { if (Enable != checkValid()) { - qDebug() << "checkValid failed!"; + qCDebug(appLog) << "checkValid failed!"; return status(); } CallStatus ret = isTtsEnable(); if (Enable != ret) { - qDebug() << "no output device!"; + qCDebug(appLog) << "no output device!"; return NoOutputDevice; } // playing, stop first if (isTtsInWorking()) { if (Success != stopTtsDirectlyInternal()) { - qWarning() << "stopTtsDirectlyInternal failed!"; + qCWarning(appLog) << "stopTtsDirectlyInternal failed!"; return Failed; } } @@ -262,7 +263,7 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::textToSpeech() QDBusInterface interface(copilotService(), "/aiassistant/deepinmain", "com.iflytek.aiassistant.mainWindow"); interface.asyncCall("TextToSpeech"); - qDebug() << "textToSpeech success!"; + qCDebug(appLog) << "textToSpeech success!"; return Success; } @@ -270,10 +271,10 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::stopTtsDirectly() const { // BUG-301561 : disable stop tts when close tab or window #ifdef ENABLE_STOP_TTS - qDebug() << "ENABLE_STOP_TTS is defined!"; + qCDebug(appLog) << "ENABLE_STOP_TTS is defined!"; return stopTtsDirectlyInternal(); #else - qDebug() << "ENABLE_STOP_TTS is not defined!, return Enable"; + qCDebug(appLog) << "ENABLE_STOP_TTS is not defined!, return Enable"; return Enable; #endif } @@ -281,26 +282,26 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::stopTtsDirectly() const IflytekAiAssistant::CallStatus IflytekAiAssistant::stopTtsDirectlyInternal() const { if (Enable != status()) { - qDebug() << "status is not enable!"; + qCDebug(appLog) << "status is not enable!"; return status(); } QDBusInterface interface(copilotService(), "/aiassistant/tts", "com.iflytek.aiassistant.tts"); interface.asyncCall("stopTTSDirectly"); - qDebug() << "stopTtsDirectly success!"; + qCDebug(appLog) << "stopTtsDirectly success!"; return Success; } IflytekAiAssistant::CallStatus IflytekAiAssistant::getIatEnable() const { if (Enable != status()) { - qDebug() << "status is not enable!"; + qCDebug(appLog) << "status is not enable!"; return status(); } // 首先检查音频输入设备是否存在 if (!hasAudioInputDevice()) { - qDebug() << "No audio input device available"; + qCDebug(appLog) << "No audio input device available"; return NoInputDevice; } @@ -309,7 +310,7 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::getIatEnable() const QDBusReply ret = interface.call("getIatEnable"); if (ret.isValid()) { - qDebug() << "getIatEnable ret:" << ret.value(); + qCDebug(appLog) << "getIatEnable ret:" << ret.value(); return ret.value() ? Enable : Disable; } return Invalid; @@ -318,27 +319,27 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::getIatEnable() const IflytekAiAssistant::CallStatus IflytekAiAssistant::speechToText() { if (Enable != checkValid()) { - qDebug() << "checkValid failed!"; + qCDebug(appLog) << "checkValid failed!"; return status(); } CallStatus ret = getIatEnable(); if (Enable != ret) { - qDebug() << "no input device!"; + qCDebug(appLog) << "no input device!"; return NoInputDevice; } QDBusInterface interface(copilotService(), "/aiassistant/deepinmain", "com.iflytek.aiassistant.mainWindow"); interface.asyncCall("SpeechToText"); - qDebug() << "speechToText success!"; + qCDebug(appLog) << "speechToText success!"; return Success; } IflytekAiAssistant::CallStatus IflytekAiAssistant::getTransEnable() const { if (Enable != status()) { - qDebug() << "status is not enable!"; + qCDebug(appLog) << "status is not enable!"; return status(); } @@ -347,36 +348,36 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::getTransEnable() const QDBusReply ret = interface.call("getTransEnable"); if (ret.isValid()) { - qDebug() << "getTransEnable ret:" << ret.value(); + qCDebug(appLog) << "getTransEnable ret:" << ret.value(); return ret.value() ? Enable : Disable; } - qDebug() << "getTransEnable failed! return Invalid"; + qCDebug(appLog) << "getTransEnable failed! return Invalid"; return Invalid; } IflytekAiAssistant::CallStatus IflytekAiAssistant::textToTranslate() { if (Enable != checkValid()) { - qDebug() << "checkValid failed!"; + qCDebug(appLog) << "checkValid failed!"; return status(); } CallStatus ret = getTransEnable(); if (Enable != ret) { - qWarning() << "getTransEnable is not enable!"; + qCWarning(appLog) << "getTransEnable is not enable!"; return Invalid; } QDBusInterface interface(copilotService(), "/aiassistant/deepinmain", "com.iflytek.aiassistant.mainWindow"); interface.asyncCall("TextToTranslate"); - qDebug() << "textToTranslate success!"; + qCDebug(appLog) << "textToTranslate success!"; return Success; } QString IflytekAiAssistant::errorString(CallStatus ret) const { - qDebug() << "errorString ret:" << ret; + qCDebug(appLog) << "errorString ret:" << ret; switch (ret) { case NotInstalled: return QObject::tr("Please install 'UOS AI' from the App Store before using"); @@ -386,7 +387,7 @@ QString IflytekAiAssistant::errorString(CallStatus ret) const return QObject::tr("No audio output device detected. Please check and try again"); default: // Unknown error - qDebug() << "unknown error ret:" << ret; + qCDebug(appLog) << "unknown error ret:" << ret; return {}; } } @@ -395,11 +396,11 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::copilotInstalled(const QShare { QDBusReply version = copilot->call("version"); if (version.isValid()) { - qInfo() << "current uos-ai version:" << version.value(); + qCInfo(appLog) << "current uos-ai version:" << version.value(); return Enable; } - qWarning() << "Query uos-ai installed faild! Maybe need install"; + qCWarning(appLog) << "Query uos-ai installed faild! Maybe need install"; return NotInstalled; } @@ -411,12 +412,12 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::isCopilotEnabled(const QShare { QDBusReply state = copilot->call("isCopilotEnabled"); if (state.isValid()) { - qDebug() << "current uos-ai user exp state:" << state.value(); + qCDebug(appLog) << "current uos-ai user exp state:" << state.value(); return state.value() ? Enable : NoUserAgreement; } // NOTE: Adapt old version, if dbus interface not valid, assume the user agreement agreed. - qWarning() << "Query uos-ai user exp state failed!" << state.error().message(); + qCWarning(appLog) << "Query uos-ai user exp state failed!" << state.error().message(); return Enable; } @@ -427,7 +428,7 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::launchCopilotChat(const QShar { QDBusMessage message = copilot->call("launchChatPage"); if (!message.errorMessage().isEmpty()) { - qWarning() << "Launch uos-ai chat page failed!" << message.errorMessage(); + qCWarning(appLog) << "Launch uos-ai chat page failed!" << message.errorMessage(); return Disable; } @@ -436,7 +437,7 @@ IflytekAiAssistant::CallStatus IflytekAiAssistant::launchCopilotChat(const QShar void IflytekAiAssistant::checkAiExists() { - qDebug() << "checkAiExists status:" << m_status; + qCDebug(appLog) << "checkAiExists status:" << m_status; static std::once_flag kAiFlag; std::call_once(kAiFlag, [this]() { QtConcurrent::run([this]() { @@ -447,7 +448,7 @@ void IflytekAiAssistant::checkAiExists() status = IflytekAiAssistant::isCopilotEnabled(copilot); } - qInfo() << QString("backend uos-ai status: %1(%2)").arg(Enable == status).arg(status); + qCInfo(appLog) << QString("backend uos-ai status: %1(%2)").arg(Enable == status).arg(status); // call on non-gui thread, so queued connection. QMetaObject::invokeMethod( diff --git a/src/common/performancemonitor.cpp b/src/common/performancemonitor.cpp index bf622dbd1..ef903786a 100644 --- a/src/common/performancemonitor.cpp +++ b/src/common/performancemonitor.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "performancemonitor.h" #include @@ -20,54 +21,54 @@ qint64 PerformanceMonitor::openFileFinishMs = 0; PerformanceMonitor::PerformanceMonitor() { - qDebug() << "PerformanceMonitor instance created"; + qCDebug(appLog) << "PerformanceMonitor instance created"; } void PerformanceMonitor::initializeAppStart() { QDateTime current = QDateTime::currentDateTime(); - qDebug() << qPrintable(LOG_FLAG) + qCDebug(appLog) << qPrintable(LOG_FLAG) << QDateTime::currentDateTime().toString(Qt::ISODateWithMs) << "start to initialize app"; initializeAppStartMs = current.toMSecsSinceEpoch(); - qDebug() << "Application start timestamp recorded:" << initializeAppStartMs; + qCDebug(appLog) << "Application start timestamp recorded:" << initializeAppStartMs; } void PerformanceMonitor::initializeAppFinish() { QDateTime current = QDateTime::currentDateTime(); - qDebug() << qPrintable(LOG_FLAG) + qCDebug(appLog) << qPrintable(LOG_FLAG) << QDateTime::currentDateTime().toString(Qt::ISODateWithMs) << " finish to initialize app"; inittalizeApoFinishMs = current.toMSecsSinceEpoch(); qint64 time = inittalizeApoFinishMs - initializeAppStartMs; - qInfo() << qPrintable(QString("%1 startduration=%2ms #(Init app time)").arg(GRAB_POINT_INIT_APP_TIME).arg(time)); + qCInfo(appLog) << qPrintable(QString("%1 startduration=%2ms #(Init app time)").arg(GRAB_POINT_INIT_APP_TIME).arg(time)); } void PerformanceMonitor::closeAppStart() { QDateTime current = QDateTime::currentDateTime(); closeAppStartMs = current.toMSecsSinceEpoch(); - qDebug() << "Application close process started, timestamp:" << closeAppStartMs; + qCDebug(appLog) << "Application close process started, timestamp:" << closeAppStartMs; } void PerformanceMonitor::closeAppFinish() { QDateTime current = QDateTime::currentDateTime(); - qDebug() << qPrintable(LOG_FLAG) + qCDebug(appLog) << qPrintable(LOG_FLAG) << QDateTime::currentDateTime().toString(Qt::ISODateWithMs) << " finish to close app"; closeAppFinishMs = current.toMSecsSinceEpoch(); qint64 time = closeAppFinishMs - closeAppStartMs; - qInfo() << qPrintable(QString("%1 closeduration=%2ms #(Close app time)").arg(GRAB_POINT_CLOSE_APP_TIME).arg(time)); + qCInfo(appLog) << qPrintable(QString("%1 closeduration=%2ms #(Close app time)").arg(GRAB_POINT_CLOSE_APP_TIME).arg(time)); } void PerformanceMonitor::openFileStart() { QDateTime current = QDateTime::currentDateTime(); - qDebug() << qPrintable(LOG_FLAG) + qCDebug(appLog) << qPrintable(LOG_FLAG) << QDateTime::currentDateTime().toString(Qt::ISODateWithMs) << "start to open file"; openFileStartMs = current.toMSecsSinceEpoch(); @@ -76,12 +77,12 @@ void PerformanceMonitor::openFileStart() void PerformanceMonitor::openFileFinish(const QString &strFileName, qint64 iFileSize) { QDateTime current = QDateTime::currentDateTime(); - qDebug() << qPrintable(LOG_FLAG) + qCDebug(appLog) << qPrintable(LOG_FLAG) << QDateTime::currentDateTime().toString(Qt::ISODateWithMs) << " finish to open file"; openFileFinishMs = current.toMSecsSinceEpoch(); qint64 time = openFileFinishMs - openFileStartMs; float fFilesize = iFileSize; - qInfo() << qPrintable(QString("%1 filename=%2 filesize=%3M opentime=%4ms #(Open file time)").arg(GRAB_POINT_OPEN_FILE_TIME).arg(strFileName).arg(QString::number(fFilesize/(1024*1024), 'f', 6)).arg(time)); + qCInfo(appLog) << qPrintable(QString("%1 filename=%2 filesize=%3M opentime=%4ms #(Open file time)").arg(GRAB_POINT_OPEN_FILE_TIME).arg(strFileName).arg(QString::number(fFilesize/(1024*1024), 'f', 6)).arg(time)); } diff --git a/src/common/settings.cpp b/src/common/settings.cpp index 2cfcfed5c..1162cc58b 100644 --- a/src/common/settings.cpp +++ b/src/common/settings.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "utils.h" #include "settings.h" @@ -27,79 +28,79 @@ CustemBackend::CustemBackend(const QString &filepath, QObject *parent) : DSettingsBackend (parent), m_settings (new QSettings(filepath, QSettings::IniFormat)) { - qDebug() << "CustemBackend::CustemBackend" << filepath; + qCDebug(appLog) << "CustemBackend::CustemBackend" << filepath; } void CustemBackend::doSync() { - qDebug() << "Entering CustemBackend::doSync"; + qCDebug(appLog) << "Entering CustemBackend::doSync"; m_settings->sync(); - qDebug() << "Leaving CustemBackend::doSync"; + qCDebug(appLog) << "Leaving CustemBackend::doSync"; } void CustemBackend::doSetOption(const QString &key, const QVariant &value) { - qDebug() << "CustemBackend::doSetOption" << key << value; + qCDebug(appLog) << "CustemBackend::doSetOption" << key << value; /* * 将配置值写入config配置文件 * 为了规避数据写入重复或者错乱,配置写入之前上锁,写入结束后开锁 */ m_writeLock.lock(); - qDebug() << "Write lock acquired"; + qCDebug(appLog) << "Write lock acquired"; m_settings->setValue(key, value); m_settings->sync(); m_writeLock.unlock(); - qDebug() << "Write lock released. Leaving CustemBackend::doSetOption"; + qCDebug(appLog) << "Write lock released. Leaving CustemBackend::doSetOption"; } QStringList CustemBackend::keys() const { - qDebug() << "Entering CustemBackend::keys"; + qCDebug(appLog) << "Entering CustemBackend::keys"; QStringList keyList = m_settings->allKeys(); - qDebug() << "Leaving CustemBackend::keys, returning:" << keyList; + qCDebug(appLog) << "Leaving CustemBackend::keys, returning:" << keyList; return keyList; } QVariant CustemBackend::getOption(const QString &key) const { - qDebug() << "Entering CustemBackend::getOption, key:" << key; + qCDebug(appLog) << "Entering CustemBackend::getOption, key:" << key; QVariant value = m_settings->value(key); - qDebug() << "Leaving CustemBackend::getOption, returning value:" << value; + qCDebug(appLog) << "Leaving CustemBackend::getOption, returning value:" << value; return value; } CustemBackend::~CustemBackend() { - qDebug() << "Entering CustemBackend::~CustemBackend"; + qCDebug(appLog) << "Entering CustemBackend::~CustemBackend"; delete m_settings; - qDebug() << "Leaving CustemBackend::~CustemBackend"; + qCDebug(appLog) << "Leaving CustemBackend::~CustemBackend"; } Settings::Settings(QWidget *parent) : QObject(parent) { - qDebug() << "Initializing Settings instance"; + qCDebug(appLog) << "Initializing Settings instance"; QString strConfigPath = QString("%1/%2/%3/config.conf") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) .arg(qApp->organizationName()) .arg(qApp->applicationName()); - qDebug() << "Config file path:" << strConfigPath; + qCDebug(appLog) << "Config file path:" << strConfigPath; removeLockFiles(); m_backend = new QSettingBackend(strConfigPath); - qDebug() << "Created QSettingBackend for config file"; + qCDebug(appLog) << "Created QSettingBackend for config file"; settings = DSettings::fromJsonFile(":/resources/settings.json"); if (!settings) { - qWarning() << "Failed to load settings from JSON file"; + qCWarning(appLog) << "Failed to load settings from JSON file"; return; } settings->setBackend(m_backend); - qInfo() << "Settings initialized successfully"; + qCInfo(appLog) << "Settings initialized successfully"; - qDebug() << "Connecting settings signals to slots"; + qCDebug(appLog) << "Connecting settings signals to slots"; auto fontFamliy = settings->option("base.font.family"); connect(fontFamliy, &Dtk::Core::DSettingsOption::valueChanged, this, &Settings::slotsigAdjustFont); @@ -155,86 +156,86 @@ Settings::Settings(QWidget *parent) windowState->setData("items", windowStateMap); connect(settings, &Dtk::Core::DSettings::valueChanged, this, &Settings::slotCustomshortcut); - qDebug() << "Leaving Settings::Settings"; + qCDebug(appLog) << "Leaving Settings::Settings"; } void Settings::setSavePath(int id,const QString& path) { - qDebug() << "Entering setSavePath for id:" << id << "path:" << path; + qCDebug(appLog) << "Entering setSavePath for id:" << id << "path:" << path; switch (id) { case PathSettingWgt::LastOptBox:{ - qDebug() << "Setting LastOptBox path"; + qCDebug(appLog) << "Setting LastOptBox path"; auto opt = settings->option("advance.open_save_setting.open_save_lastopt_path"); opt->setValue(path); break; } case PathSettingWgt::CurFileBox:{ - qDebug() << "Setting CurFileBox path"; + qCDebug(appLog) << "Setting CurFileBox path"; auto opt = settings->option("advance.open_save_setting.open_save_curfile_path"); opt->setValue(path); break; } case PathSettingWgt::CustomBox:{ - qDebug() << "Setting CustomBox path"; + qCDebug(appLog) << "Setting CustomBox path"; auto opt = settings->option("advance.open_save_setting.open_save_custom_path"); opt->setValue(path); break; } default: - qWarning() << "Unknown id in setSavePath:" << id; + qCWarning(appLog) << "Unknown id in setSavePath:" << id; break; } - qDebug() << "Leaving setSavePath"; + qCDebug(appLog) << "Leaving setSavePath"; } QString Settings::getSavePath(int id) { - qDebug() << "Entering getSavePath for id:" << id; + qCDebug(appLog) << "Entering getSavePath for id:" << id; QString path; switch (id) { case PathSettingWgt::LastOptBox:{ - qDebug() << "Getting LastOptBox path"; + qCDebug(appLog) << "Getting LastOptBox path"; path = settings->option("advance.open_save_setting.open_save_lastopt_path")->value().toString(); break; } case PathSettingWgt::CurFileBox:{ - qDebug() << "Getting CurFileBox path"; + qCDebug(appLog) << "Getting CurFileBox path"; path = settings->option("advance.open_save_setting.open_save_curfile_path")->value().toString(); break; } case PathSettingWgt::CustomBox:{ - qDebug() << "Getting CustomBox path"; + qCDebug(appLog) << "Getting CustomBox path"; path = settings->option("advance.open_save_setting.open_save_custom_path")->value().toString(); break; } default: - qWarning() << "Unknown id in getSavePath:" << id; + qCWarning(appLog) << "Unknown id in getSavePath:" << id; break; } - qDebug() << "Leaving getSavePath, returning:" << path; + qCDebug(appLog) << "Leaving getSavePath, returning:" << path; return path; } void Settings::setSavePathId(int id) { - qDebug() << "Entering setSavePathId, id:" << id; + qCDebug(appLog) << "Entering setSavePathId, id:" << id; auto opt = settings->option("advance.open_save_setting.savingpathwgt"); opt->setValue(QString::number(id)); - qDebug() << "Leaving setSavePathId. Save path ID set to:" << opt->value(); + qCDebug(appLog) << "Leaving setSavePathId. Save path ID set to:" << opt->value(); } int Settings::getSavePathId() { - qDebug() << "Entering getSavePathId"; + qCDebug(appLog) << "Entering getSavePathId"; int id = settings->option("advance.open_save_setting.savingpathwgt")->value().toInt(); - qDebug() << "Leaving getSavePathId, returning:" << id; + qCDebug(appLog) << "Leaving getSavePathId, returning:" << id; return id; } Settings::~Settings() { - qDebug() << "Destroying Settings instance"; + qCDebug(appLog) << "Destroying Settings instance"; // 单例被销毁后置空,避免 instance() 返回悬空指针(测试中可能 deleteLater 单例) if (s_pSetting == this) { s_pSetting = nullptr; @@ -250,41 +251,41 @@ Settings::~Settings() settings = nullptr; } if (m_backend != nullptr) { - qDebug() << "Cleaning up settings backend"; + qCDebug(appLog) << "Cleaning up settings backend"; delete m_backend; m_backend = nullptr; } - qDebug() << "Settings instance destroyed"; + qCDebug(appLog) << "Settings instance destroyed"; } void Settings::setSettingDialog(DSettingsDialog *settingsDialog) { - qDebug() << "Setting dialog instance"; + qCDebug(appLog) << "Setting dialog instance"; m_pSettingsDialog = settingsDialog; } // This function is workaround, it will remove after DTK fixed SettingDialog theme bug. void Settings::dtkThemeWorkaround(QWidget *parent, const QString &theme) { - qDebug() << "Entering dtkThemeWorkaround, theme:" << theme; + qCDebug(appLog) << "Entering dtkThemeWorkaround, theme:" << theme; parent->setStyle(QStyleFactory::create(theme)); - qDebug() << "Theme applied to parent widget:" << parent->objectName(); + qCDebug(appLog) << "Theme applied to parent widget:" << parent->objectName(); for (auto obj : parent->children()) { auto w = qobject_cast(obj); if (!w) { - qDebug() << "w is null"; + qCDebug(appLog) << "w is null"; continue; } - qDebug() << "w is not null"; + qCDebug(appLog) << "w is not null"; dtkThemeWorkaround(w, theme); } - qDebug() << "Leaving dtkThemeWorkaround for parent:" << parent->objectName(); + qCDebug(appLog) << "Leaving dtkThemeWorkaround for parent:" << parent->objectName(); } QPair Settings::createFontComBoBoxHandle(QObject *obj) { - qDebug() << "Entering createFontComBoBoxHandle"; + qCDebug(appLog) << "Entering createFontComBoBoxHandle"; auto option = qobject_cast(obj); QComboBox *comboBox = new QComboBox; @@ -296,7 +297,7 @@ QPair Settings::createFontComBoBoxHandle(QObject *obj) comboBox->setMinimumSize(240, 36); if (option->value().toString().isEmpty()) { - qDebug() << "option->value().toString().isEmpty()"; + qCDebug(appLog) << "option->value().toString().isEmpty()"; option->setValue(QFontDatabase::systemFont(QFontDatabase::FixedFont).family()); } @@ -304,7 +305,7 @@ QPair Settings::createFontComBoBoxHandle(QObject *obj) comboBox->setCurrentText(option->value().toString()); connect(option, &DSettingsOption::valueChanged, comboBox, [ = ](QVariant var) { - qDebug() << "Font family value changed to:" << var.toString(); + qCDebug(appLog) << "Font family value changed to:" << var.toString(); comboBox->setCurrentText(var.toString()); }); @@ -322,13 +323,13 @@ QPair Settings::createFontComBoBoxHandle(QObject *obj) }); #endif - qDebug() << "Leaving createFontComBoBoxHandle"; + qCDebug(appLog) << "Leaving createFontComBoBoxHandle"; return optionWidget; } QWidget* Settings::createSavingPathWgt(QObject* obj) { - qDebug() << "Creating saving path widget"; + qCDebug(appLog) << "Creating saving path widget"; auto option = qobject_cast(obj); QString name = option->name(); PathSettingWgt* pathwgt = new PathSettingWgt; @@ -336,7 +337,7 @@ QWidget* Settings::createSavingPathWgt(QObject* obj) connect(option, &DSettingsOption::valueChanged, pathwgt, [ = ](QVariant var) { int id = var.toInt(); - qDebug() << "pathwgt->onSaveIdChanged" << id; + qCDebug(appLog) << "pathwgt->onSaveIdChanged" << id; pathwgt->onSaveIdChanged(id); }); @@ -345,13 +346,13 @@ QWidget* Settings::createSavingPathWgt(QObject* obj) //pathwgt->setEditText(var.toString()); }); - qDebug() << "Leaving createSavingPathWgt"; + qCDebug(appLog) << "Leaving createSavingPathWgt"; return optionWidget.second; } QPair Settings::createKeySequenceEditHandle(QObject *obj) { - qDebug() << "Entering createKeySequenceEditHandle"; + qCDebug(appLog) << "Entering createKeySequenceEditHandle"; auto option = qobject_cast(obj); KeySequenceEdit *shortCutLineEdit = new KeySequenceEdit(option); @@ -361,9 +362,9 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) // init. shortCutLineEdit->setKeySequence(QKeySequence(option->value().toString())); QPair optionWidget = DSettingsWidgetFactory::createStandardItem(QByteArray(), option, shortCutLineEdit); - qDebug() << "shortCutLineEdit->editingFinished"; + qCDebug(appLog) << "shortCutLineEdit->editingFinished"; option->connect(shortCutLineEdit, &DKeySequenceEdit::editingFinished, [ = ](const QKeySequence & sequence) { - qDebug() << "shortCutLineEdit->editingFinished" << sequence; + qCDebug(appLog) << "shortCutLineEdit->editingFinished" << sequence; QString checkName = option->key(); QString reason; bool bIsConflicts = false; @@ -375,13 +376,13 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) QString defaultKey; auto defaultOption = instance()->settings->option(keySplitList.join(".")); if (defaultOption) { - qDebug() << "defaultOption" << defaultOption->defaultValue().toString(); + qCDebug(appLog) << "defaultOption" << defaultOption->defaultValue().toString(); defaultKey = defaultOption->defaultValue().toString(); } // 判断新设置的组合键序列是否允许 if (!instance()->checkShortcutValid(checkName, sequence.toString(), reason, bIsConflicts, defaultKey)) { - qDebug() << "checkShortcutValid is false"; + qCDebug(appLog) << "checkShortcutValid is false"; instance()->m_pDialog = instance()->createDialog(reason, "", bIsConflicts); instance()->m_pDialog->exec(); // 恢复组合键序列 @@ -391,7 +392,7 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) instance()->settings->option(customizeKeySplitList.join("."))->setValue(currentValidValue); keymap->setValue("emacs"); keymap->setValue("customize"); - qDebug() << "Leaving createKeySequenceEditHandle"; + qCDebug(appLog) << "Leaving createKeySequenceEditHandle"; return; } @@ -400,7 +401,7 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) QString originalKeys; if (keymap->value().toString() != "customize") { - qDebug() << "keymap->value().toString() != customize"; + qCDebug(appLog) << "keymap->value().toString() != customize"; instance()->m_bUserChangeKey = true; for (auto loopOption : instance()->settings->group("shortcuts.window_keymap_customize")->options()) { @@ -408,7 +409,7 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) loopKeySplitList[1] = QString("window_keymap_%1").arg(keymap->value().toString()); if (loopOption->value().toString() == sequence.toString()) { - qDebug() << "loopOption->value().toString() == sequence.toString()"; + qCDebug(appLog) << "loopOption->value().toString() == sequence.toString()"; if (checkName.contains(loopKeySplitList.last())) { keymap->setValue("customize"); //return; @@ -425,7 +426,7 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) loopKeySplitList[1] = QString("editor_keymap_%1").arg(keymap->value().toString()); if (loopOption->value().toString() == sequence.toString()) { - qDebug() << "loopOption->value().toString() == sequence.toString()"; + qCDebug(appLog) << "loopOption->value().toString() == sequence.toString()"; if (checkName.contains(loopKeySplitList.last())) { keymap->setValue("customize"); //return; @@ -446,12 +447,12 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) loopKeySplitList[1] = QString("window_keymap_%1").arg(keymap->value().toString()); if (loopOption->value().toString() == sequence.toString()) { - qDebug() << "loopOption->value().toString() == sequence.toString()"; + qCDebug(appLog) << "loopOption->value().toString() == sequence.toString()"; if (checkName.contains(loopKeySplitList.last())) { - qDebug() << "checkName.contains(loopKeySplitList.last())"; + qCDebug(appLog) << "checkName.contains(loopKeySplitList.last())"; //return; } else { - qDebug() << "loopOption->value().toString() != sequence.toString()"; + qCDebug(appLog) << "loopOption->value().toString() != sequence.toString()"; bIsConflicts = true; conflictsKeys = loopKeySplitList.join("."); } @@ -463,12 +464,12 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) loopKeySplitList[1] = QString("editor_keymap_%1").arg(keymap->value().toString()); if (loopOption->value().toString() == sequence.toString()) { - qDebug() << "loopOption->value().toString() == sequence.toString()"; + qCDebug(appLog) << "loopOption->value().toString() == sequence.toString()"; if (checkName.contains(loopKeySplitList.last())) { - qDebug() << "checkName.contains(loopKeySplitList.last())"; + qCDebug(appLog) << "checkName.contains(loopKeySplitList.last())"; //return; } else { - qDebug() << "loopOption->value().toString() != sequence.toString()"; + qCDebug(appLog) << "loopOption->value().toString() != sequence.toString()"; bIsConflicts = true; conflictsKeys = loopKeySplitList.join("."); } @@ -480,27 +481,27 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) keySplitList = option->key().split("."); keySplitList[1] = QString("%1_keymap_%2").arg(keySplitList[1]).arg(keymap->value().toString()); QString qstrSequence = sequence.toString(); - qDebug() << "qstrSequence" << qstrSequence; + qCDebug(appLog) << "qstrSequence" << qstrSequence; if (sequence.toString().contains("<")) { - qDebug() << "sequence.toString().contains(<)"; + qCDebug(appLog) << "sequence.toString().contains(<)"; qstrSequence.replace(qstrSequence.indexOf("<"), 1, "<"); } if (sequence.toString().contains("Return")) { - qDebug() << "sequence.toString().contains(Return)"; + qCDebug(appLog) << "sequence.toString().contains(Return)"; qstrSequence.replace(qstrSequence.indexOf("Return"), 6, "Enter"); } QString style = QString("[%1]").arg(qstrSequence); if (bIsConflicts || sequence.toString() == "Alt+M") { - qDebug() << "bIsConflicts" << bIsConflicts; + qCDebug(appLog) << "bIsConflicts" << bIsConflicts; if (sequence.toString() == "Alt+M") { - qDebug() << "sequence.toString() == Alt+M"; + qCDebug(appLog) << "sequence.toString() == Alt+M"; instance()->m_pDialog = instance()->createDialog(tr("This shortcut conflicts with system shortcut %1").arg(style), "", bIsConflicts); } else { - qDebug() << "else Alt+M"; + qCDebug(appLog) << "else Alt+M"; instance()->m_pDialog = instance()->createDialog(tr("This shortcut conflicts with %1, click on Replace to make this shortcut effective immediately").arg(style), "", bIsConflicts); } @@ -511,86 +512,86 @@ QPair Settings::createKeySequenceEditHandle(QObject *obj) shortCutLineEdit->setKeySequence(QKeySequence(instance()->settings->value(keySplitList.join(".")).toString())); keymap->setValue("emacs"); keymap->setValue("customize"); - qDebug() << "click cancel button."; + qCDebug(appLog) << "click cancel button."; return; } else { - qDebug() << "click replace button."; + qCDebug(appLog) << "click replace button."; keySplitList = option->key().split("."); keySplitList[1] = QString("%1_keymap_customize").arg(keySplitList[1]); if (!bIsCustomize) { - qDebug() << "!bIsCustomize"; + qCDebug(appLog) << "!bIsCustomize"; instance()->settings->option(keySplitList.join("."))->setValue(sequence.toString()); instance()->settings->option(conflictsKeys)->setValue(""); shortCutLineEdit->setKeySequence(QKeySequence(instance()->settings->value(checkName).toString())); } else { - qDebug() << "bIsCustomize"; + qCDebug(appLog) << "bIsCustomize"; instance()->settings->option(keySplitList.join("."))->setValue(sequence.toString()); instance()->settings->option(conflictsKeys)->setValue(""); } keymap->setValue("emacs"); keymap->setValue("customize"); - qDebug() << "click replace button."; + qCDebug(appLog) << "click replace button."; return; } } if (!bIsCustomize) { - qDebug() << "!bIsCustomize"; + qCDebug(appLog) << "!bIsCustomize"; keySplitList = option->key().split("."); keySplitList[1] = QString("%1_keymap_customize").arg(keySplitList[1]); instance()->settings->option(keySplitList.join("."))->setValue(sequence.toString()); } else { - qDebug() << "bIsCustomize"; + qCDebug(appLog) << "bIsCustomize"; instance()->settings->option(keySplitList.join("."))->setValue(sequence.toString()); } keymap->setValue("emacs"); keymap->setValue("customize"); - qDebug() << "click replace button."; + qCDebug(appLog) << "click replace button."; }); // 配置修改 option->connect(option, &DTK_CORE_NAMESPACE::DSettingsOption::valueChanged, shortCutLineEdit, &KeySequenceEdit::slotDSettingsOptionvalueChanged); - qDebug() << "Leaving createKeySequenceEditHandle"; + qCDebug(appLog) << "Leaving createKeySequenceEditHandle"; return optionWidget; } void KeySequenceEdit::slotDSettingsOptionvalueChanged(const QVariant & value) { - qDebug() << "KeySequenceEdit::slotDSettingsOptionvalueChanged" << value; + qCDebug(appLog) << "KeySequenceEdit::slotDSettingsOptionvalueChanged" << value; QString keyseq = value.toString(); - qDebug() << "keyseq" << keyseq; + qCDebug(appLog) << "keyseq" << keyseq; if (keyseq.isEmpty()) { this->clear(); - qDebug() << "keyseq is empty"; + qCDebug(appLog) << "keyseq is empty"; return; } - qDebug() << "keyseq is not empty"; + qCDebug(appLog) << "keyseq is not empty"; this->setKeySequence(QKeySequence(keyseq)); - qDebug() << "Leaving KeySequenceEdit::slotDSettingsOptionvalueChanged"; + qCDebug(appLog) << "Leaving KeySequenceEdit::slotDSettingsOptionvalueChanged"; } bool KeySequenceEdit::eventFilter(QObject *object, QEvent *event) { - qDebug() << "KeySequenceEdit::eventFilter"; + qCDebug(appLog) << "KeySequenceEdit::eventFilter"; //设置界面 回车键和空格键 切换输入 梁卫东 2020-08-21 16:28:31 if (object == this) { if (event->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = static_cast(event); - qDebug() << "KeySequenceEdit::eventFilter KeyPress"; + qCDebug(appLog) << "KeySequenceEdit::eventFilter KeyPress"; //判断是否包含组合键 梁卫东 2020-09-02 15:03:56 Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); - qDebug() << "modifiers" << modifiers; + qCDebug(appLog) << "modifiers" << modifiers; bool bHasModifier = (modifiers & Qt::ShiftModifier || modifiers & Qt::ControlModifier || modifiers & Qt::AltModifier); - qDebug() << "bHasModifier" << bHasModifier; + qCDebug(appLog) << "bHasModifier" << bHasModifier; if (!bHasModifier && (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Space)) { - qDebug() << "keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Space"; + qCDebug(appLog) << "keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Space"; QRect rect = this->rect(); - qDebug() << "rect" << rect; + qCDebug(appLog) << "rect" << rect; QList childern = findChildren(); - qDebug() << "childern" << childern; + qCDebug(appLog) << "childern" << childern; for (int i =0; i < childern.size(); i++) { QPoint pos(25,rect.height()/2); @@ -599,7 +600,7 @@ bool KeySequenceEdit::eventFilter(QObject *object, QEvent *event) DApplication::sendEvent(childern[i], &event0); } - qDebug() << "KeySequenceEdit::eventFilter KeyPress return true"; + qCDebug(appLog) << "KeySequenceEdit::eventFilter KeyPress return true"; return true; } } @@ -609,9 +610,9 @@ bool KeySequenceEdit::eventFilter(QObject *object, QEvent *event) } Settings *Settings::instance() { - qDebug() << "Accessing Settings singleton instance"; + qCDebug(appLog) << "Accessing Settings singleton instance"; if (s_pSetting == nullptr) { - qDebug() << "Creating new Settings instance"; + qCDebug(appLog) << "Creating new Settings instance"; s_pSetting = new Settings; } return s_pSetting; @@ -619,7 +620,7 @@ Settings *Settings::instance() void Settings::updateAllKeysWithKeymap(QString keymap) { - qDebug() << "Updating all keys with keymap:" << keymap; + qCDebug(appLog) << "Updating all keys with keymap:" << keymap; m_bUserChangeKey = true; int updatedCount = 0; @@ -628,10 +629,10 @@ void Settings::updateAllKeysWithKeymap(QString keymap) keySplitList[1] = QString("%1_keymap_%2").arg(keySplitList[1]).arg(keymap); auto opt = settings->option(keySplitList.join(".")); if (opt) { - qDebug() << "Updating key" << keySplitList.join(".") << "with value" << opt->value().toString(); + qCDebug(appLog) << "Updating key" << keySplitList.join(".") << "with value" << opt->value().toString(); option->setValue(opt->value().toString()); } else { - qWarning() << "Unknown shortcut key:" << keySplitList.join("."); + qCWarning(appLog) << "Unknown shortcut key:" << keySplitList.join("."); } } @@ -641,20 +642,20 @@ void Settings::updateAllKeysWithKeymap(QString keymap) keySplitList[1] = QString("%1_keymap_%2").arg(keySplitList[1]).arg(keymap); auto opt = settings->option(keySplitList.join(".")); if (opt) { - qDebug() << "Updating key" << keySplitList.join(".") << "with value" << opt->value().toString(); + qCDebug(appLog) << "Updating key" << keySplitList.join(".") << "with value" << opt->value().toString(); option->setValue(opt->value().toString()); } else { - qWarning() << "Unknown shortcut key:" << keySplitList.join("."); + qCWarning(appLog) << "Unknown shortcut key:" << keySplitList.join("."); } } m_bUserChangeKey = false; - qInfo() << "Updated" << updatedCount << "shortcuts with keymap:" << keymap; + qCInfo(appLog) << "Updated" << updatedCount << "shortcuts with keymap:" << keymap; } void Settings::copyCustomizeKeysFromKeymap(QString keymap) { - qDebug() << "Entering copyCustomizeKeysFromKeymap, keymap:" << keymap; + qCDebug(appLog) << "Entering copyCustomizeKeysFromKeymap, keymap:" << keymap; m_bUserChangeKey = true; @@ -671,23 +672,23 @@ void Settings::copyCustomizeKeysFromKeymap(QString keymap) } m_bUserChangeKey = false; - qDebug() << "Leaving copyCustomizeKeysFromKeymap"; + qCDebug(appLog) << "Leaving copyCustomizeKeysFromKeymap"; } bool Settings::checkShortcutValid(const QString &Name, QString Key, QString &Reason, bool &bIsConflicts, QString defaultValue) { Q_UNUSED(Name); - qDebug() << "Entering checkShortcutValid for" << Name << "with key" << Key; + qCDebug(appLog) << "Entering checkShortcutValid for" << Name << "with key" << Key; if (Key.contains("<")) { - qDebug() << "Key contains <"; + qCDebug(appLog) << "Key contains <"; Key.replace(Key.indexOf("<"), 1, "<"); } QString style = QString("[%1]").arg(Key); // 单键 if (Key.count("+") == 0) { - qDebug() << "Key count + is 0"; + qCDebug(appLog) << "Key count + is 0"; //F1-F12是允许的,这个正则不够精确,但是没关系。 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QRegExp regexp("^F[0-9]{1,2}$"); @@ -695,7 +696,7 @@ bool Settings::checkShortcutValid(const QString &Name, QString Key, QString &Rea QRegularExpression regexp("^F[0-9]{1,2}$"); #endif if (!Key.contains(regexp)) { - qDebug() << "Key does not contain regexp"; + qCDebug(appLog) << "Key does not contain regexp"; Reason = tr("The shortcut %1 is invalid, please set another one.").arg(style); bIsConflicts = false; return false; @@ -708,7 +709,7 @@ bool Settings::checkShortcutValid(const QString &Name, QString Key, QString &Rea QRegularExpression regexpNum("^Num+.*"); #endif if (Key.contains(regexpNum)) { - qDebug() << "Key contains regexpNum"; + qCDebug(appLog) << "Key contains regexpNum"; Reason = tr("The shortcut %1 is invalid, please set another one.").arg(style); bIsConflicts = false; return false; @@ -717,19 +718,19 @@ bool Settings::checkShortcutValid(const QString &Name, QString Key, QString &Rea // 屏蔽Shift组合键处理,但允许恢复为默认组合键序列 if (Key.contains("Shift") && Key != defaultValue) { - qDebug() << "Key contains Shift and Key is not defaultValue"; + qCDebug(appLog) << "Key contains Shift and Key is not defaultValue"; Reason = tr("The shortcut %1 is invalid, please set another one.").arg(style); bIsConflicts = false; return false; } - qDebug() << "Leaving checkShortcutValid, returning true."; + qCDebug(appLog) << "Leaving checkShortcutValid, returning true."; return true; } bool Settings::isShortcutConflict(const QString &Name, const QString &Key) { - qDebug() << "Entering isShortcutConflict for" << Name << "with key" << Key; + qCDebug(appLog) << "Entering isShortcutConflict for" << Name << "with key" << Key; for (QString tmpKey : settings->keys()) { if (settings->value(tmpKey).toString() == Key/* && tmpKey.contains("customize")*/) { if (Name != tmpKey) { @@ -737,43 +738,43 @@ bool Settings::isShortcutConflict(const QString &Name, const QString &Key) } } } - qDebug() << "Leaving isShortcutConflict, returning false."; + qCDebug(appLog) << "Leaving isShortcutConflict, returning false."; return false; } DDialog *Settings::createDialog(const QString &title, const QString &content, const bool &bIsConflicts) { - qDebug() << "Entering createDialog for" << title << "with content" << content << "and bIsConflicts" << bIsConflicts; + qCDebug(appLog) << "Entering createDialog for" << title << "with content" << content << "and bIsConflicts" << bIsConflicts; DDialog *dialog = new DDialog(title, content, m_pSettingsDialog); dialog->setWindowFlags(dialog->windowFlags() | Qt::WindowStaysOnBottomHint); dialog->setIcon(QIcon::fromTheme("deepin-editor")); if (bIsConflicts) { - qDebug() << "Adding Cancel button"; + qCDebug(appLog) << "Adding Cancel button"; dialog->addButton(QString(tr("Cancel")), true, DDialog::ButtonNormal); dialog->addButton(QString(tr("Replace")), false, DDialog::ButtonRecommend); } else { - qDebug() << "Adding OK button"; + qCDebug(appLog) << "Adding OK button"; dialog->addButton(QString(tr("OK")), true, DDialog::ButtonRecommend); } - qDebug() << "Leaving createDialog"; + qCDebug(appLog) << "Leaving createDialog"; return dialog; } //删除config.conf配置文件目录下的.lock文件和.rmlock文件 void Settings::removeLockFiles() { - qDebug() << "Removing lock files"; + qCDebug(appLog) << "Removing lock files"; QString configPath = QString("%1/%2/%3") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) .arg(qApp->organizationName()) .arg(qApp->applicationName()); - qDebug() << "Config directory:" << configPath; + qCDebug(appLog) << "Config directory:" << configPath; QDir dir(configPath); if (!dir.exists()) { - qDebug() << "Config directory does not exist"; + qCDebug(appLog) << "Config directory does not exist"; return; } @@ -785,36 +786,36 @@ void Settings::removeLockFiles() // entryList 返回裸文件名,必须拼绝对路径后再删除, // 否则删除落点依赖进程当前工作目录,正常启动场景清理必然失效 const QString lockFile = dir.absoluteFilePath(name); - qDebug() << "Removing lock file:" << lockFile; + qCDebug(appLog) << "Removing lock file:" << lockFile; if (QFile::remove(lockFile)) { - qDebug() << "Removed lock file:" << lockFile; + qCDebug(appLog) << "Removed lock file:" << lockFile; removedCount++; } else { - qWarning() << "Failed to remove lock file:" << lockFile; + qCWarning(appLog) << "Failed to remove lock file:" << lockFile; } } } - qInfo() << "Removed" << removedCount << "lock files"; + qCInfo(appLog) << "Removed" << removedCount << "lock files"; } void Settings::slotCustomshortcut(const QString &key, const QVariant &value) { - qDebug() << "Entering slotCustomshortcut for key:" << key << "value:" << value.toString(); + qCDebug(appLog) << "Entering slotCustomshortcut for key:" << key << "value:" << value.toString(); auto keymap = settings->option("shortcuts.keymap.keymap"); if (!m_bUserChangeKey && key.startsWith("shortcuts.") && key != "shortcuts.keymap.keymap" && !key.contains("_keymap_")) { - qDebug() << "start with shortcuts."; + qCDebug(appLog) << "start with shortcuts."; m_bUserChangeKey = true; - qDebug() << "m_bUserChangeKey is true"; + qCDebug(appLog) << "m_bUserChangeKey is true"; QString currentKeymap = settings->option("shortcuts.keymap.keymap")->value().toString(); - qDebug() << "currentKeymap" << currentKeymap; + qCDebug(appLog) << "currentKeymap" << currentKeymap; QStringList keySplitList = key.split("."); keySplitList[1] = QString("%1_keymap_customize").arg(keySplitList[1]); QString customizeKey = keySplitList.join("."); - qDebug() << "customizeKey" << customizeKey; + qCDebug(appLog) << "customizeKey" << customizeKey; // Just update customize key user input, don't change keymap. if (currentKeymap == "customize") { settings->option(customizeKey)->setValue(value); - qDebug() << "currentKeymap is customize"; + qCDebug(appLog) << "currentKeymap is customize"; } // If current kemap is not "customize". // Copy all customize keys from current keymap, and then update customize key just user input. @@ -823,88 +824,88 @@ void Settings::slotCustomshortcut(const QString &key, const QVariant &value) copyCustomizeKeysFromKeymap(currentKeymap); settings->option(customizeKey)->setValue(value); keymap->setValue("customize"); - qDebug() << "currentKeymap is not customize"; + qCDebug(appLog) << "currentKeymap is not customize"; } m_bUserChangeKey = false; - qDebug() << "m_bUserChangeKey is false"; + qCDebug(appLog) << "m_bUserChangeKey is false"; } - qDebug() << "Leaving slotCustomshortcut"; + qCDebug(appLog) << "Leaving slotCustomshortcut"; } void Settings::slotsigAdjustFont(QVariant value) { - qDebug() << "Font family changed to:" << value.toString(); + qCDebug(appLog) << "Font family changed to:" << value.toString(); emit sigAdjustFont(value.toString()); - qDebug() << "Leaving slotsigAdjustFont"; + qCDebug(appLog) << "Leaving slotsigAdjustFont"; } void Settings::slotsigAdjustFontSize(QVariant value) { - qDebug() << "Font size changed to:" << value.toReal(); + qCDebug(appLog) << "Font size changed to:" << value.toReal(); emit sigAdjustFontSize(value.toReal()); } void Settings::slotsigAdjustWordWrap(QVariant value) { - qDebug() << "Entering slotsigAdjustWordWrap, value:" << value.toBool(); + qCDebug(appLog) << "Entering slotsigAdjustWordWrap, value:" << value.toBool(); emit sigAdjustWordWrap(value.toBool()); - qDebug() << "Leaving slotsigAdjustWordWrap"; + qCDebug(appLog) << "Leaving slotsigAdjustWordWrap"; } void Settings::slotsigSetLineNumberShow(QVariant value) { - qDebug() << "Entering slotsigSetLineNumberShow, value:" << value.toBool(); + qCDebug(appLog) << "Entering slotsigSetLineNumberShow, value:" << value.toBool(); emit sigSetLineNumberShow(value.toBool()); - qDebug() << "Leaving slotsigSetLineNumberShow"; + qCDebug(appLog) << "Leaving slotsigSetLineNumberShow"; } void Settings::slotsigAdjustBookmark(QVariant value) { - qDebug() << "Entering slotsigAdjustBookmark, value:" << value.toBool(); + qCDebug(appLog) << "Entering slotsigAdjustBookmark, value:" << value.toBool(); emit sigAdjustBookmark(value.toBool()); - qDebug() << "Leaving slotsigAdjustBookmark"; + qCDebug(appLog) << "Leaving slotsigAdjustBookmark"; } void Settings::slotsigShowCodeFlodFlag(QVariant value) { - qDebug() << "Entering slotsigShowCodeFlodFlag, value:" << value.toBool(); + qCDebug(appLog) << "Entering slotsigShowCodeFlodFlag, value:" << value.toBool(); emit sigShowCodeFlodFlag(value.toBool()); - qDebug() << "Leaving slotsigShowCodeFlodFlag"; + qCDebug(appLog) << "Leaving slotsigShowCodeFlodFlag"; } void Settings::slotsigShowBlankCharacter(QVariant value) { - qDebug() << "Entering slotsigShowBlankCharacter, value:" << value.toBool(); + qCDebug(appLog) << "Entering slotsigShowBlankCharacter, value:" << value.toBool(); emit sigShowBlankCharacter(value.toBool()); - qDebug() << "Leaving slotsigShowBlankCharacter"; + qCDebug(appLog) << "Leaving slotsigShowBlankCharacter"; } void Settings::slotsigHightLightCurrentLine(QVariant value) { - qDebug() << "Entering slotsigHightLightCurrentLine, value:" << value.toBool(); + qCDebug(appLog) << "Entering slotsigHightLightCurrentLine, value:" << value.toBool(); emit sigHightLightCurrentLine(value.toBool()); - qDebug() << "Leaving slotsigHightLightCurrentLine"; + qCDebug(appLog) << "Leaving slotsigHightLightCurrentLine"; } void Settings::slotsigAdjustTabSpaceNumber(QVariant value) { - qDebug() << "Entering slotsigAdjustTabSpaceNumber, value:" << value.toInt(); + qCDebug(appLog) << "Entering slotsigAdjustTabSpaceNumber, value:" << value.toInt(); emit sigAdjustTabSpaceNumber(value.toInt()); - qDebug() << "Leaving slotsigAdjustTabSpaceNumber"; + qCDebug(appLog) << "Leaving slotsigAdjustTabSpaceNumber"; } void Settings::slotupdateAllKeysWithKeymap(QVariant value) { - qDebug() << "Entering slotupdateAllKeysWithKeymap, value:" << value.toString(); + qCDebug(appLog) << "Entering slotupdateAllKeysWithKeymap, value:" << value.toString(); updateAllKeysWithKeymap(value.toString()); - qDebug() << "Leaving slotupdateAllKeysWithKeymap"; + qCDebug(appLog) << "Leaving slotupdateAllKeysWithKeymap"; } KeySequenceEdit::KeySequenceEdit(DTK_CORE_NAMESPACE::DSettingsOption *opt, QWidget *parent) : DKeySequenceEdit(parent) { - qDebug() << "KeySequenceEdit constructor called"; + qCDebug(appLog) << "KeySequenceEdit constructor called"; m_pOption = opt; this->installEventFilter(this); } diff --git a/src/common/text_file_saver.cpp b/src/common/text_file_saver.cpp index fc170615a..c6161f352 100644 --- a/src/common/text_file_saver.cpp +++ b/src/common/text_file_saver.cpp @@ -7,6 +7,7 @@ * @brief Implementation of FileSaver class for safe file saving with encoding conversion */ +#include "ddlog.h" #include "text_file_saver.h" #include "utils.h" #include "../encodes/detectcode.h" @@ -29,12 +30,12 @@ TextFileSaver::TextFileSaver(QTextDocument *document) , m_fromEncode("UTF-16") , m_toEncode("UTF-8") { - qDebug() << "TextFileSaver created for document with" << document->characterCount() << "characters"; + qCDebug(appLog) << "TextFileSaver created for document with" << document->characterCount() << "characters"; } TextFileSaver::~TextFileSaver() { - qDebug() << "TextFileSaver destructor entry"; + qCDebug(appLog) << "TextFileSaver destructor entry"; } /** @@ -43,7 +44,7 @@ TextFileSaver::~TextFileSaver() */ void TextFileSaver::setFilePath(const QString &filePath) { - qDebug() << "Setting file path to:" << filePath; + qCDebug(appLog) << "Setting file path to:" << filePath; m_filePath = filePath; } @@ -53,7 +54,7 @@ void TextFileSaver::setFilePath(const QString &filePath) */ void TextFileSaver::setEncoding(const QByteArray &toEncode) { - qDebug() << "Setting target encoding to:" << toEncode; + qCDebug(appLog) << "Setting target encoding to:" << toEncode; m_toEncode = toEncode; } @@ -69,10 +70,10 @@ void TextFileSaver::setEndlineFormat(bool useCRLF) */ bool TextFileSaver::save() { - qDebug() << "Entering save"; + qCDebug(appLog) << "Entering save"; if (m_filePath.isEmpty()) { m_errorString = QObject::tr("File path is empty"); - qWarning() << "Cannot save - file path is empty"; + qCWarning(appLog) << "Cannot save - file path is empty"; return false; } @@ -90,7 +91,7 @@ bool TextFileSaver::save() // } // return saveFile.commit(); // } else { - // qWarning() << "File name too long, disable QSaveFile. path:" << m_filePath; + // qCWarning(appLog) << "File name too long, disable QSaveFile. path:" << m_filePath; QFile file(m_filePath); if (!saveToFile(file)) { return false; @@ -107,15 +108,15 @@ bool TextFileSaver::save() */ bool TextFileSaver::saveAs(const QString &newFilePath) { - qDebug() << "Saving as new file:" << newFilePath; + qCDebug(appLog) << "Saving as new file:" << newFilePath; QString oldPath = m_filePath; m_filePath = newFilePath; bool result = save(); if (!result) { - qWarning() << "SaveAs failed, reverting to original path:" << oldPath; + qCWarning(appLog) << "SaveAs failed, reverting to original path:" << oldPath; m_filePath = oldPath; } else { - qDebug() << "SaveAs completed successfully"; + qCDebug(appLog) << "SaveAs completed successfully"; } return result; } @@ -126,7 +127,7 @@ bool TextFileSaver::saveAs(const QString &newFilePath) */ QString TextFileSaver::errorString() const { - qDebug() << "errorString" << m_errorString; + qCDebug(appLog) << "errorString" << m_errorString; return m_errorString; } @@ -137,7 +138,7 @@ QString TextFileSaver::errorString() const */ bool TextFileSaver::saveToFile(QFileDevice &file) { - qDebug() << "Entering saveToFile"; + qCDebug(appLog) << "Entering saveToFile"; try { // 先完成前置校验(内存检查等),再打开/截断目标文件, // 避免校验失败时目标文件已被 Truncate 清空 @@ -146,18 +147,18 @@ bool TextFileSaver::saveToFile(QFileDevice &file) qlonglong docMemoryNeeded = characterCount * 2; if (!Utils::isMemorySufficientForOperation(Utils::OperationType::RawOperation, docMemoryNeeded, characterCount)) { m_errorString = QObject::tr("Insufficient memory to load document content"); - qWarning() << m_errorString << "- needed:" << docMemoryNeeded << "bytes"; + qCWarning(appLog) << m_errorString << "- needed:" << docMemoryNeeded << "bytes"; return false; } - qDebug() << "Attempting to open file for writing:" << m_filePath; + qCDebug(appLog) << "Attempting to open file for writing:" << m_filePath; if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { m_errorString = file.errorString(); - qWarning() << "Failed to open file:" << m_errorString; + qCWarning(appLog) << "Failed to open file:" << m_errorString; return false; } - qDebug() << "file opened"; - qDebug() << "memory sufficient"; + qCDebug(appLog) << "file opened"; + qCDebug(appLog) << "memory sufficient"; QString content = m_document->toPlainText(); if (m_useCRLF) { content.replace(QStringLiteral("\n"), QStringLiteral("\r\n")); @@ -167,13 +168,13 @@ bool TextFileSaver::saveToFile(QFileDevice &file) // Dynamically calculate chunk size (10MB or 1/8 of total length, whichever is larger) const int chunkSize = qMax(10 * 1024 * 1024, length / 8); - qDebug() << "chunkSize" << chunkSize; - qDebug() << "Saving document in chunks, total size:" << length << "chars, chunk size:" << chunkSize; + qCDebug(appLog) << "chunkSize" << chunkSize; + qCDebug(appLog) << "Saving document in chunks, total size:" << length << "chars, chunk size:" << chunkSize; for (int i = 0; i < length; i += chunkSize) { int currentChunkSize = qMin(chunkSize, length - i); - qDebug() << "Processing chunk" << i << "-" << i+currentChunkSize-1 << "of" << length; + qCDebug(appLog) << "Processing chunk" << i << "-" << i+currentChunkSize-1 << "of" << length; QByteArray input(reinterpret_cast(data + i), currentChunkSize * sizeof(ushort)); - qDebug() << "input" << input; + qCDebug(appLog) << "input" << input; // Check memory for encoding conversion (input + estimated output size) qlonglong conversionMemoryNeeded = input.size() * 2; // Estimate 2x for worst case if (!Utils::isMemorySufficientForOperation( @@ -181,21 +182,21 @@ bool TextFileSaver::saveToFile(QFileDevice &file) m_errorString = QObject::tr("Insufficient memory for encoding conversion"); return false; } - qDebug() << "memory sufficient"; + qCDebug(appLog) << "memory sufficient"; QByteArray outData; if (!convertEncoding(input, outData)) { m_errorString = QObject::tr("Encoding conversion failed"); - qWarning() << m_errorString << "from" << m_fromEncode << "to" << m_toEncode; + qCWarning(appLog) << m_errorString << "from" << m_fromEncode << "to" << m_toEncode; return false; } - qDebug() << "outData" << outData; + qCDebug(appLog) << "outData" << outData; if (outData.isEmpty()) { m_errorString = QObject::tr("Converted content is empty"); return false; } - qDebug() << "outData is not empty"; + qCDebug(appLog) << "outData is not empty"; QApplication::processEvents(); - qDebug() << "processEvents"; + qCDebug(appLog) << "processEvents"; // processEvents() may deliver a queued QCloseEvent that deletes the // EditWrapper (and thus the QTextDocument) while the save loop is // still running. Abort immediately when the document is gone or the @@ -208,37 +209,37 @@ bool TextFileSaver::saveToFile(QFileDevice &file) // prevents dereferencing a dangling pointer. Do not reorder. if (!m_document || (m_quitFlag && *m_quitFlag)) { m_errorString = QObject::tr("Save aborted: editor is closing"); - qWarning() << "Save aborted: document destroyed or quit requested"; + qCWarning(appLog) << "Save aborted: document destroyed or quit requested"; file.close(); return false; } qint64 written = file.write(outData); if (written != outData.size()) { m_errorString = file.errorString(); - qWarning() << "Failed to write full chunk. Expected:" << outData.size() + qCWarning(appLog) << "Failed to write full chunk. Expected:" << outData.size() << "bytes, wrote:" << written << "bytes. Error:" << m_errorString; return false; } } - qDebug() << "File saved successfully:" << m_filePath; + qCDebug(appLog) << "File saved successfully:" << m_filePath; // 成功保存后清空历史错误信息,保证 errorString() 不返回上次失败内容 m_errorString.clear(); return true; } catch (const std::bad_alloc &) { m_errorString = QObject::tr("Memory allocation failed"); - qDebug() << "Memory allocation failed"; + qCDebug(appLog) << "Memory allocation failed"; return false; } catch (const std::exception &e) { m_errorString = QObject::tr("Error occurred: %1").arg(e.what()); - qDebug() << "Error occurred: " << e.what(); + qCDebug(appLog) << "Error occurred: " << e.what(); return false; } catch (...) { m_errorString = QObject::tr("Unknown error occurred"); - qDebug() << "Unknown error occurred"; + qCDebug(appLog) << "Unknown error occurred"; return false; } - qDebug() << "saveToFile failed"; + qCDebug(appLog) << "saveToFile failed"; } /** @@ -250,18 +251,18 @@ bool TextFileSaver::saveToFile(QFileDevice &file) */ bool TextFileSaver::convertEncoding(QByteArray &input, QByteArray &output) const { - qDebug() << "Entering convertEncoding"; + qCDebug(appLog) << "Entering convertEncoding"; if (m_fromEncode == m_toEncode) { - qDebug() << "No encoding conversion needed (same encoding)"; + qCDebug(appLog) << "No encoding conversion needed (same encoding)"; output = input; return true; } - qDebug() << "Converting encoding from" << m_fromEncode << "to" << m_toEncode; + qCDebug(appLog) << "Converting encoding from" << m_fromEncode << "to" << m_toEncode; if (!DetectCode::ChangeFileEncodingFormat(input, output, m_fromEncode, m_toEncode)) { - qWarning() << "Encoding conversion failed using DetectCode"; + qCWarning(appLog) << "Encoding conversion failed using DetectCode"; return false; } - qDebug() << "convertEncoding success"; + qCDebug(appLog) << "convertEncoding success"; return true; } diff --git a/src/common/utils.cpp b/src/common/utils.cpp index 44131cf27..a43f10d3c 100644 --- a/src/common/utils.cpp +++ b/src/common/utils.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "utils.h" #include @@ -92,23 +93,23 @@ QString Utils::m_systemLanguage; QString Utils::getQrcPath(const QString &imageName) { - qDebug() << "Enter getQrcPath, imageName:" << imageName; + qCDebug(appLog) << "Enter getQrcPath, imageName:" << imageName; QString path = QString(":/images/%1").arg(imageName); - qDebug() << "Exit getQrcPath, return path:" << path; + qCDebug(appLog) << "Exit getQrcPath, return path:" << path; return path; } QString Utils::getQssPath(const QString &qssName) { - qDebug() << "Enter getQssPath, qssName:" << qssName; + qCDebug(appLog) << "Enter getQssPath, qssName:" << qssName; QString path = QString(":/qss/%1").arg(qssName); - qDebug() << "Exit getQssPath, return path:" << path; + qCDebug(appLog) << "Exit getQssPath, return path:" << path; return path; } QSize Utils::getRenderSize(int fontSize, const QString &string) { - qDebug() << "Entering getRenderSize with fontSize:" << fontSize << "and string:" << string.left(50); + qCDebug(appLog) << "Entering getRenderSize with fontSize:" << fontSize << "and string:" << string.left(50); QFont font; font.setPointSize(fontSize); QFontMetrics fm(font); @@ -121,41 +122,41 @@ QSize Utils::getRenderSize(int fontSize, const QString &string) int lineHeight = fm.height(); if (lineWidth > width) { - qDebug() << "New max width found:" << lineWidth; + qCDebug(appLog) << "New max width found:" << lineWidth; width = lineWidth; } height += lineHeight; } - qDebug() << "Leaving getRenderSize, returning QSize(" << width << "," << height << ")"; + qCDebug(appLog) << "Leaving getRenderSize, returning QSize(" << width << "," << height << ")"; return QSize(width, height); } void Utils::setFontSize(QPainter &painter, int textSize) { - qDebug() << "Entering setFontSize with textSize:" << textSize; + qCDebug(appLog) << "Entering setFontSize with textSize:" << textSize; QFont font = painter.font(); font.setPointSize(textSize); painter.setFont(font); - qDebug() << "Leaving setFontSize"; + qCDebug(appLog) << "Leaving setFontSize"; } void Utils::applyQss(QWidget *widget, const QString &qssName) { - qDebug() << "Entering applyQss for widget" << widget->objectName() << "with qss" << qssName; + qCDebug(appLog) << "Entering applyQss for widget" << widget->objectName() << "with qss" << qssName; QFile file(Utils::getQssPath(qssName)); file.open(QFile::ReadOnly); QTextStream filetext(&file); QString stylesheet = filetext.readAll(); widget->setStyleSheet(stylesheet); file.close(); - qDebug() << "Leaving applyQss"; + qCDebug(appLog) << "Leaving applyQss"; } float Utils::codecConfidenceForData(const QTextCodec *codec, const QByteArray &data, const QLocale::Country &country) { - qDebug() << "Entering codecConfidenceForData for codec:" << codec->name(); + qCDebug(appLog) << "Entering codecConfidenceForData for codec:" << codec->name(); qreal hep_count = 0; int non_base_latin_count = 0; qreal unidentification_count = 0; @@ -168,34 +169,34 @@ float Utils::codecConfidenceForData(const QTextCodec *codec, const QByteArray &d const QChar &ch = unicode_data.at(i); if (ch.unicode() > 0x7f) { - qDebug() << "Non-base Latin character found:" << ch; + qCDebug(appLog) << "Non-base Latin character found:" << ch; ++non_base_latin_count; } switch (ch.script()) { case QChar::Script_Hiragana: case QChar::Script_Katakana: - qDebug() << "Hiragana or Katakana character found:" << ch; + qCDebug(appLog) << "Hiragana or Katakana character found:" << ch; hep_count += (country == QLocale::Japan) ? 1.2 : 0.5; unidentification_count += (country == QLocale::Japan) ? 0 : 0.3; break; case QChar::Script_Han: - qDebug() << "Chinese character found:" << ch; + qCDebug(appLog) << "Chinese character found:" << ch; hep_count += (country == QLocale::China) ? 1.2 : 0.5; unidentification_count += (country == QLocale::China) ? 0 : 0.3; break; case QChar::Script_Hangul: - qDebug() << "Hangul character found:" << ch; + qCDebug(appLog) << "Hangul character found:" << ch; hep_count += (country == QLocale::NorthKorea) || (country == QLocale::SouthKorea) ? 1.2 : 0.5; unidentification_count += (country == QLocale::NorthKorea) || (country == QLocale::SouthKorea) ? 0 : 0.3; break; case QChar::Script_Cyrillic: - qDebug() << "Cyrillic character found:" << ch; + qCDebug(appLog) << "Cyrillic character found:" << ch; hep_count += (country == QLocale::Russia) ? 1.2 : 0.5; unidentification_count += (country == QLocale::Russia) ? 0 : 0.3; break; case QChar::Script_Devanagari: - qDebug() << "Devanagari character found:" << ch; + qCDebug(appLog) << "Devanagari character found:" << ch; hep_count += (country == QLocale::Nepal || country == QLocale::India) ? 1.2 : 0.5; unidentification_count += (country == QLocale::Nepal || country == QLocale::India) ? 0 : 0.3; break; @@ -240,21 +241,21 @@ float Utils::codecConfidenceForData(const QTextCodec *codec, const QByteArray &d c -= qreal(replacement_count) / non_base_latin_count; c -= qreal(unidentification_count) / non_base_latin_count; - qDebug() << "Leaving codecConfidenceForData, confidence:" << c; + qCDebug(appLog) << "Leaving codecConfidenceForData, confidence:" << c; return qMax(0.0f, c); } QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) { - qDebug() << "Entering detectEncode for file:" << fileName; + qCDebug(appLog) << "Entering detectEncode for file:" << fileName; // Return local encoding if nothing in file. if (data.isEmpty()) { - qDebug() << "Data is empty, returning codec for locale."; + qCDebug(appLog) << "Data is empty, returning codec for locale."; return QTextCodec::codecForLocale()->name(); } if (QTextCodec *c = QTextCodec::codecForUtfText(data, nullptr)) { - qDebug() << "Detected UTF text, codec:" << c->name(); + qCDebug(appLog) << "Detected UTF text, codec:" << c->name(); return c->name(); } @@ -262,12 +263,12 @@ QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) const QMimeType &mime_type = fileName.isEmpty() ? mime_database.mimeTypeForData(data) : mime_database.mimeTypeForFileNameAndData(fileName, data); const QString &mimetype_name = mime_type.name(); - qDebug() << "MIME type:" << mimetype_name; + qCDebug(appLog) << "MIME type:" << mimetype_name; KEncodingProber::ProberType proberType = KEncodingProber::Universal; if (mimetype_name == QStringLiteral("application/xml") || mimetype_name == QStringLiteral("text/html") || mimetype_name == QStringLiteral("application/xhtml+xml")) { - qDebug() << "XML/HTML mimetype found, checking for charset meta tag."; + qCDebug(appLog) << "XML/HTML mimetype found, checking for charset meta tag."; const QString &_data = QString::fromLatin1(data); QRegularExpression pattern("<\\bmeta.+\\bcharset=(?'charset'\\S+?)\\s*['\"/>]"); @@ -279,7 +280,7 @@ QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) .captured("charset"); if (!charset.isEmpty()) { - qDebug() << "Found charset in meta tag:" << charset; + qCDebug(appLog) << "Found charset in meta tag:" << charset; return charset.toLatin1(); } @@ -292,7 +293,7 @@ QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) .captured("language"); if (0 != language.size()) { - qDebug() << "Found language in meta tag:" << language; + qCDebug(appLog) << "Found language in meta tag:" << language; QLocale l(language); switch (l.script()) { @@ -326,10 +327,10 @@ QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) default: break; } - qDebug() << "Set prober type based on language:" << proberType; + qCDebug(appLog) << "Set prober type based on language:" << proberType; } } else if (mimetype_name == "text/x-python") { - qDebug() << "Python mimetype found, checking for coding meta tag."; + qCDebug(appLog) << "Python mimetype found, checking for coding meta tag."; QRegularExpression pattern("^#coding\\s*:\\s*(?'coding'\\S+)$"); QTextStream stream(data); @@ -378,42 +379,42 @@ QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) QByteArray prober_encoding = prober.encoding(); if (i.first != proberType && qFuzzyIsNull(prober_confidence)) { - qDebug() << "i.first != proberType && qFuzzyIsNull(prober_confidence)"; + qCDebug(appLog) << "i.first != proberType && qFuzzyIsNull(prober_confidence)"; prober_confidence = pre_confidence; prober_encoding = pre_encoding; } confidence: - qDebug() << "go to here: confidence!"; + qCDebug(appLog) << "go to here: confidence!"; if (QTextCodec *codec = QTextCodec::codecForName(prober_encoding)) { if (def_codec == codec) { - qDebug() << "def_codec == codec"; + qCDebug(appLog) << "def_codec == codec"; def_codec = nullptr; } float c = Utils::codecConfidenceForData(codec, data, i.second); if (prober_confidence > 0.5) { - qDebug() << "prober_confidence > 0.5"; + qCDebug(appLog) << "prober_confidence > 0.5"; c = c / 2 + prober_confidence / 2; } else { - qDebug() << "prober_confidence <= 0.5"; + qCDebug(appLog) << "prober_confidence <= 0.5"; c = c / 3 * 2 + prober_confidence / 3; } if (c > confidence) { - qDebug() << "c > confidence!"; + qCDebug(appLog) << "c > confidence!"; confidence = c; encoding = prober_encoding; } if (i.first == KEncodingProber::ChineseTraditional && c < 0.5) { - qDebug() << "i.first == KEncodingProber::ChineseTraditional && c < 0.5"; + qCDebug(appLog) << "i.first == KEncodingProber::ChineseTraditional && c < 0.5"; // test Big5 c = Utils::codecConfidenceForData(QTextCodec::codecForName("Big5"), data, i.second); if (c > 0.5 && c > confidence) { - qDebug() << " 0.5 set Big5"; + qCDebug(appLog) << " 0.5 set Big5"; confidence = c; encoding = "Big5"; } @@ -421,7 +422,7 @@ QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) } if (i.first != proberType) { - qDebug() << "i.first != proberType"; + qCDebug(appLog) << "i.first != proberType"; // 使用 proberType 类型探测出的结果结合此国家再次做编码检查 i.first = proberType; prober_confidence = pre_confidence; @@ -431,20 +432,20 @@ QByteArray Utils::detectEncode(const QByteArray &data, const QString &fileName) } if (def_codec && Utils::codecConfidenceForData(def_codec, data, QLocale::system().country()) > confidence) { - qDebug() << "return codec's name"; + qCDebug(appLog) << "return codec's name"; return def_codec->name(); } - qDebug() << "final return!"; + qCDebug(appLog) << "final return!"; return encoding; } QByteArray Utils::getEncode(const QByteArray &data) { - qDebug() << "Enter getEncode"; + qCDebug(appLog) << "Enter getEncode"; // try to get HTML header encoding. if (QTextCodec *codecForHtml = QTextCodec::codecForHtml(data, nullptr)) { - qDebug() << "codecForHtml" << codecForHtml->name(); + qCDebug(appLog) << "codecForHtml" << codecForHtml->name(); return codecForHtml->name(); } @@ -458,21 +459,21 @@ QByteArray Utils::getEncode(const QByteArray &data) } if (!codec) { - qDebug() << "codec is null"; + qCDebug(appLog) << "codec is null"; return QByteArray(); } - qDebug() << "codec" << codec->name(); + qCDebug(appLog) << "codec" << codec->name(); return codec->name(); } bool Utils::fileExists(const QString &path) { - qDebug() << "Enter fileExists, path:" << path; + qCDebug(appLog) << "Enter fileExists, path:" << path; QFileInfo check_file(path); - qDebug() << "check_file" << check_file.exists() << check_file.isFile(); + qCDebug(appLog) << "check_file" << check_file.exists() << check_file.isFile(); bool exists = check_file.exists() && check_file.isFile(); - qDebug() << "Exit fileExists, file exists:" << exists; + qCDebug(appLog) << "Exit fileExists, file exists:" << exists; return exists; } @@ -490,64 +491,64 @@ QString Utils::getFilePath(const QString &filePath) bool Utils::fileIsWritable(const QString &path) { - qDebug() << "Enter fileIsWritable, path:" << path; + qCDebug(appLog) << "Enter fileIsWritable, path:" << path; QFileDevice::Permissions permissions = QFile(path).permissions(); - qDebug() << "permissions" << permissions; + qCDebug(appLog) << "permissions" << permissions; bool writable = permissions & QFileDevice::WriteUser; - qDebug() << "Exit fileIsWritable, is writable:" << writable; + qCDebug(appLog) << "Exit fileIsWritable, is writable:" << writable; return writable; } bool Utils::fileIsHome(const QString &path) { - qDebug() << "Enter fileIsHome, path:" << path; + qCDebug(appLog) << "Enter fileIsHome, path:" << path; bool isHome = path.startsWith(QDir::homePath()); - qDebug() << "Exit fileIsHome, isHome:" << isHome; + qCDebug(appLog) << "Exit fileIsHome, isHome:" << isHome; return isHome; } QString Utils::getKeyshortcut(QKeyEvent *keyEvent) { - qDebug() << "Enter getKeyshortcut"; + qCDebug(appLog) << "Enter getKeyshortcut"; QStringList keys; Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); if (modifiers != Qt::NoModifier) { - qDebug() << "modifiers" << modifiers; + qCDebug(appLog) << "modifiers" << modifiers; if (modifiers.testFlag(Qt::MetaModifier)) { - qDebug() << "modifiers.testFlag(Qt::MetaModifier)"; + qCDebug(appLog) << "modifiers.testFlag(Qt::MetaModifier)"; keys.append("Meta"); } if (modifiers.testFlag(Qt::ControlModifier)) { - qDebug() << "modifiers.testFlag(Qt::ControlModifier)"; + qCDebug(appLog) << "modifiers.testFlag(Qt::ControlModifier)"; keys.append("Ctrl"); } if (modifiers.testFlag(Qt::AltModifier)) { - qDebug() << "modifiers.testFlag(Qt::AltModifier)"; + qCDebug(appLog) << "modifiers.testFlag(Qt::AltModifier)"; keys.append("Alt"); } if (modifiers.testFlag(Qt::ShiftModifier)) { - qDebug() << "modifiers.testFlag(Qt::ShiftModifier)"; + qCDebug(appLog) << "modifiers.testFlag(Qt::ShiftModifier)"; keys.append("Shift"); } // 添加小键盘处理,若为小键盘按键按下,组合键需添加 Num ,例如 Ctrl+Num+6 / Ctrl+Num+Up if (modifiers.testFlag(Qt::KeypadModifier)) { - qDebug() << "modifiers.testFlag(Qt::KeypadModifier)"; + qCDebug(appLog) << "modifiers.testFlag(Qt::KeypadModifier)"; keys.append("Num"); } } if (keyEvent->key() != 0 && keyEvent->key() != Qt::Key_unknown) { - qDebug() << "keyEvent->key() != 0 && keyEvent->key() != Qt::Key_unknown"; + qCDebug(appLog) << "keyEvent->key() != 0 && keyEvent->key() != Qt::Key_unknown"; keys.append(QKeySequence(keyEvent->key()).toString()); } for (int i = 0; i < keys.count(); i++) { if (keys.value(i).contains("Return")) { - qDebug() << "keys.value(i).contains(Return)"; + qCDebug(appLog) << "keys.value(i).contains(Return)"; keys.replace(i, "Enter"); } // 与 Return→Enter 同理:统一为常见写法,和配置/显示 "Ctrl+Shift+Tab" 一致 @@ -556,19 +557,19 @@ QString Utils::getKeyshortcut(QKeyEvent *keyEvent) } } - qDebug() << "Exit getKeyshortcut, keys:" << keys.join("+"); + qCDebug(appLog) << "Exit getKeyshortcut, keys:" << keys.join("+"); return keys.join("+"); } QString Utils::getKeyshortcutFromKeymap(Settings *settings, const QString &keyCategory, const QString &keyName) { - qDebug() << "Enter getKeyshortcutFromKeymap, keyCategory:" << keyCategory << "keyName:" << keyName; + qCDebug(appLog) << "Enter getKeyshortcutFromKeymap, keyCategory:" << keyCategory << "keyName:" << keyName; return settings->settings->option(QString("shortcuts.%1.%2").arg(keyCategory).arg(keyName))->value().toString(); } QPixmap Utils::dropShadow(const QPixmap &source, qreal radius, const QColor &color, const QPoint &offset) { - qDebug() << "Enter dropShadow"; + qCDebug(appLog) << "Enter dropShadow"; QImage shadow = dropShadow(source, radius, color); shadow.setDevicePixelRatio(source.devicePixelRatio()); @@ -577,15 +578,15 @@ QPixmap Utils::dropShadow(const QPixmap &source, qreal radius, const QColor &col pa.drawPixmap(radius - offset.x(), radius - offset.y(), source); pa.end(); - qDebug() << "Exit dropShadow"; + qCDebug(appLog) << "Exit dropShadow"; return QPixmap::fromImage(shadow); } QImage Utils::dropShadow(const QPixmap &px, qreal radius, const QColor &color) { - qDebug() << "Enter dropShadow"; + qCDebug(appLog) << "Enter dropShadow"; if (px.isNull()) { - qDebug() << "px is null"; + qCDebug(appLog) << "px is null"; return QImage(); } @@ -605,7 +606,7 @@ QImage Utils::dropShadow(const QPixmap &px, qreal radius, const QColor &color) qt_blurImage(&blurPainter, tmp, radius, false, true); blurPainter.end(); if (color == QColor(Qt::black)) { - qDebug() << "color is black"; + qCDebug(appLog) << "color is black"; return blurred; } tmp = blurred; @@ -616,46 +617,46 @@ QImage Utils::dropShadow(const QPixmap &px, qreal radius, const QColor &color) tmpPainter.fillRect(tmp.rect(), color); tmpPainter.end(); - qDebug() << "Exit dropShadow"; + qCDebug(appLog) << "Exit dropShadow"; return tmp; } qreal Utils::easeInOut(qreal x) { - qDebug() << "Enter easeInOut, x:" << x; + qCDebug(appLog) << "Enter easeInOut, x:" << x; return (1 - qCos(M_PI * x)) / 2; } qreal Utils::easeInQuad(qreal x) { - qDebug() << "Enter easeInQuad, x:" << x; + qCDebug(appLog) << "Enter easeInQuad, x:" << x; return qPow(x, 2); } qreal Utils::easeOutQuad(qreal x) { - qDebug() << "Enter easeOutQuad, x:" << x; + qCDebug(appLog) << "Enter easeOutQuad, x:" << x; return -1 * qPow(x - 1, 2) + 1; } qreal Utils::easeInQuint(qreal x) { - qDebug() << "Enter easeInQuint, x:" << x; + qCDebug(appLog) << "Enter easeInQuint, x:" << x; return qPow(x, 5); } qreal Utils::easeOutQuint(qreal x) { - qDebug() << "Enter easeOutQuint, x:" << x; + qCDebug(appLog) << "Enter easeOutQuint, x:" << x; return qPow(x - 1, 5) + 1; } QVariantMap Utils::getThemeMapFromPath(const QString &filepath) { - qDebug() << "Enter getThemeMapFromPath, filepath:" << filepath; + qCDebug(appLog) << "Enter getThemeMapFromPath, filepath:" << filepath; QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { - qDebug() << "Failed to open theme file:" << filepath; + qCDebug(appLog) << "Failed to open theme file:" << filepath; return QVariantMap(); } @@ -667,28 +668,28 @@ QVariantMap Utils::getThemeMapFromPath(const QString &filepath) QJsonDocument document = QJsonDocument::fromJson(jsonBytes); QJsonObject object = document.object(); - qDebug() << "Exit getThemeMapFromPath, object:" << object.toVariantMap(); + qCDebug(appLog) << "Exit getThemeMapFromPath, object:" << object.toVariantMap(); return object.toVariantMap(); } bool Utils::isMimeTypeSupport(const QString &filepath) { - qDebug() << "Enter isMimeTypeSupport, filepath:" << filepath; + qCDebug(appLog) << "Enter isMimeTypeSupport, filepath:" << filepath; QMimeType mime = QMimeDatabase().mimeTypeForFile(filepath, QMimeDatabase::MatchMode::MatchContent); QString mimeType = mime.name(); - qDebug() << "mimeType:" << mimeType; + qCDebug(appLog) << "mimeType:" << mimeType; if (mimeType.startsWith("text/")) { - qDebug() << "mimeType starts with text/"; + qCDebug(appLog) << "mimeType starts with text/"; return true; } if (filepath.endsWith("pub")) { - qDebug() << "filepath ends with pub"; + qCDebug(appLog) << "filepath ends with pub"; return true; } if (SupportedTextMimeTypes.contains(mimeType)) { - qDebug() << "mimeType contains textMimeTypes"; + qCDebug(appLog) << "mimeType contains textMimeTypes"; return true; } @@ -703,26 +704,26 @@ bool Utils::isMimeTypeSupport(const QString &filepath) continue; } if (mime.inherits(supported)) { - qDebug() << "mimeType inherits from supported type:" << supported; + qCDebug(appLog) << "mimeType inherits from supported type:" << supported; return true; } } } - qDebug() << "mimeType does not contain textMimeTypes"; + qCDebug(appLog) << "mimeType does not contain textMimeTypes"; return false; } bool Utils::isDraftFile(const QString &filepath) { - qDebug() << "Enter isDraftFile, filepath:" << filepath; + qCDebug(appLog) << "Enter isDraftFile, filepath:" << filepath; QString draftDir = QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()) .filePath("blank-files"); draftDir = QDir::cleanPath(draftDir); QString dir = QFileInfo(filepath).dir().absolutePath(); - qDebug() << "dir:" << dir; - qDebug() << "draftDir:" << draftDir; - qDebug() << "isDraftFile:" << (dir == draftDir); + qCDebug(appLog) << "dir:" << dir; + qCDebug(appLog) << "draftDir:" << draftDir; + qCDebug(appLog) << "isDraftFile:" << (dir == draftDir); return dir == draftDir; } @@ -732,25 +733,25 @@ bool Utils::isDraftFile(const QString &filepath) */ bool Utils::isBackupFile(const QString &filepath) { - qDebug() << "Enter isBackupFile, filepath:" << filepath; + qCDebug(appLog) << "Enter isBackupFile, filepath:" << filepath; QString backupDir = QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()) .filePath("backup-files"); QString dir = QFileInfo(filepath).dir().absolutePath(); - qDebug() << "dir:" << dir; - qDebug() << "backupDir:" << backupDir; - qDebug() << "isBackupFile:" << (dir == backupDir); + qCDebug(appLog) << "dir:" << dir; + qCDebug(appLog) << "backupDir:" << backupDir; + qCDebug(appLog) << "isBackupFile:" << (dir == backupDir); return dir == backupDir; } QStringList Utils::cleanPath(const QStringList &filePaths) { - qDebug() << "Enter cleanPath, filePaths:" << filePaths; + qCDebug(appLog) << "Enter cleanPath, filePaths:" << filePaths; QStringList paths; for (QString path : filePaths) { paths.push_back(QDir::cleanPath(path)); } - qDebug() << "Exit cleanPath, paths:" << paths; + qCDebug(appLog) << "Exit cleanPath, paths:" << paths; return paths; } @@ -761,15 +762,15 @@ QStringList Utils::cleanPath(const QStringList &filePaths) */ QString Utils::localDataPath() { - qDebug() << "Enter localDataPath"; + qCDebug(appLog) << "Enter localDataPath"; auto dataPaths = Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)); - qDebug() << "dataPaths:" << dataPaths; + qCDebug(appLog) << "dataPaths:" << dataPaths; return dataPaths.isEmpty() ? QDir::homePath() + "/.local/share/deepin/deepin-editor/" : dataPaths.first(); } const QStringList Utils::getEncodeList() { - qDebug() << "Enter getEncodeList"; + qCDebug(appLog) << "Enter getEncodeList"; QStringList encodeList; for (int mib : QTextCodec::availableMibs()) { @@ -777,54 +778,54 @@ const QStringList Utils::getEncodeList() QString encodeName = QString(codec->name()).toUpper(); if (encodeName != "UTF-8" && !encodeList.contains(encodeName)) { - qDebug() << "encodeName:" << encodeName; + qCDebug(appLog) << "encodeName:" << encodeName; encodeList.append(encodeName); } } - qDebug() << "encodeList:" << encodeList; + qCDebug(appLog) << "encodeList:" << encodeList; encodeList.sort(); encodeList.prepend("UTF-8"); - qDebug() << "Exit getEncodeList, encodeList:" << encodeList; + qCDebug(appLog) << "Exit getEncodeList, encodeList:" << encodeList; return encodeList; } QPixmap Utils::renderSVG(const QString &filePath, const QSize &size, bool bIsScale) { - qDebug() << "Enter renderSVG, filePath:" << filePath << "size:" << size << "bIsScale:" << bIsScale; + qCDebug(appLog) << "Enter renderSVG, filePath:" << filePath << "size:" << size << "bIsScale:" << bIsScale; int scaled = 1; if (qApp->devicePixelRatio() == 1.25 && bIsScale) { - qDebug() << "qApp->devicePixelRatio() == 1.25 && bIsScale"; + qCDebug(appLog) << "qApp->devicePixelRatio() == 1.25 && bIsScale"; scaled = 2; } - qDebug() << "scaled:" << scaled; + qCDebug(appLog) << "scaled:" << scaled; QPixmap pixmap(size * scaled); pixmap.fill(Qt::transparent); - qDebug() << "pixmap.fill(Qt::transparent)"; + qCDebug(appLog) << "pixmap.fill(Qt::transparent)"; QImageReader reader; - qDebug() << "reader.setFileName(filePath)"; + qCDebug(appLog) << "reader.setFileName(filePath)"; reader.setFileName(filePath); - qDebug() << "reader.canRead():" << reader.canRead(); + qCDebug(appLog) << "reader.canRead():" << reader.canRead(); if (reader.canRead()) { reader.setScaledSize(size * scaled); - qDebug() << "reader.setScaledSize(size * scaled)"; + qCDebug(appLog) << "reader.setScaledSize(size * scaled)"; pixmap = QPixmap::fromImage(reader.read()); - qDebug() << "pixmap.setDevicePixelRatio(scaled)"; + qCDebug(appLog) << "pixmap.setDevicePixelRatio(scaled)"; pixmap.setDevicePixelRatio(scaled); } else { - qDebug() << "reader.canRead() is false"; + qCDebug(appLog) << "reader.canRead() is false"; pixmap.load(filePath); } - qDebug() << "Exit renderSVG, pixmap:" << pixmap; + qCDebug(appLog) << "Exit renderSVG, pixmap:" << pixmap; return pixmap; } QList Utils::getHiglightColorList() { - qDebug() << "Enter getHiglightColorList"; + qCDebug(appLog) << "Enter getHiglightColorList"; QList listColor; listColor.append(QColor("#FFA503")); listColor.append(QColor("#FF1C49")); @@ -834,43 +835,43 @@ QList Utils::getHiglightColorList() listColor.append(QColor("#05EA6B")); listColor.append(QColor("#FEF144")); listColor.append(QColor("#D5D5D1")); - qDebug() << "Exit getHiglightColorList, listColor:" << listColor; + qCDebug(appLog) << "Exit getHiglightColorList, listColor:" << listColor; return listColor; } void Utils::clearChildrenFocus(QObject *objParent) { - qDebug() << "Enter clearChildrenFocus, objParent:" << objParent; + qCDebug(appLog) << "Enter clearChildrenFocus, objParent:" << objParent; // 可以获取焦点的控件名称列表 QStringList foucswidgetlist; // foucswidgetlist << "QLineEdit" << TERM_WIDGET_NAME; - // qDebug() << "checkChildrenFocus start" << objParent->children().size(); + // qCDebug(appLog) << "checkChildrenFocus start" << objParent->children().size(); for (QObject *obj : objParent->children()) { if (!obj->isWidgetType()) { - qDebug() << "obj is not a widget"; + qCDebug(appLog) << "obj is not a widget"; continue; } QWidget *widget = static_cast(obj); if (Qt::NoFocus != widget->focusPolicy()) { - qDebug() << "widget->focusPolicy() != Qt::NoFocus"; - // qDebug() << widget << widget->focusPolicy() << widget->metaObject()->className(); + qCDebug(appLog) << "widget->focusPolicy() != Qt::NoFocus"; + // qCDebug(appLog) << widget << widget->focusPolicy() << widget->metaObject()->className(); if (!foucswidgetlist.contains(widget->metaObject()->className())) { - qDebug() << "widget->setFocusPolicy(Qt::NoFocus)"; + qCDebug(appLog) << "widget->setFocusPolicy(Qt::NoFocus)"; widget->setFocusPolicy(Qt::NoFocus); } } - qDebug() << "clearChildrenFocus(obj)"; + qCDebug(appLog) << "clearChildrenFocus(obj)"; clearChildrenFocus(obj); } - // qDebug() << "checkChildrenFocus over" << objParent->children().size(); - qDebug() << "Exit clearChildrenFocus"; + // qCDebug(appLog) << "checkChildrenFocus over" << objParent->children().size(); + qCDebug(appLog) << "Exit clearChildrenFocus"; } void Utils::clearChildrenFoucusEx(QWidget *pWidget) { - qDebug() << "Enter clearChildrenFoucusEx, pWidget:" << pWidget; + qCDebug(appLog) << "Enter clearChildrenFoucusEx, pWidget:" << pWidget; pWidget->clearFocus(); QObjectList childern = pWidget->children(); @@ -880,20 +881,20 @@ void Utils::clearChildrenFoucusEx(QWidget *pWidget) foreach (QObject *child, childern) { if (!child->isWidgetType()) { - qDebug() << "child is not a widget"; + qCDebug(appLog) << "child is not a widget"; continue; } QWidget *obj = static_cast(child); - qDebug() << "clearChildrenFoucusEx(obj)"; + qCDebug(appLog) << "clearChildrenFoucusEx(obj)"; clearChildrenFoucusEx(obj); } - qDebug() << "Exit clearChildrenFoucusEx"; + qCDebug(appLog) << "Exit clearChildrenFoucusEx"; } void Utils::setChildrenFocus(QWidget *pWidget, Qt::FocusPolicy policy) { - qDebug() << "Enter setChildrenFocus, pWidget:" << pWidget << "policy:" << policy; + qCDebug(appLog) << "Enter setChildrenFocus, pWidget:" << pWidget << "policy:" << policy; pWidget->setFocusPolicy(policy); QObjectList childern = pWidget->children(); @@ -903,30 +904,30 @@ void Utils::setChildrenFocus(QWidget *pWidget, Qt::FocusPolicy policy) foreach (QObject *child, childern) { if (!child->isWidgetType()) { - qDebug() << "child is not a widget"; + qCDebug(appLog) << "child is not a widget"; continue; } QWidget *obj = static_cast(child); - qDebug() << "setChildrenFocus(obj, policy)"; + qCDebug(appLog) << "setChildrenFocus(obj, policy)"; setChildrenFocus(obj, policy); } - qDebug() << "Exit setChildrenFocus"; + qCDebug(appLog) << "Exit setChildrenFocus"; } int Utils::getProcessCountByName(const char *pstrName) { - qDebug() << "Enter getProcessCountByName, pstrName:" << pstrName; + qCDebug(appLog) << "Enter getProcessCountByName, pstrName:" << pstrName; if (NULL == pstrName || strlen(pstrName) == 0) { - qDebug() << "pstrName is null"; + qCDebug(appLog) << "pstrName is null"; return -1; } QProcess process; process.start("ps", QStringList() << "-ef"); if (!process.waitForFinished(5000)) { - qDebug() << "ps command timeout"; + qCDebug(appLog) << "ps command timeout"; return -1; } @@ -940,16 +941,16 @@ int Utils::getProcessCountByName(const char *pstrName) } } - qDebug() << "Exit getProcessCountByName, count:" << count; + qCDebug(appLog) << "Exit getProcessCountByName, count:" << count; return count; } void Utils::killProcessByName(const char *pstrName) { - qDebug() << "Enter killProcessByName, pstrName:" << pstrName; + qCDebug(appLog) << "Enter killProcessByName, pstrName:" << pstrName; if (pstrName == NULL || strlen(pstrName) == 0) { - qDebug() << "pstrName is null or empty"; + qCDebug(appLog) << "pstrName is null or empty"; return; } @@ -957,22 +958,22 @@ void Utils::killProcessByName(const char *pstrName) process.start("killall", QStringList() << QString::fromUtf8(pstrName)); process.waitForFinished(5000); - qDebug() << "Exit killProcessByName"; + qCDebug(appLog) << "Exit killProcessByName"; } QString Utils::getStringMD5Hash(const QString &input) { - qDebug() << "Enter getStringMD5Hash, input:" << input; + qCDebug(appLog) << "Enter getStringMD5Hash, input:" << input; QByteArray byteArray = input.toUtf8(); - qDebug() << "byteArray:" << byteArray; + qCDebug(appLog) << "byteArray:" << byteArray; QByteArray md5Path = QCryptographicHash::hash(byteArray, QCryptographicHash::Md5); - qDebug() << "md5Path:" << md5Path; + qCDebug(appLog) << "md5Path:" << md5Path; return md5Path.toHex(); } bool Utils::activeWindowFromDock(quintptr winId) { - qDebug() << "Enter activeWindowFromDock, winId:" << winId; + qCDebug(appLog) << "Enter activeWindowFromDock, winId:" << winId; bool bRet = false; // 优先采用V23接口 QDBusInterface dockDbusInterfaceV23( @@ -980,9 +981,9 @@ bool Utils::activeWindowFromDock(quintptr winId) if (dockDbusInterfaceV23.isValid()) { QDBusReply reply = dockDbusInterfaceV23.call("ActivateWindow", winId); if (!reply.isValid()) { - qDebug() << "call v23 org.deepin.dde.daemon.Dock1 failed" << reply.error(); + qCDebug(appLog) << "call v23 org.deepin.dde.daemon.Dock1 failed" << reply.error(); } else { - qDebug() << "call v23 org.deepin.dde.daemon.Dock1 success"; + qCDebug(appLog) << "call v23 org.deepin.dde.daemon.Dock1 success"; return true; } } @@ -992,61 +993,61 @@ bool Utils::activeWindowFromDock(quintptr winId) if (dockDbusInterfaceV20.isValid() && !bRet) { QDBusReply reply = dockDbusInterfaceV20.call("ActivateWindow", winId); if (!reply.isValid()) { - qDebug() << "call v20 com.deepin.dde.daemon.Dock failed" << reply.error(); + qCDebug(appLog) << "call v20 com.deepin.dde.daemon.Dock failed" << reply.error(); bRet = false; } else { - qDebug() << "call v20 com.deepin.dde.daemon.Dock success"; + qCDebug(appLog) << "call v20 com.deepin.dde.daemon.Dock success"; return true; } } - qDebug() << "Exit activeWindowFromDock, bRet:" << bRet; + qCDebug(appLog) << "Exit activeWindowFromDock, bRet:" << bRet; return bRet; } bool Utils::isShareDirAndReadOnly(const QString &filePath) { - qDebug() << "Enter isShareDirAndReadOnly, filePath:" << filePath; + qCDebug(appLog) << "Enter isShareDirAndReadOnly, filePath:" << filePath; bool ret = false; const QString sharePath = "/var/lib/samba/usershares"; QDir shareDir(sharePath); if (shareDir.exists()) { - qDebug() << "shareDir exists"; + qCDebug(appLog) << "shareDir exists"; QFileInfo fileInfo(filePath); auto name = fileInfo.dir().dirName(); if (shareDir.exists(name)) { - qDebug() << "shareDir.exists(name)"; + qCDebug(appLog) << "shareDir.exists(name)"; QFile file(sharePath + "/" + name); if (file.open(QIODevice::ReadOnly)) { QString fileContent = file.readAll(); - qDebug() << "fileContent:" << fileContent; + qCDebug(appLog) << "fileContent:" << fileContent; // 精确匹配权限字段 ":R":后跟逗号、行尾或文件末尾, // 避免 contains(":R") 子串误命中 ":RW" 等可写配置 if (fileContent.contains(QRegularExpression(":R(,|\\n|$)"))) ret = true; file.close(); } else { - qDebug() << "file.open(QIODevice::ReadOnly) failed"; + qCDebug(appLog) << "file.open(QIODevice::ReadOnly) failed"; } } } - qDebug() << "Exit isShareDirAndReadOnly, ret:" << ret; + qCDebug(appLog) << "Exit isShareDirAndReadOnly, ret:" << ret; return ret; } QString Utils::getSystemLan() { - qDebug() << "Enter getSystemLan"; + qCDebug(appLog) << "Enter getSystemLan"; if (!m_systemLanguage.isEmpty()) { - qDebug() << "m_systemLanguage is not empty"; + qCDebug(appLog) << "m_systemLanguage is not empty"; return m_systemLanguage; } else { switch (getSystemVersion()) { case V23: m_systemLanguage = QLocale::system().name(); - qDebug() << "m_systemLanguage:" << m_systemLanguage; + qCDebug(appLog) << "m_systemLanguage:" << m_systemLanguage; break; default: { QDBusInterface ie("com.deepin.daemon.LangSelector", @@ -1054,13 +1055,13 @@ QString Utils::getSystemLan() "com.deepin.daemon.LangSelector", QDBusConnection::sessionBus()); m_systemLanguage = ie.property("CurrentLocale").toString(); - qDebug() << "m_systemLanguage:" << m_systemLanguage; + qCDebug(appLog) << "m_systemLanguage:" << m_systemLanguage; break; } } - qDebug() << "getSystemLan is" << m_systemLanguage; - qDebug() << "Exit getSystemLan"; + qCDebug(appLog) << "getSystemLan is" << m_systemLanguage; + qCDebug(appLog) << "Exit getSystemLan"; return m_systemLanguage; } } @@ -1073,13 +1074,13 @@ QString Utils::getSystemLan() */ Utils::SystemVersion Utils::getSystemVersion() { - qDebug() << "Enter getSystemVersion"; + qCDebug(appLog) << "Enter getSystemVersion"; QString version = DSysInfo::majorVersion(); if (version.toInt() >= 23) { - qDebug() << "version.toInt() >= 23"; + qCDebug(appLog) << "version.toInt() >= 23"; return V23; } - qDebug() << "Exit getSystemVersion, version:" << version; + qCDebug(appLog) << "Exit getSystemVersion, version:" << version; // 其它版本默认V20 return V20; } @@ -1087,56 +1088,56 @@ Utils::SystemVersion Utils::getSystemVersion() // judge whether the protocol is wayland bool Utils::isWayland() { - qDebug() << "Enter isWayland"; + qCDebug(appLog) << "Enter isWayland"; static QString protocol; if (protocol.isEmpty()) { protocol = QProcessEnvironment::systemEnvironment().value("XDG_SESSION_TYPE"); } - qDebug() << "Exit isWayland, protocol:" << protocol; + qCDebug(appLog) << "Exit isWayland, protocol:" << protocol; return protocol.contains("wayland"); } QString Utils::lineFeed(const QString &text, int nWidth, const QFont &font, int nElidedRow) { - qDebug() << "Enter lineFeed, text:" << text << "nWidth:" << nWidth << "font:" << font << "nElidedRow:" << nElidedRow; + qCDebug(appLog) << "Enter lineFeed, text:" << text << "nWidth:" << nWidth << "font:" << font << "nElidedRow:" << nElidedRow; if (nElidedRow < 0) { - qDebug() << "nElidedRow < 0"; + qCDebug(appLog) << "nElidedRow < 0"; nElidedRow = 2; } - qDebug() << "nElidedRow:" << nElidedRow; + qCDebug(appLog) << "nElidedRow:" << nElidedRow; QString strText = text; QStringList strListLine; QFontMetrics fm(font); // 一行就直接中间截断显示 if (1 == nElidedRow) { - qDebug() << "1 == nElidedRow"; + qCDebug(appLog) << "1 == nElidedRow"; return fm.elidedText(text, Qt::ElideMiddle, nWidth); } - qDebug() << "strText:" << strText; + qCDebug(appLog) << "strText:" << strText; if (!strText.isEmpty()) { for (int i = 1; i <= strText.size(); i++) { if (fm.horizontalAdvance(strText.left(i)) >= nWidth) { - qDebug() << "fm.horizontalAdvance(strText.left(i)) >= nWidth"; + qCDebug(appLog) << "fm.horizontalAdvance(strText.left(i)) >= nWidth"; if (strListLine.size() + 1 == nElidedRow) { - qDebug() << "strListLine.size() + 1 == nElidedRow"; + qCDebug(appLog) << "strListLine.size() + 1 == nElidedRow"; break; } - qDebug() << "strListLine.append(strText.left(i - 1))"; + qCDebug(appLog) << "strListLine.append(strText.left(i - 1))"; strListLine.append(strText.left(i - 1)); strText = strText.right(strText.size() - i + 1); - qDebug() << "strText:" << strText; + qCDebug(appLog) << "strText:" << strText; i = 0; } } } - qDebug() << "strListLine:" << strListLine; + qCDebug(appLog) << "strListLine:" << strListLine; // 多行时,对最后一行字符左侧省略 if (!strListLine.isEmpty()) { strText = fm.elidedText(strText, Qt::ElideLeft, nWidth); strListLine.append(strText); strText = strListLine.join('\n'); } - qDebug() << "Exit lineFeed, strText:" << strText; + qCDebug(appLog) << "Exit lineFeed, strText:" << strText; return strText; } @@ -1150,12 +1151,12 @@ QString Utils::lineFeed(const QString &text, int nWidth, const QFont &font, int */ Utils::RegionIntersectType Utils::checkRegionIntersect(int x1, int y1, int x2, int y2) { - qDebug() << "Enter checkRegionIntersect, x1:" << x1 << "y1:" << y1 << "x2:" << x2 << "y2:" << y2; + qCDebug(appLog) << "Enter checkRegionIntersect, x1:" << x1 << "y1:" << y1 << "x2:" << x2 << "y2:" << y2; if (y1 < x2) { - qDebug() << "y1 < x2"; + qCDebug(appLog) << "y1 < x2"; return ERight; } else if (x1 > y2) { - qDebug() << "x1 > y2"; + qCDebug(appLog) << "x1 > y2"; return ELeft; } else { // 区间存在交集,判断交集类型 @@ -1165,20 +1166,20 @@ Utils::RegionIntersectType Utils::checkRegionIntersect(int x1, int y1, int x2, i bool outRightBound = y1 < y2; if (outLeftBound && outRightBound) { - qDebug() << "outLeftBound && outRightBound"; + qCDebug(appLog) << "outLeftBound && outRightBound"; return EIntersectOutter; } else if (outLeftBound) { - qDebug() << "outLeftBound"; + qCDebug(appLog) << "outLeftBound"; return EIntersectLeft; } else if (outRightBound) { - qDebug() << "outRightBound"; + qCDebug(appLog) << "outRightBound"; return EIntersectRight; } else { - qDebug() << "else"; + qCDebug(appLog) << "else"; return EIntersectInner; } } - qDebug() << "Exit checkRegionIntersect"; + qCDebug(appLog) << "Exit checkRegionIntersect"; } /** @@ -1187,37 +1188,37 @@ Utils::RegionIntersectType Utils::checkRegionIntersect(int x1, int y1, int x2, i */ QVector> Utils::getSupportEncoding() { - qDebug() << "Enter getSupportEncoding"; + qCDebug(appLog) << "Enter getSupportEncoding"; static QVector> s_groupEncodeVec; if (s_groupEncodeVec.isEmpty()) { - qDebug() << "s_groupEncodeVec is empty"; + qCDebug(appLog) << "s_groupEncodeVec is empty"; QVector> tmpEncodeVec; QFile file(":/encodes/encodes.ini"); QString data; if (file.open(QIODevice::ReadOnly)) { - qDebug() << "file.open(QIODevice::ReadOnly) success"; + qCDebug(appLog) << "file.open(QIODevice::ReadOnly) success"; data = QString::fromUtf8(file.readAll()); file.close(); } else { - qDebug() << "file.open(QIODevice::ReadOnly) failed"; + qCDebug(appLog) << "file.open(QIODevice::ReadOnly) failed"; } - qDebug() << "data:" << data; + qCDebug(appLog) << "data:" << data; QTextStream readStream(&data, QIODevice::ReadOnly); while (!readStream.atEnd()) { - qDebug() << "readStream.readLine()"; + qCDebug(appLog) << "readStream.readLine()"; QString group = readStream.readLine(); - qDebug() << "group:" << group; + qCDebug(appLog) << "group:" << group; if (!group.startsWith('[') || !group.endsWith(']')) { - qWarning() << "unexpected group line, skipped:" << group; + qCWarning(appLog) << "unexpected group line, skipped:" << group; continue; } QString key = group.mid(1, group.length() - 2).trimmed(); QString encodes = readStream.readLine(); - qDebug() << "encodes:" << encodes; + qCDebug(appLog) << "encodes:" << encodes; int eqIdx = encodes.indexOf('='); if (eqIdx == -1) { - qWarning() << "unexpected encodes line, skipped:" << encodes; + qCWarning(appLog) << "unexpected encodes line, skipped:" << encodes; continue; } QString value = encodes.mid(eqIdx + 1).trimmed(); @@ -1229,13 +1230,13 @@ QVector> Utils::getSupportEncoding() encodeNames.append(name); } } - qDebug() << "value:" << value; + qCDebug(appLog) << "value:" << value; tmpEncodeVec.append(QPair(key, encodeNames)); } - qDebug() << "tmpEncodeVec:" << tmpEncodeVec; + qCDebug(appLog) << "tmpEncodeVec:" << tmpEncodeVec; s_groupEncodeVec = tmpEncodeVec; } - qDebug() << "Exit getSupportEncoding, s_groupEncodeVec:" << s_groupEncodeVec; + qCDebug(appLog) << "Exit getSupportEncoding, s_groupEncodeVec:" << s_groupEncodeVec; return s_groupEncodeVec; } @@ -1244,58 +1245,58 @@ QVector> Utils::getSupportEncoding() */ QStringList Utils::getSupportEncodingList() { - qDebug() << "Enter getSupportEncodingList"; + qCDebug(appLog) << "Enter getSupportEncodingList"; QStringList encodingList; auto supportEncoding = getSupportEncoding(); - qDebug() << "supportEncoding:" << supportEncoding; + qCDebug(appLog) << "supportEncoding:" << supportEncoding; for (auto encodingData : supportEncoding) { encodingList.append(encodingData.second); } std::sort(encodingList.begin(), encodingList.end()); - qDebug() << "Exit getSupportEncodingList, encodingList:" << encodingList; + qCDebug(appLog) << "Exit getSupportEncodingList, encodingList:" << encodingList; return encodingList; } QString Utils::libPath(const QString &strlib) { - qDebug() << "Enter libPath, strlib:" << strlib; + qCDebug(appLog) << "Enter libPath, strlib:" << strlib; QDir dir; QString path = QLibraryInfo::location(QLibraryInfo::LibrariesPath); dir.setPath(path); QStringList list = dir.entryList(QStringList() << (strlib + "*"), QDir::NoDotAndDotDot | QDir::Files); // filter name with strlib - qDebug() << "list:" << list; + qCDebug(appLog) << "list:" << list; if (list.contains(strlib)) { - qDebug() << "list contains strlib"; + qCDebug(appLog) << "list contains strlib"; return strlib; } - qDebug() << "list does not contain strlib"; + qCDebug(appLog) << "list does not contain strlib"; list.sort(); - qDebug() << "list sorted:" << list; + qCDebug(appLog) << "list sorted:" << list; if (list.size() <= 0) { - qDebug() << "list size <= 0"; + qCDebug(appLog) << "list size <= 0"; return ""; } - qDebug() << "list size > 0"; + qCDebug(appLog) << "list size > 0"; return list.last(); } void Utils::loadCustomDLL() { - qDebug() << "Enter loadCustomDLL"; + qCDebug(appLog) << "Enter loadCustomDLL"; // 解析ZPD定制需求提供的库libzpdcallback.so LoadLibNames tmp; QByteArray zpdDll = Utils::libPath("libzpdcallback.so").toLatin1(); - qDebug() << "zpdDll:" << zpdDll; + qCDebug(appLog) << "zpdDll:" << zpdDll; if (QFile::exists(zpdDll)) { - qDebug() << "QFile::exists(zpdDll)"; + qCDebug(appLog) << "QFile::exists(zpdDll)"; tmp.chZPDDLL = zpdDll.data(); } else { - qDebug() << "QFile::exists(zpdDll) failed"; + qCDebug(appLog) << "QFile::exists(zpdDll) failed"; tmp.chZPDDLL = NULL; } setLibNames(tmp); - qDebug() << "Exit loadCustomDLL"; + qCDebug(appLog) << "Exit loadCustomDLL"; } /** @@ -1305,21 +1306,21 @@ void Utils::loadCustomDLL() */ bool Utils::enableClipCopy(const QString &filePath) { - qDebug() << "Enter enableClipCopy, filePath:" << filePath; + qCDebug(appLog) << "Enter enableClipCopy, filePath:" << filePath; #if _ZPD_ if (getLoadZPDLibsInstance()->m_document_clip_copy) { // intercept 输出为1,拦截操作 static const int disableFlag = 1; int intercept = 1; getLoadZPDLibsInstance()->m_document_clip_copy(filePath.toUtf8().data(), &intercept); - qDebug() << "intercept:" << intercept; + qCDebug(appLog) << "intercept:" << intercept; if (disableFlag == intercept) { - qWarning() << qPrintable("ZPD access control! Disable clip or copy document!"); + qCWarning(appLog) << qPrintable("ZPD access control! Disable clip or copy document!"); return false; } } #endif - qDebug() << "Exit enableClipCopy, return true"; + qCDebug(appLog) << "Exit enableClipCopy, return true"; return true; } @@ -1329,16 +1330,16 @@ bool Utils::enableClipCopy(const QString &filePath) */ void Utils::recordCloseFile(const QString &filePath) { - qDebug() << "Enter recordCloseFile, filePath:" << filePath; + qCDebug(appLog) << "Enter recordCloseFile, filePath:" << filePath; #if _ZPD_ if (getLoadZPDLibsInstance()->m_document_close) { - qDebug() << "getLoadZPDLibsInstance()->m_document_close"; + qCDebug(appLog) << "getLoadZPDLibsInstance()->m_document_close"; getLoadZPDLibsInstance()->m_document_close(filePath.toUtf8().data()); } else { - qDebug() << "getLoadZPDLibsInstance()->m_document_close is null"; + qCDebug(appLog) << "getLoadZPDLibsInstance()->m_document_close is null"; } #endif - qDebug() << "Exit recordCloseFile"; + qCDebug(appLog) << "Exit recordCloseFile"; } /** @@ -1348,7 +1349,7 @@ void Utils::recordCloseFile(const QString &filePath) */ void Utils::sendFloatMessageFixedFont(QWidget *par, const QIcon &icon, const QString &message) { - qDebug() << "Enter sendFloatMessageFixedFont, par:" << par << "icon:" << icon << "message:" << message; + qCDebug(appLog) << "Enter sendFloatMessageFixedFont, par:" << par << "icon:" << icon << "message:" << message; // 以下代码和 DMessageManager::sendMessage() 流程一致。 if (QWidget *content = par->findChild("_d_message_manager_content", Qt::FindDirectChildrenOnly)) { auto msgWidgets = content->findChildren(QString(), Qt::FindDirectChildrenOnly); @@ -1358,7 +1359,7 @@ void Utils::sendFloatMessageFixedFont(QWidget *par, const QIcon &icon, const QSt // TransientType 类型的通知消息,最多只允许同时显示三个 if (text_message_count >= 3) { - qDebug() << "text_message_count >= 3"; + qCDebug(appLog) << "text_message_count >= 3"; return; } } @@ -1369,16 +1370,16 @@ void Utils::sendFloatMessageFixedFont(QWidget *par, const QIcon &icon, const QSt floMsg->setIcon(icon); floMsg->setMessage(message); floMsg->setFont(qApp->font()); - qDebug() << "floMsg:" << floMsg; + qCDebug(appLog) << "floMsg:" << floMsg; #ifdef DTKWIDGET_CLASS_DSizeMode // 绑定 qApp 字体变更信号 QObject::connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::fontChanged, floMsg, [=](const QFont &font) { floMsg->setFont(font); }); #endif - qDebug() << "DMessageManager::instance()->sendMessage(par, floMsg)"; + qCDebug(appLog) << "DMessageManager::instance()->sendMessage(par, floMsg)"; DMessageManager::instance()->sendMessage(par, floMsg); - qDebug() << "Exit sendFloatMessageFixedFont"; + qCDebug(appLog) << "Exit sendFloatMessageFixedFont"; } /** @@ -1389,7 +1390,7 @@ void Utils::sendFloatMessageFixedFont(QWidget *par, const QIcon &icon, const QSt */ bool Utils::getSystemMemoryInfo(qlonglong &totalMemory, qlonglong &freeMemory) { - qDebug() << "Enter getSystemMemoryInfo"; + qCDebug(appLog) << "Enter getSystemMemoryInfo"; qlonglong memFree = 0; qlonglong buffers = 0; qlonglong cached = 0; @@ -1397,7 +1398,7 @@ bool Utils::getSystemMemoryInfo(qlonglong &totalMemory, qlonglong &freeMemory) QFile file(PROC_MEMINFO_PATH); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - qWarning() << "Utils: Failed to open" << PROC_MEMINFO_PATH << "for memory check."; + qCWarning(appLog) << "Utils: Failed to open" << PROC_MEMINFO_PATH << "for memory check."; return false; } @@ -1410,27 +1411,27 @@ bool Utils::getSystemMemoryInfo(qlonglong &totalMemory, qlonglong &freeMemory) line = stream.readLine(); if (line.startsWith("MemTotal:")) { totalMemory = line.section(':', 1, 1).trimmed().section(' ', 0, 0).toLongLong(&valueOk); - qDebug() << "totalMemory:" << totalMemory; + qCDebug(appLog) << "totalMemory:" << totalMemory; } else if (line.startsWith("MemFree:")) { memFree = line.section(':', 1, 1).trimmed().section(' ', 0, 0).toLongLong(&valueOk); - qDebug() << "memFree:" << memFree; + qCDebug(appLog) << "memFree:" << memFree; } else if (line.startsWith("Buffers:")) { buffers = line.section(':', 1, 1).trimmed().section(' ', 0, 0).toLongLong(&valueOk); - qDebug() << "buffers:" << buffers; + qCDebug(appLog) << "buffers:" << buffers; } else if (line.startsWith("Cached:")) { cached = line.section(':', 1, 1).trimmed().section(' ', 0, 0).toLongLong(&valueOk); - qDebug() << "cached:" << cached; + qCDebug(appLog) << "cached:" << cached; } else if (line.startsWith("MemAvailable:")) { freeMemory = line.section(':', 1, 1).trimmed().section(' ', 0, 0).toLongLong(&valueOk); - qDebug() << "freeMemory:" << freeMemory; + qCDebug(appLog) << "freeMemory:" << freeMemory; break; } if (stream.atEnd() && freeMemory == 0) { freeMemory = memFree + buffers + cached; - qDebug() << "freeMemory:" << freeMemory; + qCDebug(appLog) << "freeMemory:" << freeMemory; } } - qDebug() << "Exit getSystemMemoryInfo, totalMemory:" << totalMemory << "freeMemory:" << freeMemory; + qCDebug(appLog) << "Exit getSystemMemoryInfo, totalMemory:" << totalMemory << "freeMemory:" << freeMemory; return (totalMemory > 0 && freeMemory > 0); } @@ -1443,14 +1444,14 @@ bool Utils::getSystemMemoryInfo(qlonglong &totalMemory, qlonglong &freeMemory) */ bool Utils::isMemorySufficientForOperation(OperationType operationType, qlonglong operationDataSize, qlonglong currentDocumentSize) { - qDebug() << "Enter isMemorySufficientForOperation, operationType:" << operationType << "operationDataSize:" << operationDataSize << "currentDocumentSize:" << currentDocumentSize; + qCDebug(appLog) << "Enter isMemorySufficientForOperation, operationType:" << operationType << "operationDataSize:" << operationDataSize << "currentDocumentSize:" << currentDocumentSize; qlonglong memoryFree = 0; qlonglong memoryTotal = 0; if (!getSystemMemoryInfo(memoryTotal, memoryFree)) { // Conservatively allow the operation if memory info cannot be read - qWarning() << "Failed to get system memory info, conservatively allowing operation"; + qCWarning(appLog) << "Failed to get system memory info, conservatively allowing operation"; return true; } @@ -1463,7 +1464,7 @@ bool Utils::isMemorySufficientForOperation(OperationType operationType, qlonglon case OperationType::RawOperation: // Raw operation: Directly compare the data size with available memory if (operationDataSize > availableMemoryBytes) { - qWarning() << "Utils: Insufficient memory for raw operation. Needed:" << operationDataSize << "Available:" << availableMemoryBytes; + qCWarning(appLog) << "Utils: Insufficient memory for raw operation. Needed:" << operationDataSize << "Available:" << availableMemoryBytes; return false; } break; @@ -1472,7 +1473,7 @@ bool Utils::isMemorySufficientForOperation(OperationType operationType, qlonglon // Copy operation: Estimated memory consumption = data size * factor qlonglong estimatedMemoryNeeded = operationDataSize * COPY_CONSUME_MEMORY_MULTIPLE; if (estimatedMemoryNeeded > availableMemoryBytes) { - qWarning() << "Utils: Insufficient memory for copy operation. Needed(est):" << estimatedMemoryNeeded << "Available:" << availableMemoryBytes; + qCWarning(appLog) << "Utils: Insufficient memory for copy operation. Needed(est):" << estimatedMemoryNeeded << "Available:" << availableMemoryBytes; return false; } break; @@ -1486,13 +1487,13 @@ bool Utils::isMemorySufficientForOperation(OperationType operationType, qlonglon // Check if pasting the data itself would cause insufficient memory if (estimatedMemoryNeededForPaste > availableMemoryBytes) { - qWarning() << "Utils: Insufficient memory for paste operation (paste data). Needed(est):" << estimatedMemoryNeededForPaste << "Available:" << availableMemoryBytes; + qCWarning(appLog) << "Utils: Insufficient memory for paste operation (paste data). Needed(est):" << estimatedMemoryNeededForPaste << "Available:" << availableMemoryBytes; return false; } // Check if the estimated total document size after paste exceeds total system memory if (estimatedTotalDocMemory > totalMemoryBytes) { - qWarning() << "Utils: Paste operation might exceed total system memory. Estimated total doc memory:" << estimatedTotalDocMemory << "Total system memory:" << totalMemoryBytes; + qCWarning(appLog) << "Utils: Paste operation might exceed total system memory. Estimated total doc memory:" << estimatedTotalDocMemory << "Total system memory:" << totalMemoryBytes; return false; } @@ -1500,17 +1501,17 @@ bool Utils::isMemorySufficientForOperation(OperationType operationType, qlonglon const qlonglong DOC_SIZE_LIMIT_800MB = 800LL * DATA_SIZE_1024 * DATA_SIZE_1024; const qlonglong PASTE_SIZE_LIMIT_500KB = 500LL * DATA_SIZE_1024; if (currentDocumentSize > DOC_SIZE_LIMIT_800MB && operationDataSize > PASTE_SIZE_LIMIT_500KB) { - qWarning() << "Utils: Paste operation restricted. Document size exceeds 800MB and paste data exceeds 500KB."; + qCWarning(appLog) << "Utils: Paste operation restricted. Document size exceeds 800MB and paste data exceeds 500KB."; return false; } break; } default: - qDebug() << "default"; + qCDebug(appLog) << "default"; break; } - qDebug() << "Exit isMemorySufficientForOperation, return true"; + qCDebug(appLog) << "Exit isMemorySufficientForOperation, return true"; return true; // Memory is sufficient } diff --git a/src/controls/findbar.cpp b/src/controls/findbar.cpp index ac093e18f..de93bc6f2 100644 --- a/src/controls/findbar.cpp +++ b/src/controls/findbar.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "findbar.h" #include "../common/utils.h" @@ -19,12 +20,12 @@ const int s_FBCloseIconSizeCompact = 27; FindBar::FindBar(QWidget *parent) : DFloatingWidget(parent) { - qDebug() << "FindBar constructor start"; + qCDebug(appLog) << "FindBar constructor start"; // Init. //setWindowFlags(Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); hide(); setFixedHeight(60); - qDebug() << "FindBar initialized with height 60"; + qCDebug(appLog) << "FindBar initialized with height 60"; // Init layout and widgets. @@ -53,7 +54,7 @@ FindBar::FindBar(QWidget *parent) m_closeButton->setEnabledCircle(true); m_closeButton->setFlat(true); m_layout->setContentsMargins(16, 6, 10, 6); - qDebug() << "FindBar UI components initialized"; + qCDebug(appLog) << "FindBar UI components initialized"; m_layout->addWidget(m_findLabel); // 单独处理输入框,由于Qt坐标机制,奇数处理存在累计误差,导致显示效果和预期存在差异,添加 spacer 强制输入框居中 @@ -80,7 +81,7 @@ FindBar::FindBar(QWidget *parent) connect(m_editLine, &LineBar::returnPressed, this, &FindBar::handleContentChanged, Qt::QueuedConnection); connect(m_editLine, &LineBar::signal_sentText, this, &FindBar::receiveText, Qt::QueuedConnection); //connect(m_editLine, &LineBar::contentChanged, this, &FindBar::slot_ifClearSearchWord, Qt::QueuedConnection); - qDebug() << "FindBar signal connections established"; + qCDebug(appLog) << "FindBar signal connections established"; connect(m_findNextButton, &QPushButton::clicked, this, &FindBar::handleFindNext, Qt::QueuedConnection); connect(m_findPrevButton, &QPushButton::clicked, this, &FindBar::handleFindPrev, Qt::QueuedConnection); //connect(m_findPrevButton, &QPushButton::clicked, this, &FindBar::findPrev, Qt::QueuedConnection); @@ -92,26 +93,26 @@ FindBar::FindBar(QWidget *parent) updateSizeMode(); connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, &FindBar::updateSizeMode); #endif - qDebug() << "updateSizeMode success"; + qCDebug(appLog) << "updateSizeMode success"; } bool FindBar::isFocus() { - qDebug() << "isFocus"; + qCDebug(appLog) << "isFocus"; return m_editLine->lineEdit()->hasFocus(); } void FindBar::focus() { - qDebug() << "focus"; + qCDebug(appLog) << "focus"; m_editLine->lineEdit()->setFocus(); m_editLine->lineEdit()->selectAll(); - qDebug() << "focus success"; + qCDebug(appLog) << "focus success"; } void FindBar::activeInput(QString text, QString file, int row, int column, int scrollOffset) { - qDebug() << "Activating find bar with text:" << text << "for file:" << file; + qCDebug(appLog) << "Activating find bar with text:" << text << "for file:" << file; m_editLine->setMatchCount(0, 0); @@ -122,93 +123,93 @@ void FindBar::activeInput(QString text, QString file, int row, int column, int s // Show. QWidget::show(); - qDebug() << "Find bar shown for file:" << file; + qCDebug(appLog) << "Find bar shown for file:" << file; // Save file info for back to position. m_findFile = file; m_findFileRow = row; m_findFileColumn = column; m_findFileSrollOffset = scrollOffset; - qDebug() << "Saved position info - row:" << row << "column:" << column << "scrollOffset:" << scrollOffset; + qCDebug(appLog) << "Saved position info - row:" << row << "column:" << column << "scrollOffset:" << scrollOffset; // Focus. focus(); - qDebug() << "Find bar focused"; + qCDebug(appLog) << "Find bar focused"; } void FindBar::findCancel() { - qDebug() << "Find operation cancelled"; + qCDebug(appLog) << "Find operation cancelled"; m_editLine->setMatchCount(0, 0); QWidget::hide(); emit sigFindbarClose(); - qDebug() << "Find bar hidden and close signal emitted"; + qCDebug(appLog) << "Find bar hidden and close signal emitted"; } void FindBar::handleContentChanged() { QString text = m_editLine->lineEdit()->text(); - qDebug() << "Find content changed to:" << text; + qCDebug(appLog) << "Find content changed to:" << text; updateSearchKeyword(m_findFile, text); } void FindBar::handleFindPrev() { QString searchText = m_editLine->lineEdit()->text(); - qDebug() << "Finding previous occurrence of:" << searchText; + qCDebug(appLog) << "Finding previous occurrence of:" << searchText; findPrev(searchText); - qDebug() << "Find previous completed for:" << searchText; + qCDebug(appLog) << "Find previous completed for:" << searchText; } void FindBar::handleFindNext() { QString searchText = m_editLine->lineEdit()->text(); - qDebug() << "Finding next occurrence of:" << searchText; + qCDebug(appLog) << "Finding next occurrence of:" << searchText; findNext(searchText); - qDebug() << "Find next completed for:" << searchText; + qCDebug(appLog) << "Find next completed for:" << searchText; } void FindBar::hideEvent(QHideEvent *event) { //保留查询标记 //removeSearchKeyword(); - qDebug() << "FindBar hidden"; + qCDebug(appLog) << "FindBar hidden"; } bool FindBar::focusNextPrevChild(bool next) { - qDebug() << "focusNextPrevChild"; + qCDebug(appLog) << "focusNextPrevChild"; return false; } void FindBar::keyPressEvent(QKeyEvent *e) { const QString &key = Utils::getKeyshortcut(e); - qDebug() << "Key pressed:" << key; + qCDebug(appLog) << "Key pressed:" << key; if (key == "Esc") { - qDebug() << "Escape key pressed, hiding find bar"; + qCDebug(appLog) << "Escape key pressed, hiding find bar"; QWidget::hide(); emit sigFindbarClose(); } if (m_closeButton->hasFocus() && key == "Tab") { - qDebug() << "Tab key pressed while close button has focus"; + qCDebug(appLog) << "Tab key pressed while close button has focus"; m_editLine->lineEdit()->setFocus(); } else { DFloatingWidget::keyPressEvent(e); } if (key == "Enter") { - qDebug() << "Enter key pressed"; + qCDebug(appLog) << "Enter key pressed"; if (m_findPrevButton->hasFocus()) { - qDebug() << "Triggering find previous from keyboard"; + qCDebug(appLog) << "Triggering find previous from keyboard"; m_findPrevButton->click(); } if (m_findNextButton->hasFocus()) { - qDebug() << "Triggering find next from keyboard"; + qCDebug(appLog) << "Triggering find next from keyboard"; m_findNextButton->click(); } } - qDebug() << "keyPressEvent end"; + qCDebug(appLog) << "keyPressEvent end"; } /** @@ -217,13 +218,13 @@ void FindBar::keyPressEvent(QKeyEvent *e) */ void FindBar::updateSizeMode() { - qDebug() << "updateSizeMode"; + qCDebug(appLog) << "updateSizeMode"; #ifdef DTKWIDGET_CLASS_DSizeMode bool isCompact = DGuiApplicationHelper::isCompactMode(); - qDebug() << "Updating size mode, compact:" << isCompact; + qCDebug(appLog) << "Updating size mode, compact:" << isCompact; if (isCompact) { - qDebug() << "isCompact"; + qCDebug(appLog) << "isCompact"; setFixedHeight(s_FBHeightCompact); m_closeButton->setFixedSize(s_FBCloseBtnSizeCompact, s_FBCloseBtnSizeCompact); m_closeButton->setIconSize(QSize(s_FBCloseIconSizeCompact, s_FBCloseIconSizeCompact)); @@ -231,7 +232,7 @@ void FindBar::updateSizeMode() m_layout->setContentsMargins(s_FBContentMarginsCompact); m_layout->invalidate(); } else { - qDebug() << "is not compact"; + qCDebug(appLog) << "is not compact"; setFixedHeight(s_FBHeight); m_closeButton->setFixedSize(s_FBCloseBtnSize, s_FBCloseBtnSize); m_closeButton->setIconSize(QSize(s_FBCloseBtnSize, s_FBCloseBtnSize)); @@ -240,34 +241,34 @@ void FindBar::updateSizeMode() m_layout->invalidate(); } #endif - qDebug() << "updateSizeMode end"; + qCDebug(appLog) << "updateSizeMode end"; } void FindBar::setMismatchAlert(bool isAlert) { - qDebug() << "Setting mismatch alert:" << isAlert; + qCDebug(appLog) << "Setting mismatch alert:" << isAlert; m_editLine->setAlert(isAlert); } void FindBar::receiveText(QString t) { - qDebug() << "receiveText"; + qCDebug(appLog) << "receiveText"; searched = false; if (t != "") { m_receivedText = t; } - qDebug() << "receiveText end"; + qCDebug(appLog) << "receiveText end"; } void FindBar::setSearched(bool searched) { - qDebug() << "Setting searched state:" << searched; + qCDebug(appLog) << "Setting searched state:" << searched; this->searched = searched; } void FindBar::findPreClicked() { - qDebug() << "findPreClicked"; + qCDebug(appLog) << "findPreClicked"; if (!searched) { updateSearchKeyword(m_findFile, m_editLine->lineEdit()->text()); emit findPrev(m_editLine->lineEdit()->text()); @@ -275,19 +276,19 @@ void FindBar::findPreClicked() } else { emit findPrev(m_editLine->lineEdit()->text()); } - qDebug() << "findPreClicked end"; + qCDebug(appLog) << "findPreClicked end"; } void FindBar::handleSwitchToReplace() { - qDebug() << "handleSwitchToReplace - switching from find bar to replace bar"; + qCDebug(appLog) << "handleSwitchToReplace - switching from find bar to replace bar"; emit sigSwitchToReplaceBar(); - qDebug() << "Switch to replace bar signal emitted"; + qCDebug(appLog) << "Switch to replace bar signal emitted"; } void FindBar::slotUpdateMatchCount(int current, int total) { - qDebug() << "slotUpdateMatchCount current:" << current << "total:" << total; + qCDebug(appLog) << "slotUpdateMatchCount current:" << current << "total:" << total; m_editLine->setMatchCount(current, total); } diff --git a/src/controls/fontitemdelegate.cpp b/src/controls/fontitemdelegate.cpp index fb710fe5a..13c9ba56e 100644 --- a/src/controls/fontitemdelegate.cpp +++ b/src/controls/fontitemdelegate.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2017 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2017-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "fontitemdelegate.h" #include #include @@ -9,28 +10,28 @@ FontItemDelegate::FontItemDelegate(QObject *parent) : QStyledItemDelegate(parent) { - qDebug() << "FontItemDelegate constructor"; + qCDebug(appLog) << "FontItemDelegate constructor"; } FontItemDelegate::~FontItemDelegate() { - qDebug() << "FontItemDelegate destructor"; + qCDebug(appLog) << "FontItemDelegate destructor"; } void FontItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - // qDebug() << "FontItemDelegate paint"; + // qCDebug(appLog) << "FontItemDelegate paint"; const QString text = index.data(Qt::DisplayRole).toString(); bool isSelected = option.state & QStyle::State_Selected; - // qDebug() << "isSelected" << isSelected; + // qCDebug(appLog) << "isSelected" << isSelected; painter->setPen(Qt::black); - // qDebug() << "setPen"; + // qCDebug(appLog) << "setPen"; if (isSelected) { painter->setPen(Qt::NoPen); painter->setBrush(QColor("#2CA7F8")); painter->drawRect(option.rect); painter->setPen(Qt::white); - // qDebug() << "setPen white"; + // qCDebug(appLog) << "setPen white"; } QFont font(painter->font()); @@ -46,6 +47,6 @@ void FontItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti QSize FontItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { - // qDebug() << "FontItemDelegate sizeHint"; + // qCDebug(appLog) << "FontItemDelegate sizeHint"; return QSize(-1, 30); } diff --git a/src/controls/jumplinebar.cpp b/src/controls/jumplinebar.cpp index c9c47218b..0fe7c7bd8 100644 --- a/src/controls/jumplinebar.cpp +++ b/src/controls/jumplinebar.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "jumplinebar.h" // #include @@ -28,13 +29,13 @@ const int s_nCloseButtonSizeCompact = 27; JumpLineBar::JumpLineBar(DFloatingWidget *parent) : DFloatingWidget(parent) { - qDebug() << "JumpLineBar constructor start"; + qCDebug(appLog) << "JumpLineBar constructor start"; // Init layout and widgets. m_layout = new QHBoxLayout(); m_layout->setContentsMargins(10, 0, 10, 0); m_layout->setAlignment(Qt::AlignVCenter); m_layout->setSpacing(5); - qDebug() << "Base layout initialized"; + qCDebug(appLog) << "Base layout initialized"; m_closeButton = new DIconButton(DStyle::SP_CloseButton); m_closeButton->setObjectName("JumpCloseButton"); m_closeButton->setIconSize(QSize(30, 30)); @@ -75,30 +76,30 @@ JumpLineBar::JumpLineBar(DFloatingWidget *parent) updateSizeMode(); connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, &JumpLineBar::updateSizeMode); #endif - qDebug() << "JumpLineBar constructor end"; + qCDebug(appLog) << "JumpLineBar constructor end"; } JumpLineBar::~JumpLineBar() { - qDebug() << "JumpLineBar destructor"; + qCDebug(appLog) << "JumpLineBar destructor"; } void JumpLineBar::focus() { - qDebug() << "focus"; + qCDebug(appLog) << "focus"; m_pSpinBoxInput->lineEdit()->setFocus(); - qDebug() << "focus success"; + qCDebug(appLog) << "focus success"; } bool JumpLineBar::isFocus() { - qDebug() << "isFocus"; + qCDebug(appLog) << "isFocus"; return m_pSpinBoxInput->lineEdit()->hasFocus(); } void JumpLineBar::activeInput(QString file, int row, int column, int lineCount, int scrollOffset) { - qDebug() << "Activating input for file:" << file + qCDebug(appLog) << "Activating input for file:" << file << "row:" << row << "column:" << column << "lineCount:" << lineCount; // Save file info for back to line. @@ -112,50 +113,50 @@ void JumpLineBar::activeInput(QString file, int row, int column, int lineCount, m_pSpinBoxInput->setRange(0, lineCount); int lineWidth = QString::number(lineCount).size() * fontMetrics().horizontalAdvance('9'); if (m_pSpinBoxInput->minimumWidth() < lineWidth) { - qDebug() << "lineWidth" << lineWidth; + qCDebug(appLog) << "lineWidth" << lineWidth; m_pSpinBoxInput->setFixedWidth(lineWidth); } else { - qDebug() << "lineWidth" << lineWidth; + qCDebug(appLog) << "lineWidth" << lineWidth; m_pSpinBoxInput->setFixedWidth(s_nJumpLineBarSpinBoxWidth); } - qDebug() << "setFixedWidth"; + qCDebug(appLog) << "setFixedWidth"; setFixedWidth(m_layout->sizeHint().width() + s_nJumpLineBarHorizenMargin); // Clear line number. if (m_pSpinBoxInput->lineEdit()->text().toInt() > lineCount) { - qDebug() << "Clearing invalid line number input"; + qCDebug(appLog) << "Clearing invalid line number input"; m_pSpinBoxInput->lineEdit()->setText(""); } - qDebug() << "activeInput end"; + qCDebug(appLog) << "activeInput end"; } void JumpLineBar::handleFocusOut() { - qDebug() << "handleFocusOut"; + qCDebug(appLog) << "handleFocusOut"; //hide(); lostFocusExit(); - qDebug() << "handleFocusOut end"; + qCDebug(appLog) << "handleFocusOut end"; } void JumpLineBar::handleLineChanged() { - qDebug() << "handleLineChanged"; + qCDebug(appLog) << "handleLineChanged"; QString content = m_pSpinBoxInput->lineEdit()->text(); if (content != "") { - qDebug() << "content" << content; + qCDebug(appLog) << "content" << content; if (content.toInt() == 0) { m_pSpinBoxInput->clear(); - qDebug() << "clear"; + qCDebug(appLog) << "clear"; return; } jumpToLine(m_jumpFile, content.toInt(), false); } - qDebug() << "handleLineChanged end"; + qCDebug(appLog) << "handleLineChanged end"; } void JumpLineBar::jumpCancel() { - qDebug() << "jumpCancel"; + qCDebug(appLog) << "jumpCancel"; hide(); // esc键不跳转 返回当前 // backToPosition(m_jumpFile, m_rowBeforeJump, m_columnBeforeJump, m_jumpFileScrollOffset); @@ -163,45 +164,45 @@ void JumpLineBar::jumpCancel() void JumpLineBar::jumpConfirm() { - qDebug() << "jumpConfirm"; + qCDebug(appLog) << "jumpConfirm"; QString content = m_pSpinBoxInput->lineEdit()->text(); if (content != "") { - qDebug() << "content" << content; + qCDebug(appLog) << "content" << content; jumpToLine(m_jumpFile, content.toInt(), true); } - qDebug() << "jumpConfirm end"; + qCDebug(appLog) << "jumpConfirm end"; } void JumpLineBar::slotFocusChanged(bool bFocus) { - qDebug() << "slotFocusChanged"; + qCDebug(appLog) << "slotFocusChanged"; if (bFocus == false) { lostFocusExit(); - qDebug() << "slotFocusChanged end"; + qCDebug(appLog) << "slotFocusChanged end"; } } // Hide 跳转到行窗口时,需要清空编辑框中的内容 void JumpLineBar::hide() { - qDebug() << "hide"; + qCDebug(appLog) << "hide"; m_pSpinBoxInput->clear(); DFloatingWidget::hide(); - qDebug() << "hide end"; + qCDebug(appLog) << "hide end"; } int JumpLineBar::getLineCount() { - qDebug() << "getLineCount"; + qCDebug(appLog) << "getLineCount"; return m_lineCount; } bool JumpLineBar::eventFilter(QObject *pObject, QEvent *pEvent) { - qDebug() << "eventFilter"; + qCDebug(appLog) << "eventFilter"; if (pObject == m_pSpinBoxInput) { if (pEvent->type() == QEvent::FocusOut) { - qDebug() << "FocusOut"; + qCDebug(appLog) << "FocusOut"; handleFocusOut(); /** * 规避当DSpinBox输入框里为空且失去focus焦点时会显示上一次输入的数值内容的问题 @@ -211,7 +212,7 @@ bool JumpLineBar::eventFilter(QObject *pObject, QEvent *pEvent) } } } - qDebug() << "eventFilter end"; + qCDebug(appLog) << "eventFilter end"; return DFloatingWidget::eventFilter(pObject, pEvent); } @@ -221,13 +222,13 @@ bool JumpLineBar::eventFilter(QObject *pObject, QEvent *pEvent) */ void JumpLineBar::updateSizeMode() { - qDebug() << "updateSizeMode"; + qCDebug(appLog) << "updateSizeMode"; #ifdef DTKWIDGET_CLASS_DSizeMode bool isCompact = DGuiApplicationHelper::isCompactMode(); - qDebug() << "Updating size mode, compact:" << isCompact; + qCDebug(appLog) << "Updating size mode, compact:" << isCompact; if (isCompact) { - qDebug() << "isCompact"; + qCDebug(appLog) << "isCompact"; m_layout->setContentsMargins(s_JLBCompactMarigins); m_closeButton->setIconSize(QSize(s_nCloseButtonSizeCompact, s_nCloseButtonSizeCompact)); m_closeButton->setFixedSize(QSize(s_nCloseButtonSizeCompact, s_nCloseButtonSizeCompact)); @@ -235,7 +236,7 @@ void JumpLineBar::updateSizeMode() setMinimumWidth(s_nJumpLineBarWidthCompact); setFixedHeight(s_nJumpLineBarHeightCompact); } else { - qDebug() << "is not compact"; + qCDebug(appLog) << "is not compact"; m_layout->setContentsMargins(s_JLBDefaultMarigins); m_closeButton->setIconSize(QSize(s_nCloseButtonSize, s_nCloseButtonSize)); m_closeButton->setFixedSize(QSize(s_nCloseButtonSize, s_nCloseButtonSize)); @@ -244,6 +245,6 @@ void JumpLineBar::updateSizeMode() setFixedHeight(s_nJumpLineBarHeight); } #endif - qDebug() << "updateSizeMode end"; + qCDebug(appLog) << "updateSizeMode end"; } diff --git a/src/controls/linebar.cpp b/src/controls/linebar.cpp index 77a25f77d..f1a943aa3 100644 --- a/src/controls/linebar.cpp +++ b/src/controls/linebar.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "linebar.h" #include "../common/utils.h" @@ -23,7 +24,7 @@ const int s_nRightMargin = 6; // 清除按钮右边缘距输入框右 LineBar::LineBar(DLineEdit *parent) : DLineEdit(parent) { - qDebug() << "LineBar constructor start"; + qCDebug(appLog) << "LineBar constructor start"; // ★ 关键:禁用 DLineEdit 内置清除按钮。 // 原因:Qt6 下 QLineEdit::addAction(TrailingPosition) 和 DLineEdit::setRightWidgets @@ -55,12 +56,12 @@ LineBar::LineBar(DLineEdit *parent) m_autoSaveInternal = 50; m_autoSaveTimer = new QTimer(this); m_autoSaveTimer->setSingleShot(true); - qDebug() << "Auto-save timer initialized with interval:" << m_autoSaveInternal << "ms"; + qCDebug(appLog) << "Auto-save timer initialized with interval:" << m_autoSaveInternal << "ms"; connect(m_autoSaveTimer, &QTimer::timeout, this, &LineBar::handleTextChangeTimer); connect(this, &DLineEdit::textEdited, this, &LineBar::sendText, Qt::QueuedConnection); connect(this, &DLineEdit::textChanged, this, &LineBar::handleTextChanged, Qt::QueuedConnection); - qDebug() << "Signal connections established"; + qCDebug(appLog) << "Signal connections established"; // 自绘清除按钮:点击清空文本;可见性跟随文本是否为空 connect(m_clearButton, &DIconButton::clicked, this, [this]() { @@ -77,7 +78,7 @@ LineBar::LineBar(DLineEdit *parent) void LineBar::handleTextChangeTimer() { - qDebug() << "Text change timer triggered, emitting contentChanged"; + qCDebug(appLog) << "Text change timer triggered, emitting contentChanged"; // Emit contentChanged signal. contentChanged(); } @@ -86,11 +87,11 @@ void LineBar::handleTextChanged(const QString &str) { // Stop timer if new character is typed, avoid unused timer run. if (m_autoSaveTimer->isActive()) { - qDebug() << "Restarting text change timer"; + qCDebug(appLog) << "Restarting text change timer"; m_autoSaveTimer->stop(); } if(str.isEmpty()) { - qDebug() << "Text cleared, disabling alert"; + qCDebug(appLog) << "Text cleared, disabling alert"; setAlert(false); m_clearButton->hide(); // 文本为空时隐藏清除按钮 } else { @@ -98,7 +99,7 @@ void LineBar::handleTextChanged(const QString &str) } // Start new timer. m_autoSaveTimer->start(m_autoSaveInternal); - qDebug() << "Text changed, length:" << str.length(); + qCDebug(appLog) << "Text changed, length:" << str.length(); } void LineBar::sendText(QString t) @@ -108,7 +109,7 @@ void LineBar::sendText(QString t) void LineBar::focusOutEvent(QFocusEvent *e) { - qDebug() << "Focus lost"; + qCDebug(appLog) << "Focus lost"; // Emit focus out signal. focusOut(); @@ -120,19 +121,19 @@ void LineBar::keyPressEvent(QKeyEvent *e) { QString key = Utils::getKeyshortcut(e); Qt::KeyboardModifiers modifiers = e->modifiers(); - qDebug() << "Key pressed:" << key << "modifiers:" << modifiers; + qCDebug(appLog) << "Key pressed:" << key << "modifiers:" << modifiers; if(modifiers == Qt::ControlModifier && e->text() == "\r"){ - qDebug() << "Ctrl+Enter pressed"; + qCDebug(appLog) << "Ctrl+Enter pressed"; pressCtrlEnter(); }else if(modifiers == Qt::AltModifier && e->text() == "\r"){ - qDebug() << "Alt+Enter pressed"; + qCDebug(appLog) << "Alt+Enter pressed"; pressAltEnter(); }else if(modifiers == Qt::MetaModifier && e->text() == "\r"){ - qDebug() << "Meta+Enter pressed"; + qCDebug(appLog) << "Meta+Enter pressed"; pressMetaEnter(); }else if(modifiers == Qt::NoModifier && e->text() == "\r"){ - qDebug() << "Enter pressed"; + qCDebug(appLog) << "Enter pressed"; pressEnter(); }else { // Pass event to DLineEdit continue, otherwise you can't type anything after here. ;) diff --git a/src/controls/replacebar.cpp b/src/controls/replacebar.cpp index 66d467d68..89be76a0f 100644 --- a/src/controls/replacebar.cpp +++ b/src/controls/replacebar.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "replacebar.h" #include "../common/utils.h" @@ -19,11 +20,11 @@ const int s_RBCloseIconSizeCompact = 27; ReplaceBar::ReplaceBar(QWidget *parent) : DFloatingWidget(parent) { - qDebug() << "ReplaceBar constructor start"; + qCDebug(appLog) << "ReplaceBar constructor start"; // Init. hide(); setFixedHeight(60); - qDebug() << "ReplaceBar initialized with height 60"; + qCDebug(appLog) << "ReplaceBar initialized with height 60"; // Init layout and widgets. m_layout = new QHBoxLayout(); m_layout->setSpacing(10); @@ -102,172 +103,172 @@ ReplaceBar::ReplaceBar(QWidget *parent) updateSizeMode(); connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, &ReplaceBar::updateSizeMode); #endif - qDebug() << "ReplaceBar constructor end"; + qCDebug(appLog) << "ReplaceBar constructor end"; } bool ReplaceBar::isFocus() { - qDebug() << "isFocus"; + qCDebug(appLog) << "isFocus"; return m_replaceLine->hasFocus(); } void ReplaceBar::focus() { - qDebug() << "focus"; + qCDebug(appLog) << "focus"; m_replaceLine->lineEdit()->setFocus(); - qDebug() << "focus success"; + qCDebug(appLog) << "focus success"; } void ReplaceBar::activeInput(QString text, QString file, int row, int column, int scrollOffset) { - qDebug() << "Activating replace bar for file:" << file + qCDebug(appLog) << "Activating replace bar for file:" << file << "at row:" << row << "column:" << column; // Try fill keyword with select text. m_withLine->lineEdit()->clear(); m_replaceLine->lineEdit()->clear(); m_replaceLine->lineEdit()->insert(text); m_replaceLine->lineEdit()->selectAll(); - qDebug() << "Initial search text set, length:" << text.length(); + qCDebug(appLog) << "Initial search text set, length:" << text.length(); // Show. show(); - qDebug() << "Replace bar shown"; + qCDebug(appLog) << "Replace bar shown"; // Save file info for back to position. m_replaceFile = file; m_replaceFileRow = row; m_replaceFileColumn = column; m_replaceFileSrollOffset = scrollOffset; - qDebug() << "Saved position info - row:" << row + qCDebug(appLog) << "Saved position info - row:" << row << "column:" << column << "scrollOffset:" << scrollOffset; // Focus. focus(); - qDebug() << "Focus set to replace input"; + qCDebug(appLog) << "Focus set to replace input"; } void ReplaceBar::handleSkip() { - qDebug() << "handleSkip"; + qCDebug(appLog) << "handleSkip"; emit replaceSkip(m_replaceFile, m_replaceLine->lineEdit()->text()); } void ReplaceBar::replaceClose() { - qDebug() << "replaceClose"; + qCDebug(appLog) << "replaceClose"; searched = false; m_replaceLine->setMatchCount(0, 0); hide(); emit sigReplacebarClose(); - qDebug() << "replaceClose end"; + qCDebug(appLog) << "replaceClose end"; } void ReplaceBar::handleContentChanged() { - qDebug() << "handleContentChanged"; + qCDebug(appLog) << "handleContentChanged"; updateSearchKeyword(m_replaceFile, m_replaceLine->lineEdit()->text()); } void ReplaceBar::slotUpdateMatchCount(int current, int total) { - qDebug() << "ReplaceBar slotUpdateMatchCount current:" << current << "total:" << total; + qCDebug(appLog) << "ReplaceBar slotUpdateMatchCount current:" << current << "total:" << total; m_replaceLine->setMatchCount(current, total); } void ReplaceBar::handleReplaceNext() { - qDebug() << "handleReplaceNext"; + qCDebug(appLog) << "handleReplaceNext"; QString searchText = m_replaceLine->lineEdit()->text(); QString replaceText = m_withLine->lineEdit()->text(); - qDebug() << "Replacing next occurrence, search length:" + qCDebug(appLog) << "Replacing next occurrence, search length:" << searchText.length() << "replace length:" << replaceText.length(); if (!searched) { - qDebug() << "First search, removing previous keywords"; + qCDebug(appLog) << "First search, removing previous keywords"; emit removeSearchKeyword(); emit beforeReplace(searchText); } replaceNext(m_replaceFile, searchText, replaceText); searched = true; - qDebug() << "Replace next completed"; + qCDebug(appLog) << "Replace next completed"; } void ReplaceBar::handleReplaceRest() { - qDebug() << "handleReplaceRest"; + qCDebug(appLog) << "handleReplaceRest"; replaceRest(m_replaceLine->lineEdit()->text(), m_withLine->lineEdit()->text()); } void ReplaceBar::handleReplaceAll() { - qDebug() << "handleReplaceAll"; + qCDebug(appLog) << "handleReplaceAll"; replaceAll(m_replaceLine->lineEdit()->text(), m_withLine->lineEdit()->text()); } void ReplaceBar::hideEvent(QHideEvent *) { - qDebug() << "hideEvent"; + qCDebug(appLog) << "hideEvent"; searched = false; removeSearchKeyword(); } bool ReplaceBar::focusNextPrevChild(bool) { - qDebug() << "focusNextPrevChild"; + qCDebug(appLog) << "focusNextPrevChild"; // Make keyword jump between two EditLine widgets. auto *editWidget = qobject_cast(focusWidget()); if (editWidget != nullptr) { - qDebug() << "editWidget" << editWidget; + qCDebug(appLog) << "editWidget" << editWidget; if (editWidget == m_replaceLine) { m_withLine->lineEdit()->setFocus(); - qDebug() << "focus withLine"; + qCDebug(appLog) << "focus withLine"; return true; } else if (editWidget == m_withLine) { m_replaceLine->lineEdit()->setFocus(); - qDebug() << "focus replaceLine"; + qCDebug(appLog) << "focus replaceLine"; return true; } } - qDebug() << "focusNextPrevChild end"; + qCDebug(appLog) << "focusNextPrevChild end"; return false; } void ReplaceBar::keyPressEvent(QKeyEvent *e) { - qDebug() << "keyPressEvent"; + qCDebug(appLog) << "keyPressEvent"; const QString &key = Utils::getKeyshortcut(e); if (key == "Esc") { - qDebug() << "Esc"; + qCDebug(appLog) << "Esc"; QWidget::hide(); emit sigReplacebarClose(); - qDebug() << "sigReplacebarClose"; + qCDebug(appLog) << "sigReplacebarClose"; } if (m_closeButton->hasFocus() && key == "Tab") { - qDebug() << "Tab"; + qCDebug(appLog) << "Tab"; m_replaceLine->lineEdit()->setFocus(); } else { DFloatingWidget::keyPressEvent(e); } if (key == "Enter") { - qDebug() << "Enter"; + qCDebug(appLog) << "Enter"; if (m_replaceAllButton->hasFocus()) { - qDebug() << "replaceAllButton"; + qCDebug(appLog) << "replaceAllButton"; m_replaceAllButton->click(); } if (m_replaceButton->hasFocus()) { - qDebug() << "replaceButton"; + qCDebug(appLog) << "replaceButton"; m_replaceButton->click(); } if (m_replaceRestButton->hasFocus()) { - qDebug() << "replaceRestButton"; + qCDebug(appLog) << "replaceRestButton"; m_replaceRestButton->click(); } if (m_replaceSkipButton->hasFocus()) { - qDebug() << "replaceSkipButton"; + qCDebug(appLog) << "replaceSkipButton"; m_replaceSkipButton->click(); } } - qDebug() << "keyPressEvent end"; + qCDebug(appLog) << "keyPressEvent end"; } /** @@ -276,13 +277,13 @@ void ReplaceBar::keyPressEvent(QKeyEvent *e) */ void ReplaceBar::updateSizeMode() { - qDebug() << "updateSizeMode"; + qCDebug(appLog) << "updateSizeMode"; #ifdef DTKWIDGET_CLASS_DSizeMode bool isCompact = DGuiApplicationHelper::isCompactMode(); - qDebug() << "Updating size mode, compact:" << isCompact; + qCDebug(appLog) << "Updating size mode, compact:" << isCompact; if (isCompact) { - qDebug() << "isCompact"; + qCDebug(appLog) << "isCompact"; setFixedHeight(s_RBHeight_Compact); m_closeButton->setFixedSize(s_RBCloseBtnSizeCompact, s_RBCloseBtnSizeCompact); m_closeButton->setIconSize(QSize(s_RBCloseIconSizeCompact, s_RBCloseIconSizeCompact)); @@ -290,7 +291,7 @@ void ReplaceBar::updateSizeMode() m_layout->setContentsMargins(s_RBContetsMarginsCompact); m_layout->invalidate(); } else { - qDebug() << "is not compact"; + qCDebug(appLog) << "is not compact"; setFixedHeight(s_RBHeight); m_closeButton->setFixedSize(s_RBCloseBtnSize, s_RBCloseBtnSize); m_closeButton->setIconSize(QSize(s_RBCloseBtnSize, s_RBCloseBtnSize)); @@ -299,7 +300,7 @@ void ReplaceBar::updateSizeMode() m_layout->invalidate(); } #endif - qDebug() << "updateSizeMode end"; + qCDebug(appLog) << "updateSizeMode end"; } /** @@ -308,29 +309,29 @@ void ReplaceBar::updateSizeMode() */ QVBoxLayout *ReplaceBar::createVerticalLine(QWidget *content) const { - qDebug() << "createVerticalLine"; + qCDebug(appLog) << "createVerticalLine"; QVBoxLayout *lineBarLayout = new QVBoxLayout(); lineBarLayout->addItem(new QSpacerItem(1, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding)); lineBarLayout->addWidget(content); lineBarLayout->addItem(new QSpacerItem(1, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding)); - qDebug() << "createVerticalLine end"; + qCDebug(appLog) << "createVerticalLine end"; return lineBarLayout; } void ReplaceBar::setMismatchAlert(bool isAlert) { - qDebug() << "setMismatchAlert"; + qCDebug(appLog) << "setMismatchAlert"; m_replaceLine->setAlert(isAlert); } void ReplaceBar::setsearched(bool _) { - qDebug() << "setsearched"; + qCDebug(appLog) << "setsearched"; searched = _; } void ReplaceBar::change() { - qDebug() << "change"; + qCDebug(appLog) << "change"; searched = false; } diff --git a/src/controls/settingsdialog.cpp b/src/controls/settingsdialog.cpp index 2aed6344f..6d677a1f8 100644 --- a/src/controls/settingsdialog.cpp +++ b/src/controls/settingsdialog.cpp @@ -2,12 +2,13 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include #include void GenerateSettingTranslate() { - qDebug() << "GenerateSettingTranslate"; + qCDebug(appLog) << "GenerateSettingTranslate"; auto group_baseName = QObject::tr("Basic"); auto base_fontName = QObject::tr("Font Style"); auto base_font_familyName = QObject::tr("Font"); @@ -129,5 +130,5 @@ void GenerateSettingTranslate() auto Japanese = QObject::tr("Japanese"); auto Korean = QObject::tr("Korean"); auto Vietnamese = QObject::tr("Vietnamese"); - qDebug() << "GenerateSettingTranslate end"; + qCDebug(appLog) << "GenerateSettingTranslate end"; } diff --git a/src/controls/tabbar.cpp b/src/controls/tabbar.cpp index 9023b2f2d..c8c5b0b55 100644 --- a/src/controls/tabbar.cpp +++ b/src/controls/tabbar.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "tabbar.h" #include "../widgets/window.h" #include "../common/utils.h" @@ -32,10 +33,10 @@ const int s_TabbarHeightCompact = 26; */ QString replaceMnemonic(const QString &str) { - qDebug() << "Enter replaceMnemonic, str:" << str; + qCDebug(appLog) << "Enter replaceMnemonic, str:" << str; QString tmp = str; tmp.replace(QChar('&'), QString("&&")); - qDebug() << "Exit replaceMnemonic, tmp:" << tmp; + qCDebug(appLog) << "Exit replaceMnemonic, tmp:" << tmp; return tmp; } @@ -44,17 +45,17 @@ QString replaceMnemonic(const QString &str) */ QString restoreMnemonic(const QString &str) { - qDebug() << "Enter restoreMnemonic, str:" << str; + qCDebug(appLog) << "Enter restoreMnemonic, str:" << str; QString tmp = str; tmp.replace(QString("&&"), QChar('&')); - qDebug() << "Exit restoreMnemonic, tmp:" << tmp; + qCDebug(appLog) << "Exit restoreMnemonic, tmp:" << tmp; return tmp; } Tabbar::Tabbar(QWidget *parent) : DTabBar(parent) { - qDebug() << "Tabbar constructor start"; + qCDebug(appLog) << "Tabbar constructor start"; m_rightClickTab = -1; installEventFilter(this); @@ -74,7 +75,7 @@ Tabbar::Tabbar(QWidget *parent) setElideMode(Qt::ElideRight); setTabPalette(palette().buttonText().color().name(), palette().highlightedText().color().name()); setFocusPolicy(Qt::NoFocus); - qDebug() << "Tabbar initialized with movable and closable tabs"; + qCDebug(appLog) << "Tabbar initialized with movable and closable tabs"; connect(this, &DTabBar::dragStarted, this, &Tabbar::onTabDrapStart); connect(this, &DTabBar::tabMoved, this, &Tabbar::handleTabMoved); connect(this, &DTabBar::tabDroped, this, &Tabbar::handleTabDroped); @@ -88,7 +89,7 @@ Tabbar::Tabbar(QWidget *parent) this->update(); }); #endif - qDebug() << "Tabbar constructor end"; + qCDebug(appLog) << "Tabbar constructor end"; } Tabbar::~Tabbar() @@ -105,30 +106,30 @@ Tabbar::~Tabbar() void Tabbar::addTab(const QString &filePath, const QString &tabName, const QString &tipPath) { - qDebug() << "Enter addTab, filePath:" << filePath << "tabName:" << tabName; - qDebug() << "Adding tab for file:" << QFileInfo(filePath).fileName() + qCDebug(appLog) << "Enter addTab, filePath:" << filePath << "tabName:" << tabName; + qCDebug(appLog) << "Adding tab for file:" << QFileInfo(filePath).fileName() << "with name:" << tabName; - qDebug() << "Exit addTab"; + qCDebug(appLog) << "Exit addTab"; addTabWithIndex(count(), filePath, tabName, tipPath); } void Tabbar::addTabWithIndex(int index, const QString &filePath, const QString &tabName, const QString &tipPath) { - qDebug() << "Enter addTabWithIndex, index:" << index << "filePath:" << filePath << "tabName:" << tabName; + qCDebug(appLog) << "Enter addTabWithIndex, index:" << index << "filePath:" << filePath << "tabName:" << tabName; // FIXME(rekols): do not insert duplicate values. if (m_tabPaths.contains(filePath)) { - qDebug() << "m_tabPaths contains filePath"; + qCDebug(appLog) << "m_tabPaths contains filePath"; return; } - qDebug() << "m_tabPaths does not contain filePath"; + qCDebug(appLog) << "m_tabPaths does not contain filePath"; m_tabPaths.insert(index, filePath); m_tabTruePaths.insert(index, tipPath); - qDebug() << "Exit addTabWithIndex"; + qCDebug(appLog) << "Exit addTabWithIndex"; // } // 除去空白符 梁卫东 2020-08-26 14:49:15 ;适配助记符 QString trimmedName = replaceMnemonic(tabName.simplified()); - qDebug() << "trimmedName:" << trimmedName; + qCDebug(appLog) << "trimmedName:" << trimmedName; // Batch all layout-triggering operations to avoid jitter: // 1. Disable visual updates @@ -140,34 +141,34 @@ void Tabbar::addTabWithIndex(int index, const QString &filePath, const QString & DTabBar::insertTab(index, trimmedName); DTabBar::setCurrentIndex(index); - qDebug() << "filePath.contains(Utils::localDataPath())"; + qCDebug(appLog) << "filePath.contains(Utils::localDataPath())"; if (filePath.contains(Utils::localDataPath())) { if (Utils::isBackupFile(filePath) && !tipPath.isNull() && tipPath.length() > 0) { setTabToolTip(index, tipPath); - qDebug() << "tipPath is not null"; + qCDebug(appLog) << "tipPath is not null"; } else { setTabToolTip(index, tabName); - qDebug() << "tipPath is null"; + qCDebug(appLog) << "tipPath is null"; } } else { QString path = filePath; QFontMetrics fontMetrics(font()); int nFontWidth = fontMetrics.horizontalAdvance(path) * (qApp->devicePixelRatio() == 1.25 ? 2 : 1); - qDebug() << "nFontWidth:" << nFontWidth; + qCDebug(appLog) << "nFontWidth:" << nFontWidth; Window *pWindow = static_cast(this->window()); int w = pWindow->width() - 200; if (w < 800) w = 800; if (nFontWidth >= w) { int mod = nFontWidth % w; - qDebug() << "mod:" << mod; + qCDebug(appLog) << "mod:" << mod; int step = nFontWidth / w + (mod > 0 ? 1 : 0); - qDebug() << "step:" << step; + qCDebug(appLog) << "step:" << step; for (int i = 1; i < step; i++) { path.insert(i * (path.length() / step), '\n'); } } - qDebug() << "path:" << path; + qCDebug(appLog) << "path:" << path; setTabToolTip(index, path); } @@ -184,24 +185,24 @@ void Tabbar::addTabWithIndex(int index, const QString &filePath, const QString & void Tabbar::resizeEvent(QResizeEvent *event) { - qDebug() << "Enter resizeEvent"; + qCDebug(appLog) << "Enter resizeEvent"; int cnt = count(); - qDebug() << "cnt:" << cnt; + qCDebug(appLog) << "cnt:" << cnt; for (int i = 0; i < cnt ; i++) { QString path = tabToolTip(i); path = path.replace("\n", ""); QFontMetrics fontMetrics(font()); int nFontWidth = fontMetrics.horizontalAdvance(path) * (qApp->devicePixelRatio() == 1.25 ? 2 : 1); - qDebug() << "nFontWidth:" << nFontWidth; + qCDebug(appLog) << "nFontWidth:" << nFontWidth; Window *pWindow = static_cast(this->window()); int w = pWindow->width() - 200; if (w < 800) w = 800; - qDebug() << "w:" << w; + qCDebug(appLog) << "w:" << w; if (nFontWidth >= w) { int mod = nFontWidth % w; - qDebug() << "mod:" << mod; + qCDebug(appLog) << "mod:" << mod; int step = nFontWidth / w + (mod > 0 ? 1 : 0); - qDebug() << "step:" << step; + qCDebug(appLog) << "step:" << step; for (int j = 1; j < step; j++) { path.insert(j * (path.length() / step), '\n'); } @@ -215,82 +216,82 @@ void Tabbar::resizeEvent(QResizeEvent *event) setIconSize(iconSize()); DTabBar::resizeEvent(event); - qDebug() << "Exit resizeEvent"; + qCDebug(appLog) << "Exit resizeEvent"; } void Tabbar::closeTab(int index) { - qDebug() << "Enter closeTab, index:" << index; + qCDebug(appLog) << "Enter closeTab, index:" << index; if (index < 0) { - qWarning() << "Attempt to close tab with invalid index:" << index; + qCWarning(appLog) << "Attempt to close tab with invalid index:" << index; return; } - qDebug() << "index >= 0"; + qCDebug(appLog) << "index >= 0"; QString file = fileAt(index); - qDebug() << "Closing tab index:" << index + qCDebug(appLog) << "Closing tab index:" << index << "file:" << QFileInfo(file).fileName(); emit requestHistorySaved(file); DTabBar::removeTab(index); - qDebug() << "Exit closeTab"; + qCDebug(appLog) << "Exit closeTab"; } void Tabbar::closeCurrentTab() { - qDebug() << "Enter closeCurrentTab"; + qCDebug(appLog) << "Enter closeCurrentTab"; closeTab(currentIndex()); - qDebug() << "Exit closeCurrentTab"; + qCDebug(appLog) << "Exit closeCurrentTab"; } void Tabbar::closeCurrentTab(const QString &strFilePath) { - qDebug() << "Enter closeCurrentTab, strFilePath:" << strFilePath; + qCDebug(appLog) << "Enter closeCurrentTab, strFilePath:" << strFilePath; closeTab(this->indexOf(strFilePath)); - qDebug() << "Exit closeCurrentTab"; + qCDebug(appLog) << "Exit closeCurrentTab"; } void Tabbar::closeOtherTabs() { - qDebug() << "Enter closeOtherTabs"; + qCDebug(appLog) << "Enter closeOtherTabs"; closeOtherTabsExceptFile(currentPath()); - qDebug() << "Exit closeOtherTabs"; + qCDebug(appLog) << "Exit closeOtherTabs"; } void Tabbar::closeOtherTabsExceptFile(const QString &filePath) { - qDebug() << "Enter closeOtherTabsExceptFile, filePath:" << filePath; + qCDebug(appLog) << "Enter closeOtherTabsExceptFile, filePath:" << filePath; QStringList closePathList; for (const QString &path : m_tabPaths) { if (filePath != path) { - qDebug() << "filePath != path"; + qCDebug(appLog) << "filePath != path"; closePathList << path; } } emit closeTabs(closePathList); - qDebug() << "Exit closeOtherTabsExceptFile"; + qCDebug(appLog) << "Exit closeOtherTabsExceptFile"; } void Tabbar::closeLeftTabs(const QString &filePath) { - qDebug() << "Enter closeLeftTabs, filePath:" << filePath; + qCDebug(appLog) << "Enter closeLeftTabs, filePath:" << filePath; QStringList closePathList; for (const QString &path : m_tabPaths) { if (filePath == path) { - qDebug() << "before break filePath == path"; + qCDebug(appLog) << "before break filePath == path"; break; } closePathList << path; } - qDebug() << "closePathList:" << closePathList; + qCDebug(appLog) << "closePathList:" << closePathList; emit closeTabs(closePathList); - qDebug() << "Exit closeLeftTabs"; + qCDebug(appLog) << "Exit closeLeftTabs"; } void Tabbar::closeRightTabs(const QString &filePath) { - qDebug() << "Enter closeRightTabs, filePath:" << filePath; + qCDebug(appLog) << "Enter closeRightTabs, filePath:" << filePath; QStringList closePathlist; @@ -298,19 +299,19 @@ void Tabbar::closeRightTabs(const QString &filePath) m_tabPaths.value(i); if (filePath == m_tabPaths.value(i)) { - qDebug() << "before break filePath == m_tabPaths.value(i)"; + qCDebug(appLog) << "before break filePath == m_tabPaths.value(i)"; break; } closePathlist << m_tabPaths.value(i); } - qDebug() << "closePathlist:" << closePathlist; + qCDebug(appLog) << "closePathlist:" << closePathlist; emit closeTabs(closePathlist); - qDebug() << "Exit closeRightTabs"; + qCDebug(appLog) << "Exit closeRightTabs"; } void Tabbar::updateTab(int index, const QString &filePath, const QString &tabName) { - qDebug() << "Updating tab index:" << index + qCDebug(appLog) << "Updating tab index:" << index << "file:" << QFileInfo(filePath).fileName() << "new name:" << tabName; // 适配助记符 '&' 后设置文本 @@ -320,92 +321,92 @@ void Tabbar::updateTab(int index, const QString &filePath, const QString &tabNam //show file path at tab,blank file only show it's name. if (filePath.contains(Utils::localDataPath())) { - qDebug() << "filePath contains Utils::localDataPath()"; + qCDebug(appLog) << "filePath contains Utils::localDataPath()"; setTabToolTip(index, tabName); } else { QString path = filePath; QFontMetrics fontMetrics(font()); int nFontWidth = fontMetrics.horizontalAdvance(path) * (qApp->devicePixelRatio() == 1.25 ? 2 : 1); - qDebug() << "nFontWidth:" << nFontWidth; + qCDebug(appLog) << "nFontWidth:" << nFontWidth; Window *pWindow = static_cast(this->window()); int w = pWindow->width() - 200; if (w < 800) w = 800; - qDebug() << "w:" << w; + qCDebug(appLog) << "w:" << w; if (nFontWidth >= w) { int mod = nFontWidth % w; - qDebug() << "mod:" << mod; + qCDebug(appLog) << "mod:" << mod; int step = nFontWidth / w + (mod > 0 ? 1 : 0); - qDebug() << "step:" << step; + qCDebug(appLog) << "step:" << step; for (int i = 1; i < step; i++) { path.insert(i * (path.length() / step), '\n'); } } - qDebug() << "path:" << path; + qCDebug(appLog) << "path:" << path; setTabToolTip(index, path); } - qDebug() << "Exit updateTab"; + qCDebug(appLog) << "Exit updateTab"; } void Tabbar::previousTab() { - qDebug() << "Enter previousTab"; + qCDebug(appLog) << "Enter previousTab"; int currentIndex = DTabBar::currentIndex(); - qDebug() << "currentIndex:" << currentIndex; + qCDebug(appLog) << "currentIndex:" << currentIndex; if (currentIndex <= 0) { DTabBar::setCurrentIndex(DTabBar::count() - 1); } else { DTabBar::setCurrentIndex(currentIndex - 1); } - qDebug() << "Exit previousTab"; + qCDebug(appLog) << "Exit previousTab"; } void Tabbar::nextTab() { - qDebug() << "Enter nextTab"; + qCDebug(appLog) << "Enter nextTab"; int currentIndex = DTabBar::currentIndex(); - qDebug() << "currentIndex:" << currentIndex; + qCDebug(appLog) << "currentIndex:" << currentIndex; if (currentIndex >= DTabBar::count() - 1) { DTabBar::setCurrentIndex(0); } else { DTabBar::setCurrentIndex(currentIndex + 1); } - qDebug() << "Exit nextTab"; + qCDebug(appLog) << "Exit nextTab"; } int Tabbar::indexOf(const QString &filePath) { - qDebug() << "Enter indexOf, filePath:" << filePath; + qCDebug(appLog) << "Enter indexOf, filePath:" << filePath; return m_tabPaths.indexOf(filePath); } QString Tabbar::currentName() const { - qDebug() << "Enter currentName"; + qCDebug(appLog) << "Enter currentName"; return textAt(currentIndex()); } QString Tabbar::currentPath() const { - qDebug() << "Enter currentPath"; + qCDebug(appLog) << "Enter currentPath"; return m_tabPaths.value(currentIndex()); } QString Tabbar::truePathAt(int index) const { - qDebug() << "Enter truePathAt, index:" << index; + qCDebug(appLog) << "Enter truePathAt, index:" << index; return m_tabTruePaths.value(index); } QString Tabbar::fileAt(int index) const { - qDebug() << "Enter fileAt, index:" << index; + qCDebug(appLog) << "Enter fileAt, index:" << index; return m_tabPaths.value(index); } QString Tabbar::textAt(int index) const { // 获取显示文本时恢复设置的助记符 '&' - qDebug() << "Enter textAt, index:" << index; + qCDebug(appLog) << "Enter textAt, index:" << index; return restoreMnemonic(DTabBar::tabText(index)); } @@ -414,17 +415,17 @@ QString Tabbar::textAt(int index) const */ void Tabbar::setTabText(int index, const QString &text) { - qDebug() << "Enter setTabText, index:" << index << "text:" << text; + qCDebug(appLog) << "Enter setTabText, index:" << index << "text:" << text; // 替换助记符 QString tmp = replaceMnemonic(text); - qDebug() << "tmp:" << tmp; + qCDebug(appLog) << "tmp:" << tmp; DTabBar::setTabText(index, tmp); - qDebug() << "Exit setTabText"; + qCDebug(appLog) << "Exit setTabText"; } void Tabbar::setTabPalette(const QString &activeColor, const QString &highlightColor) { - qDebug() << "Enter setTabPalette, activeColor:" << activeColor << "highlightColor:" << highlightColor; + qCDebug(appLog) << "Enter setTabPalette, activeColor:" << activeColor << "highlightColor:" << highlightColor; // Not recommend manually setPalette() #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) Q_UNUSED(activeColor) @@ -436,28 +437,28 @@ void Tabbar::setTabPalette(const QString &activeColor, const QString &highlightC pa.setColor(QPalette::Active, QPalette::WindowText, QColor(activeColor)); setPalette(pa); #endif - qDebug() << "Exit setTabPalette"; + qCDebug(appLog) << "Exit setTabPalette"; } void Tabbar::setBackground(const QString &startColor, const QString &endColor) { - qDebug() << "Enter setBackground, startColor:" << startColor << "endColor:" << endColor; + qCDebug(appLog) << "Enter setBackground, startColor:" << startColor << "endColor:" << endColor; m_backgroundStartColor = startColor; m_backgroundEndColor = endColor; - qDebug() << "Exit setBackground"; + qCDebug(appLog) << "Exit setBackground"; } void Tabbar::setDNDColor(const QString &startColor, const QString &endColor) { - qDebug() << "Enter setDNDColor, startColor:" << startColor << "endColor:" << endColor; + qCDebug(appLog) << "Enter setDNDColor, startColor:" << startColor << "endColor:" << endColor; m_dndStartColor = startColor; m_dndEndColor = endColor; - qDebug() << "Exit setDNDColor"; + qCDebug(appLog) << "Exit setDNDColor"; } QPixmap Tabbar::createDragPixmapFromTab(int index, const QStyleOptionTab &option, QPoint *hotspot) const { - qDebug() << "Enter createDragPixmapFromTab, index:" << index; + qCDebug(appLog) << "Enter createDragPixmapFromTab, index:" << index; Window *window = static_cast(this->window()); EditWrapper *wrapper = window->wrapper(fileAt(index)); @@ -484,7 +485,7 @@ QPixmap Tabbar::createDragPixmapFromTab(int index, const QStyleOptionTab &option painter.setRenderHint(QPainter::Antialiasing, true); if (!Utils::isWayland() && count() == 1) { - qDebug() << "Utils::isWayland() && count() == 1"; + qCDebug(appLog) << "Utils::isWayland() && count() == 1"; this->window()->showMinimized(); } @@ -509,7 +510,7 @@ QPixmap Tabbar::createDragPixmapFromTab(int index, const QStyleOptionTab &option shadowColor.setAlpha(80); painter.end(); - qDebug() << "painter.end()"; + qCDebug(appLog) << "painter.end()"; if (sm_pDragPixmap) delete sm_pDragPixmap; sm_pDragPixmap = new QPixmap(Utils::dropShadow(QPixmap::fromImage(backgroundImage), 5, shadowColor, QPoint(0, 0))); return Utils::dropShadow(QPixmap::fromImage(backgroundImage), 5, shadowColor, QPoint(0, 0)); @@ -523,9 +524,9 @@ QPixmap Tabbar::createDragPixmapFromTab(int index, const QStyleOptionTab &option QMimeData *Tabbar::createMimeDataFromTab(int index, const QStyleOptionTab &option) const { - qDebug() << "Enter createMimeDataFromTab, index:" << index; + qCDebug(appLog) << "Enter createMimeDataFromTab, index:" << index; const QString tabName = textAt(index); - qDebug() << "tabName:" << tabName; + qCDebug(appLog) << "tabName:" << tabName; Window *window = static_cast(this->window()); EditWrapper *wrapper = window->wrapper(fileAt(index)); @@ -533,7 +534,7 @@ QMimeData *Tabbar::createMimeDataFromTab(int index, const QStyleOptionTab &optio if (!wrapper) { //m_tabbar->closeCurrentTab(); - qDebug() << "wrapper is null"; + qCDebug(appLog) << "wrapper is null"; return nullptr; } @@ -550,11 +551,11 @@ QMimeData *Tabbar::createMimeDataFromTab(int index, const QStyleOptionTab &optio void Tabbar::insertFromMimeDataOnDragEnter(int index, const QMimeData *source) { - qDebug() << "Enter insertFromMimeDataOnDragEnter, index:" << index; + qCDebug(appLog) << "Enter insertFromMimeDataOnDragEnter, index:" << index; if (source == nullptr) { return; } - qDebug() << "source is not null"; + qCDebug(appLog) << "source is not null"; const QString tabName = QString::fromUtf8(source->data("dedit/tabbar")); QVariant pVar = source->property("wrapper"); EditWrapper *wrapper = static_cast(pVar.value()); @@ -565,7 +566,7 @@ void Tabbar::insertFromMimeDataOnDragEnter(int index, const QMimeData *source) Window *window = static_cast(this->window()); if (!wrapper) { - qDebug() << "wrapper is null"; + qCDebug(appLog) << "wrapper is null"; return; } @@ -574,59 +575,59 @@ void Tabbar::insertFromMimeDataOnDragEnter(int index, const QMimeData *source) wrapper->updateModifyStatus(source->property("isModified").toBool()); wrapper->OnUpdateHighlighter(); window->focusActiveEditor(); - qDebug() << "Exit insertFromMimeDataOnDragEnter"; + qCDebug(appLog) << "Exit insertFromMimeDataOnDragEnter"; } void Tabbar::insertFromMimeData(int index, const QMimeData *source) { - qDebug() << "Enter insertFromMimeData, index:" << index; + qCDebug(appLog) << "Enter insertFromMimeData, index:" << index; if (source == nullptr) { - qDebug() << "source is null"; + qCDebug(appLog) << "source is null"; return; } - qDebug() << "source is not null"; + qCDebug(appLog) << "source is not null"; const QString tabName = QString::fromUtf8(source->data("dedit/tabbar")); QVariant pVar = source->property("wrapper"); EditWrapper *wrapper = static_cast(pVar.value()); Window *window = static_cast(this->window()); if (!wrapper) { - qDebug() << "wrapper is null"; + qCDebug(appLog) << "wrapper is null"; return; } - //qDebug() << "insertFromMimeData"; + //qCDebug(appLog) << "insertFromMimeData"; window->addTabWithWrapper(wrapper, wrapper->textEditor()->getFilePath(), wrapper->textEditor()->getTruePath(), tabName, index); //window->currentWrapper()->textEditor()->setModified(source->property("isModified").toBool()); wrapper->updateModifyStatus(source->property("isModified").toBool()); wrapper->OnUpdateHighlighter(); window->focusActiveEditor(); - qDebug() << "Exit insertFromMimeData"; + qCDebug(appLog) << "Exit insertFromMimeData"; } bool Tabbar::canInsertFromMimeData(int index, const QMimeData *source) const { - qDebug() << "Enter canInsertFromMimeData, index:" << index; + qCDebug(appLog) << "Enter canInsertFromMimeData, index:" << index; return source->hasFormat("dedit/tabbar"); } void Tabbar::handleDragActionChanged(Qt::DropAction action) { - qDebug() << "Enter handleDragActionChanged"; + qCDebug(appLog) << "Enter handleDragActionChanged"; // Reset cursor to Qt::ArrowCursor if drag tab to TextEditor widget. if (action == Qt::IgnoreAction) { - qDebug() << "action == Qt::IgnoreAction"; + qCDebug(appLog) << "action == Qt::IgnoreAction"; if (dragIconWindow()) { QGuiApplication::changeOverrideCursor(Qt::ArrowCursor); DPlatformWindowHandle::setDisableWindowOverrideCursor(dragIconWindow(), true); } } else if (dragIconWindow()) { - qDebug() << "dragIconWindow()"; + qCDebug(appLog) << "dragIconWindow()"; DPlatformWindowHandle::setDisableWindowOverrideCursor(dragIconWindow(), false); if (QGuiApplication::overrideCursor()) QGuiApplication::changeOverrideCursor(QGuiApplication::overrideCursor()->shape()); } - qDebug() << "Exit handleDragActionChanged"; + qCDebug(appLog) << "Exit handleDragActionChanged"; } bool Tabbar::eventFilter(QObject *watched, QEvent *event) @@ -699,7 +700,7 @@ bool Tabbar::eventFilter(QObject *watched, QEvent *event) m_moreWaysCloseMenu->addAction(m_closeAllunModifiedTabAction); if (m_tabPaths.length() < 2) { - qDebug() << "m_tabPaths.length() < 2"; + qCDebug(appLog) << "m_tabPaths.length() < 2"; m_closeOtherTabAction->setEnabled(false); m_closeLeftTabAction->setEnabled(false); m_closeRightTabAction->setEnabled(false); @@ -707,36 +708,36 @@ bool Tabbar::eventFilter(QObject *watched, QEvent *event) //优化tab菜单显示 梁卫东 if (m_rightClickTab == 0 && indexCount == 1) { - qDebug() << "m_rightClickTab == 0 && indexCount == 1"; + qCDebug(appLog) << "m_rightClickTab == 0 && indexCount == 1"; m_closeLeftTabAction->setEnabled(false); m_closeRightTabAction->setEnabled(false); } else if (m_rightClickTab == 0 && indexCount > 1) { - qDebug() << "m_rightClickTab == 0 && indexCount > 1"; + qCDebug(appLog) << "m_rightClickTab == 0 && indexCount > 1"; m_closeLeftTabAction->setEnabled(false); m_closeRightTabAction->setEnabled(true); } else if (m_rightClickTab == indexCount - 1 && indexCount == 1) { - qDebug() << "m_rightClickTab == indexCount - 1 && indexCount == 1"; + qCDebug(appLog) << "m_rightClickTab == indexCount - 1 && indexCount == 1"; m_closeLeftTabAction->setEnabled(false); m_closeRightTabAction->setEnabled(false); } else if (m_rightClickTab == indexCount - 1 && indexCount > 1) { - qDebug() << "m_rightClickTab == indexCount - 1 && indexCount > 1"; + qCDebug(appLog) << "m_rightClickTab == indexCount - 1 && indexCount > 1"; m_closeLeftTabAction->setEnabled(true); m_closeRightTabAction->setEnabled(false); } else { - qDebug() << "else"; + qCDebug(appLog) << "else"; m_closeLeftTabAction->setEnabled(true); m_closeRightTabAction->setEnabled(true); } //showTabs(); - qDebug() << "connect(m_closeTabAction, &QAction::triggered, this, [ = ]"; + qCDebug(appLog) << "connect(m_closeTabAction, &QAction::triggered, this, [ = ]"; connect(m_closeTabAction, &QAction::triggered, this, [ = ] { - qDebug() << "m_closeTabAction triggered"; + qCDebug(appLog) << "m_closeTabAction triggered"; Q_EMIT tabCloseRequested(m_rightClickTab); }); - qDebug() << "connect(m_closeOtherTabAction, &QAction::triggered, this, [ = ]"; + qCDebug(appLog) << "connect(m_closeOtherTabAction, &QAction::triggered, this, [ = ]"; connect(m_closeOtherTabAction, &QAction::triggered, this, [ = ] { - qDebug() << "m_closeOtherTabAction triggered"; + qCDebug(appLog) << "m_closeOtherTabAction triggered"; closeOtherTabsExceptFile(fileAt(m_rightClickTab)); }); @@ -789,15 +790,15 @@ bool Tabbar::eventFilter(QObject *watched, QEvent *event) m_rightMenu->addMenu(m_moreWaysCloseMenu); //yanyuhan 只有一个标签页时不显示更多方式关闭 if (m_tabPaths.size() > 1) { - qDebug() << "m_tabPaths.size() > 1"; + qCDebug(appLog) << "m_tabPaths.size() > 1"; m_moreWaysCloseMenu->setEnabled(true); } else { - qDebug() << "m_tabPaths.size() <= 1"; + qCDebug(appLog) << "m_tabPaths.size() <= 1"; m_moreWaysCloseMenu->setEnabled(false); } m_rightMenu->exec(mapToGlobal(position)); - qDebug() << "m_rightMenu->exec(mapToGlobal(position))"; + qCDebug(appLog) << "m_rightMenu->exec(mapToGlobal(position))"; return true; } } @@ -810,17 +811,17 @@ bool Tabbar::eventFilter(QObject *watched, QEvent *event) return true; } } else if (event->type() == QEvent::DragEnter) { - qDebug() << "event->type() == QEvent::DragEnter"; + qCDebug(appLog) << "event->type() == QEvent::DragEnter"; // if ((!e->source() || e->source()->parent() != this) && // mimeData->hasFormat("dedit/tabbar")) { // static_cast(this->window())->changeTitlebarBackground(m_dndStartColor, m_dndEndColor); // } } else if (event->type() == QEvent::DragLeave) { - qDebug() << "event->type() == QEvent::DragLeave"; + qCDebug(appLog) << "event->type() == QEvent::DragLeave"; } else if (event->type() == QEvent::Drop) { - qDebug() << "event->type() == QEvent::Drop"; + qCDebug(appLog) << "event->type() == QEvent::Drop"; } else if (event->type() == QEvent::DragMove) { - qDebug() << "event->type() == QEvent::DragMove"; + qCDebug(appLog) << "event->type() == QEvent::DragMove"; event->accept(); } return false; @@ -828,26 +829,26 @@ bool Tabbar::eventFilter(QObject *watched, QEvent *event) void Tabbar::mousePressEvent(QMouseEvent *e) { - qDebug() << "Enter mousePressEvent"; + qCDebug(appLog) << "Enter mousePressEvent"; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) bool midClick = (e->button() == Qt::MidButton); #else bool midClick = (e->button() == Qt::MiddleButton); #endif if (midClick) { - qDebug() << "midClick"; + qCDebug(appLog) << "midClick"; emit tabCloseRequested(tabAt(QPoint(e->x(), e->y()))); } - qDebug() << "Exit mousePressEvent"; + qCDebug(appLog) << "Exit mousePressEvent"; DTabBar::mousePressEvent(e); } void Tabbar::dropEvent(QDropEvent *e) { - qDebug() << "Enter dropEvent"; + qCDebug(appLog) << "Enter dropEvent"; if (e->dropAction() == Qt::CopyAction && e->mimeData()->hasFormat("dedit/tabbar")) { if (sm_pDragPixmap) { - qDebug() << "sm_pDragPixmap is not null"; + qCDebug(appLog) << "sm_pDragPixmap is not null"; QPoint cursorPos = QCursor::pos() - QPoint(sm_pDragPixmap->width() / 2, 20); DLabel *pLabel = new DLabel(); pLabel->setWindowFlags(Qt::FramelessWindowHint); @@ -870,12 +871,12 @@ void Tabbar::dropEvent(QDropEvent *e) } DTabBar::dropEvent(e); - qDebug() << "Exit dropEvent"; + qCDebug(appLog) << "Exit dropEvent"; } QSize Tabbar::tabSizeHint(int index) const { - qDebug() << "Enter tabSizeHint, index:" << index; + qCDebug(appLog) << "Enter tabSizeHint, index:" << index; if (index >= 0) { int total = this->width(); // 计算每个tab宽度:标签数未溢出时使用固定最大宽度,溢出时等分 @@ -894,38 +895,38 @@ QSize Tabbar::tabSizeHint(int index) const return QSize(tabWidth, 40); #endif } - qDebug() << "Exit tabSizeHint"; + qCDebug(appLog) << "Exit tabSizeHint"; return DTabBar::tabSizeHint(index); } QSize Tabbar::minimumTabSizeHint(int index) const { - qDebug() << "Enter minimumTabSizeHint, index:" << index; + qCDebug(appLog) << "Enter minimumTabSizeHint, index:" << index; Q_UNUSED(index) #ifdef DTKWIDGET_CLASS_DSizeMode return QSize(110, DGuiApplicationHelper::isCompactMode() ? s_TabbarHeightCompact : s_TabbarHeight); #else return QSize(110, 40); #endif - qDebug() << "Exit minimumTabSizeHint"; + qCDebug(appLog) << "Exit minimumTabSizeHint"; } QSize Tabbar::maximumTabSizeHint(int index) const { - qDebug() << "Enter maximumTabSizeHint, index:" << index; + qCDebug(appLog) << "Enter maximumTabSizeHint, index:" << index; Q_UNUSED(index) #ifdef DTKWIDGET_CLASS_DSizeMode return QSize(160, DGuiApplicationHelper::isCompactMode() ? s_TabbarHeightCompact : s_TabbarHeight); #else return QSize(160, 40); #endif - qDebug() << "Exit maximumTabSizeHint"; + qCDebug(appLog) << "Exit maximumTabSizeHint"; } void Tabbar::handleTabMoved(int fromIndex, int toIndex) { - qDebug() << "Enter handleTabMoved, fromIndex:" << fromIndex << "toIndex:" << toIndex; - //qDebug () << "handleTabMoved"; + qCDebug(appLog) << "Enter handleTabMoved, fromIndex:" << fromIndex << "toIndex:" << toIndex; + //qCDebug(appLog) << "handleTabMoved"; if (m_tabPaths.count() > fromIndex && m_tabPaths.count() > toIndex && fromIndex >= 0 && toIndex >= 0) { #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) m_tabPaths.swap(fromIndex, toIndex); @@ -935,12 +936,12 @@ void Tabbar::handleTabMoved(int fromIndex, int toIndex) m_tabTruePaths.swapItemsAt(fromIndex, toIndex); #endif } - qDebug() << "Exit handleTabMoved"; + qCDebug(appLog) << "Exit handleTabMoved"; } void Tabbar::showTabs() { - qDebug() << "Enter showTabs"; + qCDebug(appLog) << "Enter showTabs"; int currentIndex = DTabBar::currentIndex(); if (currentIndex <= 0) { m_closeLeftTabAction->setEnabled(false); @@ -948,19 +949,19 @@ void Tabbar::showTabs() if (currentIndex >= DTabBar::count() - 1) { m_closeRightTabAction->setEnabled(false); } - qDebug() << "Exit showTabs"; + qCDebug(appLog) << "Exit showTabs"; } void Tabbar::handleTabReleased(int index) { - qDebug() << "Enter handleTabReleased, index:" << index; + qCDebug(appLog) << "Enter handleTabReleased, index:" << index; if (index == -1) index = 0; QString path = m_listOldTabPath.value(index); if (path.isEmpty()) { - qDebug() << "path is empty"; + qCDebug(appLog) << "path is empty"; return; } - qDebug() << "path:" << path; + qCDebug(appLog) << "path:" << path; int newIndex = m_tabPaths.indexOf(path); const QString tabPath = fileAt(newIndex); const QString tabName = textAt(newIndex); @@ -968,7 +969,7 @@ void Tabbar::handleTabReleased(int index) Window *window = static_cast(this->window()); EditWrapper *wrapper = window->wrapper(tabPath); if (!wrapper) { - qDebug() << "wrapper is null"; + qCDebug(appLog) << "wrapper is null"; return; } @@ -977,23 +978,23 @@ void Tabbar::handleTabReleased(int index) closeTab(newIndex); // remove wrapper from window, not delete. window->removeWrapper(tabPath, false); - qDebug() << "Exit handleTabReleased"; + qCDebug(appLog) << "Exit handleTabReleased"; } void Tabbar::handleTabIsRemoved(int index) { - qDebug() << "Enter handleTabIsRemoved, index:" << index; + qCDebug(appLog) << "Enter handleTabIsRemoved, index:" << index; const QString filePath = m_tabPaths.at(index); Window *window = static_cast(this->window()); m_tabPaths.removeAt(index); m_tabTruePaths.removeAt(index); window->removeWrapper(filePath, false); - qDebug() << "Exit handleTabIsRemoved"; + qCDebug(appLog) << "Exit handleTabIsRemoved"; } void Tabbar::handleTabDroped(int index, Qt::DropAction action, QObject *target) { - qDebug() << "Enter handleTabDroped, index:" << index << "action:" << action << "target:" << target; + qCDebug(appLog) << "Enter handleTabDroped, index:" << index << "action:" << action << "target:" << target; Tabbar *tabbar = qobject_cast(target); if (tabbar == nullptr) { // tab页拖动到外部应用如网页电子表格或wps电子表格时, @@ -1001,22 +1002,22 @@ void Tabbar::handleTabDroped(int index, Qt::DropAction action, QObject *target) // 这种情况下DTabBar内容不能发出DTabBar::tabReleaseRequested来重新构建编辑窗口 // 因此只能再次添加判断,若目标文本编辑窗口的TabBar未创建,则重新重建文本编辑窗口 handleTabReleased(index); - qDebug() << "Exit handleTabDroped"; + qCDebug(appLog) << "Exit handleTabDroped"; } else { // QString path = m_listOldTabPath.value(index); // int newIndex = m_tabPaths.indexOf(path); - qDebug() << "closeTab(index)"; + qCDebug(appLog) << "closeTab(index)"; closeTab(index); // StartManager::instance()->setDragEnter(false); } - qDebug() << "Exit handleTabDroped"; + qCDebug(appLog) << "Exit handleTabDroped"; } void Tabbar::onTabDrapStart() { - qDebug() << "Tab drag operation started"; + qCDebug(appLog) << "Tab drag operation started"; Window *window = static_cast(this->window()); window->setChildrenFocus(false); m_listOldTabPath = m_tabPaths; - qDebug() << "Saved" << m_listOldTabPath.size() << "tabs for drag operation"; + qCDebug(appLog) << "Saved" << m_listOldTabPath.size() << "tabs for drag operation"; } diff --git a/src/controls/toolbar.cpp b/src/controls/toolbar.cpp index 861d622ed..9ba720ffd 100644 --- a/src/controls/toolbar.cpp +++ b/src/controls/toolbar.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2017 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2017-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "toolbar.h" #include #include @@ -13,20 +14,20 @@ ToolBar::ToolBar(QWidget *parent) : QWidget(parent), m_layout(new QHBoxLayout(this)) { - qDebug() << "ToolBar constructor start"; + qCDebug(appLog) << "ToolBar constructor start"; m_layout->setContentsMargins(0, 0, 0, 0); - qDebug() << "ToolBar layout initialized with zero margins"; + qCDebug(appLog) << "ToolBar layout initialized with zero margins"; } ToolBar::~ToolBar() { - qDebug() << "ToolBar destructor"; + qCDebug(appLog) << "ToolBar destructor"; } void ToolBar::setTabbar(QWidget *w) { - qDebug() << "Setting tabbar widget"; + qCDebug(appLog) << "Setting tabbar widget"; m_layout->addWidget(w, 0); m_layout->addSpacing(70); - qDebug() << "Tabbar widget added to toolbar with spacing"; + qCDebug(appLog) << "Tabbar widget added to toolbar with spacing"; } diff --git a/src/controls/warningnotices.cpp b/src/controls/warningnotices.cpp index b283eaa86..49cc3c96f 100644 --- a/src/controls/warningnotices.cpp +++ b/src/controls/warningnotices.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "warningnotices.h" #include @@ -18,7 +19,7 @@ const int s_WNCloseBtnSizeCompact = 26; WarningNotices::WarningNotices(MessageType notifyType, QWidget *parent) : DFloatingMessage(notifyType, parent) { - qDebug() << "WarningNotices constructor start, type:" << notifyType; + qCDebug(appLog) << "WarningNotices constructor start, type:" << notifyType; this->setFont(qApp->font()); setIcon(QIcon(":/images/warning.svg")); @@ -35,17 +36,17 @@ WarningNotices::WarningNotices(MessageType notifyType, QWidget *parent) m_saveAsBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_editAnywayBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_editAnywayBtn->setVisible(false); - qDebug() << "Warning buttons initialized"; + qCDebug(appLog) << "Warning buttons initialized"; connect(m_reloadBtn, &QPushButton::clicked, this, &WarningNotices::slotreloadBtnClicked); connect(m_saveAsBtn, &QPushButton::clicked, this, &WarningNotices::slotsaveAsBtnClicked); connect(m_editAnywayBtn, &QPushButton::clicked, this, &WarningNotices::slotEditAnywayBtnClicked); - qDebug() << "Warning button signals connected"; + qCDebug(appLog) << "Warning button signals connected"; #ifdef DTKWIDGET_CLASS_DSizeMode DDialogCloseButton *closeBtn = findChild(); if (closeBtn) { - qDebug() << "closeBtn is not null"; + qCDebug(appLog) << "closeBtn is not null"; closeBtn->setIconSize(DSizeModeHelper::element(QSize(26, 26), QSize(32, 32))); connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, [=]() { closeBtn->setIconSize(DSizeModeHelper::element(QSize(26, 26), QSize(32, 32))); @@ -61,82 +62,82 @@ WarningNotices::WarningNotices(MessageType notifyType, QWidget *parent) // TODO: wait dtkwidget fixed, see dtkwidget PR-628 connect(this, &DFloatingMessage::closeButtonClicked, this, [this]() { if (this->isVisible()) { - qDebug() << "closeButtonClicked"; + qCDebug(appLog) << "closeButtonClicked"; this->close(); } }); - qDebug() << "WarningNotices constructor end"; + qCDebug(appLog) << "WarningNotices constructor end"; } WarningNotices::~WarningNotices() { - qDebug() << "WarningNotices destructor"; + qCDebug(appLog) << "WarningNotices destructor"; } void WarningNotices::setReloadBtn() { - qDebug() << "setReloadBtn"; + qCDebug(appLog) << "setReloadBtn"; if (!m_reloadBtn->isVisible()) { - qDebug() << "m_reloadBtn->setVisible(true)"; + qCDebug(appLog) << "m_reloadBtn->setVisible(true)"; m_reloadBtn->setVisible(true); } - qDebug() << "m_reloadBtn->setVisible(true)"; + qCDebug(appLog) << "m_reloadBtn->setVisible(true)"; m_reloadBtn->setVisible(true); m_saveAsBtn->setVisible(false); setWidget(m_reloadBtn); - qDebug() << "setReloadBtn end"; + qCDebug(appLog) << "setReloadBtn end"; } void WarningNotices::setSaveAsBtn() { - qDebug() << "setSaveAsBtn"; + qCDebug(appLog) << "setSaveAsBtn"; if (!m_saveAsBtn->isVisible()) { m_saveAsBtn->setVisible(true); } m_saveAsBtn->setVisible(true); m_reloadBtn->setVisible(false); setWidget(m_saveAsBtn); - qDebug() << "setSaveAsBtn end"; + qCDebug(appLog) << "setSaveAsBtn end"; } void WarningNotices::clearBtn() { - qDebug() << "clearBtn"; + qCDebug(appLog) << "clearBtn"; m_saveAsBtn->setVisible(false); m_reloadBtn->setVisible(false); - qDebug() << "clearBtn end"; + qCDebug(appLog) << "clearBtn end"; } void WarningNotices::slotreloadBtnClicked() { - qDebug() << "slotreloadBtnClicked"; + qCDebug(appLog) << "slotreloadBtnClicked"; this->hide(); emit reloadBtnClicked(); - qDebug() << "slotreloadBtnClicked end"; + qCDebug(appLog) << "slotreloadBtnClicked end"; } void WarningNotices::slotsaveAsBtnClicked() { - qDebug() << "slotsaveAsBtnClicked"; + qCDebug(appLog) << "slotsaveAsBtnClicked"; this->hide(); emit saveAsBtnClicked(); - qDebug() << "slotsaveAsBtnClicked end"; + qCDebug(appLog) << "slotsaveAsBtnClicked end"; } void WarningNotices::setEditAnywayBtn() { - qDebug() << "setEditAnywayBtn"; + qCDebug(appLog) << "setEditAnywayBtn"; m_reloadBtn->setVisible(false); m_saveAsBtn->setVisible(false); m_editAnywayBtn->setVisible(true); setWidget(m_editAnywayBtn); - qDebug() << "setEditAnywayBtn end"; + qCDebug(appLog) << "setEditAnywayBtn end"; } void WarningNotices::slotEditAnywayBtnClicked() { - qDebug() << "slotEditAnywayBtnClicked"; + qCDebug(appLog) << "slotEditAnywayBtnClicked"; this->hide(); emit editAnywayBtnClicked(); - qDebug() << "slotEditAnywayBtnClicked end"; + qCDebug(appLog) << "slotEditAnywayBtnClicked end"; } diff --git a/src/ddlog.h b/src/ddlog.h new file mode 100644 index 000000000..56a715b9e --- /dev/null +++ b/src/ddlog.h @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef DDLOG_H +#define DDLOG_H + +#include +#include + +// 全应用统一的日志分类,便于 DConfig 动态日志规则(调试模式)按应用过滤 +inline Q_LOGGING_CATEGORY(appLog, "org.deepin.editor") + +#endif // DDLOG_H diff --git a/src/editor/FlashTween.cpp b/src/editor/FlashTween.cpp index 049d9318b..557442d11 100644 --- a/src/editor/FlashTween.cpp +++ b/src/editor/FlashTween.cpp @@ -2,12 +2,13 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "FlashTween.h" #include FlashTween::FlashTween() { - qDebug() << "FlashTween created"; + qCDebug(appLog) << "FlashTween created"; m_timerX = new QTimer(); QObject::connect(m_timerX, &QTimer::timeout, this ,&FlashTween::__runX); @@ -17,15 +18,15 @@ FlashTween::FlashTween() FlashTween::~FlashTween() { - qDebug() << "FlashTween destroyed"; + qCDebug(appLog) << "FlashTween destroyed"; if (m_timerX != nullptr) { - qDebug() << "delete m_timerX"; + qCDebug(appLog) << "delete m_timerX"; delete m_timerX; m_timerX = nullptr; } if (m_timerY != nullptr) { - qDebug() << "delete m_timerY"; + qCDebug(appLog) << "delete m_timerY"; delete m_timerY; m_timerY = nullptr; } @@ -33,7 +34,7 @@ FlashTween::~FlashTween() void FlashTween::startY(qreal t,qreal b,qreal c,qreal d, FunSlideInertial f) { - qInfo() << "FlashTween startY - time:" << t << "begin:" << b << "change:" << c << "duration:" << d; + qCInfo(appLog) << "FlashTween startY - time:" << t << "begin:" << b << "change:" << c << "duration:" << d; if(c==0.0 || d==0.0) return; m_currentTimeY = t; m_beginValueY = b; @@ -45,16 +46,16 @@ void FlashTween::startY(qreal t,qreal b,qreal c,qreal d, FunSlideInertial f) m_directionY = m_changeValueY<0?1:-1; if (m_timerY != nullptr) { - qDebug() << "m_timerY is not null"; + qCDebug(appLog) << "m_timerY is not null"; m_timerY->stop(); m_timerY->start(CELL_TIME); } - qDebug() << "FlashTween startY end"; + qCDebug(appLog) << "FlashTween startY end"; } void FlashTween::startX(qreal t,qreal b,qreal c,qreal d, FunSlideInertial f) { - qInfo() << "FlashTween startX - time:" << t << "begin:" << b << "change:" << c << "duration:" << d; + qCInfo(appLog) << "FlashTween startX - time:" << t << "begin:" << b << "change:" << c << "duration:" << d; if(c==0.0 || d==0.0) return; m_currentTimeX = t; m_beginValueX = b; @@ -66,11 +67,11 @@ void FlashTween::startX(qreal t,qreal b,qreal c,qreal d, FunSlideInertial f) m_directionX = m_changeValueX<0?1:-1; if (m_timerX != nullptr) { - qDebug() << "m_timerX is not null"; + qCDebug(appLog) << "m_timerX is not null"; m_timerX->stop(); m_timerX->start(CELL_TIME); } - qDebug() << "FlashTween startX end"; + qCDebug(appLog) << "FlashTween startX end"; } void FlashTween::__runY() @@ -78,21 +79,21 @@ void FlashTween::__runY() qreal tempValue = m_lastValueY; m_lastValueY = FlashTween::sinusoidalEaseOut(m_currentTimeY, m_beginValueY, abs(m_changeValueY), m_durationTimeY); m_fSlideGestureY(m_directionY*(m_lastValueY-tempValue)); - qDebug() << "FlashTween Y progress - current:" << m_currentTimeY << "/" << m_durationTimeY + qCDebug(appLog) << "FlashTween Y progress - current:" << m_currentTimeY << "/" << m_durationTimeY << "value:" << m_lastValueY << "delta:" << m_lastValueY-tempValue; if(m_currentTimeYstop(); } } - qDebug() << "FlashTween Y animation completed"; + qCDebug(appLog) << "FlashTween Y animation completed"; } void FlashTween::__runX() @@ -100,20 +101,20 @@ void FlashTween::__runX() qreal tempValue = m_lastValueX; m_lastValueX = FlashTween::sinusoidalEaseOut(m_currentTimeX, m_beginValueX, abs(m_changeValueX), m_durationTimeX); m_fSlideGestureX(m_directionX*(m_lastValueX - tempValue)); - qDebug() << "FlashTween X progress - current:" << m_currentTimeX << "/" << m_durationTimeX + qCDebug(appLog) << "FlashTween X progress - current:" << m_currentTimeX << "/" << m_durationTimeX << "value:" << m_lastValueX << "delta:" << m_lastValueX-tempValue; if(m_currentTimeXstop(); } } - qDebug() << "FlashTween X animation completed"; + qCDebug(appLog) << "FlashTween X animation completed"; } diff --git a/src/editor/bookmarkwidget.cpp b/src/editor/bookmarkwidget.cpp index dc3e7b3b0..6da364dbf 100644 --- a/src/editor/bookmarkwidget.cpp +++ b/src/editor/bookmarkwidget.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2019 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2019-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "bookmarkwidget.h" #include "leftareaoftextedit.h" #include @@ -9,13 +10,13 @@ BookMarkWidget::BookMarkWidget(LeftAreaTextEdit *leftAreaWidget) { - qDebug() << "BookMarkWidget constructor"; + qCDebug(appLog) << "BookMarkWidget constructor"; m_leftAreaWidget = leftAreaWidget; } BookMarkWidget::~BookMarkWidget() { - qDebug() << "BookMarkWidget destructor"; + qCDebug(appLog) << "BookMarkWidget destructor"; } void BookMarkWidget::paintEvent(QPaintEvent *event) diff --git a/src/editor/changemarkcommand.cpp b/src/editor/changemarkcommand.cpp index a1871e2ee..16aab1ba0 100644 --- a/src/editor/changemarkcommand.cpp +++ b/src/editor/changemarkcommand.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2020 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2020-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "changemarkcommand.h" #include @@ -11,7 +12,7 @@ ChangeMarkCommand::ChangeMarkCommand(QPointer editPtr, const QList editPtr, const QListmanualUpdateAllMark(oldMark); } - qDebug() << "ChangeMarkCommand undo end"; + qCDebug(appLog) << "ChangeMarkCommand undo end"; } void ChangeMarkCommand::redo() { - qDebug() << "Executing ChangeMarkCommand redo"; + qCDebug(appLog) << "Executing ChangeMarkCommand redo"; // 优先执行子撤销项,保证在文本操作后执行 QUndoCommand::redo(); // 插入文本后,更新颜色标记状态 if (m_EditPtr && !m_newMarkReplace.isEmpty()) { - qDebug() << "m_EditPtr is not null"; + qCDebug(appLog) << "m_EditPtr is not null"; auto newMark = TextEdit::convertReplaceToMark(m_newMarkReplace); m_EditPtr->manualUpdateAllMark(newMark); } - qDebug() << "ChangeMarkCommand redo end"; + qCDebug(appLog) << "ChangeMarkCommand redo end"; } diff --git a/src/editor/codeflodarea.cpp b/src/editor/codeflodarea.cpp index 7772fffe4..4f707dc76 100644 --- a/src/editor/codeflodarea.cpp +++ b/src/editor/codeflodarea.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2019 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2019-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "codeflodarea.h" #include "leftareaoftextedit.h" @@ -10,19 +11,19 @@ CodeFlodArea::CodeFlodArea(LeftAreaTextEdit *leftAreaWidget) { - qDebug() << "CodeFlodArea created"; + qCDebug(appLog) << "CodeFlodArea created"; m_pLeftAreaWidget = leftAreaWidget; } CodeFlodArea::~CodeFlodArea() { - qDebug() << "CodeFlodArea destroyed"; + qCDebug(appLog) << "CodeFlodArea destroyed"; } void CodeFlodArea::paintEvent(QPaintEvent *e) { - qDebug() << "CodeFlodArea paintEvent"; + qCDebug(appLog) << "CodeFlodArea paintEvent"; m_pLeftAreaWidget->codeFlodAreaPaintEvent(e); } diff --git a/src/editor/deletebackcommond.cpp b/src/editor/deletebackcommond.cpp index e192c0eb8..18f172503 100644 --- a/src/editor/deletebackcommond.cpp +++ b/src/editor/deletebackcommond.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "deletebackcommond.h" #include @@ -16,18 +17,18 @@ DeleteBackCommand::DeleteBackCommand(QTextCursor cursor, QPlainTextEdit *edit) m_delPos = std::min(m_cursor.position(), m_cursor.anchor()); m_insertPos = m_delPos; - qDebug() << "DeleteBackCommand created - delete pos:" << m_delPos + qCDebug(appLog) << "DeleteBackCommand created - delete pos:" << m_delPos << ", text length:" << m_delText.length(); } DeleteBackCommand::~DeleteBackCommand() { - qDebug() << "DeleteBackCommand destroyed"; + qCDebug(appLog) << "DeleteBackCommand destroyed"; } void DeleteBackCommand::undo() { - qDebug() << "DeleteBackCommand undo - inserting text at:" << m_insertPos + qCDebug(appLog) << "DeleteBackCommand undo - inserting text at:" << m_insertPos << ", length:" << m_delText.length(); if (nullptr == m_edit) { return; @@ -43,7 +44,7 @@ void DeleteBackCommand::undo() void DeleteBackCommand::redo() { - qDebug() << "DeleteBackCommand redo - deleting text at:" << m_delPos + qCDebug(appLog) << "DeleteBackCommand redo - deleting text at:" << m_delPos << ", length:" << m_delText.length(); if (nullptr == m_edit) { return; @@ -67,7 +68,7 @@ DeleteBackAltCommand::DeleteBackAltCommand(const QListrestoreColumnEditSelection(m_columnEditSelections); m_edit->setTextCursor(m_columnEditSelections.last().cursor); } - qDebug() << "DeleteBackAltCommand undo end"; + qCDebug(appLog) << "DeleteBackAltCommand undo end"; } void DeleteBackAltCommand::redo() { - qDebug() << "DeleteBackAltCommand redo - executing" << m_deletions.size() << "deletions"; + qCDebug(appLog) << "DeleteBackAltCommand redo - executing" << m_deletions.size() << "deletions"; for (int i = 0; i < m_deletions.size(); i++) { auto cursor = m_deletions[i].cursor; const int pos = m_deletions[i].delPos; @@ -168,15 +169,15 @@ void DeleteBackAltCommand::redo() } if (m_edit && !m_columnEditSelections.isEmpty()) { - qDebug() << "m_edit is not null"; + qCDebug(appLog) << "m_edit is not null"; m_edit->restoreColumnEditSelection(m_columnEditSelections); m_edit->setTextCursor(m_columnEditSelections.last().cursor); } - qDebug() << "DeleteBackAltCommand redo end"; + qCDebug(appLog) << "DeleteBackAltCommand redo end"; } int DeleteBackAltCommand::id() const { - qDebug() << "DeleteBackAltCommand id"; + qCDebug(appLog) << "DeleteBackAltCommand id"; return Utils::IdColumnEditDelete; } diff --git a/src/editor/deletetextundocommand.cpp b/src/editor/deletetextundocommand.cpp index 920578e9c..7e42995fe 100644 --- a/src/editor/deletetextundocommand.cpp +++ b/src/editor/deletetextundocommand.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "deletetextundocommand.h" #include "editwrapper.h" #include @@ -15,27 +16,27 @@ DeleteTextUndoCommand::DeleteTextUndoCommand(QTextCursor textcursor, TextEdit *e , m_textCursor(textcursor) , m_beginPos(m_textCursor.selectionStart()) { - qDebug() << "DeleteTextUndoCommand created - beginPos:" << m_beginPos; + qCDebug(appLog) << "DeleteTextUndoCommand created - beginPos:" << m_beginPos; if (m_textCursor.hasSelection()) { - qDebug() << "m_textCursor.hasSelection()"; + qCDebug(appLog) << "m_textCursor.hasSelection()"; m_sInsertText = m_textCursor.selectedText(); } else { - qDebug() << "m_textCursor.hasSelection() is false"; + qCDebug(appLog) << "m_textCursor.hasSelection() is false"; // 无选区删除的是光标前一个字符,m_beginPos 记录被删字符位置(光标-1), // 否则 undo 会把字符重插到原位置之后一位 m_beginPos = m_textCursor.position() - 1; int pos = m_textCursor.positionInBlock() - 1; if (pos >= 0) { - qDebug() << "pos >= 0"; + qCDebug(appLog) << "pos >= 0"; m_sInsertText = m_textCursor.block().text().at(pos); } else { //上一行lastQChar - qDebug() << "pos < 0"; + qCDebug(appLog) << "pos < 0"; m_sInsertText = "\n"; } } - qDebug() << "DeleteTextUndoCommand created end"; + qCDebug(appLog) << "DeleteTextUndoCommand created end"; } DeleteTextUndoCommand::DeleteTextUndoCommand(QList &selections, @@ -46,35 +47,35 @@ DeleteTextUndoCommand::DeleteTextUndoCommand(QList &s , m_ColumnEditSelections(selections) , m_beginPos(m_textCursor.selectionStart()) { - qDebug() << "DeleteTextUndoCommand created - beginPos:" << m_beginPos; + qCDebug(appLog) << "DeleteTextUndoCommand created - beginPos:" << m_beginPos; int cnt = m_ColumnEditSelections.size(); for (int i = 0; i < cnt; i++) { QTextCursor textCursor = m_ColumnEditSelections[i].cursor; if (textCursor.hasSelection()) { - qDebug() << "textCursor.hasSelection()"; + qCDebug(appLog) << "textCursor.hasSelection()"; m_selectTextList.append(textCursor.selectedText()); } else { int pos = textCursor.positionInBlock() - 1; if (pos >= 0) { - qDebug() << "pos >= 0"; + qCDebug(appLog) << "pos >= 0"; m_selectTextList.append(textCursor.block().text().at(pos)); } else { //上一行lastQChar - qDebug() << "pos < 0"; + qCDebug(appLog) << "pos < 0"; m_selectTextList.append("\n"); } } } - qDebug() << "DeleteTextUndoCommand created end"; + qCDebug(appLog) << "DeleteTextUndoCommand created end"; } void DeleteTextUndoCommand::undo() { - qDebug() << "DeleteTextUndoCommand undo - beginPos:" << m_beginPos + qCDebug(appLog) << "DeleteTextUndoCommand undo - beginPos:" << m_beginPos << ", text length:" << m_sInsertText.length(); if (m_ColumnEditSelections.isEmpty()) { - qDebug() << "m_ColumnEditSelections.isEmpty()"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty()"; // 插入前将光标恢复到删除前位置 m_textCursor.setPosition(m_beginPos); m_textCursor.insertText(m_sInsertText); @@ -85,7 +86,7 @@ void DeleteTextUndoCommand::undo() m_edit->setTextCursor(m_textCursor); } } else { - qDebug() << "m_ColumnEditSelections.isEmpty() is false"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty() is false"; int cnt = m_ColumnEditSelections.size(); for (int i = 0; i < cnt; i++) { m_ColumnEditSelections[i].cursor.insertText(m_selectTextList[i]); @@ -94,20 +95,20 @@ void DeleteTextUndoCommand::undo() } if (m_edit && !m_ColumnEditSelections.isEmpty()) { - qDebug() << "m_edit is not null"; + qCDebug(appLog) << "m_edit is not null"; m_edit->restoreColumnEditSelection(m_ColumnEditSelections); m_edit->setTextCursor(m_ColumnEditSelections.last().cursor); } } - qDebug() << "DeleteTextUndoCommand undo end"; + qCDebug(appLog) << "DeleteTextUndoCommand undo end"; } void DeleteTextUndoCommand::redo() { - qDebug() << "DeleteTextUndoCommand redo - beginPos:" << m_beginPos; + qCDebug(appLog) << "DeleteTextUndoCommand redo - beginPos:" << m_beginPos; if (m_ColumnEditSelections.isEmpty()) { - qDebug() << "m_ColumnEditSelections.isEmpty()"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty()"; m_textCursor.deletePreviousChar(); // 进行撤销/恢复时将光标移动到撤销位置 @@ -115,29 +116,29 @@ void DeleteTextUndoCommand::redo() m_edit->setTextCursor(m_textCursor); } } else { - qDebug() << "m_ColumnEditSelections.isEmpty() is false"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty() is false"; int cnt = m_ColumnEditSelections.size(); for (int i = 0; i < cnt; i++) { m_ColumnEditSelections[i].cursor.deletePreviousChar(); } if (m_edit && !m_ColumnEditSelections.isEmpty()) { - qDebug() << "m_edit is not null"; + qCDebug(appLog) << "m_edit is not null"; m_edit->restoreColumnEditSelection(m_ColumnEditSelections); m_edit->setTextCursor(m_ColumnEditSelections.last().cursor); } } - qDebug() << "DeleteTextUndoCommand redo end"; + qCDebug(appLog) << "DeleteTextUndoCommand redo end"; } int DeleteTextUndoCommand::id() const { - qDebug() << "DeleteTextUndoCommand id"; + qCDebug(appLog) << "DeleteTextUndoCommand id"; if (m_ColumnEditSelections.isEmpty()) { - qDebug() << "m_ColumnEditSelections.isEmpty()"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty()"; return Utils::IdDelete; } else { - qDebug() << "m_ColumnEditSelections.isEmpty() is false"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty() is false"; return Utils::IdColumnEditDelete; } } @@ -148,7 +149,7 @@ DeleteTextUndoCommand2::DeleteTextUndoCommand2(QTextCursor textcursor, QString t , m_edit(edit) , m_iscurrLine(currLine) { - qDebug() << "DeleteTextUndoCommand2 created"; + qCDebug(appLog) << "DeleteTextUndoCommand2 created"; m_sInsertText.replace("\r\n", "\n"); } @@ -161,40 +162,40 @@ DeleteTextUndoCommand2::DeleteTextUndoCommand2(QList , m_edit(edit) , m_iscurrLine(currLine) { - qDebug() << "DeleteTextUndoCommand2 created"; + qCDebug(appLog) << "DeleteTextUndoCommand2 created"; m_sInsertText.replace("\r\n", "\n"); int cnt = m_ColumnEditSelections.size(); for (int i = 0; i < cnt; i++) { QTextCursor textCursor = m_ColumnEditSelections[i].cursor; if (textCursor.hasSelection()) { - qDebug() << "textCursor.hasSelection()"; + qCDebug(appLog) << "textCursor.hasSelection()"; m_selectTextList.append(textCursor.selectedText()); } else { int pos = textCursor.positionInBlock() - 1; if (pos >= 0) { - qDebug() << "pos >= 0"; + qCDebug(appLog) << "pos >= 0"; m_selectTextList.append(textCursor.block().text().at(pos)); } else { //上一行lastQChar - qDebug() << "pos < 0"; + qCDebug(appLog) << "pos < 0"; m_selectTextList.append("\n"); } } } - qDebug() << "DeleteTextUndoCommand2 created end"; + qCDebug(appLog) << "DeleteTextUndoCommand2 created end"; } void DeleteTextUndoCommand2::undo() { - qDebug() << "DeleteTextUndoCommand2 undo"; + qCDebug(appLog) << "DeleteTextUndoCommand2 undo"; if (m_ColumnEditSelections.isEmpty()) { - qDebug() << "m_ColumnEditSelections.isEmpty()"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty()"; m_textCursor.setPosition(m_beginPostion); m_textCursor.insertText(m_sInsertText); m_textCursor.setPosition(m_beginPostion); m_edit->setTextCursor(m_textCursor); } else { - qDebug() << "m_ColumnEditSelections.isEmpty() is false"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty() is false"; int cnt = m_ColumnEditSelections.size(); // 逆序恢复:redo 按序删除时记录的各选区位置在"全部删除后"的坐标系中有效, // 逆序插入(先恢复靠后的选区)不会使靠前选区的记录位置发生偏移 @@ -205,34 +206,34 @@ void DeleteTextUndoCommand2::undo() m_edit->setTextCursor(m_ColumnEditSelections[i].cursor); } } - qDebug() << "DeleteTextUndoCommand2 undo end"; + qCDebug(appLog) << "DeleteTextUndoCommand2 undo end"; } void DeleteTextUndoCommand2::redo() { - qDebug() << "DeleteTextUndoCommand2 redo"; + qCDebug(appLog) << "DeleteTextUndoCommand2 redo"; if (m_ColumnEditSelections.isEmpty()) { - qDebug() << "m_ColumnEditSelections.isEmpty()"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty()"; bool isEmptyLine = (m_sInsertText.size() == 0); bool isBlankLine = (m_sInsertText.trimmed().size() == 0); if (!m_iscurrLine) { - qDebug() << "m_iscurrLine is false"; + qCDebug(appLog) << "m_iscurrLine is false"; //删除到行尾 if (isEmptyLine || m_textCursor.atBlockEnd()) { - qDebug() << "isEmptyLine || m_textCursor.atBlockEnd()"; + qCDebug(appLog) << "isEmptyLine || m_textCursor.atBlockEnd()"; m_textCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); } else if (isBlankLine && m_textCursor.atBlockStart()) { - qDebug() << "isBlankLine && m_textCursor.atBlockStart()"; + qCDebug(appLog) << "isBlankLine && m_textCursor.atBlockStart()"; m_textCursor.movePosition(QTextCursor::StartOfBlock); m_textCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } else { - qDebug() << "else"; + qCDebug(appLog) << "else"; m_textCursor.movePosition(QTextCursor::NoMove, QTextCursor::MoveAnchor); m_textCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } } else { - qDebug() << "m_iscurrLine is true"; + qCDebug(appLog) << "m_iscurrLine is true"; //删除整行 m_textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); m_textCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); @@ -246,7 +247,7 @@ void DeleteTextUndoCommand2::redo() // 进行撤销/恢复时将光标移动到撤销位置 m_edit->setTextCursor(m_textCursor); } else { - qDebug() << "m_ColumnEditSelections.isEmpty() is false"; + qCDebug(appLog) << "m_ColumnEditSelections.isEmpty() is false"; int cnt = m_ColumnEditSelections.size(); // 每个选区记录各自的起始位置,供 undo 恢复使用( redo/undo 严格交替,先清空防御重复累积) m_selectBeginPosList.clear(); @@ -256,5 +257,5 @@ void DeleteTextUndoCommand2::redo() m_edit->setTextCursor(m_ColumnEditSelections[i].cursor); } } - qDebug() << "DeleteTextUndoCommand2 redo end"; + qCDebug(appLog) << "DeleteTextUndoCommand2 redo end"; } diff --git a/src/editor/dtextedit.cpp b/src/editor/dtextedit.cpp index 61f73d19e..79003ad6f 100644 --- a/src/editor/dtextedit.cpp +++ b/src/editor/dtextedit.cpp @@ -3,6 +3,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "../common/utils.h" #include "../widgets/window.h" #include "../widgets/bottombar.h" @@ -65,7 +66,7 @@ TextEdit::TextEdit(QWidget *parent) : DPlainTextEdit(parent), m_wrapper(nullptr) { - qDebug() << "Initializing TextEdit component"; + qCDebug(appLog) << "Initializing TextEdit component"; // 更新单独添加的高亮格式文件 m_repository.addCustomSearchPath(KF5_HIGHLIGHT_PATH); @@ -137,14 +138,14 @@ TextEdit::TextEdit(QWidget *parent) QDBusConnection dbus = QDBusConnection::sessionBus(); switch (Utils::getSystemVersion()) { case Utils::V23: - qDebug() << "Utils::V23"; + qCDebug(appLog) << "Utils::V23"; dbus.systemBus().connect("org.deepin.dde.Gesture1", "/org/deepin/dde/Gesture1", "org.deepin.dde.Gesture1", "Event", this, SLOT(fingerZoom(QString, QString, int))); break; default: - qDebug() << "default"; + qCDebug(appLog) << "default"; dbus.systemBus().connect("com.deepin.daemon.Gesture", "/com/deepin/daemon/Gesture", "com.deepin.daemon.Gesture", "Event", @@ -194,12 +195,12 @@ TextEdit::TextEdit(QWidget *parent) // Recover blink when not selecting text. connect(this, &TextEdit::selectionChanged, this, &TextEdit::slotSelectionChanged, Qt::QueuedConnection); connect(this, &QPlainTextEdit::textChanged, this, &TextEdit::invalidateMatchCountCache); - qDebug() << "TextEdit initialized"; + qCDebug(appLog) << "TextEdit initialized"; } TextEdit::~TextEdit() { - qDebug() << "Destroying TextEdit component"; + qCDebug(appLog) << "Destroying TextEdit component"; // Disconnect D-Bus signals to prevent callbacks to destroyed object QDBusConnection dbus = QDBusConnection::sessionBus(); switch (Utils::getSystemVersion()) { @@ -229,7 +230,7 @@ TextEdit::~TextEdit() this, SLOT(onAudioPortEnabledChanged(quint32, QString, bool))); #endif if (m_scrollAnimation != nullptr) { - qDebug() << "m_scrollAnimation is not null"; + qCDebug(appLog) << "m_scrollAnimation is not null"; if (m_scrollAnimation->state() != QAbstractAnimation::Stopped) { m_scrollAnimation->stop(); } @@ -237,34 +238,34 @@ TextEdit::~TextEdit() m_scrollAnimation = nullptr; } if (m_colorMarkMenu != nullptr) { - qDebug() << "m_colorMarkMenu is not null"; + qCDebug(appLog) << "m_colorMarkMenu is not null"; delete m_colorMarkMenu; m_colorMarkMenu = nullptr; } if (m_convertCaseMenu != nullptr) { - qDebug() << "m_convertCaseMenu is not null"; + qCDebug(appLog) << "m_convertCaseMenu is not null"; delete m_convertCaseMenu; m_convertCaseMenu = nullptr; } if (m_rightMenu != nullptr) { - qDebug() << "m_rightMenu is not null"; + qCDebug(appLog) << "m_rightMenu is not null"; delete m_rightMenu; m_rightMenu = nullptr; } if (m_pUndoStack != nullptr) { - qDebug() << "m_pUndoStack is not null"; + qCDebug(appLog) << "m_pUndoStack is not null"; m_pUndoStack->deleteLater(); } } void TextEdit::insertTextEx(QTextCursor cursor, QString text) { - qDebug() << "Inserting text at position:" << cursor.position() << "Length:" << text.length(); + qCDebug(appLog) << "Inserting text at position:" << cursor.position() << "Length:" << text.length(); QUndoCommand *pInsertStack = new InsertTextUndoCommand(cursor, text, this); m_pUndoStack->push(pInsertStack); ensureCursorVisible(); - qDebug() << "Text inserted successfully"; + qCDebug(appLog) << "Text inserted successfully"; } /** @@ -273,9 +274,9 @@ void TextEdit::insertTextEx(QTextCursor cursor, QString text) */ void TextEdit::insertMultiTextEx(const QList > &multiText) { - qDebug() << "Inserting multiple texts, count:" << multiText.size(); + qCDebug(appLog) << "Inserting multiple texts, count:" << multiText.size(); if (multiText.isEmpty()) { - qDebug() << "Multi text insert skipped - empty input"; + qCDebug(appLog) << "Multi text insert skipped - empty input"; return; } @@ -287,36 +288,36 @@ void TextEdit::insertMultiTextEx(const QList > &mult } m_pUndoStack->push(pMultiCommand); ensureCursorVisible(); - qDebug() << "Multi text inserted successfully"; + qCDebug(appLog) << "Multi text inserted successfully"; } void TextEdit::deleteSelectTextEx(QTextCursor cursor) { - qDebug() << "Deleting selected text at position:" << cursor.position() + qCDebug(appLog) << "Deleting selected text at position:" << cursor.position() << "Selection length:" << cursor.selectedText().length(); if (cursor.hasSelection()) { - qDebug() << "cursor.hasSelection() is true"; + qCDebug(appLog) << "cursor.hasSelection() is true"; QUndoCommand *pDeleteStack = new DeleteTextUndoCommand(cursor, this); m_pUndoStack->push(pDeleteStack); } - qDebug() << "Selected text deleted successfully"; + qCDebug(appLog) << "Selected text deleted successfully"; } void TextEdit::deleteSelectTextEx(QTextCursor cursor, QString text, bool currLine) { - qDebug() << "Deleting selected text at position:" << cursor.position(); + qCDebug(appLog) << "Deleting selected text at position:" << cursor.position(); QUndoCommand *pDeleteStack = new DeleteTextUndoCommand2(cursor, text, this, currLine); m_pUndoStack->push(pDeleteStack); - qDebug() << "Selected text deleted successfully"; + qCDebug(appLog) << "Selected text deleted successfully"; } void TextEdit::deleteTextEx(QTextCursor cursor) { - qDebug() << "Deleting text at position:" << cursor.position(); + qCDebug(appLog) << "Deleting text at position:" << cursor.position(); flushDeferredCursorUpdate(); QUndoCommand *pDeleteStack = new DeleteTextUndoCommand(cursor, this); m_pUndoStack->push(pDeleteStack); - qDebug() << "Text deleted successfully"; + qCDebug(appLog) << "Text deleted successfully"; } /** @@ -325,9 +326,9 @@ void TextEdit::deleteTextEx(QTextCursor cursor) */ void TextEdit::deleteMultiTextEx(const QList &multiText) { - qDebug() << "Deleting multiple texts, count:" << multiText.size(); + qCDebug(appLog) << "Deleting multiple texts, count:" << multiText.size(); if (multiText.isEmpty()) { - qDebug() << "Multi text delete skipped - empty input"; + qCDebug(appLog) << "Multi text delete skipped - empty input"; return; } @@ -338,12 +339,12 @@ void TextEdit::deleteMultiTextEx(const QList &multiText) (void)new DeleteTextUndoCommand(textCursor, this, pMultiCommand); } m_pUndoStack->push(pMultiCommand); - qDebug() << "Multi text deleted successfully"; + qCDebug(appLog) << "Multi text deleted successfully"; } void TextEdit::insertSelectTextEx(QTextCursor cursor, QString text) { - qDebug() << "Inserting selected text at position:" << cursor.position() << "Length:" << text.length(); + qCDebug(appLog) << "Inserting selected text at position:" << cursor.position() << "Length:" << text.length(); const bool deferHeavyUpdate = shouldDeferCursorHeavyUpdate(cursor, text); if (!deferHeavyUpdate) { @@ -363,12 +364,12 @@ void TextEdit::insertSelectTextEx(QTextCursor cursor, QString text) if (deferHeavyUpdate) { scheduleDeferredCursorUpdateBurst(); } - qDebug() << "Selected text inserted successfully"; + qCDebug(appLog) << "Selected text inserted successfully"; } void TextEdit::insertColumnEditTextEx(QString text) { - qDebug() << "Inserting column text"; + qCDebug(appLog) << "Inserting column text"; flushDeferredCursorUpdate(); if (m_isSelectAll) { QPlainTextEdit::selectAll(); @@ -377,12 +378,12 @@ void TextEdit::insertColumnEditTextEx(QString text) QUndoCommand *pInsertStack = new InsertTextUndoCommand(m_altModSelections, text, this); m_pUndoStack->push(pInsertStack); ensureCursorVisible(); - qDebug() << "Column text inserted successfully"; + qCDebug(appLog) << "Column text inserted successfully"; } void TextEdit::initRightClickedMenu() { - qDebug() << "Initializing right clicked menu"; + qCDebug(appLog) << "Initializing right clicked menu"; // Init menu. m_rightMenu = new DMenu(); m_rightMenu->setAccessibleName("EditorContextMenu"); @@ -471,7 +472,7 @@ void TextEdit::initRightClickedMenu() m_markCurrentAct = new QAction(tr("Mark"), this); m_markCurrentAct->setObjectName("MarkCurrentLine"); connect(m_markCurrentAct, &QAction::triggered, this, [this, pColorsSelectWdg]() { - qDebug() << "Marking current line"; + qCDebug(appLog) << "Marking current line"; isMarkCurrentLine(true, pColorsSelectWdg->getDefaultColor().name()); renderAllSelections(); }); @@ -485,7 +486,7 @@ void TextEdit::initRightClickedMenu() m_markAllAct = new QAction(tr("Mark All"), this); m_markAllAct->setObjectName("MarkAll"); connect(m_markAllAct, &QAction::triggered, this, [this, pColorsAllSelectWdg]() { - qDebug() << "Marking all lines"; + qCDebug(appLog) << "Marking all lines"; m_strMarkAllLineColorName = pColorsAllSelectWdg->getDefaultColor().name(); isMarkAllLine(true, pColorsAllSelectWdg->getDefaultColor().name()); renderAllSelections(); @@ -568,12 +569,12 @@ void TextEdit::initRightClickedMenu() connect(this, &TextEdit::undoAvailable, this, &TextEdit::slotUndoAvailable); connect(this, &TextEdit::redoAvailable, this, &TextEdit::slotRedoAvailable); - qDebug() << "Right clicked menu initialized"; + qCDebug(appLog) << "Right clicked menu initialized"; } void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) { - qDebug() << "Popping right clicked menu"; + qCDebug(appLog) << "Popping right clicked menu"; //清除菜单分割线残影 if (m_rightMenu != nullptr) { delete m_rightMenu; @@ -598,26 +599,26 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) bool isAddUndoRedo = false; if (m_pUndoStack->canUndo() && !hideEdit) { - qDebug() << "Adding undo action"; + qCDebug(appLog) << "Adding undo action"; m_undoAction->setEnabled(!blockEdit); m_rightMenu->addAction(m_undoAction); isAddUndoRedo = true; } if (m_pUndoStack->canRedo() && !hideEdit) { - qDebug() << "Adding redo action"; + qCDebug(appLog) << "Adding redo action"; m_redoAction->setEnabled(!blockEdit); m_rightMenu->addAction(m_redoAction); isAddUndoRedo = true; } if (isAddUndoRedo) { - qDebug() << "Adding separator"; + qCDebug(appLog) << "Adding separator"; m_rightMenu->addSeparator(); } if (textCursor().hasSelection() || m_hasColumnSelection) { - qDebug() << "Adding cut action"; + qCDebug(appLog) << "Adding cut action"; if (!hideEdit) { m_cutAction->setEnabled(!blockEdit); m_rightMenu->addAction(m_cutAction); @@ -626,7 +627,7 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) } if (canPaste()) { - qDebug() << "Adding paste action"; + qCDebug(appLog) << "Adding paste action"; if (!hideEdit) { m_pasteAction->setEnabled(!blockEdit); m_rightMenu->addAction(m_pasteAction); @@ -634,7 +635,7 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) } if (textCursor().hasSelection() || m_hasColumnSelection) { - qDebug() << "Adding delete action"; + qCDebug(appLog) << "Adding delete action"; if (!hideEdit) { m_deleteAction->setEnabled(!blockEdit); m_rightMenu->addAction(m_deleteAction); @@ -643,33 +644,33 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) } if (!document()->isEmpty()) { - qDebug() << "Adding select all action"; + qCDebug(appLog) << "Adding select all action"; m_rightMenu->addAction(m_selectAllAction); } m_rightMenu->addSeparator(); if (!document()->isEmpty()) { - qDebug() << "Adding find action"; + qCDebug(appLog) << "Adding find action"; m_rightMenu->addAction(m_findAction); if (!hideEdit) { - qDebug() << "Adding replace action"; + qCDebug(appLog) << "Adding replace action"; m_replaceAction->setEnabled(!blockEdit); m_rightMenu->addAction(m_replaceAction); } - qDebug() << "Adding jump line action"; + qCDebug(appLog) << "Adding jump line action"; m_rightMenu->addAction(m_jumpLineAction); m_rightMenu->addSeparator(); } if (textCursor().hasSelection()) { - qDebug() << "Adding convert case menu"; + qCDebug(appLog) << "Adding convert case menu"; if (!hideEdit) { QAction *pCaseMenuAct = m_rightMenu->addMenu(m_convertCaseMenu); pCaseMenuAct->setEnabled(!blockEdit); } } else { - qDebug() << "Hiding convert case menu"; + qCDebug(appLog) << "Hiding convert case menu"; m_convertCaseMenu->hide(); } @@ -678,7 +679,7 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) if (characterCount() && (textCursor().hasSelection() || !isBlankLine) && !def.filePath().isEmpty()) { - qDebug() << "Adding add comment action"; + qCDebug(appLog) << "Adding add comment action"; /* * 不支持注释的文件类型,右键菜单不显示“添加注释/取消注释” * 不支持注释的文件类型:Markdown(.d)/vCard(.vcf)/JSON(.json) @@ -686,18 +687,18 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) if (def.name() != "Markdown" && !def.name().contains(QString("vCard")) && !def.name().contains(QString("JSON"))) { - qDebug() << "Adding add comment action"; + qCDebug(appLog) << "Adding add comment action"; m_rightMenu->addAction(m_addComment); m_rightMenu->addAction(m_cancelComment); } } if (blockEdit) { - qDebug() << "Adding add comment action"; + qCDebug(appLog) << "Adding add comment action"; m_addComment->setEnabled(false); m_cancelComment->setEnabled(false); } else { - qDebug() << "Adding add comment action"; + qCDebug(appLog) << "Adding add comment action"; m_addComment->setEnabled(true); m_cancelComment->setEnabled(true); } @@ -709,21 +710,21 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) m_rightMenu->addAction(m_openInFileManagerAction); m_rightMenu->addSeparator(); if (static_cast(this->window())->isFullScreen()) { - qDebug() << "Adding exit fullscreen action"; + qCDebug(appLog) << "Adding exit fullscreen action"; m_rightMenu->addAction(m_exitFullscreenAction); } else { - qDebug() << "Adding fullscreen action"; + qCDebug(appLog) << "Adding fullscreen action"; m_rightMenu->addAction(m_fullscreenAction); } // Block ai actions on mips by default. #ifdef __mips__ if (IflytekAiAssistant::instance()->valid()) { - qDebug() << "Adding ai actions"; + qCDebug(appLog) << "Adding ai actions"; #endif // __mips__ // 'UOS AI' actions - qDebug() << "Adding voice reading action"; + qCDebug(appLog) << "Adding voice reading action"; m_rightMenu->addAction(m_voiceReadingAction); m_voiceReadingAction->setEnabled((textCursor().hasSelection() || m_hasColumnSelection)); @@ -741,7 +742,7 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) #endif // __mips__ if (!this->document()->isEmpty()) { - qDebug() << "Adding color mark menu"; + qCDebug(appLog) << "Adding color mark menu"; m_colorMarkMenu->clear(); // 清空 tab order list @@ -765,7 +766,7 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) m_MarkColorMenuTabOrder.append(QPair(m_actionAllColorStyles, false)); if (m_markOperations.size() > 0) { - qDebug() << "Adding cancel last mark action"; + qCDebug(appLog) << "Adding cancel last mark action"; // 增加 Mark Color Menu Item m_colorMarkMenu->addAction(m_cancleLastMark); m_colorMarkMenu->addSeparator(); @@ -777,7 +778,7 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) m_rightMenu->addSeparator(); if (!hideEdit) { - qDebug() << "Adding column edit action"; + qCDebug(appLog) << "Adding column edit action"; m_columnEditAction->setEnabled(!blockEdit); m_rightMenu->addAction(m_columnEditAction); } @@ -791,131 +792,131 @@ void TextEdit::popRightMenu(QPoint pos, bool asReadOnly) pos1.setX((this->rect().width()) / 2); } if (pos.isNull()) { - qDebug() << "pos is null"; + qCDebug(appLog) << "pos is null"; m_rightMenu->exec(mapToGlobal(pos1)); } else { - qDebug() << "Executing right menu at position:" << pos; + qCDebug(appLog) << "Executing right menu at position:" << pos; m_rightMenu->exec(pos); } } void TextEdit::setWrapper(EditWrapper *w) { - qDebug() << "Setting wrapper"; + qCDebug(appLog) << "Setting wrapper"; m_wrapper = w; } EditWrapper *TextEdit::getWrapper() { - qDebug() << "Getting wrapper"; + qCDebug(appLog) << "Getting wrapper"; return m_wrapper; } bool TextEdit::isUndoRedoOpt() { - qDebug() << "Checking undo/redo availability"; + qCDebug(appLog) << "Checking undo/redo availability"; return (m_pUndoStack->canRedo() || m_pUndoStack->canUndo()); } bool TextEdit::getModified() { - qDebug() << "Checking modified status"; + qCDebug(appLog) << "Checking modified status"; return (document()->isModified() && (m_pUndoStack->canUndo() || m_pUndoStack->index() != m_lastSaveIndex)); } int TextEdit::getCurrentLine() { - qDebug() << "Getting current line"; + qCDebug(appLog) << "Getting current line"; return textCursor().blockNumber() + 1; } int TextEdit::getCurrentColumn() { - qDebug() << "Getting current column"; + qCDebug(appLog) << "Getting current column"; return textCursor().columnNumber(); } int TextEdit::getPosition() { - qDebug() << "Getting position"; + qCDebug(appLog) << "Getting position"; return textCursor().position(); } int TextEdit::getScrollOffset() { - qDebug() << "Getting scroll offset"; + qCDebug(appLog) << "Getting scroll offset"; return verticalScrollBar()->value(); } void TextEdit::forwardChar() { - qDebug() << "Moving forward by character"; + qCDebug(appLog) << "Moving forward by character"; if (m_cursorMark) { - qDebug() << "Moving forward by character with mark"; + qCDebug(appLog) << "Moving forward by character with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving forward by character without mark"; + qCDebug(appLog) << "Moving forward by character without mark"; moveCursorNoBlink(QTextCursor::NextCharacter); } } void TextEdit::backwardChar() { - qDebug() << "Moving backward by character"; + qCDebug(appLog) << "Moving backward by character"; if (m_cursorMark) { - qDebug() << "Moving backward by character with mark"; + qCDebug(appLog) << "Moving backward by character with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving backward by character without mark"; + qCDebug(appLog) << "Moving backward by character without mark"; moveCursorNoBlink(QTextCursor::PreviousCharacter); } - qDebug() << "Moving backward by character successfully"; + qCDebug(appLog) << "Moving backward by character successfully"; } void TextEdit::forwardWord() { - qDebug() << "Moving forward by word"; + qCDebug(appLog) << "Moving forward by word"; QTextCursor cursor = textCursor(); if (m_cursorMark) { - qDebug() << "Moving forward by word with mark"; + qCDebug(appLog) << "Moving forward by word with mark"; cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor); } else { - qDebug() << "Moving forward by word without mark"; + qCDebug(appLog) << "Moving forward by word without mark"; cursor.movePosition(QTextCursor::NextWord, QTextCursor::MoveAnchor); } setTextCursor(cursor); - qDebug() << "Moving forward by word successfully"; + qCDebug(appLog) << "Moving forward by word successfully"; } void TextEdit::backwardWord() { - qDebug() << "Moving backward by word"; + qCDebug(appLog) << "Moving backward by word"; QTextCursor cursor = textCursor(); if (m_cursorMark) { - qDebug() << "Moving backward by word with mark"; + qCDebug(appLog) << "Moving backward by word with mark"; // cursor.setPosition(getPrevWordPosition(cursor, QTextCursor::KeepAnchor), QTextCursor::KeepAnchor); cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor); } else { - qDebug() << "Moving backward by word without mark"; + qCDebug(appLog) << "Moving backward by word without mark"; // cursor.setPosition(getPrevWordPosition(cursor, QTextCursor::MoveAnchor), QTextCursor::MoveAnchor); cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::MoveAnchor); } setTextCursor(cursor); - qDebug() << "Moving backward by word successfully"; + qCDebug(appLog) << "Moving backward by word successfully"; } void TextEdit::forwardPair() { - qDebug() << "Moving forward by pair"; + qCDebug(appLog) << "Moving forward by pair"; // Record cursor and seleciton position before move cursor. int actionStartPos = textCursor().position(); int selectionStartPos = textCursor().selectionStart(); @@ -929,37 +930,37 @@ void TextEdit::forwardPair() // Start search. #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) - qDebug() << "Moving forward by pair with mark"; + qCDebug(appLog) << "Moving forward by pair with mark"; QRegExp regExp("[\\]>)}]"); #else QRegularExpression regExp("[\\]>)}]"); #endif - qDebug() << "Moving forward by pair without mark"; + qCDebug(appLog) << "Moving forward by pair without mark"; if (find(regExp)) { - qDebug() << "Moving forward by pair successfully"; + qCDebug(appLog) << "Moving forward by pair successfully"; int findPos = textCursor().position(); QTextCursor cursor = textCursor(); auto moveMode = m_cursorMark ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; if (actionStartPos == selectionStartPos) { - qDebug() << "Moving forward by pair with mark"; + qCDebug(appLog) << "Moving forward by pair with mark"; cursor.setPosition(selectionEndPos, QTextCursor::MoveAnchor); cursor.setPosition(findPos, moveMode); } else { - qDebug() << "Moving forward by pair without mark"; + qCDebug(appLog) << "Moving forward by pair without mark"; cursor.setPosition(selectionStartPos, QTextCursor::MoveAnchor); cursor.setPosition(findPos, moveMode); } setTextCursor(cursor); } - qDebug() << "Moving forward by pair successfully"; + qCDebug(appLog) << "Moving forward by pair successfully"; } void TextEdit::backwardPair() { - qDebug() << "Moving backward by pair"; + qCDebug(appLog) << "Moving backward by pair"; // Record cursor and seleciton position before move cursor. int actionStartPos = textCursor().position(); int selectionStartPos = textCursor().selectionStart(); @@ -980,7 +981,7 @@ void TextEdit::backwardPair() QRegularExpression regExp("[\[<({]"); #endif if (find(regExp, options)) { - qDebug() << "Moving backward by pair successfully"; + qCDebug(appLog) << "Moving backward by pair successfully"; QTextCursor cursor = textCursor(); auto moveMode = m_cursorMark ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; @@ -989,35 +990,35 @@ void TextEdit::backwardPair() int findPos = cursor.position(); if (actionStartPos == selectionStartPos) { - qDebug() << "Moving backward by pair with mark"; + qCDebug(appLog) << "Moving backward by pair with mark"; cursor.setPosition(selectionEndPos, QTextCursor::MoveAnchor); cursor.setPosition(findPos, moveMode); setTextCursor(cursor); } else { - qDebug() << "Moving backward by pair without mark"; + qCDebug(appLog) << "Moving backward by pair without mark"; cursor.setPosition(selectionStartPos, QTextCursor::MoveAnchor); cursor.setPosition(findPos, moveMode); setTextCursor(cursor); } } - qDebug() << "Moving backward by pair successfully"; + qCDebug(appLog) << "Moving backward by pair successfully"; } int TextEdit::blockCount() const { - qDebug() << "Getting block count"; + qCDebug(appLog) << "Getting block count"; return document()->blockCount(); } int TextEdit::characterCount() const { - qDebug() << "Getting character count"; + qCDebug(appLog) << "Getting character count"; return document()->characterCount(); } QTextBlock TextEdit::firstVisibleBlock() { - qDebug() << "Getting first visible block"; + qCDebug(appLog) << "Getting first visible block"; return document()->findBlockByLineNumber(getFirstVisibleBlockId()); } @@ -1029,74 +1030,74 @@ int TextEdit::topVisibleBlockNumber() const void TextEdit::moveToStart() { - qDebug() << "Moving to start"; + qCDebug(appLog) << "Moving to start"; verticalScrollBar()->setValue(0); if (m_cursorMark) { - qDebug() << "Moving to start with mark"; + qCDebug(appLog) << "Moving to start with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Start, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving to start without mark"; + qCDebug(appLog) << "Moving to start without mark"; moveCursorNoBlink(QTextCursor::Start); } // 移动展示区域,手动高亮文本 m_wrapper->OnUpdateHighlighter(); - qDebug() << "Moving to start successfully"; + qCDebug(appLog) << "Moving to start successfully"; } void TextEdit::moveToEnd() { - qDebug() << "Moving to end"; + qCDebug(appLog) << "Moving to end"; if (m_cursorMark) { - qDebug() << "Moving to end with mark"; + qCDebug(appLog) << "Moving to end with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving to end without mark"; + qCDebug(appLog) << "Moving to end without mark"; moveCursorNoBlink(QTextCursor::End); } // 移动展示区域,手动高亮文本 m_wrapper->OnUpdateHighlighter(); - qDebug() << "Moving to end successfully"; + qCDebug(appLog) << "Moving to end successfully"; } void TextEdit::moveToStartOfLine() { - qDebug() << "Moving to start of line"; + qCDebug(appLog) << "Moving to start of line"; if (m_cursorMark) { - qDebug() << "Moving to start of line with mark"; + qCDebug(appLog) << "Moving to start of line with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving to start of line without mark"; + qCDebug(appLog) << "Moving to start of line without mark"; moveCursorNoBlink(QTextCursor::StartOfBlock); } - qDebug() << "Moving to start of line successfully"; + qCDebug(appLog) << "Moving to start of line successfully"; } void TextEdit::moveToEndOfLine() { - qDebug() << "Moving to end of line"; + qCDebug(appLog) << "Moving to end of line"; if (m_cursorMark) { - qDebug() << "Moving to end of line with mark"; + qCDebug(appLog) << "Moving to end of line with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving to end of line without mark"; + qCDebug(appLog) << "Moving to end of line without mark"; moveCursorNoBlink(QTextCursor::EndOfBlock); } - qDebug() << "Moving to end of line successfully"; + qCDebug(appLog) << "Moving to end of line successfully"; } void TextEdit::moveToLineIndentation() { - qDebug() << "Moving to line indentation"; + qCDebug(appLog) << "Moving to line indentation"; // Init cursor and move type. QTextCursor cursor = textCursor(); // Get line start position. @@ -1113,14 +1114,14 @@ void TextEdit::moveToLineIndentation() QChar currentChar = *cursor.selection().toPlainText().data(); if (!currentChar.isSpace()) { - qDebug() << "Moving to line indentation successfully"; + qCDebug(appLog) << "Moving to line indentation successfully"; //stop and reset anchor while be at row indentation. cursor.setPosition(cursor.position(), QTextCursor::MoveAnchor); break; } else { - qDebug() << "Moving to line indentation with space"; + qCDebug(appLog) << "Moving to line indentation with space"; //while including 'space',just move ahead. cursor.setPosition(cursor.position() + 1, QTextCursor::KeepAnchor); } @@ -1128,81 +1129,81 @@ void TextEdit::moveToLineIndentation() } cursor.clearSelection(); setTextCursor(cursor); - qDebug() << "Moving to line indentation successfully"; + qCDebug(appLog) << "Moving to line indentation successfully"; } void TextEdit::nextLine() { - qDebug() << "Moving to next line"; + qCDebug(appLog) << "Moving to next line"; m_isSelectAll = false; if (!characterCount()) { - qDebug() << "No character count"; + qCDebug(appLog) << "No character count"; return; } if (m_cursorMark) { - qDebug() << "Moving to next line with mark"; + qCDebug(appLog) << "Moving to next line with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving to next line without mark"; + qCDebug(appLog) << "Moving to next line without mark"; moveCursorNoBlink(QTextCursor::Down); } if (m_wrapper != nullptr) { - qDebug() << "Updating highlighter"; + qCDebug(appLog) << "Updating highlighter"; m_wrapper->OnUpdateHighlighter(); if ((m_wrapper->window()->findBarIsVisiable() || m_wrapper->window()->replaceBarIsVisiable()) && (QString::compare(m_wrapper->window()->getKeywordForSearchAll(), m_wrapper->window()->getKeywordForSearch(), Qt::CaseInsensitive) == 0)) { - qDebug() << "Highlighting keyword in view"; + qCDebug(appLog) << "Highlighting keyword in view"; highlightKeywordInView(m_wrapper->window()->getKeywordForSearchAll()); } - qDebug() << "Marking all keyword in view"; + qCDebug(appLog) << "Marking all keyword in view"; markAllKeywordInView(); } - qDebug() << "Moving to next line successfully"; + qCDebug(appLog) << "Moving to next line successfully"; } void TextEdit::prevLine() { - qDebug() << "Moving to previous line"; + qCDebug(appLog) << "Moving to previous line"; m_isSelectAll = false; if (!characterCount()) { - qDebug() << "No character count"; + qCDebug(appLog) << "No character count"; return; } if (m_cursorMark) { - qDebug() << "Moving to previous line with mark"; + qCDebug(appLog) << "Moving to previous line with mark"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Up, QTextCursor::KeepAnchor); setTextCursor(cursor); } else { - qDebug() << "Moving to previous line without mark"; + qCDebug(appLog) << "Moving to previous line without mark"; moveCursorNoBlink(QTextCursor::Up); } if (m_wrapper != nullptr) { - qDebug() << "Updating highlighter"; + qCDebug(appLog) << "Updating highlighter"; m_wrapper->OnUpdateHighlighter(); if ((m_wrapper->window()->findBarIsVisiable() || m_wrapper->window()->replaceBarIsVisiable()) && (QString::compare(m_wrapper->window()->getKeywordForSearchAll(), m_wrapper->window()->getKeywordForSearch(), Qt::CaseInsensitive) == 0)) { - qDebug() << "Highlighting keyword in view"; + qCDebug(appLog) << "Highlighting keyword in view"; highlightKeywordInView(m_wrapper->window()->getKeywordForSearchAll()); } - qDebug() << "Marking all keyword in view"; + qCDebug(appLog) << "Marking all keyword in view"; markAllKeywordInView(); } - qDebug() << "Moving to previous line successfully"; + qCDebug(appLog) << "Moving to previous line successfully"; } void TextEdit::moveCursorNoBlink(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode) { - qDebug() << "Moving cursor without blink"; + qCDebug(appLog) << "Moving cursor without blink"; // Function moveCursorNoBlink will blink cursor when move cursor. // But function movePosition won't, so we use movePosition to avoid that cursor link when moving cursor. QTextCursor cursor = textCursor(); @@ -1212,23 +1213,23 @@ void TextEdit::moveCursorNoBlink(QTextCursor::MoveOperation operation, QTextCurs void TextEdit::jumpToLine(int line, bool keepLineAtCenter) { - qDebug() << "Jumping to line"; + qCDebug(appLog) << "Jumping to line"; QTextCursor cursor(document()->findBlockByNumber(line - 1)); // line - 1 because line number starts from 0 //verticalScrollBar()->setValue(fontMetrics().height() * line - height()); // Update cursor. setTextCursor(cursor); if (keepLineAtCenter) { - qDebug() << "Keeping current line at center"; + qCDebug(appLog) << "Keeping current line at center"; keepCurrentLineAtCenter(); } - qDebug() << "Jumping to line successfully"; + qCDebug(appLog) << "Jumping to line successfully"; m_pLeftAreaWidget->m_pLineNumberArea->update(); } void TextEdit::newline() { - qDebug() << "Opening new line"; + qCDebug(appLog) << "Opening new line"; // Stop mark if mark is set. tryUnsetMark(); @@ -1236,24 +1237,24 @@ void TextEdit::newline() auto com = new InsertTextUndoCommand(cursor, "\n", this); m_pUndoStack->push(com); setTextCursor(cursor); - qDebug() << "Opening new line successfully"; + qCDebug(appLog) << "Opening new line successfully"; } void TextEdit::openNewlineAbove() { - qDebug() << "Opening new line above"; + qCDebug(appLog) << "Opening new line above"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); InsertTextUndoCommand *com = new InsertTextUndoCommand(cursor, "\n", this); m_pUndoStack->push(com); cursor.movePosition(QTextCursor::Up, QTextCursor::MoveAnchor); setTextCursor(cursor); - qDebug() << "Opening new line above successfully"; + qCDebug(appLog) << "Opening new line above successfully"; } void TextEdit::openNewlineBelow() { - qDebug() << "Opening new line below"; + qCDebug(appLog) << "Opening new line below"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::MoveAnchor); InsertTextUndoCommand *com = new InsertTextUndoCommand(cursor, "\n", this); @@ -1261,7 +1262,7 @@ void TextEdit::openNewlineBelow() //make the vertical scroll bar change together. this->setTextCursor(cursor); - qDebug() << "Opening new line below successfully"; + qCDebug(appLog) << "Opening new line below successfully"; } /* @@ -1271,9 +1272,9 @@ void TextEdit::openNewlineBelow() * */ void TextEdit::moveLineDownUp(bool up) { - qDebug() << "Moving line down/up"; + qCDebug(appLog) << "Moving line down/up"; if (up) { - qDebug() << "Moving line up"; + qCDebug(appLog) << "Moving line up"; QTextCursor cursor = this->textCursor(); //current line isn't the first line of this document if (0 != cursor.blockNumber()) { @@ -1290,12 +1291,12 @@ void TextEdit::moveLineDownUp(bool up) cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); QString uptext = cursor.selectedText(); - qDebug() << "Moving line down from:" << cursor.blockNumber() << "to:" << cursor.blockNumber()+1; + qCDebug(appLog) << "Moving line down from:" << cursor.blockNumber() << "to:" << cursor.blockNumber()+1; cursor.setPosition(startpos); cursor.setPosition(endpos, QTextCursor::KeepAnchor); InsertTextUndoCommand *com = new InsertTextUndoCommand(cursor, curtext + "\n" + uptext, this); m_pUndoStack->push(com); - qDebug() << "Line move completed"; + qCDebug(appLog) << "Line move completed"; //ensure that this operation can be performed multiple times in succession. //and make the vertical scroll bar change together at the same time. @@ -1303,11 +1304,11 @@ void TextEdit::moveLineDownUp(bool up) this->setTextCursor(cursor); } } else { - qDebug() << "Moving line down"; + qCDebug(appLog) << "Moving line down"; QTextCursor cursor = this->textCursor(); //current line isn't the last line of this document if (cursor.blockNumber() + 1 != this->document()->blockCount()) { - qDebug() << "Moving line down"; + qCDebug(appLog) << "Moving line down"; int startpos = 0; int endpos = 0; cursor.movePosition(QTextCursor::StartOfLine); @@ -1321,12 +1322,12 @@ void TextEdit::moveLineDownUp(bool up) endpos = cursor.position(); QString downtext = cursor.selectedText(); - qDebug() << "Moving line up from:" << cursor.blockNumber()+1 << "to:" << cursor.blockNumber(); + qCDebug(appLog) << "Moving line up from:" << cursor.blockNumber()+1 << "to:" << cursor.blockNumber(); cursor.setPosition(startpos); cursor.setPosition(endpos, QTextCursor::KeepAnchor); InsertTextUndoCommand *com = new InsertTextUndoCommand(cursor, downtext + "\n" + curtext, this); m_pUndoStack->push(com); - qDebug() << "Line move completed"; + qCDebug(appLog) << "Line move completed"; //make the vertical scroll bar change together. cursor.setPosition(endpos); @@ -1334,52 +1335,52 @@ void TextEdit::moveLineDownUp(bool up) } } - qDebug() << "Moving line down/up successfully"; + qCDebug(appLog) << "Moving line down/up successfully"; } void TextEdit::scrollLineUp() { - qDebug() << "Scrolling line up"; + qCDebug(appLog) << "Scrolling line up"; QScrollBar *scrollbar = verticalScrollBar(); scrollbar->setValue(scrollbar->value() - 1); if (cursorRect().y() > rect().height() - fontMetrics().height()) { - qDebug() << "Scrolling line up with mark"; + qCDebug(appLog) << "Scrolling line up with mark"; auto moveMode = m_cursorMark ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Up, moveMode); setTextCursor(cursor); } else { - qDebug() << "Scrolling line up without mark"; + qCDebug(appLog) << "Scrolling line up without mark"; } - qDebug() << "Scrolling line up successfully"; + qCDebug(appLog) << "Scrolling line up successfully"; } void TextEdit::scrollLineDown() { - qDebug() << "Scrolling line down"; + qCDebug(appLog) << "Scrolling line down"; QScrollBar *scrollbar = verticalScrollBar(); scrollbar->setValue(scrollbar->value() + 1); if (cursorRect().y() < 0) { - qDebug() << "Scrolling line down with mark"; + qCDebug(appLog) << "Scrolling line down with mark"; auto moveMode = m_cursorMark ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Down, moveMode); setTextCursor(cursor); } else { - qDebug() << "Scrolling line down without mark"; + qCDebug(appLog) << "Scrolling line down without mark"; } - qDebug() << "Scrolling line down successfully"; + qCDebug(appLog) << "Scrolling line down successfully"; } void TextEdit::scrollUp() { - qDebug() << "Scrolling up"; + qCDebug(appLog) << "Scrolling up"; QScrollBar *scrollbar = verticalScrollBar(); scrollbar->triggerAction(QAbstractSlider::SliderPageStepSub); @@ -1388,7 +1389,7 @@ void TextEdit::scrollUp() //m_pLeftAreaWidget->m_pBookMarkArea->update(); if (verticalScrollBar()->maximum() > 0) { - qDebug() << "Scrolling up with mark"; + qCDebug(appLog) << "Scrolling up with mark"; auto moveMode = m_cursorMark ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; QPoint startPoint = QPointF(0, fontMetrics().height()).toPoint(); QTextCursor cur = cursorForPosition(startPoint); @@ -1398,22 +1399,22 @@ void TextEdit::scrollUp() } if (m_wrapper != nullptr) { - qDebug() << "Updating highlighter"; + qCDebug(appLog) << "Updating highlighter"; m_wrapper->OnUpdateHighlighter(); if ((m_wrapper->window()->findBarIsVisiable() || m_wrapper->window()->replaceBarIsVisiable()) && (QString::compare(m_wrapper->window()->getKeywordForSearchAll(), m_wrapper->window()->getKeywordForSearch(), Qt::CaseInsensitive) == 0)) { - qDebug() << "Highlighting keyword in view"; + qCDebug(appLog) << "Highlighting keyword in view"; highlightKeywordInView(m_wrapper->window()->getKeywordForSearchAll()); } markAllKeywordInView(); } - qDebug() << "Scrolling up successfully"; + qCDebug(appLog) << "Scrolling up successfully"; } void TextEdit::scrollDown() { - qDebug() << "Scrolling down"; + qCDebug(appLog) << "Scrolling down"; QScrollBar *scrollbar = verticalScrollBar(); scrollbar->triggerAction(QAbstractSlider::SliderPageStepAdd); @@ -1422,7 +1423,7 @@ void TextEdit::scrollDown() //m_pLeftAreaWidget->m_pBookMarkArea->update(); if (verticalScrollBar()->maximum() > 0) { - qDebug() << "Scrolling down with mark"; + qCDebug(appLog) << "Scrolling down with mark"; auto moveMode = m_cursorMark ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; QPoint endPoint = QPointF(0, height() - fontMetrics().height()).toPoint(); QTextCursor cur = cursorForPosition(endPoint); @@ -1432,17 +1433,17 @@ void TextEdit::scrollDown() } if (m_wrapper != nullptr) { - qDebug() << "Updating highlighter"; + qCDebug(appLog) << "Updating highlighter"; m_wrapper->OnUpdateHighlighter(); if ((m_wrapper->window()->findBarIsVisiable() || m_wrapper->window()->replaceBarIsVisiable()) && (QString::compare(m_wrapper->window()->getKeywordForSearchAll(), m_wrapper->window()->getKeywordForSearch(), Qt::CaseInsensitive) == 0)) { - qDebug() << "Highlighting keyword in view"; + qCDebug(appLog) << "Highlighting keyword in view"; highlightKeywordInView(m_wrapper->window()->getKeywordForSearchAll()); } markAllKeywordInView(); } - qDebug() << "Scrolling down successfully"; + qCDebug(appLog) << "Scrolling down successfully"; } /* @@ -1452,7 +1453,7 @@ void TextEdit::scrollDown() * */ void TextEdit::duplicateLine() { - qDebug() << "Duplicating line"; + qCDebug(appLog) << "Duplicating line"; auto cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); @@ -1465,15 +1466,15 @@ void TextEdit::duplicateLine() //make the vertical scroll bar change together. this->setTextCursor(cursor); - qDebug() << "Duplicating line successfully"; + qCDebug(appLog) << "Duplicating line successfully"; } void TextEdit::copyLines() { - qDebug() << "Copying lines"; + qCDebug(appLog) << "Copying lines"; // 添加权限判断是否允许拷贝,剪切;防止后续可能调用接口,冗余处理 if (!Utils::enableClipCopy(getFilePath())) { - qDebug() << "Copying lines failed"; + qCDebug(appLog) << "Copying lines failed"; return; } @@ -1482,13 +1483,13 @@ void TextEdit::copyLines() QTextCursor copyCursor = textCursor(); if (textCursor().hasSelection()) { - qDebug() << "Copying lines with selection"; + qCDebug(appLog) << "Copying lines with selection"; // Sort selection bound cursors. int startPos = textCursor().anchor(); int endPos = textCursor().position(); if (startPos > endPos) { - qDebug() << "Swapping start and end positions"; + qCDebug(appLog) << "Swapping start and end positions"; std::swap(startPos, endPos); } @@ -1506,7 +1507,7 @@ void TextEdit::copyLines() popupNotify(tr("Selected line(s) copied")); } else { - qDebug() << "Copying lines without selection"; + qCDebug(appLog) << "Copying lines without selection"; // Selection current line. copyCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); copyCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); @@ -1521,29 +1522,29 @@ void TextEdit::copyLines() // Reset cursor before copy lines. copyCursor.setPosition(currentCursor.position(), QTextCursor::MoveAnchor); setTextCursor(copyCursor); - qDebug() << "Copying lines successfully"; + qCDebug(appLog) << "Copying lines successfully"; } void TextEdit::cutlines() { - qDebug() << "Cutting lines"; + qCDebug(appLog) << "Cutting lines"; // 添加权限判断是否允许拷贝,剪切;防止后续可能调用接口,冗余处理 if (!Utils::enableClipCopy(getFilePath())) { - qDebug() << "Cutting lines failed"; + qCDebug(appLog) << "Cutting lines failed"; return; } if(m_isSelectAll) { - qDebug() << "Cutting lines with select all"; + qCDebug(appLog) << "Cutting lines with select all"; QPlainTextEdit::selectAll(); } if (textCursor().hasSelection() || m_bIsAltMod) { - qDebug() << "Cutting lines with selection"; + qCDebug(appLog) << "Cutting lines with selection"; this->cut(true); popupNotify(tr("Selected line(s) clipped")); } else { - qDebug() << "Cutting lines without selection"; + qCDebug(appLog) << "Cutting lines without selection"; auto cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); @@ -1556,16 +1557,16 @@ void TextEdit::cutlines() popupNotify(tr("Current line clipped")); } } - qDebug() << "Cutting lines successfully"; + qCDebug(appLog) << "Cutting lines successfully"; } void TextEdit::joinLines() { - qDebug() << "Joining lines"; + qCDebug(appLog) << "Joining lines"; QTextCursor cursor = this->textCursor(); //the current line isn't the last line of text. if (cursor.blockNumber() + 1 != this->document()->blockCount()) { - qDebug() << "Joining lines with next line"; + qCDebug(appLog) << "Joining lines with next line"; int startpos = 0; int endpos = 0; cursor.movePosition(QTextCursor::EndOfBlock); @@ -1583,128 +1584,128 @@ void TextEdit::joinLines() cursor.setPosition(startpos); this->setTextCursor(cursor); } - qDebug() << "Joining lines successfully"; + qCDebug(appLog) << "Joining lines successfully"; } void TextEdit::killLine() { - qDebug() << "Killing line"; + qCDebug(appLog) << "Killing line"; if (tryUnsetMark()) { - qDebug() << "Killing line failed"; + qCDebug(appLog) << "Killing line failed"; return; } // Remove selection content if has selection. if (m_isSelectAll) { - qDebug() << "Killing line with select all"; + qCDebug(appLog) << "Killing line with select all"; QPlainTextEdit::selectAll(); } if (textCursor().hasSelection()) { - qDebug() << "Killing line with selection"; + qCDebug(appLog) << "Killing line with selection"; //textCursor().removeSelectedText(); //deleteSelectTextEx(textCursor()); deleteSelectTextEx(textCursor(), textCursor().selectedText(), false); } else { - qDebug() << "Killing line without selection"; + qCDebug(appLog) << "Killing line without selection"; auto cursor = this->textCursor(); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); //the right of current line has no text but it is not the end line of this document if (cursor.selectedText().isEmpty() && cursor.blockNumber() + 1 != this->document()->blockCount()) { - qDebug() << "Killing line with next block"; + qCDebug(appLog) << "Killing line with next block"; cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor); } if (!cursor.selectedText().isEmpty()) { - qDebug() << "Killing line with selected text"; + qCDebug(appLog) << "Killing line with selected text"; DeleteBackCommand *com = new DeleteBackCommand(cursor, this); m_pUndoStack->push(com); } } - qDebug() << "Killing line successfully"; + qCDebug(appLog) << "Killing line successfully"; } void TextEdit::killCurrentLine() { - qDebug() << "Killing current line"; + qCDebug(appLog) << "Killing current line"; if (tryUnsetMark()) { - qDebug() << "Killing current line failed"; + qCDebug(appLog) << "Killing current line failed"; return; } if (m_isSelectAll) { - qDebug() << "Killing current line with select all"; + qCDebug(appLog) << "Killing current line with select all"; QPlainTextEdit::selectAll(); } auto cursor = this->textCursor(); cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); if (cursor.blockNumber() + 1 != this->document()->blockCount()) { - qDebug() << "Killing current line with next block"; + qCDebug(appLog) << "Killing current line with next block"; cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor); } else { - qDebug() << "Killing current line with end block"; + qCDebug(appLog) << "Killing current line with end block"; cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } if (!cursor.selectedText().isEmpty()) { - qDebug() << "Killing current line with selected text"; + qCDebug(appLog) << "Killing current line with selected text"; DeleteBackCommand *com = new DeleteBackCommand(cursor, this); m_pUndoStack->push(com); } - qDebug() << "Killing current line successfully"; + qCDebug(appLog) << "Killing current line successfully"; } void TextEdit::killBackwardWord() { - qDebug() << "Killing backward word"; + qCDebug(appLog) << "Killing backward word"; tryUnsetMark(); if (m_isSelectAll) { - qDebug() << "Killing backward word with select all"; + qCDebug(appLog) << "Killing backward word with select all"; QPlainTextEdit::selectAll(); } if (textCursor().hasSelection()) { - qDebug() << "Killing backward word with selection"; + qCDebug(appLog) << "Killing backward word with selection"; //textCursor().removeSelectedText(); } else { - qDebug() << "Killing backward word without selection"; + qCDebug(appLog) << "Killing backward word without selection"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor); deleteSelectTextEx(cursor); } - qDebug() << "Killing backward word successfully"; + qCDebug(appLog) << "Killing backward word successfully"; } void TextEdit::killForwardWord() { - qDebug() << "Killing forward word"; + qCDebug(appLog) << "Killing forward word"; tryUnsetMark(); if (m_isSelectAll) { - qDebug() << "Killing forward word with select all"; + qCDebug(appLog) << "Killing forward word with select all"; QPlainTextEdit::selectAll(); } if (textCursor().hasSelection()) { - qDebug() << "Killing forward word with selection"; + qCDebug(appLog) << "Killing forward word with selection"; //textCursor().removeSelectedText(); } else { - qDebug() << "Killing forward word without selection"; + qCDebug(appLog) << "Killing forward word without selection"; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor); deleteSelectTextEx(cursor); } - qDebug() << "Killing forward word successfully"; + qCDebug(appLog) << "Killing forward word successfully"; } void TextEdit::indentText() { - qDebug() << "Indenting text"; + qCDebug(appLog) << "Indenting text"; auto cursor = this->textCursor(); if (cursor.hasSelection()) { - qDebug() << "Indenting text with selection"; + qCDebug(appLog) << "Indenting text with selection"; //calculate the start postion and the end postion of current selection. int pos1 = cursor.position(); int pos2 = cursor.anchor(); @@ -1721,16 +1722,16 @@ void TextEdit::indentText() auto com = new IndentTextCommand(this, pos1, pos2, line1, line2); m_pUndoStack->push(com); } - qDebug() << "Indenting text successfully"; + qCDebug(appLog) << "Indenting text successfully"; } void TextEdit::unindentText() { - qDebug() << "Unindenting text"; + qCDebug(appLog) << "Unindenting text"; QTextCursor cursor = this->textCursor(); if (cursor.hasSelection()) { - qDebug() << "Unindenting text with selection"; + qCDebug(appLog) << "Unindenting text with selection"; //calculate the start postion and the end postion of current selection. int pos1 = cursor.position(); int pos2 = cursor.anchor(); @@ -1754,13 +1755,13 @@ void TextEdit::unindentText() //the text in front of current line is '\t'. if ("\t" == cursor.selectedText()) { - qDebug() << "Unindenting text with tab"; + qCDebug(appLog) << "Unindenting text with tab"; DeleteBackCommand *com = new DeleteBackCommand(cursor, this); m_pUndoStack->push(com); } //the text in front of current line is ' '. else if (" " == cursor.selectedText()) { - qDebug() << "Unindenting text with space"; + qCDebug(appLog) << "Unindenting text with space"; int startpos = pos; int cnt = 0; // calculate the number of ' '. @@ -1774,47 +1775,47 @@ void TextEdit::unindentText() m_pUndoStack->push(com); } } - qDebug() << "Unindenting text successfully"; + qCDebug(appLog) << "Unindenting text successfully"; } void TextEdit::setTabSpaceNumber(int number) { - qDebug() << "Setting tab space number"; + qCDebug(appLog) << "Setting tab space number"; m_tabSpaceNumber = number; updateFont(); //updateLineNumber(); updateLeftAreaWidget(); - qDebug() << "Setting tab space number successfully"; + qCDebug(appLog) << "Setting tab space number successfully"; } void TextEdit::upcaseWord() { - qDebug() << "Uppercasing word"; + qCDebug(appLog) << "Uppercasing word"; tryUnsetMark(); convertWordCase(UPPER); - qDebug() << "Uppercasing word successfully"; + qCDebug(appLog) << "Uppercasing word successfully"; } void TextEdit::downcaseWord() { - qDebug() << "Lowercasing word"; + qCDebug(appLog) << "Lowercasing word"; tryUnsetMark(); convertWordCase(LOWER); - qDebug() << "Lowercasing word successfully"; + qCDebug(appLog) << "Lowercasing word successfully"; } void TextEdit::capitalizeWord() { - qDebug() << "Capitalizing word"; + qCDebug(appLog) << "Capitalizing word"; tryUnsetMark(); convertWordCase(CAPITALIZE); - qDebug() << "Capitalizing word successfully"; + qCDebug(appLog) << "Capitalizing word successfully"; } void TextEdit::transposeChar() { - qDebug() << "Transposing character"; + qCDebug(appLog) << "Transposing character"; QTextCursor cursor = this->textCursor(); int pos = cursor.position(); cursor.setPosition(pos + 1, QTextCursor::KeepAnchor); @@ -1824,70 +1825,70 @@ void TextEdit::transposeChar() QString l = cursor.selectedText(); if (!l.isEmpty() && !r.isEmpty()) { - qDebug() << "Transposing character with selected text"; + qCDebug(appLog) << "Transposing character with selected text"; cursor.setPosition(pos - 1); cursor.setPosition(pos + 1, QTextCursor::KeepAnchor); auto com = new InsertTextUndoCommand(cursor, r + l, this); m_pUndoStack->push(com); ensureCursorVisible(); } - qDebug() << "Transposing character successfully"; + qCDebug(appLog) << "Transposing character successfully"; } void TextEdit::handleCursorMarkChanged(bool mark, QTextCursor cursor) { - qDebug() << "Handling cursor mark changed"; + qCDebug(appLog) << "Handling cursor mark changed"; if (mark) { - qDebug() << "Handling cursor mark changed with mark"; + qCDebug(appLog) << "Handling cursor mark changed with mark"; m_markStartLine = cursor.blockNumber() + 1; } else { - qDebug() << "Handling cursor mark changed without mark"; + qCDebug(appLog) << "Handling cursor mark changed without mark"; m_markStartLine = -1; } m_pLeftAreaWidget->m_pLineNumberArea->update(); m_pLeftAreaWidget->m_pBookMarkArea->update(); - qDebug() << "Handling cursor mark changed successfully"; + qCDebug(appLog) << "Handling cursor mark changed successfully"; } void TextEdit::slotValueChanged(int iValue) { - qDebug() << "Value changed"; + qCDebug(appLog) << "Value changed"; Q_UNUSED(iValue); if (m_isSelectAll) { - qDebug() << "Value changed with select all"; + qCDebug(appLog) << "Value changed with select all"; this->selectTextInView(); } this->updateLeftAreaWidget(); - qDebug() << "Value changed successfully"; + qCDebug(appLog) << "Value changed successfully"; } void TextEdit::convertWordCase(ConvertCase convertCase) { - qDebug() << "Converting word case"; + qCDebug(appLog) << "Converting word case"; #if 0 if (textCursor().hasSelection()) { - qDebug() << "Converting word case with selection"; + qCDebug(appLog) << "Converting word case with selection"; QString text = textCursor().selectedText(); if (convertCase == UPPER) { - qDebug() << "Converting word case with upper"; + qCDebug(appLog) << "Converting word case with upper"; textCursor().insertText(text.toUpper()); } else if (convertCase == LOWER) { - qDebug() << "Converting word case with lower"; + qCDebug(appLog) << "Converting word case with lower"; textCursor().insertText(text.toLower()); } else { - qDebug() << "Converting word case with capitalize"; + qCDebug(appLog) << "Converting word case with capitalize"; textCursor().insertText(capitalizeText(text)); } } else { - qDebug() << "Converting word case without selection"; + qCDebug(appLog) << "Converting word case without selection"; QTextCursor cursor; // Move cursor to mouse position first. if have word under mouse pointer. if (m_haveWordUnderCursor) { - qDebug() << "Converting word case with word under cursor"; + qCDebug(appLog) << "Converting word case with word under cursor"; setTextCursor(m_wordUnderPointerCursor); } @@ -1897,13 +1898,13 @@ void TextEdit::convertWordCase(ConvertCase convertCase) QString text = cursor.selectedText(); if (convertCase == UPPER) { - qDebug() << "Converting word case with upper"; + qCDebug(appLog) << "Converting word case with upper"; cursor.insertText(text.toUpper()); } else if (convertCase == LOWER) { - qDebug() << "Converting word case with lower"; + qCDebug(appLog) << "Converting word case with lower"; cursor.insertText(text.toLower()); } else { - qDebug() << "Converting word case with capitalize"; + qCDebug(appLog) << "Converting word case with capitalize"; cursor.insertText(capitalizeText(text)); } @@ -1914,37 +1915,37 @@ void TextEdit::convertWordCase(ConvertCase convertCase) #endif if (m_isSelectAll) { - qDebug() << "Converting word case with select all"; + qCDebug(appLog) << "Converting word case with select all"; QPlainTextEdit::selectAll(); } if (textCursor().hasSelection()) { - qDebug() << "Converting word case with selection"; + qCDebug(appLog) << "Converting word case with selection"; QString text = textCursor().selectedText(); if (convertCase == UPPER) { - qDebug() << "Converting word case with upper"; + qCDebug(appLog) << "Converting word case with upper"; text = text.toUpper(); } else if (convertCase == LOWER) { - qDebug() << "Converting word case with lower"; + qCDebug(appLog) << "Converting word case with lower"; text = text.toLower(); } else { - qDebug() << "Converting word case with capitalize"; + qCDebug(appLog) << "Converting word case with capitalize"; text = capitalizeText(text); } // 如果没有实际文本更改效果,不进行文本替换操作 if (text != textCursor().selectedText()) { - qDebug() << "Converting word case with selected text"; + qCDebug(appLog) << "Converting word case with selected text"; InsertTextUndoCommand *insertCommand = new InsertTextUndoCommand(textCursor(), text, this); m_pUndoStack->push(insertCommand); } } else { - qDebug() << "Converting word case without selection"; + qCDebug(appLog) << "Converting word case without selection"; QTextCursor cursor; // Move cursor to mouse position first. if have word under mouse pointer. if (m_haveWordUnderCursor) { - qDebug() << "Converting word case with word under cursor"; + qCDebug(appLog) << "Converting word case with word under cursor"; setTextCursor(m_wordUnderPointerCursor); } @@ -1955,17 +1956,17 @@ void TextEdit::convertWordCase(ConvertCase convertCase) QString text = cursor.selectedText(); if (!text.isEmpty()) { if (convertCase == UPPER) { - qDebug() << "Converting word case with upper"; + qCDebug(appLog) << "Converting word case with upper"; text = text.toUpper(); } else if (convertCase == LOWER) { - qDebug() << "Converting word case with lower"; + qCDebug(appLog) << "Converting word case with lower"; text = text.toLower(); } else { - qDebug() << "Converting word case with capitalize"; + qCDebug(appLog) << "Converting word case with capitalize"; text = capitalizeText(text); } - qDebug() << "Converting word case with selected text"; + qCDebug(appLog) << "Converting word case with selected text"; InsertTextUndoCommand *insertCommand = new InsertTextUndoCommand(cursor, text, this); m_pUndoStack->push(insertCommand); @@ -1974,12 +1975,12 @@ void TextEdit::convertWordCase(ConvertCase convertCase) m_haveWordUnderCursor = false; } } - qDebug() << "Converting word case successfully"; + qCDebug(appLog) << "Converting word case successfully"; } QString TextEdit::capitalizeText(QString text) { - qDebug() << "Capitalizing text"; + qCDebug(appLog) << "Capitalizing text"; QString newText = text.toLower(); QChar currentChar; QChar nextChar; @@ -1990,33 +1991,33 @@ QString TextEdit::capitalizeText(QString text) for (int i = 0; i < newText.size(); i++) { currentChar = newText.at(i); if (i + 1 < newText.size()) { - qDebug() << "Capitalizing text with next char"; + qCDebug(appLog) << "Capitalizing text with next char"; nextChar = newText.at(i + 1); } if (currentChar.isSpace() && !nextChar.isSpace()) { - qDebug() << "Capitalizing text with space and next char"; + qCDebug(appLog) << "Capitalizing text with space and next char"; newText.replace(i + 1, 1, nextChar.toUpper()); } } - qDebug() << "Capitalizing text successfully"; + qCDebug(appLog) << "Capitalizing text successfully"; return newText; } void TextEdit::keepCurrentLineAtCenter() { - qDebug() << "Keeping current line at center"; + qCDebug(appLog) << "Keeping current line at center"; QScrollBar *scrollbar = verticalScrollBar(); int currentLine = cursorRect().top() / cursorRect().height(); int halfEditorLines = rect().height() / 2 / cursorRect().height(); scrollbar->setValue(scrollbar->value() + currentLine - halfEditorLines); - qDebug() << "Keeping current line at center successfully"; + qCDebug(appLog) << "Keeping current line at center successfully"; } void TextEdit::scrollToLine(int scrollOffset, int row, int column) { - qDebug() << "Scrolling to line"; + qCDebug(appLog) << "Scrolling to line"; // Save cursor postion. m_restoreRow = row; m_restoreColumn = column; @@ -2025,12 +2026,12 @@ void TextEdit::scrollToLine(int scrollOffset, int row, int column) m_scrollAnimation->setStartValue(verticalScrollBar()->value()); m_scrollAnimation->setEndValue(scrollOffset); m_scrollAnimation->start(); - qDebug() << "Scrolling to line successfully"; + qCDebug(appLog) << "Scrolling to line successfully"; } void TextEdit::setLineWrapMode(bool enable) { - qDebug() << "Setting line wrap mode"; + qCDebug(appLog) << "Setting line wrap mode"; QTextCursor cursor = textCursor(); int nJumpLine = textCursor().blockNumber() + 1; this->setWordWrapMode(QTextOption::WrapAnywhere); @@ -2041,34 +2042,34 @@ void TextEdit::setLineWrapMode(bool enable) jumpToLine(nJumpLine, false); setTextCursor(cursor); - qDebug() << "Setting line wrap mode successfully"; + qCDebug(appLog) << "Setting line wrap mode successfully"; } void TextEdit::setFontFamily(QString name) { - qDebug() << "Setting font family"; + qCDebug(appLog) << "Setting font family"; // Update font. m_fontName = name; updateFont(); updateLeftAreaWidget(); - qDebug() << "Setting font family successfully"; + qCDebug(appLog) << "Setting font family successfully"; } void TextEdit::setFontSize(qreal size) { - qDebug() << "Setting font size"; + qCDebug(appLog) << "Setting font size"; // Update font. m_fontSize = size; updateFont(); // Update line number after adjust font size. updateLeftAreaWidget(); - qDebug() << "Setting font size successfully"; + qCDebug(appLog) << "Setting font size successfully"; } void TextEdit::updateFont() { - qDebug() << "Updating font"; + qCDebug(appLog) << "Updating font"; QFont font = document()->defaultFont(); font.setFixedPitch(true); font.setPointSizeF(m_fontSize); @@ -2077,33 +2078,33 @@ void TextEdit::updateFont() setTabStopDistance(m_tabSpaceNumber * QFontMetrics(font).horizontalAdvance(QChar(0x2192))); if (m_isSelectAll) { - qDebug() << "Updating font with select all"; + qCDebug(appLog) << "Updating font with select all"; selectTextInView(); } - qDebug() << "Updating font successfully"; + qCDebug(appLog) << "Updating font successfully"; } void TextEdit::replaceAll(const QString &replaceText, const QString &withText, Qt::CaseSensitivity caseFlag) { - qDebug() << "Starting replace all operation"; + qCDebug(appLog) << "Starting replace all operation"; if (m_readOnlyMode || m_bReadOnlyPermission) { - qDebug() << "Replace cancelled - read only mode"; + qCDebug(appLog) << "Replace cancelled - read only mode"; return; } if (replaceText.isEmpty()) { - qDebug() << "Replace cancelled - empty search text"; + qCDebug(appLog) << "Replace cancelled - empty search text"; return; } // 替换文本相同,返回 if (replaceText == withText) { - qDebug() << "Replace cancelled - same replace text"; + qCDebug(appLog) << "Replace cancelled - same replace text"; return; } - qDebug() << "Replacing all occurrences of:" << replaceText.left(20) << "with:" << withText.left(20); + qCDebug(appLog) << "Replacing all occurrences of:" << replaceText.left(20) << "with:" << withText.left(20); QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Start); @@ -2121,30 +2122,30 @@ void TextEdit::replaceAll(const QString &replaceText, const QString &withText, Q newText.replace(replaceText, withText, caseFlag); if (oldText != newText) { - qDebug() << "Replace all operation with old text and new text"; + qCDebug(appLog) << "Replace all operation with old text and new text"; ChangeMarkCommand *pChangeMark = new ChangeMarkCommand(this, backupMarkList, replaceList); // 设置替换撤销项为颜色标记变更撤销项的子项 new ReplaceAllCommand(oldText, newText, cursor, pChangeMark); m_pUndoStack->push(pChangeMark); } - qDebug() << "Replace all operation completed"; + qCDebug(appLog) << "Replace all operation completed"; } void TextEdit::replaceNext(const QString &replaceText, const QString &withText, Qt::CaseSensitivity caseFlag) { - qDebug() << "Starting replace next operation"; + qCDebug(appLog) << "Starting replace next operation"; if (m_readOnlyMode || m_bReadOnlyPermission) { - qDebug() << "Replace next operation cancelled - read only mode"; + qCDebug(appLog) << "Replace next operation cancelled - read only mode"; return; } if (m_isSelectAll) { - qDebug() << "Replace next operation with select all"; + qCDebug(appLog) << "Replace next operation with select all"; QPlainTextEdit::selectAll(); } if (replaceText.isEmpty() || !m_findHighlightSelection.cursor.hasSelection()) { - qDebug() << "Replace next operation cancelled - empty search text"; + qCDebug(appLog) << "Replace next operation cancelled - empty search text"; //无限替换的根源 return; } @@ -2152,11 +2153,11 @@ void TextEdit::replaceNext(const QString &replaceText, const QString &withText, QTextCursor cursor = textCursor(); if (m_cursorStart != -1) { - qDebug() << "Replace next operation with cursor start"; + qCDebug(appLog) << "Replace next operation with cursor start"; cursor.setPosition(m_cursorStart); m_cursorStart = -1; } else { - qDebug() << "Replace next operation with find highlight selection"; + qCDebug(appLog) << "Replace next operation with find highlight selection"; cursor.setPosition(m_findHighlightSelection.cursor.selectionStart()); } cursor.movePosition(QTextCursor::NoMove, QTextCursor::MoveAnchor); @@ -2168,10 +2169,10 @@ void TextEdit::replaceNext(const QString &replaceText, const QString &withText, QList backupMarkList = convertMarkToReplace(m_markOperations); auto replaceList = backupMarkList; for (auto &info : replaceList) { - qDebug() << "Replace next operation with mark info"; + qCDebug(appLog) << "Replace next operation with mark info"; if (MarkAll == info.opt.type || MarkAllMatch == info.opt.type) { - qDebug() << "Replace next operation with mark info - mark all"; + qCDebug(appLog) << "Replace next operation with mark info - mark all"; continue; } @@ -2182,51 +2183,51 @@ void TextEdit::replaceNext(const QString &replaceText, const QString &withText, switch (type) { case Utils::ELeft: // 当前无交集,颜色标记在替换文本左侧,表示当前颜色标记已经经过 - qDebug() << "Replace next operation with mark info - left"; + qCDebug(appLog) << "Replace next operation with mark info - left"; break; case Utils::ERight: { // 颜色标记位于右侧 - qDebug() << "Replace next operation with mark info - right"; + qCDebug(appLog) << "Replace next operation with mark info - right"; info.start += adjustlen; info.end += adjustlen; break; } case Utils::EIntersectLeft: { // 交集在替换文本左侧,拓展颜色标记右侧到替换文本右侧 - qDebug() << "Replace next operation with mark info - intersect left"; + qCDebug(appLog) << "Replace next operation with mark info - intersect left"; info.end = cursor.selectionStart() + withText.size(); break; } case Utils::EIntersectRight: { // 交集在替换文本右侧,拓展颜色标记左侧到替换文本左侧 - qDebug() << "Replace next operation with mark info - intersect right"; + qCDebug(appLog) << "Replace next operation with mark info - intersect right"; info.start = cursor.selectionStart(); info.end += adjustlen; break; } case Utils::EIntersectOutter: { // 标记内容包含替换文本 - qDebug() << "Replace next operation with mark info - intersect outter"; + qCDebug(appLog) << "Replace next operation with mark info - intersect outter"; info.end += adjustlen; break; } case Utils::EIntersectInner: { // 替换文本内容包含标记信息, 取消当前文本标记(无论单个文本还是单行文本,均移除) // 在 manualUpdateAllMark() 函数处理会移除此标记 - qDebug() << "Replace next operation with mark info - intersect inner"; + qCDebug(appLog) << "Replace next operation with mark info - intersect inner"; info.start = 0; info.end = 0; break; } default: - qDebug() << "Replace next operation with mark info - default"; + qCDebug(appLog) << "Replace next operation with mark info - default"; break; } } QString strSelection(cursor.selectedText()); if (!strSelection.compare(replaceText, caseFlag) || replaceText.contains("\n")) { - qDebug() << "Replace next operation with mark info - replace text"; + qCDebug(appLog) << "Replace next operation with mark info - replace text"; ChangeMarkCommand *pChangeMark = new ChangeMarkCommand(this, backupMarkList, replaceList); // 设置插入撤销项为颜色标记变更撤销项的子项 new InsertTextUndoCommand(cursor, withText, this, pChangeMark); @@ -2237,31 +2238,31 @@ void TextEdit::replaceNext(const QString &replaceText, const QString &withText, } highlightKeyword(replaceText, getPosition(), caseFlag); - qDebug() << "Replace all operation completed for:" << replaceText.left(20); + qCDebug(appLog) << "Replace all operation completed for:" << replaceText.left(20); } void TextEdit::replaceRest(const QString &replaceText, const QString &withText, Qt::CaseSensitivity caseFlag) { - qDebug() << "Starting replace rest operation"; + qCDebug(appLog) << "Starting replace rest operation"; if (m_readOnlyMode || m_bReadOnlyPermission) { - qDebug() << "Replace cancelled - read only mode"; + qCDebug(appLog) << "Replace cancelled - read only mode"; return; } // If replace text is nothing, don't do replace action. if (replaceText.isEmpty()) { - qDebug() << "Replace cancelled - empty search text"; + qCDebug(appLog) << "Replace cancelled - empty search text"; return; } // 替换文本相同,返回 if (replaceText == withText) { - qDebug() << "Replace cancelled - same replace text"; + qCDebug(appLog) << "Replace cancelled - same replace text"; return; } - qDebug() << "Replacing rest occurrences of:" << replaceText.left(20) << "with:" << withText.left(20); + qCDebug(appLog) << "Replacing rest occurrences of:" << replaceText.left(20) << "with:" << withText.left(20); QTextCursor cursor = textCursor(); QTextCursor startCursor = textCursor(); @@ -2282,34 +2283,34 @@ void TextEdit::replaceRest(const QString &replaceText, const QString &withText, newText += right; if (oldText != newText) { - qDebug() << "Replace rest operation with old text and new text"; + qCDebug(appLog) << "Replace rest operation with old text and new text"; ChangeMarkCommand *pChangeMark = new ChangeMarkCommand(this, backupMarkList, replaceList); // 设置替换撤销项为颜色标记变更撤销项的子项 new ReplaceAllCommand(oldText, newText, cursor, pChangeMark); m_pUndoStack->push(pChangeMark); } - qDebug() << "Replace rest operation completed"; + qCDebug(appLog) << "Replace rest operation completed"; startCursor.endEditBlock(); setTextCursor(startCursor); - qDebug() << "Replace rest operation completed for:" << replaceText.left(20); + qCDebug(appLog) << "Replace rest operation completed for:" << replaceText.left(20); } void TextEdit::beforeReplace(const QString &strReplaceText, Qt::CaseSensitivity caseFlag) { - qDebug() << "Starting before replace operation"; + qCDebug(appLog) << "Starting before replace operation"; if (strReplaceText.isEmpty() || !m_findHighlightSelection.cursor.hasSelection()) { - qDebug() << "Before replace operation with empty search text"; + qCDebug(appLog) << "Before replace operation with empty search text"; highlightKeyword(strReplaceText, getPosition(), caseFlag); } - qDebug() << "Before replace operation completed"; + qCDebug(appLog) << "Before replace operation completed"; } bool TextEdit::findKeywordForward(const QString &keyword) { - qDebug() << "Finding keyword forward:" << keyword.left(20); + qCDebug(appLog) << "Finding keyword forward:" << keyword.left(20); if (textCursor().hasSelection()) { - qDebug() << "Finding keyword forward with selection"; + qCDebug(appLog) << "Finding keyword forward with selection"; // Get selection bound. int startPos = textCursor().anchor(); int endPos = textCursor().position(); @@ -2320,7 +2321,7 @@ bool TextEdit::findKeywordForward(const QString &keyword) QTextDocument::FindFlags options; if (Qt::CaseSensitive == defaultCaseSensitive) { - qDebug() << "Finding keyword forward with case sensitive"; + qCDebug(appLog) << "Finding keyword forward with case sensitive"; options |= QTextDocument::FindCaseSensitively; } bool foundOne = find(keyword, options); @@ -2329,10 +2330,10 @@ bool TextEdit::findKeywordForward(const QString &keyword) cursor.setPosition(startPos, QTextCursor::KeepAnchor); //setTextCursor(cursor); - qDebug() << "Finding keyword forward with selection successfully: " << foundOne; + qCDebug(appLog) << "Finding keyword forward with selection successfully: " << foundOne; return foundOne; } else { - qDebug() << "Finding keyword forward without selection"; + qCDebug(appLog) << "Finding keyword forward without selection"; QTextCursor recordCursor = textCursor(); QTextCursor cursor = textCursor(); @@ -2341,21 +2342,21 @@ bool TextEdit::findKeywordForward(const QString &keyword) QTextDocument::FindFlags options; if (Qt::CaseSensitive == defaultCaseSensitive) { - qDebug() << "Finding keyword forward with case sensitive"; + qCDebug(appLog) << "Finding keyword forward with case sensitive"; options |= QTextDocument::FindCaseSensitively; } bool foundOne = find(keyword, options); //setTextCursor(recordCursor); - qDebug() << "Finding keyword forward without selection successfully: " << foundOne; + qCDebug(appLog) << "Finding keyword forward without selection successfully: " << foundOne; return foundOne; } } void TextEdit::removeKeywords() { - qDebug() << "Removing keywords"; + qCDebug(appLog) << "Removing keywords"; m_findHighlightSelection.cursor = textCursor(); m_findHighlightSelection.cursor.clearSelection(); @@ -2367,13 +2368,13 @@ void TextEdit::removeKeywords() syncRendererFindHighlight(QString()); - qDebug() << "Removing keywords successfully"; + qCDebug(appLog) << "Removing keywords successfully"; //setFocus(); } bool TextEdit::highlightKeyword(const QString &keyword, int position, Qt::CaseSensitivity caseFlag) { - qDebug() << "Highlighting keyword"; + qCDebug(appLog) << "Highlighting keyword"; Q_UNUSED(position) m_findMatchSelections.clear(); updateHighlightLineSelection(); @@ -2383,13 +2384,13 @@ bool TextEdit::highlightKeyword(const QString &keyword, int position, Qt::CaseSe syncRendererFindHighlight(keyword, caseFlag); - qDebug() << "Highlighting keyword successfully: " << bRet; + qCDebug(appLog) << "Highlighting keyword successfully: " << bRet; return bRet; } bool TextEdit::highlightKeywordInView(const QString &keyword, Qt::CaseSensitivity caseFlag) { - qDebug() << "Highlighting keyword in view"; + qCDebug(appLog) << "Highlighting keyword in view"; m_findMatchSelections.clear(); bool bRet = updateKeywordSelectionsInView(keyword, m_findMatchFormat, &m_findMatchSelections, caseFlag); // 直接设置 setExtraSelections 会导致无法显示颜色标记,调用 renderAllSelections 进行显示更新 @@ -2398,7 +2399,7 @@ bool TextEdit::highlightKeywordInView(const QString &keyword, Qt::CaseSensitivit syncRendererFindHighlight(keyword, caseFlag); - qDebug() << "Highlighting keyword in view successfully: " << bRet; + qCDebug(appLog) << "Highlighting keyword in view successfully: " << bRet; return bRet; } @@ -2427,45 +2428,45 @@ void TextEdit::syncRendererFindHighlight(const QString &keyword, Qt::CaseSensiti void TextEdit::clearFindMatchSelections() { - qDebug() << "Clearing find match selections"; + qCDebug(appLog) << "Clearing find match selections"; m_findMatchSelections.clear(); } void TextEdit::setFindHighlightSelection(const QTextCursor &cursor) { - qDebug() << "Setting find highlight selection"; + qCDebug(appLog) << "Setting find highlight selection"; m_findHighlightSelection.cursor = cursor; - qDebug() << "Find highlight selection set to position:" << cursor.position() << "with selection:" << cursor.hasSelection(); + qCDebug(appLog) << "Find highlight selection set to position:" << cursor.position() << "with selection:" << cursor.hasSelection(); } void TextEdit::updateCursorKeywordSelection(QString keyword, bool findNext, Qt::CaseSensitivity caseFlag) { - qDebug() << "Updating cursor keyword selection"; + qCDebug(appLog) << "Updating cursor keyword selection"; bool findOne = searchKeywordSeletion(keyword, textCursor(), findNext, caseFlag); - qDebug() << "Updating cursor keyword selection successfully: " << findOne; + qCDebug(appLog) << "Updating cursor keyword selection successfully: " << findOne; if (!findOne) { - qDebug() << "Updating cursor keyword selection with no find"; + qCDebug(appLog) << "Updating cursor keyword selection with no find"; QTextCursor cursor = textCursor(); cursor.movePosition(findNext ? QTextCursor::Start : QTextCursor::End, QTextCursor::MoveAnchor); if (!searchKeywordSeletion(keyword, cursor, findNext, caseFlag)) { m_findHighlightSelection.cursor = textCursor(); m_findMatchSelections.clear(); renderAllSelections(); - qDebug() << "Updating cursor keyword selection with no find successfully"; + qCDebug(appLog) << "Updating cursor keyword selection with no find successfully"; } } - qDebug() << "Updating cursor keyword selection completed"; + qCDebug(appLog) << "Updating cursor keyword selection completed"; updateMatchCount(keyword, caseFlag); } void TextEdit::updateHighlightLineSelection() { - qDebug() << "Updating highlight line selection"; + qCDebug(appLog) << "Updating highlight line selection"; if (m_gestureAction == GA_slide) { QTextCursor textCursor = QPlainTextEdit::textCursor(); - qDebug() << "Updating highlight line selection with gesture action slide"; + qCDebug(appLog) << "Updating highlight line selection with gesture action slide"; return; } @@ -2476,18 +2477,18 @@ void TextEdit::updateHighlightLineSelection() selection.cursor = textCursor(); selection.cursor.clearSelection(); m_currentLineSelection = selection; - qDebug() << "Updating highlight line selection completed"; + qCDebug(appLog) << "Updating highlight line selection completed"; } bool TextEdit::updateKeywordSelections(QString keyword, QTextCharFormat charFormat, QList &listSelection) { - qDebug() << "Updating keyword selections"; + qCDebug(appLog) << "Updating keyword selections"; // Clear keyword selections first. listSelection.clear(); // Update selections with keyword. if (!keyword.isEmpty()) { - qDebug() << "Updating keyword selections with keyword"; + qCDebug(appLog) << "Updating keyword selections with keyword"; QTextCursor cursor(document()); QTextDocument::FindFlags flags; if (Qt::CaseSensitive == defaultCaseSensitive) { @@ -2498,7 +2499,7 @@ bool TextEdit::updateKeywordSelections(QString keyword, QTextCharFormat charForm cursor = document()->find(keyword, cursor, flags); if (cursor.isNull()) { - qDebug() << "Updating keyword selections with no find"; + qCDebug(appLog) << "Updating keyword selections with no find"; return false; } @@ -2508,21 +2509,21 @@ bool TextEdit::updateKeywordSelections(QString keyword, QTextCharFormat charForm cursor = document()->find(keyword, cursor, flags); } - qDebug() << "Updating keyword selections with keyword successfully"; + qCDebug(appLog) << "Updating keyword selections with keyword successfully"; return true; } - qDebug() << "Updating keyword selections with no keyword"; + qCDebug(appLog) << "Updating keyword selections with no keyword"; return false; } QList TextEdit::scanAllMatchPositions(const QString &keyword, Qt::CaseSensitivity caseFlag) const { - qDebug() << "Scanning all match positions for keyword:" << keyword; + qCDebug(appLog) << "Scanning all match positions for keyword:" << keyword; QList positions; if (keyword.isEmpty()) { - qDebug() << "Empty keyword, return empty list"; + qCDebug(appLog) << "Empty keyword, return empty list"; return positions; } @@ -2538,15 +2539,15 @@ QList TextEdit::scanAllMatchPositions(const QString &keyword, Qt::CaseSensi cursor = document()->find(keyword, cursor, flags); } - qDebug() << "Scan completed, total positions:" << positions.size(); + qCDebug(appLog) << "Scan completed, total positions:" << positions.size(); return positions; } int TextEdit::findCurrentMatchIndex() const { - qDebug() << "Finding current match index"; + qCDebug(appLog) << "Finding current match index"; if (m_allMatchPositions.isEmpty()) { - qDebug() << "Empty cache, return 0"; + qCDebug(appLog) << "Empty cache, return 0"; return 0; } @@ -2554,26 +2555,26 @@ int TextEdit::findCurrentMatchIndex() const auto it = std::lower_bound(m_allMatchPositions.begin(), m_allMatchPositions.end(), cursorPos); if (it != m_allMatchPositions.end() && *it == cursorPos) { int index = static_cast(std::distance(m_allMatchPositions.begin(), it)); - qDebug() << "Found at index" << index; + qCDebug(appLog) << "Found at index" << index; return index + 1; } - qDebug() << "Not found in cache, return 0"; + qCDebug(appLog) << "Not found in cache, return 0"; return 0; } void TextEdit::updateMatchCount(const QString &keyword, Qt::CaseSensitivity caseFlag) { - qDebug() << "updateMatchCount keyword:" << keyword << "case:" << caseFlag; + qCDebug(appLog) << "updateMatchCount keyword:" << keyword << "case:" << caseFlag; if (keyword.isEmpty()) { - qDebug() << "Empty keyword, emit (0, 0)"; + qCDebug(appLog) << "Empty keyword, emit (0, 0)"; emit findMatchCountChanged(0, 0); return; } if (keyword != m_countedKeyword || caseFlag != m_countedCase) { - qDebug() << "Cache miss, rescan"; + qCDebug(appLog) << "Cache miss, rescan"; m_allMatchPositions = scanAllMatchPositions(keyword, caseFlag); m_countedKeyword = keyword; m_countedCase = caseFlag; @@ -2581,13 +2582,13 @@ void TextEdit::updateMatchCount(const QString &keyword, Qt::CaseSensitivity case int total = m_allMatchPositions.size(); int current = findCurrentMatchIndex(); - qDebug() << "Emit findMatchCountChanged current:" << current << "total:" << total; + qCDebug(appLog) << "Emit findMatchCountChanged current:" << current << "total:" << total; emit findMatchCountChanged(current, total); } void TextEdit::invalidateMatchCountCache() { - qDebug() << "Invalidating match count cache"; + qCDebug(appLog) << "Invalidating match count cache"; m_countedKeyword.clear(); m_allMatchPositions.clear(); } @@ -2595,13 +2596,13 @@ void TextEdit::invalidateMatchCountCache() bool TextEdit::updateKeywordSelectionsInView(QString keyword, QTextCharFormat charFormat, QList *listSelection, Qt::CaseSensitivity caseFlag) { - qDebug() << "Updating keyword selections in view"; + qCDebug(appLog) << "Updating keyword selections in view"; // Clear keyword selections first. listSelection->clear(); // Update selections with keyword. if (!keyword.isEmpty()) { - qDebug() << "Updating keyword selections in view with keyword"; + qCDebug(appLog) << "Updating keyword selections in view with keyword"; QTextCursor cursor(document()); QTextEdit::ExtraSelection extra; extra.format = charFormat; @@ -2613,11 +2614,11 @@ bool TextEdit::updateKeywordSelectionsInView(QString keyword, QTextCharFormat ch QTextBlock endBlock; if (pScrollBar->maximum() > 0) { - qDebug() << "Updating keyword selections in view with scroll bar maximum"; + qCDebug(appLog) << "Updating keyword selections in view with scroll bar maximum"; QPoint endPoint = QPointF(0, 1.5 * height()).toPoint(); endBlock = cursorForPosition(endPoint).block(); } else { - qDebug() << "Updating keyword selections in view with no scroll bar maximum"; + qCDebug(appLog) << "Updating keyword selections in view with no scroll bar maximum"; endBlock = document()->lastBlock(); } int endPos = endBlock.position() + endBlock.length() - 1; @@ -2627,11 +2628,11 @@ bool TextEdit::updateKeywordSelectionsInView(QString keyword, QTextCharFormat ch QString multiLineText; QTextDocument::FindFlags flags; if (Qt::CaseSensitive == caseFlag) { - qDebug() << "Updating keyword selections in view with case sensitive"; + qCDebug(appLog) << "Updating keyword selections in view with case sensitive"; flags |= QTextDocument::FindCaseSensitively; } if (keyword.contains(endLine)) { - qDebug() << "Updating keyword selections in view with end line"; + qCDebug(appLog) << "Updating keyword selections in view with end line"; auto temp = this->textCursor(); temp.setPosition(beginPos); while (temp.position() < endPos) { @@ -2642,12 +2643,12 @@ bool TextEdit::updateKeywordSelectionsInView(QString keyword, QTextCharFormat ch } cursor = findCursor(keyword, multiLineText, 0, false, beginPos, caseFlag); } else { - qDebug() << "Updating keyword selections in view with no end line"; + qCDebug(appLog) << "Updating keyword selections in view with no end line"; cursor = document()->find(keyword, beginPos, flags); } if (cursor.isNull()) { - qDebug() << "Updating keyword selections in view with no find"; + qCDebug(appLog) << "Updating keyword selections in view with no find"; return false; } @@ -2658,7 +2659,7 @@ bool TextEdit::updateKeywordSelectionsInView(QString keyword, QTextCharFormat ch // 防止光标位置未前进导致死循环 if (currentMatchPos <= lastMatchPos) { - qDebug() << "Updating keyword selections in view, cursor not advancing, break"; + qCDebug(appLog) << "Updating keyword selections in view, cursor not advancing, break"; break; } lastMatchPos = currentMatchPos; @@ -2667,39 +2668,39 @@ bool TextEdit::updateKeywordSelectionsInView(QString keyword, QTextCharFormat ch // 查找小写 f 时大写 F 同样会入高亮列表 Qt::CaseSensitivity option = defaultCaseSensitive; if (!extra.cursor.selectedText().compare(keyword, option) || keyword.contains(endLine, option)) { - qDebug() << "Updating keyword selections in view with selected text"; + qCDebug(appLog) << "Updating keyword selections in view with selected text"; listSelection->append(extra); } if (keyword.contains(endLine)) { int pos = std::max(extra.cursor.position(), extra.cursor.anchor()); - qDebug() << "Updating keyword selections in view with max pos"; + qCDebug(appLog) << "Updating keyword selections in view with max pos"; cursor = findCursor(keyword, multiLineText, pos - beginPos, false, beginPos, caseFlag); } else { - qDebug() << "Updating keyword selections in view with no end line"; + qCDebug(appLog) << "Updating keyword selections in view with no end line"; cursor = document()->find(keyword, cursor, flags); } if (!cursor.isNull() && cursor.position() > endPos) { - qDebug() << "Updating keyword selections in view with position greater than end pos, break"; + qCDebug(appLog) << "Updating keyword selections in view with position greater than end pos, break"; break; } } - qDebug() << "Updating keyword selections in view with keyword successfully"; + qCDebug(appLog) << "Updating keyword selections in view with keyword successfully"; return true; } - qDebug() << "Updating keyword selections in view with no keyword"; + qCDebug(appLog) << "Updating keyword selections in view with no keyword"; return false; } bool TextEdit::searchKeywordSeletion(QString keyword, QTextCursor cursor, bool findNext, Qt::CaseSensitivity caseFlag) { - qDebug() << "Searching keyword seletion"; + qCDebug(appLog) << "Searching keyword seletion"; if (keyword.isEmpty()) { - qDebug() << "Searching keyword seletion with empty keyword"; + qCDebug(appLog) << "Searching keyword seletion with empty keyword"; return false; } @@ -2707,42 +2708,42 @@ bool TextEdit::searchKeywordSeletion(QString keyword, QTextCursor cursor, bool f int offsetLines = 3; if (findNext) { - qDebug() << "Searching keyword seletion with find next"; + qCDebug(appLog) << "Searching keyword seletion with find next"; QTextDocument::FindFlags options; if (Qt::CaseSensitive == caseFlag) { - qDebug() << "Searching keyword seletion with find next and case sensitive"; + qCDebug(appLog) << "Searching keyword seletion with find next and case sensitive"; options |= QTextDocument::FindCaseSensitively; } QTextCursor next = document()->find(keyword, cursor, options); if (keyword.contains("\n")) { - qDebug() << "Searching keyword seletion with find next and contains newline"; + qCDebug(appLog) << "Searching keyword seletion with find next and contains newline"; int pos = std::max(cursor.position(), cursor.anchor()); next = findCursor(keyword, this->toPlainText(), pos, false, 0, caseFlag); } if (!next.isNull()) { - qDebug() << "Searching keyword seletion with find next and not null"; + qCDebug(appLog) << "Searching keyword seletion with find next and not null"; m_findHighlightSelection.cursor = next; jumpToLine(next.blockNumber() + offsetLines, false); setTextCursor(next); ret = true; } } else { - qDebug() << "Searching keyword seletion with find previous"; + qCDebug(appLog) << "Searching keyword seletion with find previous"; QTextDocument::FindFlags options = QTextDocument::FindBackward; if (Qt::CaseSensitive == caseFlag) { - qDebug() << "Searching keyword seletion with find previous and case sensitive"; + qCDebug(appLog) << "Searching keyword seletion with find previous and case sensitive"; options |= QTextDocument::FindCaseSensitively; } QTextCursor prev = document()->find(keyword, cursor, options); if (keyword.contains("\n")) { int pos = std::min(cursor.position(), cursor.anchor()); - qDebug() << "Searching keyword seletion with find previous and contains newline"; + qCDebug(appLog) << "Searching keyword seletion with find previous and contains newline"; prev = findCursor(keyword, this->toPlainText().mid(0, pos), -1, true, 0, caseFlag); } if (!prev.isNull()) { - qDebug() << "Searching keyword seletion with find previous and not null"; + qCDebug(appLog) << "Searching keyword seletion with find previous and not null"; m_findHighlightSelection.cursor = prev; jumpToLine(prev.blockNumber() + offsetLines, false); setTextCursor(prev); @@ -2750,19 +2751,19 @@ bool TextEdit::searchKeywordSeletion(QString keyword, QTextCursor cursor, bool f } } - qDebug() << "Searching keyword seletion completed: " << ret; + qCDebug(appLog) << "Searching keyword seletion completed: " << ret; return ret; } void TextEdit::renderAllSelections() { - qDebug() << "Rendering all selections"; + qCDebug(appLog) << "Rendering all selections"; QList finalSelections; QList> selectionsSortList; // 标记当前行的浅灰色 if (m_HightlightYes) { - qDebug() << "Rendering all selections with highlight yes"; + qCDebug(appLog) << "Rendering all selections with highlight yes"; finalSelections.append(m_currentLineSelection); } // 此处代码无作用,去除 @@ -2831,37 +2832,37 @@ void TextEdit::renderAllSelections() // 设置到 QPlainText 中进行渲染 setExtraSelections(finalSelections); - qDebug() << "Rendering all selections completed"; + qCDebug(appLog) << "Rendering all selections completed"; } void TextEdit::updateMarkAllSelectColor() { - qDebug() << "Updating mark all select color"; + qCDebug(appLog) << "Updating mark all select color"; isMarkAllLine(m_bIsMarkAllLine, m_strMarkAllLineColorName); renderAllSelections(); - qDebug() << "Updating mark all select color completed"; + qCDebug(appLog) << "Updating mark all select color completed"; } DMenu *TextEdit::getHighlightMenu() { - qDebug() << "Getting highlight menu"; + qCDebug(appLog) << "Getting highlight menu"; return m_hlGroupMenu; } void TextEdit::lineNumberAreaPaintEvent(QPaintEvent *event) { - qDebug() << "Painting line number area"; + qCDebug(appLog) << "Painting line number area"; QPainter painter(m_pLeftAreaWidget->m_pLineNumberArea); QColor lineNumberAreaBackgroundColor; if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::ColorType::DarkType) { - qDebug() << "Painting line number area with dark type"; + qCDebug(appLog) << "Painting line number area with dark type"; lineNumberAreaBackgroundColor = palette().brightText().color(); lineNumberAreaBackgroundColor.setAlphaF(0.06); m_lineNumbersColor.setAlphaF(0.2); } else { - qDebug() << "Painting line number area with light type"; + qCDebug(appLog) << "Painting line number area with light type"; lineNumberAreaBackgroundColor = palette().brightText().color(); lineNumberAreaBackgroundColor.setAlphaF(0.03); m_lineNumbersColor.setAlphaF(0.3); @@ -2878,7 +2879,7 @@ void TextEdit::lineNumberAreaPaintEvent(QPaintEvent *event) QPoint endPoint; if (verticalScrollBar()->maximum() > 0) { - qDebug() << "Painting line number area with scroll bar maximum"; + qCDebug(appLog) << "Painting line number area with scroll bar maximum"; endPoint = QPointF(0, height() + height() / verticalScrollBar()->maximum() * verticalScrollBar()->value()).toPoint(); } @@ -2889,17 +2890,17 @@ void TextEdit::lineNumberAreaPaintEvent(QPaintEvent *event) if (verticalScrollBar()->maximum() == 0) { nPageLine = blockCount() - 1; - qDebug() << "Painting line number area with no scroll bar maximum"; + qCDebug(appLog) << "Painting line number area with no scroll bar maximum"; } auto currentCursor = this->textCursor(); cur = textCursor(); for (int i = nStartLine; i <= nPageLine; i++) { if (i + 1 == m_markStartLine) { - qDebug() << "Painting line number area with mark start line"; + qCDebug(appLog) << "Painting line number area with mark start line"; painter.setPen(m_regionMarkerColor); } else { - qDebug() << "Painting line number area with no mark start line"; + qCDebug(appLog) << "Painting line number area with no mark start line"; painter.setPen(m_lineNumbersColor); } @@ -2909,7 +2910,7 @@ void TextEdit::lineNumberAreaPaintEvent(QPaintEvent *event) cur.setPosition(block.position(), QTextCursor::MoveAnchor); if (block.isVisible()) { - qDebug() << "Painting line number area with block visible"; + qCDebug(appLog) << "Painting line number area with block visible"; int w = this->m_fontSize <= 15 ? 15 : m_fontSize; updateLeftWidgetWidth(w); int offset = 0; @@ -2918,7 +2919,7 @@ void TextEdit::lineNumberAreaPaintEvent(QPaintEvent *event) offset = 2; } if (cur.blockNumber() == currentCursor.blockNumber()) { - qDebug() << "Painting line number area with current cursor block number"; + qCDebug(appLog) << "Painting line number area with current cursor block number"; painter.setPen(qApp->palette().highlight().color()); } painter.drawText(0, cursorRect(cur).y() + offset, @@ -2930,24 +2931,24 @@ void TextEdit::lineNumberAreaPaintEvent(QPaintEvent *event) top = bottom/* + document()->documentMargin()*/; bottom = top + static_cast(document()->documentLayout()->blockBoundingRect(block).height()); } - qDebug() << "Painting line number area completed"; + qCDebug(appLog) << "Painting line number area completed"; } void TextEdit::codeFLodAreaPaintEvent(QPaintEvent *event) { - qDebug() << "Painting code flod area"; + qCDebug(appLog) << "Painting code flod area"; m_listFlodIconPos.clear(); QPainter painter(m_pLeftAreaWidget->m_pFlodArea); QColor codeFlodAreaBackgroundColor; if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::ColorType::DarkType) { - qDebug() << "Painting code flod area with dark type"; + qCDebug(appLog) << "Painting code flod area with dark type"; codeFlodAreaBackgroundColor = palette().brightText().color(); codeFlodAreaBackgroundColor.setAlphaF(0.06); m_lineNumbersColor.setAlphaF(0.2); } else { - qDebug() << "Painting code flod area with light type"; + qCDebug(appLog) << "Painting code flod area with light type"; codeFlodAreaBackgroundColor = palette().brightText().color(); codeFlodAreaBackgroundColor.setAlphaF(0.03); m_lineNumbersColor.setAlphaF(0.3); @@ -2960,10 +2961,10 @@ void TextEdit::codeFLodAreaPaintEvent(QPaintEvent *event) QString theme = ""; if (guiAppHelp->themeType() == DGuiApplicationHelper::ColorType::DarkType) { //暗色主题 - qDebug() << "Painting code flod area with dark type"; + qCDebug(appLog) << "Painting code flod area with dark type"; theme = "d"; } else { //浅色主题 - qDebug() << "Painting code flod area with light type"; + qCDebug(appLog) << "Painting code flod area with light type"; theme = "l"; } @@ -2973,7 +2974,7 @@ void TextEdit::codeFLodAreaPaintEvent(QPaintEvent *event) QPoint endPoint; if (verticalScrollBar()->maximum() > 0) { - qDebug() << "Painting code flod area with scroll bar maximum"; + qCDebug(appLog) << "Painting code flod area with scroll bar maximum"; endPoint = QPointF(0, height() + height() / verticalScrollBar()->maximum() * verticalScrollBar()->value()).toPoint(); } @@ -2983,14 +2984,14 @@ void TextEdit::codeFLodAreaPaintEvent(QPaintEvent *event) if (verticalScrollBar()->maximum() == 0) { nPageLine = blockCount() - 1; - qDebug() << "Painting code flod area with no scroll bar maximum"; + qCDebug(appLog) << "Painting code flod area with no scroll bar maximum"; } cur = textCursor(); for (int iBlockCount = blockNumber ; iBlockCount <= nPageLine; ++iBlockCount) { if (block.isVisible()) { - qDebug() << "Painting code flod area with block visible"; + qCDebug(appLog) << "Painting code flod area with block visible"; //判定是否包含注释代码左括号、是否整行是注释,isNeedShowFoldIcon该函数是为了做判定当前行是否包含成对的括号,如果包括,则不显示折叠标志 //获取行数文本块 出去字符串判断 梁卫东2020年09月01日17:16:17 @@ -3009,20 +3010,20 @@ void TextEdit::codeFLodAreaPaintEvent(QPaintEvent *event) QString singleLineCommentMark; if (m_commentDefinition.isValid()) { - qDebug() << "Painting code flod area with comment definition"; + qCDebug(appLog) << "Painting code flod area with comment definition"; multiLineCommentMark = m_commentDefinition.multiLineStart.trimmed(); singleLineCommentMark = m_commentDefinition.singleLine.trimmed(); //判断是否包含单行或多行注释 if (!multiLineCommentMark.isEmpty()) bHasCommnent = block.text().trimmed().startsWith(multiLineCommentMark); if (!singleLineCommentMark.isEmpty()) bHasCommnent = block.text().trimmed().startsWith(singleLineCommentMark); } else { - qDebug() << "Painting code flod area with no comment definition"; + qCDebug(appLog) << "Painting code flod area with no comment definition"; bHasCommnent = false; } //添加注释判断 存在不显示折叠标志 不存在显示折叠标准 梁卫东 2020年09月03日17:28:50 if (curText.contains("{") && isNeedShowFoldIcon(block) && !bHasCommnent) { - qDebug() << "Painting code flod area with contains {"; + qCDebug(appLog) << "Painting code flod area with contains {"; cur.setPosition(block.position(), QTextCursor::MoveAnchor); painter.setRenderHint(QPainter::Antialiasing, true); @@ -3039,15 +3040,15 @@ void TextEdit::codeFLodAreaPaintEvent(QPaintEvent *event) QRect rect(0, cursorRect(cur).y() + offset, w, w); if (block.next().isVisible()) { - qDebug() << "Painting code flod area with block next visible"; + qCDebug(appLog) << "Painting code flod area with block next visible"; if (block.isVisible()) { - qDebug() << "Painting code flod area with block next visible"; + qCDebug(appLog) << "Painting code flod area with block next visible"; paintCodeFlod(&painter, rect); } } else { - qDebug() << "Painting code flod area with block next not visible"; + qCDebug(appLog) << "Painting code flod area with block next not visible"; if (block.isVisible()) { - qDebug() << "Painting code flod area with block next not visible"; + qCDebug(appLog) << "Painting code flod area with block next not visible"; paintCodeFlod(&painter, rect, true); } } @@ -3057,42 +3058,42 @@ void TextEdit::codeFLodAreaPaintEvent(QPaintEvent *event) block = block.next(); } - qDebug() << "Painting code flod area completed"; + qCDebug(appLog) << "Painting code flod area completed"; } void TextEdit::setBookmarkFlagVisable(bool isVisable, bool bIsFirstOpen) { - qDebug() << "Setting bookmark flag visible"; + qCDebug(appLog) << "Setting bookmark flag visible"; int w = this->m_fontSize <= 15 ? 15 : m_fontSize; updateLeftWidgetWidth(w); m_pIsShowBookmarkArea = isVisable; m_pLeftAreaWidget->m_pBookMarkArea->setVisible(isVisable); - qDebug() << "Setting bookmark flag visible completed"; + qCDebug(appLog) << "Setting bookmark flag visible completed"; } void TextEdit::setCodeFlodFlagVisable(bool isVisable, bool bIsFirstOpen) { - qDebug() << "Setting code flod flag visible"; + qCDebug(appLog) << "Setting code flod flag visible"; int w = this->m_fontSize <= 15 ? 15 : m_fontSize; updateLeftWidgetWidth(w); m_pIsShowCodeFoldArea = isVisable; m_pLeftAreaWidget->m_pFlodArea->setVisible(isVisable); - qDebug() << "Setting code flod flag visible completed"; + qCDebug(appLog) << "Setting code flod flag visible completed"; } void TextEdit::setHighLineCurrentLine(bool ok) { - qDebug() << "Setting high line current line"; + qCDebug(appLog) << "Setting high line current line"; m_HightlightYes = ok; renderAllSelections(); - qDebug() << "Setting high line current line completed"; + qCDebug(appLog) << "Setting high line current line completed"; } void TextEdit::updateLeftAreaWidget() { - qDebug() << "Updating left area widget"; + qCDebug(appLog) << "Updating left area widget"; #if 0 // not used anymore int blockSize = QString::number(blockCount()).size(); @@ -3100,28 +3101,28 @@ void TextEdit::updateLeftAreaWidget() //跟新左边框宽度 if (m_pIsShowBookmarkArea) { - qDebug() << "Updating left area widget with bookmark area"; + qCDebug(appLog) << "Updating left area widget with bookmark area"; leftAreaWidth += m_pLeftAreaWidget->m_pBookMarkArea->width(); } if (m_pIsShowCodeFoldArea) { - qDebug() << "Updating left area widget with code fold area"; + qCDebug(appLog) << "Updating left area widget with code fold area"; leftAreaWidth += m_pLeftAreaWidget->m_pFlodArea->width(); } if (bIsSetLineNumberWidth) { - qDebug() << "Updating left area widget with line number width"; + qCDebug(appLog) << "Updating left area widget with line number width"; leftAreaWidth += blockSize * fontMetrics().width('9') + 5; } // m_pLeftAreaWidget->setFixedWidth(leftAreaWidth); #endif m_pLeftAreaWidget->updateAll(); - qDebug() << "Updating left area widget completed"; + qCDebug(appLog) << "Updating left area widget completed"; } void TextEdit::handleScrollFinish() { - qDebug() << "Handling scroll finish"; + qCDebug(appLog) << "Handling scroll finish"; // Restore cursor postion. jumpToLine(m_restoreRow, false); @@ -3131,12 +3132,12 @@ void TextEdit::handleScrollFinish() // Update cursor. setTextCursor(cursor); - qDebug() << "Handling scroll finish completed"; + qCDebug(appLog) << "Handling scroll finish completed"; } void TextEdit::setSyntaxDefinition(KSyntaxHighlighting::Definition def) { - qDebug() << "Setting syntax definition"; + qCDebug(appLog) << "Setting syntax definition"; m_commentDefinition.setComments(def.singleLineCommentMarker(), def.multiLineCommentMarker().first, def.multiLineCommentMarker().second); } @@ -3198,7 +3199,7 @@ void TextEdit::updateCursorPositionStatusLightweight() void TextEdit::applyCursorHeavyUpdate() { - qDebug() << "Cursor position changed"; + qCDebug(appLog) << "Cursor position changed"; // 以赋值形式,清空 Bracket 括号的selection // m_beginBracketSelection 和 m_endBracketSelection 将在 updateHighlightBrackets 重新设置 m_beginBracketSelection = QTextEdit::ExtraSelection(); @@ -3215,7 +3216,7 @@ void TextEdit::applyCursorHeavyUpdate() m_pLeftAreaWidget->m_pLineNumberArea->update(); m_pLeftAreaWidget->m_pBookMarkArea->update(); m_pLeftAreaWidget->m_pFlodArea->update(); - qDebug() << "Cursor position changed completed"; + qCDebug(appLog) << "Cursor position changed completed"; } void TextEdit::cursorPositionChanged() @@ -3240,21 +3241,21 @@ void TextEdit::cursorPositionChanged() */ void TextEdit::cut(bool ignoreCheck) { - qDebug() << "Cutting text"; + qCDebug(appLog) << "Cutting text"; // 添加权限判断是否允许拷贝,剪切;防止后续可能调用接口,冗余处理 if (!ignoreCheck && !Utils::enableClipCopy(getFilePath())) { - qDebug() << "Cutting text with no permission, return"; + qCDebug(appLog) << "Cutting text with no permission, return"; return; } if (m_isSelectAll) { - qDebug() << "Cutting text with select all"; + qCDebug(appLog) << "Cutting text with select all"; QPlainTextEdit::selectAll(); } //列编辑添加撤销重做 if (m_bIsAltMod && !m_altModSelections.isEmpty()) { - qDebug() << "Cutting text with alt mod"; + qCDebug(appLog) << "Cutting text with alt mod"; QString data; for (auto it = m_altModSelections.begin(); it != m_altModSelections.end(); it++) { auto text = (*it).cursor.selectedText(); @@ -3270,11 +3271,11 @@ void TextEdit::cut(bool ignoreCheck) QClipboard *clipboard = QApplication::clipboard(); //获取系统剪贴板指针 clipboard->setText(data); } else { - qDebug() << "Cutting text with no alt mod"; + qCDebug(appLog) << "Cutting text with no alt mod"; QTextCursor cursor = textCursor(); //有选择内容才剪切 if (cursor.hasSelection()) { - qDebug() << "Cutting text with selection"; + qCDebug(appLog) << "Cutting text with selection"; QString data = this->selectedText(true); QUndoCommand *pDeleteStack = new DeleteTextUndoCommand(cursor, this); m_pUndoStack->push(pDeleteStack); @@ -3282,9 +3283,9 @@ void TextEdit::cut(bool ignoreCheck) clipboard->setText(data); } } - qDebug() << "Cutting text completed"; + qCDebug(appLog) << "Cutting text completed"; unsetMark(); - qDebug() << "Cutting text unset mark completed"; + qCDebug(appLog) << "Cutting text unset mark completed"; } /** @@ -3293,15 +3294,15 @@ void TextEdit::cut(bool ignoreCheck) */ void TextEdit::copy(bool ignoreCheck) { - qDebug() << "Copying text"; + qCDebug(appLog) << "Copying text"; // 添加权限判断是否允许拷贝,剪切;防止后续可能调用接口,冗余处理 if (!ignoreCheck && !Utils::enableClipCopy(getFilePath())) { - qDebug() << "Copying text with no permission, return"; + qCDebug(appLog) << "Copying text with no permission, return"; return; } if (m_bIsAltMod && !m_altModSelections.isEmpty()) { - qDebug() << "Copying text with alt mod"; + qCDebug(appLog) << "Copying text with alt mod"; QString data; for (auto it = m_altModSelections.begin(); it != m_altModSelections.end(); it++) { auto text = (*it).cursor.selectedText(); @@ -3313,32 +3314,32 @@ void TextEdit::copy(bool ignoreCheck) clipboard->setText(data); tryUnsetMark(); } else { - qDebug() << "Copying text with no alt mod"; + qCDebug(appLog) << "Copying text with no alt mod"; if (!m_isSelectAll) { - qDebug() << "Copying text with no alt mod"; + qCDebug(appLog) << "Copying text with no alt mod"; QClipboard *clipboard = QApplication::clipboard(); //获取系统剪贴板指针 if (textCursor().hasSelection()) { - qDebug() << "Copying text with selection"; + qCDebug(appLog) << "Copying text with selection"; //clipboard->setText(textCursor().selection().toPlainText()); clipboard->setText(this->selectedText(true)); tryUnsetMark(); } else { - qDebug() << "Copying text with no selection"; + qCDebug(appLog) << "Copying text with no selection"; clipboard->setText(m_highlightWordCacheCursor.selectedText()); } } else { - qDebug() << "Copying text with select all"; + qCDebug(appLog) << "Copying text with select all"; QClipboard *clipboard = QApplication::clipboard(); QString text = this->toPlainText(); clipboard->setText(text); } } - qDebug() << "Copying text completed"; + qCDebug(appLog) << "Copying text completed"; } void TextEdit::paste() { - qDebug() << "Pasting text"; + qCDebug(appLog) << "Pasting text"; #if 0 //2021-05-25:为解决大文本粘贴卡顿而注释重写 if (m_isSelectAll) @@ -3347,16 +3348,16 @@ void TextEdit::paste() const QClipboard *clipboard = QApplication::clipboard(); //获取剪切版内容 auto text = clipboard->text(); if (text.isEmpty()) { - qDebug() << "Pasting text with empty text, return"; + qCDebug(appLog) << "Pasting text with empty text, return"; return; } if (!m_bIsAltMod) { - qDebug() << "Pasting text with no alt mod"; + qCDebug(appLog) << "Pasting text with no alt mod"; QTextCursor cursor = textCursor(); insertSelectTextEx(cursor, text); unsetMark(); } else { - qDebug() << "Pasting text with alt mod"; + qCDebug(appLog) << "Pasting text with alt mod"; insertColumnEditTextEx(text); } @@ -3365,7 +3366,7 @@ void TextEdit::paste() //大文件粘贴-采用分块插入 if (m_isSelectAll) { - qDebug() << "Pasting text with select all"; + qCDebug(appLog) << "Pasting text with select all"; QPlainTextEdit::selectAll(); } @@ -3373,52 +3374,52 @@ void TextEdit::paste() auto text = clipboard->text(); if (text.isEmpty()) { - qDebug() << "Pasting text with empty text, return"; + qCDebug(appLog) << "Pasting text with empty text, return"; return; } if (!m_bIsAltMod) { - qDebug() << "Pasting text with no alt mod"; + qCDebug(appLog) << "Pasting text with no alt mod"; int block = 1 * 1024 * 1024; int size = text.size(); if (size > block) { - qDebug() << "Pasting text with size greater than block"; + qCDebug(appLog) << "Pasting text with size greater than block"; InsertBlockByTextCommand *commond = new InsertBlockByTextCommand(text, this, m_wrapper); m_pUndoStack->push(commond); } else { - qDebug() << "Pasting text with size less than block"; + qCDebug(appLog) << "Pasting text with size less than block"; QTextCursor cursor = textCursor(); insertSelectTextEx(cursor, text); unsetMark(); } } else { - qDebug() << "Pasting text with alt mod"; + qCDebug(appLog) << "Pasting text with alt mod"; insertColumnEditTextEx(text); } m_isSelectAll = false; - qDebug() << "Pasting text completed"; + qCDebug(appLog) << "Pasting text completed"; } void TextEdit::highlight() { QTimer::singleShot(0, this, [&]() { if (nullptr != m_wrapper) { - qDebug() << "Highlighting with wrapper"; + qCDebug(appLog) << "Highlighting with wrapper"; m_wrapper->OnUpdateHighlighter(); } }); - qDebug() << "Highlighting completed"; + qCDebug(appLog) << "Highlighting completed"; } void TextEdit::selectTextInView() { - qDebug() << "Selecting text in view"; + qCDebug(appLog) << "Selecting text in view"; // 重入守卫:setTextCursor 会触发 QInputMethod::update(在 fcitx5 环境下会 // 异步回查光标矩形),并改变滚动条/布局,这些会分别触发 slotValueChanged、 // resizeEvent;它们在 m_isSelectAll 时会再次调用 selectTextInView,形成 // 自激振荡导致主线程死循环卡死。这里阻断重入。 if (m_isSelectingInView) { - qDebug() << "Selecting text in view skipped: already in progress"; + qCDebug(appLog) << "Selecting text in view skipped: already in progress"; return; } m_isSelectingInView = true; @@ -3434,7 +3435,7 @@ void TextEdit::selectTextInView() this->horizontalScrollBar()->setValue(0); m_isSelectingInView = false; - qDebug() << "Selecting text in view completed"; + qCDebug(appLog) << "Selecting text in view completed"; } /** @@ -3445,9 +3446,9 @@ void TextEdit::selectTextInView() */ void TextEdit::setSelectAll() { - qDebug() << "Setting select all"; + qCDebug(appLog) << "Setting select all"; if (m_wrapper->getFileLoading()) { - qDebug() << "Setting select all with file loading, return"; + qCDebug(appLog) << "Setting select all with file loading, return"; return; } @@ -3456,18 +3457,18 @@ void TextEdit::setSelectAll() selectTextInView(); if (!document()->isEmpty() && IflytekAiAssistant::instance()->valid()) { - qDebug() << "Setting select all with valid"; + qCDebug(appLog) << "Setting select all with valid"; if (auto clip = qApp->clipboard()) { - qDebug() << "Setting select all with clipboard"; + qCDebug(appLog) << "Setting select all with clipboard"; // limit the size of the text to avoid performance issue static const int kMaxSelectCount = 200000; int charCount = document()->characterCount(); if (charCount < kMaxSelectCount) { - qDebug() << "Setting select all with clipboard and char count less than kMaxSelectCount"; + qCDebug(appLog) << "Setting select all with clipboard and char count less than kMaxSelectCount"; clip->setText(toPlainText(), QClipboard::Selection); } else { - qDebug() << "Setting select all with clipboard and char count greater than kMaxSelectCount"; + qCDebug(appLog) << "Setting select all with clipboard and char count greater than kMaxSelectCount"; auto selectCursor = textCursor(); selectCursor.setPosition(0); selectCursor.setPosition(kMaxSelectCount, QTextCursor::KeepAnchor); @@ -3475,350 +3476,350 @@ void TextEdit::setSelectAll() } } } - qDebug() << "Setting select all completed"; + qCDebug(appLog) << "Setting select all completed"; } void TextEdit::slotSigColorSelected(bool bSelected, QColor color) { - qDebug() << "Slot sig color selected"; + qCDebug(appLog) << "Slot sig color selected"; if (m_isSelectAll) { - qDebug() << "Slot sig color selected with select all"; + qCDebug(appLog) << "Slot sig color selected with select all"; QPlainTextEdit::selectAll(); } isMarkCurrentLine(bSelected, color.name()); renderAllSelections(); m_colorMarkMenu->close(); m_rightMenu->close(); //选择颜色关闭菜单 梁卫东 2020-08-21 09:34:53 - qDebug() << "Slot sig color selected completed"; + qCDebug(appLog) << "Slot sig color selected completed"; } void TextEdit::slotSigColorAllSelected(bool bSelected, QColor color) { - qDebug() << "Slot sig color all selected"; + qCDebug(appLog) << "Slot sig color all selected"; if (m_isSelectAll) { - qDebug() << "Slot sig color all selected with select all"; + qCDebug(appLog) << "Slot sig color all selected with select all"; QPlainTextEdit::selectAll(); } isMarkAllLine(bSelected, color.name()); renderAllSelections(); m_colorMarkMenu->close(); m_rightMenu->close(); //选择颜色关闭菜单 梁卫东 2020-08-21 09:34:53 - qDebug() << "Slot sig color all selected completed"; + qCDebug(appLog) << "Slot sig color all selected completed"; } void TextEdit::slotCutAction(bool checked) { - qDebug() << "Slot cut action"; + qCDebug(appLog) << "Slot cut action"; Q_UNUSED(checked); this->cut(); - qDebug() << "Slot cut action completed"; + qCDebug(appLog) << "Slot cut action completed"; } void TextEdit::slotCopyAction(bool checked) { - qDebug() << "Slot copy action"; + qCDebug(appLog) << "Slot copy action"; Q_UNUSED(checked); if (isAbleOperation(Utils::CopyOperation)) { - qDebug() << "Slot copy action with able operation"; + qCDebug(appLog) << "Slot copy action with able operation"; copy(); } else { #ifdef DTKWIDGET_CLASS_DSizeMode - qDebug() << "Slot copy action with dsize mode"; + qCDebug(appLog) << "Slot copy action with dsize mode"; Utils::sendFloatMessageFixedFont(this, QIcon(":/images/warning.svg"), tr("Copy failed: not enough memory")); #else - qDebug() << "Slot copy action with no dsize mode"; + qCDebug(appLog) << "Slot copy action with no dsize mode"; DMessageManager::instance()->sendMessage(this, QIcon(":/images/warning.svg"), tr("Copy failed: not enough memory")); #endif } - qDebug() << "Slot copy action completed"; + qCDebug(appLog) << "Slot copy action completed"; } void TextEdit::slotPasteAction(bool checked) { - qDebug() << "Slot paste action"; + qCDebug(appLog) << "Slot paste action"; Q_UNUSED(checked); if (isAbleOperation(Utils::PasteOperation)) { - qDebug() << "Slot paste action with able operation"; + qCDebug(appLog) << "Slot paste action with able operation"; paste(); } else { #ifdef DTKWIDGET_CLASS_DSizeMode - qDebug() << "Slot paste action with dsize mode"; + qCDebug(appLog) << "Slot paste action with dsize mode"; Utils::sendFloatMessageFixedFont(this, QIcon(":/images/warning.svg"), tr("Paste failed: not enough memory")); #else - qDebug() << "Slot paste action with no dsize mode"; + qCDebug(appLog) << "Slot paste action with no dsize mode"; DMessageManager::instance()->sendMessage(this, QIcon(":/images/warning.svg"), tr("Paste failed: not enough memory")); #endif } - qDebug() << "Slot paste action completed"; + qCDebug(appLog) << "Slot paste action completed"; } void TextEdit::slotDeleteAction(bool checked) { - qDebug() << "Slot delete action"; + qCDebug(appLog) << "Slot delete action"; Q_UNUSED(checked); if (m_isSelectAll) { - qDebug() << "Slot delete action with select all"; + qCDebug(appLog) << "Slot delete action with select all"; QPlainTextEdit::selectAll(); } if (m_bIsAltMod && !m_altModSelections.isEmpty()) { - qDebug() << "Slot delete action with alt mod"; + qCDebug(appLog) << "Slot delete action with alt mod"; QUndoCommand *pDeleteStack = new DeleteBackAltCommand(m_altModSelections, this); m_pUndoStack->push(pDeleteStack); } else { if (textCursor().hasSelection()) { - qDebug() << "Slot delete action with selection"; + qCDebug(appLog) << "Slot delete action with selection"; QUndoCommand *pDeleteStack = new DeleteTextUndoCommand(textCursor(), this); m_pUndoStack->push(pDeleteStack); } else { - qDebug() << "Slot delete action with no selection"; + qCDebug(appLog) << "Slot delete action with no selection"; setTextCursor(m_highlightWordCacheCursor); } } - qDebug() << "Slot delete action completed"; + qCDebug(appLog) << "Slot delete action completed"; } void TextEdit::slotSelectAllAction(bool checked) { - qDebug() << "Slot select all action"; + qCDebug(appLog) << "Slot select all action"; Q_UNUSED(checked); setSelectAll(); - qDebug() << "Slot select all action completed"; + qCDebug(appLog) << "Slot select all action completed"; } bool TextEdit::slotOpenInFileManagerAction(bool checked) { - qDebug() << "Slot open in file manager action"; + qCDebug(appLog) << "Slot open in file manager action"; Q_UNUSED(checked); return DDesktopServices::showFileItem(this->getTruePath()); } void TextEdit::slotAddComment(bool checked) { - qDebug() << "Slot add comment action"; + qCDebug(appLog) << "Slot add comment action"; Q_UNUSED(checked); toggleComment(true); - qDebug() << "Slot add comment action completed"; + qCDebug(appLog) << "Slot add comment action completed"; } void TextEdit::slotCancelComment(bool checked) { - qDebug() << "Slot cancel comment action"; + qCDebug(appLog) << "Slot cancel comment action"; Q_UNUSED(checked); toggleComment(false); - qDebug() << "Slot cancel comment action completed"; + qCDebug(appLog) << "Slot cancel comment action completed"; } void TextEdit::slotVoiceReadingAction(bool checked) { - qDebug() << "Slot voice reading action"; + qCDebug(appLog) << "Slot voice reading action"; Q_UNUSED(checked); auto ret = IflytekAiAssistant::instance()->textToSpeech(); if (IflytekAiAssistant::Success != ret) { - qDebug() << "Slot voice reading action with error"; + qCDebug(appLog) << "Slot voice reading action with error"; Q_EMIT popupNotify(IflytekAiAssistant::instance()->errorString(ret), true); } emit signal_readingPath(); - qDebug() << "Slot voice reading action completed"; + qCDebug(appLog) << "Slot voice reading action completed"; } bool TextEdit::slotStopReadingAction(bool checked) { - qDebug() << "Slot stop reading action"; + qCDebug(appLog) << "Slot stop reading action"; Q_UNUSED(checked); bool ret = IflytekAiAssistant::instance()->stopTtsDirectly(); - qDebug() << "Slot stop reading action completed"; + qCDebug(appLog) << "Slot stop reading action completed"; return ret; } void TextEdit::slotdictationAction(bool checked) { - qDebug() << "Slot dictation action"; + qCDebug(appLog) << "Slot dictation action"; Q_UNUSED(checked); auto ret = IflytekAiAssistant::instance()->speechToText(); if (IflytekAiAssistant::Success != ret) { - qDebug() << "Slot dictation action with error"; + qCDebug(appLog) << "Slot dictation action with error"; Q_EMIT popupNotify(IflytekAiAssistant::instance()->errorString(ret), true); } - qDebug() << "Slot dictation action completed"; + qCDebug(appLog) << "Slot dictation action completed"; } void TextEdit::slotColumnEditAction(bool checked) { Q_UNUSED(checked); - qDebug() << "Slot column edit action"; + qCDebug(appLog) << "Slot column edit action"; #ifdef DTKWIDGET_CLASS_DSizeMode Utils::sendFloatMessageFixedFont(this, QIcon(":/images/ok.svg"), tr("Press ALT and click lines to edit in column mode")); #else DMessageManager::instance()->sendMessage(this, QIcon(":/images/ok.svg"), tr("Press ALT and click lines to edit in column mode")); #endif - qDebug() << "Slot column edit action completed"; + qCDebug(appLog) << "Slot column edit action completed"; } void TextEdit::slotPreBookMarkAction(bool checked) { - qDebug() << "Slot pre book mark action"; + qCDebug(appLog) << "Slot pre book mark action"; Q_UNUSED(checked); int line = getLineFromPoint(m_mouseClickPos); int index = m_listBookmark.indexOf(line); if (index == 0) { - qDebug() << "Slot pre book mark action with index 0"; + qCDebug(appLog) << "Slot pre book mark action with index 0"; jumpToLine(m_listBookmark.last(), true); } else { - qDebug() << "Slot pre book mark action with index not 0"; + qCDebug(appLog) << "Slot pre book mark action with index not 0"; jumpToLine(m_listBookmark.value(index - 1), true); } - qDebug() << "Slot pre book mark action completed"; + qCDebug(appLog) << "Slot pre book mark action completed"; } void TextEdit::slotNextBookMarkAction(bool checked) { - qDebug() << "Slot next book mark action"; + qCDebug(appLog) << "Slot next book mark action"; Q_UNUSED(checked); int line = getLineFromPoint(m_mouseClickPos); int index = m_listBookmark.indexOf(line); if (index == -1 && !m_listBookmark.isEmpty()) { - qDebug() << "Slot next book mark action with index -1"; + qCDebug(appLog) << "Slot next book mark action with index -1"; jumpToLine(m_listBookmark.last(), false); // 无书签命中时跳至末个书签后直接返回,避免落入下方 if/else 二次跳转 return; } if (index == m_listBookmark.count() - 1) { - qDebug() << "Slot next book mark action with index equal to count - 1"; + qCDebug(appLog) << "Slot next book mark action with index equal to count - 1"; jumpToLine(m_listBookmark.first(), false); } else { - qDebug() << "Slot next book mark action with index not equal to count - 1"; + qCDebug(appLog) << "Slot next book mark action with index not equal to count - 1"; jumpToLine(m_listBookmark.value(index + 1), false); } - qDebug() << "Slot next book mark action completed"; + qCDebug(appLog) << "Slot next book mark action completed"; } void TextEdit::slotClearBookMarkAction(bool checked) { - qDebug() << "Slot clear book mark action"; + qCDebug(appLog) << "Slot clear book mark action"; Q_UNUSED(checked); m_listBookmark.clear(); - qDebug() << "ClearBookMark:" << m_listBookmark; + qCDebug(appLog) << "ClearBookMark:" << m_listBookmark; m_pLeftAreaWidget->m_pBookMarkArea->update(); - qDebug() << "Slot clear book mark action completed"; + qCDebug(appLog) << "Slot clear book mark action completed"; } void TextEdit::slotFlodAllLevel(bool checked) { - qDebug() << "Slot flod all level action"; + qCDebug(appLog) << "Slot flod all level action"; Q_UNUSED(checked); flodOrUnflodAllLevel(true); - qDebug() << "Slot flod all level action completed"; + qCDebug(appLog) << "Slot flod all level action completed"; } void TextEdit::slotUnflodAllLevel(bool checked) { - qDebug() << "Slot unflod all level action"; + qCDebug(appLog) << "Slot unflod all level action"; Q_UNUSED(checked); flodOrUnflodAllLevel(false); - qDebug() << "Slot unflod all level action completed"; + qCDebug(appLog) << "Slot unflod all level action completed"; } void TextEdit::slotFlodCurrentLevel(bool checked) { - qDebug() << "Slot flod current level action"; + qCDebug(appLog) << "Slot flod current level action"; Q_UNUSED(checked); flodOrUnflodCurrentLevel(true); - qDebug() << "Slot flod current level action completed"; + qCDebug(appLog) << "Slot flod current level action completed"; } void TextEdit::slotUnflodCurrentLevel(bool checked) { - qDebug() << "Slot unflod current level action"; + qCDebug(appLog) << "Slot unflod current level action"; Q_UNUSED(checked); flodOrUnflodCurrentLevel(false); - qDebug() << "Slot unflod current level action completed"; + qCDebug(appLog) << "Slot unflod current level action completed"; } void TextEdit::slotCancleMarkAllLine(bool checked) { - qDebug() << "Slot cancle mark all line action"; + qCDebug(appLog) << "Slot cancle mark all line action"; Q_UNUSED(checked); isMarkAllLine(false); - qDebug() << "Slot cancle mark all line action completed"; + qCDebug(appLog) << "Slot cancle mark all line action completed"; } void TextEdit::slotCancleLastMark(bool checked) { - qDebug() << "Slot cancle last mark action"; + qCDebug(appLog) << "Slot cancle last mark action"; Q_UNUSED(checked); cancelLastMark(); - qDebug() << "Slot cancle last mark action completed"; + qCDebug(appLog) << "Slot cancle last mark action completed"; } void TextEdit::slotUndoAvailable(bool undoIsAvailable) { - qDebug() << "Slot undo available action"; + qCDebug(appLog) << "Slot undo available action"; m_canUndo = undoIsAvailable; - qDebug() << "Slot undo available action completed"; + qCDebug(appLog) << "Slot undo available action completed"; } void TextEdit::slotRedoAvailable(bool redoIsAvailable) { - qDebug() << "Slot redo available action"; + qCDebug(appLog) << "Slot redo available action"; m_canRedo = redoIsAvailable; - qDebug() << "Slot redo available action completed"; + qCDebug(appLog) << "Slot redo available action completed"; } void TextEdit::redo_() { - qDebug() << "Starting redo operation"; + qCDebug(appLog) << "Starting redo operation"; flushDeferredCursorUpdate(); if (!m_pUndoStack->canRedo()) { - qDebug() << "Redo operation skipped - nothing to redo"; + qCDebug(appLog) << "Redo operation skipped - nothing to redo"; return; } // Get current stack info before redo const bool needUpdate = refreshUndoRedoColumnStatus(); - qDebug() << "Redo operation - need update selections:" << needUpdate; + qCDebug(appLog) << "Redo operation - need update selections:" << needUpdate; m_pUndoStack->redo(); - qDebug() << "Redo operation executed, new stack index:" << m_pUndoStack->index(); + qCDebug(appLog) << "Redo operation executed, new stack index:" << m_pUndoStack->index(); if (needUpdate) { renderAllSelections(); update(); - qDebug() << "Selections updated after redo"; + qCDebug(appLog) << "Selections updated after redo"; } if (m_pUndoStack->index() == m_lastSaveIndex) { this->m_wrapper->window()->updateModifyStatus(m_sFilePath, false); this->m_wrapper->setTemFile(false); this->document()->setModified(false); - qDebug() << "File modification status reset after redo"; + qCDebug(appLog) << "File modification status reset after redo"; } - qDebug() << "Redo operation completed successfully"; + qCDebug(appLog) << "Redo operation completed successfully"; } void TextEdit::undo_() { - qDebug() << "Starting undo operation"; - qDebug() << "Starting undo operation"; + qCDebug(appLog) << "Starting undo operation"; + qCDebug(appLog) << "Starting undo operation"; flushDeferredCursorUpdate(); if (!m_pUndoStack->canUndo()) { - qDebug() << "Undo operation skipped - nothing to undo"; + qCDebug(appLog) << "Undo operation skipped - nothing to undo"; return; } m_pUndoStack->undo(); - qDebug() << "Undo operation executed, new stack index:" << m_pUndoStack->index(); + qCDebug(appLog) << "Undo operation executed, new stack index:" << m_pUndoStack->index(); const bool needUpdate = refreshUndoRedoColumnStatus(); if (needUpdate) { renderAllSelections(); update(); - qDebug() << "Selections updated after undo"; + qCDebug(appLog) << "Selections updated after undo"; } // 对撤销栈清空的情况下,有两种文件仍需保留*号(重做无需如下判定) @@ -3830,9 +3831,9 @@ void TextEdit::undo_() this->m_wrapper->window()->updateModifyStatus(m_sFilePath, false); this->m_wrapper->setTemFile(false); this->document()->setModified(false); - qDebug() << "File modification status reset after undo"; + qCDebug(appLog) << "File modification status reset after undo"; } - qDebug() << "Undo operation completed successfully"; + qCDebug(appLog) << "Undo operation completed successfully"; } /*! @@ -3845,14 +3846,14 @@ void TextEdit::undo_() */ void TextEdit::moveText(int from, int to, const QString &text, bool copy) { - qDebug() << "Moving text from" << from << "to" << to << "with text" << text << "and copy" << copy; + qCDebug(appLog) << "Moving text from" << from << "to" << to << "with text" << text << "and copy" << copy; auto cursor = this->textCursor(); auto list = new UndoList; cursor.setPosition(from); QUndoCommand *delCommand = nullptr; // 拷贝模式下无需删除文本 if (!copy) { - qDebug() << "Moving text with delete"; + qCDebug(appLog) << "Moving text with delete"; cursor.setPosition(from + text.size(), QTextCursor::KeepAnchor); delCommand = new DeleteBackCommand(cursor, this); } @@ -3863,17 +3864,17 @@ void TextEdit::moveText(int from, int to, const QString &text, bool copy) //the positon of 'from' is on the left of the position of 'to', //therefore,firstly do the insert operation. if (from < to) { - qDebug() << "Moving text with from < to"; + qCDebug(appLog) << "Moving text with from < to"; list->appendCom(insertCommand); if (!copy) { - qDebug() << "Moving text with delete and from < to"; + qCDebug(appLog) << "Moving text with delete and from < to"; list->appendCom(delCommand); } m_pUndoStack->push(list); } else if (from > to) { - qDebug() << "Moving text with from > to"; + qCDebug(appLog) << "Moving text with from > to"; if (!copy) { - qDebug() << "Moving text with delete and from > to"; + qCDebug(appLog) << "Moving text with delete and from > to"; list->appendCom(delCommand); } list->appendCom(insertCommand); @@ -3885,7 +3886,7 @@ void TextEdit::moveText(int from, int to, const QString &text, bool copy) delete delCommand; } } - qDebug() << "Moving text completed"; + qCDebug(appLog) << "Moving text completed"; } /** @@ -3900,33 +3901,33 @@ void TextEdit::moveText(int from, int to, const QString &text, bool copy) QTextCursor TextEdit::findCursor(const QString &substr, const QString &text, int from, bool backward, int cursorPos, Qt::CaseSensitivity caseFlag) { - qDebug() << "Finding text:" << substr.left(20) << "from position:" << from + qCDebug(appLog) << "Finding text:" << substr.left(20) << "from position:" << from << "direction:" << (backward ? "backward" : "forward"); // 处理换行符为 \r\n (光标计算时被视为单个字符)的情况,移除多计算的字符数 // text 均为 \n 结尾 QString findSubStr = substr; if (BottomBar::Windows == m_wrapper->bottomBar()->getEndlineFormat()) { - qDebug() << "Finding text with windows endline format"; + qCDebug(appLog) << "Finding text with windows endline format"; findSubStr.replace("\r\n", "\n"); } int index = -1; if (backward) { - qDebug() << "Finding text with backward direction"; + qCDebug(appLog) << "Finding text with backward direction"; index = text.lastIndexOf(findSubStr, from, caseFlag); } else { - qDebug() << "Finding text with forward direction"; + qCDebug(appLog) << "Finding text with forward direction"; index = text.indexOf(findSubStr, from, caseFlag); } if (-1 != index) { - qDebug() << "Find successful at position:" << index; + qCDebug(appLog) << "Find successful at position:" << index; auto cursor = this->textCursor(); cursor.setPosition(index + cursorPos); cursor.setPosition(cursor.position() + findSubStr.size(), QTextCursor::KeepAnchor); return cursor; } else { - qDebug() << "Find failed - text not found"; + qCDebug(appLog) << "Find failed - text not found"; return QTextCursor(); } } @@ -3938,22 +3939,22 @@ QTextCursor TextEdit::findCursor(const QString &substr, const QString &text, int */ void TextEdit::onPressedLineNumber(const QPoint &point) { - qDebug() << "On pressed line number"; + qCDebug(appLog) << "On pressed line number"; // 在执行大文件加载过程中,由于 cursorForPosition() 计算耗时,不响应点击处理 if (TextEdit::FileOpenBegin == m_LeftAreaUpdateState) { - qDebug() << "On pressed line number with file open begin, return"; + qCDebug(appLog) << "On pressed line number with file open begin, return"; return; } if (point.x() < 0 || point.x() > m_pLeftAreaWidget->m_pLineNumberArea->width()) { - qDebug() << "On pressed line number with point x out of range, return"; + qCDebug(appLog) << "On pressed line number with point x out of range, return"; return; } int offset = 0; //the language currently set by the system is Tibetan. if ("bo_CN" == Utils::getSystemLan()) { - qDebug() << "On pressed line number with Tibetan language"; + qCDebug(appLog) << "On pressed line number with Tibetan language"; offset = 2; } @@ -3961,22 +3962,22 @@ void TextEdit::onPressedLineNumber(const QPoint &point) QTextBlock possibleBlock = cursorForPosition(checkPoint).block(); if (possibleBlock.isValid()) { - qDebug() << "On pressed line number with possible block"; + qCDebug(appLog) << "On pressed line number with possible block"; QTextCursor cursor = textCursor(); cursor.setPosition(possibleBlock.position(), QTextCursor::MoveAnchor); // 尾行光标不调整到下一行 if (possibleBlock == document()->lastBlock()) { - qDebug() << "On pressed line number with last block"; + qCDebug(appLog) << "On pressed line number with last block"; cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } else { - qDebug() << "On pressed line number with not last block"; + qCDebug(appLog) << "On pressed line number with not last block"; cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor); } setTextCursor(cursor); } - qDebug() << "On pressed line number completed"; + qCDebug(appLog) << "On pressed line number completed"; } /** @@ -3987,7 +3988,7 @@ void TextEdit::onPressedLineNumber(const QPoint &point) */ QString TextEdit::selectedText(bool checkCRLF) { - qDebug() << "Getting selected text"; + qCDebug(appLog) << "Getting selected text"; auto cursor = this->textCursor(); auto temp = cursor; int startpos = std::min(cursor.anchor(), cursor.position()); @@ -3999,7 +4000,7 @@ QString TextEdit::selectedText(bool checkCRLF) endblock = cursor.blockNumber(); // 仅单个文本块,直接提取文本数据 if (startblock == endblock) { - qDebug() << "Getting selected text with single block, return"; + qCDebug(appLog) << "Getting selected text with single block, return"; return temp.selectedText(); } @@ -4013,7 +4014,7 @@ QString TextEdit::selectedText(bool checkCRLF) // 不同风格使用不同换行符,默认不替换,仅在剪贴板、保存文件等时设置 QString endLine = "\n"; if (checkCRLF && BottomBar::Windows == m_wrapper->bottomBar()->getEndlineFormat()) { - qDebug() << "Getting selected text with windows endline format"; + qCDebug(appLog) << "Getting selected text with windows endline format"; endLine = "\r\n"; } @@ -4027,7 +4028,7 @@ QString TextEdit::selectedText(bool checkCRLF) // 取得尾部文本块内容 if (cursor.position() < endpos) { - qDebug() << "Getting selected text with tail block"; + qCDebug(appLog) << "Getting selected text with tail block"; // 判断是否尾部文本块达到当前文本块末尾,到达末尾需要将 U+2029 替换为 \n bool needAdjustNewline = bool(cursor.position() + cursor.block().length() == endpos); cursor.setPosition(endpos, QTextCursor::KeepAnchor); @@ -4039,7 +4040,7 @@ QString TextEdit::selectedText(bool checkCRLF) } } - qDebug() << "Getting selected text completed"; + qCDebug(appLog) << "Getting selected text completed"; return text; } @@ -4052,11 +4053,11 @@ QString TextEdit::selectedText(bool checkCRLF) void TextEdit::onEndlineFormatChanged(BottomBar::EndlineFormat from, BottomBar::EndlineFormat to) { - qDebug() << "On endline format changed"; + qCDebug(appLog) << "On endline format changed"; //auto endlineCom = new EndlineFormartCommand(this,m_wrapper->bottomBar(),from,to); //m_pUndoStack->push(endlineCom); m_wrapper->bottomBar()->setEndlineMenuText(to); - qDebug() << "On endline format changed completed"; + qCDebug(appLog) << "On endline format changed completed"; } /** @@ -4064,10 +4065,10 @@ void TextEdit::onEndlineFormatChanged(BottomBar::EndlineFormat from, BottomBar:: */ void TextEdit::onAppPaletteChanged() { - qDebug() << "On app palette changed"; + qCDebug(appLog) << "On app palette changed"; // 判断是否处于列选取状态 if (m_bIsAltMod && !m_altModSelections.isEmpty()) { - qDebug() << "On app palette changed with alt mod"; + qCDebug(appLog) << "On app palette changed with alt mod"; QColor highlightBackground = DGuiApplicationHelper::instance()->applicationPalette().color(QPalette::Highlight); for (auto &selection : m_altModSelections) { selection.format.setBackground(highlightBackground); @@ -4075,12 +4076,12 @@ void TextEdit::onAppPaletteChanged() // 更新高亮状态 renderAllSelections(); } - qDebug() << "On app palette changed completed"; + qCDebug(appLog) << "On app palette changed completed"; } void TextEdit::updateHighlightBrackets(const QChar &openChar, const QChar &closeChar) { - qDebug() << "Updating highlight brackets"; + qCDebug(appLog) << "Updating highlight brackets"; QTextDocument *doc = document(); QTextCursor cursor = textCursor(); int position = cursor.position(); @@ -4090,7 +4091,7 @@ void TextEdit::updateHighlightBrackets(const QChar &openChar, const QChar &close cursor.clearSelection(); if (!bracketBeginCursor.isNull() || !bracketEndCursor.isNull()) { - qDebug() << "Updating highlight brackets with null"; + qCDebug(appLog) << "Updating highlight brackets with null"; bracketBeginCursor.setCharFormat(QTextCharFormat()); bracketEndCursor.setCharFormat(QTextCharFormat()); bracketBeginCursor = bracketEndCursor = QTextCursor(); @@ -4102,30 +4103,30 @@ void TextEdit::updateHighlightBrackets(const QChar &openChar, const QChar &close doc->characterAt(position) == closeChar || doc->characterAt(position - 1) == openChar || doc->characterAt(position - 1) == closeChar) { - qDebug() << "Updating highlight brackets with character at position"; + qCDebug(appLog) << "Updating highlight brackets with character at position"; bool forward = doc->characterAt(position) == openChar || doc->characterAt(position - 1) == openChar; if (forward) { - qDebug() << "Updating highlight brackets with forward"; + qCDebug(appLog) << "Updating highlight brackets with forward"; if (doc->characterAt(position) == openChar) { - qDebug() << "Updating highlight brackets with openChar"; + qCDebug(appLog) << "Updating highlight brackets with openChar"; position++; } else { - qDebug() << "Updating highlight brackets with closeChar"; + qCDebug(appLog) << "Updating highlight brackets with closeChar"; cursor.setPosition(position - 1); } begin = openChar; end = closeChar; } else { - qDebug() << "Updating highlight brackets with backward"; + qCDebug(appLog) << "Updating highlight brackets with backward"; if (doc->characterAt(position) == closeChar) { - qDebug() << "Updating highlight brackets with closeChar"; + qCDebug(appLog) << "Updating highlight brackets with closeChar"; cursor.setPosition(position + 1); position -= 1; } else { - qDebug() << "Updating highlight brackets with openChar"; + qCDebug(appLog) << "Updating highlight brackets with openChar"; position -= 2; } @@ -4143,20 +4144,20 @@ void TextEdit::updateHighlightBrackets(const QChar &openChar, const QChar &close QChar c; while (!(c = doc->characterAt(position)).isNull()) { if (inCodeString) { - qDebug() << "Updating highlight brackets with in code string"; + qCDebug(appLog) << "Updating highlight brackets with in code string"; // 判断 " 是否存在转义字符,若不存在,则退出字符串模式 // 注意回退(!forward)模式下,position = 0,characterAt(position - 1) 将返回空字符,同样符合判断,不会触发越界访问 if ('"' == c && '\\' != doc->characterAt(position - 1)) { - qDebug() << "Updating highlight brackets with not in code string"; + qCDebug(appLog) << "Updating highlight brackets with not in code string"; inCodeString = false; } } else { - qDebug() << "Updating highlight brackets with not in code string"; + qCDebug(appLog) << "Updating highlight brackets with not in code string"; if (c == begin) { - qDebug() << "Updating highlight brackets with begin"; + qCDebug(appLog) << "Updating highlight brackets with begin"; braceDepth++; } else if (c == end) { - qDebug() << "Updating highlight brackets with end"; + qCDebug(appLog) << "Updating highlight brackets with end"; braceDepth--; if (!braceDepth) { @@ -4166,7 +4167,7 @@ void TextEdit::updateHighlightBrackets(const QChar &openChar, const QChar &close break; } } else if ('"' == c) { - qDebug() << "Updating highlight brackets with \""; + qCDebug(appLog) << "Updating highlight brackets with \""; inCodeString = true; } } @@ -4176,7 +4177,7 @@ void TextEdit::updateHighlightBrackets(const QChar &openChar, const QChar &close // cannot find the end bracket to not need to highlight. if (!bracketEndCursor.isNull()) { - qDebug() << "Updating highlight brackets with not null"; + qCDebug(appLog) << "Updating highlight brackets with not null"; m_beginBracketSelection.cursor = bracketBeginCursor; m_beginBracketSelection.format = m_bracketMatchFormat; @@ -4184,15 +4185,15 @@ void TextEdit::updateHighlightBrackets(const QChar &openChar, const QChar &close m_endBracketSelection.format = m_bracketMatchFormat; } } - qDebug() << "Updating highlight brackets completed"; + qCDebug(appLog) << "Updating highlight brackets completed"; } int TextEdit::getFirstVisibleBlockId() const { - qDebug() << "Getting first visible block id"; + qCDebug(appLog) << "Getting first visible block id"; QTextCursor cur = QTextCursor(this->document()); if (cur.isNull()) { - qDebug() << "Getting first visible block id with null, return 0"; + qCDebug(appLog) << "Getting first visible block id with null, return 0"; return 0; } cur.movePosition(QTextCursor::Start); @@ -4201,11 +4202,11 @@ int TextEdit::getFirstVisibleBlockId() const QTextBlock startBlock, endBlock; if (verticalScrollBar()->maximum() > height()) { - qDebug() << "Getting first visible block id with maximum > height"; + qCDebug(appLog) << "Getting first visible block id with maximum > height"; startPoint = QPointF(0, height() / verticalScrollBar()->maximum() * verticalScrollBar()->value()).toPoint(); //endPoint = QPointF(0,height() + height()/verticalScrollBar()->maximum()*verticalScrollBar()->value()).toPoint(); } else if (verticalScrollBar()->maximum() > 0 && verticalScrollBar()->maximum() <= height()) { - qDebug() << "Getting first visible block id with maximum > 0 and maximum <= height"; + qCDebug(appLog) << "Getting first visible block id with maximum > 0 and maximum <= height"; startPoint = QPointF(0, verticalScrollBar()->value() / verticalScrollBar()->maximum()).toPoint(); } @@ -4213,47 +4214,47 @@ int TextEdit::getFirstVisibleBlockId() const startBlock = document()->findBlock(cur.position()); cur.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); if (startBlock.text() != cur.selection().toPlainText()) { - qDebug() << "Getting first visible block id with text not equal to selection"; + qCDebug(appLog) << "Getting first visible block id with text not equal to selection"; return startBlock.blockNumber() + 1; } - qDebug() << "Getting first visible block id completed"; + qCDebug(appLog) << "Getting first visible block id completed"; return startBlock.blockNumber(); } void TextEdit::setLeftAreaUpdateState(TextEdit::UpdateOperationType statevalue) { - qDebug() << "Setting left area update state"; + qCDebug(appLog) << "Setting left area update state"; if (statevalue != m_LeftAreaUpdateState) { - qDebug() << "Setting left area update state with statevalue not equal to m_LeftAreaUpdateState"; + qCDebug(appLog) << "Setting left area update state with statevalue not equal to m_LeftAreaUpdateState"; m_LeftAreaUpdateState = statevalue; // 当文件读取完成时,手动触发更新界面 if (TextEdit::FileOpenEnd == m_LeftAreaUpdateState) { - qDebug() << "Setting left area update state with FileOpenEnd"; + qCDebug(appLog) << "Setting left area update state with FileOpenEnd"; m_pLeftAreaWidget->updateAll(); } } - qDebug() << "Setting left area update state completed"; + qCDebug(appLog) << "Setting left area update state completed"; } TextEdit::UpdateOperationType TextEdit::getLeftAreaUpdateState() { - qDebug() << "Getting left area update state"; + qCDebug(appLog) << "Getting left area update state"; return m_LeftAreaUpdateState; } //line 开始处理的行号 isvisable是否折叠 iInitnum左括号默认开始计算的数量 isFirstLine是否是第一行,因为第一行默认不折叠 bool TextEdit::getNeedControlLine(int line, bool isVisable) { - qDebug() << "Processing code fold control for line" << line << "visibility:" << (isVisable ? "show" : "hide"); + qCDebug(appLog) << "Processing code fold control for line" << line << "visibility:" << (isVisable ? "show" : "hide"); // 查询折叠区域文本块范围 QTextBlock beginBlock, endBlock, curBlock; bool bFoundBrace = findFoldBlock(line, beginBlock, endBlock, curBlock); - qDebug() << "Found matching brace:" << bFoundBrace; + qCDebug(appLog) << "Found matching brace:" << bFoundBrace; //没有找到右括弧折叠左括弧后面所有行 if (!bFoundBrace) { - qDebug() << "No matching closing brace found, folding all subsequent lines"; + qCDebug(appLog) << "No matching closing brace found, folding all subsequent lines"; //遍历最后右括弧文本块 设置块隐藏或显示 int blockCount = 0; while (beginBlock.isValid()) { @@ -4262,14 +4263,14 @@ bool TextEdit::getNeedControlLine(int line, bool isVisable) beginBlock = beginBlock.next(); blockCount++; } - qDebug() << "Processed" << blockCount << "blocks with visibility:" << (isVisable ? "shown" : "hidden"); + qCDebug(appLog) << "Processed" << blockCount << "blocks with visibility:" << (isVisable ? "shown" : "hidden"); return true; //没有找到匹配左右括弧 //如果左右"{" "}"在同一行不折叠 } else if (!bFoundBrace || endBlock == curBlock) { - qDebug() << "Braces on same line or no proper match found, skipping fold operation"; + qCDebug(appLog) << "Braces on same line or no proper match found, skipping fold operation"; return false; } else { - qDebug() << "Processing fold region from line" << line << "to line" << endBlock.blockNumber(); + qCDebug(appLog) << "Processing fold region from line" << line << "to line" << endBlock.blockNumber(); //遍历最后右括弧文本块 设置块隐藏或显示 int blockCount = 0; while (beginBlock != endBlock && beginBlock.isValid()) { @@ -4288,7 +4289,7 @@ bool TextEdit::getNeedControlLine(int line, bool isVisable) viewport()->adjustSize(); } - qDebug() << "Fold operation completed, processed" << blockCount << "blocks with visibility:" << (isVisable ? "shown" : "hidden"); + qCDebug(appLog) << "Fold operation completed, processed" << blockCount << "blocks with visibility:" << (isVisable ? "shown" : "hidden"); return true; } } @@ -4297,11 +4298,11 @@ bool TextEdit::event(QEvent *event) { switch (event->type()) { case QEvent::Gesture: - qDebug() << "Event gesture"; + qCDebug(appLog) << "Event gesture"; gestureEvent(static_cast(event)); break; case QEvent::PaletteChange: - qDebug() << "Event palette change"; + qCDebug(appLog) << "Event palette change"; // 调色板更新时更新选取高亮颜色 onAppPaletteChanged(); break; @@ -4314,134 +4315,134 @@ bool TextEdit::event(QEvent *event) bool TextEdit::gestureEvent(QGestureEvent *event) { - qDebug() << "Gesture event"; + qCDebug(appLog) << "Gesture event"; if (QGesture *tap = event->gesture(Qt::TapGesture)) { - qDebug() << "Gesture tap"; + qCDebug(appLog) << "Gesture tap"; tapGestureTriggered(static_cast(tap)); } if (QGesture *tapAndHold = event->gesture(Qt::TapAndHoldGesture)) { - qDebug() << "Gesture tap and hold"; + qCDebug(appLog) << "Gesture tap and hold"; tapAndHoldGestureTriggered(static_cast(tapAndHold)); } if (QGesture *pan = event->gesture(Qt::PanGesture)) { - qDebug() << "Gesture pan"; + qCDebug(appLog) << "Gesture pan"; panTriggered(static_cast(pan)); } if (QGesture *pinch = event->gesture(Qt::PinchGesture)) { - qDebug() << "Gesture pinch"; + qCDebug(appLog) << "Gesture pinch"; pinchTriggered(static_cast(pinch)); } if (QGesture *swipe = event->gesture(Qt::SwipeGesture)) { - qDebug() << "Gesture swipe"; + qCDebug(appLog) << "Gesture swipe"; swipeTriggered(static_cast(swipe)); } - qDebug() << "Gesture event completed, return true"; + qCDebug(appLog) << "Gesture event completed, return true"; return true; } void TextEdit::tapGestureTriggered(QTapGesture *tap) { - qDebug() << "Tap gesture triggered"; + qCDebug(appLog) << "Tap gesture triggered"; //单指点击函数 switch (tap->state()) { case Qt::GestureStarted: { m_gestureAction = GA_tap; m_tapBeginTime = QDateTime::currentDateTime().toMSecsSinceEpoch(); - qDebug() << "Tap gesture triggered with started"; + qCDebug(appLog) << "Tap gesture triggered with started"; break; } case Qt::GestureUpdated: { m_gestureAction = GA_slide; - qDebug() << "Tap gesture triggered with updated"; + qCDebug(appLog) << "Tap gesture triggered with updated"; break; } case Qt::GestureCanceled: { - qDebug() << "Tap gesture triggered with canceled"; + qCDebug(appLog) << "Tap gesture triggered with canceled"; //根据时间长短区分轻触滑动 qint64 timeSpace = QDateTime::currentDateTime().toMSecsSinceEpoch() - m_tapBeginTime; if (timeSpace < TAP_MOVE_DELAY || m_slideContinueX || m_slideContinueY) { m_slideContinueX = false; m_slideContinueY = false; m_gestureAction = GA_slide; - qDebug() << "slide start" << timeSpace; + qCDebug(appLog) << "slide start" << timeSpace; } else { - qDebug() << "null start" << timeSpace; + qCDebug(appLog) << "null start" << timeSpace; m_gestureAction = GA_null; } break; } case Qt::GestureFinished: { - qDebug() << "Tap gesture triggered with finished"; + qCDebug(appLog) << "Tap gesture triggered with finished"; m_gestureAction = GA_null; break; } default: { - qDebug() << "Tap gesture triggered with default"; + qCDebug(appLog) << "Tap gesture triggered with default"; Q_ASSERT(false); break; } } - qDebug() << "Tap gesture triggered completed"; + qCDebug(appLog) << "Tap gesture triggered completed"; } void TextEdit::tapAndHoldGestureTriggered(QTapAndHoldGesture *tapAndHold) { - qDebug() << "Tap and hold gesture triggered"; + qCDebug(appLog) << "Tap and hold gesture triggered"; //单指长按 switch (tapAndHold->state()) { case Qt::GestureStarted: m_gestureAction = GA_hold; - qDebug() << "Tap and hold gesture triggered with started"; + qCDebug(appLog) << "Tap and hold gesture triggered with started"; break; case Qt::GestureUpdated: - qDebug() << "Tap and hold gesture triggered with updated"; + qCDebug(appLog) << "Tap and hold gesture triggered with updated"; break; case Qt::GestureCanceled: - qDebug() << "Tap and hold gesture triggered with canceled"; + qCDebug(appLog) << "Tap and hold gesture triggered with canceled"; break; case Qt::GestureFinished: - qDebug() << "Tap and hold gesture triggered with finished"; + qCDebug(appLog) << "Tap and hold gesture triggered with finished"; m_gestureAction = GA_null; break; default: break; } - qDebug() << "Tap and hold gesture triggered completed"; + qCDebug(appLog) << "Tap and hold gesture triggered completed"; } void TextEdit::panTriggered(QPanGesture *pan) { - qDebug() << "Pan gesture triggered"; + qCDebug(appLog) << "Pan gesture triggered"; //两指平移 switch (pan->state()) { case Qt::GestureStarted: m_gestureAction = GA_pan; - qDebug() << "Pan gesture triggered with started"; + qCDebug(appLog) << "Pan gesture triggered with started"; break; case Qt::GestureUpdated: - qDebug() << "Pan gesture triggered with updated"; + qCDebug(appLog) << "Pan gesture triggered with updated"; break; case Qt::GestureCanceled: - qDebug() << "Pan gesture triggered with canceled"; + qCDebug(appLog) << "Pan gesture triggered with canceled"; break; case Qt::GestureFinished: m_gestureAction = GA_null; - qDebug() << "Pan gesture triggered with finished"; + qCDebug(appLog) << "Pan gesture triggered with finished"; break; default: - qDebug() << "Pan gesture triggered with default"; + qCDebug(appLog) << "Pan gesture triggered with default"; break; } - qDebug() << "Pan gesture triggered completed"; + qCDebug(appLog) << "Pan gesture triggered completed"; } void TextEdit::pinchTriggered(QPinchGesture *pinch) { - qDebug() << "Pinch gesture triggered"; + qCDebug(appLog) << "Pinch gesture triggered"; //两指拉伸 -----缩放or放大 switch (pinch->state()) { case Qt::GestureStarted: { - qDebug() << "Pinch gesture triggered with started"; + qCDebug(appLog) << "Pinch gesture triggered with started"; m_gestureAction = GA_pinch; if (static_cast(m_scaleFactor) != m_fontSize) { m_scaleFactor = m_fontSize; @@ -4449,7 +4450,7 @@ void TextEdit::pinchTriggered(QPinchGesture *pinch) break; } case Qt::GestureUpdated: { - qDebug() << "Pinch gesture triggered with updated"; + qCDebug(appLog) << "Pinch gesture triggered with updated"; QPinchGesture::ChangeFlags changeFlags = pinch->changeFlags(); if (changeFlags & QPinchGesture::ScaleFactorChanged) { m_currentStepScaleFactor = pinch->totalScaleFactor(); @@ -4457,18 +4458,18 @@ void TextEdit::pinchTriggered(QPinchGesture *pinch) break; } case Qt::GestureCanceled: { - qDebug() << "Pinch gesture triggered with canceled"; + qCDebug(appLog) << "Pinch gesture triggered with canceled"; break; } case Qt::GestureFinished: { - qDebug() << "Pinch gesture triggered with finished"; + qCDebug(appLog) << "Pinch gesture triggered with finished"; m_gestureAction = GA_null; m_scaleFactor *= m_currentStepScaleFactor; m_currentStepScaleFactor = 1; break; } default: { - qDebug() << "Pinch gesture triggered with default"; + qCDebug(appLog) << "Pinch gesture triggered with default"; break; } }//switch @@ -4483,12 +4484,12 @@ void TextEdit::pinchTriggered(QPinchGesture *pinch) setFontSize(size); //同步设置界面字体栏数值 qobject_cast(this->window())->changeSettingDialogComboxFontNumber(size); - qDebug() << "Pinch gesture triggered completed, size:" << size; + qCDebug(appLog) << "Pinch gesture triggered completed, size:" << size; } void TextEdit::swipeTriggered(QSwipeGesture *swipe) { - qDebug() << "Swipe gesture triggered"; + qCDebug(appLog) << "Swipe gesture triggered"; //三指滑动 // switch (swipe->state()) { // case Qt::GestureStarted: @@ -4511,29 +4512,29 @@ void TextEdit::swipeTriggered(QSwipeGesture *swipe) void TextEdit::slideGestureY(qreal diff) { - qDebug() << "Slide gesture y, diff:" << diff; + qCDebug(appLog) << "Slide gesture y, diff:" << diff; static qreal delta = 0.0; int step = static_cast(diff + delta); delta = diff + delta - step; verticalScrollBar()->setValue(verticalScrollBar()->value() + step); - qDebug() << "Slide gesture y, verticalScrollBar()->value():" << verticalScrollBar()->value(); + qCDebug(appLog) << "Slide gesture y, verticalScrollBar()->value():" << verticalScrollBar()->value(); } void TextEdit::slideGestureX(qreal diff) { - qDebug() << "Slide gesture x, diff:" << diff; + qCDebug(appLog) << "Slide gesture x, diff:" << diff; static qreal delta = 0.0; int step = static_cast(diff + delta); delta = diff + delta - step; horizontalScrollBar()->setValue(horizontalScrollBar()->value() + step * 30); - qDebug() << "Slide gesture x, horizontalScrollBar()->value():" << horizontalScrollBar()->value(); + qCDebug(appLog) << "Slide gesture x, horizontalScrollBar()->value():" << horizontalScrollBar()->value(); } void TextEdit::setTheme(const QString &path) { - qDebug() << "Set theme, path:" << path; + qCDebug(appLog) << "Set theme, path:" << path; QVariantMap jsonMap = Utils::getThemeMapFromPath(path); QVariantMap textStylesMap = jsonMap["text-styles"].toMap(); QString themeCurrentLineColor = jsonMap["editor-colors"].toMap()["current-line"].toString(); @@ -4575,12 +4576,12 @@ void TextEdit::setTheme(const QString &path) updateHighlightLineSelection(); renderAllSelections(); - qDebug() << "Set theme completed"; + qCDebug(appLog) << "Set theme completed"; } void TextEdit::removeHighlightWordUnderCursor() { - qDebug() << "Remove highlight word under cursor"; + qCDebug(appLog) << "Remove highlight word under cursor"; //m_highlightWordCacheCursor = m_wordUnderCursorSelection.cursor; QTextEdit::ExtraSelection selection; //m_wordUnderCursorSelection = selection; @@ -4588,12 +4589,12 @@ void TextEdit::removeHighlightWordUnderCursor() renderAllSelections(); m_nBookMarkHoverLine = -1; m_pLeftAreaWidget->m_pBookMarkArea->update(); - qDebug() << "Remove highlight word under cursor completed"; + qCDebug(appLog) << "Remove highlight word under cursor completed"; } void TextEdit::setSettings(Settings *keySettings) { - qDebug() << "Set settings, keySettings:" << keySettings; + qCDebug(appLog) << "Set settings, keySettings:" << keySettings; m_settings = keySettings; } @@ -4603,15 +4604,15 @@ void TextEdit::setSettings(Settings *keySettings) */ void TextEdit::copySelectedText(bool ignoreCheck) { - qDebug() << "Copy selected text, ignoreCheck:" << ignoreCheck; + qCDebug(appLog) << "Copy selected text, ignoreCheck:" << ignoreCheck; // 添加权限判断是否允许拷贝,剪切;防止后续可能调用接口,冗余处理 if (!ignoreCheck && !Utils::enableClipCopy(getFilePath())) { - qDebug() << "Copy selected text, ignoreCheck is false and enableClipCopy is false"; + qCDebug(appLog) << "Copy selected text, ignoreCheck is false and enableClipCopy is false"; return; } if (m_bIsAltMod && !m_altModSelections.isEmpty()) { - qDebug() << "Copy selected text, m_bIsAltMod is true and m_altModSelections is not empty"; + qCDebug(appLog) << "Copy selected text, m_bIsAltMod is true and m_altModSelections is not empty"; QString data; for (auto sel : m_altModSelections) { data.append(sel.cursor.selectedText()); @@ -4619,19 +4620,19 @@ void TextEdit::copySelectedText(bool ignoreCheck) QClipboard *clipboard = QApplication::clipboard(); //获取系统剪贴板指针 clipboard->setText(data); } else { - qDebug() << "Copy selected text, m_bIsAltMod is false or m_altModSelections is empty"; + qCDebug(appLog) << "Copy selected text, m_bIsAltMod is false or m_altModSelections is empty"; QClipboard *clipboard = QApplication::clipboard(); //获取系统剪贴板指针 if (textCursor().hasSelection()) { clipboard->setText(textCursor().selection().toPlainText()); - qDebug() << "Copy selected text, textCursor().hasSelection() is true"; + qCDebug(appLog) << "Copy selected text, textCursor().hasSelection() is true"; tryUnsetMark(); } else { - qDebug() << "Copy selected text, textCursor().hasSelection() is false"; + qCDebug(appLog) << "Copy selected text, textCursor().hasSelection() is false"; clipboard->setText(m_highlightWordCacheCursor.selectedText()); } } tryUnsetMark(); - qDebug() << "Copy selected text completed"; + qCDebug(appLog) << "Copy selected text completed"; } /** @@ -4640,10 +4641,10 @@ void TextEdit::copySelectedText(bool ignoreCheck) */ void TextEdit::cutSelectedText(bool ignoreCheck) { - qDebug() << "Cut selected text, ignoreCheck:" << ignoreCheck; + qCDebug(appLog) << "Cut selected text, ignoreCheck:" << ignoreCheck; // 添加权限判断是否允许拷贝,剪切;防止后续可能调用接口,冗余处理 if (!ignoreCheck && !Utils::enableClipCopy(getFilePath())) { - qDebug() << "Cut selected text, ignoreCheck is false and enableClipCopy is false"; + qCDebug(appLog) << "Cut selected text, ignoreCheck is false and enableClipCopy is false"; return; } @@ -4655,64 +4656,64 @@ void TextEdit::cutSelectedText(bool ignoreCheck) setTextCursor(cursor); unsetMark(); - qDebug() << "Cut selected text completed"; + qCDebug(appLog) << "Cut selected text completed"; } void TextEdit::pasteText() { - qDebug() << "Paste text"; + qCDebug(appLog) << "Paste text"; QPlainTextEdit::paste(); unsetMark(); - qDebug() << "Paste text unsetMark completed"; + qCDebug(appLog) << "Paste text unsetMark completed"; } void TextEdit::setMark() { - qDebug() << "Set mark"; + qCDebug(appLog) << "Set mark"; bool currentMark = m_cursorMark; bool markCursorChanged = false; if (m_cursorMark) { - qDebug() << "Set mark, m_cursorMark is true"; + qCDebug(appLog) << "Set mark, m_cursorMark is true"; if (textCursor().hasSelection()) { - qDebug() << "Set mark, textCursor().hasSelection() is true"; + qCDebug(appLog) << "Set mark, textCursor().hasSelection() is true"; markCursorChanged = true; QTextCursor cursor = textCursor(); cursor.clearSelection(); setTextCursor(cursor); } else { - qDebug() << "Set mark, textCursor().hasSelection() is false"; + qCDebug(appLog) << "Set mark, textCursor().hasSelection() is false"; m_cursorMark = false; } } else { - qDebug() << "Set mark, m_cursorMark is false"; + qCDebug(appLog) << "Set mark, m_cursorMark is false"; m_cursorMark = true; } if (m_cursorMark != currentMark || markCursorChanged) { - qDebug() << "Set mark, m_cursorMark != currentMark || markCursorChanged"; + qCDebug(appLog) << "Set mark, m_cursorMark != currentMark || markCursorChanged"; cursorMarkChanged(m_cursorMark, textCursor()); } - qDebug() << "Set mark completed"; + qCDebug(appLog) << "Set mark completed"; } void TextEdit::unsetMark() { - qDebug() << "Unset mark"; + qCDebug(appLog) << "Unset mark"; bool currentMark = m_cursorMark; m_cursorMark = false; if (m_cursorMark != currentMark) { - qDebug() << "Unset mark, m_cursorMark != currentMark"; + qCDebug(appLog) << "Unset mark, m_cursorMark != currentMark"; cursorMarkChanged(m_cursorMark, textCursor()); } - qDebug() << "Unset mark completed"; + qCDebug(appLog) << "Unset mark completed"; } bool TextEdit::tryUnsetMark() { - qDebug() << "Try unset mark"; + qCDebug(appLog) << "Try unset mark"; if (m_cursorMark) { QTextCursor cursor = textCursor(); cursor.clearSelection(); @@ -4720,22 +4721,22 @@ bool TextEdit::tryUnsetMark() unsetMark(); - qDebug() << "Try unset mark, m_cursorMark is true, return true"; + qCDebug(appLog) << "Try unset mark, m_cursorMark is true, return true"; return true; } else { - qDebug() << "Try unset mark, m_cursorMark is false"; + qCDebug(appLog) << "Try unset mark, m_cursorMark is false"; return false; } } void TextEdit::exchangeMark() { - qDebug() << "Exchange mark"; + qCDebug(appLog) << "Exchange mark"; unsetMark(); - qDebug() << "Exchange mark, textCursor().hasSelection():" << textCursor().hasSelection(); + qCDebug(appLog) << "Exchange mark, textCursor().hasSelection():" << textCursor().hasSelection(); if (textCursor().hasSelection()) { - qDebug() << "Exchange mark, textCursor().hasSelection() is true"; + qCDebug(appLog) << "Exchange mark, textCursor().hasSelection() is true"; // Record cursor and seleciton position before move cursor. int actionStartPos = textCursor().position(); int selectionStartPos = textCursor().selectionStart(); @@ -4743,33 +4744,33 @@ void TextEdit::exchangeMark() QTextCursor cursor = textCursor(); if (actionStartPos == selectionStartPos) { - qDebug() << "Exchange mark, actionStartPos == selectionStartPos"; + qCDebug(appLog) << "Exchange mark, actionStartPos == selectionStartPos"; cursor.setPosition(selectionStartPos, QTextCursor::MoveAnchor); cursor.setPosition(selectionEndPos, QTextCursor::KeepAnchor); } else { - qDebug() << "Exchange mark, actionStartPos != selectionStartPos"; + qCDebug(appLog) << "Exchange mark, actionStartPos != selectionStartPos"; cursor.setPosition(selectionEndPos, QTextCursor::MoveAnchor); cursor.setPosition(selectionStartPos, QTextCursor::KeepAnchor); } setTextCursor(cursor); } - qDebug() << "Exchange mark completed"; + qCDebug(appLog) << "Exchange mark completed"; } void TextEdit::saveMarkStatus() { - qDebug() << "Save mark status"; + qCDebug(appLog) << "Save mark status"; m_cursorMarkStatus = m_cursorMark; m_cursorMarkPosition = textCursor().anchor(); - qDebug() << "Save mark status completed"; + qCDebug(appLog) << "Save mark status completed"; } void TextEdit::restoreMarkStatus() { - qDebug() << "Restore mark status"; + qCDebug(appLog) << "Restore mark status"; if (m_cursorMarkStatus) { - qDebug() << "Restore mark status, m_cursorMarkStatus is true"; + qCDebug(appLog) << "Restore mark status, m_cursorMarkStatus is true"; QTextCursor currentCursor = textCursor(); QTextCursor cursor = textCursor(); @@ -4778,31 +4779,31 @@ void TextEdit::restoreMarkStatus() setTextCursor(cursor); } - qDebug() << "Restore mark status completed"; + qCDebug(appLog) << "Restore mark status completed"; } void TextEdit::slot_translate() { - qDebug() << "Translate"; + qCDebug(appLog) << "Translate"; auto ret = IflytekAiAssistant::instance()->textToTranslate(); if (IflytekAiAssistant::Success != ret) { - qDebug() << "Translate, ret is not Success"; + qCDebug(appLog) << "Translate, ret is not Success"; Q_EMIT popupNotify(IflytekAiAssistant::instance()->errorString(ret), true); } - qDebug() << "Translate completed"; + qCDebug(appLog) << "Translate completed"; } QString TextEdit::getWordAtCursor() { - qDebug() << "Get word at cursor"; + qCDebug(appLog) << "Get word at cursor"; // QTextDocument::characterCount() 恒 >= 1(含结尾分隔符),不能作为空文档判据; // 空文档下 toPlainText().at(0) 会触发 QString 越界断言 if (document()->isEmpty()) { - qDebug() << "Get word at cursor, document is empty"; + qCDebug(appLog) << "Get word at cursor, document is empty"; return ""; } else { - qDebug() << "Get word at cursor, characterCount() is not 0"; + qCDebug(appLog) << "Get word at cursor, characterCount() is not 0"; QTextCursor cursor = textCursor(); QChar currentChar = toPlainText().at(std::max(cursor.position() - 1, 0)); @@ -4817,20 +4818,20 @@ QString TextEdit::getWordAtCursor() } } - qDebug() << "Get word at cursor, cursor.selectedText():" << cursor.selectedText(); + qCDebug(appLog) << "Get word at cursor, cursor.selectedText():" << cursor.selectedText(); return cursor.selectedText(); } - qDebug() << "Get word at cursor completed"; + qCDebug(appLog) << "Get word at cursor completed"; } QString TextEdit::getWordAtMouse() { - qDebug() << "Get word at mouse"; + qCDebug(appLog) << "Get word at mouse"; if (!characterCount()) { - qDebug() << "Get word at mouse, characterCount() is 0"; + qCDebug(appLog) << "Get word at mouse, characterCount() is 0"; return ""; } else { - qDebug() << "Get word at mouse, characterCount() is not 0"; + qCDebug(appLog) << "Get word at mouse, characterCount() is not 0"; auto pos = mapFromGlobal(QCursor::pos()); QTextCursor cursor(cursorForPosition(pos)); @@ -4847,26 +4848,26 @@ QString TextEdit::getWordAtMouse() (pos.y() <= rect.y() + rect.height())) { cursor.select(QTextCursor::WordUnderCursor); - qDebug() << "Get word at mouse, cursor.selectedText():" << cursor.selectedText(); + qCDebug(appLog) << "Get word at mouse, cursor.selectedText():" << cursor.selectedText(); return cursor.selectedText(); } else { - qDebug() << "Get word at mouse, cursor.selectedText() is empty"; + qCDebug(appLog) << "Get word at mouse, cursor.selectedText() is empty"; return ""; } } - qDebug() << "Get word at mouse completed"; + qCDebug(appLog) << "Get word at mouse completed"; } void TextEdit::toggleReadOnlyMode(bool notNotify) { - qDebug() << "Toggle read only mode, notNotify:" << notNotify; + qCDebug(appLog) << "Toggle read only mode, notNotify:" << notNotify; if (m_readOnlyMode) { - qDebug() << "Toggle read only mode, m_readOnlyMode is true"; + qCDebug(appLog) << "Toggle read only mode, m_readOnlyMode is true"; if (m_cursorMode == Overwrite) { - qDebug() << "Toggle read only mode, m_cursorMode is Overwrite"; + qCDebug(appLog) << "Toggle read only mode, m_cursorMode is Overwrite"; emit cursorModeChanged(Overwrite); } else { - qDebug() << "Toggle read only mode, m_cursorMode is Insert"; + qCDebug(appLog) << "Toggle read only mode, m_cursorMode is Insert"; emit cursorModeChanged(Insert); } setReadOnly(false); @@ -4875,11 +4876,11 @@ void TextEdit::toggleReadOnlyMode(bool notNotify) updateHighlightLineSelection(); if (!notNotify) { - qDebug() << "Toggle read only mode, notNotify is false"; + qCDebug(appLog) << "Toggle read only mode, notNotify is false"; popupNotify(tr("Read-Only mode is off")); } } else { - qDebug() << "Toggle read only mode, m_readOnlyMode is false"; + qCDebug(appLog) << "Toggle read only mode, m_readOnlyMode is false"; m_readOnlyMode = true; setReadOnly(true); setCursorWidth(0); //隐藏光标 @@ -4887,17 +4888,17 @@ void TextEdit::toggleReadOnlyMode(bool notNotify) updateHighlightLineSelection(); if (!notNotify) { - qDebug() << "Toggle read only mode, notNotify is false"; + qCDebug(appLog) << "Toggle read only mode, notNotify is false"; popupNotify(tr("Read-Only mode is on")); } emit cursorModeChanged(Readonly); } - qDebug() << "Toggle read only mode completed"; + qCDebug(appLog) << "Toggle read only mode completed"; } void TextEdit::toggleComment(bool bValue) { - qDebug() << "Toggle comment, bValue:" << bValue; + qCDebug(appLog) << "Toggle comment, bValue:" << bValue; const auto def = m_repository.definitionForFileName(QFileInfo(m_sFilePath).fileName().toLower()); QTextCursor selectionCursor = textCursor(); selectionCursor.movePosition(QTextCursor::StartOfBlock); @@ -4906,12 +4907,12 @@ void TextEdit::toggleComment(bool bValue) // init base. bool isBlankLine = text.trimmed().isEmpty(); if (characterCount() == 0 || isBlankLine || def.filePath().isEmpty()) { - qDebug() << "Toggle comment, characterCount() is 0 or isBlankLine or def.filePath().isEmpty()"; + qCDebug(appLog) << "Toggle comment, characterCount() is 0 or isBlankLine or def.filePath().isEmpty()"; return; } if (m_readOnlyMode) { - qDebug() << "Toggle comment, m_readOnlyMode is true"; + qCDebug(appLog) << "Toggle comment, m_readOnlyMode is true"; popupNotify(tr("Read-Only mode is on")); return; } @@ -4928,40 +4929,40 @@ void TextEdit::toggleComment(bool bValue) } } if (!bHasCommnent) { - qDebug() << "Toggle comment, !bHasCommnent"; + qCDebug(appLog) << "Toggle comment, !bHasCommnent"; return; } QString name = def.name(); if (name == "Markdown") { - qDebug() << "Toggle comment, name is Markdown"; + qCDebug(appLog) << "Toggle comment, name is Markdown"; return; } if (!def.filePath().isEmpty()) { - qDebug() << "Toggle comment, def.filePath() is not empty"; + qCDebug(appLog) << "Toggle comment, def.filePath() is not empty"; if (bValue) { - qDebug() << "Toggle comment, bValue is true"; + qCDebug(appLog) << "Toggle comment, bValue is true"; setComment(); } else { - qDebug() << "Toggle comment, bValue is false"; + qCDebug(appLog) << "Toggle comment, bValue is false"; removeComment(); //unCommentSelection(); } } else { - qDebug() << "Toggle comment, def.filePath() is empty"; + qCDebug(appLog) << "Toggle comment, def.filePath() is empty"; // do not need to prompt the user. // popupNotify(tr("File does not support syntax comments")); } - qDebug() << "Toggle comment completed"; + qCDebug(appLog) << "Toggle comment completed"; } int TextEdit::getNextWordPosition(QTextCursor &cursor, QTextCursor::MoveMode moveMode) { - qDebug() << "Get next word position, cursor:" << cursor.position(); + qCDebug(appLog) << "Get next word position, cursor:" << cursor.position(); // FIXME(rekols): if is empty text, it will crash. if (!characterCount()) { - qDebug() << "Get next word position, characterCount() is 0"; + qCDebug(appLog) << "Get next word position, characterCount() is 0"; return 0; } @@ -4972,7 +4973,7 @@ int TextEdit::getNextWordPosition(QTextCursor &cursor, QTextCursor::MoveMode mov // Just to next non-space char if current char is space. if (currentChar.data()->isSpace()) { - qDebug() << "Get next word position, currentChar is space"; + qCDebug(appLog) << "Get next word position, currentChar is space"; while (copyCursor.position() < characterCount() - 1 && currentChar.data()->isSpace()) { copyCursor.movePosition(QTextCursor::NextCharacter, moveMode); currentChar = copyCursor.selection().toPlainText(); @@ -4985,21 +4986,21 @@ int TextEdit::getNextWordPosition(QTextCursor &cursor, QTextCursor::MoveMode mov } // Just to next word-separator char. else { - qDebug() << "Get next word position, currentChar is not space"; + qCDebug(appLog) << "Get next word position, currentChar is not space"; while (copyCursor.position() < characterCount() - 1 && !atWordSeparator(copyCursor.position())) { copyCursor.movePosition(QTextCursor::NextCharacter, moveMode); } } - qDebug() << "Get next word position, copyCursor.position():" << copyCursor.position(); + qCDebug(appLog) << "Get next word position, copyCursor.position():" << copyCursor.position(); return copyCursor.position(); } int TextEdit::getPrevWordPosition(QTextCursor cursor, QTextCursor::MoveMode moveMode) { - qDebug() << "Get prev word position, cursor:" << cursor.position(); + qCDebug(appLog) << "Get prev word position, cursor:" << cursor.position(); if (!characterCount()) { - qDebug() << "Get prev word position, characterCount() is 0"; + qCDebug(appLog) << "Get prev word position, characterCount() is 0"; return 0; } @@ -5010,7 +5011,7 @@ int TextEdit::getPrevWordPosition(QTextCursor cursor, QTextCursor::MoveMode move // Just to next non-space char if current char is space. if (currentChar.data()->isSpace()) { - qDebug() << "Get prev word position, currentChar is space"; + qCDebug(appLog) << "Get prev word position, currentChar is space"; while (copyCursor.position() > 0 && currentChar.data()->isSpace()) { copyCursor.movePosition(QTextCursor::PreviousCharacter, moveMode); currentChar = copyCursor.selection().toPlainText(); @@ -5018,64 +5019,64 @@ int TextEdit::getPrevWordPosition(QTextCursor cursor, QTextCursor::MoveMode move } // Just to next word-separator char. else { - qDebug() << "Get prev word position, currentChar is not space"; + qCDebug(appLog) << "Get prev word position, currentChar is not space"; while (copyCursor.position() > 0 && !atWordSeparator(copyCursor.position())) { copyCursor.movePosition(QTextCursor::PreviousCharacter, moveMode); } } - qDebug() << "Get prev word position, copyCursor.position():" << copyCursor.position(); + qCDebug(appLog) << "Get prev word position, copyCursor.position():" << copyCursor.position(); return copyCursor.position(); } bool TextEdit::atWordSeparator(int position) { - qDebug() << "At word separator, position:" << position; + qCDebug(appLog) << "At word separator, position:" << position; QTextCursor copyCursor = textCursor(); copyCursor.setPosition(position, QTextCursor::MoveAnchor); copyCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); QString currentChar = copyCursor.selection().toPlainText(); - qDebug() << "At word separator, currentChar:" << currentChar; + qCDebug(appLog) << "At word separator, currentChar:" << currentChar; return m_wordSepartors.contains(currentChar); } void TextEdit::showCursorBlink() { - qDebug() << "Show cursor blink"; + qCDebug(appLog) << "Show cursor blink"; // -1 表示恢复Qt的默认值 QApplication::setCursorFlashTime(-1); } void TextEdit::hideCursorBlink() { - qDebug() << "Hide cursor blink"; + qCDebug(appLog) << "Hide cursor blink"; QApplication::setCursorFlashTime(0); } void TextEdit::setReadOnlyPermission(bool permission) { - qDebug() << "Set read only permission, permission:" << permission; + qCDebug(appLog) << "Set read only permission, permission:" << permission; m_bReadOnlyPermission = permission; //true为不可读 if (permission) { - qDebug() << "Set read only permission, permission is true"; + qCDebug(appLog) << "Set read only permission, permission is true"; m_Permission2 = true; setReadOnly(true); emit cursorModeChanged(Readonly); } else { - qDebug() << "Set read only permission, permission is false"; + qCDebug(appLog) << "Set read only permission, permission is false"; m_Permission = false; if (!m_readOnlyMode) { - qDebug() << "Set read only permission, m_readOnlyMode is false"; + qCDebug(appLog) << "Set read only permission, m_readOnlyMode is false"; setReadOnly(false); //emit cursorModeChanged(Insert); } else { - qDebug() << "Set read only permission, m_readOnlyMode is true"; + qCDebug(appLog) << "Set read only permission, m_readOnlyMode is true"; setReadOnly(true); emit cursorModeChanged(Readonly); } } SendtoggleReadOnlyMode(); - qDebug() << "Set read only permission completed"; + qCDebug(appLog) << "Set read only permission completed"; } // 右键菜单「视图模式」入口(§8.1):由 EditWrapper 在 viewModeChanged/markdownAvailabilityChanged 时回写 @@ -5104,44 +5105,44 @@ void TextEdit::updateViewModeActions(ViewMode mode, bool isMarkdown) void TextEdit::SendtoggleReadmessage() { - qDebug() << "Send toggle read only message"; + qCDebug(appLog) << "Send toggle read only message"; if (!m_bReadOnlyPermission) { - qDebug() << "Send toggle read only message, m_bReadOnlyPermission is false"; + qCDebug(appLog) << "Send toggle read only message, m_bReadOnlyPermission is false"; if (m_cursorMode == Overwrite) { - qDebug() << "Send toggle read only message, m_cursorMode is Overwrite"; + qCDebug(appLog) << "Send toggle read only message, m_cursorMode is Overwrite"; emit cursorModeChanged(Overwrite); } else { - qDebug() << "Send toggle read only message, m_cursorMode is Insert"; + qCDebug(appLog) << "Send toggle read only message, m_cursorMode is Insert"; emit cursorModeChanged(Insert); } setReadOnly(false); setCursorWidth(1); updateHighlightLineSelection(); } else { - qDebug() << "Send toggle read only message, m_bReadOnlyPermission is true"; + qCDebug(appLog) << "Send toggle read only message, m_bReadOnlyPermission is true"; setReadOnly(true); setCursorWidth(0); //隐藏光标 document()->clearUndoRedoStacks(); updateHighlightLineSelection(); emit cursorModeChanged(Readonly); } - qDebug() << "Send toggle read only message completed"; + qCDebug(appLog) << "Send toggle read only message completed"; } bool TextEdit::isAbleOperation(Utils::OperationType iOperationType) { - qDebug() << "Is able operation, iOperationType:" << iOperationType; + qCDebug(appLog) << "Is able operation, iOperationType:" << iOperationType; bool bRet = true; qlonglong operationDataSize = 0; qlonglong currentDocSize = document()->characterCount(); if (iOperationType == Utils::CopyOperation) { - qDebug() << "Is able operation, iOperationType is CopyOperation"; + qCDebug(appLog) << "Is able operation, iOperationType is CopyOperation"; if (m_isSelectAll) { - qDebug() << "Is able operation, m_isSelectAll is true"; + qCDebug(appLog) << "Is able operation, m_isSelectAll is true"; operationDataSize = currentDocSize; } else if (m_bIsAltMod && !m_altModSelections.isEmpty()) { - qDebug() << "Is able operation, m_bIsAltMod is true and m_altModSelections is not empty"; + qCDebug(appLog) << "Is able operation, m_bIsAltMod is true and m_altModSelections is not empty"; for (auto it = m_altModSelections.begin(); it != m_altModSelections.end(); it++) { auto &itCursor = (*it).cursor; operationDataSize += (itCursor.selectionEnd() - itCursor.selectionStart()); @@ -5149,86 +5150,86 @@ bool TextEdit::isAbleOperation(Utils::OperationType iOperationType) operationDataSize++; } } else if (textCursor().hasSelection()) { - qDebug() << "Is able operation, textCursor().hasSelection() is true"; + qCDebug(appLog) << "Is able operation, textCursor().hasSelection() is true"; operationDataSize = textCursor().selectionEnd() - textCursor().selectionStart(); } - qDebug() << "Is able operation, operationDataSize:" << operationDataSize; + qCDebug(appLog) << "Is able operation, operationDataSize:" << operationDataSize; bRet = Utils::isMemorySufficientForOperation(iOperationType, operationDataSize, currentDocSize); - qDebug() << "Is able operation, bRet:" << bRet; + qCDebug(appLog) << "Is able operation, bRet:" << bRet; } else if (iOperationType == Utils::PasteOperation) { - qDebug() << "Is able operation, iOperationType is PasteOperation"; + qCDebug(appLog) << "Is able operation, iOperationType is PasteOperation"; const QClipboard *clipboard = QApplication::clipboard(); QString strClipboardText = clipboard->text(); operationDataSize = strClipboardText.size(); - qDebug() << "Is able operation, operationDataSize:" << operationDataSize; + qCDebug(appLog) << "Is able operation, operationDataSize:" << operationDataSize; bRet = Utils::isMemorySufficientForOperation(iOperationType, operationDataSize, currentDocSize); - qDebug() << "Is able operation, bRet:" << bRet; + qCDebug(appLog) << "Is able operation, bRet:" << bRet; } - qDebug() << "Is able operation completed"; + qCDebug(appLog) << "Is able operation completed"; return bRet; } void TextEdit::SendtoggleReadOnlyMode() { - qDebug() << "Send toggle read only mode"; + qCDebug(appLog) << "Send toggle read only mode"; if (m_bReadOnlyPermission && !m_Permission) { - qDebug() << "Send toggle read only mode, m_bReadOnlyPermission is true and m_Permission is false"; + qCDebug(appLog) << "Send toggle read only mode, m_bReadOnlyPermission is true and m_Permission is false"; m_Permission = m_bReadOnlyPermission; SendtoggleReadmessage(); } else if (m_Permission2 && !m_bReadOnlyPermission) { - qDebug() << "Send toggle read only mode, m_Permission2 is true and m_bReadOnlyPermission is false"; + qCDebug(appLog) << "Send toggle read only mode, m_Permission2 is true and m_bReadOnlyPermission is false"; m_Permission2 = m_bReadOnlyPermission; SendtoggleReadmessage(); } - qDebug() << "Send toggle read only mode completed"; + qCDebug(appLog) << "Send toggle read only mode completed"; } bool TextEdit::getReadOnlyPermission() { - qDebug() << "Get read only permission"; + qCDebug(appLog) << "Get read only permission"; return m_bReadOnlyPermission; } bool TextEdit::getReadOnlyMode() { - qDebug() << "Get read only mode"; + qCDebug(appLog) << "Get read only mode"; return m_readOnlyMode; } void TextEdit::setReadOnlyState(bool readOnly) { - qDebug() << "Set read only state:" << readOnly; + qCDebug(appLog) << "Set read only state:" << readOnly; m_readOnlyMode = readOnly; setReadOnly(readOnly); } void TextEdit::hideRightMenu() { - qDebug() << "Hide right menu"; + qCDebug(appLog) << "Hide right menu"; //arm平台全屏然后恢复窗口,右键菜单不会消失,所以加了这个函数 if (m_rightMenu) { - qDebug() << "Send toggle read only mode, m_rightMenu is not null"; + qCDebug(appLog) << "Send toggle read only mode, m_rightMenu is not null"; m_rightMenu->hide(); } - qDebug() << "Hide right menu completed"; + qCDebug(appLog) << "Hide right menu completed"; } void TextEdit::bookMarkAreaPaintEvent(QPaintEvent *event) { - qDebug() << "Book mark area paint event"; + qCDebug(appLog) << "Book mark area paint event"; BookMarkWidget *bookMarkArea = m_pLeftAreaWidget->m_pBookMarkArea; QPainter painter(bookMarkArea); QColor lineNumberAreaBackgroundColor; if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::ColorType::DarkType) { - qDebug() << "Book mark area paint event, DGuiApplicationHelper::ColorType::DarkType"; + qCDebug(appLog) << "Book mark area paint event, DGuiApplicationHelper::ColorType::DarkType"; lineNumberAreaBackgroundColor = palette().brightText().color(); lineNumberAreaBackgroundColor.setAlphaF(0.06); m_lineNumbersColor.setAlphaF(0.2); } else { - qDebug() << "Book mark area paint event, DGuiApplicationHelper::ColorType::LightType"; + qCDebug(appLog) << "Book mark area paint event, DGuiApplicationHelper::ColorType::LightType"; lineNumberAreaBackgroundColor = palette().brightText().color(); lineNumberAreaBackgroundColor.setAlphaF(0.03); m_lineNumbersColor.setAlphaF(0.3); @@ -5241,10 +5242,10 @@ void TextEdit::bookMarkAreaPaintEvent(QPaintEvent *event) bool bIsContains = false; if (!m_listBookmark.contains(m_nBookMarkHoverLine) && m_nBookMarkHoverLine != -1 && m_nBookMarkHoverLine <= blockCount()) { - qDebug() << "Book mark area paint event, m_listBookmark does not contain m_nBookMarkHoverLine"; + qCDebug(appLog) << "Book mark area paint event, m_listBookmark does not contain m_nBookMarkHoverLine"; list << m_nBookMarkHoverLine; } else { - qDebug() << "Book mark area paint event, m_listBookmark contains m_nBookMarkHoverLine"; + qCDebug(appLog) << "Book mark area paint event, m_listBookmark contains m_nBookMarkHoverLine"; bIsContains = true; } @@ -5253,7 +5254,7 @@ void TextEdit::bookMarkAreaPaintEvent(QPaintEvent *event) QTextCursor cur = textCursor(); cur.setPosition(lineBlock.position(), QTextCursor::MoveAnchor); if (line == m_nBookMarkHoverLine && !bIsContains) { - qDebug() << "Book mark area paint event, line == m_nBookMarkHoverLine and !bIsContains"; + qCDebug(appLog) << "Book mark area paint event, line == m_nBookMarkHoverLine and !bIsContains"; if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::ColorType::DarkType) { pixmapPath = ":/images/like_hover_dark.svg"; image = QImage(":/images/like_hover_dark.svg"); @@ -5262,16 +5263,16 @@ void TextEdit::bookMarkAreaPaintEvent(QPaintEvent *event) pixmapPath = ":/images/like_hover_light.svg"; } } else { - qDebug() << "Book mark area paint event, line != m_nBookMarkHoverLine or bIsContains"; + qCDebug(appLog) << "Book mark area paint event, line != m_nBookMarkHoverLine or bIsContains"; image = QImage(":/images/bookmark.svg"); pixmapPath = ":/images/bookmark.svg"; } if (line > 0) { - qDebug() << "Book mark area paint event, line > 0"; + qCDebug(appLog) << "Book mark area paint event, line > 0"; lineBlock = document()->findBlockByNumber(line - 1); if (!lineBlock.isVisible()) { - qDebug() << "Book mark area paint event, lineBlock is not visible"; + qCDebug(appLog) << "Book mark area paint event, lineBlock is not visible"; continue; } @@ -5290,21 +5291,21 @@ void TextEdit::bookMarkAreaPaintEvent(QPaintEvent *event) render.render(&painter, rect); } } - qDebug() << "Book mark area paint event completed"; + qCDebug(appLog) << "Book mark area paint event completed"; } int TextEdit::getLineFromPoint(const QPoint &point) { - qDebug() << "Get line from point, point:" << point; + qCDebug(appLog) << "Get line from point, point:" << point; QTextCursor cursor = cursorForPosition(point); QTextBlock block = cursor.block(); - qDebug() << "Get line from point, block.blockNumber():" << block.blockNumber(); + qCDebug(appLog) << "Get line from point, block.blockNumber():" << block.blockNumber(); return block.blockNumber() + 1; } void TextEdit::addOrDeleteBookMark() { - qDebug() << "Add or delete book mark"; + qCDebug(appLog) << "Add or delete book mark"; int line = 0; if (m_bIsShortCut) { line = getCurrentLine(); @@ -5314,106 +5315,106 @@ void TextEdit::addOrDeleteBookMark() } if (line > blockCount()) { - qDebug() << "Add or delete book mark, line > blockCount()"; + qCDebug(appLog) << "Add or delete book mark, line > blockCount()"; return; } if (m_listBookmark.contains(line)) { - qDebug() << "Add or delete book mark, m_listBookmark contains line"; + qCDebug(appLog) << "Add or delete book mark, m_listBookmark contains line"; m_listBookmark.removeOne(line); m_nBookMarkHoverLine = -1; - qDebug() << "DeleteBookMark:" << line << m_listBookmark; + qCDebug(appLog) << "DeleteBookMark:" << line << m_listBookmark; } else { - qDebug() << "Add or delete book mark, m_listBookmark does not contain line"; + qCDebug(appLog) << "Add or delete book mark, m_listBookmark does not contain line"; m_listBookmark.push_back(line); - qDebug() << "AddBookMark:" << line << m_listBookmark; + qCDebug(appLog) << "AddBookMark:" << line << m_listBookmark; } m_pLeftAreaWidget->m_pBookMarkArea->update(); - qDebug() << "Add or delete book mark completed"; + qCDebug(appLog) << "Add or delete book mark completed"; } void TextEdit::moveToPreviousBookMark() { - qDebug() << "Move to previous book mark"; + qCDebug(appLog) << "Move to previous book mark"; int line = getCurrentLine(); int index = m_listBookmark.indexOf(line); if (index == -1 && !m_listBookmark.isEmpty()) { jumpToLine(m_listBookmark.last(), false); - qDebug() << "Move to previous book mark, index == -1 and !m_listBookmark.isEmpty(), return"; + qCDebug(appLog) << "Move to previous book mark, index == -1 and !m_listBookmark.isEmpty(), return"; return; } if (index == 0) { - qDebug() << "Move to previous book mark, index == 0"; + qCDebug(appLog) << "Move to previous book mark, index == 0"; jumpToLine(m_listBookmark.last(), false); } else { - qDebug() << "index != 0"; + qCDebug(appLog) << "index != 0"; jumpToLine(m_listBookmark.value(index - 1), false); } - qDebug() << "Move to previous book mark completed"; + qCDebug(appLog) << "Move to previous book mark completed"; } void TextEdit::moveToNextBookMark() { - qDebug() << "Move to next book mark"; + qCDebug(appLog) << "Move to next book mark"; int line = getCurrentLine(); int index = m_listBookmark.indexOf(line); if (index == -1 && !m_listBookmark.isEmpty()) { jumpToLine(m_listBookmark.first(), false); - qDebug() << "Move to next book mark, index == -1 and !m_listBookmark.isEmpty(), return"; + qCDebug(appLog) << "Move to next book mark, index == -1 and !m_listBookmark.isEmpty(), return"; return; } if (index == m_listBookmark.count() - 1) { - qDebug() << "Move to next book mark, index == m_listBookmark.count() - 1"; + qCDebug(appLog) << "Move to next book mark, index == m_listBookmark.count() - 1"; jumpToLine(m_listBookmark.first(), false); } else { - qDebug() << "Move to next book mark, index != m_listBookmark.count() - 1"; + qCDebug(appLog) << "Move to next book mark, index != m_listBookmark.count() - 1"; jumpToLine(m_listBookmark.value(index + 1), false); } - qDebug() << "Move to next book mark completed"; + qCDebug(appLog) << "Move to next book mark completed"; } void TextEdit::checkBookmarkLineMove(int from, int charsRemoved, int charsAdded) { - qDebug() << "Check bookmark line move, from:" << from << "charsRemoved:" << charsRemoved << "charsAdded:" << charsAdded; + qCDebug(appLog) << "Check bookmark line move, from:" << from << "charsRemoved:" << charsRemoved << "charsAdded:" << charsAdded; Q_UNUSED(charsRemoved); Q_UNUSED(charsAdded); if (m_bIsFileOpen) { - qDebug() << "Check bookmark line move, m_bIsFileOpen is true, return"; + qCDebug(appLog) << "Check bookmark line move, m_bIsFileOpen is true, return"; return; } if (m_nLines != blockCount()) { - qDebug() << "Check bookmark line move, m_nLines != blockCount()"; + qCDebug(appLog) << "Check bookmark line move, m_nLines != blockCount()"; QTextCursor cursor = textCursor(); int nAddorDeleteLine = document()->findBlock(from).blockNumber() + 1; int currLine = textCursor().blockNumber() + 1; if (m_nLines > blockCount()) { - qDebug() << "Check bookmark line move, m_nLines > blockCount()"; + qCDebug(appLog) << "Check bookmark line move, m_nLines > blockCount()"; foreach (const auto line, m_listBookmark) { - qDebug() << "Check bookmark line move, foreach line:" << line; + qCDebug(appLog) << "Check bookmark line move, foreach line:" << line; if (m_nSelectEndLine != -1) { - qDebug() << "Check bookmark line move, m_nSelectEndLine != -1"; + qCDebug(appLog) << "Check bookmark line move, m_nSelectEndLine != -1"; if (nAddorDeleteLine < line && line <= m_nSelectEndLine) { - qDebug() << "Check bookmark line move, nAddorDeleteLine < line && line <= m_nSelectEndLine"; + qCDebug(appLog) << "Check bookmark line move, nAddorDeleteLine < line && line <= m_nSelectEndLine"; m_listBookmark.removeOne(line); } else if (line > m_nSelectEndLine) { - qDebug() << "Check bookmark line move, line > m_nSelectEndLine"; + qCDebug(appLog) << "Check bookmark line move, line > m_nSelectEndLine"; m_listBookmark.replace(m_listBookmark.indexOf(line), line - m_nSelectEndLine + nAddorDeleteLine); } } else { - qDebug() << "Check bookmark line move, m_nSelectEndLine == -1"; + qCDebug(appLog) << "Check bookmark line move, m_nSelectEndLine == -1"; if (line == currLine + 1) { - qDebug() << "Check bookmark line move, line == currLine + 1"; + qCDebug(appLog) << "Check bookmark line move, line == currLine + 1"; m_listBookmark.removeOne(currLine + 1); } else if (line > currLine + 1) { - qDebug() << "Check bookmark line move, line > currLine + 1"; + qCDebug(appLog) << "Check bookmark line move, line > currLine + 1"; m_listBookmark.replace(m_listBookmark.indexOf(line), line - m_nLines + blockCount()); } } @@ -5421,19 +5422,19 @@ void TextEdit::checkBookmarkLineMove(int from, int charsRemoved, int charsAdded) } else { foreach (const auto line, m_listBookmark) { if (nAddorDeleteLine < line) { - qDebug() << "Check bookmark line move, nAddorDeleteLine < line"; + qCDebug(appLog) << "Check bookmark line move, nAddorDeleteLine < line"; m_listBookmark.replace(m_listBookmark.indexOf(line), line + blockCount() - m_nLines); } } } } m_nLines = blockCount(); - qDebug() << "Check bookmark line move completed"; + qCDebug(appLog) << "Check bookmark line move completed"; } void TextEdit::flodOrUnflodAllLevel(bool isFlod) { - qDebug() << "Processing" << (isFlod ? "fold" : "unfold") << "all code blocks in document"; + qCDebug(appLog) << "Processing" << (isFlod ? "fold" : "unfold") << "all code blocks in document"; m_listMainFlodAllPos.clear(); int totalBlocks = document()->blockCount(); @@ -5442,7 +5443,7 @@ void TextEdit::flodOrUnflodAllLevel(bool isFlod) //折叠 if (isFlod) { - qDebug() << "Searching for visible blocks with opening braces to fold"; + qCDebug(appLog) << "Searching for visible blocks with opening braces to fold"; for (int line = 0; line < totalBlocks; line++) { if (blockContainStrBrackets(line) && document()->findBlockByNumber(line).isVisible() @@ -5453,14 +5454,14 @@ void TextEdit::flodOrUnflodAllLevel(bool isFlod) foldPointsFound++; if (foldPointsFound % 20 == 0) { - qDebug() << "Found" << foldPointsFound << "fold points so far"; + qCDebug(appLog) << "Found" << foldPointsFound << "fold points so far"; } } } } //展开 } else { - qDebug() << "Searching for hidden blocks with opening braces to unfold"; + qCDebug(appLog) << "Searching for hidden blocks with opening braces to unfold"; for (int line = 0; line < totalBlocks; line++) { if (blockContainStrBrackets(line) && !document()->findBlockByNumber(line + 1).isVisible() @@ -5471,14 +5472,14 @@ void TextEdit::flodOrUnflodAllLevel(bool isFlod) foldPointsFound++; if (foldPointsFound % 20 == 0) { - qDebug() << "Found" << foldPointsFound << "unfold points so far"; + qCDebug(appLog) << "Found" << foldPointsFound << "unfold points so far"; } } } } } - qDebug() << "Found" << foldPointsFound << "fold points after processing" << processedBlocks + qCDebug(appLog) << "Found" << foldPointsFound << "fold points after processing" << processedBlocks << "blocks out of" << totalBlocks << "total blocks"; //折叠时出现点击光标选择行变短 @@ -5487,7 +5488,7 @@ void TextEdit::flodOrUnflodAllLevel(bool isFlod) this->setWordWrapMode(QTextOption::WrapAnywhere); this->setLineWrapMode(WrapMode); - qDebug() << "Updating UI components after fold/unfold operation"; + qCDebug(appLog) << "Updating UI components after fold/unfold operation"; m_pLeftAreaWidget->m_pFlodArea->update(); m_pLeftAreaWidget->m_pLineNumberArea->update(); m_pLeftAreaWidget->m_pBookMarkArea->update(); @@ -5497,34 +5498,34 @@ void TextEdit::flodOrUnflodAllLevel(bool isFlod) this->setLineWrapMode(curMode); viewport()->update(); - qDebug() << (isFlod ? "Fold" : "Unfold") << "all operation completed with" << foldPointsFound << "points processed"; + qCDebug(appLog) << (isFlod ? "Fold" : "Unfold") << "all operation completed with" << foldPointsFound << "points processed"; } void TextEdit::flodOrUnflodCurrentLevel(bool isFlod) { - qDebug() << "Processing" << (isFlod ? "fold" : "unfold") << "operation at cursor position"; + qCDebug(appLog) << "Processing" << (isFlod ? "fold" : "unfold") << "operation at cursor position"; int line = getLineFromPoint(m_mouseClickPos); - qDebug() << "Target line for fold/unfold:" << (line - 1) << "based on mouse position at line" << line; + qCDebug(appLog) << "Target line for fold/unfold:" << (line - 1) << "based on mouse position at line" << line; bool success = getNeedControlLine(line - 1, !isFlod); if (success) { - qDebug() << "Successfully" << (!isFlod ? "unfolded" : "folded") << "code block at line" << (line - 1); + qCDebug(appLog) << "Successfully" << (!isFlod ? "unfolded" : "folded") << "code block at line" << (line - 1); } else { - qDebug() << "Could not" << (!isFlod ? "unfold" : "fold") << "code block at line" << (line - 1) << "- no valid fold point found"; + qCDebug(appLog) << "Could not" << (!isFlod ? "unfold" : "fold") << "code block at line" << (line - 1) << "- no valid fold point found"; } - qDebug() << "Updating UI components after fold/unfold operation"; + qCDebug(appLog) << "Updating UI components after fold/unfold operation"; m_pLeftAreaWidget->m_pFlodArea->update(); m_pLeftAreaWidget->m_pLineNumberArea->update(); m_pLeftAreaWidget->m_pBookMarkArea->update(); viewport()->update(); document()->adjustSize(); - qDebug() << (isFlod ? "Fold" : "Unfold") << "operation completed at line" << (line - 1); + qCDebug(appLog) << (isFlod ? "Fold" : "Unfold") << "operation completed at line" << (line - 1); } void TextEdit::getHideRowContent(int iLine) { - qDebug() << "Preparing fold preview content for line" << iLine; + qCDebug(appLog) << "Preparing fold preview content for line" << iLine; // 预览文本块没有必要读取所有文本数据,调整为仅读取部分 // Note:需要注意单个文本块(一般为一行数据)过长的情况 // 最大显示的预览文本块数量,不超过1000 @@ -5536,14 +5537,14 @@ void TextEdit::getHideRowContent(int iLine) // 根据背景色亮度设置高亮模式 bool isDarkTheme = QColor(m_backgroundColor).lightness() < 128; - qDebug() << "Setting highlight mode based on theme:" << (isDarkTheme ? "dark" : "light"); + qCDebug(appLog) << "Setting highlight mode based on theme:" << (isDarkTheme ? "dark" : "light"); m_foldCodeShow->initHighLight(m_sFilePath, !isDarkTheme); m_foldCodeShow->appendText("{", width()); //左右括弧没有匹配到 if (!bFoundBrace) { - qDebug() << "No matching braces found, showing all subsequent content"; + qCDebug(appLog) << "No matching braces found, showing all subsequent content"; // 读取文本块索引 int curIndex = 0; int blocksAdded = 0; @@ -5554,14 +5555,14 @@ void TextEdit::getHideRowContent(int iLine) beginBlock = beginBlock.next(); blocksAdded++; } - qDebug() << "Added" << blocksAdded << "blocks to fold preview"; + qCDebug(appLog) << "Added" << blocksAdded << "blocks to fold preview"; //如果左右"{" "}"在同一行不折叠 } else if (endBlock == curBlock) { - qDebug() << "Braces on same line, no fold preview needed"; + qCDebug(appLog) << "Braces on same line, no fold preview needed"; return; } else { - qDebug() << "Found matching braces from line" << beginBlock.blockNumber() << "to" << endBlock.blockNumber(); + qCDebug(appLog) << "Found matching braces from line" << beginBlock.blockNumber() << "to" << endBlock.blockNumber(); // 读取文本块索引 int curIndex = 0; int blocksAdded = 0; @@ -5578,19 +5579,19 @@ void TextEdit::getHideRowContent(int iLine) } if (endBlock.text().simplified() == "}") { - qDebug() << "Adding closing brace from end block to preview"; + qCDebug(appLog) << "Adding closing brace from end block to preview"; m_foldCodeShow->appendText("}", width()); } m_foldCodeShow->appendText("}", width()); - qDebug() << "Added" << blocksAdded << "blocks to fold preview"; + qCDebug(appLog) << "Added" << blocksAdded << "blocks to fold preview"; } - qDebug() << "Fold preview content preparation completed for line" << iLine; + qCDebug(appLog) << "Fold preview content preparation completed for line" << iLine; } bool TextEdit::isNeedShowFoldIcon(QTextBlock block) { - qDebug() << "Checking if fold icon needed for block at line" << block.blockNumber(); + qCDebug(appLog) << "Checking if fold icon needed for block at line" << block.blockNumber(); QString blockText = block.text(); bool hasFindLeft = false; // 是否已经找到当前行第一个左括号 int rightNum = 0, leftNum = 0;//右括号数目、左括号数目 @@ -5607,15 +5608,15 @@ bool TextEdit::isNeedShowFoldIcon(QTextBlock block) } } - qDebug() << "Block analysis: found" << leftNum << "opening and" << rightNum << "closing braces"; + qCDebug(appLog) << "Block analysis: found" << leftNum << "opening and" << rightNum << "closing braces"; // 判断是否需要显示折叠图标 bool needFoldIcon = (rightNum != leftNum); if (needFoldIcon) { - qDebug() << "Fold icon needed - unbalanced braces in line" << block.blockNumber(); + qCDebug(appLog) << "Fold icon needed - unbalanced braces in line" << block.blockNumber(); } else { - qDebug() << "No fold icon needed - balanced braces in line" << block.blockNumber(); + qCDebug(appLog) << "No fold icon needed - balanced braces in line" << block.blockNumber(); } return needFoldIcon; @@ -5623,7 +5624,7 @@ bool TextEdit::isNeedShowFoldIcon(QTextBlock block) int TextEdit::getHighLightRowContentLineNum(int iLine) { - qDebug() << "Calculating highlight range end line for fold starting at line" << iLine; + qCDebug(appLog) << "Calculating highlight range end line for fold starting at line" << iLine; // 查询折叠区域文本块范围 QTextBlock beginBlock, endBlock, curBlock; bool bFoundBrace = findFoldBlock(iLine, beginBlock, endBlock, curBlock); @@ -5633,7 +5634,7 @@ int TextEdit::getHighLightRowContentLineNum(int iLine) //左右括弧没有匹配到 if (!bFoundBrace) { - qDebug() << "No matching closing brace found, counting all subsequent blocks"; + qCDebug(appLog) << "No matching closing brace found, counting all subsequent blocks"; //遍历最后右括弧文本块 设置块隐藏或显示 int blockCount = 0; while (beginBlock.isValid()) { @@ -5641,14 +5642,14 @@ int TextEdit::getHighLightRowContentLineNum(int iLine) beginBlock = beginBlock.next(); blockCount++; } - qDebug() << "Found" << blockCount << "blocks after line" << iLine << ", resulting end line:" << resultLine; + qCDebug(appLog) << "Found" << blockCount << "blocks after line" << iLine << ", resulting end line:" << resultLine; return resultLine; //如果左右"{" "}"在同一行不折叠 } else if (!bFoundBrace || endBlock == curBlock) { - qDebug() << "Braces on same line or invalid fold point, returning original line" << iLine; + qCDebug(appLog) << "Braces on same line or invalid fold point, returning original line" << iLine; return resultLine; } else { - qDebug() << "Found matching brace at line" << endBlock.blockNumber() << ", counting blocks in between"; + qCDebug(appLog) << "Found matching brace at line" << endBlock.blockNumber() << ", counting blocks in between"; int blockCount = 0; while (beginBlock != endBlock && beginBlock.isValid()) { resultLine++; @@ -5657,7 +5658,7 @@ int TextEdit::getHighLightRowContentLineNum(int iLine) } resultLine++; - qDebug() << "Found" << blockCount << "blocks between braces, resulting end line:" << resultLine + qCDebug(appLog) << "Found" << blockCount << "blocks between braces, resulting end line:" << resultLine << "(+" << (resultLine - initialLine) << " lines)"; return resultLine; } @@ -5665,7 +5666,7 @@ int TextEdit::getHighLightRowContentLineNum(int iLine) void TextEdit::paintCodeFlod(QPainter *painter, QRect rect, bool flod) { - qDebug() << "Paint code flod, painter:" << painter << "rect:" << rect << "flod:" << flod; + qCDebug(appLog) << "Paint code flod, painter:" << painter << "rect:" << rect << "flod:" << flod; painter->save(); painter->translate(rect.width() / 2.0, rect.height() / 2.0); @@ -5682,7 +5683,7 @@ void TextEdit::paintCodeFlod(QPainter *painter, QRect rect, bool flod) path.lineTo(p2); if (flod) { - qDebug() << "Paint code flod, flod is true"; + qCDebug(appLog) << "Paint code flod, flod is true"; painter->rotate(-90); } @@ -5692,18 +5693,18 @@ void TextEdit::paintCodeFlod(QPainter *painter, QRect rect, bool flod) painter->drawPath(path); painter->restore(); - qDebug() << "Paint code flod completed"; + qCDebug(appLog) << "Paint code flod completed"; } QColor TextEdit::getBackColor() { - qDebug() << "Get back color"; + qCDebug(appLog) << "Get back color"; return m_backgroundColor; } int TextEdit::lineNumberAreaWidth() { - qDebug() << "Line number area width"; + qCDebug(appLog) << "Line number area width"; int digits = 1; int max = qMax(1, this->document()->blockCount()); while (max >= 10) { @@ -5714,25 +5715,25 @@ int TextEdit::lineNumberAreaWidth() QFontMetrics fm(m_fontLineNumberArea); int w = fm.horizontalAdvance(QLatin1Char('9')) * digits; - qDebug() << "Line number area width completed"; + qCDebug(appLog) << "Line number area width completed"; return w > 15 ? w : 15; } void TextEdit::updateLeftWidgetWidth(int width) { - qDebug() << "Update left widget width, width:" << width; + qCDebug(appLog) << "Update left widget width, width:" << width; if (m_LeftAreaUpdateState != TextEdit::FileOpenBegin) { m_pLeftAreaWidget->m_pFlodArea->setFixedWidth(width); m_pLeftAreaWidget->m_pLineNumberArea->setFixedWidth(lineNumberAreaWidth()); m_pLeftAreaWidget->m_pBookMarkArea->setFixedWidth(width); setLeftAreaUpdateState(TextEdit::Normal); } - qDebug() << "Update left widget width completed"; + qCDebug(appLog) << "Update left widget width completed"; } int TextEdit::getLinePosYByLineNum(int iLine) { - qDebug() << "Get line pos y by line num, iLine:" << iLine; + qCDebug(appLog) << "Get line pos y by line num, iLine:" << iLine; QTextBlock block = document()->findBlockByNumber(iLine); QTextCursor cur = textCursor(); @@ -5741,43 +5742,43 @@ int TextEdit::getLinePosYByLineNum(int iLine) } cur.setPosition(block.position(), QTextCursor::MoveAnchor); - qDebug() << "Get line pos y by line num completed"; + qCDebug(appLog) << "Get line pos y by line num completed"; return cursorRect(cur).y(); } bool TextEdit::ifHasHighlight() { - qDebug() << "If has highlight"; + qCDebug(appLog) << "If has highlight"; if (!m_findHighlightSelection.cursor.isNull()) { - qDebug() << "If has highlight, m_findHighlightSelection.cursor is not null"; + qCDebug(appLog) << "If has highlight, m_findHighlightSelection.cursor is not null"; return m_findHighlightSelection.cursor.hasSelection(); } else { - qDebug() << "If has highlight, m_findHighlightSelection.cursor is null"; + qCDebug(appLog) << "If has highlight, m_findHighlightSelection.cursor is null"; return false; } - qDebug() << "If has highlight completed"; + qCDebug(appLog) << "If has highlight completed"; } void TextEdit::setIsFileOpen() { - qDebug() << "Set is file open"; + qCDebug(appLog) << "Set is file open"; m_bIsFileOpen = true; } void TextEdit::setTextFinished() { - qDebug() << "Set text finished"; + qCDebug(appLog) << "Set text finished"; m_bIsFileOpen = false; m_nLines = blockCount(); m_lastLeftAreaBlockCount = m_nLines; if (!m_settings) { - qDebug() << "Set text finished, m_settings is null, skip"; + qCDebug(appLog) << "Set text finished, m_settings is null, skip"; return; } if (!m_listBookmark.isEmpty()) { - qDebug() << "Set text finished, m_listBookmark is not empty"; + qCDebug(appLog) << "Set text finished, m_listBookmark is not empty"; return; } @@ -5788,7 +5789,7 @@ void TextEdit::setTextFinished() QString qstrPath = m_sFilePath; if (filePathList.contains(qstrPath)) { - qDebug() << "Set text finished, filePathList contains qstrPath"; + qCDebug(appLog) << "Set text finished, filePathList contains qstrPath"; int index = 2; QString qstrLines = bookmarkList.value(filePathList.indexOf(qstrPath)); QString sign; @@ -5798,29 +5799,29 @@ void TextEdit::setTextFinished() sign.append(qstrLines.at(i + 1)); if (sign == ",*" || sign == ")*") { - qDebug() << "Set text finished, sign == \",*\" || sign == \")\""; + qCDebug(appLog) << "Set text finished, sign == \",*\" || sign == \")\""; linesList << qstrLines.mid(index, i - index).toInt(); index = i + 2; } } - qDebug() << "Set text finished, filePathList does not contain qstrPath"; + qCDebug(appLog) << "Set text finished, filePathList does not contain qstrPath"; } foreach (const auto line, linesList) { if (line <= document()->blockCount()) { if (!m_listBookmark.contains(line)) { - qDebug() << "Set text finished, line <= document()->blockCount()"; + qCDebug(appLog) << "Set text finished, line <= document()->blockCount()"; m_listBookmark << line; } } } - qDebug() << "Set text finished, completed"; -// qDebug() << m_listBookmark << document()->blockCount(); + qCDebug(appLog) << "Set text finished, completed"; +// qCDebug(appLog) << m_listBookmark << document()->blockCount(); } QStringList TextEdit::readHistoryRecord(QString key) { - qDebug() << "Read history record, key:" << key; + qCDebug(appLog) << "Read history record, key:" << key; QString history = m_settings->settings->option(key)->value().toString(); QStringList historyList; int nLeftPosition = history.indexOf("*{"); @@ -5832,13 +5833,13 @@ QStringList TextEdit::readHistoryRecord(QString key) nRightPosition = history.indexOf("}*", nRightPosition + 2); } - qDebug() << "Read history record completed"; + qCDebug(appLog) << "Read history record completed"; return historyList; } QStringList TextEdit::readHistoryRecordofBookmark() { - qDebug() << "Read history record of bookmark"; + qCDebug(appLog) << "Read history record of bookmark"; QString history = m_settings->settings->option("advance.editor.browsing_history_file")->value().toString(); QStringList bookmarkList; int nLeftPosition = history.indexOf("*("); @@ -5850,13 +5851,13 @@ QStringList TextEdit::readHistoryRecordofBookmark() nRightPosition = history.indexOf(")*", nRightPosition + 2); } - qDebug() << "Read history record of bookmark completed"; + qCDebug(appLog) << "Read history record of bookmark completed"; return bookmarkList; } QStringList TextEdit::readHistoryRecordofFilePath(QString key) { - qDebug() << "Read history record of file path, key:" << key; + qCDebug(appLog) << "Read history record of file path, key:" << key; QString history = m_settings->settings->option(key)->value().toString(); QStringList filePathList; int nLeftPosition = history.indexOf("*["); @@ -5868,17 +5869,17 @@ QStringList TextEdit::readHistoryRecordofFilePath(QString key) nRightPosition = history.indexOf("]*", nRightPosition + 2); } - qDebug() << "Read history record of file path completed"; + qCDebug(appLog) << "Read history record of file path completed"; return filePathList; } void TextEdit::writeEncodeHistoryRecord() { - qDebug() << "Write encode history record"; + qCDebug(appLog) << "Write encode history record"; // EditWrapper 可能脱离 Window 独立构造(m_settings 未注入), // 使用前判空,与 setTextFinished 的空判保护保持一致 if (!m_settings || !m_settings->settings) { - qWarning() << "Write encode history record, m_settings is null, skip"; + qCWarning(appLog) << "Write encode history record, m_settings is null, skip"; return; } QString history = m_settings->settings->option("advance.editor.browsing_encode_history")->value().toString(); @@ -5888,7 +5889,7 @@ void TextEdit::writeEncodeHistoryRecord() foreach (auto path, pathList) { QFileInfo f(path); if (!f.isFile()) { - qDebug() << "Write encode history record, path is not a file"; + qCDebug(appLog) << "Write encode history record, path is not a file"; int nLeftPosition = history.indexOf(path); int nRightPosition = history.indexOf("}*", nLeftPosition); history.remove(nLeftPosition - 4, nRightPosition + 6 - nLeftPosition); @@ -5899,18 +5900,18 @@ void TextEdit::writeEncodeHistoryRecord() int nRightPosition = history.indexOf("}*", nLeftPosition); if (history.contains(m_sFilePath)) { - qDebug() << "Write encode history record, history contains m_sFilePath"; + qCDebug(appLog) << "Write encode history record, history contains m_sFilePath"; history.remove(nLeftPosition - 4, nRightPosition + 6 - nLeftPosition); } QString encodeHistory = history + "*{*[" + m_sFilePath + "]*" + m_textEncode + "}*"; m_settings->settings->option("advance.editor.browsing_encode_history")->setValue(encodeHistory); - qDebug() << "Write encode history record completed"; + qCDebug(appLog) << "Write encode history record completed"; } QStringList TextEdit::readEncodeHistoryRecord() { - qDebug() << "Read encode history record"; + qCDebug(appLog) << "Read encode history record"; QString history = m_settings->settings->option("advance.editor.browsing_encode_history")->value().toString(); QStringList filePathList; int nLeftPosition = history.indexOf("]*"); @@ -5922,7 +5923,7 @@ QStringList TextEdit::readEncodeHistoryRecord() nRightPosition = history.indexOf("}*", nRightPosition + 2); } - qDebug() << "Read encode history record completed"; + qCDebug(appLog) << "Read encode history record completed"; return filePathList; } @@ -5950,13 +5951,13 @@ void TextEdit::setTextEncode(const QString &encode) void TextEdit::tellFindBarClose() { - qDebug() << "Tell find bar close"; + qCDebug(appLog) << "Tell find bar close"; m_bIsFindClose = true; } void TextEdit::setEditPalette(const QString &activeColor, const QString &inactiveColor) { - qDebug() << "Set edit palette, activeColor:" << activeColor << "inactiveColor:" << inactiveColor; + qCDebug(appLog) << "Set edit palette, activeColor:" << activeColor << "inactiveColor:" << inactiveColor; // Not recommend manually setPalette() #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) Q_UNUSED(activeColor) @@ -5967,68 +5968,68 @@ void TextEdit::setEditPalette(const QString &activeColor, const QString &inactiv pa.setColor(QPalette::Active, QPalette::Text, QColor(activeColor)); setPalette(pa); #endif - qDebug() << "Set edit palette completed"; + qCDebug(appLog) << "Set edit palette completed"; } void TextEdit::setCodeFoldWidgetHide(bool isHidden) { - qDebug() << "Set code fold widget hide, isHidden:" << isHidden; + qCDebug(appLog) << "Set code fold widget hide, isHidden:" << isHidden; if (m_foldCodeShow) { - qDebug() << "Set code fold widget hide, m_foldCodeShow is not null"; + qCDebug(appLog) << "Set code fold widget hide, m_foldCodeShow is not null"; m_foldCodeShow->setHidden(isHidden); } - qDebug() << "Set code fold widget hide completed"; + qCDebug(appLog) << "Set code fold widget hide completed"; } void TextEdit::setTruePath(QString qstrTruePath) { - qDebug() << "Set true path, qstrTruePath:" << qstrTruePath; + qCDebug(appLog) << "Set true path, qstrTruePath:" << qstrTruePath; m_qstrTruePath = qstrTruePath; - qDebug() << "Set true path completed"; + qCDebug(appLog) << "Set true path completed"; } QString TextEdit::getTruePath() { - qDebug() << "Get true path"; + qCDebug(appLog) << "Get true path"; if (m_qstrTruePath.isEmpty()) { - qDebug() << "Get true path, m_qstrTruePath is empty"; + qCDebug(appLog) << "Get true path, m_qstrTruePath is empty"; return m_sFilePath; } - qDebug() << "Get true path completed"; + qCDebug(appLog) << "Get true path completed"; return m_qstrTruePath; } QList TextEdit::getBookmarkInfo() { - qDebug() << "Get bookmark info"; + qCDebug(appLog) << "Get bookmark info"; return m_listBookmark; } void TextEdit::setBookMarkList(QList bookMarkList) { m_listBookmark = bookMarkList; - qDebug() << "Set bookmark list completed"; + qCDebug(appLog) << "Set bookmark list completed"; } void TextEdit::updateSaveIndex() { - qDebug() << "Update save index"; + qCDebug(appLog) << "Update save index"; m_lastSaveIndex = m_pUndoStack->index(); - qDebug() << "Update save index completed"; + qCDebug(appLog) << "Update save index completed"; } void TextEdit::isMarkCurrentLine(bool isMark, QString strColor, qint64 timeStamp) { - qDebug() << "Is mark current line, isMark:" << isMark << "strColor:" << strColor << "timeStamp:" << timeStamp; + qCDebug(appLog) << "Is mark current line, isMark:" << isMark << "strColor:" << strColor << "timeStamp:" << timeStamp; qint64 operationTimeStamp = timeStamp; if (operationTimeStamp < 0) { - qDebug() << "Is mark current line, timeStamp is less than 0"; + qCDebug(appLog) << "Is mark current line, timeStamp is less than 0"; operationTimeStamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); } if (isMark) { - qDebug() << "Is mark current line, isMark is true"; + qCDebug(appLog) << "Is mark current line, isMark is true"; QTextEdit::ExtraSelection selection; selection.cursor = textCursor(); selection.format.setBackground(QColor(strColor)); @@ -6038,9 +6039,9 @@ void TextEdit::isMarkCurrentLine(bool isMark, QString strColor, qint64 timeStam if (textCursor().hasSelection()) { markOperation.type = MarkOnce; - qDebug() << "Is mark current line, textCursor().hasSelection() is true"; + qCDebug(appLog) << "Is mark current line, textCursor().hasSelection() is true"; } else { - qDebug() << "Is mark current line, textCursor().hasSelection() is false"; + qCDebug(appLog) << "Is mark current line, textCursor().hasSelection() is false"; markOperation.type = MarkLine; int beginPos = textCursor().block().position(); int endPos = beginPos + textCursor().block().length() - 1; @@ -6049,7 +6050,7 @@ void TextEdit::isMarkCurrentLine(bool isMark, QString strColor, qint64 timeStam } //alt选中光标单独处理 if (m_bIsAltMod) { - qDebug() << "Is mark current line, m_bIsAltMod is true"; + qCDebug(appLog) << "Is mark current line, m_bIsAltMod is true"; for (int i = 0; i < m_altModSelections.size(); ++i) { markOperation.cursor = m_altModSelections[i].cursor; selection.cursor = m_altModSelections[i].cursor; @@ -6059,7 +6060,7 @@ void TextEdit::isMarkCurrentLine(bool isMark, QString strColor, qint64 timeStam (selection, operationTimeStamp)); } } else { - qDebug() << "Is mark current line, m_bIsAltMod is false"; + qCDebug(appLog) << "Is mark current line, m_bIsAltMod is false"; markOperation.cursor = selection.cursor; m_markOperations.append(QPair(markOperation, operationTimeStamp)); m_wordMarkSelections.append( @@ -6067,17 +6068,17 @@ void TextEdit::isMarkCurrentLine(bool isMark, QString strColor, qint64 timeStam (selection, operationTimeStamp)); } } else { - qDebug() << "Is mark current line, isMark is false"; + qCDebug(appLog) << "Is mark current line, isMark is false"; clearMarksForTextCursor(); } - qDebug() << "Is mark current line completed"; + qCDebug(appLog) << "Is mark current line completed"; } void TextEdit::markAllKeywordInView() { - qDebug() << "Mark all keyword in view"; + qCDebug(appLog) << "Mark all keyword in view"; if (m_markOperations.isEmpty()) { - qDebug() << "Mark all keyword in view, m_markOperations is empty, return"; + qCDebug(appLog) << "Mark all keyword in view, m_markOperations is empty, return"; return; } @@ -6085,30 +6086,30 @@ void TextEdit::markAllKeywordInView() for (it = m_markOperations.begin(); it != m_markOperations.end(); ++it) { if (MarkAllMatch == it->first.type) { - qDebug() << "Mark all keyword in view, type is MarkAllMatch"; + qCDebug(appLog) << "Mark all keyword in view, type is MarkAllMatch"; // 标记当前视图根据匹配文本查找的所有文本 markKeywordInView(it->first.matchText, it->first.color, it->second); } else if (MarkAll == it->first.type) { - qDebug() << "Mark all keyword in view, type is MarkAll"; + qCDebug(appLog) << "Mark all keyword in view, type is MarkAll"; markAllInView(it->first.color, it->second); } } renderAllSelections(); - qDebug() << "Mark all keyword in view completed"; + qCDebug(appLog) << "Mark all keyword in view completed"; } bool TextEdit::markKeywordInView(QString keyword, QString color, qint64 timeStamp) { - qDebug() << "Mark keyword in view, keyword:" << keyword << "color:" << color << "timeStamp:" << timeStamp; + qCDebug(appLog) << "Mark keyword in view, keyword:" << keyword << "color:" << color << "timeStamp:" << timeStamp; qint64 operationTimeStamp = timeStamp; if (operationTimeStamp < 0) { - qDebug() << "Mark keyword in view, timeStamp is less than 0"; + qCDebug(appLog) << "Mark keyword in view, timeStamp is less than 0"; operationTimeStamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); } if (keyword.isEmpty()) { - qDebug() << "Mark keyword in view, keyword is empty, retun false"; + qCDebug(appLog) << "Mark keyword in view, keyword is empty, retun false"; return false; } @@ -6127,21 +6128,21 @@ bool TextEdit::markKeywordInView(QString keyword, QString color, qint64 timeStam } if (ret) { - qDebug() << "Mark keyword in view, ret is true"; + qCDebug(appLog) << "Mark keyword in view, ret is true"; m_mapKeywordMarkSelections[keyword] = listExtraSelectionWithTimeStamp; } - qDebug() << "Mark keyword in view completed"; + qCDebug(appLog) << "Mark keyword in view completed"; return ret; } void TextEdit::markAllInView(QString color, qint64 timeStamp) { - qDebug() << "Mark all keyword in view, color:" << color << "timeStamp:" << timeStamp; + qCDebug(appLog) << "Mark all keyword in view, color:" << color << "timeStamp:" << timeStamp; // 增加时间戳 qint64 operationTimeStamp = timeStamp; if (operationTimeStamp < 0) { - qDebug() << "Mark all keyword in view, timeStamp is less than 0"; + qCDebug(appLog) << "Mark all keyword in view, timeStamp is less than 0"; operationTimeStamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); } @@ -6177,20 +6178,20 @@ void TextEdit::markAllInView(QString color, qint64 timeStamp) (selection, operationTimeStamp)); m_mapKeywordMarkSelections[TEXT_EIDT_MARK_ALL] = listSelections; - qDebug() << "Mark all keyword in view completed"; + qCDebug(appLog) << "Mark all keyword in view completed"; } void TextEdit::isMarkAllLine(bool isMark, QString strColor) { - qDebug() << "Is mark all line, isMark:" << isMark << "strColor:" << strColor; + qCDebug(appLog) << "Is mark all line, isMark:" << isMark << "strColor:" << strColor; // 增加时间戳 qint64 timeStamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); if (isMark) { - qDebug() << "Is mark all line, isMark is true"; + qCDebug(appLog) << "Is mark all line, isMark is true"; QString selectionText = textCursor().selectedText(); if (selectionText.length() != 0 && selectionText.length() < (document()->characterCount() - 1)) { - qDebug() << "Is mark all line, selectionText is not empty"; + qCDebug(appLog) << "Is mark all line, selectionText is not empty"; // 没有使用的变量,去除 // QList wordMarkSelections = m_wordMarkSelections; QList listExtraSelection; @@ -6210,7 +6211,7 @@ void TextEdit::isMarkAllLine(bool isMark, QString strColor) m_markOperations.append(QPair(markOperation, timeStamp)); if (updateKeywordSelectionsInView(selectionText, format, &listExtraSelection)) { - qDebug() << "Is mark all line, updateKeywordSelectionsInView is true"; + qCDebug(appLog) << "Is mark all line, updateKeywordSelectionsInView is true"; QList> listExtraSelectionWithTimeStamp; for (int i = 0; i < listExtraSelection.size(); i++) { @@ -6220,7 +6221,7 @@ void TextEdit::isMarkAllLine(bool isMark, QString strColor) m_mapKeywordMarkSelections[selectionText] = listExtraSelectionWithTimeStamp; } else { - qDebug() << "Is mark all line, updateKeywordSelectionsInView is false"; + qCDebug(appLog) << "Is mark all line, updateKeywordSelectionsInView is false"; // 选中部分在文档中仅此一个,查找标记失败了,进行补充处理 QTextEdit::ExtraSelection extraSelect; listExtraSelection.append(extraSelection); @@ -6234,7 +6235,7 @@ void TextEdit::isMarkAllLine(bool isMark, QString strColor) } } else if (!textCursor().hasSelection() || selectionText.length() == (document()->characterCount() - 1)) { - qDebug() << "Is mark all line, selectionText is empty or equal to document length"; + qCDebug(appLog) << "Is mark all line, selectionText is empty or equal to document length"; TextEdit::MarkOperation markOperation; markOperation.type = MarkAll; markOperation.color = strColor; @@ -6242,7 +6243,7 @@ void TextEdit::isMarkAllLine(bool isMark, QString strColor) markAllInView(strColor, timeStamp); } } else { - qDebug() << "Is mark all line, isMark is false"; + qCDebug(appLog) << "Is mark all line, isMark is false"; m_markOperations.clear(); m_wordMarkSelections.clear(); m_mapKeywordMarkSelections.clear(); @@ -6256,29 +6257,29 @@ void TextEdit::isMarkAllLine(bool isMark, QString strColor) } renderAllSelections(); - qDebug() << "Cancel last mark completed"; + qCDebug(appLog) << "Cancel last mark completed"; } void TextEdit::cancelLastMark() { - qDebug() << "Cancel last mark"; + qCDebug(appLog) << "Cancel last mark"; if (m_markOperations.isEmpty()) { - qDebug() << "Cancel last mark, m_markOperations is empty"; + qCDebug(appLog) << "Cancel last mark, m_markOperations is empty"; return; } switch (m_markOperations.last().first.type) { case MarkOnce: case MarkLine: { - qDebug() << "Cancel last mark, type is MarkOnce or MarkLine"; + qCDebug(appLog) << "Cancel last mark, type is MarkOnce or MarkLine"; if (!m_wordMarkSelections.isEmpty()) { - qDebug() << "Cancel last mark, m_wordMarkSelections is not empty"; + qCDebug(appLog) << "Cancel last mark, m_wordMarkSelections is not empty"; // m_wordMarkSelections.removeLast(); // 考虑到可能的插入操作,需要同步清理时间戳一样的selection const qint64 operationTimeStamp = m_markOperations.last().second; for (int i = 0; i < m_wordMarkSelections.size(); i++) { if (operationTimeStamp == m_wordMarkSelections.at(i).second) { - qDebug() << "Cancel last mark, find same time stamp selection"; + qCDebug(appLog) << "Cancel last mark, find same time stamp selection"; m_wordMarkSelections.removeAt(i); i--; } @@ -6288,7 +6289,7 @@ void TextEdit::cancelLastMark() } case MarkAllMatch: { - qDebug() << "Cancel last mark, type is MarkAllMatch"; + qCDebug(appLog) << "Cancel last mark, type is MarkAllMatch"; // QString keyword = m_markOperations.last().first.cursor.selectedText(); QString keyword; qint64 timeStamp = m_markOperations.last().second; @@ -6296,10 +6297,10 @@ void TextEdit::cancelLastMark() QMap>>::Iterator it; for (it = m_mapKeywordMarkSelections.begin(); it != m_mapKeywordMarkSelections.end(); ++it) { if (it.value().size() > 0) { - qDebug() << "Cancel last mark, find keyword in map"; + qCDebug(appLog) << "Cancel last mark, find keyword in map"; qint64 itsTimeStamp = it.value().first().second; if (itsTimeStamp == timeStamp) { - qDebug() << "Cancel last mark, find keyword in map, time stamp is same"; + qCDebug(appLog) << "Cancel last mark, find keyword in map, time stamp is same"; keyword = it.key(); break; } @@ -6307,14 +6308,14 @@ void TextEdit::cancelLastMark() } if (m_mapKeywordMarkSelections.contains(keyword)) { - qDebug() << "Cancel last mark, find keyword in map, remove"; + qCDebug(appLog) << "Cancel last mark, find keyword in map, remove"; m_mapKeywordMarkSelections.remove(keyword); } break; } case MarkAll: { - qDebug() << "Cancel last mark, type is MarkAll"; + qCDebug(appLog) << "Cancel last mark, type is MarkAll"; if (m_mapKeywordMarkSelections.contains(TEXT_EIDT_MARK_ALL)) { m_mapKeywordMarkSelections.remove(TEXT_EIDT_MARK_ALL); } @@ -6328,36 +6329,36 @@ void TextEdit::cancelLastMark() // 如果在标记颜色操作后,更改文本内容,如果存在残留,补充一个清除处理 if (m_markOperations.isEmpty() && (m_wordMarkSelections.size() > 0 || m_mapKeywordMarkSelections.size() > 0)) { - qWarning() << __FUNCTION__ << __LINE__ << " cancle mark color operation," + qCWarning(appLog) << __FUNCTION__ << __LINE__ << " cancle mark color operation," << "find exist remain selections, will clear!"; m_wordMarkSelections.clear(); m_mapKeywordMarkSelections.clear(); } renderAllSelections(); - qDebug() << "Cancel last mark completed"; + qCDebug(appLog) << "Cancel last mark completed"; } bool TextEdit::clearMarkOperationForCursor(QTextCursor cursor) { - qDebug() << "Cancel last mark, find cursor in m_markOperations"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_markOperations"; bool bRet = false; for (int i = m_markOperations.size() - 1; i >= 0; --i) { if (m_markOperations.at(i).first.cursor == cursor) { m_markOperations.removeAt(i); bRet = true; - qDebug() << "Cancel last mark, find cursor in m_markOperations, break!"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_markOperations, break!"; break; } } - qDebug() << "Cancel last mark, find cursor in m_markOperations, return: " << bRet; + qCDebug(appLog) << "Cancel last mark, find cursor in m_markOperations, return: " << bRet; return bRet; } bool TextEdit::clearMarksForTextCursor() { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections"; bool bFind = false; QTextCursor cursor; QTextCursor textcursor = textCursor(); @@ -6365,17 +6366,17 @@ bool TextEdit::clearMarksForTextCursor() for (int i = m_wordMarkSelections.size() - 1; i >= 0; --i) { cursor = m_wordMarkSelections.at(i).first.cursor; if (textcursor.hasSelection()) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, has selection"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, has selection"; if (textcursor == cursor) { bFind = true; clearMarkOperationForCursor(cursor); m_wordMarkSelections.removeAt(i); - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, has selection, equal, break"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, has selection, equal, break"; break; } } else { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, has no selection"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, has no selection"; if (textcursor.position() >= cursor.selectionStart() && textcursor.position() <= cursor.selectionEnd()) { bFind = true; clearMarkOperationForCursor(cursor); @@ -6384,21 +6385,21 @@ bool TextEdit::clearMarksForTextCursor() } } - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, return: " << bFind; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, return: " << bFind; return bFind; } void TextEdit::toggleMarkSelections() { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, toggle"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, toggle"; if (!clearMarksForTextCursor()) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, no find"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, no find"; ColorSelectWdg *pColorSelectWdg = static_cast(m_actionColorStyles->defaultWidget()); isMarkCurrentLine(true, pColorSelectWdg->getDefaultColor().name()); } renderAllSelections(); - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, toggle end"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, toggle end"; } /** @@ -6409,7 +6410,7 @@ void TextEdit::toggleMarkSelections() */ QList > TextEdit::convertReplaceToMark(const QList &replaceInfo) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, convert"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, convert"; QList > markList; for (auto info : replaceInfo) { MarkOperation markOpt = info.opt; @@ -6421,7 +6422,7 @@ QList > TextEdit::convertReplaceToMark(co markList.append(qMakePair(markOpt, info.time)); } - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, convert end"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, convert end"; return markList; } @@ -6433,7 +6434,7 @@ QList > TextEdit::convertReplaceToMark(co */ QList TextEdit::convertMarkToReplace(const QList > &markInfo) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, convert"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, toggle, convert"; QList replaceMarkList; for (auto info : markInfo) { MarkReplaceInfo replace; @@ -6447,7 +6448,7 @@ QList TextEdit::convertMarkToReplace(const QList TextEdit::convertMarkToReplace(const QList > &markInfo) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark"; m_markOperations = markInfo; // 全部标记更新后,修改手动标记文本部分 @@ -6469,20 +6470,20 @@ void TextEdit::manualUpdateAllMark(const QList > &m if (MarkAll == (*itr).first.type || MarkAllMatch == (*itr).first.type) { ++itr; - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, all mark, continue"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, all mark, continue"; continue; } // 若无选中项,则过滤此颜色标记 if (!(*itr).first.cursor.hasSelection()) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, no selection, erase"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, no selection, erase"; itr = m_markOperations.erase(itr); continue; } auto &info = *itr; if (MarkOnce == info.first.type) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, once mark"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, once mark"; QTextEdit::ExtraSelection selection; selection.format.setBackground(QColor(info.first.color)); selection.cursor = info.first.cursor; @@ -6491,7 +6492,7 @@ void TextEdit::manualUpdateAllMark(const QList > &m m_wordMarkSelections.append(qMakePair(selection, info.second)); } else if (MarkLine == info.first.type) { - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, line mark"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, line mark"; int selectStart = info.first.cursor.selectionStart(); int selectEnd = info.first.cursor.selectionEnd(); QTextBlock startBlock = document()->findBlock(selectStart); @@ -6527,7 +6528,7 @@ void TextEdit::manualUpdateAllMark(const QList > &m // 若为多行颜色标记,会将当前文本颜色标记移除,后续添加为多行颜色标记 if (isMultiLine) { itr = m_markOperations.erase(itr); - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, multi line, erase"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, multi line, erase"; continue; } } @@ -6551,7 +6552,7 @@ void TextEdit::manualUpdateAllMark(const QList > &m // 计算全文标记部分并刷新界面颜色标记 markAllKeywordInView(); - qDebug() << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, end"; + qCDebug(appLog) << "Cancel last mark, find cursor in m_wordMarkSelections, manualUpdateAllMark, end"; } /** @@ -6565,11 +6566,11 @@ void TextEdit::manualUpdateAllMark(const QList > &m */ static QPair findMatchRange(const QList &posList, int markStart, int markEnd, const QString &replaceText) { - qDebug() << "findMatchRange, markStart" << markStart << "markEnd" << markEnd << "replaceText" << replaceText; + qCDebug(appLog) << "findMatchRange, markStart" << markStart << "markEnd" << markEnd << "replaceText" << replaceText; // 判断颜色标记 info 范围内是否包含替换文本索引信息 QPair foundPosRange {-1, -1}; if (posList.isEmpty()) { - qDebug() << "findMatchRange, posList is empty, return"; + qCDebug(appLog) << "findMatchRange, posList is empty, return"; return foundPosRange; } @@ -6580,7 +6581,7 @@ static QPair findMatchRange(const QList &posList, int markStart, auto leftfindItr = std::upper_bound(posList.begin(), posList.end(), adjustMarkStart); if (leftfindItr != posList.end() && (*leftfindItr) < markEnd) { - qDebug() << "findMatchRange, leftfindItr" << (*leftfindItr) << "markEnd" << markEnd; + qCDebug(appLog) << "findMatchRange, leftfindItr" << (*leftfindItr) << "markEnd" << markEnd; // 设置查询的左边界 foundPosRange.first = static_cast(std::distance(posList.begin(), leftfindItr)); } @@ -6589,15 +6590,15 @@ static QPair findMatchRange(const QList &posList, int markStart, auto rightFindItr = std::lower_bound(posList.rbegin(), posList.rend(), markEnd - 1, std::greater()); if (rightFindItr != posList.rend() && markStart < (*rightFindItr)) { - qDebug() << "findMatchRange, rightFindItr" << (*rightFindItr) << "markStart" << markStart; + qCDebug(appLog) << "findMatchRange, rightFindItr" << (*rightFindItr) << "markStart" << markStart; // 设置右边界 foundPosRange.second = static_cast(std::distance(rightFindItr, posList.rend() - 1)); } else if (-1 != foundPosRange.first) { - qDebug() << "findMatchRange, foundPosRange.first" << foundPosRange.first; + qCDebug(appLog) << "findMatchRange, foundPosRange.first" << foundPosRange.first; foundPosRange.second = foundPosRange.first; } - qDebug() << "findMatchRange, foundPosRange" << foundPosRange; + qCDebug(appLog) << "findMatchRange, foundPosRange" << foundPosRange; return foundPosRange; } @@ -6610,7 +6611,7 @@ static QPair findMatchRange(const QList &posList, int markStart, */ static void updateMarkReplaceRange(const QList &foundPosList, TextEdit::MarkReplaceInfo &info, const QString &replaceText, const QString &withText) { - qDebug() << "updateMarkReplaceRange, info"; + qCDebug(appLog) << "updateMarkReplaceRange, info"; // 文本替换长度变更调整量 int adjustlen = withText.size() - replaceText.size(); // 获取替换文本位置索引列表 @@ -6618,7 +6619,7 @@ static void updateMarkReplaceRange(const QList &foundPosList, TextEdit::Mar if (-1 == posIndexRange.first && -1 == posIndexRange.second) { - qDebug() << "updateMarkReplaceRange, posIndexRange, first" << posIndexRange.first << "second" << posIndexRange.second; + qCDebug(appLog) << "updateMarkReplaceRange, posIndexRange, first" << posIndexRange.first << "second" << posIndexRange.second; // 颜色标记内不包含替换文本,和替换文本无交集 // 根据当前查询位置判断 foundPosList[findCount - 1] 方向 if (!foundPosList.isEmpty() @@ -6632,7 +6633,7 @@ static void updateMarkReplaceRange(const QList &foundPosList, TextEdit::Mar info.end += foundPosList.size() * adjustlen; } } else { - qDebug() << "updateMarkReplaceRange, posIndexRange, first" << posIndexRange.first << "second" << posIndexRange.second; + qCDebug(appLog) << "updateMarkReplaceRange, posIndexRange, first" << posIndexRange.first << "second" << posIndexRange.second; // 判断左侧是否有交集,拓展颜色标记到替换文本 if (-1 != posIndexRange.first && foundPosList[posIndexRange.first] <= info.start) { @@ -6651,7 +6652,7 @@ static void updateMarkReplaceRange(const QList &foundPosList, TextEdit::Mar info.end += (posIndexRange.second + 1) * adjustlen; } } - qDebug() << "updateMarkReplaceRange exit"; + qCDebug(appLog) << "updateMarkReplaceRange exit"; } /** @@ -6678,11 +6679,11 @@ static void updateMarkReplaceRange(const QList &foundPosList, TextEdit::Mar void TextEdit::calcMarkReplaceList(QList &replaceList, const QString &oldText, const QString &replaceText, const QString &withText, int offset, Qt::CaseSensitivity caseFlag) const { - qDebug() << "calcMarkReplaceList, replaceList, size=" << replaceList.size(); + qCDebug(appLog) << "calcMarkReplaceList, replaceList, size=" << replaceList.size(); // 当前替换项为空或相同,退出 if (replaceList.isEmpty() || replaceText == withText) { - qDebug() << "calcMarkReplaceList, replaceList is empty or replaceText == withText, return"; + qCDebug(appLog) << "calcMarkReplaceList, replaceList is empty or replaceText == withText, return"; return; } @@ -6697,27 +6698,27 @@ void TextEdit::calcMarkReplaceList(QList &replaceList QPair curMarkRange {0, 0}; // 更新当前标记替换项索引和其对应的标记范围 auto updateMarkIndexAndRange = [&]() { - qDebug() << "updateMarkIndexAndRange, currentMarkIndex" << currentMarkIndex; + qCDebug(appLog) << "updateMarkIndexAndRange, currentMarkIndex" << currentMarkIndex; currentMarkIndex++; while (currentMarkIndex >= 0 && currentMarkIndex < replaceList.size()) { auto &markInfo = replaceList.at(currentMarkIndex); - qDebug() << "updateMarkIndexAndRange, markInfo, start" << markInfo.start << "end" << markInfo.end; + qCDebug(appLog) << "updateMarkIndexAndRange, markInfo, start" << markInfo.start << "end" << markInfo.end; // 标记类型为标记全文或文本全文标记(使用文本查找而非光标位置),不进行替换处理 if (MarkAllMatch == markInfo.opt.type || MarkAll == markInfo.opt.type) { - qDebug() << "updateMarkIndexAndRange, markInfo, type is MarkAllMatch or MarkAll, continue"; + qCDebug(appLog) << "updateMarkIndexAndRange, markInfo, type is MarkAllMatch or MarkAll, continue"; currentMarkIndex++; continue; } curMarkRange = qMakePair(markInfo.start, markInfo.end); - qDebug() << "updateMarkIndexAndRange, curMarkRange" << curMarkRange; + qCDebug(appLog) << "updateMarkIndexAndRange, curMarkRange" << curMarkRange; break; } }; - qDebug() << "updateMarkIndexAndRange, before updateMarkIndexAndRange"; + qCDebug(appLog) << "updateMarkIndexAndRange, before updateMarkIndexAndRange"; updateMarkIndexAndRange(); - qDebug() << "updateMarkIndexAndRange, after updateMarkIndexAndRange"; + qCDebug(appLog) << "updateMarkIndexAndRange, after updateMarkIndexAndRange"; // 查找统计及已查找偏移量 int findOffset = 0; @@ -6728,7 +6729,7 @@ void TextEdit::calcMarkReplaceList(QList &replaceList // 需要取得左侧所有的变更相对偏移,从文本左侧开始循环遍历 while (-1 != findPos && currentMarkIndex < replaceList.size()) { - qDebug() << "calcMarkReplaceList, findPos" << findPos << "offset" << offset; + qCDebug(appLog) << "calcMarkReplaceList, findPos" << findPos << "offset" << offset; // 转换为相对全文的偏移 int realPos = findPos + offset; // 记录已查询的索引位置 @@ -6741,11 +6742,11 @@ void TextEdit::calcMarkReplaceList(QList &replaceList // 判断是否处于查询范围内,处于右侧区间则后续处理 while (Utils::ERight != type) { auto &info = replaceList[currentMarkIndex]; - qDebug() << "calcMarkReplaceList, info, start" << info.start << "end" << info.end; + qCDebug(appLog) << "calcMarkReplaceList, info, start" << info.start << "end" << info.end; bool checkNext = false; switch (type) { case Utils::EIntersectInner: { - qDebug() << "calcMarkReplaceList, type is EIntersectInner"; + qCDebug(appLog) << "calcMarkReplaceList, type is EIntersectInner"; // 替换文本内容包含标记信息, 取消当前文本标记(无论单个文本还是单行文本,均移除) // 在 manualUpdateAllMark() 函数处理会移除此标记 info.start = 0; @@ -6754,7 +6755,7 @@ void TextEdit::calcMarkReplaceList(QList &replaceList break; } case Utils::ELeft: { - qDebug() << "calcMarkReplaceList, type is ELeft"; + qCDebug(appLog) << "calcMarkReplaceList, type is ELeft"; // 当前无交集,颜色标记在替换文本左侧,表示当前颜色标记已经经过 updateMarkReplaceRange(foundPosList, info, replaceText, withText); @@ -6767,25 +6768,25 @@ void TextEdit::calcMarkReplaceList(QList &replaceList } if (checkNext) { - qDebug() << "calcMarkReplaceList, checkNext is true"; + qCDebug(appLog) << "calcMarkReplaceList, checkNext is true"; // 更新当前计算的颜色标记和范围 updateMarkIndexAndRange(); // 判断颜色标记是否计算完成 if (currentMarkIndex == replaceList.size()) { - qDebug() << "calcMarkReplaceList, currentMarkIndex == replaceList.size(), break"; + qCDebug(appLog) << "calcMarkReplaceList, currentMarkIndex == replaceList.size(), break"; break; } // 继续查找下一颜色标记和当前查询位置的交叉范围 type = Utils::checkRegionIntersect(realPos, realPos + replaceText.size(), curMarkRange.first, curMarkRange.second); } else { - qDebug() << "calcMarkReplaceList, checkNext is false, break"; + qCDebug(appLog) << "calcMarkReplaceList, checkNext is false, break"; break; } } if (currentMarkIndex == replaceList.size()) { - qDebug() << "calcMarkReplaceList, currentMarkIndex == replaceList.size(), break"; + qCDebug(appLog) << "calcMarkReplaceList, currentMarkIndex == replaceList.size(), break"; break; } @@ -6796,19 +6797,19 @@ void TextEdit::calcMarkReplaceList(QList &replaceList // 继续处理剩余颜色标记偏移 while (currentMarkIndex != replaceList.size()) { - qDebug() << "calcMarkReplaceList, currentMarkIndex != replaceList.size(), while"; + qCDebug(appLog) << "calcMarkReplaceList, currentMarkIndex != replaceList.size(), while"; // 将后续未处理到的颜色标记调整偏移量 auto &info = replaceList[currentMarkIndex]; updateMarkReplaceRange(foundPosList, info, replaceText, withText); updateMarkIndexAndRange(); } - qDebug() << "calcMarkReplaceList, completed"; + qCDebug(appLog) << "calcMarkReplaceList, completed"; } void TextEdit::markSelectWord() { - qDebug() << "markSelectWord"; + qCDebug(appLog) << "markSelectWord"; bool isFind = false; for (int i = 0 ; i < m_wordMarkSelections.size(); ++i) { QTextCursor curson = m_wordMarkSelections.at(i).first.cursor; @@ -6817,7 +6818,7 @@ void TextEdit::markSelectWord() currentCurson.movePosition(QTextCursor::EndOfLine); //if (m_wordMarkSelections.at(i).cursor == textCursor()) { if (curson == currentCurson) { - qDebug() << "markSelectWord, curson == currentCurson"; + qCDebug(appLog) << "markSelectWord, curson == currentCurson"; isFind = true; m_wordMarkSelections.removeAt(i); renderAllSelections(); @@ -6825,22 +6826,22 @@ void TextEdit::markSelectWord() } } if (!isFind) { - qDebug() << "markSelectWord, isFind is false"; + qCDebug(appLog) << "markSelectWord, isFind is false"; //添加快捷键标记颜色 ColorSelectWdg *pColorSelectWdg = static_cast(m_actionColorStyles->defaultWidget()); isMarkCurrentLine(true, pColorSelectWdg->getDefaultColor().name()); renderAllSelections(); } - qDebug() << "markSelectWord, completed"; + qCDebug(appLog) << "markSelectWord, completed"; } void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) { - qDebug() << "updateMark, from" << from << "charsRemoved" << charsRemoved << "charsAdded" << charsAdded; + qCDebug(appLog) << "updateMark, from" << from << "charsRemoved" << charsRemoved << "charsAdded" << charsAdded; //只读模式下实现禁止语音输入的效果 if (m_readOnlyMode) { //undo(); - qDebug() << "updateMark, readOnlyMode, return"; + qCDebug(appLog) << "updateMark, readOnlyMode, return"; return; } @@ -6856,7 +6857,7 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) return; } - qDebug() << "updateMark, charsRemoved" << charsRemoved << "charsAdded" << charsAdded; + qCDebug(appLog) << "updateMark, charsRemoved" << charsRemoved << "charsAdded" << charsAdded; //更新标记 int nStartPos = 0,///< 标记的起始位置 nEndPos = 0,///< 标记的结束位置 @@ -6869,7 +6870,7 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) //如果是删除字符 if (charsRemoved > 0) { - qDebug() << "updateMark, charsRemoved > 0"; + qCDebug(appLog) << "updateMark, charsRemoved > 0"; QList listRemoveItem;///< 要移除标记的indexs //寻找要移除标记的index @@ -6881,13 +6882,13 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) //如果有文字被选择 if (m_nSelectEndLine != -1) { - qDebug() << "updateMark, charsRemoved > 0, m_nSelectEndLine != -1"; + qCDebug(appLog) << "updateMark, charsRemoved > 0, m_nSelectEndLine != -1"; //如果删除的内容,完全包含标记内容 if (m_nSelectStart <= nStartPos && m_nSelectEnd >= nEndPos) { listRemoveItem.append(i); } } else { - qDebug() << "updateMark, charsRemoved > 0, m_nSelectEndLine == -1"; + qCDebug(appLog) << "updateMark, charsRemoved > 0, m_nSelectEndLine == -1"; //如果标记内容全部被删除 if (wordMarkSelections.value(i).first.cursor.selection().toPlainText().isEmpty()) { // 此时 remove m_wordMarkSelections中的元素 @@ -6908,21 +6909,21 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) m_wordMarkSelections.removeAt(i); } } - qDebug() << "updateMark: Removed marks, remaining:" << m_wordMarkSelections.size(); + qCDebug(appLog) << "updateMark: Removed marks, remaining:" << m_wordMarkSelections.size(); #else QSet removeSet(listRemoveItem.begin(), listRemoveItem.end()); int index = 0; int removedCount = m_wordMarkSelections.removeIf([&removeSet, &index](const auto&) { return removeSet.contains(index++); }); - qDebug() << "updateMark: Removed" << removedCount << "marks, remaining:" << m_wordMarkSelections.size(); + qCDebug(appLog) << "updateMark: Removed" << removedCount << "marks, remaining:" << m_wordMarkSelections.size(); #endif } } //如果是添加字符 if (charsAdded > 0) { - qDebug() << "updateMark, charsAdded > 0"; + qCDebug(appLog) << "updateMark, charsAdded > 0"; for (int i = 0; i < wordMarkSelections.count(); i++) { nEndPos = wordMarkSelections.value(i).first.cursor.selectionEnd(); nStartPos = wordMarkSelections.value(i).first.cursor.selectionStart(); @@ -6931,25 +6932,25 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) //如果字符添加在标记中 if (nCurrentPos > nStartPos && nCurrentPos < nEndPos) { - qDebug() << "updateMark, charsAdded > 0, nCurrentPos > nStartPos && nCurrentPos < nEndPos"; + qCDebug(appLog) << "updateMark, charsAdded > 0, nCurrentPos > nStartPos && nCurrentPos < nEndPos"; //Qt已自动调整cursor范围以包含新插入的文本,保持标记为整体不做分割, //避免分割后新输入文本落在两段标记间隙中导致颜色丢失 //BUG-345731 break; } else if (nCurrentPos == nEndPos) { //如果字符添加在标记后 - qDebug() << "updateMark, charsAdded > 0, nCurrentPos == nEndPos"; + qCDebug(appLog) << "updateMark, charsAdded > 0, nCurrentPos == nEndPos"; m_wordMarkSelections.removeAt(i); selection.format.setBackground(strColor); selection.cursor = textCursor(); if (m_bIsInputMethod) { - qDebug() << "updateMark, charsAdded > 0, m_bIsInputMethod"; + qCDebug(appLog) << "updateMark, charsAdded > 0, m_bIsInputMethod"; selection.cursor.setPosition(nStartPos, QTextCursor::MoveAnchor); selection.cursor.setPosition(nEndPos - m_qstrCommitString.size(), QTextCursor::KeepAnchor); m_bIsInputMethod = false; } else { - qDebug() << "updateMark, charsAdded > 0, !m_bIsInputMethod"; + qCDebug(appLog) << "updateMark, charsAdded > 0, !m_bIsInputMethod"; selection.cursor.setPosition(nStartPos, QTextCursor::MoveAnchor); selection.cursor.setPosition(from + charsAdded, QTextCursor::KeepAnchor); } @@ -6967,7 +6968,7 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) listSelections = list; listSelections.insert(k, selection); bIsFind = true; - qDebug() << "updateMark, charsAdded > 0, bIsFind, break"; + qCDebug(appLog) << "updateMark, charsAdded > 0, bIsFind, break"; break; } } @@ -6975,11 +6976,11 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) if (bIsFind) { m_mapWordMarkSelections.remove(j); m_mapWordMarkSelections.insert(j, listSelections); - qDebug() << "updateMark, charsAdded > 0, bIsFind, break"; + qCDebug(appLog) << "updateMark, charsAdded > 0, bIsFind, break"; break; } } - qDebug() << "updateMark, charsAdded > 0, break"; + qCDebug(appLog) << "updateMark, charsAdded > 0, break"; break; } } @@ -6987,40 +6988,40 @@ void TextEdit::updateMark(int from, int charsRemoved, int charsAdded) //渲染所有的指定字符格式 renderAllSelections(); - qDebug() << "updateMark, completed"; + qCDebug(appLog) << "updateMark, completed"; } void TextEdit::setCursorStart(int pos) { - qDebug() << "setCursorStart, pos" << pos; + qCDebug(appLog) << "setCursorStart, pos" << pos; m_cursorStart = pos; } void TextEdit::completionWord(QString word) { - qDebug() << "completionWord, word" << word; + qCDebug(appLog) << "completionWord, word" << word; QString wordAtCursor = getWordAtCursor(); QTextCursor cursor = textCursor(); QString completionString = word.remove(0, wordAtCursor.size()); if (completionString.size() > 0) { - qDebug() << "completionWord, completionString" << completionString; + qCDebug(appLog) << "completionWord, completionString" << completionString; cursor = textCursor(); cursor.insertText(completionString); setTextCursor(cursor); } - qDebug() << "completionWord, completed"; + qCDebug(appLog) << "completionWord, completed"; } bool TextEdit::eventFilter(QObject *object, QEvent *event) { - // qDebug() << "eventFilter, event->type()" << event->type(); + // qCDebug(appLog) << "eventFilter, event->type()" << event->type(); switch (event->type()) { case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: { - qDebug() << "eventFilter, case QEvent::TouchBegin, QEvent::TouchUpdate, QEvent::TouchEnd"; + qCDebug(appLog) << "eventFilter, case QEvent::TouchBegin, QEvent::TouchUpdate, QEvent::TouchEnd"; QTouchEvent *touchEvent = static_cast(event); QList touchPoints = touchEvent->touchPoints(); QMouseEvent *event2 = static_cast(event); @@ -7033,12 +7034,12 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) default: break; } if (event->type() == QEvent::MouseButtonPress) { - qDebug() << "eventFilter, case QEvent::MouseButtonPress"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress"; QMouseEvent *mouseEvent = static_cast(event); m_mouseClickPos = mouseEvent->pos(); if (object == m_pLeftAreaWidget->m_pBookMarkArea) { - qDebug() << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea"; m_mouseClickPos = mouseEvent->pos(); if (mouseEvent->button() == Qt::RightButton) { m_rightMenu->clear(); @@ -7050,31 +7051,31 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) if (m_listBookmark.contains(line)) { m_rightMenu->addAction(m_cancelBookMarkAction); if (m_listBookmark.count() > 1) { - qDebug() << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, m_listBookmark.count() > 1"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, m_listBookmark.count() > 1"; m_rightMenu->addAction(m_preBookMarkAction); m_rightMenu->addAction(m_nextBookMarkAction); } } else { - qDebug() << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, m_listBookmark.isEmpty()"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, m_listBookmark.isEmpty()"; m_rightMenu->addAction(m_addBookMarkAction); } if (!m_listBookmark.isEmpty()) { - qDebug() << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, !m_listBookmark.isEmpty()"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, !m_listBookmark.isEmpty()"; m_rightMenu->addAction(m_clearBookMarkAction); } m_rightMenu->exec(mouseEvent->globalPos()); } else { - qDebug() << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, else"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pBookMarkArea, else"; addOrDeleteBookMark(); } return true; } else if (object == m_pLeftAreaWidget->m_pFlodArea) { - qDebug() << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pFlodArea"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pFlodArea"; m_foldCodeShow->hide(); if (mouseEvent->button() == Qt::LeftButton) { - qDebug() << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pFlodArea, mouseEvent->button() == Qt::LeftButton"; + qCDebug(appLog) << "eventFilter, case QEvent::MouseButtonPress, object == m_pLeftAreaWidget->m_pFlodArea, mouseEvent->button() == Qt::LeftButton"; int line = getLineFromPoint(mouseEvent->pos()); m_markFoldHighLightSelections.clear(); renderAllSelections(); @@ -7087,7 +7088,7 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) if (m_commentDefinition.isValid()) { multiLineCommentMark = m_commentDefinition.multiLineStart.trimmed(); singleLineCommentMark = m_commentDefinition.singleLine.trimmed(); - //qDebug()<<"CommentMark:"<findBlockByNumber(line - 1).text().trimmed().startsWith(multiLineCommentMark); if (!singleLineCommentMark.isEmpty()) bHasCommnent = document()->findBlockByNumber(line - 1).text().trimmed().startsWith(singleLineCommentMark); @@ -7097,7 +7098,7 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) // 当前行line-1 判断下行line是否隐藏 if (document()->findBlockByNumber(line).isVisible() && document()->findBlockByNumber(line - 1).text().contains("{") && !bHasCommnent) { - qDebug() << "Processing visible block at line" << line << "with opening brace, folding code"; + qCDebug(appLog) << "Processing visible block at line" << line << "with opening brace, folding code"; getNeedControlLine(line - 1, false); document()->adjustSize(); @@ -7110,11 +7111,11 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) m_pLeftAreaWidget->updateCodeFlod(); m_pLeftAreaWidget->updateLineNumber(); this->setLineWrapMode(curMode); - qDebug() << "Code fold completed for visible block at line" << line; + qCDebug(appLog) << "Code fold completed for visible block at line" << line; viewport()->update(); } else if (!document()->findBlockByNumber(line).isVisible() && document()->findBlockByNumber(line - 1).text().contains("{") && !bHasCommnent) { - qDebug() << "Processing hidden block at line" << line << "with opening brace, unfolding code"; + qCDebug(appLog) << "Processing hidden block at line" << line << "with opening brace, unfolding code"; getNeedControlLine(line - 1, true); document()->adjustSize(); @@ -7127,10 +7128,10 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) m_pLeftAreaWidget->updateCodeFlod(); m_pLeftAreaWidget->updateLineNumber(); this->setLineWrapMode(curMode); - qDebug() << "Code unfold completed for hidden block at line" << line; + qCDebug(appLog) << "Code unfold completed for hidden block at line" << line; viewport()->update(); } else { - qDebug() << "No fold/unfold action needed for line" << line; + qCDebug(appLog) << "No fold/unfold action needed for line" << line; //其他不做处理 } @@ -7311,7 +7312,7 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) } if (currentIndex == -1) { - qWarning() << " can not find current item in tab order list , need check 'Mark Color Menu' tab order setting!"; + qCWarning(appLog) << " can not find current item in tab order list , need check 'Mark Color Menu' tab order setting!"; return; } @@ -7342,7 +7343,7 @@ bool TextEdit::eventFilter(QObject *object, QEvent *event) if (nextAction != nullptr) { menuGuard->setActiveAction(nextAction); } else { - qWarning() << " can not find valid item , need check 'Mark Color Menu' tab order setting!"; + qCWarning(appLog) << " can not find valid item , need check 'Mark Color Menu' tab order setting!"; } } }); @@ -9121,7 +9122,7 @@ bool TextEdit::blockContainStrBrackets(int line) */ bool TextEdit::findFoldBlock(int line, QTextBlock &beginBlock, QTextBlock &endBlock, QTextBlock &curBlock) { - qDebug() << "Finding fold block for line" << line; + qCDebug(appLog) << "Finding fold block for line" << line; //使用统一 折叠判断算法 根据左右"{""}"高亮算法 QTextDocument *doc = document(); //获取行号对应文本块 @@ -9133,7 +9134,7 @@ bool TextEdit::findFoldBlock(int line, QTextBlock &beginBlock, QTextBlock &endBl //如果是第一行不包括左括弧"{" if (line == 0 && !curBlock.text().contains("{")) { - qDebug() << "First line without opening brace, moving to next block"; + qCDebug(appLog) << "First line without opening brace, moving to next block"; curBlock = curBlock.next(); } @@ -9169,17 +9170,17 @@ bool TextEdit::findFoldBlock(int line, QTextBlock &beginBlock, QTextBlock &endBl } else { if (c == begin) { braceDepth++; - qDebug() << "Found opening brace at position" << position << ", depth now" << braceDepth; + qCDebug(appLog) << "Found opening brace at position" << position << ", depth now" << braceDepth; } else if (c == end) { braceDepth--; - qDebug() << "Found closing brace at position" << position << ", depth now" << braceDepth; + qCDebug(appLog) << "Found closing brace at position" << position << ", depth now" << braceDepth; if (0 == braceDepth) { bracketEndCursor = QTextCursor(doc); bracketEndCursor.setPosition(position); bracketEndCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); endBlock = bracketEndCursor.block(); - qDebug() << "Matching closing brace found at line" << endBlock.blockNumber() << "position" << position; + qCDebug(appLog) << "Matching closing brace found at line" << endBlock.blockNumber() << "position" << position; break; } } else if ('"' == c) { @@ -9191,7 +9192,7 @@ bool TextEdit::findFoldBlock(int line, QTextBlock &beginBlock, QTextBlock &endBl } bool result = (0 == braceDepth); - qDebug() << "Fold block search result:" << result << "for line" << line << "ending at line" << endBlock.blockNumber(); + qCDebug(appLog) << "Fold block search result:" << result << "for line" << line << "ending at line" << endBlock.blockNumber(); return result; } diff --git a/src/editor/editwrapper.cpp b/src/editor/editwrapper.cpp index f86424631..1f5ed004b 100644 --- a/src/editor/editwrapper.cpp +++ b/src/editor/editwrapper.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "editwrapper.h" #include "leftareaoftextedit.h" #include "drecentmanager.h" @@ -71,24 +72,24 @@ class ParseFileEvent : public QEvent ParseFileEvent::ParseFileEvent() : QEvent(static_cast(EParseFile)) { - qDebug() << "ParseFileEvent constructor"; + qCDebug(appLog) << "ParseFileEvent constructor"; } ParseFileEvent::~ParseFileEvent() { - qDebug() << "ParseFileEvent destructor"; + qCDebug(appLog) << "ParseFileEvent destructor"; } ParseFileEvent *ParseFileEvent::clone() const { - qDebug() << "ParseFileEvent clone"; + qCDebug(appLog) << "ParseFileEvent clone"; // 创建克隆对象,复制数据(浅拷贝) ParseFileEvent *cloneEvent = new ParseFileEvent; cloneEvent->m_contentData = this->m_contentData; cloneEvent->m_alreadyReadOffset = this->m_alreadyReadOffset; cloneEvent->m_cursor = this->m_cursor; cloneEvent->m_codec = this->m_codec; - qDebug() << "ParseFileEvent clone exit"; + qCDebug(appLog) << "ParseFileEvent clone exit"; return cloneEvent; } @@ -101,7 +102,7 @@ EditWrapper::EditWrapper(Window *window, QWidget *parent) m_pWaringNotices(new WarningNotices(WarningNotices::ResidentType, this)) { - qDebug() << "EditWrapper constructor"; + qCDebug(appLog) << "EditWrapper constructor"; // 更新单独添加的高亮格式文件 m_Repository.addCustomSearchPath(KF5_HIGHLIGHT_PATH); @@ -182,30 +183,30 @@ EditWrapper::EditWrapper(Window *window, QWidget *parent) connect(m_pWaringNotices, &WarningNotices::editAnywayBtnClicked, this, &EditWrapper::onEditAnyway); // NOTE: 文本高亮会触发重新布局,与界面布局(拖拽、放大窗口)变更时的布局操作冲突,因此调整更新顺序,在布局后刷新高亮 connect(m_pTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, this, [this](int) { - qDebug() << "EditWrapper connect verticalScrollBar valueChanged"; + qCDebug(appLog) << "EditWrapper connect verticalScrollBar valueChanged"; OnUpdateHighlighter(); if ((m_pWindow->findBarIsVisiable() || m_pWindow->replaceBarIsVisiable()) && (QString::compare(m_pWindow->getKeywordForSearchAll(), m_pWindow->getKeywordForSearch(), Qt::CaseInsensitive) == 0)) { - qDebug() << "EditWrapper connect verticalScrollBar valueChanged, highlightKeywordInView"; + qCDebug(appLog) << "EditWrapper connect verticalScrollBar valueChanged, highlightKeywordInView"; m_pTextEdit->highlightKeywordInView(m_pWindow->getKeywordForSearchAll()); } m_pTextEdit->markAllKeywordInView(); }, Qt::QueuedConnection); - qDebug() << "EditWrapper constructor exit"; + qCDebug(appLog) << "EditWrapper constructor exit"; } EditWrapper::~EditWrapper() { - qDebug() << "EditWrapper destructor"; + qCDebug(appLog) << "EditWrapper destructor"; if (m_pTextEdit != nullptr) { - qDebug() << "EditWrapper destructor, m_pTextEdit not nullptr"; + qCDebug(appLog) << "EditWrapper destructor, m_pTextEdit not nullptr"; disconnect(m_pTextEdit); delete m_pTextEdit; m_pTextEdit = nullptr; } if (m_pBottomBar != nullptr) { - qDebug() << "EditWrapper destructor, m_pBottomBar not nullptr"; + qCDebug(appLog) << "EditWrapper destructor, m_pBottomBar not nullptr"; disconnect(m_pBottomBar); delete m_pBottomBar; m_pBottomBar = nullptr; @@ -216,31 +217,31 @@ EditWrapper::~EditWrapper() // delete m_pWaringNotices; // m_pWaringNotices = nullptr; // } - qDebug() << "EditWrapper destructor exit"; + qCDebug(appLog) << "EditWrapper destructor exit"; } void EditWrapper::setQuitFlag() { - qDebug() << "EditWrapper setQuitFlag"; + qCDebug(appLog) << "EditWrapper setQuitFlag"; m_bQuit = true; - qDebug() << "EditWrapper setQuitFlag exit"; + qCDebug(appLog) << "EditWrapper setQuitFlag exit"; } bool EditWrapper::isQuit() { - qDebug() << "EditWrapper isQuit"; + qCDebug(appLog) << "EditWrapper isQuit"; return m_bQuit; } bool EditWrapper::getFileLoading() { - qDebug() << "EditWrapper getFileLoading"; + qCDebug(appLog) << "EditWrapper getFileLoading"; return (m_bQuit || m_bFileLoading); } void EditWrapper::openFile(const QString &filepath, QString qstrTruePath, bool bIsTemFile) { - qDebug() << "Opening file:" << filepath << "Real path:" << qstrTruePath << "Is temp:" << bIsTemFile; + qCDebug(appLog) << "Opening file:" << filepath << "Real path:" << qstrTruePath << "Is temp:" << bIsTemFile; m_bIsTemFile = bIsTemFile; // update file path. @@ -251,17 +252,17 @@ void EditWrapper::openFile(const QString &filepath, QString qstrTruePath, bool b if (!bIsTemFile && !isDraftFile()) { QString absPath = QFileInfo(qstrTruePath).absolutePath(); - qDebug() << "EditWrapper openFile, Setting save paths to:" << absPath; + qCDebug(appLog) << "EditWrapper openFile, Setting save paths to:" << absPath; Settings::instance()->setSavePath(PathSettingWgt::LastOptBox, absPath); Settings::instance()->setSavePath(PathSettingWgt::CurFileBox, absPath); } FileLoadThread *thread = new FileLoadThread(filepath); - qDebug() << "Created file load thread for:" << filepath; + qCDebug(appLog) << "Created file load thread for:" << filepath; // 优先使用历史记录的编码 QByteArray storedEncode = TextEdit::getStoredEncode(filepath); if (!storedEncode.isEmpty()) { - qDebug() << "Using stored encoding from history:" << storedEncode; + qCDebug(appLog) << "Using stored encoding from history:" << storedEncode; thread->setEncodeHint(storedEncode); } // begin to load the file. @@ -279,39 +280,39 @@ void EditWrapper::openFile(const QString &filepath, QString qstrTruePath, bool b */ bool EditWrapper::readFile(QByteArray encode) { - qDebug() << "Reading file with encoding:" << encode; + qCDebug(appLog) << "Reading file with encoding:" << encode; QString filePath = m_pTextEdit->getTruePath(); - qDebug() << "Reading file:" << filePath << "with encode:" << encode; + qCDebug(appLog) << "Reading file:" << filePath << "with encode:" << encode; QFile file(filePath); if (file.open(QIODevice::ReadOnly)) { - qDebug() << "File opened successfully"; + qCDebug(appLog) << "File opened successfully"; QByteArray fileContent = file.readAll(); QByteArray newEncode = encode; if (newEncode.isEmpty()) { - qDebug() << "Auto detecting file encoding"; + qCDebug(appLog) << "Auto detecting file encoding"; // 接口修改,补充文件头内容,最多读取1MB文件头数据 newEncode = DetectCode::GetFileEncodingFormat( m_pTextEdit->getFilePath(), fileContent.left(DATA_SIZE_1024 * DATA_SIZE_1024)); - qDebug() << "Detected file encoding:" << newEncode; + qCDebug(appLog) << "Detected file encoding:" << newEncode; m_sFirstEncode = newEncode; } QByteArray Outdata; bool encodeSuccess = DetectCode::ChangeFileEncodingFormat(fileContent, Outdata, newEncode, QString("UTF-8")); if (!encodeSuccess) { - qWarning() << "EditWrapper readFile, Failed to convert file encoding"; + qCWarning(appLog) << "EditWrapper readFile, Failed to convert file encoding"; return false; } - qDebug() << "File encoding converted successfully"; + qCDebug(appLog) << "File encoding converted successfully"; loadContent(Outdata); file.close(); m_sCurEncode = newEncode; updateModifyStatus(false); - qDebug() << "EditWrapper readFile exit, return true"; + qCDebug(appLog) << "EditWrapper readFile exit, return true"; return true; } - qDebug() << "EditWrapper readFile exit, return false"; + qCDebug(appLog) << "EditWrapper readFile exit, return false"; return false; } @@ -323,7 +324,7 @@ bool EditWrapper::readFile(QByteArray encode) */ bool EditWrapper::saveAsFile(const QString &newFilePath, const QByteArray &encodeName) { - qDebug() << "Attempting to save file to:" << newFilePath << "with encoding:" << encodeName; + qCDebug(appLog) << "Attempting to save file to:" << newFilePath << "with encoding:" << encodeName; // Use TextFileSaver for safe file saving QPointer guard(this); @@ -338,7 +339,7 @@ bool EditWrapper::saveAsFile(const QString &newFilePath, const QByteArray &encod return false; } if (!saveSuccess) { - qWarning() << "Failed to save file:" << newFilePath << "Error:" << saver.errorString(); + qCWarning(appLog) << "Failed to save file:" << newFilePath << "Error:" << saver.errorString(); QWidget *curWidget = this->window()->getStackedWgt()->currentWidget(); if (curWidget) { DMessageManager::instance()->sendMessage( @@ -347,20 +348,20 @@ bool EditWrapper::saveAsFile(const QString &newFilePath, const QByteArray &encod QString(tr("You do not have permission to save %1")).arg(QFileInfo(newFilePath).fileName()) ); } - qDebug() << "EditWrapper saveAsFile, Failed to save file:" << newFilePath << "Error:" << saver.errorString(); + qCDebug(appLog) << "EditWrapper saveAsFile, Failed to save file:" << newFilePath << "Error:" << saver.errorString(); return false; } QFileInfo fi(filePath()); m_tModifiedDateTime = fi.lastModified(); - qDebug() << "EditWrapper saveAsFile, save file success, return true"; + qCDebug(appLog) << "EditWrapper saveAsFile, save file success, return true"; return true; } bool EditWrapper::saveAsFile() { - qDebug() << "EditWrapper saveAsFile"; + qCDebug(appLog) << "EditWrapper saveAsFile"; // Create save file dialog DFileDialog dialog(this, tr("Save")); dialog.setAcceptMode(QFileDialog::AcceptSave); @@ -375,7 +376,7 @@ bool EditWrapper::saveAsFile() if (QDialog::Accepted == mode) { const QString newFilePath = dialog.selectedFiles().value(0); if (newFilePath.isEmpty()) { - qDebug() << "EditWrapper saveAsFile, newFilePath is empty, return false"; + qCDebug(appLog) << "EditWrapper saveAsFile, newFilePath is empty, return false"; return false; } @@ -387,14 +388,14 @@ bool EditWrapper::saveAsFile() saver.setQuitFlag(&m_bQuit); if (!saver.save()) { - qWarning() << "EditWrapper saveAsFile, Failed to save file:" << saver.errorString(); + qCWarning(appLog) << "EditWrapper saveAsFile, Failed to save file:" << saver.errorString(); return false; } - qDebug() << "EditWrapper saveAsFile, save file success, return true"; + qCDebug(appLog) << "EditWrapper saveAsFile, save file success, return true"; return true; } - qDebug() << "EditWrapper saveAsFile, save file failed, return false"; + qCDebug(appLog) << "EditWrapper saveAsFile, save file failed, return false"; return false; } @@ -405,17 +406,17 @@ bool EditWrapper::saveAsFile() */ bool EditWrapper::reloadFileEncode(QByteArray encode) { - qDebug() << "Reloading file with new encoding:" << encode.size(); + qCDebug(appLog) << "Reloading file with new encoding:" << encode.size(); //切换编码相同不重写加载 if (m_sCurEncode == encode) { - qDebug() << "Encoding unchanged, skipping reload"; + qCDebug(appLog) << "Encoding unchanged, skipping reload"; return false; } //草稿文件 空白文件不保存 if (Utils::isDraftFile(m_pTextEdit->getFilePath()) && m_pTextEdit->toPlainText().isEmpty()) { - qDebug() << "EditWrapper reloadFileEncode, isDraftFile and toPlainText is empty, return true"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, isDraftFile and toPlainText is empty, return true"; m_sCurEncode = encode; m_sFirstEncode = encode; return true; @@ -425,13 +426,13 @@ bool EditWrapper::reloadFileEncode(QByteArray encode) auto tabname = this->window()->getTabbar()->currentName(); bool hasFlag = false; if (tabname.size() > 0 && "*" == tabname[0]) { - qDebug() << "EditWrapper reloadFileEncode, tabname is not empty and tabname[0] is *, hasFlag is true"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, tabname is not empty and tabname[0] is *, hasFlag is true"; hasFlag = true; } //1.如果修改切换编码提示用户是否保存,不保存重新打开文件读取.2.没有修改是否另存为 if (m_pTextEdit->getModified() || hasFlag) { - qDebug() << "EditWrapper reloadFileEncode, m_pTextEdit->getModified() or hasFlag is true"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, m_pTextEdit->getModified() or hasFlag is true"; DDialog *dialog = new DDialog(tr("Encoding changed. Do you want to save the file now?"), "", this); //dialog->setWindowFlags(dialog->windowFlags() | Qt::WindowStaysOnBottomHint); dialog->setIcon(QIcon::fromTheme("deepin-editor")); @@ -442,7 +443,7 @@ bool EditWrapper::reloadFileEncode(QByteArray encode) //关闭对话框 if (res == 0) { - qDebug() << "EditWrapper reloadFileEncode, res is 0, return false"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, res is 0, return false"; return false; } @@ -457,44 +458,44 @@ bool EditWrapper::reloadFileEncode(QByteArray encode) //保存 if (res == 1) { - qDebug() << "EditWrapper reloadFileEncode, res is 1, save file"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, res is 1, save file"; // 保存文件前缓存当前文件的编码格式,文件将按之前的编码格式保存 QString tempEncode = m_sCurEncode; //草稿文件 bool reloadSucc = false; if (Utils::isDraftFile(m_pTextEdit->getFilePath())) { - qDebug() << "EditWrapper reloadFileEncode, Utils::isDraftFile(m_pTextEdit->getFilePath())"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, Utils::isDraftFile(m_pTextEdit->getFilePath())"; QString newFilePath; if (saveDraftFile(newFilePath)) { - qDebug() << "EditWrapper reloadFileEncode, saveDraftFile(newFilePath) success"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, saveDraftFile(newFilePath) success"; reloadSucc = readFile(encode); } } else { - qDebug() << "EditWrapper reloadFileEncode, !Utils::isDraftFile(m_pTextEdit->getFilePath())"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, !Utils::isDraftFile(m_pTextEdit->getFilePath())"; if (this->window()->saveAsFile()) { - qDebug() << "EditWrapper reloadFileEncode, this->window()->saveAsFile() success"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, this->window()->saveAsFile() success"; reloadSucc = readFile(encode); } } if (reloadSucc) { - qDebug() << "EditWrapper reloadFileEncode, reloadSucc is true"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, reloadSucc is true"; // 保存成功,更新编码格式 m_pBottomBar->setEncodeName(encode); } else { - qDebug() << "EditWrapper reloadFileEncode, reloadSucc is false"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, reloadSucc is false"; // 未成功保存,复位编码格式 m_sCurEncode = tempEncode; } - qDebug() << "EditWrapper reloadFileEncode, reloadSucc:" << reloadSucc; + qCDebug(appLog) << "EditWrapper reloadFileEncode, reloadSucc:" << reloadSucc; return reloadSucc; } - qDebug() << "EditWrapper reloadFileEncode, return false"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, return false"; return false; } else { - qDebug() << "EditWrapper reloadFileEncode, readFile(encode)"; + qCDebug(appLog) << "EditWrapper reloadFileEncode, readFile(encode)"; return readFile(encode); } } @@ -506,18 +507,18 @@ bool EditWrapper::reloadFileEncode(QByteArray encode) */ void EditWrapper::reloadFileHighlight(QString definitionName) { - qDebug() << "Reloading syntax highlight with definition:" << definitionName; + qCDebug(appLog) << "Reloading syntax highlight with definition:" << definitionName; m_Definition = m_Repository.definitionForName(definitionName); if (m_Definition.isValid() && !m_Definition.filePath().isEmpty()) { - qDebug() << "EditWrapper reloadFileHighlight, m_Definition.isValid() && !m_Definition.filePath().isEmpty()"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, m_Definition.isValid() && !m_Definition.filePath().isEmpty()"; if (!m_pSyntaxHighlighter) m_pSyntaxHighlighter = new CSyntaxHighlighter(m_pTextEdit->document()); QString m_themePath = Settings::instance()->settings->option("advance.editor.theme")->value().toString(); - qDebug() << "EditWrapper reloadFileHighlight, m_themePath:" << m_themePath; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, m_themePath:" << m_themePath; if (m_themePath.contains("dark")) { - qDebug() << "EditWrapper reloadFileHighlight, m_themePath contains dark"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, m_themePath contains dark"; m_pSyntaxHighlighter->setTheme(m_Repository.defaultTheme(KSyntaxHighlighting::Repository::DarkTheme)); } else { - qDebug() << "EditWrapper reloadFileHighlight, m_themePath not contains dark"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, m_themePath not contains dark"; m_pSyntaxHighlighter->setTheme(m_Repository.defaultTheme(KSyntaxHighlighting::Repository::LightTheme)); } if (m_pSyntaxHighlighter) m_pSyntaxHighlighter->setDefinition(m_Definition); @@ -531,11 +532,11 @@ void EditWrapper::reloadFileHighlight(QString definitionName) QScrollBar *pScrollBar = m_pTextEdit->verticalScrollBar(); if (pScrollBar->maximum() > 0) { - qDebug() << "EditWrapper reloadFileHighlight, pScrollBar->maximum() > 0"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, pScrollBar->maximum() > 0"; QPoint endPoint = QPointF(0, 1.5 * m_pTextEdit->height()).toPoint(); endBlock = m_pTextEdit->cursorForPosition(endPoint).block(); } else { - qDebug() << "EditWrapper reloadFileHighlight, pScrollBar->maximum() <= 0"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, pScrollBar->maximum() <= 0"; endBlock = m_pTextEdit->document()->lastBlock(); } @@ -545,7 +546,7 @@ void EditWrapper::reloadFileHighlight(QString definitionName) for (QTextBlock var = beginBlock; var.isValid(); var = var.next()) { var.layout()->clearFormats(); if (var == endBlock) { - qDebug() << "EditWrapper reloadFileHighlight, var == endBlock, break!"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, var == endBlock, break!"; break; } } @@ -562,27 +563,27 @@ void EditWrapper::reloadFileHighlight(QString definitionName) } } } else { - qDebug() << "EditWrapper reloadFileHighlight, m_Definition.isValid() && !m_Definition.filePath().isEmpty() is false"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, m_Definition.isValid() && !m_Definition.filePath().isEmpty() is false"; // 不允许的高亮格式或无对应的高亮格式文件,例如“None”,移除高亮效果 m_bHighlighterAll = false; m_Definition = KSyntaxHighlighting::Definition(); if (m_pSyntaxHighlighter) { - qDebug() << "EditWrapper reloadFileHighlight, m_pSyntaxHighlighter is not nullptr"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, m_pSyntaxHighlighter is not nullptr"; m_pSyntaxHighlighter->deleteLater(); m_pSyntaxHighlighter = nullptr; } - qDebug() << "EditWrapper reloadFileHighlight, m_pTextEdit->setSyntaxDefinition(m_Definition)"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, m_pTextEdit->setSyntaxDefinition(m_Definition)"; m_pTextEdit->setSyntaxDefinition(m_Definition); } // 语言切换钩子(§4.4):刷新 Markdown 识别;识别丢失时按 FSM 回退(不强切默认视图) updateMarkdownRecognition(m_pTextEdit->getFilePath(), definitionName); - qDebug() << "EditWrapper reloadFileHighlight, exit"; + qCDebug(appLog) << "EditWrapper reloadFileHighlight, exit"; } void EditWrapper::reloadModifyFile() { - qDebug() << "EditWrapper reloadModifyFile"; + qCDebug(appLog) << "EditWrapper reloadModifyFile"; hideWarningNotices(); int curPos = m_pTextEdit->textCursor().position(); @@ -590,14 +591,14 @@ void EditWrapper::reloadModifyFile() int xoffset = m_pTextEdit->horizontalScrollBar()->value(); bool bIsModified = m_pTextEdit->getModified(); - qDebug() << "EditWrapper reloadModifyFile, bIsModified:" << bIsModified; + qCDebug(appLog) << "EditWrapper reloadModifyFile, bIsModified:" << bIsModified; if (m_pWindow->getTabbar()->textAt(m_pWindow->getTabbar()->currentIndex()).front() == "*") { - qDebug() << "EditWrapper reloadModifyFile, m_pWindow->getTabbar()->textAt(m_pWindow->getTabbar()->currentIndex()).front() == *"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, m_pWindow->getTabbar()->textAt(m_pWindow->getTabbar()->currentIndex()).front() == *"; bIsModified = true; } //如果文件修改提示用户是否保存 如果临时文件保存就是另存为 if (bIsModified) { - qDebug() << "EditWrapper reloadModifyFile, bIsModified is true"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, bIsModified is true"; DDialog *dialog = new DDialog(tr("Do you want to save this file?"), "", this); dialog->setWindowFlags(dialog->windowFlags() | Qt::WindowStaysOnBottomHint); dialog->setIcon(QIcon::fromTheme("deepin-editor")); @@ -609,30 +610,30 @@ void EditWrapper::reloadModifyFile() //点击关闭 if (res == 0) { - qDebug() << "EditWrapper reloadModifyFile, res is 0, return"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, res is 0, return"; return; } //不保存 if (res == 1) { - qDebug() << "EditWrapper reloadModifyFile, res is 1, readFile"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, res is 1, readFile"; //重写加载文件 readFile(); m_bIsTemFile = false; } //另存 if (res == 2) { - qDebug() << "EditWrapper reloadModifyFile, res is 2, saveAsFile"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, res is 2, saveAsFile"; //临时文件保存另存为 需要删除源草稿文件文件 if (Utils::isDraftFile(m_pTextEdit->getFilePath())) { QString newFilePath; if (!saveDraftFile(newFilePath)) { - qDebug() << "EditWrapper reloadModifyFile, saveDraftFile(newFilePath) failed, return"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, saveDraftFile(newFilePath) failed, return"; return; } } else { if (!this->window()->saveAsFile()) { - qDebug() << "EditWrapper reloadModifyFile, this->window()->saveAsFile() failed, return"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, this->window()->saveAsFile() failed, return"; return; } } @@ -642,11 +643,11 @@ void EditWrapper::reloadModifyFile() } } else { - qDebug() << "EditWrapper reloadModifyFile, bIsModified is false, readFile"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, bIsModified is false, readFile"; //重写加载文件 readFile(); } - qDebug() << "EditWrapper reloadModifyFile, setBookMarkList"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, setBookMarkList"; m_pTextEdit->setBookMarkList(QList()); QFileInfo fi(m_pTextEdit->getTruePath()); m_tModifiedDateTime = fi.lastModified(); @@ -656,12 +657,12 @@ void EditWrapper::reloadModifyFile() m_pTextEdit->setTextCursor(textcur); m_pTextEdit->verticalScrollBar()->setValue(yoffset); m_pTextEdit->horizontalScrollBar()->setValue(xoffset); - qDebug() << "EditWrapper reloadModifyFile, exit"; + qCDebug(appLog) << "EditWrapper reloadModifyFile, exit"; } QString EditWrapper::getTextEncode() { - qDebug() << "EditWrapper getTextEncode, m_sCurEncode:" << m_sCurEncode; + qCDebug(appLog) << "EditWrapper getTextEncode, m_sCurEncode:" << m_sCurEncode; return m_sCurEncode; } @@ -673,11 +674,11 @@ QString EditWrapper::getTextEncode() */ bool EditWrapper::saveFile(QByteArray encode) { - qDebug() << "EditWrapper saveFile, encode:" << encode; + qCDebug(appLog) << "EditWrapper saveFile, encode:" << encode; // 预览模式下不允许直接静默保存,交由 Window 层确认弹窗 if (m_bInvalidCharPreview) { - qDebug() << "EditWrapper saveFile, in preview mode, returning false"; + qCDebug(appLog) << "EditWrapper saveFile, in preview mode, returning false"; return false; } @@ -686,7 +687,7 @@ bool EditWrapper::saveFile(QByteArray encode) // 更新编码设置 if (!encode.isEmpty()) { - qDebug() << "EditWrapper saveFile, encode is not empty"; + qCDebug(appLog) << "EditWrapper saveFile, encode is not empty"; m_sCurEncode = encode; m_pBottomBar->setEncodeName(encode); } @@ -706,7 +707,7 @@ bool EditWrapper::saveFile(QByteArray encode) return false; } if (ok) { - qDebug() << "EditWrapper saveFile, ok is true"; + qCDebug(appLog) << "EditWrapper saveFile, ok is true"; m_sFirstEncode = m_sCurEncode; QFileInfo fi(qstrFilePath); m_tModifiedDateTime = fi.lastModified(); @@ -716,20 +717,20 @@ bool EditWrapper::saveFile(QByteArray encode) m_pTextEdit->setTextEncode(m_sCurEncode); m_pTextEdit->writeEncodeHistoryRecord(); } else { - qDebug() << "EditWrapper saveFile, ok is false"; + qCDebug(appLog) << "EditWrapper saveFile, ok is false"; DMessageManager::instance()->sendMessage( this->window()->getStackedWgt()->currentWidget(), QIcon(":/images/warning.svg"), QString(tr("You do not have permission to save %1")).arg(QFileInfo(qstrFilePath).fileName()) ); } - qDebug() << "EditWrapper saveFile, ok:" << ok; + qCDebug(appLog) << "EditWrapper saveFile, ok:" << ok; return ok; } void EditWrapper::onEditAnyway() { - qDebug() << "EditWrapper onEditAnyway, allowing edit in preview mode"; + qCDebug(appLog) << "EditWrapper onEditAnyway, allowing edit in preview mode"; m_bInvalidCharEditAllowed = true; m_pTextEdit->setReadOnly(false); m_pWaringNotices->hide(); @@ -738,7 +739,7 @@ void EditWrapper::onEditAnyway() void EditWrapper::exitInvalidCharPreview() { - qDebug() << "EditWrapper exitInvalidCharPreview, exiting preview mode"; + qCDebug(appLog) << "EditWrapper exitInvalidCharPreview, exiting preview mode"; m_bInvalidCharPreview = false; m_bInvalidCharEditAllowed = false; m_sInvalidCharOriginalPath.clear(); @@ -752,7 +753,7 @@ void EditWrapper::exitInvalidCharPreview() bool EditWrapper::forceSaveInvalidCharFile() { - qDebug() << "EditWrapper forceSaveInvalidCharFile, saving to original path:" << m_sInvalidCharOriginalPath; + qCDebug(appLog) << "EditWrapper forceSaveInvalidCharFile, saving to original path:" << m_sInvalidCharOriginalPath; QString savePath = m_sInvalidCharOriginalPath; QPointer guard(this); TextFileSaver saver(m_pTextEdit->document()); @@ -766,7 +767,7 @@ bool EditWrapper::forceSaveInvalidCharFile() return false; } if (ok) { - qDebug() << "EditWrapper forceSaveInvalidCharFile, save succeeded"; + qCDebug(appLog) << "EditWrapper forceSaveInvalidCharFile, save succeeded"; m_sFirstEncode = m_sCurEncode; QFileInfo fi(savePath); m_tModifiedDateTime = fi.lastModified(); @@ -775,18 +776,18 @@ bool EditWrapper::forceSaveInvalidCharFile() m_pTextEdit->writeEncodeHistoryRecord(); exitInvalidCharPreview(); } else { - qDebug() << "EditWrapper forceSaveInvalidCharFile, save failed"; + qCDebug(appLog) << "EditWrapper forceSaveInvalidCharFile, save failed"; } return ok; } void EditWrapper::getPlainTextContent(QByteArray &plainTextContent) { - qDebug() << "EditWrapper getPlainTextContent"; + qCDebug(appLog) << "EditWrapper getPlainTextContent"; QString strPlainText = m_pTextEdit->toPlainText(); - qDebug() << "EditWrapper getPlainTextContent, strPlainText:" << strPlainText; + qCDebug(appLog) << "EditWrapper getPlainTextContent, strPlainText:" << strPlainText; if (BottomBar::EndlineFormat::Windows == m_pBottomBar->getEndlineFormat()) { - qDebug() << "EditWrapper getPlainTextContent, BottomBar::EndlineFormat::Windows"; + qCDebug(appLog) << "EditWrapper getPlainTextContent, BottomBar::EndlineFormat::Windows"; strPlainText.replace("\n", "\r\n"); } @@ -796,7 +797,7 @@ void EditWrapper::getPlainTextContent(QByteArray &plainTextContent) /* 如果文本框里的文本内容小于等于300MB,无需分段转换 */ if (iPlainTextAllLen <= iStep) { plainTextContent = QByteArray(strPlainText.toLocal8Bit()); - qDebug() << "EditWrapper getPlainTextContent, iPlainTextAllLen <= iStep, plainTextContent:" << plainTextContent; + qCDebug(appLog) << "EditWrapper getPlainTextContent, iPlainTextAllLen <= iStep, plainTextContent:" << plainTextContent; return; } @@ -815,7 +816,7 @@ void EditWrapper::getPlainTextContent(QByteArray &plainTextContent) plainTextContent += strPlainText.mid(iSections * iStep, iResidue).toLocal8Bit(); } } - qDebug() << "EditWrapper getPlainTextContent, exit"; + qCDebug(appLog) << "EditWrapper getPlainTextContent, exit"; } /** @@ -825,7 +826,7 @@ void EditWrapper::getPlainTextContent(QByteArray &plainTextContent) */ bool EditWrapper::saveTemFile(QString qstrDir) { - qDebug() << "EditWrapper saveTemFile, qstrDir:" << qstrDir; + qCDebug(appLog) << "EditWrapper saveTemFile, qstrDir:" << qstrDir; // Use TextFileSaver for safe file saving QPointer guard(this); TextFileSaver saver(m_pTextEdit->document()); @@ -839,46 +840,46 @@ bool EditWrapper::saveTemFile(QString qstrDir) return false; } if (ok) { - qDebug() << "EditWrapper saveTemFile, ok is true"; + qCDebug(appLog) << "EditWrapper saveTemFile, ok is true"; m_sFirstEncode = m_sCurEncode; updateModifyStatus(isModified()); m_pTextEdit->setTextEncode(m_sCurEncode); m_pTextEdit->writeEncodeHistoryRecord(); } - qDebug() << "EditWrapper saveTemFile, ok:" << ok; + qCDebug(appLog) << "EditWrapper saveTemFile, ok:" << ok; return ok; } void EditWrapper::updatePath(const QString &file, QString qstrTruePath) { - qDebug() << "EditWrapper updatePath, file:" << file << "qstrTruePath:" << qstrTruePath; + qCDebug(appLog) << "EditWrapper updatePath, file:" << file << "qstrTruePath:" << qstrTruePath; if (qstrTruePath.isEmpty()) { - qDebug() << "EditWrapper updatePath, qstrTruePath is empty"; + qCDebug(appLog) << "EditWrapper updatePath, qstrTruePath is empty"; qstrTruePath = file; } - qDebug() << "EditWrapper updatePath, qstrTruePath:" << qstrTruePath; + qCDebug(appLog) << "EditWrapper updatePath, qstrTruePath:" << qstrTruePath; QFileInfo fi(qstrTruePath); m_tModifiedDateTime = fi.lastModified(); - qDebug() << "EditWrapper updatePath, m_tModifiedDateTime:" << m_tModifiedDateTime; + qCDebug(appLog) << "EditWrapper updatePath, m_tModifiedDateTime:" << m_tModifiedDateTime; m_pTextEdit->setFilePath(file); - qDebug() << "EditWrapper updatePath, m_pTextEdit->setFilePath(file)"; + qCDebug(appLog) << "EditWrapper updatePath, m_pTextEdit->setFilePath(file)"; m_pTextEdit->setTruePath(qstrTruePath); - qDebug() << "EditWrapper updatePath, m_pTextEdit->setTruePath(qstrTruePath)"; + qCDebug(appLog) << "EditWrapper updatePath, m_pTextEdit->setTruePath(qstrTruePath)"; } bool EditWrapper::isModified() { - qDebug() << "EditWrapper isModified"; + qCDebug(appLog) << "EditWrapper isModified"; //编码改变内容没有修改也算是文件修改 // bool modified = (m_sFirstEncode != m_sCurEncode || m_pTextEdit->document()->isModified()); bool modified = m_pTextEdit->getModified(); - qDebug() << "EditWrapper isModified, modified:" << modified << "m_bIsTemFile:" << m_bIsTemFile; + qCDebug(appLog) << "EditWrapper isModified, modified:" << modified << "m_bIsTemFile:" << m_bIsTemFile; return modified | m_bIsTemFile; } bool EditWrapper::isDraftFile() { - qDebug() << "EditWrapper isDraftFile"; + qCDebug(appLog) << "EditWrapper isDraftFile"; return Utils::isDraftFile(m_pTextEdit->getFilePath()); } @@ -887,19 +888,19 @@ bool EditWrapper::isDraftFile() */ bool EditWrapper::isBackupFile() { - qDebug() << "EditWrapper isBackupFile"; + qCDebug(appLog) << "EditWrapper isBackupFile"; return Utils::isBackupFile(m_pTextEdit->getFilePath()); } bool EditWrapper::isPlainTextEmpty() { - qDebug() << "EditWrapper isPlainTextEmpty"; + qCDebug(appLog) << "EditWrapper isPlainTextEmpty"; return m_pTextEdit->document()->isEmpty(); } bool EditWrapper::isTemFile() { - qDebug() << "EditWrapper isTemFile"; + qCDebug(appLog) << "EditWrapper isTemFile"; return m_bIsTemFile; } @@ -911,7 +912,7 @@ bool EditWrapper::isTemFile() */ bool EditWrapper::saveDraftFile(QString &newFilePath) { - qDebug() << "EditWrapper saveDraftFile, newFilePath:" << newFilePath; + qCDebug(appLog) << "EditWrapper saveDraftFile, newFilePath:" << newFilePath; DFileDialog dialog(this, tr("Save")); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setDirectory(QDir::homePath()); @@ -935,7 +936,7 @@ bool EditWrapper::saveDraftFile(QString &newFilePath) hideWarningNotices(); if (mode == 1) { - qDebug() << "EditWrapper saveDraftFile, mode is 1"; + qCDebug(appLog) << "EditWrapper saveDraftFile, mode is 1"; // Get selected encoding and file path const QByteArray encode = dialog.getComboBoxValue(QObject::tr("Encoding")).toUtf8(); newFilePath = dialog.selectedFiles().value(0); @@ -949,7 +950,7 @@ bool EditWrapper::saveDraftFile(QString &newFilePath) saver.setEndlineFormat(m_pBottomBar->getEndlineFormat() == BottomBar::EndlineFormat::Windows); if (!saver.save()) { - qDebug() << "EditWrapper saveDraftFile, saver.save() failed"; + qCDebug(appLog) << "EditWrapper saveDraftFile, saver.save() failed"; return false; } @@ -961,77 +962,77 @@ bool EditWrapper::saveDraftFile(QString &newFilePath) m_bIsTemFile = false; m_pTextEdit->setTextEncode(m_sCurEncode); m_pTextEdit->writeEncodeHistoryRecord(); - qDebug() << "EditWrapper saveDraftFile, saver.save() success"; + qCDebug(appLog) << "EditWrapper saveDraftFile, saver.save() success"; return true; } - qDebug() << "EditWrapper saveDraftFile, mode is not 1, return false"; + qCDebug(appLog) << "EditWrapper saveDraftFile, mode is not 1, return false"; return false; } void EditWrapper::hideWarningNotices() { - qDebug() << "EditWrapper hideWarningNotices"; + qCDebug(appLog) << "EditWrapper hideWarningNotices"; if (m_pWaringNotices->isVisible()) { - qDebug() << "EditWrapper hideWarningNotices, m_pWaringNotices->isVisible()"; + qCDebug(appLog) << "EditWrapper hideWarningNotices, m_pWaringNotices->isVisible()"; m_pWaringNotices->hide(); } - qDebug() << "EditWrapper hideWarningNotices, exit"; + qCDebug(appLog) << "EditWrapper hideWarningNotices, exit"; } //除草稿文件 检查文件是否被删除,是否被修复 void EditWrapper::checkForReload() { - qDebug() << "EditWrapper checkForReload"; + qCDebug(appLog) << "EditWrapper checkForReload"; if (Utils::isDraftFile(m_pTextEdit->getTruePath())) { - qDebug() << "EditWrapper checkForReload, Utils::isDraftFile(m_pTextEdit->getTruePath())"; + qCDebug(appLog) << "EditWrapper checkForReload, Utils::isDraftFile(m_pTextEdit->getTruePath())"; return; } QFileInfo fi(m_pTextEdit->getTruePath()); - qDebug() << "EditWrapper checkForReload, fi:" << fi; + qCDebug(appLog) << "EditWrapper checkForReload, fi:" << fi; // 使用 QPointer 检查对象是否还存在 QPointer self(this); QTimer::singleShot(50, [self, fi]() { if (self.isNull()) { - qWarning() << "EditWrapper obj is destroyed"; + qCWarning(appLog) << "EditWrapper obj is destroyed"; return; // 对象已被销毁 } if (fi.lastModified() == self->m_tModifiedDateTime || self->m_pWaringNotices->isVisible()) { - qDebug() << "EditWrapper checkForReload, fi.lastModified() == m_tModifiedDateTime || m_pWaringNotices->isVisible()"; + qCDebug(appLog) << "EditWrapper checkForReload, fi.lastModified() == m_tModifiedDateTime || m_pWaringNotices->isVisible()"; return; } - qDebug() << "EditWrapper checkForReload, fi.lastModified() != m_tModifiedDateTime && !m_pWaringNotices->isVisible()"; + qCDebug(appLog) << "EditWrapper checkForReload, fi.lastModified() != m_tModifiedDateTime && !m_pWaringNotices->isVisible()"; if (self->m_pTextEdit == nullptr) { - qWarning() << "TextEdit obj is destroyed"; + qCWarning(appLog) << "TextEdit obj is destroyed"; return; // 对象已被销毁 } QFileInfo finfo(self->m_pTextEdit->getTruePath()); - qDebug() << "EditWrapper checkForReload, finfo:" << finfo; + qCDebug(appLog) << "EditWrapper checkForReload, finfo:" << finfo; if (!finfo.exists()) { - qDebug() << "EditWrapper checkForReload, finfo.exists() is false"; + qCDebug(appLog) << "EditWrapper checkForReload, finfo.exists() is false"; self->m_pWaringNotices->setMessage(tr("File removed on the disk. Save it now?")); self->m_pWaringNotices->setSaveAsBtn(); self->m_pWaringNotices->show(); DMessageManager::instance()->sendMessage(self->m_pTextEdit, self->m_pWaringNotices); } else if (!self->m_tModifiedDateTime.toString().isEmpty() && finfo.lastModified().toString() != self->m_tModifiedDateTime.toString()) { - qDebug() << "EditWrapper checkForReload, finfo.lastModified().toString() != m_tModifiedDateTime.toString()"; + qCDebug(appLog) << "EditWrapper checkForReload, finfo.lastModified().toString() != m_tModifiedDateTime.toString()"; self->m_pWaringNotices->setMessage(tr("File has changed on disk. Reload?")); self->m_pWaringNotices->setReloadBtn(); self->m_pWaringNotices->show(); DMessageManager::instance()->sendMessage(self->m_pTextEdit, self->m_pWaringNotices); } }); - qDebug() << "EditWrapper checkForReload, exit"; + qCDebug(appLog) << "EditWrapper checkForReload, exit"; } void EditWrapper::showNotify(const QString &message, bool warning) { - qDebug() << "EditWrapper showNotify, message:" << message << "warning:" << warning; + qCDebug(appLog) << "EditWrapper showNotify, message:" << message << "warning:" << warning; if (message.isEmpty()) { - qDebug() << "EditWrapper showNotify, message is empty, return"; + qCDebug(appLog) << "EditWrapper showNotify, message is empty, return"; return; } @@ -1039,26 +1040,26 @@ void EditWrapper::showNotify(const QString &message, bool warning) QWidget *target = (m_viewMode == ViewMode::ReadView && m_isMarkdown) ? m_pReadPage : m_pTextEdit; if (!target) { - qDebug() << "EditWrapper showNotify, target is null, return"; + qCDebug(appLog) << "EditWrapper showNotify, target is null, return"; return; } if (warning || m_pTextEdit->getReadOnlyPermission() || m_pTextEdit->getReadOnlyMode()) { - qDebug() << "EditWrapper showNotify, warning || m_pTextEdit->getReadOnlyPermission() || m_pTextEdit->getReadOnlyMode()"; + qCDebug(appLog) << "EditWrapper showNotify, warning || m_pTextEdit->getReadOnlyPermission() || m_pTextEdit->getReadOnlyMode()"; #ifdef DTKWIDGET_CLASS_DSizeMode Utils::sendFloatMessageFixedFont(target, QIcon(":/images/warning.svg"), message); #else DMessageManager::instance()->sendMessage(target, QIcon(":/images/warning.svg"), message); #endif } else { - qDebug() << "EditWrapper showNotify, warning is false"; + qCDebug(appLog) << "EditWrapper showNotify, warning is false"; #ifdef DTKWIDGET_CLASS_DSizeMode Utils::sendFloatMessageFixedFont(target, QIcon(":/images/ok.svg"), message); #else DMessageManager::instance()->sendMessage(target, QIcon(":/images/ok.svg"), message); #endif } - qDebug() << "EditWrapper showNotify, exit"; + qCDebug(appLog) << "EditWrapper showNotify, exit"; } @@ -1071,7 +1072,7 @@ void EditWrapper::showNotify(const QString &message, bool warning) */ void EditWrapper::handleFilePreProcess(const QByteArray &encode, const QByteArray &content) { - qDebug() << "EditWrapper handleFilePreProcess"; + qCDebug(appLog) << "EditWrapper handleFilePreProcess"; // 重新加载处理 reinitOnFileLoad(encode); // 已进行预处理标识 @@ -1085,7 +1086,7 @@ void EditWrapper::handleFilePreProcess(const QByteArray &encode, const QByteArra QTextCodec *codec = QTextCodec::codecForName("UTF-8"); if (!codec) { - qInfo() << "QTextCodec::codecForName \"UTF-8\" return nullptr"; + qCInfo(appLog) << "QTextCodec::codecForName \"UTF-8\" return nullptr"; return; } @@ -1099,7 +1100,7 @@ void EditWrapper::handleFilePreProcess(const QByteArray &encode, const QByteArra m_pTextEdit->setLeftAreaUpdateState(TextEdit::FileOpenEnd); QApplication::restoreOverrideCursor(); - qDebug() << "EditWrapper handleFilePreProcess, exit"; + qCDebug(appLog) << "EditWrapper handleFilePreProcess, exit"; } /** @@ -1109,19 +1110,19 @@ void EditWrapper::handleFilePreProcess(const QByteArray &encode, const QByteArra */ void EditWrapper::handleFileLoadFinished(const QByteArray &encode, const QByteArray &content, bool error, bool hasNul) { - qDebug() << "File load finished. Encoding:" << encode << "Error:" << error << "Preprocessed:" << m_bHasPreProcess; + qCDebug(appLog) << "File load finished. Encoding:" << encode << "Error:" << error << "Preprocessed:" << m_bHasPreProcess; // 判断是否预加载,若已预加载,则无需重新初始化 if (!m_bHasPreProcess) { - qDebug() << "Performing initial file load initialization"; + qCDebug(appLog) << "Performing initial file load initialization"; reinitOnFileLoad(encode); } if (!error) { - qDebug() << "File content loaded successfully. Size:" << content.size() << "bytes"; + qCDebug(appLog) << "File content loaded successfully. Size:" << content.size() << "bytes"; bool flag = m_pTextEdit->getReadOnlyPermission(); if (flag == true) { - qDebug() << "EditWrapper handleFileLoadFinished, flag is true"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, flag is true"; // note: 特殊处理,由于需要TextEdit处于可编辑状态追加文件数据,临时设置非只读状态 m_pTextEdit->setReadOnly(false); } @@ -1130,7 +1131,7 @@ void EditWrapper::handleFileLoadFinished(const QByteArray &encode, const QByteAr //备份显示修改状态 if (m_bIsTemFile) { - qDebug() << "EditWrapper handleFileLoadFinished, m_bIsTemFile is true"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, m_bIsTemFile is true"; updateModifyStatus(true); } @@ -1139,19 +1140,19 @@ void EditWrapper::handleFileLoadFinished(const QByteArray &encode, const QByteAr // 加载数据 loadContent(content); if (checkPtr.isNull()) { - qDebug() << "EditWrapper handleFileLoadFinished, checkPtr is null, return"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, checkPtr is null, return"; return; } m_bFileLoading = false; if (flag == true) { - qDebug() << "EditWrapper handleFileLoadFinished, flag is true, setReadOnly(true)"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, flag is true, setReadOnly(true)"; m_pTextEdit->setReadOnly(true); } // 无效字符(NUL)预览模式初始化 if (hasNul) { - qDebug() << "EditWrapper handleFileLoadFinished, hasNul is true, entering preview mode"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, hasNul is true, entering preview mode"; m_bInvalidCharPreview = true; m_bInvalidCharEditAllowed = false; m_sInvalidCharOriginalPath = m_pTextEdit->getTruePath(); @@ -1176,12 +1177,12 @@ void EditWrapper::handleFileLoadFinished(const QByteArray &encode, const QByteAr } if (m_bQuit) { - qDebug() << "EditWrapper handleFileLoadFinished, m_bQuit is true, return"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, m_bQuit is true, return"; return; } } else { // 清除之前读取的数据 - qDebug() << "EditWrapper handleFileLoadFinished, flag is false, clear"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, flag is false, clear"; m_pTextEdit->clear(); } @@ -1209,25 +1210,25 @@ void EditWrapper::handleFileLoadFinished(const QByteArray &encode, const QByteAr QJsonDocument doucment = QJsonDocument::fromJson(temFileList.value(var).toUtf8(), &jsonError); // 解析未发生错误 if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)) { - qDebug() << "EditWrapper handleFileLoadFinished, doucment is not null"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, doucment is not null"; if (doucment.isObject()) { - qDebug() << "EditWrapper handleFileLoadFinished, doucment is object"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, doucment is object"; // JSON 文档为对象 QJsonObject object = doucment.object(); // 转化为对象 if (object.contains("localPath") || object.contains("temFilePath")) { - qDebug() << "EditWrapper handleFileLoadFinished, doucment contains localPath or temFilePath"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, doucment contains localPath or temFilePath"; // 包含指定的 key QJsonValue localPathValue = object.value("localPath"); // 获取指定 key 对应的 value QJsonValue temFilePathValue = object.value("temFilePath"); // 获取指定 key 对应的 value if (localPathValue.toString() == m_pTextEdit->getFilePath() || temFilePathValue.toString() == m_pTextEdit->getFilePath()) { - qDebug() << "EditWrapper handleFileLoadFinished, localPathValue or temFilePathValue is equal to m_pTextEdit->getFilePath()"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, localPathValue or temFilePathValue is equal to m_pTextEdit->getFilePath()"; QJsonValue value = object.value("cursorPosition"); // 获取指定 key 对应的 value if (value.isString()) { - qDebug() << "EditWrapper handleFileLoadFinished, value is string"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, value is string"; QTextCursor cursor = m_pTextEdit->textCursor(); cursor.setPosition(value.toString().toInt()); m_pTextEdit->setTextCursor(cursor); @@ -1244,12 +1245,12 @@ void EditWrapper::handleFileLoadFinished(const QByteArray &encode, const QByteAr //备份显示修改状态 if (m_bIsTemFile) { - qDebug() << "EditWrapper handleFileLoadFinished, m_bIsTemFile is true, updateModifyStatus(true)"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, m_bIsTemFile is true, updateModifyStatus(true)"; updateModifyStatus(true); } if (m_pSyntaxHighlighter) { - qDebug() << "EditWrapper handleFileLoadFinished, m_pSyntaxHighlighter is not nullptr"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, m_pSyntaxHighlighter is not nullptr"; m_pSyntaxHighlighter->setEnableHighlight(true); OnUpdateHighlighter(); } @@ -1258,21 +1259,21 @@ void EditWrapper::handleFileLoadFinished(const QByteArray &encode, const QByteAr // 提示读取错误信息 if (error) { - qDebug() << "EditWrapper handleFileLoadFinished, error is true, onReadAllocError()"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, error is true, onReadAllocError()"; // 如果文件不存在,静默处理(可能是新建文件),不显示错误提示 if (!QFileInfo::exists(m_pTextEdit->getTruePath())) { - qDebug() << "File does not exist, skipping error notification (new file scenario)"; + qCDebug(appLog) << "File does not exist, skipping error notification (new file scenario)"; } else { onReadAllocError(); } } - qDebug() << "EditWrapper handleFileLoadFinished, exit"; + qCDebug(appLog) << "EditWrapper handleFileLoadFinished, exit"; } void EditWrapper::OnThemeChangeSlot(QString theme) { - qDebug() << "EditWrapper OnThemeChangeSlot, theme:" << theme; + qCDebug(appLog) << "EditWrapper OnThemeChangeSlot, theme:" << theme; QVariantMap jsonMap = Utils::getThemeMapFromPath(theme); QString backgroundColor = jsonMap["editor-colors"].toMap()["background-color"].toString(); QString textColor = jsonMap["Normal"].toMap()["text-color"].toString(); @@ -1285,21 +1286,21 @@ void EditWrapper::OnThemeChangeSlot(QString theme) //设置编辑器 if (m_pSyntaxHighlighter) { - qDebug() << "EditWrapper OnThemeChangeSlot, m_pSyntaxHighlighter is not nullptr"; + qCDebug(appLog) << "EditWrapper OnThemeChangeSlot, m_pSyntaxHighlighter is not nullptr"; if (QColor(backgroundColor).lightness() < 128) { m_pSyntaxHighlighter->setTheme(m_Repository.defaultTheme(KSyntaxHighlighting::Repository::DarkTheme)); - qDebug() << "EditWrapper OnThemeChangeSlot, QColor(backgroundColor).lightness() < 128, setTheme(DarkTheme)"; + qCDebug(appLog) << "EditWrapper OnThemeChangeSlot, QColor(backgroundColor).lightness() < 128, setTheme(DarkTheme)"; } else { m_pSyntaxHighlighter->setTheme(m_Repository.defaultTheme(KSyntaxHighlighting::Repository::LightTheme)); - qDebug() << "EditWrapper OnThemeChangeSlot, QColor(backgroundColor).lightness() >= 128, setTheme(LightTheme)"; + qCDebug(appLog) << "EditWrapper OnThemeChangeSlot, QColor(backgroundColor).lightness() >= 128, setTheme(LightTheme)"; } m_pSyntaxHighlighter->setEnableHighlight(true); m_pSyntaxHighlighter->rehighlight(); - qDebug() << "EditWrapper OnThemeChangeSlot, m_pSyntaxHighlighter->rehighlight()"; + qCDebug(appLog) << "EditWrapper OnThemeChangeSlot, m_pSyntaxHighlighter->rehighlight()"; } m_pTextEdit->setTheme(theme); - qDebug() << "EditWrapper OnThemeChangeSlot, m_pTextEdit->setTheme(theme)"; + qCDebug(appLog) << "EditWrapper OnThemeChangeSlot, m_pTextEdit->setTheme(theme)"; // Markdown 渲染视图跟随主题(§4.7:themeMap 序列化为 CSS 变量注入渲染页) if (m_pRenderer) @@ -1308,7 +1309,7 @@ void EditWrapper::OnThemeChangeSlot(QString theme) void EditWrapper::UpdateBottomBarWordCnt(int cnt) { - qDebug() << "EditWrapper UpdateBottomBarWordCnt, cnt:" << cnt; + qCDebug(appLog) << "EditWrapper UpdateBottomBarWordCnt, cnt:" << cnt; m_pBottomBar->updateWordCount(cnt); } @@ -1318,9 +1319,9 @@ void EditWrapper::UpdateBottomBarWordCnt(int cnt) */ void EditWrapper::OnUpdateHighlighter() { - qDebug() << "EditWrapper OnUpdateHighlighter"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter"; if (m_pSyntaxHighlighter && !m_bQuit && !m_bHighlighterAll) { - qDebug() << "EditWrapper OnUpdateHighlighter, m_pSyntaxHighlighter is not nullptr"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, m_pSyntaxHighlighter is not nullptr"; QScrollBar *pScrollBar = m_pTextEdit->verticalScrollBar(); QPoint startPoint = QPoint(0, 0); QTextBlock beginBlock = m_pTextEdit->cursorForPosition(startPoint).block(); @@ -1328,17 +1329,17 @@ void EditWrapper::OnUpdateHighlighter() QTextBlock foundBlock; if (pScrollBar->maximum() > 0) { - qDebug() << "EditWrapper OnUpdateHighlighter, pScrollBar->maximum() > 0"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, pScrollBar->maximum() > 0"; QPoint endPoint = QPointF(0, 1.5 * m_pTextEdit->height()).toPoint(); endBlock = m_pTextEdit->cursorForPosition(endPoint).block(); } else { - qDebug() << "EditWrapper OnUpdateHighlighter, pScrollBar->maximum() <= 0"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, pScrollBar->maximum() <= 0"; endBlock = m_pTextEdit->document()->lastBlock(); } // 判断当前文件是否支持高亮处理 if (m_pSyntaxHighlighter->definition().isValid()) { - qDebug() << "EditWrapper OnUpdateHighlighter, m_pSyntaxHighlighter->definition().isValid()"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, m_pSyntaxHighlighter->definition().isValid()"; // NOTE: 同样需要考虑极限条件下遍历全部文本的情况 // 限制最多向上查找512个文本块 static int s_MaxFindCount = 512; @@ -1354,25 +1355,25 @@ void EditWrapper::OnUpdateHighlighter() && maxFindBlockNumber < prevBlock.blockNumber()) { // 逆序查询文本块数据,查找起始文本块 QString text = prevBlock.text(); - qDebug() << "EditWrapper OnUpdateHighlighter, text:" << text; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, text:" << text; for (int i = text.size() - 1; i >= 0; i--) { if (text.at(i) == end) { - qDebug() << "EditWrapper OnUpdateHighlighter, text.at(i) == end"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, text.at(i) == end"; braceDepth++; } else if (text.at(i) == begin) { - qDebug() << "EditWrapper OnUpdateHighlighter, text.at(i) == begin"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, text.at(i) == begin"; braceDepth--; // 防止'{'处于展示文本块中间的情况,查询不准确 if (braceDepth < 0) { - qDebug() << "EditWrapper OnUpdateHighlighter, braceDepth < 0"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, braceDepth < 0"; braceDepth = 0; } // 判断是否查找到完整折叠区域 if (0 == braceDepth && prevBlock.blockNumber() <= beginBlock.blockNumber()) { - qDebug() << "EditWrapper OnUpdateHighlighter, foundBrace"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, foundBrace"; foundBrace = true; break; } @@ -1384,28 +1385,28 @@ void EditWrapper::OnUpdateHighlighter() // 仅在查询到折叠区域更新文本块 if (foundBrace) { - qDebug() << "EditWrapper OnUpdateHighlighter, foundBrace"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, foundBrace"; foundBlock = prevBlock; } } if (!beginBlock.isValid() || !endBlock.isValid()) { - qDebug() << "EditWrapper OnUpdateHighlighter, !beginBlock.isValid() || !endBlock.isValid()"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, !beginBlock.isValid() || !endBlock.isValid()"; return; } auto rehighlightBlock = [this](const QTextBlock &block) { - qDebug() << "EditWrapper OnUpdateHighlighter, rehighlightBlock"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, rehighlightBlock"; m_pSyntaxHighlighter->rehighlightBlock(block); }; if (foundBlock.isValid() && foundBlock < beginBlock) { - qDebug() << "EditWrapper OnUpdateHighlighter, foundBlock.isValid() && foundBlock < beginBlock"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, foundBlock.isValid() && foundBlock < beginBlock"; for (QTextBlock var = foundBlock; var.isValid() && var != beginBlock; var = var.next()) { // Kate syntax highlighter 在高亮文本后会设置数据,通过此数据判断是否需要重复设置高亮 if (var.userData()) { - qDebug() << "EditWrapper OnUpdateHighlighter, var.userData()"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, var.userData()"; continue; } @@ -1415,7 +1416,7 @@ void EditWrapper::OnUpdateHighlighter() for (QTextBlock var = beginBlock; var.isValid(); var = var.next()) { if (!var.userData()) { - qDebug() << "EditWrapper OnUpdateHighlighter, rehighlightBlock"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, rehighlightBlock"; rehighlightBlock(var); } if (var == endBlock) { @@ -1423,14 +1424,14 @@ void EditWrapper::OnUpdateHighlighter() } } } - qDebug() << "EditWrapper OnUpdateHighlighter, exit"; + qCDebug(appLog) << "EditWrapper OnUpdateHighlighter, exit"; } void EditWrapper::setTemFile(bool value) { - qDebug() << "EditWrapper setTemFile, value:" << value; + qCDebug(appLog) << "EditWrapper setTemFile, value:" << value; m_bIsTemFile = value; - qDebug() << "EditWrapper setTemFile, exit"; + qCDebug(appLog) << "EditWrapper setTemFile, exit"; } void EditWrapper::setRestoreCursorPosition(int position) @@ -1440,14 +1441,14 @@ void EditWrapper::setRestoreCursorPosition(int position) void EditWrapper::updateHighlighterAll() { - qDebug() << "EditWrapper updateHighlighterAll"; + qCDebug(appLog) << "EditWrapper updateHighlighterAll"; if (m_pSyntaxHighlighter && !m_bQuit && !m_bHighlighterAll) { - qDebug() << "EditWrapper updateHighlighterAll, m_pSyntaxHighlighter is not nullptr"; + qCDebug(appLog) << "EditWrapper updateHighlighterAll, m_pSyntaxHighlighter is not nullptr"; QTextBlock beginBlock = m_pTextEdit->document()->firstBlock(); QTextBlock endBlock = m_pTextEdit->document()->lastBlock(); if (!beginBlock.isValid() || !endBlock.isValid()) { - qDebug() << "EditWrapper updateHighlighterAll, !beginBlock.isValid() || !endBlock.isValid()"; + qCDebug(appLog) << "EditWrapper updateHighlighterAll, !beginBlock.isValid() || !endBlock.isValid()"; return; } @@ -1459,18 +1460,18 @@ void EditWrapper::updateHighlighterAll() m_bHighlighterAll = true; } - qDebug() << "EditWrapper updateHighlighterAll, exit"; + qCDebug(appLog) << "EditWrapper updateHighlighterAll, exit"; } QDateTime EditWrapper::getLastModifiedTime() const { - qDebug() << "EditWrapper getLastModifiedTime"; + qCDebug(appLog) << "EditWrapper getLastModifiedTime"; return m_tModifiedDateTime; } void EditWrapper::setLastModifiedTime(const QString &time) { - qDebug() << "EditWrapper setLastModifiedTime, time:" << time; + qCDebug(appLog) << "EditWrapper setLastModifiedTime, time:" << time; // 与写入侧 toString(Qt::ISODate) 对称的显式格式解析; // 兼容历史记录中的默认 TextDate 格式,避免依赖 locale 相关默认重载 QDateTime dt = QDateTime::fromString(time, Qt::ISODate); @@ -1481,45 +1482,45 @@ void EditWrapper::setLastModifiedTime(const QString &time) } void EditWrapper::updateModifyStatus(bool bModified) { - qDebug() << "EditWrapper updateModifyStatus, bModified:" << bModified; + qCDebug(appLog) << "EditWrapper updateModifyStatus, bModified:" << bModified; if (getFileLoading()) { - qDebug() << "Skipping modify status update during file loading"; + qCDebug(appLog) << "Skipping modify status update during file loading"; return; } QString filePath = m_pTextEdit->getFilePath(); - qDebug() << "Updating modify status for:" << filePath << "New status:" << bModified; + qCDebug(appLog) << "Updating modify status for:" << filePath << "New status:" << bModified; if (!bModified) { - qDebug() << "Updating save index for:" << filePath; + qCDebug(appLog) << "Updating save index for:" << filePath; m_pTextEdit->updateSaveIndex(); } m_pTextEdit->document()->setModified(bModified); Window *pWindow = static_cast(QWidget::window()); pWindow->updateModifyStatus(filePath, bModified); - qDebug() << "EditWrapper updateModifyStatus, exit"; + qCDebug(appLog) << "EditWrapper updateModifyStatus, exit"; } void EditWrapper::updateSaveAsFileName(QString strOldFilePath, QString strNewFilePath) { - qDebug() << "EditWrapper updateSaveAsFileName, strOldFilePath:" << strOldFilePath << "strNewFilePath:" << strNewFilePath; + qCDebug(appLog) << "EditWrapper updateSaveAsFileName, strOldFilePath:" << strOldFilePath << "strNewFilePath:" << strNewFilePath; m_pWindow->updateSaveAsFileName(strOldFilePath, strNewFilePath); } //yanyuhan void EditWrapper::setLineNumberShow(bool bIsShow, bool bIsFirstShow) { - qDebug() << "EditWrapper setLineNumberShow, bIsShow:" << bIsShow << "bIsFirstShow:" << bIsFirstShow; + qCDebug(appLog) << "EditWrapper setLineNumberShow, bIsShow:" << bIsShow << "bIsFirstShow:" << bIsFirstShow; if (bIsShow && !bIsFirstShow) { - qDebug() << "EditWrapper setLineNumberShow, bIsShow && !bIsFirstShow"; + qCDebug(appLog) << "EditWrapper setLineNumberShow, bIsShow && !bIsFirstShow"; //int lineNumberAreaWidth = m_pTextEdit->getLeftAreaWidget()->m_pLineNumberArea->width(); //int leftAreaWidth = m_pTextEdit->getLeftAreaWidget()->width(); m_pTextEdit->getLeftAreaWidget()->m_pLineNumberArea->show(); //m_pTextEdit->getLeftAreaWidget()->setFixedWidth(leftAreaWidth + lineNumberAreaWidth); } else if (!bIsShow) { - qDebug() << "EditWrapper setLineNumberShow, !bIsShow"; + qCDebug(appLog) << "EditWrapper setLineNumberShow, !bIsShow"; // int lineNumberAreaWidth = m_pTextEdit->getLeftAreaWidget()->m_pLineNumberArea->width(); //int leftAreaWidth = m_pTextEdit->getLeftAreaWidget()->width(); m_pTextEdit->getLeftAreaWidget()->m_pLineNumberArea->hide(); @@ -1527,15 +1528,15 @@ void EditWrapper::setLineNumberShow(bool bIsShow, bool bIsFirstShow) } m_pTextEdit->bIsSetLineNumberWidth = bIsShow; m_pTextEdit->updateLeftAreaWidget(); - qDebug() << "EditWrapper setLineNumberShow, exit"; + qCDebug(appLog) << "EditWrapper setLineNumberShow, exit"; } //显示空白符 void EditWrapper::setShowBlankCharacter(bool ok) { - qDebug() << "EditWrapper setShowBlankCharacter, ok:" << ok; + qCDebug(appLog) << "EditWrapper setShowBlankCharacter, ok:" << ok; if (ok) { - qDebug() << "EditWrapper setShowBlankCharacter, ok is true"; + qCDebug(appLog) << "EditWrapper setShowBlankCharacter, ok is true"; QTextOption opts = m_pTextEdit->document()->defaultTextOption(); QTextOption::Flags flag = opts.flags(); flag |= QTextOption::ShowTabsAndSpaces; @@ -1543,7 +1544,7 @@ void EditWrapper::setShowBlankCharacter(bool ok) opts.setFlags(flag); m_pTextEdit->document()->setDefaultTextOption(opts); } else { - qDebug() << "EditWrapper setShowBlankCharacter, ok is false"; + qCDebug(appLog) << "EditWrapper setShowBlankCharacter, ok is false"; QTextOption opts = m_pTextEdit->document()->defaultTextOption(); QTextOption::Flags flag = opts.flags(); flag &= ~QTextOption::ShowTabsAndSpaces; @@ -1551,49 +1552,49 @@ void EditWrapper::setShowBlankCharacter(bool ok) opts.setFlags(flag); m_pTextEdit->document()->setDefaultTextOption(opts); } - qDebug() << "EditWrapper setShowBlankCharacter, exit"; + qCDebug(appLog) << "EditWrapper setShowBlankCharacter, exit"; } BottomBar *EditWrapper::bottomBar() { - qDebug() << "EditWrapper bottomBar"; + qCDebug(appLog) << "EditWrapper bottomBar"; return m_pBottomBar; } QString EditWrapper::filePath() { - qDebug() << "EditWrapper filePath"; + qCDebug(appLog) << "EditWrapper filePath"; return m_pTextEdit->getFilePath(); } TextEdit *EditWrapper::textEditor() { - qDebug() << "EditWrapper textEditor"; + qCDebug(appLog) << "EditWrapper textEditor"; return m_pTextEdit; } Window *EditWrapper::window() { - qDebug() << "EditWrapper window"; + qCDebug(appLog) << "EditWrapper window"; Window *window = static_cast(QWidget::window()); if (m_pWindow != window) { - qDebug() << "EditWrapper window, m_pWindow != window"; + qCDebug(appLog) << "EditWrapper window, m_pWindow != window"; m_pWindow = window; } - qDebug() << "EditWrapper window, return m_pWindow"; + qCDebug(appLog) << "EditWrapper window, return m_pWindow"; return m_pWindow; } void EditWrapper::customEvent(QEvent *e) { - qDebug() << "EditWrapper customEvent"; + qCDebug(appLog) << "EditWrapper customEvent"; // 处理解析文件任务,大文件不会在单次事件任务中处理,而是每次读取一部分并将下次任务抛出 if (static_cast(ParseFileEvent::EParseFile) == e->type()) { // 中途退出则不继续处理 if (m_bQuit) { - qDebug() << "EditWrapper customEvent, m_bQuit is true"; + qCDebug(appLog) << "EditWrapper customEvent, m_bQuit is true"; return; } @@ -1605,13 +1606,13 @@ void EditWrapper::customEvent(QEvent *e) // 调整最大读取长度(单次读取最大长度) if (needReadLen > EReadStepSize) { - qDebug() << "EditWrapper customEvent, needReadLen > EReadStepSize"; + qCDebug(appLog) << "EditWrapper customEvent, needReadLen > EReadStepSize"; needReadLen = EReadStepSize; } // 转码数据并插入光标位置 QByteArray text = parseEvent->m_contentData.mid(parseEvent->m_alreadyReadOffset, needReadLen); - qDebug() << "EditWrapper customEvent, text:" << text; + qCDebug(appLog) << "EditWrapper customEvent, text:" << text; QTextCodec::ConverterState state; QString data = parseEvent->m_codec->toUnicode(text.constData(), text.size(), &state); @@ -1621,13 +1622,13 @@ void EditWrapper::customEvent(QEvent *e) // 当前为首次读取 if (0 == parseEvent->m_alreadyReadOffset) { - qDebug() << "EditWrapper customEvent, 0 == parseEvent->m_alreadyReadOffset"; + qCDebug(appLog) << "EditWrapper customEvent, 0 == parseEvent->m_alreadyReadOffset"; QTextCursor firstLineCursor = m_pTextEdit->textCursor(); firstLineCursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor); m_pTextEdit->setTextCursor(firstLineCursor); //秒开界面语法高亮 OnUpdateHighlighter(); - qDebug() << "EditWrapper customEvent, OnUpdateHighlighter()"; + qCDebug(appLog) << "EditWrapper customEvent, OnUpdateHighlighter()"; } // 此次读取后的偏移量 @@ -1635,11 +1636,11 @@ void EditWrapper::customEvent(QEvent *e) // 是否已读取完成 if (parseEvent->m_contentData.length() == curReadOffset) { - qDebug() << "EditWrapper customEvent, parseEvent->m_contentData.length() == curReadOffset"; + qCDebug(appLog) << "EditWrapper customEvent, parseEvent->m_contentData.length() == curReadOffset"; // 异步读取结束 m_bAsyncReadFileFinished = true; } else { - qDebug() << "EditWrapper customEvent, parseEvent->m_contentData.length() != curReadOffset"; + qCDebug(appLog) << "EditWrapper customEvent, parseEvent->m_contentData.length() != curReadOffset"; ParseFileEvent *nextEvent = parseEvent->clone(); // 调整已读取偏移位置 nextEvent->m_alreadyReadOffset = curReadOffset; @@ -1649,31 +1650,31 @@ void EditWrapper::customEvent(QEvent *e) } catch (const std::bad_alloc &) { errorOccurred = true; - qWarning() << "Memory allocation failed"; + qCWarning(appLog) << "Memory allocation failed"; } catch (const std::exception &e) { errorOccurred = true; - qWarning() << QString("Error occurred: %1").arg(e.what()); + qCWarning(appLog) << QString("Error occurred: %1").arg(e.what()); } if (errorOccurred) { - qDebug() << "EditWrapper customEvent, errorOccurred is true"; + qCDebug(appLog) << "EditWrapper customEvent, errorOccurred is true"; m_bAsyncReadFileFinished = true; QMetaObject::invokeMethod(this, &EditWrapper::onReadAllocError, Qt::QueuedConnection); } } - qDebug() << "EditWrapper customEvent, exit"; + qCDebug(appLog) << "EditWrapper customEvent, exit"; } //支持大文本加载 界面不卡顿 秒关闭 void EditWrapper::loadContent(const QByteArray &strContent) { - qDebug() << "EditWrapper loadContent, strContent:" << strContent; + qCDebug(appLog) << "EditWrapper loadContent, strContent:" << strContent; if (m_pBottomBar != nullptr) { - qDebug() << "EditWrapper loadContent, m_pBottomBar is not nullptr"; + qCDebug(appLog) << "EditWrapper loadContent, m_pBottomBar is not nullptr"; m_pBottomBar->setChildEnabled(false); } if (m_pWindow != nullptr) { - qDebug() << "EditWrapper loadContent, m_pWindow is not nullptr"; + qCDebug(appLog) << "EditWrapper loadContent, m_pWindow is not nullptr"; m_pWindow->setPrintEnabled(false); } @@ -1692,7 +1693,7 @@ void EditWrapper::loadContent(const QByteArray &strContent) QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); if (nullptr == codec) { - qInfo() << "QTextCodec::codecForName return nullptr"; + qCInfo(appLog) << "QTextCodec::codecForName return nullptr"; return; } @@ -1705,7 +1706,7 @@ void EditWrapper::loadContent(const QByteArray &strContent) int inserted = 0; if (len > max) { - qDebug() << "EditWrapper loadContent, len > max"; + qCDebug(appLog) << "EditWrapper loadContent, len > max"; // 当读取大文件时,采用事件队列方式处理 ParseFileEvent *parseEvent = new ParseFileEvent; parseEvent->m_contentData = strContent; @@ -1733,7 +1734,7 @@ void EditWrapper::loadContent(const QByteArray &strContent) } else if (len > 0) { //初始化秒开 if (!m_bQuit && len > InitContentPos) { - qDebug() << "EditWrapper loadContent, len > InitContentPos"; + qCDebug(appLog) << "EditWrapper loadContent, len > InitContentPos"; //data = strContent.mid(0, InitContentPos); QByteArray text = strContent.mid(0, InitContentPos); data = codec->toUnicode(text.constData(), text.size(), &state); @@ -1748,7 +1749,7 @@ void EditWrapper::loadContent(const QByteArray &strContent) double progress = (inserted * 1.0) / len * 100; m_pBottomBar->setProgress(static_cast(progress)); if (!m_bQuit) { - qDebug() << "EditWrapper loadContent, !m_bQuit"; + qCDebug(appLog) << "EditWrapper loadContent, !m_bQuit"; //data = strContent.mid(InitContentPos, len - InitContentPos); QByteArray text = strContent.mid(InitContentPos, len - InitContentPos); data = codec->toUnicode(text.constData(), text.size(), &state); @@ -1758,9 +1759,9 @@ void EditWrapper::loadContent(const QByteArray &strContent) m_pBottomBar->setProgress(static_cast(progress)); } } else { - qDebug() << "EditWrapper loadContent, m_bQuit"; + qCDebug(appLog) << "EditWrapper loadContent, m_bQuit"; if (!m_bQuit) { - qDebug() << "EditWrapper loadContent, !m_bQuit"; + qCDebug(appLog) << "EditWrapper loadContent, !m_bQuit"; //cursor.insertText(strContent); data = codec->toUnicode(strContent.constData(), strContent.size(), &state); cursor.insertText(data); @@ -1776,11 +1777,11 @@ void EditWrapper::loadContent(const QByteArray &strContent) } } if (m_pWindow != nullptr) { - qDebug() << "EditWrapper loadContent, m_pWindow is not nullptr"; + qCDebug(appLog) << "EditWrapper loadContent, m_pWindow is not nullptr"; m_pWindow->setPrintEnabled(true); } if (m_pBottomBar != nullptr) { - qDebug() << "EditWrapper loadContent, m_pBottomBar is not nullptr"; + qCDebug(appLog) << "EditWrapper loadContent, m_pBottomBar is not nullptr"; m_pBottomBar->setChildEnabled(true); auto format = BottomBar::getEndlineFormat(strContent); m_pBottomBar->setEndlineMenuText(format); @@ -1788,7 +1789,7 @@ void EditWrapper::loadContent(const QByteArray &strContent) m_pTextEdit->setReadOnly(false); m_pTextEdit->setLeftAreaUpdateState(TextEdit::FileOpenEnd); QApplication::restoreOverrideCursor(); - qDebug() << "EditWrapper loadContent, exit"; + qCDebug(appLog) << "EditWrapper loadContent, exit"; } /** @@ -1797,31 +1798,31 @@ void EditWrapper::loadContent(const QByteArray &strContent) */ void EditWrapper::reinitOnFileLoad(const QByteArray &encode) { - qDebug() << "EditWrapper reinitOnFileLoad"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad"; m_Definition = m_Repository.definitionForFileName(QFileInfo(m_pTextEdit->getFilePath()).fileName().toLower()); if (m_Definition.isValid() && !m_Definition.filePath().isEmpty()) { - qDebug() << "EditWrapper reinitOnFileLoad, m_Definition.isValid() && !m_Definition.filePath().isEmpty()"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad, m_Definition.isValid() && !m_Definition.filePath().isEmpty()"; if (!m_pSyntaxHighlighter) m_pSyntaxHighlighter = new CSyntaxHighlighter(m_pTextEdit->document()); QString m_themePath = Settings::instance()->settings->option("advance.editor.theme")->value().toString(); if (m_themePath.contains("dark")) { - qDebug() << "EditWrapper reinitOnFileLoad, m_themePath contains dark"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad, m_themePath contains dark"; m_pSyntaxHighlighter->setTheme(m_Repository.defaultTheme(KSyntaxHighlighting::Repository::DarkTheme)); } else { - qDebug() << "EditWrapper reinitOnFileLoad, m_themePath does not contain dark"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad, m_themePath does not contain dark"; m_pSyntaxHighlighter->setTheme(m_Repository.defaultTheme(KSyntaxHighlighting::Repository::LightTheme)); } if (m_pSyntaxHighlighter) { - qDebug() << "EditWrapper reinitOnFileLoad, m_pSyntaxHighlighter is not nullptr"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad, m_pSyntaxHighlighter is not nullptr"; m_pSyntaxHighlighter->setDefinition(m_Definition); } m_pTextEdit->setSyntaxDefinition(m_Definition); m_pBottomBar->getHighlightMenu()->setCurrentTextOnly(m_Definition.translatedName()); - qDebug() << "EditWrapper reinitOnFileLoad, exit"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad, exit"; } if (!Utils::isDraftFile(m_pTextEdit->getFilePath())) { - qDebug() << "EditWrapper reinitOnFileLoad, !Utils::isDraftFile(m_pTextEdit->getFilePath())"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad, !Utils::isDraftFile(m_pTextEdit->getFilePath())"; DRecentData data; data.appName = "Deepin Editor"; data.appExec = "deepin-editor"; @@ -1835,15 +1836,15 @@ void EditWrapper::reinitOnFileLoad(const QByteArray &encode) // 初始化设置编码 m_sCurEncode = encode; m_sFirstEncode = encode; - qDebug() << "EditWrapper reinitOnFileLoad, exit"; + qCDebug(appLog) << "EditWrapper reinitOnFileLoad, exit"; } void EditWrapper::onReadAllocError() { - qDebug() << "EditWrapper onReadAllocError"; + qCDebug(appLog) << "EditWrapper onReadAllocError"; // 设置文本为只读模式,且不显示通知 if (!m_pTextEdit->getReadOnlyMode()) { - qDebug() << "EditWrapper onReadAllocError, !m_pTextEdit->getReadOnlyMode()"; + qCDebug(appLog) << "EditWrapper onReadAllocError, !m_pTextEdit->getReadOnlyMode()"; m_pTextEdit->toggleReadOnlyMode(true); } @@ -1851,22 +1852,22 @@ void EditWrapper::onReadAllocError() m_pWaringNotices->clearBtn(); m_pWaringNotices->show(); DMessageManager::instance()->sendMessage(m_pTextEdit, m_pWaringNotices); - qDebug() << "EditWrapper onReadAllocError, exit"; + qCDebug(appLog) << "EditWrapper onReadAllocError, exit"; } void EditWrapper::clearDoubleCharaterEncode() { - qDebug() << "EditWrapper clearDoubleCharaterEncode"; + qCDebug(appLog) << "EditWrapper clearDoubleCharaterEncode"; if (QFileInfo(filePath()).baseName().contains("double") || QFileInfo(filePath()).baseName().contains("user") || QFileInfo(filePath()).baseName().contains("four")) { if (QFileInfo(filePath()).size() > 500 * 1024) { - qDebug() << "EditWrapper size > 500 * 1024, return"; + qCDebug(appLog) << "EditWrapper size > 500 * 1024, return"; return; } emit sigClearDoubleCharaterEncode(); } - qDebug() << "EditWrapper clearDoubleCharaterEncode, exit"; + qCDebug(appLog) << "EditWrapper clearDoubleCharaterEncode, exit"; } // diff --git a/src/editor/endlineformatcommond.cpp b/src/editor/endlineformatcommond.cpp index c277bda55..6a8180ff6 100644 --- a/src/editor/endlineformatcommond.cpp +++ b/src/editor/endlineformatcommond.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2019 - 2023 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2019-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "endlineformatcommond.h" #include EndlineFormartCommand::EndlineFormartCommand(TextEdit* edit,BottomBar* bar,BottomBar::EndlineFormat from,BottomBar::EndlineFormat to): @@ -10,22 +11,22 @@ EndlineFormartCommand::EndlineFormartCommand(TextEdit* edit,BottomBar* bar,Botto m_from(from), m_to(to) { - qDebug() << "EndlineFormartCommand created - edit:" << edit + qCDebug(appLog) << "EndlineFormartCommand created - edit:" << edit << "bar:" << bar << "from:" << from << "to:" << to; } EndlineFormartCommand::~EndlineFormartCommand() { - qDebug() << "EndlineFormartCommand destroyed"; + qCDebug(appLog) << "EndlineFormartCommand destroyed"; } void EndlineFormartCommand::undo() { - qInfo() << "EndlineFormartCommand undo - setting format to:" << m_from; + qCInfo(appLog) << "EndlineFormartCommand undo - setting format to:" << m_from; m_bar->setEndlineMenuText(m_from); } void EndlineFormartCommand::redo() { - qInfo() << "EndlineFormartCommand redo - setting format to:" << m_to; + qCInfo(appLog) << "EndlineFormartCommand redo - setting format to:" << m_to; auto cursor = m_edit->textCursor(); auto pos = cursor.position(); cursor.insertText(" "); diff --git a/src/editor/indenttextcommond.cpp b/src/editor/indenttextcommond.cpp index 3051cfc57..c0c7ec6cc 100644 --- a/src/editor/indenttextcommond.cpp +++ b/src/editor/indenttextcommond.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "indenttextcommond.h" #include "dtextedit.h" #include @@ -13,19 +14,19 @@ IndentTextCommand::IndentTextCommand(TextEdit* edit,int startpos,int endpos,int m_startline(startline), m_endline(endline) { - qDebug() << "IndentTextCommand created - startpos:" << startpos + qCDebug(appLog) << "IndentTextCommand created - startpos:" << startpos << "endpos:" << endpos << "lines:" << startline << "-" << endline << "hasSelection:" << m_edit->textCursor().hasSelection(); m_hasselected = m_edit->textCursor().hasSelection(); } IndentTextCommand::~IndentTextCommand() { - qDebug() << "IndentTextCommand destroyed"; + qCDebug(appLog) << "IndentTextCommand destroyed"; } void IndentTextCommand::redo() { - qInfo() << "IndentTextCommand redo - adding indents to lines:" + qCInfo(appLog) << "IndentTextCommand redo - adding indents to lines:" << m_startline << "-" << m_endline; auto cursor = m_edit->textCursor(); @@ -40,37 +41,37 @@ void IndentTextCommand::redo() //reset selection. if(m_hasselected){ - qDebug() << "IndentTextCommand redo, m_hasselected"; + qCDebug(appLog) << "IndentTextCommand redo, m_hasselected"; if(m_startline == m_endline){ - qDebug() << "IndentTextCommand redo, m_startline == m_endline"; + qCDebug(appLog) << "IndentTextCommand redo, m_startline == m_endline"; cursor.setPosition(m_startpos); cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock,QTextCursor::KeepAnchor); m_edit->setTextCursor(cursor); } else{ - qDebug() << "IndentTextCommand redo, m_startline != m_endline"; + qCDebug(appLog) << "IndentTextCommand redo, m_startline != m_endline"; cursor.setPosition(m_startpos+1); cursor.setPosition(m_endpos + m_endline - m_startline +1,QTextCursor::KeepAnchor); m_edit->setTextCursor(cursor); } } - qDebug() << "IndentTextCommand redo exit"; + qCDebug(appLog) << "IndentTextCommand redo exit"; } void IndentTextCommand::undo() { - qInfo() << "IndentTextCommand undo - removing indents from lines:" + qCInfo(appLog) << "IndentTextCommand undo - removing indents from lines:" << m_startline << "-" << m_endline; auto cursor = m_edit->textCursor(); //delete "\t" in front of multiple lines. cursor.setPosition(m_startpos); for(int i=m_startline;i<=m_endline;i++){ - qDebug() << "IndentTextCommand undo, i:" << i; + qCDebug(appLog) << "IndentTextCommand undo, i:" << i; cursor.movePosition(QTextCursor::StartOfBlock); cursor.deleteChar(); @@ -79,12 +80,12 @@ void IndentTextCommand::undo() //reset selection if(m_hasselected){ - qDebug() << "IndentTextCommand undo, m_hasselected"; + qCDebug(appLog) << "IndentTextCommand undo, m_hasselected"; cursor.setPosition(m_startpos); cursor.setPosition(m_endpos,QTextCursor::KeepAnchor); m_edit->setTextCursor(cursor); } - qDebug() << "IndentTextCommand undo exit"; + qCDebug(appLog) << "IndentTextCommand undo exit"; } UnindentTextCommand::UnindentTextCommand(TextEdit* edit,int startpos,int endpos,int startline,int endline,int tabSpaceNumber): @@ -95,7 +96,7 @@ UnindentTextCommand::UnindentTextCommand(TextEdit* edit,int startpos,int endpos, m_endline(endline), m_tabSpaceNumber(tabSpaceNumber) { - qDebug() << "UnindentTextCommand created - startpos:" << startpos + qCDebug(appLog) << "UnindentTextCommand created - startpos:" << startpos << "endpos:" << endpos << "lines:" << startline << "-" << endline << "hasSelection:" << m_edit->textCursor().hasSelection(); m_hasselected = m_edit->textCursor().hasSelection(); @@ -104,12 +105,12 @@ UnindentTextCommand::UnindentTextCommand(TextEdit* edit,int startpos,int endpos, UnindentTextCommand::~UnindentTextCommand() { - qDebug() << "UnindentTextCommand destroyed"; + qCDebug(appLog) << "UnindentTextCommand destroyed"; } void UnindentTextCommand::redo() { - qInfo() << "UnindentTextCommand redo - removing indents from lines:" + qCInfo(appLog) << "UnindentTextCommand redo - removing indents from lines:" << m_startline << "-" << m_endline; auto cursor = m_edit->textCursor(); @@ -150,9 +151,9 @@ void UnindentTextCommand::redo() //reset selection. if(m_hasselected){ - qDebug() << "UnindentTextCommand redo, m_hasselected, totalRemoved:" << totalRemoved; + qCDebug(appLog) << "UnindentTextCommand redo, m_hasselected, totalRemoved:" << totalRemoved; if(m_startline == m_endline){ - qDebug() << "UnindentTextCommand redo, m_startline == m_endline"; + qCDebug(appLog) << "UnindentTextCommand redo, m_startline == m_endline"; int newStartPos = m_startpos - m_removedChars[0]; if(newStartPos < 0) newStartPos = 0; cursor.setPosition(newStartPos); @@ -161,7 +162,7 @@ void UnindentTextCommand::redo() m_edit->setTextCursor(cursor); } else{ - qDebug() << "UnindentTextCommand redo, m_startline != m_endline"; + qCDebug(appLog) << "UnindentTextCommand redo, m_startline != m_endline"; int firstLineRemoved = m_removedChars[0]; int newStartPos = m_startpos - firstLineRemoved; int newEndPos = m_endpos - totalRemoved; @@ -175,19 +176,19 @@ void UnindentTextCommand::redo() m_edit->setTextCursor(cursor); } } - qDebug() << "UnindentTextCommand redo exit"; + qCDebug(appLog) << "UnindentTextCommand redo exit"; } void UnindentTextCommand::undo() { - qInfo() << "UnindentTextCommand undo - restoring indents to lines:" + qCInfo(appLog) << "UnindentTextCommand undo - restoring indents to lines:" << m_startline << "-" << m_endline; auto cursor = m_edit->textCursor(); //restore indentation to multiple lines. cursor.setPosition(m_startpos); for(int i=m_startline;i<=m_endline;i++){ - qDebug() << "UnindentTextCommand undo, i:" << i; + qCDebug(appLog) << "UnindentTextCommand undo, i:" << i; cursor.movePosition(QTextCursor::StartOfBlock); int removed = m_removedChars[i - m_startline]; @@ -205,10 +206,10 @@ void UnindentTextCommand::undo() //reset selection if(m_hasselected){ - qDebug() << "UnindentTextCommand undo, m_hasselected"; + qCDebug(appLog) << "UnindentTextCommand undo, m_hasselected"; cursor.setPosition(m_startpos); cursor.setPosition(m_endpos, QTextCursor::KeepAnchor); m_edit->setTextCursor(cursor); } - qDebug() << "UnindentTextCommand undo exit"; + qCDebug(appLog) << "UnindentTextCommand undo exit"; } diff --git a/src/editor/insertblockbytextcommond.cpp b/src/editor/insertblockbytextcommond.cpp index 33e62571a..7f2ee7511 100644 --- a/src/editor/insertblockbytextcommond.cpp +++ b/src/editor/insertblockbytextcommond.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2022-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "insertblockbytextcommond.h" #include "inserttextundocommand.h" #include @@ -16,7 +17,7 @@ InsertBlockByTextCommand::InsertBlockByTextCommand(const QString &text,TextEdit m_edit(edit), m_wrapper(wrapper) { - qDebug() << "InsertBlockByTextCommand created - text size:" << text.size() + qCDebug(appLog) << "InsertBlockByTextCommand created - text size:" << text.size() << "edit:" << edit << "wrapper:" << wrapper; if(nullptr == m_edit || m_text.isEmpty() || nullptr == m_wrapper) return; @@ -25,27 +26,27 @@ InsertBlockByTextCommand::InsertBlockByTextCommand(const QString &text,TextEdit if(cursor.hasSelection()){ m_selected = cursor.selectedText(); m_insertPos = std::min(cursor.anchor(),cursor.position()); - qDebug() << "Has selection - text:" << m_selected << "pos:" << m_insertPos; + qCDebug(appLog) << "Has selection - text:" << m_selected << "pos:" << m_insertPos; } } InsertBlockByTextCommand::~InsertBlockByTextCommand() { - qDebug() << "InsertBlockByTextCommand destroyed"; + qCDebug(appLog) << "InsertBlockByTextCommand destroyed"; } void InsertBlockByTextCommand::redo() { - qInfo() << "InsertBlockByTextCommand redo - inserting text block"; + qCInfo(appLog) << "InsertBlockByTextCommand redo - inserting text block"; treat(true); insertByBlock(); treat(false); - qDebug() << "InsertBlockByTextCommand redo exit"; + qCDebug(appLog) << "InsertBlockByTextCommand redo exit"; } void InsertBlockByTextCommand::undo() { - qInfo() << "InsertBlockByTextCommand undo - removing inserted text block"; + qCInfo(appLog) << "InsertBlockByTextCommand undo - removing inserted text block"; treat(true); auto cursor = m_edit->textCursor(); @@ -54,72 +55,72 @@ void InsertBlockByTextCommand::undo() cursor.deleteChar(); if(!m_selected.isEmpty()){ - qDebug() << "Restoring original selection - text:" << m_selected << "pos:" << m_insertPos; + qCDebug(appLog) << "Restoring original selection - text:" << m_selected << "pos:" << m_insertPos; cursor.setPosition(m_insertPos); cursor.insertText(m_selected); } treat(false); - qDebug() << "InsertBlockByTextCommand undo exit"; + qCDebug(appLog) << "InsertBlockByTextCommand undo exit"; } void InsertBlockByTextCommand::treat(bool isStart) { - qDebug() << "InsertBlockByTextCommand treat, isStart:" << isStart; + qCDebug(appLog) << "InsertBlockByTextCommand treat, isStart:" << isStart; if(m_wrapper!=nullptr){ - qDebug() << "InsertBlockByTextCommand treat, m_wrapper not nullptr"; + qCDebug(appLog) << "InsertBlockByTextCommand treat, m_wrapper not nullptr"; Window* window = m_wrapper->window(); BottomBar* bar = m_wrapper->bottomBar(); if(window){ - qDebug() << "InsertBlockByTextCommand treat, window not nullptr"; + qCDebug(appLog) << "InsertBlockByTextCommand treat, window not nullptr"; window->setPrintEnabled(!isStart); } if(bar){ - qDebug() << "InsertBlockByTextCommand treat, bar not nullptr"; + qCDebug(appLog) << "InsertBlockByTextCommand treat, bar not nullptr"; bar->setChildEnabled(!isStart); } } if(!isStart) { - qDebug() << "InsertBlockByTextCommand treat, connect cursorPositionChanged"; + qCDebug(appLog) << "InsertBlockByTextCommand treat, connect cursorPositionChanged"; QObject::connect(m_edit, &QPlainTextEdit::cursorPositionChanged, m_edit, &TextEdit::cursorPositionChanged); } else { - qDebug() << "InsertBlockByTextCommand treat, disconnect cursorPositionChanged"; + qCDebug(appLog) << "InsertBlockByTextCommand treat, disconnect cursorPositionChanged"; QObject::disconnect(m_edit, &QPlainTextEdit::cursorPositionChanged, m_edit, &TextEdit::cursorPositionChanged); } - qDebug() << "InsertBlockByTextCommand treat exit"; + qCDebug(appLog) << "InsertBlockByTextCommand treat exit"; } void InsertBlockByTextCommand::insertByBlock() { - qDebug() << "InsertBlockByTextCommand insertByBlock"; + qCDebug(appLog) << "InsertBlockByTextCommand insertByBlock"; auto cursor = m_edit->textCursor(); int block = 1 * 1024 * 1024 ; int size = m_text.size(); - qDebug() << "Inserting text by blocks - total size:" << size << "block size:" << block; + qCDebug(appLog) << "Inserting text by blocks - total size:" << size << "block size:" << block; if(size > block){ - qDebug() << "InsertBlockByTextCommand insertByBlock, size > block"; + qCDebug(appLog) << "InsertBlockByTextCommand insertByBlock, size > block"; int n = size / (block); int y = size % (block); int k=0; for(;kisQuit()){ QString insertText = m_text.mid(k*block,block); - qDebug() << "Inserting block" << k+1 << "/" << n << "size:" << insertText.size(); + qCDebug(appLog) << "Inserting block" << k+1 << "/" << n << "size:" << insertText.size(); cursor.insertText(insertText); QApplication::processEvents(); } } if(y){ - qDebug() << "InsertBlockByTextCommand insertByBlock, y:" << y; + qCDebug(appLog) << "InsertBlockByTextCommand insertByBlock, y:" << y; if(m_wrapper!=nullptr && !m_wrapper->isQuit()){ QString insertText = m_text.mid(k*block,y); - qDebug() << "Inserting final block size:" << y; + qCDebug(appLog) << "Inserting final block size:" << y; cursor.insertText(insertText); QApplication::processEvents(); } } } m_delPos = cursor.position(); - qDebug() << "Insert completed - delete position:" << m_delPos; + qCDebug(appLog) << "Insert completed - delete position:" << m_delPos; } diff --git a/src/editor/inserttextundocommand.cpp b/src/editor/inserttextundocommand.cpp index bf56461ab..6af1cbdd3 100644 --- a/src/editor/inserttextundocommand.cpp +++ b/src/editor/inserttextundocommand.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "inserttextundocommand.h" #include "dtextedit.h" #include @@ -16,7 +17,7 @@ InsertTextUndoCommand::InsertTextUndoCommand(const QTextCursor &textcursor, , m_sInsertText(text) { m_sInsertText.replace("\r\n", "\n"); - qDebug() << "InsertTextUndoCommand created"; + qCDebug(appLog) << "InsertTextUndoCommand created"; } InsertTextUndoCommand::InsertTextUndoCommand(QList &selections, @@ -29,7 +30,7 @@ InsertTextUndoCommand::InsertTextUndoCommand(QList &s , m_columnEditSelections(selections) { m_sInsertText.replace("\r\n", "\n"); - qDebug() << "InsertTextUndoCommand(multi-selection) created"; + qCDebug(appLog) << "InsertTextUndoCommand(multi-selection) created"; for (const auto &selection : m_columnEditSelections) { ColumnReplaceNode replaceNode; @@ -43,26 +44,26 @@ InsertTextUndoCommand::InsertTextUndoCommand(QList &s void InsertTextUndoCommand::undo() { - qDebug() << "InsertTextUndoCommand undo"; + qCDebug(appLog) << "InsertTextUndoCommand undo"; if (m_columnEditSelections.isEmpty()) { - qDebug() << "InsertTextUndoCommand undo, columnEditSelections empty"; + qCDebug(appLog) << "InsertTextUndoCommand undo, columnEditSelections empty"; // note that some characters appear to occupy more than 1 place m_textCursor.setPosition(m_endPostion); m_textCursor.setPosition(m_beginPostion, QTextCursor::KeepAnchor); m_textCursor.deleteChar(); if (m_selectText != QString()) { - qDebug() << "InsertTextUndoCommand undo, selectText not empty"; + qCDebug(appLog) << "InsertTextUndoCommand undo, selectText not empty"; m_textCursor.insertText(m_selectText); m_textCursor.setPosition(m_textCursor.position() - m_selectText.length(), QTextCursor::KeepAnchor); } // restore cursor position if (m_pEdit) { - qDebug() << "InsertTextUndoCommand undo, pEdit not empty"; + qCDebug(appLog) << "InsertTextUndoCommand undo, pEdit not empty"; m_pEdit->setTextCursor(m_textCursor); } } else { - qDebug() << "InsertTextUndoCommand undo, columnEditSelections not empty"; + qCDebug(appLog) << "InsertTextUndoCommand undo, columnEditSelections not empty"; Q_ASSERT_X(m_columnEditSelections.size() == m_replaces.size(), "Column editing insert undo", "column data size check"); for (int i = 0; i < m_columnEditSelections.size(); i++) { @@ -76,11 +77,11 @@ void InsertTextUndoCommand::undo() cursor.insertText(replaceNode.originText); if (replaceNode.leftToRight) { - qDebug() << "InsertTextUndoCommand undo, leftToRight"; + qCDebug(appLog) << "InsertTextUndoCommand undo, leftToRight"; cursor.setPosition(replaceNode.startPos); cursor.setPosition(replaceNode.endPos, QTextCursor::KeepAnchor); } else { - qDebug() << "InsertTextUndoCommand undo, rightToLeft"; + qCDebug(appLog) << "InsertTextUndoCommand undo, rightToLeft"; cursor.setPosition(replaceNode.endPos); cursor.setPosition(replaceNode.startPos, QTextCursor::KeepAnchor); } @@ -89,26 +90,26 @@ void InsertTextUndoCommand::undo() } if (m_pEdit && !m_columnEditSelections.isEmpty()) { - qDebug() << "InsertTextUndoCommand undo, pEdit not empty"; + qCDebug(appLog) << "InsertTextUndoCommand undo, pEdit not empty"; m_pEdit->restoreColumnEditSelection(m_columnEditSelections); m_pEdit->setTextCursor(m_columnEditSelections.last().cursor); } } - qDebug() << "InsertTextUndoCommand undo exit"; + qCDebug(appLog) << "InsertTextUndoCommand undo exit"; } void InsertTextUndoCommand::redo() { - qDebug() << "InsertTextUndoCommand redo"; + qCDebug(appLog) << "InsertTextUndoCommand redo"; if (m_columnEditSelections.isEmpty()) { - qDebug() << "InsertTextUndoCommand redo, columnEditSelections empty"; + qCDebug(appLog) << "InsertTextUndoCommand redo, columnEditSelections empty"; if (m_textCursor.hasSelection()) { - qDebug() << "InsertTextUndoCommand redo, textCursor has selection"; + qCDebug(appLog) << "InsertTextUndoCommand redo, textCursor has selection"; m_selectText = m_textCursor.selectedText(); m_textCursor.removeSelectedText(); } - qDebug() << "InsertTextUndoCommand redo, insert text"; + qCDebug(appLog) << "InsertTextUndoCommand redo, insert text"; m_textCursor.insertText(m_sInsertText); m_textCursor.setPosition(m_textCursor.position() - m_sInsertText.length(), QTextCursor::KeepAnchor); m_beginPostion = m_textCursor.selectionStart(); @@ -116,13 +117,13 @@ void InsertTextUndoCommand::redo() // restore cursor position if (m_pEdit) { - qDebug() << "InsertTextUndoCommand redo, pEdit not empty"; + qCDebug(appLog) << "InsertTextUndoCommand redo, pEdit not empty"; QTextCursor curCursor = m_pEdit->textCursor(); curCursor.setPosition(m_endPostion); m_pEdit->setTextCursor(curCursor); } } else { - qDebug() << "InsertTextUndoCommand redo, columnEditSelections not empty"; + qCDebug(appLog) << "InsertTextUndoCommand redo, columnEditSelections not empty"; Q_ASSERT_X(m_columnEditSelections.size() == m_replaces.size(), "Column editing insert undo", "column data size check"); // insert will change all text cursor @@ -138,11 +139,11 @@ void InsertTextUndoCommand::redo() cursor.insertText(m_sInsertText); if (replaceNode.leftToRight) { - qDebug() << "InsertTextUndoCommand redo, leftToRight"; + qCDebug(appLog) << "InsertTextUndoCommand redo, leftToRight"; cursor.setPosition(columnOffset + replaceNode.startPos); cursor.setPosition(columnOffset + replaceNode.startPos + m_sInsertText.size(), QTextCursor::KeepAnchor); } else { - qDebug() << "InsertTextUndoCommand redo, rightToLeft"; + qCDebug(appLog) << "InsertTextUndoCommand redo, rightToLeft"; cursor.setPosition(columnOffset + replaceNode.startPos + m_sInsertText.size()); cursor.setPosition(columnOffset + replaceNode.startPos, QTextCursor::KeepAnchor); } @@ -152,13 +153,13 @@ void InsertTextUndoCommand::redo() } if (m_pEdit && !m_columnEditSelections.isEmpty()) { - qDebug() << "InsertTextUndoCommand redo, pEdit not empty"; + qCDebug(appLog) << "InsertTextUndoCommand redo, pEdit not empty"; QTextCursor curCursor = m_pEdit->textCursor(); curCursor.setPosition(m_columnEditSelections.last().cursor.selectionEnd()); m_pEdit->setTextCursor(curCursor); } } - qDebug() << "InsertTextUndoCommand redo exit"; + qCDebug(appLog) << "InsertTextUndoCommand redo exit"; } int InsertTextUndoCommand::id() const @@ -181,12 +182,12 @@ MidButtonInsertTextUndoCommand::MidButtonInsertTextUndoCommand(const QTextCursor , m_sInsertText(text) { m_sInsertText.replace("\r\n", "\n"); - qDebug() << "MidButtonInsertTextUndoCommand created, text size:" << m_sInsertText.size() + qCDebug(appLog) << "MidButtonInsertTextUndoCommand created, text size:" << m_sInsertText.size() << "cursor pos:" << textcursor.position() << "edit:" << edit; // 中键黏贴需要构造时计算一次光标位置 m_beginPostion = m_textCursor.position(); m_endPostion = m_textCursor.position() + m_sInsertText.length(); - qDebug() << "MidButtonInsertTextUndoCommand created, beginPostion:" << m_beginPostion << "endPostion:" << m_endPostion; + qCDebug(appLog) << "MidButtonInsertTextUndoCommand created, beginPostion:" << m_beginPostion << "endPostion:" << m_endPostion; } /** @@ -194,7 +195,7 @@ MidButtonInsertTextUndoCommand::MidButtonInsertTextUndoCommand(const QTextCursor */ void MidButtonInsertTextUndoCommand::undo() { - qDebug() << "MidButtonInsertTextUndoCommand undo, removing text from" + qCDebug(appLog) << "MidButtonInsertTextUndoCommand undo, removing text from" << m_beginPostion << "to" << m_endPostion; m_textCursor.setPosition(m_endPostion); m_textCursor.setPosition(m_beginPostion, QTextCursor::KeepAnchor); @@ -202,10 +203,10 @@ void MidButtonInsertTextUndoCommand::undo() // 进行撤销/恢复时将光标移动到撤销位置 if (m_pEdit) { - qDebug() << "MidButtonInsertTextUndoCommand undo, pEdit not empty"; + qCDebug(appLog) << "MidButtonInsertTextUndoCommand undo, pEdit not empty"; m_pEdit->setTextCursor(m_textCursor); } - qDebug() << "MidButtonInsertTextUndoCommand undo exit"; + qCDebug(appLog) << "MidButtonInsertTextUndoCommand undo exit"; } /** @@ -215,21 +216,21 @@ void MidButtonInsertTextUndoCommand::undo() */ void MidButtonInsertTextUndoCommand::redo() { - qDebug() << "MidButtonInsertTextUndoCommand redo - inserting text size:" << m_sInsertText.size(); + qCDebug(appLog) << "MidButtonInsertTextUndoCommand redo - inserting text size:" << m_sInsertText.size(); m_textCursor.insertText(m_sInsertText); m_textCursor.setPosition(m_textCursor.position() - m_sInsertText.length(), QTextCursor::KeepAnchor); m_beginPostion = m_textCursor.selectionStart(); m_endPostion = m_textCursor.selectionEnd(); - qDebug() << "Inserted text at position:" << m_beginPostion << "-" << m_endPostion; + qCDebug(appLog) << "Inserted text at position:" << m_beginPostion << "-" << m_endPostion; // 进行撤销/恢复时将光标移动到撤销位置 if (m_pEdit) { - qDebug() << "MidButtonInsertTextUndoCommand redo, pEdit not empty"; + qCDebug(appLog) << "MidButtonInsertTextUndoCommand redo, pEdit not empty"; QTextCursor curCursor = m_pEdit->textCursor(); curCursor.setPosition(m_endPostion); m_pEdit->setTextCursor(curCursor); } - qDebug() << "MidButtonInsertTextUndoCommand redo exit"; + qCDebug(appLog) << "MidButtonInsertTextUndoCommand redo exit"; } /** @@ -245,7 +246,7 @@ DragInsertTextUndoCommand::DragInsertTextUndoCommand(const QTextCursor &textcurs , m_textCursor(textcursor) , m_sInsertText(text) { - qDebug() << "DragInsertTextUndoCommand created, text size:" << text.size() + qCDebug(appLog) << "DragInsertTextUndoCommand created, text size:" << text.size() << "cursor pos:" << textcursor.position() << "edit:" << edit; // 与 InsertText/MidButton 命令保持一致:归一化 CRLF, // 否则 undo 以含 \r 的长度计算删除区间会越界,导致恢复不完整 @@ -258,17 +259,17 @@ DragInsertTextUndoCommand::DragInsertTextUndoCommand(const QTextCursor &textcurs */ void DragInsertTextUndoCommand::undo() { - qDebug() << "DragInsertTextUndoCommand undo, removing text from" + qCDebug(appLog) << "DragInsertTextUndoCommand undo, removing text from" << m_beginPostion << "to" << m_beginPostion + m_sInsertText.size(); m_textCursor.setPosition(m_beginPostion); m_textCursor.setPosition(m_beginPostion + m_sInsertText.size(), QTextCursor::KeepAnchor); m_textCursor.deleteChar(); if (m_pEdit) { - qDebug() << "DragInsertTextUndoCommand undo, pEdit not empty"; + qCDebug(appLog) << "DragInsertTextUndoCommand undo, pEdit not empty"; m_pEdit->setTextCursor(m_textCursor); } - qDebug() << "DragInsertTextUndoCommand undo exit"; + qCDebug(appLog) << "DragInsertTextUndoCommand undo exit"; } /** @@ -276,20 +277,20 @@ void DragInsertTextUndoCommand::undo() */ void DragInsertTextUndoCommand::redo() { - qDebug() << "DragInsertTextUndoCommand redo - inserting text size:" << m_sInsertText.size(); + qCDebug(appLog) << "DragInsertTextUndoCommand redo - inserting text size:" << m_sInsertText.size(); if (m_beginPostion != m_textCursor.position()) { - qDebug() << "DragInsertTextUndoCommand redo, beginPostion != textCursor.position()"; + qCDebug(appLog) << "DragInsertTextUndoCommand redo, beginPostion != textCursor.position()"; m_textCursor.setPosition(m_beginPostion); } m_textCursor.insertText(m_sInsertText); - qDebug() << "Inserted text at position:" << m_beginPostion; + qCDebug(appLog) << "Inserted text at position:" << m_beginPostion; if (m_pEdit) { - qDebug() << "DragInsertTextUndoCommand redo, pEdit not empty"; + qCDebug(appLog) << "DragInsertTextUndoCommand redo, pEdit not empty"; QTextCursor curCursor = m_pEdit->textCursor(); curCursor.setPosition(m_beginPostion + m_sInsertText.size()); m_pEdit->setTextCursor(curCursor); } - qDebug() << "DragInsertTextUndoCommand redo exit"; + qCDebug(appLog) << "DragInsertTextUndoCommand redo exit"; } diff --git a/src/editor/leftareaoftextedit.cpp b/src/editor/leftareaoftextedit.cpp index b9e4a072a..36ff6fac8 100644 --- a/src/editor/leftareaoftextedit.cpp +++ b/src/editor/leftareaoftextedit.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2019 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2019-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "leftareaoftextedit.h" #include "linenumberarea.h" #include "bookmarkwidget.h" @@ -15,7 +16,7 @@ LeftAreaTextEdit::LeftAreaTextEdit(TextEdit *textEdit) : m_pTextEdit(textEdit) { - qDebug() << "LeftAreaTextEdit created with textEdit:" << textEdit; + qCDebug(appLog) << "LeftAreaTextEdit created with textEdit:" << textEdit; QHBoxLayout *pHLayout = new QHBoxLayout(this); m_pLineNumberArea = new LineNumberArea(this); m_pBookMarkArea = new BookMarkWidget(this); @@ -35,23 +36,23 @@ LeftAreaTextEdit::LeftAreaTextEdit(TextEdit *textEdit) : pHLayout->setContentsMargins(0, 0, 0, 0); pHLayout->setSpacing(0); this->setLayout(pHLayout); - qDebug() << "LeftAreaTextEdit layout initialized with 3 areas"; + qCDebug(appLog) << "LeftAreaTextEdit layout initialized with 3 areas"; } LeftAreaTextEdit::~LeftAreaTextEdit() { - qDebug() << "LeftAreaTextEdit destroyed"; + qCDebug(appLog) << "LeftAreaTextEdit destroyed"; } void LeftAreaTextEdit::lineNumberAreaPaintEvent(QPaintEvent *event) { - qDebug() << "LeftAreaTextEdit lineNumberAreaPaintEvent"; + qCDebug(appLog) << "LeftAreaTextEdit lineNumberAreaPaintEvent"; m_pTextEdit->lineNumberAreaPaintEvent(event); } int LeftAreaTextEdit::lineNumberAreaWidth() { - qDebug() << "LeftAreaTextEdit lineNumberAreaWidth"; + qCDebug(appLog) << "LeftAreaTextEdit lineNumberAreaWidth"; int digits = 1; int max = qMax(1, m_pTextEdit->document()->blockCount()); while (max >= 10) { @@ -59,90 +60,90 @@ int LeftAreaTextEdit::lineNumberAreaWidth() ++digits; } - qDebug() << "LeftAreaTextEdit lineNumberAreaWidth return"; + qCDebug(appLog) << "LeftAreaTextEdit lineNumberAreaWidth return"; return 13 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits + 40; } void LeftAreaTextEdit::bookMarkAreaPaintEvent(QPaintEvent *event) { - qDebug() << "LeftAreaTextEdit bookMarkAreaPaintEvent"; + qCDebug(appLog) << "LeftAreaTextEdit bookMarkAreaPaintEvent"; m_pTextEdit->bookMarkAreaPaintEvent(event); } void LeftAreaTextEdit::codeFlodAreaPaintEvent(QPaintEvent *event) { - qDebug() << "LeftAreaTextEdit codeFlodAreaPaintEvent"; + qCDebug(appLog) << "LeftAreaTextEdit codeFlodAreaPaintEvent"; m_pTextEdit->codeFLodAreaPaintEvent(event); } void LeftAreaTextEdit::updateLineNumber() { - qDebug() << "LeftAreaTextEdit updateLineNumber"; + qCDebug(appLog) << "LeftAreaTextEdit updateLineNumber"; if (m_pLineNumberArea) { - qDebug() << "LeftAreaTextEdit updateLineNumber m_pLineNumberArea"; + qCDebug(appLog) << "LeftAreaTextEdit updateLineNumber m_pLineNumberArea"; m_pLineNumberArea->update(); } } void LeftAreaTextEdit::updateBookMark() { - qDebug() << "LeftAreaTextEdit updateBookMark"; + qCDebug(appLog) << "LeftAreaTextEdit updateBookMark"; if (m_pBookMarkArea) { - qDebug() << "LeftAreaTextEdit updateBookMark m_pBookMarkArea"; + qCDebug(appLog) << "LeftAreaTextEdit updateBookMark m_pBookMarkArea"; m_pBookMarkArea->update(); } } void LeftAreaTextEdit::updateCodeFlod() { - qDebug() << "LeftAreaTextEdit updateCodeFlod"; + qCDebug(appLog) << "LeftAreaTextEdit updateCodeFlod"; if (m_pFlodArea) { - qDebug() << "LeftAreaTextEdit updateCodeFlod m_pFlodArea"; + qCDebug(appLog) << "LeftAreaTextEdit updateCodeFlod m_pFlodArea"; m_pFlodArea->update(); } } void LeftAreaTextEdit::updateAll() { - qDebug() << "LeftAreaTextEdit updateAll"; + qCDebug(appLog) << "LeftAreaTextEdit updateAll"; if (m_pLineNumberArea) { - qDebug() << "LeftAreaTextEdit updateAll m_pLineNumberArea"; + qCDebug(appLog) << "LeftAreaTextEdit updateAll m_pLineNumberArea"; m_pLineNumberArea->update(); } if (m_pBookMarkArea) { - qDebug() << "LeftAreaTextEdit updateAll m_pBookMarkArea"; + qCDebug(appLog) << "LeftAreaTextEdit updateAll m_pBookMarkArea"; m_pBookMarkArea->update(); } if (m_pFlodArea) { - qDebug() << "LeftAreaTextEdit updateAll m_pFlodArea"; + qCDebug(appLog) << "LeftAreaTextEdit updateAll m_pFlodArea"; m_pFlodArea->update(); } - qDebug() << "LeftAreaTextEdit updateAll exit"; + qCDebug(appLog) << "LeftAreaTextEdit updateAll exit"; } void LeftAreaTextEdit::paintEvent(QPaintEvent *event) { - qDebug() << "LeftAreaTextEdit paintEvent"; + qCDebug(appLog) << "LeftAreaTextEdit paintEvent"; QPainter painter(this); QColor bdColor; if (m_pTextEdit->getBackColor().lightness() < 128) { - qDebug() << "LeftAreaTextEdit paintEvent getBackColor lightness < 128"; + qCDebug(appLog) << "LeftAreaTextEdit paintEvent getBackColor lightness < 128"; bdColor = palette().brightText().color(); bdColor.setAlphaF(0.06); } else { - qDebug() << "LeftAreaTextEdit paintEvent getBackColor lightness >= 128"; + qCDebug(appLog) << "LeftAreaTextEdit paintEvent getBackColor lightness >= 128"; bdColor = palette().brightText().color(); bdColor.setAlphaF(0.03); } painter.fillRect(event->rect(), bdColor); - qDebug() << "LeftAreaTextEdit paintEvent exit"; + qCDebug(appLog) << "LeftAreaTextEdit paintEvent exit"; } TextEdit* LeftAreaTextEdit::getEdit() { - qDebug() << "LeftAreaTextEdit getEdit"; + qCDebug(appLog) << "LeftAreaTextEdit getEdit"; return m_pTextEdit; } diff --git a/src/editor/linenumberarea.cpp b/src/editor/linenumberarea.cpp index 33eff2ab2..090d12743 100644 --- a/src/editor/linenumberarea.cpp +++ b/src/editor/linenumberarea.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "linenumberarea.h" #include "dtextedit.h" #include "leftareaoftextedit.h" @@ -10,7 +11,7 @@ LineNumberArea::LineNumberArea(LeftAreaTextEdit *leftAreaWidget) { - qDebug() << "LineNumberArea created with leftAreaWidget:" << leftAreaWidget; + qCDebug(appLog) << "LineNumberArea created with leftAreaWidget:" << leftAreaWidget; m_leftAreaWidget = leftAreaWidget; setContentsMargins(0, 0, 0, 0); //m_textEdit = textEdit; @@ -18,12 +19,12 @@ LineNumberArea::LineNumberArea(LeftAreaTextEdit *leftAreaWidget) LineNumberArea::~LineNumberArea() { - qDebug() << "LineNumberArea destroyed"; + qCDebug(appLog) << "LineNumberArea destroyed"; } void LineNumberArea::paintEvent(QPaintEvent *e) { - //qDebug() << "LineNumberArea::paintEvent "; + //qCDebug(appLog) << "LineNumberArea::paintEvent "; m_leftAreaWidget->lineNumberAreaPaintEvent(e); //m_textEdit->lineNumberAreaPaintEvent(e); } @@ -36,7 +37,7 @@ QSize LineNumberArea::sizeHint() const void LineNumberArea::mousePressEvent(QMouseEvent *e) { - qDebug() << "LineNumberArea mousePressEvent at position:" << e->pos(); + qCDebug(appLog) << "LineNumberArea mousePressEvent at position:" << e->pos(); m_pressPoint = e->pos(); // m_leftAreaWidget->update(); m_leftAreaWidget->getEdit()->onPressedLineNumber(e->pos()); diff --git a/src/editor/markdown/markdownview.cpp b/src/editor/markdown/markdownview.cpp index 2d6fc1a69..7e62d29c7 100644 --- a/src/editor/markdown/markdownview.cpp +++ b/src/editor/markdown/markdownview.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "markdownview.h" #include "themeserializer.h" #include @@ -50,7 +51,7 @@ class MarkdownImageHandler : public QWebEngineUrlSchemeHandler path = QLatin1Char('/') + url.host() + path; QFileInfo fi(path); if (!fi.exists() || !fi.isFile()) { - qWarning() << "mdimg: resource not found:" << path; + qCWarning(appLog) << "mdimg: resource not found:" << path; job->fail(QWebEngineUrlRequestJob::UrlNotFound); return; } @@ -62,7 +63,7 @@ class MarkdownImageHandler : public QWebEngineUrlSchemeHandler const QString canonical = fi.canonicalFilePath(); const QString mime = QMimeDatabase().mimeTypeForFile(fi).name(); if (canonical.isEmpty() || !mime.startsWith(QLatin1String("image/"))) { - qWarning() << "mdimg: request denied (traversal or non-image):" << path << "mime:" << mime; + qCWarning(appLog) << "mdimg: request denied (traversal or non-image):" << path << "mime:" << mime; job->fail(QWebEngineUrlRequestJob::RequestDenied); return; } @@ -91,15 +92,15 @@ MarkdownView::MarkdownView(QWidget *parent) const QUrl url(urlStr); const QString scheme = url.scheme().toLower(); if (scheme == QLatin1String("http") || scheme == QLatin1String("https")) { - qInfo() << "MarkdownView: open external link in system browser:" << urlStr; + qCInfo(appLog) << "MarkdownView: open external link in system browser:" << urlStr; QDesktopServices::openUrl(url); } else { - qWarning() << "MarkdownView: blocked link with non-whitelisted scheme:" << urlStr; + qCWarning(appLog) << "MarkdownView: blocked link with non-whitelisted scheme:" << urlStr; } }); // §4 阶段 4 崩溃恢复:WebEngine 渲染进程终止时重新加载页面 connect(this, &QWebEngineView::renderProcessTerminated, this, [this](QWebEnginePage::RenderProcessTerminationStatus, int) { - qWarning() << "MarkdownView: render process terminated, reloading"; + qCWarning(appLog) << "MarkdownView: render process terminated, reloading"; m_ready = false; QTimer::singleShot(300, this, [this]() { page()->triggerAction(QWebEnginePage::Reload); @@ -131,7 +132,7 @@ void MarkdownView::init() connect(page(), &QWebEnginePage::urlChanged, this, [this](const QUrl &url) { const QString scheme = url.scheme(); if (scheme == QLatin1String("http") || scheme == QLatin1String("https")) { - qWarning() << "MarkdownView: external navigation blocked, delegating to browser:" << url; + qCWarning(appLog) << "MarkdownView: external navigation blocked, delegating to browser:" << url; QDesktopServices::openUrl(url); load(QUrl(QStringLiteral("qrc:/editor/markdown/web/milkdown.html"))); } diff --git a/src/editor/replaceallcommond.cpp b/src/editor/replaceallcommond.cpp index fe9efd96f..d55616f16 100644 --- a/src/editor/replaceallcommond.cpp +++ b/src/editor/replaceallcommond.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2022-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "replaceallcommond.h" #include @@ -12,18 +13,18 @@ ReplaceAllCommand::ReplaceAllCommand(QString &oldText, QString &newText, QTextCu , m_newText(newText) , m_cursor(cursor) { - qDebug() << "ReplaceAllCommand created - oldText length:" << oldText.length() + qCDebug(appLog) << "ReplaceAllCommand created - oldText length:" << oldText.length() << "newText length:" << newText.length() << "cursor pos:" << cursor.position(); } ReplaceAllCommand::~ReplaceAllCommand() { - qDebug() << "ReplaceAllCommand destroyed"; + qCDebug(appLog) << "ReplaceAllCommand destroyed"; } void ReplaceAllCommand::redo() { - qInfo() << "ReplaceAllCommand redo - replacing all text with new text (length:" << m_newText.length() << ")"; + qCInfo(appLog) << "ReplaceAllCommand redo - replacing all text with new text (length:" << m_newText.length() << ")"; m_cursor.setPosition(0); m_cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); m_cursor.deleteChar(); @@ -33,7 +34,7 @@ void ReplaceAllCommand::redo() void ReplaceAllCommand::undo() { - qInfo() << "ReplaceAllCommand undo - restoring original text (length:" << m_oldText.length() << ")"; + qCInfo(appLog) << "ReplaceAllCommand undo - restoring original text (length:" << m_oldText.length() << ")"; m_cursor.setPosition(0); m_cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); m_cursor.deleteChar(); diff --git a/src/editor/showflodcodewidget.cpp b/src/editor/showflodcodewidget.cpp index 0785473f4..add78b8c2 100644 --- a/src/editor/showflodcodewidget.cpp +++ b/src/editor/showflodcodewidget.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "showflodcodewidget.h" #include #include @@ -22,7 +23,7 @@ DWIDGET_USE_NAMESPACE ShowFlodCodeWidget::ShowFlodCodeWidget(DWidget *parent) : DFrame(parent) { - qDebug() << "ShowFlodCodeWidget created with parent:" << parent; + qCDebug(appLog) << "ShowFlodCodeWidget created with parent:" << parent; //setFrameRounded(false); QGraphicsDropShadowEffect *effert = new QGraphicsDropShadowEffect(this); effert->setOffset(0,6); @@ -50,23 +51,23 @@ ShowFlodCodeWidget::ShowFlodCodeWidget(DWidget *parent) ShowFlodCodeWidget::~ShowFlodCodeWidget() { - qDebug() << "ShowFlodCodeWidget destroyed"; + qCDebug(appLog) << "ShowFlodCodeWidget destroyed"; m_highlighter->deleteLater(); m_highlighter = nullptr; } void ShowFlodCodeWidget::clear() { - qDebug() << "ShowFlodCodeWidget clear content"; + qCDebug(appLog) << "ShowFlodCodeWidget clear content"; m_pContentEdit->document()->clear(); m_nTextWidth = 0; adjustSize(); - qDebug() << "ShowFlodCodeWidget::clear() exit"; + qCDebug(appLog) << "ShowFlodCodeWidget::clear() exit"; } void ShowFlodCodeWidget::initHighLight(QString filepath, bool bIsLight) { - qInfo() << "ShowFlodCodeWidget initHighLight - file:" << filepath << "light theme:" << bIsLight; + qCInfo(appLog) << "ShowFlodCodeWidget initHighLight - file:" << filepath << "light theme:" << bIsLight; if (m_highlighter != nullptr) { if (!bIsLight) { m_highlighter->setTheme(m_repository.defaultTheme(KSyntaxHighlighting::Repository::DarkTheme)); @@ -77,24 +78,24 @@ void ShowFlodCodeWidget::initHighLight(QString filepath, bool bIsLight) // m_highlighter->rehighlight(); const auto def = m_repository.definitionForFileName(QFileInfo(filepath).fileName().toLower()); m_highlighter->setDefinition(def); - qDebug() << "Syntax definition set to:" << def.name(); + qCDebug(appLog) << "Syntax definition set to:" << def.name(); } void ShowFlodCodeWidget::setStyle(bool bIsLineWrap) { - qDebug() << "ShowFlodCodeWidget setStyle - lineWrap:" << bIsLineWrap; + qCDebug(appLog) << "ShowFlodCodeWidget setStyle - lineWrap:" << bIsLineWrap; QPalette pa = palette(); QColor color(25,25,25); if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::DarkType) { - qDebug() << "Setting dark theme style"; + qCDebug(appLog) << "Setting dark theme style"; color.setAlphaF(0.8); pa.setColor(QPalette::Base,color); m_pContentEdit->setPalette(pa); pa.setColor(QPalette::Base,QColor(25,25,25)); setPalette(pa); } else { - qDebug() << "Setting light theme style"; + qCDebug(appLog) << "Setting light theme style"; color = QColor(247,247,247); color.setAlphaF(0.6); pa.setColor(QPalette::Base,color); @@ -104,18 +105,18 @@ void ShowFlodCodeWidget::setStyle(bool bIsLineWrap) } if (bIsLineWrap) { - qDebug() << "Setting line wrap mode to WidgetWidth"; + qCDebug(appLog) << "Setting line wrap mode to WidgetWidth"; m_pContentEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth); } else { - qDebug() << "Setting line wrap mode to NoWrap"; + qCDebug(appLog) << "Setting line wrap mode to NoWrap"; m_pContentEdit->setLineWrapMode(QPlainTextEdit::NoWrap); } - qDebug() << "ShowFlodCodeWidget::setStyle() exit"; + qCDebug(appLog) << "ShowFlodCodeWidget::setStyle() exit"; } void ShowFlodCodeWidget::hideFirstBlock() { - qDebug() << "ShowFlodCodeWidget hideFirstBlock"; + qCDebug(appLog) << "ShowFlodCodeWidget hideFirstBlock"; m_pContentEdit->document()->firstBlock().setVisible(false); m_pContentEdit->document()->lastBlock().setVisible(false); int editHight = 0; @@ -123,7 +124,7 @@ void ShowFlodCodeWidget::hideFirstBlock() for (auto block = m_pContentEdit->document()->firstBlock(); block.isValid(); block = block.next()) { if (block == m_pContentEdit->document()->lastBlock()) { - qDebug() << "Reached last block, breaking loop"; + qCDebug(appLog) << "Reached last block, breaking loop"; break; } @@ -131,38 +132,38 @@ void ShowFlodCodeWidget::hideFirstBlock() } m_pContentEdit->setFixedHeight(editHight + 10); - qDebug() << "Adjusted height to:" << editHight + 10; - qDebug() << "ShowFlodCodeWidget::hideFirstBlock() exit"; + qCDebug(appLog) << "Adjusted height to:" << editHight + 10; + qCDebug(appLog) << "ShowFlodCodeWidget::hideFirstBlock() exit"; } void ShowFlodCodeWidget::appendText(QString strText, int maxWidth) { - qDebug() << "ShowFlodCodeWidget appendText - text length:" << strText.length() << "maxWidth:" << maxWidth; + qCDebug(appLog) << "ShowFlodCodeWidget appendText - text length:" << strText.length() << "maxWidth:" << maxWidth; int textWidth = m_pContentEdit->fontMetrics().horizontalAdvance(strText) + 10; if (m_nTextWidth < textWidth) { - qDebug() << "Updating text width, old:" << m_nTextWidth << ", new:" << textWidth; + qCDebug(appLog) << "Updating text width, old:" << m_nTextWidth << ", new:" << textWidth; m_nTextWidth = textWidth; if (m_nTextWidth > maxWidth - 50) { - qDebug() << "Adjusting text width to fit maxWidth - 50"; + qCDebug(appLog) << "Adjusting text width to fit maxWidth - 50"; m_nTextWidth = maxWidth - 50; } } m_pContentEdit->setFixedWidth(m_nTextWidth); - qDebug() << "Text width set to:" << m_nTextWidth; + qCDebug(appLog) << "Text width set to:" << m_nTextWidth; if (m_pContentEdit->document()->isEmpty()) { - qDebug() << "Document is empty, setting plain text"; + qCDebug(appLog) << "Document is empty, setting plain text"; m_pContentEdit->setPlainText(strText); } else { - qDebug() << "Document not empty, appending plain text"; + qCDebug(appLog) << "Document not empty, appending plain text"; m_pContentEdit->appendPlainText(strText); } QTextCursor cursor = m_pContentEdit->textCursor(); cursor.movePosition(QTextCursor::Start); m_pContentEdit->setTextCursor(cursor); - qDebug() << "ShowFlodCodeWidget::appendText() exit"; + qCDebug(appLog) << "ShowFlodCodeWidget::appendText() exit"; } diff --git a/src/editor/uncommentselection.cpp b/src/editor/uncommentselection.cpp index 70e9709ae..fe67cb68e 100644 --- a/src/editor/uncommentselection.cpp +++ b/src/editor/uncommentselection.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2019 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2019-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "uncommentselection.h" #include #include @@ -10,42 +11,42 @@ using namespace Comment; CommentDefinition::CommentDefinition() : isAfterWhiteSpaces(false) { - qDebug() << "CommentDefinition constructor called"; - qDebug() << "CommentDefinition::CommentDefinition() exit"; + qCDebug(appLog) << "CommentDefinition constructor called"; + qCDebug(appLog) << "CommentDefinition::CommentDefinition() exit"; } void CommentDefinition::setComments(QString singleLineComment, QString multiLineCommentStart, QString multiLineCommentEnd) { - qInfo() << "Setting comments - singleLine:" << singleLineComment + qCInfo(appLog) << "Setting comments - singleLine:" << singleLineComment << "multiLineStart:" << multiLineCommentStart << "multiLineEnd:" << multiLineCommentEnd; singleLine = singleLineComment; multiLineStart = multiLineCommentStart; multiLineEnd = multiLineCommentEnd; - qDebug() << "CommentDefinition::setComments() exit"; + qCDebug(appLog) << "CommentDefinition::setComments() exit"; } bool CommentDefinition::isValid() const { - qDebug() << "CommentDefinition::isValid() entry"; + qCDebug(appLog) << "CommentDefinition::isValid() entry"; bool result = hasSingleLineStyle() || hasMultiLineStyle(); - qDebug() << "CommentDefinition::isValid() exit, result:" << result; + qCDebug(appLog) << "CommentDefinition::isValid() exit, result:" << result; return result; } bool CommentDefinition::hasSingleLineStyle() const { - qDebug() << "CommentDefinition::hasSingleLineStyle() entry"; + qCDebug(appLog) << "CommentDefinition::hasSingleLineStyle() entry"; bool result = !singleLine.isEmpty(); - qDebug() << "CommentDefinition::hasSingleLineStyle() exit, result:" << result; + qCDebug(appLog) << "CommentDefinition::hasSingleLineStyle() exit, result:" << result; return result; } bool CommentDefinition::hasMultiLineStyle() const { - qDebug() << "CommentDefinition::hasMultiLineStyle() entry"; + qCDebug(appLog) << "CommentDefinition::hasMultiLineStyle() entry"; bool result = !multiLineStart.isEmpty() && !multiLineEnd.isEmpty(); - qDebug() << "CommentDefinition::hasMultiLineStyle() exit, result:" << result; + qCDebug(appLog) << "CommentDefinition::hasMultiLineStyle() exit, result:" << result; return result; } diff --git a/src/editor/undolist.cpp b/src/editor/undolist.cpp index 5d6366bbe..306c7c152 100644 --- a/src/editor/undolist.cpp +++ b/src/editor/undolist.cpp @@ -1,19 +1,20 @@ -// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2022-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "undolist.h" #include UndoList::UndoList() { - qDebug() << "UndoList created"; + qCDebug(appLog) << "UndoList created"; } UndoList::~UndoList() { - qDebug() << "UndoList destroyed, cleaning up commands"; + qCDebug(appLog) << "UndoList destroyed, cleaning up commands"; for (auto& it : m_coms) { if(nullptr != it){ delete it; @@ -26,42 +27,42 @@ UndoList::~UndoList() void UndoList::appendCom(QUndoCommand* com) { if(nullptr != com){ - qDebug() << "Appending undo command:" << com->text(); + qCDebug(appLog) << "Appending undo command:" << com->text(); m_coms.push_back(com); } } void UndoList::undo() { - qDebug() << "Executing undo on" << m_coms.size() << "commands"; + qCDebug(appLog) << "Executing undo on" << m_coms.size() << "commands"; //do the undo operation in the reverse order. int total = m_coms.size(); int processed = 0; - qDebug() << "Starting undo of" << total << "commands"; + qCDebug(appLog) << "Starting undo of" << total << "commands"; for(auto it = m_coms.rbegin();it!=m_coms.rend();it++){ - qDebug() << "Undoing command:" << (*it)->text(); + qCDebug(appLog) << "Undoing command:" << (*it)->text(); (*it)->undo(); processed++; if (processed % 10 == 0 || processed == total) { - qDebug() << "Undo progress:" << processed << "/" << total; + qCDebug(appLog) << "Undo progress:" << processed << "/" << total; } } } void UndoList::redo() { - qDebug() << "Executing redo on" << m_coms.size() << "commands"; + qCDebug(appLog) << "Executing redo on" << m_coms.size() << "commands"; int total = m_coms.size(); int processed = 0; - qDebug() << "Starting redo of" << total << "commands"; + qCDebug(appLog) << "Starting redo of" << total << "commands"; foreach (auto it, m_coms) { - qDebug() << "Redoing command:" << it->text(); + qCDebug(appLog) << "Redoing command:" << it->text(); it->redo(); processed++; if (processed % 10 == 0 || processed == total) { - qDebug() << "Redo progress:" << processed << "/" << total; + qCDebug(appLog) << "Redo progress:" << processed << "/" << total; } } } diff --git a/src/editorapplication.cpp b/src/editorapplication.cpp index e2067ffde..8c1e7fa83 100644 --- a/src/editorapplication.cpp +++ b/src/editorapplication.cpp @@ -2,67 +2,68 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "editorapplication.h" #include "common/settings.h" #include EditorApplication::EditorApplication(int &argc, char *argv[]) : DApplication(argc, argv) { - qDebug() << "Enter EditorApplication constructor"; + qCDebug(appLog) << "Enter EditorApplication constructor"; const char *descriptionText = QT_TRANSLATE_NOOP( "MainWindow", "Text Editor is a powerful tool for viewing and editing text files."); const QString acknowledgementLink = "https://www.deepin.org/original/deepin-editor/"; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) - qDebug() << "Setting Qt::AA_UseHighDpiPixmaps attribute for Qt version < 6.0.0"; + qCDebug(appLog) << "Setting Qt::AA_UseHighDpiPixmaps attribute for Qt version < 6.0.0"; setAttribute(Qt::AA_UseHighDpiPixmaps); #else - qDebug() << "Running with Qt version >= 6.0.0, skipping AA_UseHighDpiPixmaps"; + qCDebug(appLog) << "Running with Qt version >= 6.0.0, skipping AA_UseHighDpiPixmaps"; #endif - qDebug() << "Loading translator"; + qCDebug(appLog) << "Loading translator"; loadTranslator(); - qDebug() << "Setting organization name: deepin"; + qCDebug(appLog) << "Setting organization name: deepin"; setOrganizationName("deepin"); - qDebug() << "Setting application name: deepin-editor"; + qCDebug(appLog) << "Setting application name: deepin-editor"; setApplicationName("deepin-editor"); - qDebug() << "Setting application display name: Text Editor"; + qCDebug(appLog) << "Setting application display name: Text Editor"; setApplicationDisplayName(QObject::tr("Text Editor")); - qDebug() << "Setting application version:" << VERSION; + qCDebug(appLog) << "Setting application version:" << VERSION; setApplicationVersion(VERSION); - qDebug() << "Setting product icon from theme: deepin-editor"; + qCDebug(appLog) << "Setting product icon from theme: deepin-editor"; setProductIcon(QIcon::fromTheme("deepin-editor")); - qDebug() << "Setting product name: Text Editor"; + qCDebug(appLog) << "Setting product name: Text Editor"; setProductName(DApplication::translate("MainWindow", "Text Editor")); - qDebug() << "Setting application description"; + qCDebug(appLog) << "Setting application description"; setApplicationDescription(DApplication::translate("MainWindow", descriptionText) + "\n"); - qDebug() << "Setting acknowledgement page:" << acknowledgementLink; + qCDebug(appLog) << "Setting acknowledgement page:" << acknowledgementLink; setApplicationAcknowledgementPage(acknowledgementLink); - qDebug() << "Setting quitOnLastWindowClosed to false"; + qCDebug(appLog) << "Setting quitOnLastWindowClosed to false"; setQuitOnLastWindowClosed(false); - qDebug() << "Exit EditorApplication constructor"; - qInfo() << "Application initialized with version:" << VERSION; + qCDebug(appLog) << "Exit EditorApplication constructor"; + qCInfo(appLog) << "Application initialized with version:" << VERSION; } EditorApplication::~EditorApplication() { - qDebug() << "Enter EditorApplication destructor"; + qCDebug(appLog) << "Enter EditorApplication destructor"; // StartManager 生命周期由 main() 接管(创建于 create(),事件循环结束后显式释放), // 析构不得触碰,否则 D-Bus 转发进程会在退出期意外实例化单例(BUG-378901) - qDebug() << "Exit EditorApplication destructor"; - qInfo() << "Application resources released"; + qCDebug(appLog) << "Exit EditorApplication destructor"; + qCInfo(appLog) << "Application resources released"; } void EditorApplication::handleQuitAction() { - qDebug() << "Enter handleQuitAction"; + qCDebug(appLog) << "Enter handleQuitAction"; QWidget* active = activeWindow(); if (active) { - qDebug() << "Active window found, closing it"; + qCDebug(appLog) << "Active window found, closing it"; active->close(); } else { - qWarning() << "No active window found to close"; + qCWarning(appLog) << "No active window found to close"; } - qDebug() << "Exit handleQuitAction"; - qInfo() << "Quit action triggered, closing active window"; + qCDebug(appLog) << "Exit handleQuitAction"; + qCInfo(appLog) << "Quit action triggered, closing active window"; } bool EditorApplication::notify(QObject *object, QEvent *event) @@ -87,7 +88,7 @@ bool EditorApplication::notify(QObject *object, QEvent *event) DPushButton *pushButton = static_cast(object); // 模拟空格键按下事件 pressSpace(pushButton); - qDebug() << "Return/Enter key event processed, simulated space key press"; + qCDebug(appLog) << "Return/Enter key event processed, simulated space key press"; return true; } /***add end by ut001121***/ @@ -100,10 +101,10 @@ bool EditorApplication::notify(QObject *object, QEvent *event) DPushButton *pushButton = static_cast(object); // 模拟空格键按下事件 pressSpace(pushButton); - qDebug() << "Left key event processed, simulated space key press"; + qCDebug(appLog) << "Left key event processed, simulated space key press"; return true; } - qDebug() << "KeyPress event delegated to QApplication::notify"; + qCDebug(appLog) << "KeyPress event delegated to QApplication::notify"; return QApplication::notify(object, event); } @@ -112,17 +113,17 @@ bool EditorApplication::notify(QObject *object, QEvent *event) void EditorApplication::pressSpace(DPushButton *pushButton) { - qDebug() << "Enter pressSpace, button:" << pushButton->objectName(); + qCDebug(appLog) << "Enter pressSpace, button:" << pushButton->objectName(); // 模拟空格键按下事件 QKeyEvent pressSpace(QEvent::KeyPress, Qt::Key_Space, Qt::NoModifier, " "); - qDebug() << "Sending space key press event to button"; + qCDebug(appLog) << "Sending space key press event to button"; QApplication::sendEvent(pushButton, &pressSpace); // 设置定时 QTimer::singleShot(80, this, [pushButton]() { - qDebug() << "Timer triggered, sending space key release to button:" << pushButton->objectName(); + qCDebug(appLog) << "Timer triggered, sending space key release to button:" << pushButton->objectName(); // 模拟空格键松开事件 QKeyEvent releaseSpace(QEvent::KeyRelease, Qt::Key_Space, Qt::NoModifier, " "); QApplication::sendEvent(pushButton, &releaseSpace); }); - qDebug() << "Exit pressSpace, scheduled release event in 80ms"; + qCDebug(appLog) << "Exit pressSpace, scheduled release event in 80ms"; } diff --git a/src/encodes/detectcode.cpp b/src/encodes/detectcode.cpp index f0d4c0914..860be593f 100644 --- a/src/encodes/detectcode.cpp +++ b/src/encodes/detectcode.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "detectcode.h" #include "../common/config.h" @@ -125,7 +126,7 @@ DetectCode::DetectCode() {} */ QByteArray DetectCode::GetFileEncodingFormat(QString filepath, QByteArray content) { - qDebug() << "Enter GetFileEncodingFormat"; + qCDebug(appLog) << "Enter GetFileEncodingFormat"; QString charDetectedResult; QByteArray ucharDetectdRet; QByteArrayList icuDetectRetList; @@ -142,26 +143,26 @@ QByteArray DetectCode::GetFileEncodingFormat(QString filepath, QByteArray conten #endif bool bFlag = str.contains(reg); if (bFlag) { - qDebug() << "Content contains Chinese characters"; + qCDebug(appLog) << "Content contains Chinese characters"; const QByteArray suffix = "为增加探测率保留的中文"; QByteArray newContent = content; //手动添加中文字符,避免字符长度太短而导致判断编码错误 newContent += suffix; DetectCode::ChartDet_DetectingTextCoding(newContent, charDetectedResult, chardetconfidence); - qDebug() << "Initial chardet confidence for Chinese content:" << chardetconfidence; + qCDebug(appLog) << "Initial chardet confidence for Chinese content:" << chardetconfidence; // 大文本数据存在从文档中间截断的可能,导致unicode中文字符被截断,解析为乱码,处理部分情况 // 根据文本中断的情况,每次尝试解析编码后移除尾部字符,直到识别率达到90%以上 int tryCount = 5; while (chardetconfidence < gs_dMinConfidence && newContent.size() > suffix.size() && tryCount-- > 0) { - qDebug() << "Confidence too low, retrying. Try count left:" << tryCount << ", current confidence:" << chardetconfidence; + qCDebug(appLog) << "Confidence too low, retrying. Try count left:" << tryCount << ", current confidence:" << chardetconfidence; // 移除可能的乱码尾部字符 newContent.remove(newContent.size() - suffix.size(), 1); DetectCode::ChartDet_DetectingTextCoding(newContent, charDetectedResult, chardetconfidence); } - qDebug() << "Final chardet confidence after retries:" << chardetconfidence; + qCDebug(appLog) << "Final chardet confidence after retries:" << chardetconfidence; } else { - qDebug() << "Content does not contain Chinese characters"; + qCDebug(appLog) << "Content does not contain Chinese characters"; DetectCode::ChartDet_DetectingTextCoding(content, charDetectedResult, chardetconfidence); // 部分非unicode编码同为中文,例如 GB18030, BIG5 等中文编码,同样判断识别率,识别率较低手动干预多次检测 @@ -171,42 +172,42 @@ QByteArray DetectCode::GetFileEncodingFormat(QString filepath, QByteArray conten newContent.chop(1); DetectCode::ChartDet_DetectingTextCoding(newContent, charDetectedResult, chardetconfidence); } - qDebug() << "Final chardet confidence for non-Chinese after retries:" << chardetconfidence; + qCDebug(appLog) << "Final chardet confidence for non-Chinese after retries:" << chardetconfidence; } ucharDetectdRet = charDetectedResult.toLatin1(); // uchardet识别编码 若识别率过低, 考虑是否非单字节编码格式。 if (ucharDetectdRet.contains("unknown") || ucharDetectdRet.contains("ASCII") || ucharDetectdRet.contains("???") || ucharDetectdRet.isEmpty() || chardetconfidence < gs_dMinConfidence) { - qDebug() << "Uchardet detection needed or confidence too low, calling UchardetCode"; + qCDebug(appLog) << "Uchardet detection needed or confidence too low, calling UchardetCode"; ucharDetectdRet = DetectCode::UchardetCode(filepath); } if (ucharDetectdRet.contains("ASCII")) { - qDebug() << "Detected ASCII, using default encoding"; + qCDebug(appLog) << "Detected ASCII, using default encoding"; // 使用配置的默认文件编码,默认为UTF-8 detectRet = Config::instance()->defaultEncoding(); } else { - qDebug() << "Detected non-ASCII, trying ICU and selecting coding"; + qCDebug(appLog) << "Detected non-ASCII, trying ICU and selecting coding"; // icu识别编码 icuDetectTextEncoding(filepath, icuDetectRetList); detectRet = selectCoding(ucharDetectdRet, icuDetectRetList, chardetconfidence); if (detectRet.contains("ASCII") || detectRet.isEmpty()) { - qDebug() << "Selected encoding is ASCII or empty, using default encoding"; + qCDebug(appLog) << "Selected encoding is ASCII or empty, using default encoding"; // 使用配置的默认文件编码,默认为UTF-8 detectRet = Config::instance()->defaultEncoding(); } } - qDebug() << "GetFileEncodingFormat exit, detected encoding:" << detectRet.toUpper(); - qDebug() << "Exit GetFileEncodingFormat"; + qCDebug(appLog) << "GetFileEncodingFormat exit, detected encoding:" << detectRet.toUpper(); + qCDebug(appLog) << "Exit GetFileEncodingFormat"; return detectRet.toUpper(); } QByteArray DetectCode::UchardetCode(QString filepath) { - qDebug() << "Enter UchardetCode, file:" << filepath; + qCDebug(appLog) << "Enter UchardetCode, file:" << filepath; FILE *fp; QByteArray charset; @@ -222,13 +223,13 @@ QByteArray DetectCode::UchardetCode(QString filepath) fp = fopen(filepath.toLocal8Bit().data(), "rb"); if (fp) { - qDebug() << "File opened successfully for UchardetCode:" << filepath; + qCDebug(appLog) << "File opened successfully for UchardetCode:" << filepath; while (!feof(fp)) { size_t len = fread(buff, 1, buffer_size, fp); - qDebug() << "Reading data for UchardetCode, len:" << len; + qCDebug(appLog) << "Reading data for UchardetCode, len:" << len; int retval = uchardet_handle_data(handle, buff, len); if (retval != 0) { - qWarning() << "uchardet_handle_data returned non-zero value:" << retval; + qCWarning(appLog) << "uchardet_handle_data returned non-zero value:" << retval; continue; } @@ -238,9 +239,9 @@ QByteArray DetectCode::UchardetCode(QString filepath) uchardet_data_end(handle); charset = uchardet_get_charset(handle); - qDebug() << "Uchardet detected charset:" << charset; + qCDebug(appLog) << "Uchardet detected charset:" << charset; } else { - qWarning() << "Failed to open file for UchardetCode:" << filepath; + qCWarning(appLog) << "Failed to open file for UchardetCode:" << filepath; } uchardet_delete(handle); @@ -248,19 +249,19 @@ QByteArray DetectCode::UchardetCode(QString filepath) buff = nullptr; if (charset == "MAC-CENTRALEUROPE") { - qDebug() << "Correcting charset from MAC-CENTRALEUROPE"; + qCDebug(appLog) << "Correcting charset from MAC-CENTRALEUROPE"; charset = "MACCENTRALEUROPE"; } if (charset == "MAC-CYRILLIC") { - qDebug() << "Correcting charset from MAC-CYRILLIC"; + qCDebug(appLog) << "Correcting charset from MAC-CYRILLIC"; charset = "MACCYRILLIC"; } if (charset.contains("WINDOWS-")) { - qDebug() << "Correcting charset from WINDOWS-"; + qCDebug(appLog) << "Correcting charset from WINDOWS-"; charset = charset.replace("WINDOWS-", "CP"); } - qDebug() << "Exit UchardetCode"; + qCDebug(appLog) << "Exit UchardetCode"; return charset; } @@ -271,12 +272,12 @@ QByteArray DetectCode::UchardetCode(QString filepath) **/ void DetectCode::icuDetectTextEncoding(const QString &filePath, QByteArrayList &listDetectRet) { - qDebug() << "Enter icuDetectTextEncoding, file:" << filePath; + qCDebug(appLog) << "Enter icuDetectTextEncoding, file:" << filePath; FILE *file; file = fopen(filePath.toLocal8Bit().data(), "rb"); if (file == nullptr) { - qWarning() << "Failed to open file for icuDetectTextEncoding:" << filePath; - qInfo() << "fopen file failed."; + qCWarning(appLog) << "Failed to open file for icuDetectTextEncoding:" << filePath; + qCInfo(appLog) << "fopen file failed."; return; } @@ -289,14 +290,14 @@ void DetectCode::icuDetectTextEncoding(const QString &filePath, QByteArrayList & while (!feof(file)) { size_t len = fread(buffer, 1, iBuffSize, file); readed += len; - qDebug() << "Reading data for icuDetectTextEncoding, len:" << len << ", total read:" << readed; + qCDebug(appLog) << "Reading data for icuDetectTextEncoding, len:" << len << ", total read:" << readed; if (readed > 1 * 1024 * 1024) { - qDebug() << "Read limit exceeded (1MB), breaking loop"; + qCDebug(appLog) << "Read limit exceeded (1MB), breaking loop"; break; } if (detectTextEncoding(buffer, len, &detected, listDetectRet)) { - qDebug() << "Text encoding detected, breaking loop"; + qCDebug(appLog) << "Text encoding detected, breaking loop"; break; } } @@ -304,7 +305,7 @@ void DetectCode::icuDetectTextEncoding(const QString &filePath, QByteArrayList & delete[] buffer; buffer = nullptr; fclose(file); - qDebug() << "Exit icuDetectTextEncoding, detected encodings:" << listDetectRet; + qCDebug(appLog) << "Exit icuDetectTextEncoding, detected encodings:" << listDetectRet; } /** @@ -316,7 +317,7 @@ void DetectCode::icuDetectTextEncoding(const QString &filePath, QByteArrayList & **/ bool DetectCode::detectTextEncoding(const char *data, size_t len, char **detected, QByteArrayList &listDetectRet) { - qDebug() << "[DetectCode] Enter detectTextEncoding, data size:" << len; + qCDebug(appLog) << "[DetectCode] Enter detectTextEncoding, data size:" << len; Q_UNUSED(detected); @@ -327,46 +328,46 @@ bool DetectCode::detectTextEncoding(const char *data, size_t len, char **detecte UErrorCode status = U_ZERO_ERROR; csd = ucsdet_open(&status); if (status != U_ZERO_ERROR) { - qWarning() << "ucsdet_open failed, status:" << status; + qCWarning(appLog) << "ucsdet_open failed, status:" << status; return false; } ucsdet_setText(csd, data, len, &status); if (status != U_ZERO_ERROR) { - qWarning() << "ucsdet_setText failed, status:" << status; + qCWarning(appLog) << "ucsdet_setText failed, status:" << status; return false; } csm = ucsdet_detectAll(csd, &matchCount, &status); if (status != U_ZERO_ERROR) { - qWarning() << "ucsdet_detectAll failed, status:" << status; + qCWarning(appLog) << "ucsdet_detectAll failed, status:" << status; return false; } - qDebug() << "matchCount from ucsdet_detectAll:" << matchCount; + qCDebug(appLog) << "matchCount from ucsdet_detectAll:" << matchCount; int readMax = 0; // 提高GB18030识别率时,拓展允许读取的编码列表 if (Config::instance()->enableImproveGB18030()) { - qDebug() << "Improving GB18030 recognition, setting readMax to min(6, matchCount)"; + qCDebug(appLog) << "Improving GB18030 recognition, setting readMax to min(6, matchCount)"; readMax = qMin(6, matchCount); } else { - qDebug() << "Not improving GB18030 recognition, setting readMax to min(3, matchCount)"; + qCDebug(appLog) << "Not improving GB18030 recognition, setting readMax to min(3, matchCount)"; readMax = qMin(3, matchCount); } - qDebug() << "Final readMax:" << readMax; + qCDebug(appLog) << "Final readMax:" << readMax; for (int i = 0; i < readMax; i++) { auto str = ucsdet_getName(csm[i], &status); if (status != U_ZERO_ERROR) { - qWarning() << "ucsdet_getName failed for index" << i << ", status:" << status; + qCWarning(appLog) << "ucsdet_getName failed for index" << i << ", status:" << status; return false; } listDetectRet << QByteArray(str); - qDebug() << "Detected encoding:" << str << "(index:" << i << ")"; + qCDebug(appLog) << "Detected encoding:" << str << "(index:" << i << ")"; } ucsdet_close(csd); - qDebug() << "Exit detectTextEncoding, result:" << !listDetectRet.isEmpty(); + qCDebug(appLog) << "Exit detectTextEncoding, result:" << !listDetectRet.isEmpty(); return true; } @@ -379,62 +380,62 @@ bool DetectCode::detectTextEncoding(const char *data, size_t len, char **detecte **/ QByteArray DetectCode::selectCoding(QByteArray ucharDetectdRet, QByteArrayList icuDetectRetList, float confidence) { - qDebug() << "[DetectCode] Enter selectCoding, uchardet:" << ucharDetectdRet + qCDebug(appLog) << "[DetectCode] Enter selectCoding, uchardet:" << ucharDetectdRet << "icu:" << icuDetectRetList << "confidence:" << confidence; // 列表不允许为空 if (icuDetectRetList.isEmpty()) { - qDebug() << "[DetectCode] Exit selectCoding, selected:" << (icuDetectRetList.isEmpty() ? QByteArray() : icuDetectRetList[0]); + qCDebug(appLog) << "[DetectCode] Exit selectCoding, selected:" << (icuDetectRetList.isEmpty() ? QByteArray() : icuDetectRetList[0]); return QByteArray(); } if (!ucharDetectdRet.isEmpty()) { - qDebug() << "ucharDetectdRet is not empty"; + qCDebug(appLog) << "ucharDetectdRet is not empty"; // 获取是否允许提高GB18030编码的策略 if (Config::instance()->enableImproveGB18030()) { - qDebug() << "GB18030 improvement enabled"; + qCDebug(appLog) << "GB18030 improvement enabled"; // 中文环境优先匹配GB18030编码 if (QLocale::Chinese == QLocale::system().language()) { - qDebug() << "System language is Chinese"; + qCDebug(appLog) << "System language is Chinese"; if (confidence < gs_dMinConfidence && icuDetectRetList.contains("GB18030")) { - qDebug() << "Confidence low and GB18030 in list, returning GB18030"; + qCDebug(appLog) << "Confidence low and GB18030 in list, returning GB18030"; return QByteArray("GB18030"); } } } if (ucharDetectdRet.contains(icuDetectRetList[0])) { - qDebug() << "ucharDetectdRet contains first ICU result, returning uchardetDetectRet"; + qCDebug(appLog) << "ucharDetectdRet contains first ICU result, returning uchardetDetectRet"; return ucharDetectdRet; } else { - qDebug() << "ucharDetectdRet does not contain first ICU result"; + qCDebug(appLog) << "ucharDetectdRet does not contain first ICU result"; if (icuDetectRetList.contains("GB18030")) { - qDebug() << "ICU list contains GB18030, returning GB18030"; + qCDebug(appLog) << "ICU list contains GB18030, returning GB18030"; return QByteArray("GB18030"); } else { // 筛选部分带后缀的编码格式,例如 UTF-16 BE 和 UTF-16 if (icuDetectRetList[0].contains(ucharDetectdRet)) { - qDebug() << "First ICU result contains uchardetDetectRet, returning first ICU result"; + qCDebug(appLog) << "First ICU result contains uchardetDetectRet, returning first ICU result"; return icuDetectRetList[0]; } - qDebug() << "Returning uchardetDetectRet as fallback"; + qCDebug(appLog) << "Returning uchardetDetectRet as fallback"; return ucharDetectdRet; } } } if (ucharDetectdRet.isEmpty()) { - qDebug() << "ucharDetectdRet is empty, checking ICU list for GB18030"; + qCDebug(appLog) << "ucharDetectdRet is empty, checking ICU list for GB18030"; if (icuDetectRetList.contains("GB18030")) { - qDebug() << "ICU list contains GB18030, returning GB18030"; + qCDebug(appLog) << "ICU list contains GB18030, returning GB18030"; return QByteArray("GB18030"); } else { - qDebug() << "ICU list does not contain GB18030, returning first ICU result"; + qCDebug(appLog) << "ICU list does not contain GB18030, returning first ICU result"; return icuDetectRetList[0]; } } - qDebug() << "Exit selectCoding, selected:" << (icuDetectRetList.isEmpty() ? QByteArray() : icuDetectRetList[0]); + qCDebug(appLog) << "Exit selectCoding, selected:" << (icuDetectRetList.isEmpty() ? QByteArray() : icuDetectRetList[0]); return QByteArray(); } @@ -483,7 +484,7 @@ QByteArray DetectCode::EncaDetectCode(QString filepath) size_t len = fread(buff, 1, buffer_size, fp); EncaEncoding encoding = enca_analyse(analyser, buff, len); charset = enca_charset_name(encoding.charset, EncaNameStyle::ENCA_NAME_STYLE_MIME); - qDebug() << QStringLiteral("ENCA文本的编码方式是:") << charset; + qCDebug(appLog) << QStringLiteral("ENCA文本的编码方式是:") << charset; //识别文本编码识别 if (encoding.charset == -1) continue; break; @@ -497,7 +498,7 @@ QByteArray DetectCode::EncaDetectCode(QString filepath) fclose(fp); } else { - qDebug() << QStringLiteral("ENCA打开失败:") << filepath; + qCDebug(appLog) << QStringLiteral("ENCA打开失败:") << filepath; } if (charset == "US-ASCII") charset = "ASCII"; @@ -522,7 +523,7 @@ int DetectCode::ChartDet_DetectingTextCoding(const char *str, QString &encoding, DetectObj *obj = detect_obj_init(); if (obj == nullptr) { - // qInfo() << "Memory Allocation failed\n"; + // qCInfo(appLog) << "Memory Allocation failed\n"; return CHARDET_MEM_ALLOCATED_FAIL; } @@ -538,7 +539,7 @@ int DetectCode::ChartDet_DetectingTextCoding(const char *str, QString &encoding, size_t len = fread(buff, 1, buffer_size, fp); detect(buff, &obj); QString encoding = obj->encoding; - qInfo() << "==== encoding: " << encoding; + qCInfo(appLog) << "==== encoding: " << encoding; if (encoding == "") { continue; } else if (!encoding.isEmpty()) { @@ -560,19 +561,19 @@ int DetectCode::ChartDet_DetectingTextCoding(const char *str, QString &encoding, #endif { case CHARDET_OUT_OF_MEMORY: - qInfo() << "On handle processing, occured out of memory\n"; + qCInfo(appLog) << "On handle processing, occured out of memory\n"; detect_obj_free(&obj); return CHARDET_OUT_OF_MEMORY; case CHARDET_NULL_OBJECT: - qInfo() << "2st argument of chardet() is must memory allocation with detect_obj_init API\n"; + qCInfo(appLog) << "2st argument of chardet() is must memory allocation with detect_obj_init API\n"; return CHARDET_NULL_OBJECT; } #ifndef CHARDET_BOM_CHECK - // qInfo() << "encoding:" << obj->encoding << "; confidence: " << obj->confidence; + // qCInfo(appLog) << "encoding:" << obj->encoding << "; confidence: " << obj->confidence; #else // from 1.0.6 support return whether exists BOM - qInfo() << "encoding:" << obj->encoding << "; confidence: " << obj->confidence << "; bom: " << obj->bom; + qCInfo(appLog) << "encoding:" << obj->encoding << "; confidence: " << obj->confidence << "; bom: " << obj->bom; #endif encoding = obj->encoding; @@ -595,7 +596,7 @@ int DetectCode::ChartDet_DetectingTextCoding(const char *str, QString &encoding, */ int utf8MultiByteCount(char *buf, size_t size) { - qDebug() << "utf8MultiByteCount() entry, size:" << size; + qCDebug(appLog) << "utf8MultiByteCount() entry, size:" << size; // UTF 字符类型,单字符,中间字符,双字节,三字节,四字节 enum UtfCharType { Single, @@ -618,25 +619,25 @@ int utf8MultiByteCount(char *buf, size_t size) int count = 0; while (size > 0 && count < FourBytes) { - qDebug() << "Looping in utf8MultiByteCount, current size:" << size << ", count:" << count; + qCDebug(appLog) << "Looping in utf8MultiByteCount, current size:" << size << ", count:" << count; int leftBits = LeftBitFunc(*buf); - qDebug() << "Left bits for current byte:" << leftBits; + qCDebug(appLog) << "Left bits for current byte:" << leftBits; switch (leftBits) { case Mid: - qDebug() << "Case Mid, incrementing count"; + qCDebug(appLog) << "Case Mid, incrementing count"; count++; break; case DoubleBytes: - qDebug() << "Case DoubleBytes, returning leftBits"; + qCDebug(appLog) << "Case DoubleBytes, returning leftBits"; return leftBits; case ThreeBytes: - qDebug() << "Case ThreeBytes, returning leftBits"; + qCDebug(appLog) << "Case ThreeBytes, returning leftBits"; return leftBits; case FourBytes: - qDebug() << "Case FourBytes, returning leftBits"; + qCDebug(appLog) << "Case FourBytes, returning leftBits"; return leftBits; default: - qDebug() << "Case default (single byte or >4 bytes), returning 1"; + qCDebug(appLog) << "Case default (single byte or >4 bytes), returning 1"; // 超过4字节或单字节,均返回1 return 1; } @@ -645,7 +646,7 @@ int utf8MultiByteCount(char *buf, size_t size) size--; } - qDebug() << "utf8MultiByteCount() exit, returning count:" << count; + qCDebug(appLog) << "utf8MultiByteCount() exit, returning count:" << count; return count; } @@ -688,33 +689,33 @@ int utf8MultiByteCount(char *buf, size_t size) */ bool checkGB18030ToUtf8Error(char *buf, size_t size, size_t &replaceLen, QByteArray &appendChar) { - qDebug() << "checkGB18030ToUtf8Error() entry, size:" << size; + qCDebug(appLog) << "checkGB18030ToUtf8Error() entry, size:" << size; // 对于GB18030-2005编码规范PUA区域的字符,iconv报错,替换为对应的字符序。 static const int sc_minGB18030PUACharLen = 4; if (size < sc_minGB18030PUACharLen) { - qDebug() << "Size is less than min GB18030 PUA char length, returning false"; + qCDebug(appLog) << "Size is less than min GB18030 PUA char length, returning false"; replaceLen = 1; appendChar = "?"; return false; } quint32 puaChar = *reinterpret_cast(buf); - qDebug() << "Processing puaChar:" << QString::number(puaChar, 16); + qCDebug(appLog) << "Processing puaChar:" << QString::number(puaChar, 16); appendChar = gs_UTF8MapGB18030Data.key(puaChar); if (appendChar.isEmpty()) { - qDebug() << "appendChar from gs_UTF8MapGB18030Data is empty, checking gs_ReplaceToUTF8_2005Error"; + qCDebug(appLog) << "appendChar from gs_UTF8MapGB18030Data is empty, checking gs_ReplaceToUTF8_2005Error"; // FFFFFF0X -> \uE816...\uE855 appendChar = gs_ReplaceToUTF8_2005Error.key(QByteArray(buf, sc_minGB18030PUACharLen)); } - qDebug() << "appendChar after first check:" << appendChar; + qCDebug(appLog) << "appendChar after first check:" << appendChar; if (appendChar.isEmpty()) { - qDebug() << "appendChar is still empty, returning false"; + qCDebug(appLog) << "appendChar is still empty, returning false"; replaceLen = 1; appendChar = "?"; return false; } else { - qDebug() << "appendChar found, returning true, replaceLen:" << sc_minGB18030PUACharLen; + qCDebug(appLog) << "appendChar found, returning true, replaceLen:" << sc_minGB18030PUACharLen; replaceLen = sc_minGB18030PUACharLen; return true; } @@ -725,43 +726,43 @@ bool checkGB18030ToUtf8Error(char *buf, size_t size, size_t &replaceLen, QByteAr */ bool checkUTF8ToGB18030Error(char *buf, size_t size, size_t &replaceLen, QByteArray &appendChar) { - qDebug() << "checkUTF8ToGB18030Error() entry, size:" << size; + qCDebug(appLog) << "checkUTF8ToGB18030Error() entry, size:" << size; // 待转换的PUA字符均为3 static const int sc_minUTFPUACharLen = 3; if (size < sc_minUTFPUACharLen) { - qDebug() << "Size is less than min UTF PUA char length, returning false"; + qCDebug(appLog) << "Size is less than min UTF PUA char length, returning false"; replaceLen = 1; appendChar = "?"; return false; } QByteArray puaChar(buf, sc_minUTFPUACharLen); - qDebug() << "Processing puaChar:" << puaChar.toHex(); + qCDebug(appLog) << "Processing puaChar:" << puaChar.toHex(); quint32 gb18030char = gs_UTF8MapGB18030Data.value(puaChar, 0); - qDebug() << "gb18030char from gs_UTF8MapGB18030Data:" << QString::number(gb18030char, 16); + qCDebug(appLog) << "gb18030char from gs_UTF8MapGB18030Data:" << QString::number(gb18030char, 16); if (!gb18030char) { - qDebug() << "gb18030char is null, checking gs_ReplaceUtf8ToGB18030_2005Error"; + qCDebug(appLog) << "gb18030char is null, checking gs_ReplaceUtf8ToGB18030_2005Error"; // \uE816 -> 0xFE51 appendChar = gs_ReplaceUtf8ToGB18030_2005Error.value(puaChar); if (appendChar.isEmpty()) { - qDebug() << "appendChar from gs_ReplaceUtf8ToGB18030_2005Error is empty, checking gs_ReplaceFromUtf8_2020Error"; + qCDebug(appLog) << "appendChar from gs_ReplaceUtf8ToGB18030_2005Error is empty, checking gs_ReplaceFromUtf8_2020Error"; // 0xFFFF11 -> 0x95329031 appendChar = gs_ReplaceFromUtf8_2020Error.key(puaChar); } - qDebug() << "appendChar after second check:" << appendChar; + qCDebug(appLog) << "appendChar after second check:" << appendChar; if (!appendChar.isEmpty()) { - qDebug() << "appendChar found, returning true, replaceLen:" << sc_minUTFPUACharLen; + qCDebug(appLog) << "appendChar found, returning true, replaceLen:" << sc_minUTFPUACharLen; replaceLen = sc_minUTFPUACharLen; return true; } - qDebug() << "appendChar is empty, returning false"; + qCDebug(appLog) << "appendChar is empty, returning false"; replaceLen = 1; appendChar = "?"; return false; } else { - qDebug() << "gb18030char found, returning true, replaceLen:" << sc_minUTFPUACharLen; + qCDebug(appLog) << "gb18030char found, returning true, replaceLen:" << sc_minUTFPUACharLen; replaceLen = sc_minUTFPUACharLen; appendChar = QByteArray(reinterpret_cast(&gb18030char), sizeof(gb18030char)); return true; @@ -777,17 +778,17 @@ bool DetectCode::ChangeFileEncodingFormat(QByteArray &inputStr, const QString &fromCode, const QString &toCode) { - qDebug() << "[DetectCode] Enter ChangeFileEncodingFormat, from:" << fromCode << "to:" << toCode + qCDebug(appLog) << "[DetectCode] Enter ChangeFileEncodingFormat, from:" << fromCode << "to:" << toCode << "input size:" << inputStr.size(); if (fromCode == toCode) { - qDebug() << "fromCode and toCode are the same, no conversion needed"; + qCDebug(appLog) << "fromCode and toCode are the same, no conversion needed"; outStr = inputStr; return true; } if (inputStr.isEmpty()) { - qDebug() << "Input string is empty, clearing output and returning true"; + qCDebug(appLog) << "Input string is empty, clearing output and returning true"; outStr.clear(); return true; } @@ -796,40 +797,40 @@ bool DetectCode::ChangeFileEncodingFormat(QByteArray &inputStr, // 使用QTextCodec对部分编码进行处理 static QStringList codecList{"GB18030"}; if (codecList.contains(fromCode) || codecList.contains(toCode)) { - qDebug() << "Codec list contains fromCode or toCode, using convertEncodingTextCodec"; + qCDebug(appLog) << "Codec list contains fromCode or toCode, using convertEncodingTextCodec"; return convertEncodingTextCodec(inputStr, outStr, fromCode, toCode); } #endif iconv_t handle = iconv_open(toCode.toLocal8Bit().data(), fromCode.toLocal8Bit().data()); if (handle != reinterpret_cast(-1)) { - qDebug() << "iconv_open successful"; + qCDebug(appLog) << "iconv_open successful"; MibEncoding fromMib = UnknownMib; QTextCodec *fromCodec = QTextCodec::codecForName(fromCode.toUtf8()); if (fromCodec) { fromMib = static_cast(fromCodec->mibEnum()); - qDebug() << "fromMib:" << fromMib; + qCDebug(appLog) << "fromMib:" << fromMib; } // 不使用上层修改的Iconv处理时,不检测转换的编码格式,跳过GB18030转换特殊处理 MibEncoding toMib = UnknownMib; const bool enablePatchedIconv = Config::instance()->enablePatchedIconv(); if (enablePatchedIconv) { - qDebug() << "Patched Iconv enabled"; + qCDebug(appLog) << "Patched Iconv enabled"; QTextCodec *toCodec = QTextCodec::codecForName(toCode.toUtf8()); if (toCodec) { toMib = static_cast(toCodec->mibEnum()); - qDebug() << "toMib:" << toMib; + qCDebug(appLog) << "toMib:" << toMib; } // 替换需手动修改 UTF-8 和 GB180303 编码转换的部分 if (GB18030 == fromMib && UTF_8 == toMib) { - qDebug() << "Converting from GB18030 to UTF-8, applying 2005 error replacements"; + qCDebug(appLog) << "Converting from GB18030 to UTF-8, applying 2005 error replacements"; for (auto itr = gs_ReplaceFromGB18030_2005Error.begin(); itr != gs_ReplaceFromGB18030_2005Error.end(); ++itr) { inputStr.replace(itr.key(), itr.value()); } } else if (UTF_8 == fromMib && GB18030 == toMib) { - qDebug() << "Converting from UTF-8 to GB18030, applying 2020 error replacements"; + qCDebug(appLog) << "Converting from UTF-8 to GB18030, applying 2020 error replacements"; for (auto itr = gs_ReplaceToGB18030_2020Error.begin(); itr != gs_ReplaceToGB18030_2020Error.end(); ++itr) { inputStr.replace(itr.key(), itr.value()); } @@ -851,16 +852,16 @@ bool DetectCode::ChangeFileEncodingFormat(QByteArray &inputStr, do { ret = iconv(handle, &inbuf, &inbytesleft, &outbuf, &outbytesleft); if (static_cast(-1) == ret) { - qWarning() << "iconv conversion failed, errno:" << errno; + qCWarning(appLog) << "iconv conversion failed, errno:" << errno; // 记录错误信息 errorNum = errno; // 遇到错误的输入,错误码 EILSEQ (84),跳过当前位置并添加'?' if (EILSEQ == errorNum) { - qDebug() << "EILSEQ error encountered"; + qCDebug(appLog) << "EILSEQ error encountered"; // 缓冲区不足跳出 if (outbytesleft == 0) { - qWarning() << "Output buffer exhausted, breaking conversion"; + qCWarning(appLog) << "Output buffer exhausted, breaking conversion"; break; } @@ -870,10 +871,10 @@ bool DetectCode::ChangeFileEncodingFormat(QByteArray &inputStr, switch (fromMib) { case UTF_8: { - qDebug() << "UTF-8 source encoding detected"; + qCDebug(appLog) << "UTF-8 source encoding detected"; // 特殊处理,若为UTF-8 到 GB18030的转换,优先排查异常数据 if (GB18030 == toMib) { - qDebug() << "Target is GB18030, checking for UTF8ToGB18030Error"; + qCDebug(appLog) << "Target is GB18030, checking for UTF8ToGB18030Error"; if (checkUTF8ToGB18030Error(inbuf, inbytesleft, replaceLen, appendChar)) { break; } @@ -881,37 +882,37 @@ bool DetectCode::ChangeFileEncodingFormat(QByteArray &inputStr, // 源编码为 UTF-8 时,可计算需跳过的字符数 replaceLen = static_cast(utf8MultiByteCount(inbuf, inbytesleft)); - qDebug() << "Calculated replaceLen for UTF-8:" << replaceLen; + qCDebug(appLog) << "Calculated replaceLen for UTF-8:" << replaceLen; } break; case GB18030: - qDebug() << "GB18030 source encoding detected"; + qCDebug(appLog) << "GB18030 source encoding detected"; // 特殊处理,若为GB18030 到 UTF-8 的转换,优先排查异常数据 if (UTF_8 == toMib) { - qDebug() << "Target is UTF-8, checking for GB18030ToUtf8Error"; + qCDebug(appLog) << "Target is UTF-8, checking for GB18030ToUtf8Error"; if (checkGB18030ToUtf8Error(inbuf, inbytesleft, replaceLen, appendChar)) { break; } } break; default: - qDebug() << "Default case for fromMib, no special handling"; + qCDebug(appLog) << "Default case for fromMib, no special handling"; break; } // 替换错误字符为对应字符 size_t appendSize = static_cast(appendChar.size()); if (outbytesleft < appendSize) { - qWarning() << "Output buffer too small for appendChar, breaking"; + qCWarning(appLog) << "Output buffer too small for appendChar, breaking"; break; } outbytesleft -= appendSize; ::memcpy(outbuf, appendChar.data(), appendSize); outbuf += appendSize; - qDebug() << "Appended error character:" << appendChar << ", remaining outbytesleft:" << outbytesleft; + qCDebug(appLog) << "Appended error character:" << appendChar << ", remaining outbytesleft:" << outbytesleft; if (inbytesleft <= replaceLen) { - qDebug() << "No more input bytes left or replaceLen covers remaining, moving to end"; + qCDebug(appLog) << "No more input bytes left or replaceLen covers remaining, moving to end"; // 移动至末尾 inbuf += inbytesleft; inbytesleft = 0; @@ -920,41 +921,41 @@ bool DetectCode::ChangeFileEncodingFormat(QByteArray &inputStr, inbuf += replaceLen; inbytesleft -= replaceLen; - qDebug() << "Skipped" << replaceLen << "bytes from input, remaining inbytesleft:" << inbytesleft; + qCDebug(appLog) << "Skipped" << replaceLen << "bytes from input, remaining inbytesleft:" << inbytesleft; } else { - qWarning() << "[DetectCode] iconv_open failed for conversion from" << fromCode << "to" << toCode; + qCWarning(appLog) << "[DetectCode] iconv_open failed for conversion from" << fromCode << "to" << toCode; break; } } } while (static_cast(-1) == ret); } catch (const std::exception &e) { - qWarning() << qPrintable("iconv convert encoding catching exception") << qPrintable(e.what()); + qCWarning(appLog) << qPrintable("iconv convert encoding catching exception") << qPrintable(e.what()); } if (errorNum) { - qWarning() << qPrintable("iconv() convert text encoding error, errocode:") << errorNum; + qCWarning(appLog) << qPrintable("iconv() convert text encoding error, errocode:") << errorNum; } iconv_close(handle); // 手动添加 UTF BOM 信息 outStr.append(gs_byteOrderMark.value(toCode)); - qDebug() << "Appended BOM for toCode:" << toCode; + qCDebug(appLog) << "Appended BOM for toCode:" << toCode; // 计算 iconv() 实际转换的字节数 size_t realConvertSize = maxBufferSize - outbytesleft; outStr += QByteArray(bufferHeader, static_cast(realConvertSize)); - qDebug() << "Converted data size:" << realConvertSize; + qCDebug(appLog) << "Converted data size:" << realConvertSize; delete[] bufferHeader; bufferHeader = nullptr; - qDebug() << "Exit convertEncodingTextCodec, output size:" << outStr.size(); + qCDebug(appLog) << "Exit convertEncodingTextCodec, output size:" << outStr.size(); return true; } else { - qWarning() << qPrintable("Text encoding convert error, iconv_open() failed."); + qCWarning(appLog) << qPrintable("Text encoding convert error, iconv_open() failed."); // 尝试使用QTextCodec加载 return convertEncodingTextCodec(inputStr, outStr, fromCode, toCode); } @@ -969,41 +970,41 @@ bool DetectCode::convertEncodingTextCodec(QByteArray &inputStr, const QString &fromCode, const QString &toCode) { - qDebug() << "Enter convertEncodingTextCodec, from:" << fromCode << "to:" << toCode + qCDebug(appLog) << "Enter convertEncodingTextCodec, from:" << fromCode << "to:" << toCode << "input size:" << inputStr.size(); QString convertData; if (fromCode != "UTF-8") { - qDebug() << "fromCode is not UTF-8"; + qCDebug(appLog) << "fromCode is not UTF-8"; QTextCodec *fromCodec = QTextCodec::codecForName(fromCode.toUtf8()); if (!fromCodec) { - qWarning() << "Failed to get codec for fromCode:" << fromCode; + qCWarning(appLog) << "Failed to get codec for fromCode:" << fromCode; return false; } convertData = fromCodec->toUnicode(inputStr); } else { - qDebug() << "fromCode is UTF-8"; + qCDebug(appLog) << "fromCode is UTF-8"; convertData = QString::fromUtf8(inputStr); } if (toCode != "UTF-8") { - qDebug() << "toCode is not UTF-8"; + qCDebug(appLog) << "toCode is not UTF-8"; QTextCodec *toCodec = QTextCodec::codecForName(toCode.toUtf8()); if (!toCodec) { - qWarning() << "Failed to get codec for toCode:" << toCode; + qCWarning(appLog) << "Failed to get codec for toCode:" << toCode; return false; } outStr = toCodec->fromUnicode(convertData); } else { - qDebug() << "toCode is UTF-8"; + qCDebug(appLog) << "toCode is UTF-8"; outStr = convertData.toUtf8(); } // 手动添加 UTF BOM 信息:BOM 必须写在转换结果之前(BOM+data), // 与上方 iconv 主路径的字节序保持一致,否则 UTF-16 目标产生 "data+BOM" 错误序列 outStr.prepend(gs_byteOrderMark.value(toCode)); - qDebug() << "Exit convertEncodingTextCodec, output size:" << outStr.size(); + qCDebug(appLog) << "Exit convertEncodingTextCodec, output size:" << outStr.size(); return true; } diff --git a/src/logger.cpp b/src/logger.cpp new file mode 100644 index 000000000..e5c768c1e --- /dev/null +++ b/src/logger.cpp @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "logger.h" + +#include +#include + +#ifdef DTKCORE_CLASS_DConfigFile +#include +#endif +DCORE_USE_NAMESPACE + +MLogger::MLogger(QObject *parent) + : QObject(parent), m_rules("") +#ifdef DTKCORE_CLASS_DConfigFile + , m_config(nullptr) +#endif +{ + QByteArray logRules = qgetenv("QT_LOGGING_RULES"); + // qunsetenv 之前一定不要有任何日志打印,否则取消环境变量设置不会生效 + qunsetenv("QT_LOGGING_RULES"); + + // set env + m_rules = logRules; + +#ifdef DTKCORE_CLASS_DConfigFile + // set dconfig + m_config = DConfig::create("org.deepin.editor", "org.deepin.editor"); + logRules = m_config->value("log_rules").toByteArray(); + appendRules(logRules); + setRules(m_rules); + + // 监听 dconfig 变更,实现运行中动态调整 + connect(m_config, &DConfig::valueChanged, this, [this](const QString &key) { + if (key == "log_rules") { + setRules(m_config->value(key).toByteArray()); + } + }); +#else + setRules(m_rules); +#endif +} + +MLogger::~MLogger() +{ +#ifdef DTKCORE_CLASS_DConfigFile + if (m_config) { + m_config->deleteLater(); + } +#endif +} + +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/src/logger.h b/src/logger.h new file mode 100644 index 000000000..b8ed46448 --- /dev/null +++ b/src/logger.h @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef DEEPIN_EDITOR_LOGGER_H +#define DEEPIN_EDITOR_LOGGER_H + +#include +#include + +#ifdef DTKCORE_CLASS_DConfigFile +DCORE_BEGIN_NAMESPACE +class DConfig; +DCORE_END_NAMESPACE +#endif + +// 动态日志规则管理:从 DConfig(log_rules) 读取过滤规则并监听变更, +// 支持调试模式(deepin-debug-config)运行中动态调整日志级别 +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; +#ifdef DTKCORE_CLASS_DConfigFile + Dtk::Core::DConfig *m_config; +#endif +}; + +#endif // DEEPIN_EDITOR_LOGGER_H diff --git a/src/main.cpp b/src/main.cpp index 4ccf78b67..bec1ac0aa 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,6 +2,8 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" +#include "logger.h" #include "environments.h" #include "utils.h" #include "window.h" @@ -30,7 +32,11 @@ DWIDGET_USE_NAMESPACE int main(int argc, char *argv[]) { - qDebug() << "Application starting with arguments:" << QCoreApplication::arguments(); + // 动态日志规则初始化:从 DConfig 读取 log_rules 并监听变更(调试模式), + // 必须在任何日志打印之前实例化 + MLogger logger; + + qCDebug(appLog) << "Application starting with arguments:" << QCoreApplication::arguments(); DCORE_USE_NAMESPACE PerformanceMonitor::initializeAppStart(); @@ -46,18 +52,18 @@ int main(int argc, char *argv[]) // sw_64(申威):V8 JIT 不支持,必须 jitless 纯解释执行,否则渲染进程崩溃; // 合并 --disable-gpu 一次性设置,避免被分段设置覆盖(参考 deepin-manual bug-347387) qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --single-process --js-flags=--jitless"); - qDebug() << "Set QTWEBENGINE_CHROMIUM_FLAGS for sw_64: --disable-gpu --single-process --js-flags=--jitless"; + qCDebug(appLog) << "Set QTWEBENGINE_CHROMIUM_FLAGS for sw_64: --disable-gpu --single-process --js-flags=--jitless"; #else // 通用(含 x86/arm64/loongarch64/mips):禁用 GPU 合成走软件渲染, // 规避国产平台显卡驱动兼容问题(参考 deepin-manual 全架构处理) qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu"); - qDebug() << "Set QTWEBENGINE_CHROMIUM_FLAGS=--disable-gpu"; + qCDebug(appLog) << "Set QTWEBENGINE_CHROMIUM_FLAGS=--disable-gpu"; # ifndef __mips__ // 非 Wayland 会话追加 --single-process(渲染进程并入主进程,加快首屏并规避 // 欧拉 root 下 no-sandbox 报错);mips 上实测有问题须禁用(deepin-manual de2df4a4) if (!isWaylandSession) { qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --single-process"); - qDebug() << "Non-Wayland session, set --single-process additionally"; + qCDebug(appLog) << "Non-Wayland session, set --single-process additionally"; } # endif #endif @@ -66,71 +72,71 @@ int main(int argc, char *argv[]) qputenv("DTK_FORCE_RASTER_WIDGETS", "FALSE"); if (!QString(qgetenv("XDG_CURRENT_DESKTOP")).toLower().startsWith("deepin")) { - qDebug() << "XDG_CURRENT_DESKTOP not set to Deepin, setting environment variable"; + qCDebug(appLog) << "XDG_CURRENT_DESKTOP not set to Deepin, setting environment variable"; setenv("XDG_CURRENT_DESKTOP", "Deepin", 1); } else { - qDebug() << "XDG_CURRENT_DESKTOP already set to:" << qgetenv("XDG_CURRENT_DESKTOP"); + qCDebug(appLog) << "XDG_CURRENT_DESKTOP already set to:" << qgetenv("XDG_CURRENT_DESKTOP"); } - qDebug() << "XDG_CURRENT_DESKTOP set to:" << qgetenv("XDG_CURRENT_DESKTOP"); + qCDebug(appLog) << "XDG_CURRENT_DESKTOP set to:" << qgetenv("XDG_CURRENT_DESKTOP"); QCoreApplication::setAttribute(Qt::AA_UseOpenGLES); // QWebEngineView 硬性前提:共享 GL 上下文必须在 QApplication 构造前设置, // 否则 Markdown 渲染视图无法创建共享上下文导致白屏(Qt6 文档要求) QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); - qDebug() << "Qt::AA_UseOpenGLES / AA_ShareOpenGLContexts attributes set"; + qCDebug(appLog) << "Qt::AA_UseOpenGLES / AA_ShareOpenGLContexts attributes set"; EditorApplication app(argc, argv); - qInfo() << "Application instance created, version:" << app.applicationVersion(); + qCInfo(appLog) << "Application instance created, version:" << app.applicationVersion(); // save theme // DApplicationSettings savetheme; // 需在App构造后初始化日志设置 DLogManager::registerConsoleAppender(); DLogManager::registerFileAppender(); - qDebug() << "Log system initialized"; + qCDebug(appLog) << "Log system initialized"; // Parser input arguments. QCommandLineParser parser; const QCommandLineOption newWindowOption("w", "Open file in new window"); const QCommandLineOption helpOption = parser.addHelpOption(); parser.addOption(newWindowOption); parser.process(app); - qDebug() << "Command line arguments processed, positional args:" << parser.positionalArguments().size(); + qCDebug(appLog) << "Command line arguments processed, positional args:" << parser.positionalArguments().size(); - qInfo() << qPrintable(QString("App start, pid: %1, version: %2").arg(app.applicationPid()).arg(app.applicationVersion())); + qCInfo(appLog) << qPrintable(QString("App start, pid: %1, version: %2").arg(app.applicationPid()).arg(app.applicationVersion())); QStringList urls; QStringList arguments = parser.positionalArguments(); - qDebug() << "Processing" << arguments.size() << "file arguments"; + qCDebug(appLog) << "Processing" << arguments.size() << "file arguments"; for (const QString &path : arguments) { UrlInfo info(path); urls << info.url.toLocalFile(); QFileInfo fileInfo(path); - qInfo() << qPrintable(QString("Open file, isFile: %1, suffix: %2, size: %3, permssion: %4").arg(fileInfo.isFile()) + qCInfo(appLog) << qPrintable(QString("Open file, isFile: %1, suffix: %2, size: %3, permssion: %4").arg(fileInfo.isFile()) .arg(fileInfo.suffix()).arg(fileInfo.size()).arg(static_cast(fileInfo.permissions()))); } bool hasWindowFlag = parser.isSet(newWindowOption); - qDebug() << "New window flag set:" << hasWindowFlag; + qCDebug(appLog) << "New window flag set:" << hasWindowFlag; QDBusConnection dbus = QDBusConnection::sessionBus(); // Start editor process if not found any editor use DBus. - qDebug() << "Attempting to register DBus service"; + qCDebug(appLog) << "Attempting to register DBus service"; if (dbus.registerService("com.deepin.Editor")) { - qInfo() << "DBus service registered successfully"; + qCInfo(appLog) << "DBus service registered successfully"; #ifdef DTKWIDGET_CLASS_DSizeMode - qDebug() << "DTKWIDGET_CLASS_DSizeMode defined, setting up size mode handler"; + qCDebug(appLog) << "DTKWIDGET_CLASS_DSizeMode defined, setting up size mode handler"; // 不同模式下的基础字体像素大小不同,系统级别为 T6 的字体大小, 默认是 14px ;在紧凑模式下 T6 为 12px QObject::connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, []() { const int genericPixelSize = 14; const int genericPixelSizeCompact = 12; bool isCompact = DGuiApplicationHelper::isCompactMode(); - qDebug() << "Size mode changed, compact mode:" << isCompact; + qCDebug(appLog) << "Size mode changed, compact mode:" << isCompact; DFontSizeManager::instance()->setFontGenericPixelSize( DGuiApplicationHelper::isCompactMode() ? genericPixelSizeCompact : genericPixelSize); }); #else - qDebug() << "DTKWIDGET_CLASS_DSizeMode not defined, skipping size mode handler"; + qCDebug(appLog) << "DTKWIDGET_CLASS_DSizeMode not defined, skipping size mode handler"; #endif // 单例唯一创建点;D-Bus 转发进程走不到这里,不会实例化 StartManager @@ -143,42 +149,42 @@ int main(int argc, char *argv[]) {"mode", 1}, }; Eventlogutils::GetInstance()->writeLogs(objStartEvent); - qDebug() << "Startup event logged with version:" << VERSION; + qCDebug(appLog) << "Startup event logged with version:" << VERSION; bool save_tab_before_close = Settings::instance()->settings->option("advance.startup.save_tab_before_close")->value().toBool(); if (!save_tab_before_close && urls.isEmpty()) { - qDebug() << "No files to open and save_tab_before_close is false, creating window with blank tab"; + qCDebug(appLog) << "No files to open and save_tab_before_close is false, creating window with blank tab"; auto window = startManager->createWindow(true); window->addBlankTab(); } else { if (hasWindowFlag) { - qDebug() << "Opening" << urls.size() << "files in new window"; + qCDebug(appLog) << "Opening" << urls.size() << "files in new window"; startManager->openFilesInWindow(urls); } else { - qDebug() << "Opening" << urls.size() << "files in current window"; + qCDebug(appLog) << "Opening" << urls.size() << "files in current window"; startManager->openFilesInTab(urls); } } #if _ZPD_ - qDebug() << "ZPD customization enabled, loading custom DLL"; + qCDebug(appLog) << "ZPD customization enabled, loading custom DLL"; // 解析ZPD定制需求提供的库libzpdcallback.so Utils::loadCustomDLL(); #endif dbus.registerObject("/com/deepin/Editor", startManager, QDBusConnection::ExportScriptableSlots); - qDebug() << "DBus object registered at /com/deepin/Editor"; + qCDebug(appLog) << "DBus object registered at /com/deepin/Editor"; PerformanceMonitor::initializeAppFinish(); - qDebug() << "Entering main event loop"; + qCDebug(appLog) << "Entering main event loop"; int ret = app.exec(); // 事件循环已停止,在此显式释放单例;~EditorApplication 不再管理其生命周期 - qDebug() << "Deleting StartManager instance on exit"; + qCDebug(appLog) << "Deleting StartManager instance on exit"; delete StartManager::instance(); return ret; } // Just send dbus message to exist editor process. else { - qInfo() << "Another editor instance detected, sending commands via DBus"; + qCInfo(appLog) << "Another editor instance detected, sending commands via DBus"; QDBusInterface notification( "com.deepin.Editor", "/com/deepin/Editor", "com.deepin.Editor", QDBusConnection::sessionBus()); @@ -186,14 +192,14 @@ int main(int argc, char *argv[]) args << urls; if (hasWindowFlag) { - qDebug() << "Calling openFilesInWindow via DBus with" << urls.size() << "files"; + qCDebug(appLog) << "Calling openFilesInWindow via DBus with" << urls.size() << "files"; notification.callWithArgumentList(QDBus::AutoDetect, "openFilesInWindow", args); } else { - qDebug() << "Calling openFilesInTab via DBus with" << urls.size() << "files"; + qCDebug(appLog) << "Calling openFilesInTab via DBus with" << urls.size() << "files"; notification.callWithArgumentList(QDBus::AutoDetect, "openFilesInTab", args); } } - qDebug() << "Application exiting with code 0"; + qCDebug(appLog) << "Application exiting with code 0"; return 0; } diff --git a/src/startmanager.cpp b/src/startmanager.cpp index 232dc5d33..e615c73ba 100644 --- a/src/startmanager.cpp +++ b/src/startmanager.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "startmanager.h" //#include #include @@ -35,7 +36,7 @@ StartManager *StartManager::m_instance = nullptr; StartManager *StartManager::create() { if (m_instance == nullptr) { - qDebug() << "StartManager instance is null, creating new instance"; + qCDebug(appLog) << "StartManager instance is null, creating new instance"; m_instance = new StartManager; } @@ -49,7 +50,7 @@ StartManager *StartManager::instance() StartManager::~StartManager() { - qDebug() << "Enter StartManager destructor"; + qCDebug(appLog) << "Enter StartManager destructor"; // 单例被销毁(应用退出/测试 deleteLater)后置空,避免 instance() 返回悬空指针 if (m_instance == this) { m_instance = nullptr; @@ -64,31 +65,31 @@ StartManager::~StartManager() StartManager::StartManager(QObject *parent) : QObject(parent) { - qDebug() << "Enter StartManager constructor"; + qCDebug(appLog) << "Enter StartManager constructor"; //m_bIsDragEnter = false; //Create blank directory if it not exist. initBlockShutdown(); - qDebug() << "inited block shutdown"; + qCDebug(appLog) << "inited block shutdown"; m_blankFileDir = QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()).filePath("blank-files"); m_backupDir = QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()).filePath("backup-files"); m_autoBackupDir = QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()).filePath("autoBackup-files"); if (!QFileInfo(m_blankFileDir).exists()) { - qDebug() << "blank file dir not exist, create it"; + qCDebug(appLog) << "blank file dir not exist, create it"; QDir().mkpath(m_blankFileDir); } if (!QFileInfo(m_backupDir).exists()) { - qDebug() << "backup file dir not exist, create it"; + qCDebug(appLog) << "backup file dir not exist, create it"; QDir().mkpath(m_backupDir); } m_qlistTemFile = Settings::instance()->settings->option("advance.editor.browsing_history_temfile")->value().toStringList(); // 初始化书签信息记录表 initBookmark(); - qDebug() << "inited bookmark"; + qCDebug(appLog) << "inited bookmark"; //按时间自动备份(5分钟) m_pTimer = new QTimer; @@ -97,13 +98,13 @@ StartManager::StartManager(QObject *parent) // init flytek backend, check service valid IflytekAiAssistant::instance()->checkAiExists(); - qInfo() << "StartManager initialized with backup interval:" << EAutoBackupInterval << "ms"; - qDebug() << "Exit StartManager constructor"; + qCInfo(appLog) << "StartManager initialized with backup interval:" << EAutoBackupInterval << "ms"; + qCDebug(appLog) << "Exit StartManager constructor"; } bool StartManager::checkPath(const QString &file) { - qDebug() << "Enter checkPath, file:" << file; + qCDebug(appLog) << "Enter checkPath, file:" << file; for (int i = 0; i < m_windows.count(); i++) { EditWrapper *wrapper = m_windows.value(i)->wrapper(file); @@ -112,47 +113,47 @@ bool StartManager::checkPath(const QString &file) // Open exist tab if file has opened. popupExistTabs(info); - qDebug() << "Exit checkPath, return false"; + qCDebug(appLog) << "Exit checkPath, return false"; return false; } } - qDebug() << "Exit checkPath, return true"; + qCDebug(appLog) << "Exit checkPath, return true"; return true; } bool StartManager::ifKlu() { - qDebug() << "Enter ifKlu"; + qCDebug(appLog) << "Enter ifKlu"; auto e = QProcessEnvironment::systemEnvironment(); QString XDG_SESSION_TYPE = e.value(QStringLiteral("XDG_SESSION_TYPE")); QString WAYLAND_DISPLAY = e.value(QStringLiteral("WAYLAND_DISPLAY")); if (XDG_SESSION_TYPE == QLatin1String("wayland") || WAYLAND_DISPLAY.contains(QLatin1String("wayland"), Qt::CaseInsensitive)) { - qDebug() << "Exit ifKlu, return true"; + qCDebug(appLog) << "Exit ifKlu, return true"; return true; } else { - qDebug() << "Exit ifKlu, return false"; + qCDebug(appLog) << "Exit ifKlu, return false"; return false; } } bool StartManager::isMultiWindow() { - qDebug() << "Enter isMultiWindow"; + qCDebug(appLog) << "Enter isMultiWindow"; if (m_windows.count() > 1) { - qDebug() << "Exit isMultiWindow, return true"; + qCDebug(appLog) << "Exit isMultiWindow, return true"; return true; } - qDebug() << "Exit isMultiWindow, return false"; + qCDebug(appLog) << "Exit isMultiWindow, return false"; return false; } bool StartManager::hasEmptyTemFile() { - qDebug() << "Enter hasEmptyTemFile"; + qCDebug(appLog) << "Enter hasEmptyTemFile"; bool bIsEmpty = false; for (auto temFile : m_qlistTemFile) { @@ -161,28 +162,28 @@ bool StartManager::hasEmptyTemFile() } } - qDebug() << "Exit hasEmptyTemFile, return" << bIsEmpty; + qCDebug(appLog) << "Exit hasEmptyTemFile, return" << bIsEmpty; return bIsEmpty; } void StartManager::autoBackupFile() { - qDebug() << "Enter autoBackupFile"; + qCDebug(appLog) << "Enter autoBackupFile"; // 标签页在拖拽状态时不执行备份 if (m_bIsTagDragging) { - qDebug() << "Exit autoBackupFile, return"; + qCDebug(appLog) << "Exit autoBackupFile, return"; return; } //如果自动备份文件夹不存在,创建自动备份文件夹 if (!QFileInfo(m_autoBackupDir).exists()) { - qDebug() << "Auto backup dir not exist, create it"; + qCDebug(appLog) << "Auto backup dir not exist, create it"; QDir().mkpath(m_autoBackupDir); } else { - qDebug() << "Auto backup dir exist, remove user backup"; + qCDebug(appLog) << "Auto backup dir exist, remove user backup"; //有用户备份时删除用户备份 if (!QDir(m_backupDir).isEmpty()) { - qDebug() << "User backup exist, remove it"; + qCDebug(appLog) << "User backup exist, remove it"; QDir(m_backupDir).removeRecursively(); } } @@ -209,7 +210,7 @@ void StartManager::autoBackupFile() for (EditWrapper *wrapper : wrappers) { //大文件加载时不备份 if (wrapper->getFileLoading()) { - qDebug() << "File loading, skip auto backup, continue"; + qCDebug(appLog) << "File loading, skip auto backup, continue"; continue; } @@ -219,7 +220,7 @@ void StartManager::autoBackupFile() // 懒加载兼容:使用当前窗口 TabBar 的本地索引,避免跨窗口索引错位 int tabIndex = tabbar->indexOf(filePath); if (tabIndex < 0) { - qWarning() << "autoBackupFile: tab not found for path:" << filePath << ", skip"; + qCWarning(appLog) << "autoBackupFile: tab not found for path:" << filePath << ", skip"; continue; } curPos = QString::number(wrapper->textEditor()->textCursor().position()); @@ -237,7 +238,7 @@ void StartManager::autoBackupFile() QList bookmarkList = wrapper->textEditor()->getBookmarkInfo(); if (!bookmarkList.isEmpty()) { - qDebug() << "File has bookmark, record it"; + qCDebug(appLog) << "File has bookmark, record it"; QString bookmarkInfo; for (int i = 0; i < bookmarkList.count(); i++) { @@ -253,7 +254,7 @@ void StartManager::autoBackupFile() // 更新记录全局书签信息 m_bookmarkTable.insert(localPath, bookmarkList); } else { - qDebug() << "File has no bookmark, remove it"; + qCDebug(appLog) << "File has no bookmark, remove it"; // 无书签,移除 m_bookmarkTable.remove(localPath); } @@ -267,12 +268,12 @@ void StartManager::autoBackupFile() //保存备份文件 if (Utils::isDraftFile(filePath)) { - qDebug() << "File is draft, save it as temporary file"; + qCDebug(appLog) << "File is draft, save it as temporary file"; wrapper->saveTemFile(filePath); } else { - qDebug() << "File is not draft, save it as backup file"; + qCDebug(appLog) << "File is not draft, save it as backup file"; if (wrapper->isModified()) { - qDebug() << "File is modified, save it as backup file"; + qCDebug(appLog) << "File is modified, save it as backup file"; QString name = fileInfo.absolutePath().replace("/", "_"); QString qstrFilePath = m_autoBackupDir + "/" + Utils::getStringMD5Hash(fileInfo.baseName()) + "." + name + "." + fileInfo.suffix(); jsonObject.insert("temFilePath", qstrFilePath); @@ -287,7 +288,7 @@ void StartManager::autoBackupFile() if (tabIndex < list.size()) { list.replace(tabIndex, byteArray); } else { - qWarning() << "autoBackupFile: tabIndex" << tabIndex << "out of range (size" << list.size() << "), appending"; + qCWarning(appLog) << "autoBackupFile: tabIndex" << tabIndex << "out of range (size" << list.size() << "), appending"; list.append(byteArray); } } @@ -320,36 +321,36 @@ void StartManager::autoBackupFile() m_qlistTemFile.append(list); } - qDebug() << "Exit autoBackupFile"; + qCDebug(appLog) << "Exit autoBackupFile"; //将json串列表写入配置文件 - qInfo() << __func__ << "history file counts:" << m_qlistTemFile.size(); + qCInfo(appLog) << __func__ << "history file counts:" << m_qlistTemFile.size(); Settings::instance()->settings->option("advance.editor.browsing_history_temfile")->setValue(m_qlistTemFile); // 备份书签信息 saveBookmark(); - qDebug() << "Exit autoBackupFile"; + qCDebug(appLog) << "Exit autoBackupFile"; } int StartManager::recoverFile(Window *window) { - qDebug() << "Enter recoverFile"; + qCDebug(appLog) << "Enter recoverFile"; Window *pFocusWindow = nullptr; QString focusPath; QStringList blankFiles = QDir(m_blankFileDir).entryList(QStringList(), QDir::Files); - qDebug() << "Found" << blankFiles.size() << "blank files in directory:" << m_blankFileDir; + qCDebug(appLog) << "Found" << blankFiles.size() << "blank files in directory:" << m_blankFileDir; int recFilesSum = 0; QStringList files = blankFiles; //去除非新建文件 for (auto file : blankFiles) { if (!file.contains("blank_file")) { files.removeOne(file); - qDebug() << "Removed non-blank file from list:" << file; + qCDebug(appLog) << "Removed non-blank file from list:" << file; } } - qDebug() << "After filtering, found" << files.size() << "blank files"; + qCDebug(appLog) << "After filtering, found" << files.size() << "blank files"; // 第一阶段:解析所有 JSON 记录 - qDebug() << "Processing" << m_qlistTemFile.count() << "temporary files for recovery"; + qCDebug(appLog) << "Processing" << m_qlistTemFile.count() << "temporary files for recovery"; QVector tabRecords; for (int i = 0; i < m_qlistTemFile.count(); i++) { QJsonParseError jsonError; @@ -358,7 +359,7 @@ int StartManager::recoverFile(Window *window) tabRecords.append(doucment.object()); } } - qDebug() << "Parsed" << tabRecords.size() << "valid tab records"; + qCDebug(appLog) << "Parsed" << tabRecords.size() << "valid tab records"; // 找到焦点标签页 int focusIndex = -1; @@ -366,14 +367,14 @@ int StartManager::recoverFile(Window *window) const QJsonObject &obj = tabRecords[i]; if (obj.contains("focus") && obj.value("focus").toBool()) { focusIndex = i; - qDebug() << "Found focus tab at index:" << focusIndex; + qCDebug(appLog) << "Found focus tab at index:" << focusIndex; break; } } // 如果没有焦点标签页,默认第一个 if (focusIndex == -1 && !tabRecords.isEmpty()) { focusIndex = 0; - qDebug() << "No focus tab found, using first tab as focus"; + qCDebug(appLog) << "No focus tab found, using first tab as focus"; } int windowIndex = -1; @@ -393,7 +394,7 @@ int StartManager::recoverFile(Window *window) int cursorPosition = -1; QList bookmarks; - qDebug() << "Processing record" << (i + 1) << "of" << tabRecords.size() + qCDebug(appLog) << "Processing record" << (i + 1) << "of" << tabRecords.size() << "(focus:" << (i == focusIndex) << ")"; // 解析公共字段 @@ -415,9 +416,9 @@ int StartManager::recoverFile(Window *window) if (object.contains("localPath") && object.value("localPath").isString()) { localPath = object.value("localPath").toString(); QFileInfo fi(localPath); - qDebug() << "Local file path:" << localPath << "exists:" << fi.exists(); + qCDebug(appLog) << "Local file path:" << localPath << "exists:" << fi.exists(); if (!fi.exists()) { - qWarning() << "Local file does not exist, skipping:" << localPath; + qCWarning(appLog) << "Local file does not exist, skipping:" << localPath; continue; } } @@ -445,10 +446,10 @@ int StartManager::recoverFile(Window *window) int newWindowIdx = static_cast(object.value("window").toDouble()); if (windowIndex == -1) { windowIndex = newWindowIdx; - qDebug() << "First window index:" << windowIndex; + qCDebug(appLog) << "First window index:" << windowIndex; } else if (windowIndex != newWindowIdx) { windowIndex = newWindowIdx; - qDebug() << "New window index:" << windowIndex << ", creating window"; + qCDebug(appLog) << "New window index:" << windowIndex << ", creating window"; window = createWindow(true); window->showCenterWindow(false); window->setBatchAddingPendingTabs(true); @@ -464,11 +465,11 @@ int StartManager::recoverFile(Window *window) // 恢复书签 if (!bookmarks.isEmpty()) { - qDebug() << "Setting bookmarks for focus tab:" << bookmarks; + qCDebug(appLog) << "Setting bookmarks for focus tab:" << bookmarks; if (auto *w = window->wrapper(openPath)) w->textEditor()->setBookMarkList(bookmarks); } else if (m_bookmarkTable.contains(openPath)) { - qDebug() << "Setting bookmarks from global config for focus tab:" << openPath; + qCDebug(appLog) << "Setting bookmarks from global config for focus tab:" << openPath; if (auto *w = window->wrapper(openPath)) w->textEditor()->setBookMarkList(m_bookmarkTable.value(openPath)); } @@ -490,7 +491,7 @@ int StartManager::recoverFile(Window *window) recFilesSum++; } } - qDebug() << "Pending tabs added, total:" << recFilesSum << "tabs"; + qCDebug(appLog) << "Pending tabs added, total:" << recFilesSum << "tabs"; // 恢复所有参与恢复窗口的 handleCurrentChanged 懒加载能力 for (Window *w : recoveryWindows) { @@ -499,103 +500,103 @@ int StartManager::recoverFile(Window *window) // 激活焦点标签页 if (pFocusWindow != nullptr && !focusPath.isNull()) { - qDebug() << "Activating focus tab:" << focusPath; + qCDebug(appLog) << "Activating focus tab:" << focusPath; FileTabInfo info; info.windowIndex = m_windows.indexOf(pFocusWindow); info.tabIndex = pFocusWindow->getTabIndex(focusPath); popupExistTabs(info); } else if (recFilesSum > 0 && window->getTabbar()->count() > 0) { // 焦点标签页文件不存在或无焦点记录,加载第一个可用标签页 - qDebug() << "No focus tab available, loading first tab"; + qCDebug(appLog) << "No focus tab available, loading first tab"; window->activeTab(0); } - qInfo() << "Recovered files count:" << recFilesSum; - qDebug() << "Exit recoverFile"; + qCInfo(appLog) << "Recovered files count:" << recFilesSum; + qCDebug(appLog) << "Exit recoverFile"; return recFilesSum; } void StartManager::openFilesInWindow(QStringList files) { - qDebug() << "Enter openFilesInWindow, file count:" << files.size(); + qCDebug(appLog) << "Enter openFilesInWindow, file count:" << files.size(); // Open window with blank tab if no files need open. if (files.isEmpty()) { if (m_windows.count() >= 20) { - qWarning() << "Maximum window limit (20) reached, cannot create new window"; + qCWarning(appLog) << "Maximum window limit (20) reached, cannot create new window"; return; } Window *window = createWindow(); - qDebug() << "Created new window with no files"; + qCDebug(appLog) << "Created new window with no files"; if (m_windows.count() > 0) { - qDebug() << "Multiple windows exist, showing new window without centering"; + qCDebug(appLog) << "Multiple windows exist, showing new window without centering"; window->showCenterWindow(false); } else { - qDebug() << "First window, showing centered"; + qCDebug(appLog) << "First window, showing centered"; window->showCenterWindow(true); } window->addBlankTab(); window->activateWindow(); - qDebug() << "Added blank tab and activated window"; + qCDebug(appLog) << "Added blank tab and activated window"; } else { - qDebug() << "Processing files to open in window:" << files; + qCDebug(appLog) << "Processing files to open in window:" << files; for (const QString &file : files) { QString resolvedFile = Utils::getFilePath(file); - qDebug() << "Processing file:" << file << "resolved path:" << resolvedFile; + qCDebug(appLog) << "Processing file:" << file << "resolved path:" << resolvedFile; FileTabInfo info = getFileTabInfo(resolvedFile); // Open exist tab if file has opened. if (info.windowIndex != -1) { - qDebug() << "File already open in window" << info.windowIndex << "tab" << info.tabIndex << ", activating"; + qCDebug(appLog) << "File already open in window" << info.windowIndex << "tab" << info.tabIndex << ", activating"; popupExistTabs(info); } // Add new tab in current window. else { - qDebug() << "File not open, creating new window and tab"; + qCDebug(appLog) << "File not open, creating new window and tab"; Window *window = createWindow(); window->showCenterWindow(true); window->addTab(resolvedFile); - qDebug() << "Added tab for file:" << resolvedFile; + qCDebug(appLog) << "Added tab for file:" << resolvedFile; } } } - qDebug() << "Exit openFilesInWindow"; + qCDebug(appLog) << "Exit openFilesInWindow"; } void StartManager::openFilesInTab(QStringList files) { - qDebug() << "Enter openFilesInTab, file count:" << files.size(); + qCDebug(appLog) << "Enter openFilesInTab, file count:" << files.size(); if (files.isEmpty()) { - qDebug() << "No files to open, checking blank files directory"; + qCDebug(appLog) << "No files to open, checking blank files directory"; QDir blankDirectory = QDir(QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()).filePath("blank-files")); QStringList blankFiles = blankDirectory.entryList(QStringList(), QDir::Files); - qDebug() << "Found" << blankFiles.size() << "blank files"; + qCDebug(appLog) << "Found" << blankFiles.size() << "blank files"; if (m_windows.isEmpty()) { - qDebug() << "No windows exist, creating first window"; + qCDebug(appLog) << "No windows exist, creating first window"; Window *window = createWindow(true); window->showCenterWindow(true); if (!hasEmptyTemFile()) { - qDebug() << "Temporary files exist, attempting to recover"; + qCDebug(appLog) << "Temporary files exist, attempting to recover"; int recoveredCount = recoverFile(window); - qDebug() << "Recovered" << recoveredCount << "files"; + qCDebug(appLog) << "Recovered" << recoveredCount << "files"; if (recoveredCount == 0) { - qDebug() << "No files recovered, adding blank tab"; + qCDebug(appLog) << "No files recovered, adding blank tab"; window->addBlankTab(); } } else { - qDebug() << "No temporary files, checking blank files"; + qCDebug(appLog) << "No temporary files, checking blank files"; if (blankFiles.isEmpty()) { - qDebug() << "No blank files, adding new blank tab"; + qCDebug(appLog) << "No blank files, adding new blank tab"; window->addBlankTab(); } else { - qDebug() << "Cleaning up blank files and adding new blank tab"; + qCDebug(appLog) << "Cleaning up blank files and adding new blank tab"; for (auto file : blankFiles) { if (file.contains("blank_file")) { blankDirectory.remove(file); - qDebug() << "Removed blank file:" << file; + qCDebug(appLog) << "Removed blank file:" << file; } } @@ -605,19 +606,19 @@ void StartManager::openFilesInTab(QStringList files) } // Just active first window if no file is need opened. else { - qDebug() << "Windows already exist, creating new window with blank tab"; + qCDebug(appLog) << "Windows already exist, creating new window with blank tab"; Window *window = createWindow(); window->show(); window->addBlankTab(); } } else { - qDebug() << "Processing" << files.size() << "files to open in tabs"; + qCDebug(appLog) << "Processing" << files.size() << "files to open in tabs"; for (const QString &file : files) { QString resolvedFile = Utils::getFilePath(file); - qDebug() << "Processing file:" << file << "resolved path:" << resolvedFile; + qCDebug(appLog) << "Processing file:" << file << "resolved path:" << resolvedFile; if (!checkPath(resolvedFile)) { - qDebug() << "File already open, skipping:" << resolvedFile; + qCDebug(appLog) << "File already open, skipping:" << resolvedFile; // 存在已打开文件时,进行下一文件判断 continue; } @@ -626,44 +627,44 @@ void StartManager::openFilesInTab(QStringList files) // Open exist tab if file has opened. if (info.windowIndex != -1) { - qDebug() << "File found in existing window" << info.windowIndex << ", activating tab" << info.tabIndex; + qCDebug(appLog) << "File found in existing window" << info.windowIndex << ", activating tab" << info.tabIndex; popupExistTabs(info); } // Create new window with file if haven't window exist. else if (m_windows.size() == 0) { - qDebug() << "No windows exist, creating first window for file"; + qCDebug(appLog) << "No windows exist, creating first window for file"; Window *window = createWindow(true); window->showCenterWindow(true); // 以 window 为 context:窗口在延时期间被销毁则不触发,避免悬空调用 QTimer::singleShot(50, window, [ = ] { - qDebug() << "Delayed file opening for:" << resolvedFile; + qCDebug(appLog) << "Delayed file opening for:" << resolvedFile; recoverFile(window); window->addTab(resolvedFile); }); } // Open file tab in first window of window list. else { - qDebug() << "Opening file in first existing window"; + qCDebug(appLog) << "Opening file in first existing window"; Window *window = m_windows[0]; window->addTab(resolvedFile); - qDebug() << "Added tab for file:" << resolvedFile << "in existing window"; + qCDebug(appLog) << "Added tab for file:" << resolvedFile << "in existing window"; //window->setWindowState(Qt::WindowActive); //通过dbus接口从任务栏激活窗口 if (!Q_LIKELY(Utils::activeWindowFromDock(window->winId()))) { - qDebug() << "Activating window via Qt (DBus activation failed)"; + qCDebug(appLog) << "Activating window via Qt (DBus activation failed)"; window->activateWindow(); } else { - qDebug() << "Window activated via DBus"; + qCDebug(appLog) << "Window activated via DBus"; } } } } - qDebug() << "Exit openFilesInTab"; + qCDebug(appLog) << "Exit openFilesInTab"; } void StartManager::createWindowFromWrapper(const QString &tabName, const QString &filePath, const QString &qstrTruePath, EditWrapper *buffer, bool isModifyed) { - qDebug() << "Enter createWindowFromWrapper"; + qCDebug(appLog) << "Enter createWindowFromWrapper"; Window *pWindow = createWindow(); //window->showCenterWindow(); QRect rect = pWindow->rect(); @@ -677,18 +678,18 @@ void StartManager::createWindowFromWrapper(const QString &tabName, const QString if ((pos.x() + rect.width()) > desktopRect.width()) { startPos.setX(desktopRect.width() - rect.width()); - qDebug() << "Window position out of desktop, adjusting x"; + qCDebug(appLog) << "Window position out of desktop, adjusting x"; } else if (pos.x() < 0) { startPos.setX(0); - qDebug() << "Window position out of desktop, adjusting x"; + qCDebug(appLog) << "Window position out of desktop, adjusting x"; } if ((pos.y() + rect.height()) > desktopRect.height()) { startPos.setY(desktopRect.height() - rect.height()); - qDebug() << "Window position out of desktop, adjusting y"; + qCDebug(appLog) << "Window position out of desktop, adjusting y"; } else if (pos.y() < 0) { startPos.setY(0); - qDebug() << "Window position out of desktop, adjusting y"; + qCDebug(appLog) << "Window position out of desktop, adjusting y"; } // 拖拽 pixmap 仅在真实鼠标拖拽时创建;编程式触发(如 handleTabDroped 回退)下可能为空,回退为窗口尺寸 @@ -730,7 +731,7 @@ void StartManager::createWindowFromWrapper(const QString &tabName, const QString geometry->deleteLater(); group->deleteLater(); if (bufferGuard.isNull()) { - qDebug() << "createWindowFromWrapper: buffer destroyed during animation, drop tear-off"; + qCDebug(appLog) << "createWindowFromWrapper: buffer destroyed during animation, drop tear-off"; return; } @@ -747,45 +748,45 @@ void StartManager::createWindowFromWrapper(const QString &tabName, const QString group->addAnimation(geometry); // group->addAnimation(Opacity); group->start(); - qDebug() << "Exit createWindowFromWrapper"; + qCDebug(appLog) << "Exit createWindowFromWrapper"; } void StartManager::loadTheme(const QString &themeName) { - qDebug() << "Enter loadTheme, themeName:" << themeName; + qCDebug(appLog) << "Enter loadTheme, themeName:" << themeName; for (Window *window : m_windows) { window->loadTheme(themeName); } - qDebug() << "Exit loadTheme"; + qCDebug(appLog) << "Exit loadTheme"; } Window *StartManager::createWindow(bool alwaysCenter) { - qDebug() << "Enter createWindow, alwaysCenter:" << alwaysCenter; + qCDebug(appLog) << "Enter createWindow, alwaysCenter:" << alwaysCenter; // Create window. Window *window = new Window; - qDebug() << "Window object created, connecting signals"; + qCDebug(appLog) << "Window object created, connecting signals"; connect(window, &Window::themeChanged, this, &StartManager::loadTheme, Qt::QueuedConnection); connect(window, &Window::sigJudgeBlockShutdown, this, &StartManager::slotCheckUnsaveTab, Qt::QueuedConnection); connect(window, &Window::tabChanged, this, &StartManager::slotDelayBackupFile, Qt::QueuedConnection); // Quit application if close last window. connect(window, &Window::closeWindow, this, &StartManager::slotCloseWindow); - qDebug() << "Window signals connected"; + qCDebug(appLog) << "Window signals connected"; // Init window position. initWindowPosition(window, alwaysCenter); - qDebug() << "Window position initialized, alwaysCenter:" << alwaysCenter; + qCDebug(appLog) << "Window position initialized, alwaysCenter:" << alwaysCenter; connect(window, &Window::newWindow, this, &StartManager::slotCreatNewwindow); // 标签页拖拽状态变更时触发,防止在拖拽过程中备份导致获取的标签状态异常 connect(window->getTabbar(), &DTabBar::dragStarted, this, [this](){ - qDebug() << "Tab drag started, pausing backup"; + qCDebug(appLog) << "Tab drag started, pausing backup"; m_bIsTagDragging = true; }); connect(window->getTabbar(), &DTabBar::dragEnd, this, [this](){ - qDebug() << "Tab drag ended, resuming backup"; + qCDebug(appLog) << "Tab drag ended, resuming backup"; m_bIsTagDragging = false; slotDelayBackupFile(); }); @@ -793,25 +794,25 @@ Window *StartManager::createWindow(bool alwaysCenter) // Append window in window list. m_windows << window; - qInfo() << "Window created, total windows:" << m_windows.size(); - qDebug() << "Exit createWindow"; + qCInfo(appLog) << "Window created, total windows:" << m_windows.size(); + qCDebug(appLog) << "Exit createWindow"; return window; } void StartManager::slotCloseWindow() { - qDebug() << "Enter slotCloseWindow"; + qCDebug(appLog) << "Enter slotCloseWindow"; Window *pWindow = static_cast(sender()); int windowIndex = m_windows.indexOf(pWindow); if (windowIndex >= 0) { - qDebug() << "Window closed, index:" << windowIndex; + qCDebug(appLog) << "Window closed, index:" << windowIndex; m_windows.takeAt(windowIndex); } if (m_windows.isEmpty()) { - qDebug() << "No remaining windows, saving bookmark"; + qCDebug(appLog) << "No remaining windows, saving bookmark"; // 保存书签信息 saveBookmark(); @@ -823,10 +824,10 @@ void StartManager::slotCloseWindow() QStringList nameList = path.entryList(); foreach (auto name, nameList) { if (name.contains("tabPaths.txt")) { - qDebug() << "Delete tabPaths.txt"; + qCDebug(appLog) << "Delete tabPaths.txt"; // entryList 返回裸文件名,拼绝对路径后再删除,避免落点依赖进程工作目录 if (!QFile::remove(path.absoluteFilePath(name))) { - qWarning() << "Failed to remove tabPaths.txt:" << path.absoluteFilePath(name); + qCWarning(appLog) << "Failed to remove tabPaths.txt:" << path.absoluteFilePath(name); } } } @@ -843,18 +844,18 @@ void StartManager::slotCloseWindow() PerformanceMonitor::closeAppFinish(); } - qDebug() << "Exit slotCloseWindow"; + qCDebug(appLog) << "Exit slotCloseWindow"; } void StartManager::slotDelayBackupFile() { - qDebug() << "Enter slotDelayBackupFile"; + qCDebug(appLog) << "Enter slotDelayBackupFile"; // 判断定时器是否已在触发状态,防止短时间内的多次触发,标签页拖拽状态不触发 if (!m_DelayTimer.isActive() && !m_bIsTagDragging) { - qDebug() << "Start timer for delay backup"; + qCDebug(appLog) << "Start timer for delay backup"; m_DelayTimer.start(EDelayBackupInterval, this); } - qDebug() << "Exit slotDelayBackupFile"; + qCDebug(appLog) << "Exit slotDelayBackupFile"; } void StartManager::delayMallocTrim() @@ -866,10 +867,10 @@ void StartManager::delayMallocTrim() void StartManager::timerEvent(QTimerEvent *e) { - qDebug() << "Enter timerEvent"; + qCDebug(appLog) << "Enter timerEvent"; // 判断是否为延迟备份 if (e->timerId() == m_DelayTimer.timerId()) { - qDebug() << "Timer expired, backup file"; + qCDebug(appLog) << "Timer expired, backup file"; m_DelayTimer.stop(); // 执行配置文件备份 autoBackupFile(); @@ -877,29 +878,29 @@ void StartManager::timerEvent(QTimerEvent *e) // 重启周期定时备份 m_pTimer->start(EAutoBackupInterval); } - qDebug() << "Exit timerEvent"; + qCDebug(appLog) << "Exit timerEvent"; if (e->timerId() == m_FreeMemTimer.timerId()) { m_FreeMemTimer.stop(); malloc_trim(0); - qInfo() << "malloc_trim over"; + qCInfo(appLog) << "malloc_trim over"; } } void StartManager::slotCreatNewwindow() { - qDebug() << "Enter slotCreatNewwindow"; + qCDebug(appLog) << "Enter slotCreatNewwindow"; openFilesInWindow(QStringList()); } void StartManager::initWindowPosition(Window *window, bool alwaysCenter) { - qDebug() << "Enter initWindowPosition"; + qCDebug(appLog) << "Enter initWindowPosition"; if (m_windows.isEmpty() || alwaysCenter) { - qDebug() << "No existing windows or alwaysCenter is true, centering window"; + qCDebug(appLog) << "No existing windows or alwaysCenter is true, centering window"; //Dtk::Widget::moveToCenter(window); } else { - qDebug() << "Adding window offset to avoid all editor window popup at same coordinate"; + qCDebug(appLog) << "Adding window offset to avoid all editor window popup at same coordinate"; // Add window offset to avoid all editor window popup at same coordinate. int windowOffset = m_windows.size() * 50; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) @@ -909,19 +910,19 @@ void StartManager::initWindowPosition(Window *window, bool alwaysCenter) #endif window->move(screenGeometry.x() + windowOffset, screenGeometry.y() + windowOffset); } - qDebug() << "Exit initWindowPosition"; + qCDebug(appLog) << "Exit initWindowPosition"; } void StartManager::popupExistTabs(FileTabInfo info) { - qDebug() << "Enter popupExistTabs"; + qCDebug(appLog) << "Enter popupExistTabs"; Window *window = m_windows[info.windowIndex]; //window->showNormal(); window->activeTab(info.tabIndex); //window->setWindowState(Qt::WindowActive); //通过dbus接口从任务栏激活窗口 if (!Q_LIKELY(Utils::activeWindowFromDock(window->winId()))) { - qDebug() << "Window not active from Dock, activating manually"; + qCDebug(appLog) << "Window not active from Dock, activating manually"; window->activateWindow(); } @@ -963,33 +964,33 @@ void StartManager::popupExistTabs(FileTabInfo info) active << winid; QDBusConnection::sessionBus().call(active, QDBus::BlockWithGui); #endif - qDebug() << "Exit popupExistTabs"; + qCDebug(appLog) << "Exit popupExistTabs"; } StartManager::FileTabInfo StartManager::getFileTabInfo(QString file) { - qDebug() << "Enter getFileTabInfo"; + qCDebug(appLog) << "Enter getFileTabInfo"; FileTabInfo info = {-1, -1}; - //qDebug() << "Windows size: " << m_windows.size(); + //qCDebug(appLog) << "Windows size: " << m_windows.size(); for (Window *window : m_windows) { int tabIndex = window->getTabIndex(file); if (tabIndex >= 0) { info.windowIndex = m_windows.indexOf(window); info.tabIndex = tabIndex; - qDebug() << "Break, File found in window " << info.windowIndex << " tab " << tabIndex; + qCDebug(appLog) << "Break, File found in window " << info.windowIndex << " tab " << tabIndex; break; } } - qDebug() << "Exit getFileTabInfo"; + qCDebug(appLog) << "Exit getFileTabInfo"; return info; } QList StartManager::analyzeBookmakeInfo(QString bookmarkInfo) { - qDebug() << "Enter analyzeBookmakeInfo"; + qCDebug(appLog) << "Enter analyzeBookmakeInfo"; QList bookmarkList; int nLeftPosition = 0; int nRightPosition = bookmarkInfo.indexOf(","); @@ -1002,7 +1003,7 @@ QList StartManager::analyzeBookmakeInfo(QString bookmarkInfo) nLeftPosition = nRightPosition; } - qDebug() << "Exit analyzeBookmakeInfo"; + qCDebug(appLog) << "Exit analyzeBookmakeInfo"; return bookmarkList; } @@ -1013,9 +1014,9 @@ QList StartManager::analyzeBookmakeInfo(QString bookmarkInfo) */ void StartManager::recordBookmark(const QString &localPath, const QList &bookmark) { - qDebug() << "Enter recordBookmark"; + qCDebug(appLog) << "Enter recordBookmark"; m_bookmarkTable.insert(localPath, bookmark); - qDebug() << "Exit recordBookmark"; + qCDebug(appLog) << "Exit recordBookmark"; } /** @@ -1023,15 +1024,15 @@ void StartManager::recordBookmark(const QString &localPath, const QList &bo */ QList StartManager::findBookmark(const QString &localPath) { - qDebug() << "Enter findBookmark"; + qCDebug(appLog) << "Enter findBookmark"; return m_bookmarkTable.value(localPath); } void StartManager::initBlockShutdown() { - qDebug() << "Enter initBlockShutdown"; + qCDebug(appLog) << "Enter initBlockShutdown"; if (m_reply.value().isValid()) { - qDebug() << "reply is valid, block shutdown"; + qCDebug(appLog) << "reply is valid, block shutdown"; return; } @@ -1047,10 +1048,10 @@ void StartManager::initBlockShutdown() m_reply = m_pLoginManager->callWithArgumentList(QDBus::Block, "Inhibit", m_arg); if (m_reply.isValid()) { - qDebug() << "Inhibit reply is valid"; + qCDebug(appLog) << "Inhibit reply is valid"; //m_reply.value().fileDescriptor(); } - qDebug() << "Exit initBlockShutdown"; + qCDebug(appLog) << "Exit initBlockShutdown"; } /** @@ -1059,7 +1060,7 @@ void StartManager::initBlockShutdown() */ void StartManager::initBookmark() { - qDebug() << "Enter initBookmark"; + qCDebug(appLog) << "Enter initBookmark"; // 遍历书签信息列表 QStringList bookmarkInfoList = Settings::instance()->settings->value(s_bookMarkKey).toStringList(); for (const QString &bookmarkInfo : bookmarkInfoList) { @@ -1075,10 +1076,10 @@ void StartManager::initBookmark() && QFileInfo::exists(filePath)) { QString bookmarkStr = obj.value("bookmark").toString(); if (!bookmarkStr.isEmpty()) { - qDebug() << "bookmarkStr:" << bookmarkStr; + qCDebug(appLog) << "bookmarkStr:" << bookmarkStr; QList bookmarkList = analyzeBookmakeInfo(bookmarkStr); if (!bookmarkList.isEmpty()) { - qDebug() << "bookmarkList:" << bookmarkList; + qCDebug(appLog) << "bookmarkList:" << bookmarkList; // 文件存在且书签标记非空,缓存书签信息 m_bookmarkTable.insert(filePath, bookmarkList); } @@ -1086,7 +1087,7 @@ void StartManager::initBookmark() } } } - qDebug() << "Exit initBookmark"; + qCDebug(appLog) << "Exit initBookmark"; } /** @@ -1095,7 +1096,7 @@ void StartManager::initBookmark() */ void StartManager::saveBookmark() { - qDebug() << "Enter saveBookmark"; + qCDebug(appLog) << "Enter saveBookmark"; QStringList recordInfo; // 遍历记录 for (auto itr = m_bookmarkTable.begin(); itr != m_bookmarkTable.end();) { @@ -1103,9 +1104,9 @@ void StartManager::saveBookmark() || itr.value().isEmpty()) { // 文件不存在则销毁记录 itr = m_bookmarkTable.erase(itr); - qDebug() << "File not exist, remove bookmark record"; + qCDebug(appLog) << "File not exist, remove bookmark record"; } else { - qDebug() << "File exist, save bookmark record"; + qCDebug(appLog) << "File exist, save bookmark record"; QJsonObject obj; obj.insert("localPath", itr.key()); @@ -1125,53 +1126,53 @@ void StartManager::saveBookmark() recordInfo.append(doc.toJson(QJsonDocument::Compact)); ++itr; - qDebug() << "Exit slotCheckUnsaveTab"; + qCDebug(appLog) << "Exit slotCheckUnsaveTab"; } } // 将书签信息保存至配置文件 Settings::instance()->settings->option(s_bookMarkKey)->setValue(recordInfo); - qDebug() << "Exit saveBookmark"; + qCDebug(appLog) << "Exit saveBookmark"; } void StartManager::slotCheckUnsaveTab() { - qDebug() << "Enter slotCheckUnsaveTab"; + qCDebug(appLog) << "Enter slotCheckUnsaveTab"; for (Window *pWindow : m_windows) { //如果返回true,则表示有未保存的tab项,则阻塞系统关机 bool bRet = pWindow->checkBlockShutdown(); if (bRet == true) { m_reply = m_pLoginManager->callWithArgumentList(QDBus::Block, "Inhibit", m_arg); if (m_reply.isValid()) { - qDebug() << "Inhibit reply is valid"; + qCDebug(appLog) << "Inhibit reply is valid"; } - qDebug() << "Find unsaved tab, block shutdown"; + qCDebug(appLog) << "Find unsaved tab, block shutdown"; return; } } //如果for结束则表示没有发现未保存的tab项,则放开阻塞关机 if (m_reply.isValid()) { - qDebug() << "No unsaved tab, unblock shutdown"; + qCDebug(appLog) << "No unsaved tab, unblock shutdown"; m_reply = QDBusReply(); } - qDebug() << "Exit slotCheckUnsaveTab"; + qCDebug(appLog) << "Exit slotCheckUnsaveTab"; } void StartManager::closeAboutForWindow(Window *window) { - qDebug() << "Enter closeAboutForWindow"; + qCDebug(appLog) << "Enter closeAboutForWindow"; if (qApp != nullptr) { DAboutDialog *pAboutDialog = qApp->aboutDialog(); if (pAboutDialog != nullptr) { if (pAboutDialog->parent() != nullptr) { if (pAboutDialog->parent() == window) { pAboutDialog->close(); - qDebug() << "Close about dialog for window"; + qCDebug(appLog) << "Close about dialog for window"; } } } } - qDebug() << "Exit closeAboutForWindow"; + qCDebug(appLog) << "Exit closeAboutForWindow"; } diff --git a/src/thememodule/themeitemdelegate.cpp b/src/thememodule/themeitemdelegate.cpp index 1cf12d16f..715b2e5ba 100644 --- a/src/thememodule/themeitemdelegate.cpp +++ b/src/thememodule/themeitemdelegate.cpp @@ -1,7 +1,8 @@ -// SPDX-FileCopyrightText: 2017 - 2022 UnionTech Software Technology Co., Ltd. +// SPDX-FileCopyrightText: 2017-2026 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "themeitemdelegate.h" #include "themelistmodel.h" #include "../common/utils.h" @@ -11,17 +12,17 @@ ThemeItemDelegate::ThemeItemDelegate(QObject *parent) : QAbstractItemDelegate(parent) { - qDebug() << "ThemeItemDelegate constructor"; + qCDebug(appLog) << "ThemeItemDelegate constructor"; } ThemeItemDelegate::~ThemeItemDelegate() { - qDebug() << "ThemeItemDelegate destructor"; + qCDebug(appLog) << "ThemeItemDelegate destructor"; } void ThemeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - // qDebug() << "Start painting theme item for index:" << index.row(); + // qCDebug(appLog) << "Start painting theme item for index:" << index.row(); const QString &themePath = index.data(ThemeListModel::ThemePath).toString(); const QString &themeName = index.data(ThemeListModel::ThemeName).toString(); QVariantMap jsonMap = Utils::getThemeMapFromPath(themePath); @@ -50,7 +51,7 @@ void ThemeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt int paddingY = 8; // draw background. - // qDebug() << "Drawing background for theme item"; + // qCDebug(appLog) << "Drawing background for theme item"; QPainterPath backgroundPath; backgroundPath.addRoundedRect(QRect(rect.x() + paddingX, rect.y() + paddingY, @@ -62,7 +63,7 @@ void ThemeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt painter->fillPath(backgroundPath, QColor(backgroundColor)); // draw frame. - // qDebug() << "Drawing frame for theme item"; + // qCDebug(appLog) << "Drawing frame for theme item"; QPainterPath framePath; framePath.addRoundedRect(QRect(rect.x() + paddingX, rect.y() + paddingY, @@ -136,11 +137,11 @@ void ThemeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt int bracketY = includeY + lineHeight * 4; painter->setPen(QPen(QColor(normalColor))); painter->drawText(QRect(rect.x() + bracketX, rect.y() + bracketY, rect.width(), lineHeight), Qt::AlignLeft | Qt::AlignTop, "}"); - // qDebug() << "Finished painting theme item"; + // qCDebug(appLog) << "Finished painting theme item"; } QSize ThemeItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { - qDebug() << "Getting size hint for theme item"; + qCDebug(appLog) << "Getting size hint for theme item"; return QSize(-1, 130); } diff --git a/src/thememodule/themelistmodel.cpp b/src/thememodule/themelistmodel.cpp index 343d18cae..17863d344 100644 --- a/src/thememodule/themelistmodel.cpp +++ b/src/thememodule/themelistmodel.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "themelistmodel.h" #include "../common/utils.h" #include @@ -13,31 +14,31 @@ ThemeListModel::ThemeListModel(QObject *parent) : QAbstractListModel(parent) { - qDebug() << "ThemeListModel constructor"; + qCDebug(appLog) << "ThemeListModel constructor"; initThemes(); } ThemeListModel::~ThemeListModel() { - qDebug() << "ThemeListModel destructor"; + qCDebug(appLog) << "ThemeListModel destructor"; } void ThemeListModel::setFrameColor(const QString &selectedColor, const QString &normalColor) { - qInfo() << "Setting frame colors - selected:" << selectedColor << "normal:" << normalColor; + qCInfo(appLog) << "Setting frame colors - selected:" << selectedColor << "normal:" << normalColor; m_frameSelectedColor = selectedColor; m_frameNormalColor = normalColor; } void ThemeListModel::setSelection(const QString &path) { - qDebug() << "Setting selection for theme path:" << path; + qCDebug(appLog) << "Setting selection for theme path:" << path; for (auto pair : m_themes) { if (path == pair.second) { const int row = m_themes.indexOf(pair); const QModelIndex &idx = QAbstractListModel::index(row, 0); emit requestCurrentIndex(idx); - qDebug() << "Break, Selection set for theme path:" << path; + qCDebug(appLog) << "Break, Selection set for theme path:" << path; break; } } @@ -52,10 +53,10 @@ QVariant ThemeListModel::data(const QModelIndex &index, int role) const { // 按 QAbstractItemModel 契约校验索引有效性,无效索引返回 QVariant() if (!index.isValid() || index.row() < 0 || index.row() >= m_themes.size()) { - qWarning() << "Invalid index for row:" << index.row(); + qCWarning(appLog) << "Invalid index for row:" << index.row(); return QVariant(); } - qDebug() << "Getting data for row:" << index.row() << "role:" << role; + qCDebug(appLog) << "Getting data for row:" << index.row() << "role:" << role; const int r = index.row(); const QString &name = m_themes.at(r).first; @@ -63,26 +64,26 @@ QVariant ThemeListModel::data(const QModelIndex &index, int role) const switch (role) { case ThemeName: - qDebug() << "Theme name:" << name; + qCDebug(appLog) << "Theme name:" << name; return name; case ThemePath: - qDebug() << "Theme path:" << path; + qCDebug(appLog) << "Theme path:" << path; return path; case FrameNormalColor: - qDebug() << "Frame normal color:" << m_frameNormalColor; + qCDebug(appLog) << "Frame normal color:" << m_frameNormalColor; return m_frameNormalColor; case FrameSelectedColor: - qDebug() << "Frame selected color:" << m_frameSelectedColor; + qCDebug(appLog) << "Frame selected color:" << m_frameSelectedColor; return m_frameSelectedColor; } - qDebug() << "No data for role:" << role; + qCDebug(appLog) << "No data for role:" << role; return QVariant(); } void ThemeListModel::initThemes() { - qDebug() << "Initializing theme list"; + qCDebug(appLog) << "Initializing theme list"; QFileInfoList infoList = QDir(QString("%1share/deepin-editor/themes").arg(LINGLONG_PREFIX)).entryInfoList(QDir::Files | QDir::NoDotAndDotDot); for (QFileInfo info : infoList) { @@ -91,11 +92,11 @@ void ThemeListModel::initThemes() pair.first = jsonMap["metadata"].toMap()["name"].toString(); pair.second = info.filePath(); - qDebug() << "Found theme:" << pair.first << "at path:" << pair.second; + qCDebug(appLog) << "Found theme:" << pair.first << "at path:" << pair.second; m_themes << pair; } - qDebug() << "Sorting themes by background lightness"; + qCDebug(appLog) << "Sorting themes by background lightness"; std::sort(m_themes.begin(), m_themes.end(), [=] (QPair &a, QPair &b) { QVariantMap firstMap = Utils::getThemeMapFromPath(a.second); @@ -107,5 +108,5 @@ void ThemeListModel::initThemes() return QColor(firstColor).lightness() < QColor(secondColor).lightness(); }); - qDebug() << "Themes:" << m_themes; + qCDebug(appLog) << "Themes:" << m_themes; } diff --git a/src/thememodule/themelistview.cpp b/src/thememodule/themelistview.cpp index d817ffd6b..6b4a76aed 100644 --- a/src/thememodule/themelistview.cpp +++ b/src/thememodule/themelistview.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "themelistview.h" #include "themelistmodel.h" #include @@ -12,7 +13,7 @@ ThemeListView::ThemeListView(QWidget *parent) : QListView(parent) { - qDebug() << "ThemeListView constructor"; + qCDebug(appLog) << "ThemeListView constructor"; installEventFilter(this); setVerticalScrollMode(ScrollPerPixel); @@ -24,17 +25,17 @@ ThemeListView::ThemeListView(QWidget *parent) ThemeListView::~ThemeListView() { - qDebug() << "ThemeListView destructor"; + qCDebug(appLog) << "ThemeListView destructor"; } void ThemeListView::adjustScrollbarMargins() { if (!isVisible()) { - qDebug() << "View not visible, skipping scrollbar adjustment"; + qCDebug(appLog) << "View not visible, skipping scrollbar adjustment"; return; } - qInfo() << "Adjusting scrollbar margins"; + qCInfo(appLog) << "Adjusting scrollbar margins"; QEvent event(QEvent::LayoutRequest); QApplication::sendEvent(this, &event); @@ -46,7 +47,7 @@ void ThemeListView::adjustScrollbarMargins() bool ThemeListView::eventFilter(QObject *, QEvent *event) { if (event->type() == QEvent::FocusOut) { - qDebug() << "Focus out event detected"; + qCDebug(appLog) << "Focus out event detected"; emit focusOut(); } @@ -55,13 +56,13 @@ bool ThemeListView::eventFilter(QObject *, QEvent *event) void ThemeListView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { - qDebug() << "Selection changed"; + qCDebug(appLog) << "Selection changed"; QListView::selectionChanged(selected, deselected); QModelIndexList list = selectionModel()->selectedIndexes(); for (const QModelIndex &index : list) { const QString &themePath = index.data(ThemeListModel::ThemePath).toString(); - qDebug() << "Selected theme path:" << themePath; + qCDebug(appLog) << "Selected theme path:" << themePath; emit themeChanged(themePath); } diff --git a/src/thememodule/themepanel.cpp b/src/thememodule/themepanel.cpp index 35097b237..429ea9191 100644 --- a/src/thememodule/themepanel.cpp +++ b/src/thememodule/themepanel.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "themepanel.h" #include "../widgets/window.h" @@ -18,7 +19,7 @@ ThemePanel::ThemePanel(QWidget *parent) m_themeModel(new ThemeListModel), m_window(static_cast(parent)) { - qDebug() << "ThemePanel constructor"; + qCDebug(appLog) << "ThemePanel constructor"; // init view. m_themeView->setAccessibleName("ThemeListView"); m_themeView->setObjectName("ThemeView"); @@ -43,12 +44,12 @@ ThemePanel::ThemePanel(QWidget *parent) m_themeView->setCurrentIndex(idx); m_themeView->scrollTo(idx); }); - qDebug() << "ThemePanel initialized"; + qCDebug(appLog) << "ThemePanel initialized"; } ThemePanel::~ThemePanel() { - qDebug() << "ThemePanel destructor"; + qCDebug(appLog) << "ThemePanel destructor"; } void ThemePanel::paintEvent(QPaintEvent *e) @@ -67,27 +68,27 @@ void ThemePanel::paintEvent(QPaintEvent *e) } void ThemePanel::setBackground(const QString &color) { - qDebug() << "Setting panel background color:" << color; + qCDebug(appLog) << "Setting panel background color:" << color; m_backgroundColor = QColor(color); if (m_backgroundColor.lightness() < 128) { - qDebug() << "Background color is dark"; + qCDebug(appLog) << "Background color is dark"; m_frameColor = m_frameDarkColor; } else { - qDebug() << "Background color is light"; + qCDebug(appLog) << "Background color is light"; m_frameColor = m_frameLightColor; } update(); - qDebug() << "Panel background color set"; + qCDebug(appLog) << "Panel background color set"; } void ThemePanel::popup() { - qDebug() << "Showing theme panel with animation"; + qCDebug(appLog) << "Showing theme panel with animation"; // parent 非 Window(或为空)时 m_window 无效,直接早退避免空指针解引用 if (!m_window) { - qWarning() << "Theme panel has no host window, skip popup"; + qCWarning(appLog) << "Theme panel has no host window, skip popup"; QWidget::show(); return; } @@ -107,15 +108,15 @@ void ThemePanel::popup() connect(animation, &QPropertyAnimation::valueChanged, this, [=] { m_themeView->adjustScrollbarMargins(); }); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); - qDebug() << "popup end"; + qCDebug(appLog) << "popup end"; } void ThemePanel::hide() { - qDebug() << "Hiding theme panel with animation"; + qCDebug(appLog) << "Hiding theme panel with animation"; // parent 非 Window(或为空)时 m_window 无效,直接早退避免空指针解引用 if (!m_window) { - qWarning() << "Theme panel has no host window, hide directly"; + qCWarning(appLog) << "Theme panel has no host window, hide directly"; QWidget::hide(); return; } @@ -131,17 +132,17 @@ void ThemePanel::hide() connect(animation, &QPropertyAnimation::finished, this, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); - qDebug() << "hide end"; + qCDebug(appLog) << "hide end"; } void ThemePanel::setFrameColor(const QString &selectedColor, const QString &normalColor) { - qDebug() << "Setting frame color:" << selectedColor << normalColor; + qCDebug(appLog) << "Setting frame color:" << selectedColor << normalColor; m_themeModel->setFrameColor(selectedColor, normalColor); } void ThemePanel::setSelectionTheme(const QString &path) { - qDebug() << "Setting selected theme path:" << path; + qCDebug(appLog) << "Setting selected theme path:" << path; m_themeModel->setSelection(path); } diff --git a/src/widgets/ColorSelectWdg.cpp b/src/widgets/ColorSelectWdg.cpp index 93dc48388..a56a045f4 100644 --- a/src/widgets/ColorSelectWdg.cpp +++ b/src/widgets/ColorSelectWdg.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "ColorSelectWdg.h" #include "../common/utils.h" #include "../common/settings.h" @@ -13,22 +14,22 @@ ColorLabel::ColorLabel(QColor color,QWidget *parent) : DWidget(parent), m_color(color) { - qDebug() << "ColorLabel constructor"; + qCDebug(appLog) << "ColorLabel constructor"; setMouseTracking(true); } void ColorLabel::setColorSelected(bool bSelect) { - qDebug() << "Setting color selected state:" << bSelect; + qCDebug(appLog) << "Setting color selected state:" << bSelect; if(m_bSelected == bSelect) { - qDebug() << "Color selected state is the same as current state, no need to update"; + qCDebug(appLog) << "Color selected state is the same as current state, no need to update"; return; } m_bSelected = bSelect; update(); - qDebug() << "Color selected state updated to:" << m_bSelected; + qCDebug(appLog) << "Color selected state updated to:" << m_bSelected; } bool ColorLabel::isSelected() @@ -123,86 +124,86 @@ void ColorLabel::leaveEvent(QEvent *event) void ColorLabel::mousePressEvent(QMouseEvent *e) { - qDebug() << "ColorLabel mouse press event"; + qCDebug(appLog) << "ColorLabel mouse press event"; if (e->button() == Qt::LeftButton) { m_bPressed = true; update(); } DWidget::mousePressEvent(e); - qDebug() << "ColorLabel mouse press event end"; + qCDebug(appLog) << "ColorLabel mouse press event end"; } void ColorLabel::mouseReleaseEvent(QMouseEvent *e) { - qDebug() << "ColorLabel mouse release event"; + qCDebug(appLog) << "ColorLabel mouse release event"; if (e->button() == Qt::LeftButton && m_bPressed) { m_bPressed = false; m_bSelected = true; update(); emit sigColorClicked(m_bSelected, m_color); - qDebug() << "ColorLabel mouse release event, color selected state updated to:" << m_bSelected; + qCDebug(appLog) << "ColorLabel mouse release event, color selected state updated to:" << m_bSelected; } DWidget::mouseReleaseEvent(e); - qDebug() << "ColorLabel mouse release event end"; + qCDebug(appLog) << "ColorLabel mouse release event end"; } ColorSelectWdg::ColorSelectWdg(QString text,QWidget *parent):DWidget (parent),m_text(text) { - qDebug() << "ColorSelectWdg constructor with text:" << text; + qCDebug(appLog) << "ColorSelectWdg constructor with text:" << text; setFocusPolicy(Qt::NoFocus); setMouseTracking(true); if(!text.isEmpty())setFixedHeight(60); else setFixedHeight(35); initWidget(); - qDebug() << "ColorSelectWdg constructor end"; + qCDebug(appLog) << "ColorSelectWdg constructor end"; } ColorSelectWdg::~ColorSelectWdg() { - qDebug() << "ColorSelectWdg destructor"; + qCDebug(appLog) << "ColorSelectWdg destructor"; if (m_pHLayout2 != nullptr) { - qDebug() << "ColorSelectWdg destructor, deleting m_pHLayout2"; + qCDebug(appLog) << "ColorSelectWdg destructor, deleting m_pHLayout2"; delete m_pHLayout2; m_pHLayout2=nullptr; } if (m_pHLayout1 != nullptr) { - qDebug() << "ColorSelectWdg destructor, deleting m_pHLayout1"; + qCDebug(appLog) << "ColorSelectWdg destructor, deleting m_pHLayout1"; delete m_pHLayout1; m_pHLayout1=nullptr; } if (m_pMainLayout != nullptr) { - qDebug() << "ColorSelectWdg destructor, deleting m_pMainLayout"; + qCDebug(appLog) << "ColorSelectWdg destructor, deleting m_pMainLayout"; delete m_pMainLayout; m_pMainLayout=nullptr; } - qDebug() << "ColorSelectWdg destructor end"; + qCDebug(appLog) << "ColorSelectWdg destructor end"; } void ColorSelectWdg::initWidget() { - qDebug() << "ColorSelectWdg initWidget"; + qCDebug(appLog) << "ColorSelectWdg initWidget"; if(m_text.isEmpty()){ - qDebug() << "ColorSelectWdg initWidget, text is empty, using default layout"; + qCDebug(appLog) << "ColorSelectWdg initWidget, text is empty, using default layout"; m_pHLayout2 = new QHBoxLayout(this); } else { - qDebug() << "ColorSelectWdg initWidget, text is not empty, using custom layout"; + qCDebug(appLog) << "ColorSelectWdg initWidget, text is not empty, using custom layout"; m_pMainLayout = new QVBoxLayout(this); m_pHLayout2 = new QHBoxLayout; } if(!m_text.isEmpty()){ - qDebug() << "ColorSelectWdg initWidget, text is not empty, creating button"; + qCDebug(appLog) << "ColorSelectWdg initWidget, text is not empty, creating button"; m_pButton = new DPushButton(m_text,this); m_pButton->setObjectName("PButton"); m_pButton->setAccessibleName("PButton"); m_pButton->setMinimumSize(80,25); m_pButton->setFlat(true); connect(m_pButton,&QPushButton::clicked,this,[this](){ - qInfo() << "Color select button clicked, default color:" << m_defaultColor.name(); + qCInfo(appLog) << "Color select button clicked, default color:" << m_defaultColor.name(); //发送选择信号 emit this->sigColorSelected(true,m_defaultColor); }); @@ -215,9 +216,9 @@ void ColorSelectWdg::initWidget() //第一个设置默认标记颜色 if(i == 0){ - qDebug() << "ColorSelectWdg initWidget, setting default color to:" << colors[i].name(); + qCDebug(appLog) << "ColorSelectWdg initWidget, setting default color to:" << colors[i].name(); m_defaultColor = colors[i]; - qDebug() << "Setting default color to:" << m_defaultColor.name(); + qCDebug(appLog) << "Setting default color to:" << m_defaultColor.name(); colorlabel->setColorSelected(true); } @@ -226,11 +227,11 @@ void ColorSelectWdg::initWidget() connect(colorlabel,&ColorLabel::sigColorClicked,this,[this,colorlabel](bool bSelect,QColor color){ if(bSelect){ - qDebug() << "Color label clicked, selected color:" << color.name(); + qCDebug(appLog) << "Color label clicked, selected color:" << color.name(); foreach(ColorLabel* pLabel,m_colorLabels){ //如果选择 设置其他颜色label为未选中状态 if(pLabel != colorlabel && pLabel->isSelected()) { - qDebug() << "Deselecting color label:" << pLabel->getColor().name(); + qCDebug(appLog) << "Deselecting color label:" << pLabel->getColor().name(); pLabel->setColorSelected(false); } } @@ -242,7 +243,7 @@ void ColorSelectWdg::initWidget() } if(!m_text.isEmpty()){ - qDebug() << "ColorSelectWdg initWidget, text is not empty, creating button layout"; + qCDebug(appLog) << "ColorSelectWdg initWidget, text is not empty, creating button layout"; m_pHLayout1 = new QHBoxLayout; m_pHLayout1->addWidget(m_pButton); m_pHLayout1->addSpacerItem(new QSpacerItem(100,25,QSizePolicy::Expanding,QSizePolicy::Preferred)); @@ -255,26 +256,26 @@ void ColorSelectWdg::initWidget() m_pMainLayout->setContentsMargins(0,0,0,0); //this->setLayout(m_pMainLayout); }else { - qDebug() << "ColorSelectWdg initWidget, text is empty, setting layout margins"; + qCDebug(appLog) << "ColorSelectWdg initWidget, text is empty, setting layout margins"; m_pHLayout2->setContentsMargins(8+m_labelWidth,0,8+m_labelWidth,0); //this->setLayout(m_pHLayout2); } - qDebug() << "ColorSelectWdg initWidget end"; + qCDebug(appLog) << "ColorSelectWdg initWidget end"; } void ColorSelectWdg::setTheme(const QString &theme) { - qDebug() << "ColorSelectWdg setTheme, theme:" << theme; + qCDebug(appLog) << "ColorSelectWdg setTheme, theme:" << theme; //获取主题颜色 if(theme == "light") { m_textColor = "#1f1c1b"; - qDebug() << "ColorSelectWdg setTheme, theme is light"; + qCDebug(appLog) << "ColorSelectWdg setTheme, theme is light"; }else if(theme == "dark"){ m_textColor = "#cfcfc2"; - qDebug() << "ColorSelectWdg setTheme, theme is dark"; + qCDebug(appLog) << "ColorSelectWdg setTheme, theme is dark"; } - qDebug() << "ColorSelectWdg setTheme, theme end"; + qCDebug(appLog) << "ColorSelectWdg setTheme, theme end"; } QColor ColorSelectWdg::getDefaultColor() diff --git a/src/widgets/bottombar.cpp b/src/widgets/bottombar.cpp index 901a106d3..998fb2c78 100644 --- a/src/widgets/bottombar.cpp +++ b/src/widgets/bottombar.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include #include #include @@ -34,7 +35,7 @@ BottomBar::BottomBar(QWidget *parent) m_progressLabel(new DLabel), m_progressBar(new DProgressBar) { - qDebug() << "BottomBar constructor"; + qCDebug(appLog) << "BottomBar constructor"; QFont font; m_pPositionLabel->setFont(font); m_pPositionLabel->setAccessibleName("PositionLabel"); @@ -131,13 +132,13 @@ BottomBar::BottomBar(QWidget *parent) //切换编码 connect(m_pEncodeMenu, &DDropdownMenu::currentActionChanged, this,[this](QAction* pAct){ - qInfo() << "Encoding changed to:" << pAct->text(); + qCInfo(appLog) << "Encoding changed to:" << pAct->text(); // 保持界面统一 QString previousText = m_pEncodeMenu->getCurrentText(); // 处于文件加载状态或转换失败则恢复默认编码格式 if (m_pWrapper->getFileLoading() || !m_pWrapper->reloadFileEncode(pAct->text().toLocal8Bit())) { - qWarning() << "Failed to change encoding, reverting to:" << previousText; + qCWarning(appLog) << "Failed to change encoding, reverting to:" << previousText; m_pEncodeMenu->setCurrentTextOnly(previousText); } else { // 存储完成后更新底栏显示文本,重载时可能需要保存旧文本 @@ -147,7 +148,7 @@ BottomBar::BottomBar(QWidget *parent) //切换文件类型 connect(m_pHighlightMenu, &DDropdownMenu::currentActionChanged, this,[this](QAction* pAct) { - qInfo() << "Highlight mode changed to:" << pAct->text(); + qCInfo(appLog) << "Highlight mode changed to:" << pAct->text(); m_pHighlightMenu->setCurrentTextOnly(pAct->text()); // 更新使用格式高亮类型 @@ -169,7 +170,7 @@ BottomBar::BottomBar(QWidget *parent) BottomBar::~BottomBar() { - qDebug() << "BottomBar destructor"; + qCDebug(appLog) << "BottomBar destructor"; if (m_pEncodeMenu != nullptr) { delete m_pEncodeMenu; m_pEncodeMenu = nullptr; @@ -288,12 +289,12 @@ void BottomBar::setProgress(int progress) if(progress<0){ return; } - qDebug() << "Loading progress:" << progress << "%"; + qCDebug(appLog) << "Loading progress:" << progress << "%"; m_progressBar->show(); m_progressLabel->show(); m_progressBar->setValue(progress); if(progress >= 100){ - qDebug() << "Loading completed"; + qCDebug(appLog) << "Loading completed"; m_progressBar->hide(); m_progressLabel->hide(); } @@ -433,7 +434,7 @@ void BottomBar::onFormatMenuTrigged(QAction* action) return; } - qInfo() << "Endline format changed from" << m_endlineFormat << "to" << type; + qCInfo(appLog) << "Endline format changed from" << m_endlineFormat << "to" << type; m_pWrapper->textEditor()->onEndlineFormatChanged(m_endlineFormat,(EndlineFormat)type); m_endlineFormat = (EndlineFormat)type; diff --git a/src/widgets/ddropdownmenu.cpp b/src/widgets/ddropdownmenu.cpp index 8403fc187..eb8761c97 100644 --- a/src/widgets/ddropdownmenu.cpp +++ b/src/widgets/ddropdownmenu.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "../common/utils.h" #include "../common/settings.h" #include "ddropdownmenu.h" @@ -75,7 +76,7 @@ DDropdownMenu::DDropdownMenu(QWidget *parent) , m_pToolButton(new LabelToolButton(this, this)) , m_menu(new DMenu) { - qDebug() << "DDropdownMenu constructor"; + qCDebug(appLog) << "DDropdownMenu constructor"; // 更新单独添加的高亮格式文件 m_Repository.addCustomSearchPath(KF5_HIGHLIGHT_PATH); @@ -117,34 +118,34 @@ DDropdownMenu::DDropdownMenu(QWidget *parent) updateButtonSize(); }); #endif - qDebug() << "DDropdownMenu constructor end"; + qCDebug(appLog) << "DDropdownMenu constructor end"; } DDropdownMenu::~DDropdownMenu() { - qDebug() << "DDropdownMenu destructor"; + qCDebug(appLog) << "DDropdownMenu destructor"; deleteMenuActionGroup(); deleteMenu(); - qDebug() << "DDropdownMenu destructor end"; + qCDebug(appLog) << "DDropdownMenu destructor end"; } void DDropdownMenu::setFontEx(const QFont& font) { - qDebug() << "DDropdownMenu setFontEx"; + qCDebug(appLog) << "DDropdownMenu setFontEx"; m_pToolButton->setFont(font); m_font = font; //字体变化影响文本宽度,需重算按钮尺寸 updateButtonSize(); - qDebug() << "DDropdownMenu setFontEx end"; + qCDebug(appLog) << "DDropdownMenu setFontEx end"; } void DDropdownMenu::setCurrentAction(QAction *pAct) { - qDebug() << "DDropdownMenu setCurrentAction"; + qCDebug(appLog) << "DDropdownMenu setCurrentAction"; if(pAct){ - qDebug() << "pAct is not null"; + qCDebug(appLog) << "pAct is not null"; if (m_menu == nullptr) { - qDebug() << "DDropdownMenu setCurrentAction: menu is null"; + qCDebug(appLog) << "DDropdownMenu setCurrentAction: menu is null"; setText(pAct->text()); return; } @@ -162,12 +163,12 @@ void DDropdownMenu::setCurrentAction(QAction *pAct) } setText(pAct->text()); } - qDebug() << "DDropdownMenu setCurrentAction end"; + qCDebug(appLog) << "DDropdownMenu setCurrentAction end"; } void DDropdownMenu::setCurrentTextOnly(const QString &name) { - qDebug() << "DDropdownMenu setCurrentTextOnly"; + qCDebug(appLog) << "DDropdownMenu setCurrentTextOnly"; // QList menuList = m_menu->actions(); // for (int i = 0; i < menuList.size(); i++) { @@ -193,43 +194,43 @@ void DDropdownMenu::setCurrentTextOnly(const QString &name) } setText(name); - qDebug() << "DDropdownMenu setCurrentTextOnly end"; + qCDebug(appLog) << "DDropdownMenu setCurrentTextOnly end"; } void DDropdownMenu::setCheckedExclusive(QAction* action,const QString& name) { - qDebug() << "DDropdownMenu setCheckedExclusive"; + qCDebug(appLog) << "DDropdownMenu setCheckedExclusive"; if (nullptr == action) { - qDebug() << "action is null, return"; + qCDebug(appLog) << "action is null, return"; return; } if (action->menu()) { - qDebug() << "action has menu"; + qCDebug(appLog) << "action has menu"; for(auto ac:action->menu()->actions()){ setCheckedExclusive(ac,name); } } else { - qDebug() << "action has no menu"; + qCDebug(appLog) << "action has no menu"; if (action->text() != name) { - qDebug() << "action text is not equal to name"; + qCDebug(appLog) << "action text is not equal to name"; action->setCheckable(false); action->setChecked(false); } else { - qDebug() << "action text is equal to name"; + qCDebug(appLog) << "action text is equal to name"; action->setCheckable(true); action->setChecked(true); } } - qDebug() << "DDropdownMenu setCheckedExclusive end"; + qCDebug(appLog) << "DDropdownMenu setCheckedExclusive end"; } void DDropdownMenu::slotRequestMenu(bool request) { - qDebug() << "DDropdownMenu slotRequestMenu"; + qCDebug(appLog) << "DDropdownMenu slotRequestMenu"; if (request) { - qDebug() << "request is true"; + qCDebug(appLog) << "request is true"; //如果鼠标点击清除focus m_pToolButton->clearFocus(); } @@ -251,21 +252,21 @@ void DDropdownMenu::slotRequestMenu(bool request) QApplication::sendEvent(m_pToolButton, &event); #endif emit sigSetTextEditFocus(); - qDebug() << "DDropdownMenu slotRequestMenu end"; + qCDebug(appLog) << "DDropdownMenu slotRequestMenu end"; } void DDropdownMenu::setText(const QString &text) { - qDebug() << "DDropdownMenu setText:" << text; + qCDebug(appLog) << "DDropdownMenu setText:" << text; m_text = text; //文本宽度变化时重算按钮尺寸(文本原生绘制,无需重建位图图标) updateButtonSize(); - qDebug() << "DDropdownMenu setText end"; + qCDebug(appLog) << "DDropdownMenu setText end"; } void DDropdownMenu::setMenu(DMenu *menu) { - qDebug() << "DDropdownMenu setMenu"; + qCDebug(appLog) << "DDropdownMenu setMenu"; deleteMenu(); m_menu = menu; if (m_menu != nullptr) { @@ -276,38 +277,38 @@ void DDropdownMenu::setMenu(DMenu *menu) void DDropdownMenu::deleteMenu() { - qDebug() << "DDropdownMenu deleteMenu"; + qCDebug(appLog) << "DDropdownMenu deleteMenu"; if (m_menu != nullptr) { - qDebug() << "m_menu is not null, deleting"; + qCDebug(appLog) << "m_menu is not null, deleting"; delete m_menu; m_menu = nullptr; } - qDebug() << "DDropdownMenu deleteMenu end"; + qCDebug(appLog) << "DDropdownMenu deleteMenu end"; } void DDropdownMenu::setMenuActionGroup(QActionGroup *actionGroup) { - qDebug() << "DDropdownMenu setMenuActionGroup"; + qCDebug(appLog) << "DDropdownMenu setMenuActionGroup"; deleteMenuActionGroup(); m_actionGroup = actionGroup; m_actionGroup->setObjectName("ActionGroup"); - qDebug() << "DDropdownMenu setMenuActionGroup end"; + qCDebug(appLog) << "DDropdownMenu setMenuActionGroup end"; } void DDropdownMenu::deleteMenuActionGroup() { - qDebug() << "DDropdownMenu deleteMenuActionGroup"; + qCDebug(appLog) << "DDropdownMenu deleteMenuActionGroup"; if (m_actionGroup != nullptr) { - qDebug() << "m_actionGroup is not null, deleting"; + qCDebug(appLog) << "m_actionGroup is not null, deleting"; delete m_actionGroup; m_actionGroup = nullptr; } - qDebug() << "DDropdownMenu deleteMenuActionGroup end"; + qCDebug(appLog) << "DDropdownMenu deleteMenuActionGroup end"; } void DDropdownMenu::setTheme(const QString &theme) { - qDebug() << "DDropdownMenu setTheme:" << theme; + qCDebug(appLog) << "DDropdownMenu setTheme:" << theme; m_theme = theme; QString arrowSvgPath = QString(":/images/dropdown_arrow_%1.svg").arg(theme); // 根据当前显示缩放转换图片 @@ -325,51 +326,51 @@ void DDropdownMenu::setTheme(const QString &theme) //按下态箭头依赖旧调色板颜色,置空待下次按下时按当前调色板重建 m_pressedArrowPixmap = QPixmap(); m_pToolButton->update(); - qDebug() << "DDropdownMenu setTheme end"; + qCDebug(appLog) << "DDropdownMenu setTheme end"; } void DDropdownMenu::setChildrenFocus(bool ok) { - qDebug() << "DDropdownMenu setChildrenFocus:" << ok; + qCDebug(appLog) << "DDropdownMenu setChildrenFocus:" << ok; if (ok) { - qDebug() << "setChildrenFocus is true"; + qCDebug(appLog) << "setChildrenFocus is true"; m_pToolButton->setFocusPolicy(Qt::StrongFocus); } else { - qDebug() << "setChildrenFocus is false"; + qCDebug(appLog) << "setChildrenFocus is false"; m_pToolButton->clearFocus(); m_pToolButton->setFocusPolicy(Qt::NoFocus); } - qDebug() << "DDropdownMenu setChildrenFocus end"; + qCDebug(appLog) << "DDropdownMenu setChildrenFocus end"; } void DDropdownMenu::setRequestMenu(bool request) { - qDebug() << "DDropdownMenu setRequestMenu:" << request; + qCDebug(appLog) << "DDropdownMenu setRequestMenu:" << request; isRequest = request; - qDebug() << "DDropdownMenu setRequestMenu end"; + qCDebug(appLog) << "DDropdownMenu setRequestMenu end"; } DToolButton *DDropdownMenu::getButton() { - qDebug() << "DDropdownMenu getButton"; + qCDebug(appLog) << "DDropdownMenu getButton"; return m_pToolButton; } QString DDropdownMenu::getCurrentText() const { - qDebug() << "DDropdownMenu getCurrentText"; + qCDebug(appLog) << "DDropdownMenu getCurrentText"; return m_text; } DDropdownMenu *DDropdownMenu::createEncodeMenu() { - qDebug() << "DDropdownMenu createEncodeMenu"; + qCDebug(appLog) << "DDropdownMenu createEncodeMenu"; DDropdownMenu *m_pEncodeMenu = new DDropdownMenu(); DMenu* m_pMenu = new DMenu(); auto groupEncodeVec = Utils::getSupportEncoding(); if (!groupEncodeVec.isEmpty()) { - qDebug() << "groupEncodeVec is not empty, creating menu"; + qCDebug(appLog) << "groupEncodeVec is not empty, creating menu"; int cnt = groupEncodeVec.size(); for (int i = 0; i < cnt;i++) { QMenu* groupMenu = new QMenu(QObject::tr(groupEncodeVec[i].first.toLocal8Bit().data())); @@ -377,13 +378,13 @@ DDropdownMenu *DDropdownMenu::createEncodeMenu() { QAction *act= groupMenu->addAction(QObject::tr(var.toLocal8Bit().data())); if (act->text() == "UTF-8") { - qDebug() << "Adding UTF-8 action"; + qCDebug(appLog) << "Adding UTF-8 action"; m_pEncodeMenu->m_pActUtf8 = act; act->setCheckable(true); act->setChecked(true); m_pEncodeMenu->m_pActUtf8->setObjectName("PActUtf8"); } else { - qDebug() << "Adding other action"; + qCDebug(appLog) << "Adding other action"; act->setCheckable(false); } } @@ -393,10 +394,10 @@ DDropdownMenu *DDropdownMenu::createEncodeMenu() } connect(m_pMenu, &DMenu::triggered, m_pEncodeMenu,[m_pEncodeMenu](QAction *action) { - qInfo() << "Encoding changed to:" << action->text(); + qCInfo(appLog) << "Encoding changed to:" << action->text(); //编码内容改变触发内容改变和信号发射 梁卫东 2020.7.7 if (m_pEncodeMenu->m_text != action->text()) { - qDebug() << "Encoding changed to:" << action->text(); + qCDebug(appLog) << "Encoding changed to:" << action->text(); emit m_pEncodeMenu->currentActionChanged(action); } }); @@ -404,13 +405,13 @@ DDropdownMenu *DDropdownMenu::createEncodeMenu() m_pEncodeMenu->setText("UTF-8"); m_pEncodeMenu->setMenu(m_pMenu); - qDebug() << "DDropdownMenu createEncodeMenu end"; + qCDebug(appLog) << "DDropdownMenu createEncodeMenu end"; return m_pEncodeMenu; } DDropdownMenu *DDropdownMenu::createHighLightMenu() { - qDebug() << "DDropdownMenu createHighLightMenu"; + qCDebug(appLog) << "DDropdownMenu createHighLightMenu"; DDropdownMenu *m_pHighLightMenu = new DDropdownMenu(); DMenu *m_pMenu = new DMenu; QAction *noHlAction = m_pMenu->addAction(tr("None")); @@ -429,22 +430,22 @@ DDropdownMenu *DDropdownMenu::createHighLightMenu() if(def.translatedName()=="Intel x86 (NASM)"&&intel) { intel = false; - qDebug() << "Intel x86 (NASM) is hidden, continue"; + qCDebug(appLog) << "Intel x86 (NASM) is hidden, continue"; continue; } if (def.isHidden()) { - qDebug() << "def is hidden, continue"; + qCDebug(appLog) << "def is hidden, continue"; continue; } if (currentGroup != def.section()) { - qDebug() << "currentGroup is not equal to def.section(), creating new submenu"; + qCDebug(appLog) << "currentGroup is not equal to def.section(), creating new submenu"; currentGroup = def.section(); pSubMenu = m_pMenu->addMenu(def.translatedSection()); } if (!pSubMenu) { - qDebug() << "pSubMenu is null, continue"; + qCDebug(appLog) << "pSubMenu is null, continue"; continue; } @@ -457,7 +458,7 @@ DDropdownMenu *DDropdownMenu::createHighLightMenu() // 转发选中“None“无高亮选项的信号 connect(noHlAction, &QAction::triggered, m_pHighLightMenu, [noHlAction, m_pHighLightMenu] (bool checked) { if (checked) { - qInfo() << "Highlight mode changed to None"; + qCInfo(appLog) << "Highlight mode changed to None"; emit m_pHighLightMenu->currentActionChanged(noHlAction); } }); @@ -466,11 +467,11 @@ DDropdownMenu *DDropdownMenu::createHighLightMenu() const auto defName = action->text(); const auto def = m_pHighLightMenu->m_Repository.definitionForName(defName); if (def.isValid() && m_pHighLightMenu->m_text != action->text()) { - qInfo() << "Highlight mode changed to:" << defName; + qCInfo(appLog) << "Highlight mode changed to:" << defName; emit m_pHighLightMenu->currentActionChanged(action); } else { - qDebug() << "Invalid highlight definition, setting to None"; + qCDebug(appLog) << "Invalid highlight definition, setting to None"; m_pHighLightMenu->setText(tr("None")); } @@ -480,7 +481,7 @@ DDropdownMenu *DDropdownMenu::createHighLightMenu() m_pHighLightMenu->setMenu(m_pMenu); m_pHighLightMenu->setMenuActionGroup(m_pActionGroup); - qDebug() << "DDropdownMenu createHighLightMenu end"; + qCDebug(appLog) << "DDropdownMenu createHighLightMenu end"; return m_pHighLightMenu; } @@ -504,14 +505,14 @@ void DDropdownMenu::updateButtonSize() void DDropdownMenu::OnFontChangedSlot(const QFont &font) { - qDebug() << "DDropdownMenu OnFontChangedSlot"; + qCDebug(appLog) << "DDropdownMenu OnFontChangedSlot"; m_font = font; //字体族跟随系统字体,但字号保持底栏 T9(原 Qt6 分支漏设字号会导致文字随应用字号变化) int fontsize = DFontSizeManager::instance()->fontPixelSize(DFontSizeManager::T9); m_font.setPixelSize(fontsize); m_pToolButton->setFont(m_font); updateButtonSize(); - qDebug() << "DDropdownMenu OnFontChangedSlot end"; + qCDebug(appLog) << "DDropdownMenu OnFontChangedSlot end"; } @@ -535,21 +536,21 @@ bool DDropdownMenu::eventFilter(QObject *object, QEvent *event) if(object == m_pToolButton){ if(event->type() == QEvent::KeyPress){ QKeyEvent *keyEvent = static_cast(event); - qDebug() << "Key pressed:" << keyEvent->key(); + qCDebug(appLog) << "Key pressed:" << keyEvent->key(); if(keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Space) //按下enter展开列表 { - qDebug() << "Triggering context menu via keyboard"; + qCDebug(appLog) << "Triggering context menu via keyboard"; Q_EMIT requestContextMenu(false); return true; } - qDebug() << "Key event not handled, return false"; + qCDebug(appLog) << "Key event not handled, return false"; return false; } if(event->type() == QEvent::MouseButtonPress){ QMouseEvent *mouseEvent = static_cast(event); if(mouseEvent->button() == Qt::LeftButton){ - qDebug() << "Left mouse button pressed on dropdown menu"; + qCDebug(appLog) << "Left mouse button pressed on dropdown menu"; m_bPressed = true; //按下时按当前调色板高亮色重建箭头,文本颜色由 paintEvent 实时取色 DPalette dpalette = DPaletteHelper::instance()->palette(m_pToolButton); @@ -559,24 +560,24 @@ bool DDropdownMenu::eventFilter(QObject *object, QEvent *event) } if(mouseEvent->button() == Qt::RightButton){ - qDebug() << "Right mouse button pressed on dropdown menu, return true"; + qCDebug(appLog) << "Right mouse button pressed on dropdown menu, return true"; return true; } } if(event->type() == QEvent::MouseButtonRelease){ - qDebug() << "Left mouse button released on dropdown menu"; + qCDebug(appLog) << "Left mouse button released on dropdown menu"; QMouseEvent *mouseEvent = static_cast(event); if(mouseEvent->button() == Qt::LeftButton){ m_bPressed = false; m_pToolButton->update(); if (isEnabled()) { - qDebug() << "Left mouse button released, showing context menu"; + qCDebug(appLog) << "Left mouse button released, showing context menu"; Q_EMIT requestContextMenu(true); } m_pToolButton->clearFocus(); } - qDebug() << "Left mouse button released, return true"; + qCDebug(appLog) << "Left mouse button released, return true"; return true; } } @@ -586,12 +587,12 @@ bool DDropdownMenu::eventFilter(QObject *object, QEvent *event) QPixmap DDropdownMenu::setSvgColor(QString color) { - qDebug() << "DDropdownMenu setSvgColor"; + qCDebug(appLog) << "DDropdownMenu setSvgColor"; //设置图标颜色 QString path = QString(":/images/arrow_dark.svg"); QFile file(path); if (!file.open(QIODevice::ReadOnly)) { - qWarning() << "DDropdownMenu setSvgColor: failed to open" << path << file.errorString(); + qCWarning(appLog) << "DDropdownMenu setSvgColor: failed to open" << path << file.errorString(); return QPixmap(); } QByteArray data = file.readAll(); @@ -613,16 +614,16 @@ QPixmap DDropdownMenu::setSvgColor(QString color) QPainter painter(&pixmap); svg_render.render(&painter,QRect(0,0,8,5)); - qDebug() << "DDropdownMenu setSvgColor end"; + qCDebug(appLog) << "DDropdownMenu setSvgColor end"; return pixmap; } void DDropdownMenu::SetSVGBackColor(QDomElement &elem, QString strattr, QString strattrval) { - qDebug() << "DDropdownMenu SetSVGBackColor"; + qCDebug(appLog) << "DDropdownMenu SetSVGBackColor"; if (elem.tagName().compare("g") == 0 && elem.attribute("id").compare("color") == 0) { - qDebug() << "DDropdownMenu SetSVGBackColor, found color group"; + qCDebug(appLog) << "DDropdownMenu SetSVGBackColor, found color group"; elem.setAttribute(strattr, strattrval); } for (int i = 0; i < elem.childNodes().count(); i++) @@ -631,5 +632,5 @@ void DDropdownMenu::SetSVGBackColor(QDomElement &elem, QString strattr, QString QDomElement element = elem.childNodes().at(i).toElement(); SetSVGBackColor(element, strattr, strattrval); } - qDebug() << "DDropdownMenu SetSVGBackColor end"; + qCDebug(appLog) << "DDropdownMenu SetSVGBackColor end"; } diff --git a/src/widgets/pathsettintwgt.cpp b/src/widgets/pathsettintwgt.cpp index 8dc9f1309..5a981259e 100644 --- a/src/widgets/pathsettintwgt.cpp +++ b/src/widgets/pathsettintwgt.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "pathsettintwgt.h" #include "../common/settings.h" @@ -22,35 +23,35 @@ const int s_PSWSuggestIconSizeCompact = 16; PathSettingWgt::PathSettingWgt(QWidget* parent):DWidget(parent) { - qDebug() << "PathSettingWgt constructor"; + qCDebug(appLog) << "PathSettingWgt constructor"; init(); onSaveIdChanged(Settings::instance()->getSavePathId()); - qDebug() << "PathSettingWgt constructor end"; + qCDebug(appLog) << "PathSettingWgt constructor end"; } PathSettingWgt::~PathSettingWgt() { - qDebug() << "PathSettingWgt destructor"; + qCDebug(appLog) << "PathSettingWgt destructor"; } void PathSettingWgt::onSaveIdChanged(int id) { - qDebug() << "PathSettingWgt onSaveIdChanged, id:" << id; + qCDebug(appLog) << "PathSettingWgt onSaveIdChanged, id:" << id; switch (id) { case CurFileBox:{ - qDebug() << "CurFileBox selected"; + qCDebug(appLog) << "CurFileBox selected"; m_curFileBox->setChecked(true); m_customBtn->setEnabled(false); break; } case LastOptBox:{ - qDebug() << "LastOptBox selected"; + qCDebug(appLog) << "LastOptBox selected"; m_lastOptBox->setChecked(true); m_customBtn->setEnabled(false); break; } case CustomBox:{ - qDebug() << "CustomBox selected"; + qCDebug(appLog) << "CustomBox selected"; m_customBox->setChecked(true); m_customBtn->setEnabled(true); setEditText(Settings::instance()->getSavePath(CustomBox)); @@ -59,12 +60,12 @@ void PathSettingWgt::onSaveIdChanged(int id) default: break; } - qDebug() << "PathSettingWgt onSaveIdChanged end"; + qCDebug(appLog) << "PathSettingWgt onSaveIdChanged end"; } void PathSettingWgt::init() { - qDebug() << "PathSettingWgt init"; + qCDebug(appLog) << "PathSettingWgt init"; QVBoxLayout* layout = new QVBoxLayout(this); m_group = new QButtonGroup(this); m_group->setObjectName("Group"); @@ -115,12 +116,12 @@ void PathSettingWgt::init() updateSizeMode(); QObject::connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, &PathSettingWgt::updateSizeMode); #endif - qDebug() << "PathSettingWgt init end"; + qCDebug(appLog) << "PathSettingWgt init end"; } void PathSettingWgt::connections() { - qDebug() << "PathSettingWgt connections"; + qCDebug(appLog) << "PathSettingWgt connections"; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) connect(m_group, static_cast(&QButtonGroup::buttonClicked),this,&PathSettingWgt::onBoxClicked); #else @@ -130,39 +131,39 @@ void PathSettingWgt::connections() }); #endif connect(m_customBtn, &QPushButton::clicked, this, &PathSettingWgt::onBtnClicked); - qDebug() << "PathSettingWgt connections end"; + qCDebug(appLog) << "PathSettingWgt connections end"; } void PathSettingWgt::setEditText(const QString& text) { - qDebug() << "PathSettingWgt setEditText:" << text; + qCDebug(appLog) << "PathSettingWgt setEditText:" << text; QFontMetrics metrics(m_customEdit->font()); Qt::TextElideMode em = Qt::TextElideMode::ElideMiddle; m_customEdit->setText(metrics.elidedText(text, em, 175)); - qDebug() << "PathSettingWgt setEditText end"; + qCDebug(appLog) << "PathSettingWgt setEditText end"; } void PathSettingWgt::onBoxClicked(int id) { - qInfo() << "Save path option changed to:" << id; + qCInfo(appLog) << "Save path option changed to:" << id; switch (id) { case CurFileBox:{ - qDebug() << "CurFileBox selected"; + qCDebug(appLog) << "CurFileBox selected"; Settings::instance()->setSavePathId(CurFileBox); m_customBtn->setEnabled(false); break; } case LastOptBox:{ - qDebug() << "LastOptBox selected"; + qCDebug(appLog) << "LastOptBox selected"; Settings::instance()->setSavePathId(LastOptBox); m_customBtn->setEnabled(false); break; } case CustomBox:{ - qDebug() << "CustomBox selected"; + qCDebug(appLog) << "CustomBox selected"; Settings::instance()->setSavePathId(CustomBox); QString path = Settings::instance()->getSavePath(CustomBox); - qDebug() << "Custom path set to:" << path; + qCDebug(appLog) << "Custom path set to:" << path; setEditText(path); m_customBtn->setEnabled(true); break; @@ -170,32 +171,32 @@ void PathSettingWgt::onBoxClicked(int id) default: break; } - qDebug() << "PathSettingWgt onBoxClicked end"; + qCDebug(appLog) << "PathSettingWgt onBoxClicked end"; } void PathSettingWgt::onBtnClicked() { - qDebug() << "Custom path button clicked"; + qCDebug(appLog) << "Custom path button clicked"; QFileDialog dialog(this); dialog.setFileMode(QFileDialog::Directory); dialog.setAcceptMode(QFileDialog::AcceptOpen); QString path = Settings::instance()->getSavePath(PathSettingWgt::CustomBox); if(!QDir(path).exists() || path.isEmpty()){ path = QDir::homePath() + "/Documents"; - qDebug() << "Using default documents path:" << path; + qCDebug(appLog) << "Using default documents path:" << path; } dialog.setDirectory(path); const int mode = dialog.exec(); if (mode != QDialog::Accepted) { - qDebug() << "Path selection dialog canceled"; + qCDebug(appLog) << "Path selection dialog canceled"; return; } path = dialog.selectedFiles().at(0); - qInfo() << "Selected new custom path:" << path; + qCInfo(appLog) << "Selected new custom path:" << path; setEditText(path); Settings::instance()->setSavePath(PathSettingWgt::CustomBox,path); - qDebug() << "PathSettingWgt onBtnClicked end"; + qCDebug(appLog) << "PathSettingWgt onBtnClicked end"; } /** @@ -204,17 +205,17 @@ void PathSettingWgt::onBtnClicked() */ void PathSettingWgt::updateSizeMode() { - qDebug() << "PathSettingWgt updateSizeMode"; + qCDebug(appLog) << "PathSettingWgt updateSizeMode"; #ifdef DTKWIDGET_CLASS_DSizeMode if (DGuiApplicationHelper::isCompactMode()) { - qDebug() << "Compact mode"; + qCDebug(appLog) << "Compact mode"; m_customBtn->setFixedSize(s_PSWSuggestBtnSizeCompact, s_PSWSuggestBtnSizeCompact); m_customBtn->setIconSize(QSize(s_PSWSuggestIconSizeCompact, s_PSWSuggestIconSizeCompact)); } else { - qDebug() << "Normal mode"; + qCDebug(appLog) << "Normal mode"; m_customBtn->setFixedSize(s_PSWSuggestBtnSize, s_PSWSuggestBtnSize); m_customBtn->setIconSize(QSize(s_PSWSuggestIconSize, s_PSWSuggestIconSize)); } #endif - qDebug() << "PathSettingWgt updateSizeMode end"; + qCDebug(appLog) << "PathSettingWgt updateSizeMode end"; } diff --git a/src/widgets/window.cpp b/src/widgets/window.cpp index 91a9af107..b2df33356 100644 --- a/src/widgets/window.cpp +++ b/src/widgets/window.cpp @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later +#include "ddlog.h" #include "window.h" #include "pathsettintwgt.h" #include @@ -52,7 +53,7 @@ */ static QTextDocument *createNewDocument(QTextDocument *doc) { - qDebug() << "createNewDocument called"; + qCDebug(appLog) << "createNewDocument called"; QTextDocument *createDoc = new QTextDocument(doc); // 不记录撤销信息 createDoc->setUndoRedoEnabled(false); @@ -70,7 +71,7 @@ static QTextDocument *createNewDocument(QTextDocument *doc) textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); createDoc->setDefaultTextOption(textOption); - qDebug() << "createNewDocument end"; + qCDebug(appLog) << "createNewDocument end"; return createDoc; } @@ -84,7 +85,7 @@ static QTextDocument *createNewDocument(QTextDocument *doc) void Window::printPage(int index, QPainter *painter, const QTextDocument *doc, const QRectF &body, const QRectF &pageCountBox) { - qDebug() << "printPage called"; + qCDebug(appLog) << "printPage called"; painter->save(); painter->translate(body.left(), body.top() - (index - 1) * body.height()); @@ -105,7 +106,7 @@ void Window::printPage(int index, QPainter *painter, const QTextDocument *doc, layout->draw(painter, ctx); painter->restore(); - qDebug() << "printPage end"; + qCDebug(appLog) << "printPage end"; } /** @@ -218,7 +219,7 @@ Window::Window(DMainWindow *parent) m_titlebarStyleSheet(titlebar()->styleSheet()), m_themePath(Settings::instance()->settings->option("advance.editor.theme")->value().toString()) { - qDebug() << "Window constructor called"; + qCDebug(appLog) << "Window constructor called"; m_tabbar->setObjectName("Tabbar"); m_tabbar->setAccessibleName("Tabbar"); @@ -273,7 +274,7 @@ Window::Window(DMainWindow *parent) // Init titlebar. if (titlebar()) { - qDebug() << "init titlebar"; + qCDebug(appLog) << "init titlebar"; initTitlebar(); } @@ -371,34 +372,34 @@ Window::Window(DMainWindow *parent) // 适配紧凑模式更新,注意 Qt::QueuedConnection 需要在其他子组件更新后触发 connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, &Window::updateSizeMode, Qt::QueuedConnection); #endif - qDebug() << "Window constructor end"; + qCDebug(appLog) << "Window constructor end"; } Window::~Window() { - qDebug() << "Window destructor called"; + qCDebug(appLog) << "Window destructor called"; // We don't need clean pointers because application has exit here. if (nullptr != m_shortcutViewProcess) { - qDebug() << "delete m_shortcutViewProcess"; + qCDebug(appLog) << "delete m_shortcutViewProcess"; delete (m_shortcutViewProcess); m_shortcutViewProcess = nullptr; } clearPrintTextDocument(); - qDebug() << "Window destructor end"; + qCDebug(appLog) << "Window destructor end"; } void Window::loadIflytekaiassistantConfig() { - qDebug() << "loadIflytekaiassistantConfig"; + qCDebug(appLog) << "loadIflytekaiassistantConfig"; QString configPath = QString("%1/%2") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) .arg("iflytek"); QDir dir(configPath); if (!dir.exists()) { - qDebug() << "iflytekaiassistant config dir not exist, return"; + qCDebug(appLog) << "iflytekaiassistant config dir not exist, return"; return; } QString configKey = "base/enable"; @@ -411,37 +412,37 @@ void Window::loadIflytekaiassistantConfig() m_IflytekAiassistantState[name.split(".").first()] = file.value(configKey).toBool(); } } - qDebug() << "loadIflytekaiassistantConfig end"; + qCDebug(appLog) << "loadIflytekaiassistantConfig end"; } bool Window::getIflytekaiassistantConfig(const QString &mode_name) { - qDebug() << "getIflytekaiassistantConfig"; + qCDebug(appLog) << "getIflytekaiassistantConfig"; if (m_IflytekAiassistantState.contains(mode_name)) { - qDebug() << "getIflytekaiassistantConfig end"; + qCDebug(appLog) << "getIflytekaiassistantConfig end"; return m_IflytekAiassistantState[mode_name]; } else { - qWarning() << "mode_name is not valid"; + qCWarning(appLog) << "mode_name is not valid"; return false; } } void Window::updateModifyStatus(const QString &path, bool isModified) { - qDebug() << "updateModifyStatus"; + qCDebug(appLog) << "updateModifyStatus"; int tabIndex = m_tabbar->indexOf(path); if (tabIndex == -1) { - qWarning() << "Failed to get tab index for path:" << path; + qCWarning(appLog) << "Failed to get tab index for path:" << path; return; } QString tabName; QString filePath = m_tabbar->truePathAt(tabIndex); if (filePath.isNull() || filePath.length() <= 0 || Utils::isDraftFile(filePath)) { - qDebug() << "Failed to get true path for tab index:" << tabIndex; + qCDebug(appLog) << "Failed to get true path for tab index:" << tabIndex; tabName = m_tabbar->textAt(tabIndex); if (isModified) { - qDebug() << "Modified but not saved, add * to tab name"; + qCDebug(appLog) << "Modified but not saved, add * to tab name"; if (!tabName.contains('*')) { tabName.prepend('*'); } @@ -449,16 +450,16 @@ void Window::updateModifyStatus(const QString &path, bool isModified) QRegularExpression reg("[^*](.+)"); QRegularExpressionMatch match = reg.match(tabName); if (match.hasMatch()) { - qDebug() << "Tab name does not contain *, remove * from tab name"; + qCDebug(appLog) << "Tab name does not contain *, remove * from tab name"; tabName = match.captured(0); } } } else { - qDebug() << "File path is valid, updating tab name"; + qCDebug(appLog) << "File path is valid, updating tab name"; QFileInfo fileInfo(filePath); tabName = fileInfo.fileName(); if (isModified) { - qDebug() << "Modified but not saved, add * to tab name"; + qCDebug(appLog) << "Modified but not saved, add * to tab name"; tabName.prepend('*'); } } @@ -466,16 +467,16 @@ void Window::updateModifyStatus(const QString &path, bool isModified) m_tabbar->setTabText(tabIndex, tabName); //判断是否需要阻塞系统关机 emit sigJudgeBlockShutdown(); - qDebug() << "updateModifyStatus end"; + qCDebug(appLog) << "updateModifyStatus end"; } void Window::updateSaveAsFileName(QString strOldFilePath, QString strNewFilePath) { - qDebug() << "updateSaveAsFileName called with old path:" << strOldFilePath << "new path:" << strNewFilePath; + qCDebug(appLog) << "updateSaveAsFileName called with old path:" << strOldFilePath << "new path:" << strNewFilePath; int tabIndex = m_tabbar->indexOf(strOldFilePath); EditWrapper *wrapper = m_wrappers.value(strOldFilePath); if (!wrapper) { - qWarning() << "Failed to get wrapper for old path"; + qCWarning(appLog) << "Failed to get wrapper for old path"; return; } m_tabbar->updateTab(tabIndex, strNewFilePath, QFileInfo(strNewFilePath).fileName()); @@ -483,62 +484,62 @@ void Window::updateSaveAsFileName(QString strOldFilePath, QString strNewFilePath //tabbar中存在和strNewFilePath同名的tab if (m_wrappers.contains(strNewFilePath)) { - qDebug() << "Tab with new file path already exists, closing old tab."; + qCDebug(appLog) << "Tab with new file path already exists, closing old tab."; closeTab(strNewFilePath); } m_wrappers.remove(strOldFilePath); m_wrappers.insert(strNewFilePath, wrapper); - qDebug() << "updateSaveAsFileName end"; + qCDebug(appLog) << "updateSaveAsFileName end"; } void Window::updateSabeAsFileNameTemp(QString strOldFilePath, QString strNewFilePath) { - qDebug() << "updateSabeAsFileNameTemp called with old path:" << strOldFilePath << "new path:" << strNewFilePath; + qCDebug(appLog) << "updateSabeAsFileNameTemp called with old path:" << strOldFilePath << "new path:" << strNewFilePath; int tabIndex = m_tabbar->indexOf(strOldFilePath); EditWrapper *wrapper = m_wrappers.value(strOldFilePath); if (!wrapper) { - qWarning() << "Failed to get wrapper for old path"; + qCWarning(appLog) << "Failed to get wrapper for old path"; return; } m_tabbar->updateTab(tabIndex, strNewFilePath, QFileInfo(strNewFilePath).fileName()); wrapper->updatePath(strNewFilePath); m_wrappers.remove(strOldFilePath); m_wrappers.insert(strNewFilePath, wrapper); - qDebug() << "updateSabeAsFileNameTemp end"; + qCDebug(appLog) << "updateSabeAsFileNameTemp end"; } void Window::showCenterWindow(bool bIsCenter) { - qDebug() << "Window::showCenterWindow() - bIsCenter:" << bIsCenter; + qCDebug(appLog) << "Window::showCenterWindow() - bIsCenter:" << bIsCenter; // Init window state with config. // Below code must before this->titlebar()->setMenu, otherwise main menu can't display pre-build-in menu items by dtk. QString windowState = Settings::instance()->settings->option("advance.window.windowstate")->value().toString(); if (bIsCenter) { - qDebug() << "Window::showCenterWindow() - bIsCenter is true"; + qCDebug(appLog) << "Window::showCenterWindow() - bIsCenter is true"; Dtk::Widget::moveToCenter(this); } // init window state. if (windowState == "window_maximum") { - qDebug() << "Window::showCenterWindow() - setting window to maximized state"; + qCDebug(appLog) << "Window::showCenterWindow() - setting window to maximized state"; showMaximized(); m_needMoveToCenter = true; } else if (windowState == "fullscreen") { - qDebug() << "Window::showCenterWindow() - setting window to fullscreen state"; + qCDebug(appLog) << "Window::showCenterWindow() - setting window to fullscreen state"; showFullScreen(); m_needMoveToCenter = true; } else { - qDebug() << "Window::showCenterWindow() - setting window to normal state"; + qCDebug(appLog) << "Window::showCenterWindow() - setting window to normal state"; showNormal(); } - qDebug() << "Window::showCenterWindow() - end"; + qCDebug(appLog) << "Window::showCenterWindow() - end"; } void Window::initTitlebar() { - qDebug() << "initTitlebar called"; + qCDebug(appLog) << "initTitlebar called"; QAction *newWindowAction(new QAction(tr("New window"), this)); newWindowAction->setObjectName("NewWindow"); QAction *newTabAction(new QAction(tr("New tab"), this)); @@ -611,17 +612,17 @@ void Window::initTitlebar() connect(m_tabbar, &Tabbar::requestHistorySaved, this, [ = ](const QString & filePath) { // 单个Tab页关闭文件时记录文件信息 if (StartManager::instance()->checkPath(filePath)) { - qDebug() << "Recording close file history for file:" << filePath; + qCDebug(appLog) << "Recording close file history for file:" << filePath; Utils::recordCloseFile(filePath); } if (QFileInfo(filePath).dir().absolutePath() == m_blankFileDir) { - qDebug() << "File is a blank file, not recording in history:" << filePath; + qCDebug(appLog) << "File is a blank file, not recording in history:" << filePath; return; } if (!m_closeFileHistory.contains(filePath)) { - qDebug() << "Adding file to close file history:" << filePath; + qCDebug(appLog) << "Adding file to close file history:" << filePath; m_closeFileHistory << filePath; } }); @@ -643,42 +644,42 @@ void Window::initTitlebar() connect(printAction, &QAction::triggered, this, &Window::popupPrintDialog); connect(settingAction, &QAction::triggered, this, &Window::popupSettingsDialog); connect(switchThemeAction, &QAction::triggered, this, &Window::popupThemePanel); - qDebug() << "initTitlebar end"; + qCDebug(appLog) << "initTitlebar end"; } bool Window::checkBlockShutdown() { - qDebug() << "checkBlockShutdown called"; + qCDebug(appLog) << "checkBlockShutdown called"; //判断是否有未保存的tab项 for (int i = 0; i < m_tabbar->count(); i++) { QString tabText = m_tabbar->textAt(i); if (tabText.isNull() || tabText.isEmpty()) { - qDebug() << "Tab name is null or empty, return false"; + qCDebug(appLog) << "Tab name is null or empty, return false"; return false; } //如果有未保存的tab项,return true阻塞系统关机 if (tabText.at(0) == '*') { - qDebug() << "There are unsaved tabs, return true"; + qCDebug(appLog) << "There are unsaved tabs, return true"; return true; } } - qDebug() << "There are no unsaved tabs, return false"; + qCDebug(appLog) << "There are no unsaved tabs, return false"; return false; } int Window::getTabIndex(const QString &file) { - qDebug() << "getTabIndex called with file:" << file; + qCDebug(appLog) << "getTabIndex called with file:" << file; return m_tabbar->indexOf(file); } void Window::activeTab(int index) { - qDebug() << "activeTab called with index:" << index; + qCDebug(appLog) << "activeTab called with index:" << index; DMainWindow::activateWindow(); m_tabbar->setCurrentIndex(index); - qDebug() << "activeTab end"; + qCDebug(appLog) << "activeTab end"; } Tabbar *Window::getTabbar() @@ -688,23 +689,23 @@ Tabbar *Window::getTabbar() void Window::addTab(const QString &filepath, bool activeTab) { - qDebug() << "Enter addTab, filepath:" << filepath << "activeTab:" << activeTab; + qCDebug(appLog) << "Enter addTab, filepath:" << filepath << "activeTab:" << activeTab; // check whether it is an editable file thround mimeType. if (Utils::isMimeTypeSupport(filepath)) { const QFileInfo fileInfo(filepath); QString tabName = fileInfo.fileName(); - qDebug() << "File is supported, name:" << tabName << "writable:" << fileInfo.isWritable() << "readable:" << fileInfo.isReadable(); + qCDebug(appLog) << "File is supported, name:" << tabName << "writable:" << fileInfo.isWritable() << "readable:" << fileInfo.isReadable(); EditWrapper *curWrapper = currentWrapper(); if (!fileInfo.isWritable() && fileInfo.isReadable()) { tabName += QString(" (%1)").arg(tr("Read-Only")); - qDebug() << "File is read-only, updated tab name:" << tabName; + qCDebug(appLog) << "File is read-only, updated tab name:" << tabName; } if (curWrapper) { // if the current page is a draft file and is empty if (m_tabbar->indexOf(filepath) != -1) { - qDebug() << "File already open in tab index:" << m_tabbar->indexOf(filepath) << ", activating tab"; + qCDebug(appLog) << "File already open in tab index:" << m_tabbar->indexOf(filepath) << ", activating tab"; m_tabbar->setCurrentIndex(m_tabbar->indexOf(filepath)); } } @@ -717,32 +718,32 @@ void Window::addTab(const QString &filepath, bool activeTab) if (testFile.open(QIODevice::ReadOnly)) { testFile.close(); } else if (testFile.error() == QFileDevice::PermissionsError) { - qWarning() << "No permission to read file:" << filepath << "error:" << testFile.errorString(); + qCWarning(appLog) << "No permission to read file:" << filepath << "error:" << testFile.errorString(); QWidget *const msgParent = m_editorWidget->currentWidget() ? m_editorWidget->currentWidget() : this; DMessageManager::instance()->sendMessage(msgParent, QIcon(":/images/warning.svg"), QString(tr("You do not have permission to open %1")).arg(filepath)); return; } else { - qWarning() << "Failed to open file:" << filepath << "error:" << testFile.errorString(); + qCWarning(appLog) << "Failed to open file:" << filepath << "error:" << testFile.errorString(); } } if (StartManager::instance()->checkPath(filepath)) { - qDebug() << "Path check passed, adding tab for file"; + qCDebug(appLog) << "Path check passed, adding tab for file"; m_tabbar->addTab(filepath, tabName, filepath); if (!m_wrappers.contains(filepath)) { - qDebug() << "Creating new editor wrapper for file"; + qCDebug(appLog) << "Creating new editor wrapper for file"; EditWrapper *wrapper = createEditor(); showNewEditor(wrapper); m_wrappers[filepath] = wrapper; if (!fileInfo.isWritable() && fileInfo.isReadable()) { - qDebug() << "Setting read-only permission for editor"; + qCDebug(appLog) << "Setting read-only permission for editor"; wrapper->textEditor()->setReadOnlyPermission(true); } - qDebug() << "Opening file in editor"; + qCDebug(appLog) << "Opening file in editor"; wrapper->openFile(filepath, filepath); // 查找文件是否存在书签 @@ -751,59 +752,59 @@ void Window::addTab(const QString &filepath, bool activeTab) } // Activate window. activateWindow(); - qDebug() << "Window activated"; + qCDebug(appLog) << "Window activated"; } else { - qDebug() << "Path check failed, file may already be open in another window"; + qCDebug(appLog) << "Path check failed, file may already be open in another window"; } // Active tab if activeTab is true. if (activeTab) { int tabIndex = m_tabbar->indexOf(filepath); if (tabIndex != -1) { - qDebug() << "Activating tab at index:" << tabIndex; + qCDebug(appLog) << "Activating tab at index:" << tabIndex; m_tabbar->setCurrentIndex(tabIndex); } else { - qWarning() << "Failed to find tab for filepath:" << filepath; + qCWarning(appLog) << "Failed to find tab for filepath:" << filepath; } } } else { - qWarning() << "File is not supported by MIME type:" << filepath; + qCWarning(appLog) << "File is not supported by MIME type:" << filepath; if (currentWrapper() == nullptr) { - qDebug() << "No current wrapper, adding blank tab"; + qCDebug(appLog) << "No current wrapper, adding blank tab"; this->addBlankTab(); } QString strFileName = QFileInfo(filepath).fileName(); strFileName = tr("Invalid file: %1").arg(strFileName); strFileName = Utils::lineFeed(strFileName, m_editorWidget->currentWidget()->width() - FLOATTIP_MARGIN, m_editorWidget->currentWidget()->font(), 2); - qDebug() << "Showing invalid file notification"; + qCDebug(appLog) << "Showing invalid file notification"; DMessageManager::instance()->sendMessage(m_editorWidget->currentWidget(), QIcon(":/images/warning.svg"), strFileName); } - qDebug() << "Exit addTab"; + qCDebug(appLog) << "Exit addTab"; } void Window::addTabWithWrapper(EditWrapper *wrapper, const QString &filepath, const QString &qstrTruePath, const QString &tabName, int index) { - qDebug() << "Enter addTabWithWrapper, filepath:" << filepath << "truePath:" << qstrTruePath << "tabName:" << tabName << "index:" << index; + qCDebug(appLog) << "Enter addTabWithWrapper, filepath:" << filepath << "truePath:" << qstrTruePath << "tabName:" << tabName << "index:" << index; if (index == -1) { index = m_tabbar->count(); - qDebug() << "Index not specified, using tab count:" << index; + qCDebug(appLog) << "Index not specified, using tab count:" << index; } //这里会重复连接信号和槽,先全部取消 QDBusConnection dbus = QDBusConnection::sessionBus(); - qDebug() << "Disconnecting previous DBus signals for gesture events"; + qCDebug(appLog) << "Disconnecting previous DBus signals for gesture events"; switch (Utils::getSystemVersion()) { case Utils::V23: - qDebug() << "Using V23 DBus path for gesture events"; + qCDebug(appLog) << "Using V23 DBus path for gesture events"; dbus.systemBus().disconnect("org.deepin.dde.Gesture1", "/org/deepin/dde/Gesture1", "org.deepin.dde.Gesture1", "Event", wrapper->textEditor(), SLOT(fingerZoom(QString, QString, int))); break; default: - qDebug() << "Using default DBus path for gesture events"; + qCDebug(appLog) << "Using default DBus path for gesture events"; dbus.systemBus().disconnect("com.deepin.daemon.Gesture", "/com/deepin/daemon/Gesture", "com.deepin.daemon.Gesture", "Event", @@ -811,10 +812,10 @@ void Window::addTabWithWrapper(EditWrapper *wrapper, const QString &filepath, co break; } - qDebug() << "Disconnecting all signals from text editor"; + qCDebug(appLog) << "Disconnecting all signals from text editor"; wrapper->textEditor()->disconnect(); - qDebug() << "Connecting signals to text editor"; + qCDebug(appLog) << "Connecting signals to text editor"; connect(wrapper->textEditor(), &TextEdit::clickFindAction, this, &Window::popupFindBar, Qt::QueuedConnection); connect(wrapper->textEditor(), &TextEdit::clickReplaceAction, this, &Window::popupReplaceBar, Qt::QueuedConnection); connect(wrapper->textEditor(), &TextEdit::clickJumpLineAction, this, &Window::popupJumpLineBar, Qt::QueuedConnection); @@ -826,17 +827,17 @@ void Window::addTabWithWrapper(EditWrapper *wrapper, const QString &filepath, co m_findBar, &FindBar::slotUpdateMatchCount, Qt::QueuedConnection); connect(wrapper->textEditor(), &TextEdit::findMatchCountChanged, m_replaceBar, &ReplaceBar::slotUpdateMatchCount, Qt::QueuedConnection); - qDebug() << "Reconnecting DBus signals for gesture events"; + qCDebug(appLog) << "Reconnecting DBus signals for gesture events"; switch (Utils::getSystemVersion()) { case Utils::V23: - qDebug() << "Connecting to V23 DBus path for gesture events"; + qCDebug(appLog) << "Connecting to V23 DBus path for gesture events"; dbus.systemBus().connect("org.deepin.dde.Gesture1", "/org/deepin/dde/Gesture1", "org.deepin.dde.Gesture1", "Event", wrapper->textEditor(), SLOT(fingerZoom(QString, QString, int))); break; default: - qDebug() << "Connecting to default DBus path for gesture events"; + qCDebug(appLog) << "Connecting to default DBus path for gesture events"; dbus.systemBus().connect("com.deepin.daemon.Gesture", "/com/deepin/daemon/Gesture", "com.deepin.daemon.Gesture", "Event", @@ -850,16 +851,16 @@ void Window::addTabWithWrapper(EditWrapper *wrapper, const QString &filepath, co wrapper->UpdateBottomBarWordCnt(wrapper->textEditor()->characterCount()); }); - qDebug() << "Adding tab to tabbar at index:" << index << "with filepath:" << filepath << "tabName:" << tabName; + qCDebug(appLog) << "Adding tab to tabbar at index:" << index << "with filepath:" << filepath << "tabName:" << tabName; // add wrapper to this window. m_tabbar->addTabWithIndex(index, filepath, tabName, qstrTruePath); m_wrappers[filepath] = wrapper; wrapper->updatePath(filepath, qstrTruePath); - qDebug() << "Showing new editor and applying theme"; + qCDebug(appLog) << "Showing new editor and applying theme"; showNewEditor(wrapper); wrapper->OnThemeChangeSlot(m_themePath); - qDebug() << "Exit addTabWithWrapper"; + qCDebug(appLog) << "Exit addTabWithWrapper"; } /** @@ -867,24 +868,24 @@ void Window::addTabWithWrapper(EditWrapper *wrapper, const QString &filepath, co */ bool Window::closeTab() { - qDebug() << "Enter closeTab (no arguments)"; + qCDebug(appLog) << "Enter closeTab (no arguments)"; const QString &filePath = m_tabbar->currentPath(); // 避免异常情况重入时当前已无标签页的情况 if (filePath.isEmpty()) { - qWarning() << "Current tab path is empty, cannot close tab"; + qCWarning(appLog) << "Current tab path is empty, cannot close tab"; return false; } - qDebug() << "Closing current tab with path:" << filePath; + qCDebug(appLog) << "Closing current tab with path:" << filePath; return closeTab(filePath); } bool Window::closeTab(const QString &filePath) { - qDebug() << "Enter closeTab with path:" << filePath; + qCDebug(appLog) << "Enter closeTab with path:" << filePath; // 懒加载:如果标签页处于待加载状态,直接移除 if (isPendingTab(filePath)) { - qInfo() << "Closing pending tab:" << filePath; + qCInfo(appLog) << "Closing pending tab:" << filePath; m_pendingTabs.remove(filePath); int index = m_tabbar->indexOf(filePath); if (index >= 0) { @@ -899,35 +900,35 @@ bool Window::closeTab(const QString &filePath) EditWrapper *wrapper = m_wrappers.value(filePath); if (!wrapper) { - qWarning() << "No wrapper found for path:" << filePath; + qCWarning(appLog) << "No wrapper found for path:" << filePath; return false; } if (!currentWrapper()) { - qWarning() << "No current wrapper, cannot close tab"; + qCWarning(appLog) << "No current wrapper, cannot close tab"; return false; } if (m_reading_list.contains(currentWrapper()->textEditor())) { - qDebug() << "Current editor is in reading list, syncing settings"; + qCDebug(appLog) << "Current editor is in reading list, syncing settings"; if (m_settings->settings) { m_settings->settings->sync(); } if (IflytekAiAssistant::instance()->valid()) { - qDebug() << "Stopping TTS playback"; + qCDebug(appLog) << "Stopping TTS playback"; IflytekAiAssistant::instance()->stopTtsDirectly(); } } // 当前窗口为打印文本窗口 if (wrapper == m_printWrapper) { - qDebug() << "Closing print wrapper, exiting print mode"; + qCDebug(appLog) << "Closing print wrapper, exiting print mode"; // 退出打印 m_bPrintProcessing = false; } - qDebug() << "Disconnecting all signals from wrapper"; + qCDebug(appLog) << "Disconnecting all signals from wrapper"; disconnect(wrapper, nullptr); disconnect(wrapper->textEditor(), &TextEdit::textChanged, nullptr, nullptr); @@ -935,41 +936,41 @@ bool Window::closeTab(const QString &filePath) bool isModified = wrapper->isModified(); bool isDraftFile = wrapper->isDraftFile(); bool bIsBackupFile = false; - qDebug() << "Tab state - modified:" << isModified << "draft file:" << isDraftFile; + qCDebug(appLog) << "Tab state - modified:" << isModified << "draft file:" << isDraftFile; if (wrapper->isTemFile()) { bIsBackupFile = true; - qDebug() << "Tab is a temporary backup file"; + qCDebug(appLog) << "Tab is a temporary backup file"; } if (wrapper->getFileLoading()) { - qDebug() << "File is still loading, setting modified to false"; + qCDebug(appLog) << "File is still loading, setting modified to false"; isModified = false; } // 关闭标签页前,记录全局的书签信息 QList bookmarkInfo = wrapper->textEditor()->getBookmarkInfo(); if (!bookmarkInfo.isEmpty()) { - qDebug() << "Saving bookmarks for file:" << bookmarkInfo; + qCDebug(appLog) << "Saving bookmarks for file:" << bookmarkInfo; QString localPath = wrapper->textEditor()->getTruePath(); StartManager::instance()->recordBookmark(localPath, bookmarkInfo); } if (isDraftFile) { if (isModified) { - qDebug() << "Draft file is modified, prompting to save"; + qCDebug(appLog) << "Draft file is modified, prompting to save"; DDialog *dialog = createDialog(tr("Do you want to save this file?"), ""); int res = dialog->exec(); //取消或关闭弹窗不做任务操作 if (res == 0 || res == -1) { - qDebug() << "Dialog cancelled or closed, not performing any actions"; + qCDebug(appLog) << "Dialog cancelled or closed, not performing any actions"; return false; } //不保存 if (res == 1) { - qDebug() << "User chose not to save, removing wrapper and closing tab"; + qCDebug(appLog) << "User chose not to save, removing wrapper and closing tab"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); QFile(filePath).remove(); @@ -982,19 +983,19 @@ bool Window::closeTab(const QString &filePath) QString newFilePath; if (wrapper->saveDraftFile(newFilePath)) { - qDebug() << "Draft file saved, removing wrapper and closing tab"; + qCDebug(appLog) << "Draft file saved, removing wrapper and closing tab"; removeWrapper(filePath, true); // 保存临时文件后已更新tab页的文件路径,使用新的文件路径删除窗口 m_tabbar->closeCurrentTab(newFilePath); QFile(filePath).remove(); } else { // 保存不成功时不关闭窗口 - qDebug() << "Draft file save failed, not closing tab"; + qCDebug(appLog) << "Draft file save failed, not closing tab"; return false; } } } else { - qDebug() << "Draft file is not modified, removing wrapper and closing tab"; + qCDebug(appLog) << "Draft file is not modified, removing wrapper and closing tab"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); QFile(filePath).remove(); @@ -1012,13 +1013,13 @@ bool Window::closeTab(const QString &filePath) int res = confirmInvalidCharSave(fileName); switch (res) { case 0: // Don't Save - qDebug() << "Preview closeTab: Don't Save, closing tab"; + qCDebug(appLog) << "Preview closeTab: Don't Save, closing tab"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); return true; case 1: // Save As { - qDebug() << "Preview closeTab: Save As"; + qCDebug(appLog) << "Preview closeTab: Save As"; QString newPath = saveAsFileToDisk(); if (!newPath.isEmpty()) { // saveAsFileToDisk 成功后 wrapper 映射键已更新为 newPath,必须用 newPath 关闭 @@ -1029,7 +1030,7 @@ bool Window::closeTab(const QString &filePath) return false; // 失败或取消不关闭 } case 2: // Save Anyway - qDebug() << "Preview closeTab: Save Anyway"; + qCDebug(appLog) << "Preview closeTab: Save Anyway"; if (wrapper->forceSaveInvalidCharFile()) { removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); @@ -1037,12 +1038,12 @@ bool Window::closeTab(const QString &filePath) } return false; default: // 取消 - qDebug() << "Preview closeTab: cancelled"; + qCDebug(appLog) << "Preview closeTab: cancelled"; return false; } } else { // 预览模式但未编辑(未点 Edit Anyway 或无修改),直接关闭不提示 - qDebug() << "Preview closeTab: no edits, closing tab without prompt"; + qCDebug(appLog) << "Preview closeTab: no edits, closing tab without prompt"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); return true; @@ -1050,37 +1051,37 @@ bool Window::closeTab(const QString &filePath) } if (isModified) { - qDebug() << "File is modified, prompting to save"; + qCDebug(appLog) << "File is modified, prompting to save"; DDialog *dialog = createDialog(tr("Do you want to save this file?"), ""); int res = dialog->exec(); //取消或关闭弹窗不做任务操作 if (res == 0 || res == -1) { - qDebug() << "Dialog cancelled or closed, not performing any actions"; + qCDebug(appLog) << "Dialog cancelled or closed, not performing any actions"; return false; } //不保存 if (res == 1) { - qDebug() << "User chose not to save, removing wrapper and closing tab"; + qCDebug(appLog) << "User chose not to save, removing wrapper and closing tab"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); //删除备份文件 if (bIsBackupFile) { - qDebug() << "Deleting backup file"; + qCDebug(appLog) << "Deleting backup file"; QFile(filePath).remove(); } //删除自动备份文件 if (QFileInfo(m_autoBackupDir).exists()) { - qDebug() << "Deleting auto backup file"; + qCDebug(appLog) << "Deleting auto backup file"; fileInfo.setFile(wrapper->textEditor()->getTruePath()); QString name = fileInfo.absolutePath().replace("/", "_"); QDir(m_autoBackupDir).remove(fileInfo.baseName() + "." + name + "." + fileInfo.suffix()); } - qDebug() << "Exit closeTab, return true"; + qCDebug(appLog) << "Exit closeTab, return true"; return true; } @@ -1088,66 +1089,66 @@ bool Window::closeTab(const QString &filePath) if (res == 2) { if (bIsBackupFile) { if (wrapper->saveFile()) { - qDebug() << "File saved, removing wrapper and closing tab"; + qCDebug(appLog) << "File saved, removing wrapper and closing tab"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); QFile(filePath).remove(); } else { - qDebug() << "File save failed, fall to save as"; + qCDebug(appLog) << "File save failed, fall to save as"; // 另存被拒/失败时保留标签页并返回 false, // 防止调用方(如 closeAllFiles)误认为关闭成功而丢失未保存修改 if (!saveAsFile()) { - qWarning() << "Save as file cancelled or failed, keep tab open"; + qCWarning(appLog) << "Save as file cancelled or failed, keep tab open"; return false; } } } else { - qDebug() << "File is not a backup file, saving normally"; + qCDebug(appLog) << "File is not a backup file, saving normally"; if (wrapper->saveFile()) { - qDebug() << "File saved, removing wrapper and closing tab"; + qCDebug(appLog) << "File saved, removing wrapper and closing tab"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); } else { - qDebug() << "File save failed, fall to save as"; + qCDebug(appLog) << "File save failed, fall to save as"; if (!saveAsFile()) { - qWarning() << "Save as file cancelled or failed, keep tab open"; + qCWarning(appLog) << "Save as file cancelled or failed, keep tab open"; return false; } } } } } else { - qDebug() << "File is not modified, removing wrapper and closing tab"; + qCDebug(appLog) << "File is not modified, removing wrapper and closing tab"; removeWrapper(filePath, true); m_tabbar->closeCurrentTab(filePath); } //删除自动备份文件 if (QFileInfo(m_autoBackupDir).exists()) { - qDebug() << "Deleting auto backup file"; + qCDebug(appLog) << "Deleting auto backup file"; fileInfo.setFile(wrapper->textEditor()->getTruePath()); QString name = fileInfo.absolutePath().replace("/", "_"); QDir(m_autoBackupDir).remove(fileInfo.baseName() + "." + name + "." + fileInfo.suffix()); } } - qDebug() << "Exit closeTab, return true"; + qCDebug(appLog) << "Exit closeTab, return true"; return true; } void Window::restoreTab() { - qDebug() << "Enter restoreTab"; + qCDebug(appLog) << "Enter restoreTab"; if (m_closeFileHistory.size() > 0) { - qDebug() << "Restoring tab from history"; + qCDebug(appLog) << "Restoring tab from history"; addTab(m_closeFileHistory.takeLast()); } - qDebug() << "Exit restoreTab"; + qCDebug(appLog) << "Exit restoreTab"; } EditWrapper *Window::createEditor() { - qDebug() << "Creating new EditWrapper instance"; + qCDebug(appLog) << "Creating new EditWrapper instance"; EditWrapper *wrapper = new EditWrapper(this); connect(wrapper, &EditWrapper::sigClearDoubleCharaterEncode, this, &Window::slotClearDoubleCharaterEncode); connect(wrapper->textEditor(), &TextEdit::signal_readingPath, this, &Window::slot_saveReadingPath, Qt::QueuedConnection); @@ -1183,33 +1184,33 @@ EditWrapper *Window::createEditor() wrapper->textEditor()->setCodeFlodFlagVisable(m_settings->settings->option("base.font.codeflod")->value().toBool(), true); wrapper->textEditor()->updateLeftAreaWidget(); - qDebug() << "Creating new TextEdit instance"; + qCDebug(appLog) << "Creating new TextEdit instance"; return wrapper; } EditWrapper *Window::currentWrapper() { - qDebug() << "Enter currentWrapper"; + qCDebug(appLog) << "Enter currentWrapper"; if (m_wrappers.contains(m_tabbar->currentPath())) { - qDebug() << "Found wrapper for current path:" << m_tabbar->currentPath(); + qCDebug(appLog) << "Found wrapper for current path:" << m_tabbar->currentPath(); return m_wrappers.value(m_tabbar->currentPath()); } else { - qDebug() << "No wrapper found for current path:" << m_tabbar->currentPath(); + qCDebug(appLog) << "No wrapper found for current path:" << m_tabbar->currentPath(); return nullptr; } } EditWrapper *Window::wrapper(const QString &filePath) { - qDebug() << "Enter wrapper with path:" << filePath; + qCDebug(appLog) << "Enter wrapper with path:" << filePath; if (m_wrappers.contains(filePath)) { EditWrapper* wrapper = m_wrappers.value(filePath); // Although contains check passed, add a safety check if (!wrapper) { - qWarning() << "Wrapper is null even after contains check"; + qCWarning(appLog) << "Wrapper is null even after contains check"; return nullptr; } - qDebug() << "Found wrapper for path:" << filePath; + qCDebug(appLog) << "Found wrapper for path:" << filePath; return wrapper; } else { for (auto iterWrapper : m_wrappers) { @@ -1221,59 +1222,59 @@ EditWrapper *Window::wrapper(const QString &filePath) QString originalWrapperPath = iterWrapper->textEditor()->getFilePath(); EditWrapper* foundWrapper = m_wrappers.value(originalWrapperPath); if (!foundWrapper) { - qWarning() << "Failed to get wrapper for original path when searching"; + qCWarning(appLog) << "Failed to get wrapper for original path when searching"; // Continue searching instead of returning nullptr immediately continue; } - qDebug() << "Found wrapper for original path:" << originalWrapperPath; + qCDebug(appLog) << "Found wrapper for original path:" << originalWrapperPath; return foundWrapper; } } - qDebug() << "No wrapper found for path:" << filePath; + qCDebug(appLog) << "No wrapper found for path:" << filePath; return nullptr; } } TextEdit *Window::getTextEditor(const QString &filepath) { - qDebug() << "Enter getTextEditor with path:" << filepath; + qCDebug(appLog) << "Enter getTextEditor with path:" << filepath; if (m_wrappers.contains(filepath)) { EditWrapper* wrapper = m_wrappers.value(filepath); if (!wrapper) { - qWarning() << "Wrapper is null even after contains check"; + qCWarning(appLog) << "Wrapper is null even after contains check"; return nullptr; } - qDebug() << "Found text editor for path:" << filepath; + qCDebug(appLog) << "Found text editor for path:" << filepath; return wrapper->textEditor(); } else { - qDebug() << "No text editor found for path:" << filepath; + qCDebug(appLog) << "No text editor found for path:" << filepath; return nullptr; } } void Window::focusActiveEditor() { - qDebug() << "Enter focusActiveEditor"; + qCDebug(appLog) << "Enter focusActiveEditor"; if (m_tabbar->count() > 0) { if (currentWrapper() == nullptr) { - qDebug() << "No current wrapper, adding blank tab"; + qCDebug(appLog) << "No current wrapper, adding blank tab"; return; } currentWrapper()->textEditor()->setFocus(); } - qDebug() << "Exit focusActiveEditor"; + qCDebug(appLog) << "Exit focusActiveEditor"; } void Window::removeWrapper(const QString &filePath, bool isDelete) { - qDebug() << "Enter removeWrapper with path:" << filePath << "isDelete:" << isDelete; + qCDebug(appLog) << "Enter removeWrapper with path:" << filePath << "isDelete:" << isDelete; EditWrapper *wrapper = m_wrappers.value(filePath); if (wrapper) { - qInfo() << "begin removeWrapper"; + qCInfo(appLog) << "begin removeWrapper"; if (nullptr == m_editorWidget) { - qWarning() << "m_editorWidget is null"; + qCWarning(appLog) << "m_editorWidget is null"; return; } m_editorWidget->removeWidget(wrapper); @@ -1283,7 +1284,7 @@ void Window::removeWrapper(const QString &filePath, bool isDelete) disconnect(wrapper, nullptr); wrapper->setQuitFlag(); wrapper->deleteLater(); - qInfo() << "after delete wrapper"; + qCInfo(appLog) << "after delete wrapper"; } } @@ -1292,16 +1293,16 @@ void Window::removeWrapper(const QString &filePath, bool isDelete) // Only close the window when the tabbar has no tabs left. if (m_wrappers.isEmpty() && m_tabbar->count() == 0) { close(); - qInfo() << "after close"; + qCInfo(appLog) << "after close"; } - qInfo() << "end removeWrapper"; + qCInfo(appLog) << "end removeWrapper"; StartManager::instance()->delayMallocTrim(); } void Window::openFile() { - qDebug() << "Opening file dialog"; + qCDebug(appLog) << "Opening file dialog"; QFileDialog dialog(this); dialog.setFileMode(QFileDialog::ExistingFiles); @@ -1311,28 +1312,28 @@ void Window::openFile() QString historyDirStr = m_settings->settings->option("advance.editor.file_dialog_dir")->value().toString(); if (historyDirStr.isEmpty() || !QDir(historyDirStr).exists() || !QFileInfo(historyDirStr).isWritable() || !QDir(historyDirStr).isReadable()) { historyDirStr = QDir::homePath() + "/Documents"; - qDebug() << "History directory is empty or invalid, using default path:" << historyDirStr; + qCDebug(appLog) << "History directory is empty or invalid, using default path:" << historyDirStr; } dialog.setDirectory(historyDirStr); QDir historyDir(historyDirStr); if (historyDir.exists()) { - qDebug() << "Setting dialog directory to history directory:" << historyDir.absolutePath(); + qCDebug(appLog) << "Setting dialog directory to history directory:" << historyDir.absolutePath(); dialog.setDirectory(historyDir); } else { - qDebug() << "historyDir or default path not existed:" << historyDir; + qCDebug(appLog) << "historyDir or default path not existed:" << historyDir; } QString path = m_settings->getSavePath(m_settings->getSavePathId()); // 使用当前文件路径时,打开当前文件的目录,新建文档为系统-文档目录 if (PathSettingWgt::CurFileBox == m_settings->getSavePathId()) { path = getCurrentOpenFilePath(); - qDebug() << "Setting dialog directory to current file path:" << path; + qCDebug(appLog) << "Setting dialog directory to current file path:" << path; } if (path.isEmpty() || !QDir(path).exists() || !QFileInfo(path).isWritable() || !QDir(path).isReadable()) { path = QDir::homePath() + "/Documents"; - qDebug() << "Save path is empty or invalid, using default path:" << path; + qCDebug(appLog) << "Save path is empty or invalid, using default path:" << path; } dialog.setDirectory(path); @@ -1343,7 +1344,7 @@ void Window::openFile() m_settings->settings->option("advance.editor.file_dialog_dir")->setValue(dialog.directoryUrl().toLocalFile()); if (mode != QDialog::Accepted) { - qDebug() << "File dialog not accepted, returning"; + qCDebug(appLog) << "File dialog not accepted, returning"; return; } @@ -1383,12 +1384,12 @@ void Window::openFile() foreach (QString var, otherfiles) { addTab(var, true); } - qDebug() << "Exit openFile"; + qCDebug(appLog) << "Exit openFile"; } int Window::confirmInvalidCharSave(const QString &fileName) { - qDebug() << "confirmInvalidCharSave for file:" << fileName; + qCDebug(appLog) << "confirmInvalidCharSave for file:" << fileName; DDialog *dialog = new DDialog( tr("Invalid characters detected while saving \"%1\"").arg(fileName), tr("If you force save this file, it may cause file corruption. Still want to save?"), @@ -1407,13 +1408,13 @@ int Window::confirmInvalidCharSave(const QString &fileName) bool Window::saveFile() { - qDebug() << "Saving current file"; + qCDebug(appLog) << "Saving current file"; EditWrapper *wrapperEdit = currentWrapper(); //大文本加载过程不允许保存 if (!wrapperEdit || wrapperEdit->getFileLoading()) { - qDebug() << "Wrapper is null or file is loading, returning"; + qCDebug(appLog) << "Wrapper is null or file is loading, returning"; return false; } @@ -1421,7 +1422,7 @@ bool Window::saveFile() if (wrapperEdit->isInvalidCharPreview()) { // 未编辑(未点 Edit Anyway)时无需保存,直接返回 if (!wrapperEdit->isInvalidCharEditAllowed()) { - qDebug() << "Preview save: no edits made, nothing to save"; + qCDebug(appLog) << "Preview save: no edits made, nothing to save"; return false; } QString filePath = wrapperEdit->textEditor()->getTruePath(); @@ -1429,20 +1430,20 @@ bool Window::saveFile() int res = confirmInvalidCharSave(fileName); switch (res) { case 0: // Don't Save - qDebug() << "Preview save: Don't Save"; + qCDebug(appLog) << "Preview save: Don't Save"; return false; case 1: // Save As - qDebug() << "Preview save: Save As"; + qCDebug(appLog) << "Preview save: Save As"; return saveAsFile(); case 2: // Save Anyway - qDebug() << "Preview save: Save Anyway"; + qCDebug(appLog) << "Preview save: Save Anyway"; if (wrapperEdit->forceSaveInvalidCharFile()) { showNotify(tr("Saved successfully")); return true; } return false; default: // 取消 - qDebug() << "Preview save: cancelled"; + qCDebug(appLog) << "Preview save: cancelled"; return false; } } @@ -1453,7 +1454,7 @@ bool Window::saveFile() // save blank file. if (isDraftFile) { - qDebug() << "Saving draft file"; + qCDebug(appLog) << "Saving draft file"; return saveAsFile(); } @@ -1466,7 +1467,7 @@ bool Window::saveFile() if (!isWrite) { DMessageManager::instance()->sendMessage(m_editorWidget->currentWidget(), QIcon(":/images/warning.svg") , QString(tr("You do not have permission to save %1")).arg(info.fileName())); - qDebug() << "File does not have write permission, returning"; + qCDebug(appLog) << "File does not have write permission, returning"; return false; } } @@ -1484,7 +1485,7 @@ bool Window::saveFile() if (success) { updateSabeAsFileNameTemp(temPath, filePath); if (currentWrapper()) { - qDebug() << "Saved successfully, updating save as file name"; + qCDebug(appLog) << "Saved successfully, updating save as file name"; currentWrapper()->hideWarningNotices(); } showNotify(tr("Saved successfully")); @@ -1496,33 +1497,33 @@ bool Window::saveFile() //删除自动备份文件 if (QFileInfo(m_autoBackupDir).exists()) { - qDebug() << "Deleting auto backup file"; + qCDebug(appLog) << "Deleting auto backup file"; QFileInfo fileInfo(filePath); QString name = fileInfo.absolutePath().replace("/", "_"); QDir(m_autoBackupDir).remove(fileInfo.baseName() + "." + name + "." + fileInfo.suffix()); } - qDebug() << "Exit saveFile, return true"; + qCDebug(appLog) << "Exit saveFile, return true"; return true; } - qDebug() << "Failed to save file, returning"; + qCDebug(appLog) << "Failed to save file, returning"; return false; } bool Window::saveAsFile() { - qDebug() << "Enter saveAsFile"; + qCDebug(appLog) << "Enter saveAsFile"; return !saveAsFileToDisk().isEmpty(); } QString Window::saveAsFileToDisk() { - qDebug() << "Enter saveAsFileToDisk"; + qCDebug(appLog) << "Enter saveAsFileToDisk"; EditWrapper *wrapper = currentWrapper(); //大文本加载过程不允许保存 梁卫东 if (!wrapper || wrapper->getFileLoading()) { - qDebug() << "Wrapper is null or file is loading, returning"; + qCDebug(appLog) << "Wrapper is null or file is loading, returning"; return QString(); } @@ -1543,11 +1544,11 @@ QString Window::saveAsFileToDisk() // 使用当前文件路径时,打开当前文件的目录,新建文档为系统-文档目录 if (PathSettingWgt::CurFileBox == m_settings->getSavePathId()) { path = getCurrentOpenFilePath(); - qDebug() << "Setting dialog directory to current file path:" << path; + qCDebug(appLog) << "Setting dialog directory to current file path:" << path; } if (path.isEmpty() || !QDir(path).exists() || !QFileInfo(path).isWritable() || !QDir(path).isReadable()) { path = QDir::homePath() + "/Documents"; - qDebug() << "Save path is empty or invalid, using default path:" << path; + qCDebug(appLog) << "Save path is empty or invalid, using default path:" << path; } dialog.setDirectory(path); @@ -1555,16 +1556,16 @@ QString Window::saveAsFileToDisk() QRegularExpression reg("[^*](.+)"); QRegularExpressionMatch match = reg.match(m_tabbar->currentName()); dialog.selectFile(match.captured(0) + ".txt"); - qDebug() << "Setting dialog file name to draft file name:" << match.captured(0) + ".txt"; + qCDebug(appLog) << "Setting dialog file name to draft file name:" << match.captured(0) + ".txt"; } else { dialog.setDirectory(fileInfo.dir()); dialog.selectFile(fileInfo.fileName()); - qDebug() << "Setting dialog file name to current file name:" << fileInfo.fileName(); + qCDebug(appLog) << "Setting dialog file name to current file name:" << fileInfo.fileName(); } int mode = dialog.exec(); if (mode == QDialog::Accepted) { - qDebug() << "File dialog accepted, proceeding with save as"; + qCDebug(appLog) << "File dialog accepted, proceeding with save as"; const QByteArray encode = dialog.getComboBoxValue(QObject::tr("Encoding")).toUtf8(); const QString newFilePath = dialog.selectedFiles().value(0); Settings::instance()->setSavePath(PathSettingWgt::LastOptBox, QFileInfo(newFilePath).absolutePath()); @@ -1574,7 +1575,7 @@ QString Window::saveAsFileToDisk() if (wrapper->isInvalidCharPreview()) { QString originalPath = wrapper->invalidCharOriginalPath(); if (QFileInfo(originalPath).absoluteFilePath() == QFileInfo(newFilePath).absoluteFilePath()) { - qDebug() << "Save As rejected: same as original path in preview mode"; + qCDebug(appLog) << "Save As rejected: same as original path in preview mode"; DMessageManager::instance()->sendMessage( m_editorWidget->currentWidget(), QIcon(":/images/warning.svg"), @@ -1593,19 +1594,19 @@ QString Window::saveAsFileToDisk() == QFileInfo(newFilePath).absoluteFilePath()) { // 相同路径,直接保存文件 saveSucc = wrapper->saveFile(encode); - qDebug() << "Same file path, directly saving file"; + qCDebug(appLog) << "Same file path, directly saving file"; } else { saveSucc = wrapper->saveAsFile(newFilePath, encode); - qDebug() << "Saving file as new path:" << newFilePath; + qCDebug(appLog) << "Saving file as new path:" << newFilePath; } if (!saveSucc) { /* 如果保存未成功,无需记录更新新文件路径 */ wrapper->updatePath(wrapper->filePath(), QString()); - qDebug() << "Save failed, returning empty string"; + qCDebug(appLog) << "Save failed, returning empty string"; return QString(); } else { - qDebug() << "Save successful, updating file path to:" << newFilePath; + qCDebug(appLog) << "Save successful, updating file path to:" << newFilePath; // 保存成功后再更新路径,防止文件还未保存完成就触发文件是否存在的检测 wrapper->updatePath(oldFilePath, newFilePath); @@ -1621,18 +1622,18 @@ QString Window::saveAsFileToDisk() // 若编码变更,保存完成后,重新加载文件 if (needChangeEncode) { wrapper->readFile(encode); - qDebug() << "Encoding changed, reloading file with new encoding"; + qCDebug(appLog) << "Encoding changed, reloading file with new encoding"; } } if (wrapper->filePath().contains(m_backupDir) || wrapper->filePath().contains(m_blankFileDir)) { QFile(wrapper->filePath()).remove(); - qDebug() << "Removed backup or blank file at path:" << wrapper->filePath(); + qCDebug(appLog) << "Removed backup or blank file at path:" << wrapper->filePath(); } //删除自动备份文件 if (QFileInfo(m_autoBackupDir).exists()) { - qDebug() << "Deleting auto backup file"; + qCDebug(appLog) << "Deleting auto backup file"; QString truePath = wrapper->textEditor()->getTruePath(); fileInfo.setFile(truePath); QString name = fileInfo.absolutePath().replace("/", "_"); @@ -1641,36 +1642,36 @@ QString Window::saveAsFileToDisk() /* 如果另存为的文件名+路径与当前tab项对应的文件名+路径是一致,则直接做保存操作即可 */ if (!wrapper->filePath().compare(newFilePath)) { - qDebug() << "File path matches new file path, updating tab name"; + qCDebug(appLog) << "File path matches new file path, updating tab name"; if (saveFile()) { - qDebug() << "Save successful, returning new file path"; + qCDebug(appLog) << "Save successful, returning new file path"; return newFilePath; } } updateSaveAsFileName(oldFilePath, newFilePath); - qDebug() << "Exit saveAsFileToDisk, return new file path"; + qCDebug(appLog) << "Exit saveAsFileToDisk, return new file path"; return newFilePath; } - qDebug() << "Exit saveAsFileToDisk, return empty string"; + qCDebug(appLog) << "Exit saveAsFileToDisk, return empty string"; return QString(); } QString Window::saveBlankFileToDisk() { - qDebug() << "Enter saveBlankFileToDisk"; + qCDebug(appLog) << "Enter saveBlankFileToDisk"; QString filePath = m_tabbar->currentPath(); EditWrapper *wrapper = m_wrappers.value(filePath); if (!wrapper) { - qWarning() << "Failed to get wrapper for current path"; + qCWarning(appLog) << "Failed to get wrapper for current path"; return QString(); } bool isDraft = Utils::isDraftFile(filePath); QFileInfo fileInfo(filePath); if (!wrapper) { - qWarning() << "Failed to get wrapper for current path"; + qCWarning(appLog) << "Failed to get wrapper for current path"; return QString(); } @@ -1683,11 +1684,11 @@ QString Window::saveBlankFileToDisk() QRegularExpression reg("[^*](.+)"); QRegularExpressionMatch match = reg.match(m_tabbar->currentName()); dialog.selectFile(match.captured(0) + ".txt"); - qDebug() << "Setting dialog file name to draft file name:" << match.captured(0) + ".txt"; + qCDebug(appLog) << "Setting dialog file name to draft file name:" << match.captured(0) + ".txt"; } else { dialog.setDirectory(fileInfo.dir()); dialog.selectFile(fileInfo.fileName()); - qDebug() << "Setting dialog file name to current file name:" << fileInfo.fileName(); + qCDebug(appLog) << "Setting dialog file name to current file name:" << fileInfo.fileName(); } int mode = dialog.exec(); @@ -1700,20 +1701,20 @@ QString Window::saveBlankFileToDisk() m_wrappers.insert(newFilePath, wrapper); // wrapper->textEditor()->loadHighlighter(); - qDebug() << "Saved blank file to disk, returning new file path:" << newFilePath; + qCDebug(appLog) << "Saved blank file to disk, returning new file path:" << newFilePath; return newFilePath; } - qDebug() << "Exit saveBlankFileToDisk, returning empty string"; + qCDebug(appLog) << "Exit saveBlankFileToDisk, returning empty string"; return QString(); } bool Window::saveAsOtherTabFile(EditWrapper *wrapper) { - qDebug() << "Enter saveAsOtherTabFile"; + qCDebug(appLog) << "Enter saveAsOtherTabFile"; // 判空必须前置于任何 wrapper 成员访问,否则空指针解引用 if (!wrapper) { - qWarning() << "Wrapper is null, cannot save as other tab file"; + qCWarning(appLog) << "Wrapper is null, cannot save as other tab file"; return false; } QString filePath = wrapper->textEditor()->getFilePath(); @@ -1732,11 +1733,11 @@ bool Window::saveAsOtherTabFile(EditWrapper *wrapper) QRegularExpression reg("[^*](.+)"); QRegularExpressionMatch match = reg.match(strTabText); dialog.selectFile(match.captured(0) + ".txt"); - qDebug() << "Setting dialog file name to draft file name:" << match.captured(0) + ".txt"; + qCDebug(appLog) << "Setting dialog file name to draft file name:" << match.captured(0) + ".txt"; } else { dialog.setDirectory(fileInfo.dir()); dialog.selectFile(fileInfo.fileName()); - qDebug() << "Setting dialog file name to current file name:" << fileInfo.fileName(); + qCDebug(appLog) << "Setting dialog file name to current file name:" << fileInfo.fileName(); } int mode = dialog.exec(); @@ -1755,7 +1756,7 @@ bool Window::saveAsOtherTabFile(EditWrapper *wrapper) if (isDraft) { QFile(filePath).remove(); - qDebug() << "Removing draft file at path:" << filePath; + qCDebug(appLog) << "Removing draft file at path:" << filePath; } //m_tabbar->updateTab(m_tabbar->currentIndex(), newFilePath, newFileInfo.fileName()); @@ -1767,11 +1768,11 @@ bool Window::saveAsOtherTabFile(EditWrapper *wrapper) // wrapper->textEditor()->loadHighlighter(); } else { - qWarning() << "Failed to get wrapper for current path"; + qCWarning(appLog) << "Failed to get wrapper for current path"; return false; } - qDebug() << "Exit saveAsOtherTabFile, returning true"; + qCDebug(appLog) << "Exit saveAsOtherTabFile, returning true"; return true; } @@ -1788,19 +1789,19 @@ void Window::changeSettingDialogComboxFontNumber(int fontNumber) */ qreal Window::calcFontScale(qreal fontSize) { - qDebug() << "Calculating font scale for font size:" << fontSize; + qCDebug(appLog) << "Calculating font scale for font size:" << fontSize; if (qFuzzyCompare(fontSize, m_settings->m_iDefaultFontSize)) { - qDebug() << "Font size is equal to default font size, returning 100% scale"; + qCDebug(appLog) << "Font size is equal to default font size, returning 100% scale"; return 100.0; } else if (fontSize > m_settings->m_iDefaultFontSize) { static const qreal delta = (500 - 100) * 1.0 / (m_settings->m_iMaxFontSize - m_settings->m_iDefaultFontSize); qreal fontScale = 100 + delta * (fontSize - m_settings->m_iDefaultFontSize); - qDebug() << "Font size is greater than default, calculated font scale:" << fontScale; + qCDebug(appLog) << "Font size is greater than default, calculated font scale:" << fontScale; return qMin(fontScale, 500.0); } else { static const qreal delta = (100 - 10) * 1.0 / (m_settings->m_iDefaultFontSize - m_settings->m_iMinFontSize); qreal fontScale = 100 + delta * (fontSize - m_settings->m_iDefaultFontSize); - qDebug() << "Font size is less than default, calculated font scale:" << fontScale; + qCDebug(appLog) << "Font size is less than default, calculated font scale:" << fontScale; return qMax(fontScale, 10.0); } } @@ -1812,26 +1813,26 @@ qreal Window::calcFontScale(qreal fontSize) */ qreal Window::calcFontSizeFromScale(qreal fontScale) { - qDebug() << "Calculating font size from scale:" << fontScale; + qCDebug(appLog) << "Calculating font size from scale:" << fontScale; if (qFuzzyCompare(fontScale, 100.0)) { - qDebug() << "Font scale is equal to 100%, returning default font size"; + qCDebug(appLog) << "Font scale is equal to 100%, returning default font size"; return m_settings->m_iDefaultFontSize; } else if (fontScale > 100.0) { static const qreal delta = (m_settings->m_iMaxFontSize - m_settings->m_iDefaultFontSize) * 1.0 / (500 - 100); qreal fontSize = m_settings->m_iDefaultFontSize + delta * ((fontScale) - 100); - qDebug() << "Font scale is greater than 100%, calculated font size:" << fontSize; + qCDebug(appLog) << "Font scale is greater than 100%, calculated font size:" << fontSize; return qMin(fontSize, m_settings->m_iMaxFontSize); } else { static const qreal delta = (m_settings->m_iDefaultFontSize - m_settings->m_iMinFontSize) * 1.0 / (100 - 10) ; qreal fontSize = m_settings->m_iMinFontSize + delta * (fontScale - 10); - qDebug() << "Font scale is less than 100%, calculated font size:" << fontSize; + qCDebug(appLog) << "Font scale is less than 100%, calculated font size:" << fontSize; return qMax(fontSize, m_settings->m_iMinFontSize); } } void Window::decrementFontSize() { - qDebug() << "Decrementing font size"; + qCDebug(appLog) << "Decrementing font size"; qreal fontScale = calcFontScale(m_fontSize); // 减少10% fontScale -= 10; @@ -1839,12 +1840,12 @@ void Window::decrementFontSize() qreal size = qMax(m_fontSize, m_settings->m_iMinFontSize); m_settings->settings->option("base.font.size")->setValue(size); - qDebug() << "New font size:" << m_fontSize; + qCDebug(appLog) << "New font size:" << m_fontSize; } void Window::incrementFontSize() { - qDebug() << "Incrementing font size"; + qCDebug(appLog) << "Incrementing font size"; qreal fontScale = calcFontScale(m_fontSize); // 增加10% fontScale += 10; @@ -1852,29 +1853,29 @@ void Window::incrementFontSize() qreal size = qMin(m_fontSize, m_settings->m_iMaxFontSize); m_settings->settings->option("base.font.size")->setValue(size); - qDebug() << "New font size:" << m_fontSize; + qCDebug(appLog) << "New font size:" << m_fontSize; } void Window::resetFontSize() { - qDebug() << "Resetting font size to default"; + qCDebug(appLog) << "Resetting font size to default"; m_settings->settings->option("base.font.size")->setValue(m_settings->m_iDefaultFontSize); } void Window::setFontSizeWithConfig(EditWrapper *wrapper) { - qDebug() << "Setting font size with config"; + qCDebug(appLog) << "Setting font size with config"; qreal size = m_settings->settings->option("base.font.size")->value().toReal(); wrapper->textEditor()->setFontSize(size); wrapper->bottomBar()->setScaleLabelText(size); m_fontSize = size; - qDebug() << "Font size set to:" << m_fontSize; + qCDebug(appLog) << "Font size set to:" << m_fontSize; } void Window::popupFindBar() { - qDebug() << "Enter popupFindBar"; + qCDebug(appLog) << "Enter popupFindBar"; #if 0 // This block seems related to UI focus management and might be outdated or incorrect. // The original code directly calls textEditor()->setFocus() without checking if the wrapper or textEditor is null. @@ -1886,7 +1887,7 @@ void Window::popupFindBar() if (wrapper && wrapper->textEditor()) { wrapper->textEditor()->setFocus(); } else { - qWarning() << "Failed to get wrapper or text editor to set focus in popupFindBar"; + qCWarning(appLog) << "Failed to get wrapper or text editor to set focus in popupFindBar"; } } else { m_findBar->focus(); @@ -1901,19 +1902,19 @@ void Window::popupFindBar() EditWrapper *wrapper = currentWrapper(); if (currentWrapper() == nullptr) { - qDebug() << "No current wrapper, cannot popup find bar"; + qCDebug(appLog) << "No current wrapper, cannot popup find bar"; return; } if (wrapper->textEditor()->document()->isEmpty()) { - qDebug() << "Current document is empty, cannot popup find bar"; + qCDebug(appLog) << "Current document is empty, cannot popup find bar"; return; } currentWrapper()->bottomBar()->updateSize(m_findBar->height() + 8, true); if (m_replaceBar->isVisible()) { - qDebug() << "Hiding replace bar before showing find bar"; + qCDebug(appLog) << "Hiding replace bar before showing find bar"; m_replaceBar->hide(); } m_findBar->raise(); @@ -1933,24 +1934,24 @@ void Window::popupFindBar() m_keywordForSearchAll = m_keywordForSearch = text; QTimer::singleShot(10, this, [ = ] { m_findBar->focus(); }); - qDebug() << "Popup find bar completed"; + qCDebug(appLog) << "Popup find bar completed"; } void Window::popupReplaceBar() { - qDebug() << "Enter popupReplaceBar"; + qCDebug(appLog) << "Enter popupReplaceBar"; if (currentWrapper() == nullptr) { - qDebug() << "No current wrapper, cannot popup replace bar"; + qCDebug(appLog) << "No current wrapper, cannot popup replace bar"; return; } if (currentWrapper()->textEditor()->document()->isEmpty()) { - qDebug() << "Current document is empty, cannot popup replace bar"; + qCDebug(appLog) << "Current document is empty, cannot popup replace bar"; return; } if (currentWrapper() && currentWrapper()->getFileLoading()) { - qDebug() << "File is loading, cannot popup replace bar"; + qCDebug(appLog) << "File is loading, cannot popup replace bar"; return; } @@ -1962,12 +1963,12 @@ void Window::popupReplaceBar() if (cursor.hasSelection()) { currentWrapper()->textEditor()->setCursorStart(cursor.selectionStart()); - qDebug() << "Replace bar: selected"; + qCDebug(appLog) << "Replace bar: selected"; } if (bIsReadOnly) { showNotify(tr("Read-Only mode is on")); - qDebug() << "Replace bar: Read-Only mode is on, cannot popup replace bar"; + qCDebug(appLog) << "Replace bar: Read-Only mode is on, cannot popup replace bar"; return; } @@ -1976,7 +1977,7 @@ void Window::popupReplaceBar() EditWrapper *wrapper = currentWrapper(); if (m_findBar->isVisible()) { m_findBar->hide(); - qDebug() << "Hiding find bar before showing replace bar"; + qCDebug(appLog) << "Hiding find bar before showing replace bar"; } m_replaceBar->raise(); m_replaceBar->show(); @@ -1993,37 +1994,37 @@ void Window::popupReplaceBar() m_replaceBar->activeInput(text, tabPath, row, column, scrollOffset); QTimer::singleShot(10, this, [ = ] { m_replaceBar->focus(); }); - qDebug() << "Popup replace bar completed"; + qCDebug(appLog) << "Popup replace bar completed"; } void Window::popupJumpLineBar() { - qDebug() << "Enter popupJumpLineBar"; + qCDebug(appLog) << "Enter popupJumpLineBar"; EditWrapper *curWrapper = currentWrapper(); if (curWrapper == nullptr) { - qDebug() << "No current wrapper, cannot popup jump line bar"; + qCDebug(appLog) << "No current wrapper, cannot popup jump line bar"; return; } if (curWrapper->textEditor()->document()->isEmpty()) { - qDebug() << "Current document is empty, cannot popup jump line bar"; + qCDebug(appLog) << "Current document is empty, cannot popup jump line bar"; return; } if (m_jumpLineBar->isVisible()) { m_jumpLineBar->hide(); - qDebug() << "Hiding jump line bar before showing find bar"; + qCDebug(appLog) << "Hiding jump line bar before showing find bar"; return; } if (m_jumpLineBar->isVisible()) { - qDebug() << "Jump line bar is visible, cannot popup jump line bar"; + qCDebug(appLog) << "Jump line bar is visible, cannot popup jump line bar"; if (m_jumpLineBar->isFocus()) { //QTimer::singleShot(0, m_wrappers.value(m_tabbar->currentPath())->textEditor(), SLOT(setFocus())); - qDebug() << "Jump line bar is focused, set focus to text editor"; + qCDebug(appLog) << "Jump line bar is focused, set focus to text editor"; } else { - qDebug() << "Jump line bar is not focused, focusing it"; + qCDebug(appLog) << "Jump line bar is not focused, focusing it"; m_jumpLineBar->focus(); } } else { @@ -2038,13 +2039,13 @@ void Window::popupJumpLineBar() m_jumpLineBar->activeInput(tabPath, row, column, count, scrollOffset); m_jumpLineBar->show(); m_jumpLineBar->focus(); - qDebug() << "Popup jump line bar completed"; + qCDebug(appLog) << "Popup jump line bar completed"; } } void Window::updateJumpLineBar(TextEdit *editor) { - qDebug() << "Enter updateJumpLineBar"; + qCDebug(appLog) << "Enter updateJumpLineBar"; // 文本块内容未新增行不更新跳转行号 if (m_jumpLineBar->isVisible() && editor->blockCount() != m_jumpLineBar->getLineCount()) { QString tabPath = m_tabbar->currentPath(); @@ -2056,16 +2057,16 @@ void Window::updateJumpLineBar(TextEdit *editor) m_jumpLineBar->activeInput(tabPath, row, column, count, scrollOffset); } if (editor && !editor->ifHasHighlight()) { - qDebug() << "No highlight, updating jump line bar"; + qCDebug(appLog) << "No highlight, updating jump line bar"; m_findBar->setSearched(false); m_replaceBar->setsearched(false); } - qDebug() << "Update jump line bar completed"; + qCDebug(appLog) << "Update jump line bar completed"; } void Window::popupSettingsDialog() { - qDebug() << "Enter popupSettingsDialog"; + qCDebug(appLog) << "Enter popupSettingsDialog"; DSettingsDialog *dialog = new DSettingsDialog(this); dialog->widgetFactory()->registerWidget("fontcombobox", Settings::createFontComBoBoxHandle); dialog->widgetFactory()->registerWidget("keySequenceEdit", Settings::createKeySequenceEditHandle); @@ -2080,7 +2081,7 @@ void Window::popupSettingsDialog() delete dialog; m_settings->settings->sync(); - qDebug() << "Popup settings dialog completed"; + qCDebug(appLog) << "Popup settings dialog completed"; } /** @@ -2088,12 +2089,12 @@ void Window::popupSettingsDialog() */ void Window::clearPrintTextDocument() { - qDebug() << "Clearing print text document"; + qCDebug(appLog) << "Clearing print text document"; if (m_printDoc != nullptr) { - qDebug() << "Print document is not null, clearing it"; + qCDebug(appLog) << "Print document is not null, clearing it"; if (!m_printDoc->isEmpty()) { m_printDoc->clear(); - qDebug() << "Print document cleared"; + qCDebug(appLog) << "Print document cleared"; } m_printDoc = nullptr; } @@ -2103,34 +2104,34 @@ void Window::clearPrintTextDocument() for (auto &info : m_printDocList) { if (info.highlighter) { delete info.highlighter; - qDebug() << "Print document highlighter deleted"; + qCDebug(appLog) << "Print document highlighter deleted"; } if (info.doc) { info.doc->clear(); delete info.doc; - qDebug() << "Print document deleted"; + qCDebug(appLog) << "Print document deleted"; } } m_printDocList.clear(); } - qDebug() << "Print text document cleared"; + qCDebug(appLog) << "Print text document cleared"; } void Window::setWindowTitleInfo() { - qDebug() << "Setting window title info"; + qCDebug(appLog) << "Setting window title info"; if (m_tabbar) { if (m_tabbar->truePathAt(m_tabbar->currentIndex()) != "") { - qDebug() << "Current tab has true path, setting window title to it"; + qCDebug(appLog) << "Current tab has true path, setting window title to it"; setWindowTitle(m_tabbar->truePathAt(m_tabbar->currentIndex())); } else { - qDebug() << "Current tab has no true path, setting window title to tab name"; + qCDebug(appLog) << "Current tab has no true path, setting window title to tab name"; setWindowTitle(m_tabbar->currentName()); } } - qDebug() << "Window title info set"; + qCDebug(appLog) << "Window title info set"; } /** @@ -2139,24 +2140,24 @@ void Window::setWindowTitleInfo() */ QString Window::getCurrentOpenFilePath() { - qDebug() << "Getting current open file path"; + qCDebug(appLog) << "Getting current open file path"; QString path; EditWrapper *wrapper = currentWrapper(); if (wrapper) { - qDebug() << "Current wrapper is not null, getting current file path"; + qCDebug(appLog) << "Current wrapper is not null, getting current file path"; QString curFilePath = wrapper->textEditor() ? wrapper->textEditor()->getTruePath() : wrapper->filePath(); // 临时文件或备份文件,均返回"文档"目录 if (Utils::isDraftFile(curFilePath) || Utils::isBackupFile(curFilePath)) { path = QDir::homePath() + "/Documents"; - qDebug() << "Current file is draft or backup, setting path to home documents"; + qCDebug(appLog) << "Current file is draft or backup, setting path to home documents"; } else { path = QFileInfo(curFilePath).absolutePath(); - qDebug() << "Current file is not draft or backup, setting path to file path"; + qCDebug(appLog) << "Current file is not draft or backup, setting path to file path"; } } - qDebug() << "Current open file path:" << path; + qCDebug(appLog) << "Current open file path:" << path; return path; } @@ -2171,10 +2172,10 @@ QString Window::getCurrentOpenFilePath() */ bool Window::cloneLargeDocument(EditWrapper *editWrapper) { - qDebug() << "Cloning large document"; + qCDebug(appLog) << "Cloning large document"; if (!editWrapper) { - qWarning() << "Invalid edit wrapper, cannot clone document"; + qCWarning(appLog) << "Invalid edit wrapper, cannot clone document"; return false; } @@ -2193,9 +2194,9 @@ bool Window::cloneLargeDocument(EditWrapper *editWrapper) info.highlighter = new CSyntaxHighlighter(info.doc); info.highlighter->setDefinition(editWrapper->getSyntaxHighlighter()->definition()); info.highlighter->setTheme(editWrapper->getSyntaxHighlighter()->theme()); - qDebug() << "Print document highlighter created"; + qCDebug(appLog) << "Print document highlighter created"; } - qDebug() << "Print document created"; + qCDebug(appLog) << "Print document created"; return info; }; @@ -2231,7 +2232,7 @@ bool Window::cloneLargeDocument(EditWrapper *editWrapper) currentCopyCharCount += srcBlock.length(); if (currentCopyCharCount >= s_StepCopyCharCount) { - qDebug() << "Copying " << s_StepCopyCharCount << " characters"; + qCDebug(appLog) << "Copying " << s_StepCopyCharCount << " characters"; // 判断是否超过单个文档允许的最大范围 if ((copyDoc->characterCount() + currentCopyCharCount) > s_MaxDocCharCount || (copyDoc->blockCount() + currentSelectBlock) > s_MaxDocBlockCount) { @@ -2240,7 +2241,7 @@ bool Window::cloneLargeDocument(EditWrapper *editWrapper) copyDoc = m_printDocList.last().doc; // 创建新的插入光标 copyCursor = QTextCursor(copyDoc); - qDebug() << "Creating new print document for large print"; + qCDebug(appLog) << "Creating new print document for large print"; } srcCursor.setPosition(srcOffset); @@ -2255,7 +2256,7 @@ bool Window::cloneLargeDocument(EditWrapper *editWrapper) // 处理其它事件 qApp->processEvents(); if (!checkPtr || !m_bPrintProcessing) { - qWarning() << "Abort print copy!"; + qCWarning(appLog) << "Abort print copy!"; clearPrintTextDocument(); return false; } @@ -2270,14 +2271,14 @@ bool Window::cloneLargeDocument(EditWrapper *editWrapper) m_bPrintProcessing = false; } catch (const std::exception &e) { - qWarning() << "Print copy doc error!" << e.what(); + qCWarning(appLog) << "Print copy doc error!" << e.what(); // 清理数据 m_bPrintProcessing = false; clearPrintTextDocument(); return false; } - qDebug() << "Large document cloned"; + qCDebug(appLog) << "Large document cloned"; return true; } @@ -2286,9 +2287,9 @@ bool Window::cloneLargeDocument(EditWrapper *editWrapper) */ void Window::rehighlightPrintDoc(QTextDocument *doc, CSyntaxHighlighter *highlighter) { - qDebug() << "Rehighlighting print document"; + qCDebug(appLog) << "Rehighlighting print document"; if (!doc || !highlighter) { - qWarning() << "Invalid document or highlighter, cannot rehighlight"; + qCWarning(appLog) << "Invalid document or highlighter, cannot rehighlight"; return; } @@ -2297,7 +2298,7 @@ void Window::rehighlightPrintDoc(QTextDocument *doc, CSyntaxHighlighter *highlig highlighter->setEnableHighlight(true); if (backgroundIsDark) { - qDebug() << "Background is dark, rehighlighting each block"; + qCDebug(appLog) << "Background is dark, rehighlighting each block"; for (QTextBlock block = doc->firstBlock(); block.isValid(); block = block.next()) { highlighter->rehighlightBlock(block); @@ -2313,7 +2314,7 @@ void Window::rehighlightPrintDoc(QTextDocument *doc, CSyntaxHighlighter *highlig color.setHsv(h, s, qMin(128, v), a); brush.setColor(color); format.setForeground(brush); - qDebug() << "Adjusted syntax highlighting color for block"; + qCDebug(appLog) << "Adjusted syntax highlighting color for block"; } format.setBackground(Qt::white); } @@ -2321,11 +2322,11 @@ void Window::rehighlightPrintDoc(QTextDocument *doc, CSyntaxHighlighter *highlig block.layout()->setFormats(formatList); } } else { - qDebug() << "Background is light, rehighlighting all text"; + qCDebug(appLog) << "Background is light, rehighlighting all text"; highlighter->rehighlight(); } highlighter->setEnableHighlight(false); - qDebug() << "Print document rehighlighted"; + qCDebug(appLog) << "Print document rehighlighted"; } /** @@ -2335,59 +2336,59 @@ void Window::rehighlightPrintDoc(QTextDocument *doc, CSyntaxHighlighter *highlig */ void Window::updateSizeMode() { - qDebug() << "Update size mode"; + qCDebug(appLog) << "Update size mode"; EditWrapper *wrapper = currentWrapper(); if (!wrapper) { - qWarning() << "No current wrapper, skip size mode update"; + qCWarning(appLog) << "No current wrapper, skip size mode update"; return; } BottomBar *bottomBar = wrapper->bottomBar(); if (!bottomBar) { - qWarning() << "No bottom bar, skip size mode update"; + qCWarning(appLog) << "No bottom bar, skip size mode update"; return; } if (m_findBar && m_findBar->isVisible()) { - qDebug() << "Find bar is visible, updating its position"; + qCDebug(appLog) << "Find bar is visible, updating its position"; bottomBar->updateSize(m_findBar->height() + 8, true); m_findBar->move(QPoint(4, height() - m_findBar->height() - 4)); } if (m_replaceBar && m_replaceBar->isVisible()) { - qDebug() << "Replace bar is visible, updating its position"; + qCDebug(appLog) << "Replace bar is visible, updating its position"; bottomBar->updateSize(m_replaceBar->height() + 8, true); m_replaceBar->move(QPoint(4, height() - m_replaceBar->height() - 4)); } - qDebug() << "Size mode updated"; + qCDebug(appLog) << "Size mode updated"; } void Window::popupPrintDialog() { - qDebug() << "Enter popupPrintDialog"; + qCDebug(appLog) << "Enter popupPrintDialog"; // 无打开文件时直接返回,避免 currentWrapper() 空指针解引用 if (!currentWrapper()) { - qWarning() << "No open file, cannot print"; + qCWarning(appLog) << "No open file, cannot print"; return; } //大文本加载过程不允许打印操作 if (currentWrapper()->getFileLoading()) { - qDebug() << "File is loading, cannot print"; + qCDebug(appLog) << "File is loading, cannot print"; return; } // 已有处理的打印事件,不继续进入 if (m_bPrintProcessing) { - qDebug() << "Print processing, cannot print"; + qCDebug(appLog) << "Print processing, cannot print"; return; } const QString &filePath = currentWrapper()->textEditor()->getFilePath(); const QString &fileDir = QFileInfo(filePath).dir().absolutePath(); - qInfo() << qPrintable("Start print doc"); + qCInfo(appLog) << qPrintable("Start print doc"); //适配打印接口2.0,dtk版本大于或等于5.4.10才放开最新的2.0打印预览接口 #if (DTK_VERSION_MAJOR > 5 \ @@ -2401,7 +2402,7 @@ void Window::popupPrintDialog() m_multiDocPageCount = 0; if (doc != nullptr && !doc->isEmpty()) { - qDebug() << "Document is not empty, checking if it needs highlighting"; + qCDebug(appLog) << "Document is not empty, checking if it needs highlighting"; static const int s_maxDirectReadLen = 1024 * 1024 * 10; static const int s_maxHighlighterDirectReadLen = 1024 * 1024 * 5; // 判断是否需要文本高亮,文本数据量大小,不同数据量使用不同分支。 @@ -2412,24 +2413,24 @@ void Window::popupPrintDialog() && doc->characterCount() > s_maxHighlighterDirectReadLen) { // 需要高亮且数据量超过 5MB m_bLargePrint = true; - qInfo() << qPrintable("Clone large print document with highlighting"); + qCInfo(appLog) << qPrintable("Clone large print document with highlighting"); } else if (!needHighlighter && doc->characterCount() > s_maxDirectReadLen) { // 无需高亮且数据量超过 10MB m_bLargePrint = true; - qInfo() << qPrintable("Clone large print document without highlighting"); + qCInfo(appLog) << qPrintable("Clone large print document without highlighting"); } else { currentWrapper()->updateHighlighterAll(); m_printDoc = doc->clone(doc); - qInfo() << qPrintable("Clone small print document"); + qCInfo(appLog) << qPrintable("Clone small print document"); } // 大文件处理 if (m_bLargePrint) { - qInfo() << qPrintable("Clone large print document"); + qCInfo(appLog) << qPrintable("Clone large print document"); // 克隆大文本数据 if (!cloneLargeDocument(currentWrapper())) { - qWarning() << "Failed to clone large document for printing!"; + qCWarning(appLog) << "Failed to clone large document for printing!"; return; } } @@ -2437,7 +2438,7 @@ void Window::popupPrintDialog() if ((!m_bLargePrint && nullptr == m_printDoc) || (m_bLargePrint && m_printDocList.isEmpty())) { - qWarning() << "The print document is not valid!"; + qCWarning(appLog) << "The print document is not valid!"; return; } @@ -2451,14 +2452,14 @@ void Window::popupPrintDialog() QRegularExpression reg("[^*](.+)"); QRegularExpressionMatch match = reg.match(name); QString docName = match.captured(0); - qInfo() << __func__ << "print blank file, docName:" << docName; - qInfo() << qPrintable("Print blank file"); + qCInfo(appLog) << __func__ << "print blank file, docName:" << docName; + qCInfo(appLog) << qPrintable("Print blank file"); m_pPreview->setDocName(docName); } else { - qInfo() << qPrintable("Print file: ") << filePath; + qCInfo(appLog) << qPrintable("Print file: ") << filePath; QString path = currentWrapper()->textEditor()->getTruePath(); QString docName = QFileInfo(path).baseName(); - qInfo() << __func__ << "print normal file, docName:" << docName; + qCInfo(appLog) << __func__ << "print normal file, docName:" << docName; m_pPreview->setDocName(docName); } @@ -2478,10 +2479,10 @@ void Window::popupPrintDialog() this, [ = ](DPrinter * _printer, const QVector &pageRange) { if (m_bLargePrint) { this->doPrintWithLargeDoc(_printer, pageRange); - qInfo() << qPrintable("Print large document"); + qCInfo(appLog) << qPrintable("Print large document"); } else { this->doPrint(_printer, pageRange); - qInfo() << qPrintable("Print small document"); + qCInfo(appLog) << qPrintable("Print small document"); } }); @@ -2508,29 +2509,29 @@ void Window::popupPrintDialog() void Window::popupThemePanel() { - qDebug() << "Enter popupThemePanel"; + qCDebug(appLog) << "Enter popupThemePanel"; updateThemePanelGeomerty(); m_themePanel->setSelectionTheme(m_themePath); m_themePanel->popup(); - qDebug() << "Exit popupThemePanel"; + qCDebug(appLog) << "Exit popupThemePanel"; } void Window::toggleFullscreen() { - qDebug() << "Enter toggleFullscreen"; + qCDebug(appLog) << "Enter toggleFullscreen"; if (!window()->windowState().testFlag(Qt::WindowFullScreen)) { - qDebug() << "Enter fullscreen"; + qCDebug(appLog) << "Enter fullscreen"; window()->setWindowState(windowState() | Qt::WindowFullScreen); } else { - qDebug() << "Exit fullscreen"; + qCDebug(appLog) << "Exit fullscreen"; window()->setWindowState(windowState() & ~Qt::WindowFullScreen); } - qDebug() << "Exit toggleFullscreen"; + qCDebug(appLog) << "Exit toggleFullscreen"; } void Window::remberPositionSave() { - qDebug() << "Enter remberPositionSave"; + qCDebug(appLog) << "Enter remberPositionSave"; EditWrapper *wrapper = currentWrapper(); m_remberPositionFilePath = m_tabbar->currentPath(); @@ -2539,14 +2540,14 @@ void Window::remberPositionSave() m_remberPositionScrollOffset = wrapper->textEditor()->getScrollOffset(); currentWrapper()->showNotify(tr("Current location remembered")); - qDebug() << "Exit remberPositionSave"; + qCDebug(appLog) << "Exit remberPositionSave"; } void Window::remberPositionRestore() { - qDebug() << "Enter remberPositionRestore"; + qCDebug(appLog) << "Enter remberPositionRestore"; if (m_remberPositionFilePath.isEmpty()) { - qDebug() << "No remembered position, cannot restore"; + qCDebug(appLog) << "No remembered position, cannot restore"; return; } @@ -2559,18 +2560,18 @@ void Window::remberPositionRestore() activeTab(m_tabbar->indexOf(m_remberPositionFilePath)); EditWrapper* wrapper = m_wrappers.value(filePath); if (!wrapper || !wrapper->textEditor()) { - qWarning() << "Failed to get wrapper or text editor in remberPositionRestore"; + qCWarning(appLog) << "Failed to get wrapper or text editor in remberPositionRestore"; return; } wrapper->textEditor()->scrollToLine(scrollOffset, row, column); } - qDebug() << "Exit remberPositionRestore"; + qCDebug(appLog) << "Exit remberPositionRestore"; } void Window::displayShortcuts() { - qDebug() << "Enter displayShortcuts"; + qCDebug(appLog) << "Enter displayShortcuts"; QRect rect = window()->geometry(); QPoint pos(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2); @@ -2580,10 +2581,10 @@ void Window::displayShortcuts() if (DGuiApplicationHelper::isTabletEnvironment()) { // bug 88079 避免屏幕旋转弹出位置错误 screen = qApp->primaryScreen(); - qDebug() << "Tablet environment, use primary screen"; + qCDebug(appLog) << "Tablet environment, use primary screen"; } else { screen = QGuiApplication::screenAt(QCursor::pos()); - qDebug() << "Use screen at cursor position"; + qCDebug(appLog) << "Use screen at cursor position"; } #else screen = QGuiApplication::screenAt(QCursor::pos()); @@ -2591,7 +2592,7 @@ void Window::displayShortcuts() if (screen) { pos = screen->geometry().center(); - qDebug() << "Screen center position: " << pos; + qCDebug(appLog) << "Screen center position: " << pos; } //窗体快捷键 @@ -2694,7 +2695,7 @@ void Window::displayShortcuts() m_shortcutViewProcess->startDetached("deepin-shortcut-viewer", shortcutString); connect(m_shortcutViewProcess, SIGNAL(finished(int)), m_shortcutViewProcess, SLOT(deleteLater())); - qDebug() << "Exit displayShortcuts"; + qCDebug(appLog) << "Exit displayShortcuts"; } /*! @@ -2706,21 +2707,21 @@ void Window::displayShortcuts() || (DTK_VERSION_MAJOR == 5 && DTK_VERSION_MINOR == 4 && DTK_VERSION_PATCH >= 10)) void Window::doPrint(DPrinter *printer, const QVector &pageRange) { - qDebug() << "Enter doPrint"; + qCDebug(appLog) << "Enter doPrint"; if (nullptr == m_printDoc) { - qDebug() << "Print document is null"; + qCDebug(appLog) << "Print document is null"; return; } //如果打印预览请求的页码为空,则直接返回 if (pageRange.isEmpty()) { - qDebug() << "Page range is empty"; + qCDebug(appLog) << "Page range is empty"; return; } QPainter p(printer); if (!p.isActive()) { - qDebug() << "Painter is not active"; + qCDebug(appLog) << "Painter is not active"; return; } @@ -2728,7 +2729,7 @@ void Window::doPrint(DPrinter *printer, const QVector &pageRange) if (m_lastLayout == printer->pageLayout()) { // 如果打印属性没发生变化,直接加载已生成的资源,提高切换速度 asynPrint(p, printer, pageRange); - qDebug() << "Exit doPrint"; + qCDebug(appLog) << "Exit doPrint"; return; } } @@ -2744,7 +2745,7 @@ void Window::doPrint(DPrinter *printer, const QVector &pageRange) (void)m_printDoc->documentLayout(); // make sure that there is a layout if (currentWrapper() == nullptr) { - qDebug() << "Current wrapper is null"; + qCDebug(appLog) << "Current wrapper is null"; return; } QColor background = currentWrapper()->textEditor()->palette().color(QPalette::Base); @@ -2755,7 +2756,7 @@ void Window::doPrint(DPrinter *printer, const QVector &pageRange) srcBlock = srcBlock.next(), dstBlock = dstBlock.next()) { QVector formatList = srcBlock.layout()->formats(); if (backgroundIsDark) { - qDebug() << "Background is dark"; + qCDebug(appLog) << "Background is dark"; // adjust syntax highlighting colors for better contrast for (int i = formatList.count() - 1; i >= 0; --i) { QTextCharFormat &format = formatList[i].format; @@ -2811,7 +2812,7 @@ void Window::doPrint(DPrinter *printer, const QVector &pageRange) if (i != pageRange.count() - 1) printer->newPage(); } - qDebug() << "Exit doPrint"; + qCDebug(appLog) << "Exit doPrint"; } /** @@ -2821,26 +2822,26 @@ void Window::doPrint(DPrinter *printer, const QVector &pageRange) */ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRange) { - qDebug() << "Enter doPrintWithLargeDoc"; + qCDebug(appLog) << "Enter doPrintWithLargeDoc"; if (m_bPrintProcessing) { - qDebug() << "Print processing"; + qCDebug(appLog) << "Print processing"; return; } if (m_printDocList.isEmpty()) { - qDebug() << "Print doc list is empty"; + qCDebug(appLog) << "Print doc list is empty"; return; } //如果打印预览请求的页码为空,则直接返回 if (pageRange.isEmpty()) { - qDebug() << "Page range is empty"; + qCDebug(appLog) << "Page range is empty"; return; } QPainter p(printer); if (!p.isActive()) { - qDebug() << "Painter is not active"; + qCDebug(appLog) << "Painter is not active"; return; } @@ -2848,7 +2849,7 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang if (m_lastLayout == printer->pageLayout()) { // 如果打印属性没发生变化,直接加载已生成的资源,提高切换速度 asynPrint(p, printer, pageRange); - qDebug() << "Exit doPrintWithLargeDoc"; + qCDebug(appLog) << "Exit doPrintWithLargeDoc"; return; } } @@ -2858,11 +2859,11 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang m_isNewPrint = false; if (currentWrapper() == nullptr) { - qDebug() << "Current wrapper is null"; + qCDebug(appLog) << "Current wrapper is null"; return; } - qInfo() << qPrintable("Calc print large doc!"); + qCInfo(appLog) << qPrintable("Calc print large doc!"); // 执行处理时屏蔽其它输入 DPrintPreviewWidget *prieviewWidget = m_pPreview->findChild(); @@ -2878,7 +2879,7 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang wid->setEnabled(false); widList.append(wid); } else { - qWarning() << "not find widget"; + qCWarning(appLog) << "not find widget"; } } @@ -2928,7 +2929,7 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang qApp->processEvents(QEventLoop::AllEvents | QEventLoop::DialogExec); // 判断当前窗口是否关闭,退出打印状态 if (!checkPtr || !m_bPrintProcessing) { - qWarning() << "Abort print layout!"; + qCWarning(appLog) << "Abort print layout!"; // 手动清理数据 QObject::disconnect(m_pPreview, nullptr, this, nullptr); @@ -2936,7 +2937,7 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang // 异常退出、中断打印时需要关闭窗口 QMetaObject::invokeMethod(m_pPreview, "reject", Qt::QueuedConnection); - qDebug() << "Exit doPrintWithLargeDoc"; + qCDebug(appLog) << "Exit doPrintWithLargeDoc"; return; } } @@ -2946,7 +2947,7 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang } if (prieviewWidget) { - qDebug() << "Print preview widget is valid"; + qCDebug(appLog) << "Print preview widget is valid"; prieviewWidget->refreshEnd(); } @@ -2959,7 +2960,7 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang m_pPreview->setAsynPreview(m_multiDocPageCount); if (!m_printDocList.isEmpty()) { - qDebug() << "Print doc list is not empty"; + qCDebug(appLog) << "Print doc list is not empty"; //渲染第一页文本 for (int i = 0; i < pageRange.count(); ++i) { if (pageRange[i] > m_multiDocPageCount) @@ -2970,7 +2971,7 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang } } - qInfo() << qPrintable("Calc print large doc finised!"); + qCInfo(appLog) << qPrintable("Calc print large doc finised!"); } #endif @@ -2980,10 +2981,10 @@ void Window::doPrintWithLargeDoc(DPrinter *printer, const QVector &pageRang */ void Window::asynPrint(QPainter &p, DPrinter *printer, const QVector &pageRange) { - qDebug() << "Enter asynPrint"; + qCDebug(appLog) << "Enter asynPrint"; if ((!m_bLargePrint && nullptr == m_printDoc) || (m_bLargePrint && m_printDocList.isEmpty())) { - qWarning() << "The print document is not valid!"; + qCWarning(appLog) << "The print document is not valid!"; return; } @@ -3007,7 +3008,7 @@ void Window::asynPrint(QPainter &p, DPrinter *printer, const QVector &pageR if (m_bLargePrint && !m_printDocList.isEmpty()) { - qDebug() << "Large print and print doc list is not empty"; + qCDebug(appLog) << "Large print and print doc list is not empty"; // 大文本打印 for (int i = 0; i < pageRange.count(); ++i) { if (pageRange[i] > m_multiDocPageCount) @@ -3017,7 +3018,7 @@ void Window::asynPrint(QPainter &p, DPrinter *printer, const QVector &pageR printer->newPage(); } } else { - qDebug() << "Small print or print doc list is empty"; + qCDebug(appLog) << "Small print or print doc list is empty"; for (int i = 0; i < pageRange.count(); ++i) { if (pageRange[i] > m_printDoc->pageCount()) continue; @@ -3027,14 +3028,14 @@ void Window::asynPrint(QPainter &p, DPrinter *printer, const QVector &pageR } } - qDebug() << "Exit asynPrint"; + qCDebug(appLog) << "Exit asynPrint"; } void Window::backupFile() { - qInfo() << "begin backupFile()"; + qCInfo(appLog) << "begin backupFile()"; if (!QFileInfo(m_backupDir).exists()) { - qInfo() << "backupDir not exist, create it"; + qCInfo(appLog) << "backupDir not exist, create it"; QDir().mkpath(m_backupDir); } @@ -3052,13 +3053,13 @@ void Window::backupFile() for (EditWrapper *wrapper : wrappers) { if (nullptr == wrapper) { - qWarning() << "wrapper is null, continue"; + qCWarning(appLog) << "wrapper is null, continue"; continue; } if (wrapper->getFileLoading()) continue; if (nullptr == wrapper->textEditor()) { - qWarning() << "textEditor is null, continue"; + qCWarning(appLog) << "textEditor is null, continue"; continue; } @@ -3066,15 +3067,15 @@ void Window::backupFile() localPath = wrapper->textEditor()->getTruePath(); if (localPath.isEmpty()) { - qWarning() << "localPath is empty, use filePath instead"; + qCWarning(appLog) << "localPath is empty, use filePath instead"; localPath = filePath; } - qInfo() << "begin backupFile()"; + qCInfo(appLog) << "begin backupFile()"; // 使用当前窗口的 TabBar 索引,避免跨窗口索引错位 int tabIndex = m_tabbar->indexOf(filePath); if (tabIndex < 0) { - qWarning() << "backupFile: tab not found for path:" << filePath << ", skip"; + qCWarning(appLog) << "backupFile: tab not found for path:" << filePath << ", skip"; continue; } curPos = QString::number(wrapper->textEditor()->textCursor().position()); @@ -3093,7 +3094,7 @@ void Window::backupFile() jsonObject.insert("lastModifiedTime", wrapper->getLastModifiedTime().toString(Qt::ISODate)); QList bookmarkList = wrapper->textEditor()->getBookmarkInfo(); if (!bookmarkList.isEmpty()) { - qInfo() << "bookmarkList is not empty"; + qCInfo(appLog) << "bookmarkList is not empty"; QString bookmarkInfo; //记录书签 @@ -3110,20 +3111,20 @@ void Window::backupFile() //记录活动页 if (filePath == m_tabbar->currentPath()) { - qInfo() << "current tab is this file, set focus to true"; + qCInfo(appLog) << "current tab is this file, set focus to true"; jsonObject.insert("focus", true); } //保存备份文件 if (wrapper->isInvalidCharPreview()) { // 预览模式跳过备份,不写 temFilePath,不保存临时文件 - qInfo() << "preview mode, skip backup file"; + qCInfo(appLog) << "preview mode, skip backup file"; } else if (Utils::isDraftFile(filePath)) { - qInfo() << "is draft file, save to draft dir"; + qCInfo(appLog) << "is draft file, save to draft dir"; wrapper->saveTemFile(filePath); } else { if (wrapper->isModified()) { - qInfo() << "is modified, save to backup dir"; + qCInfo(appLog) << "is modified, save to backup dir"; QString name = fileInfo.absolutePath().replace("/", "_"); QString qstrFilePath = m_backupDir + "/" + Utils::getStringMD5Hash(fileInfo.baseName()) + "." + name + "." + fileInfo.suffix(); jsonObject.insert("temFilePath", qstrFilePath); @@ -3131,7 +3132,7 @@ void Window::backupFile() } } - qInfo() << "after call wrapper->saveTemFile()"; + qCInfo(appLog) << "after call wrapper->saveTemFile()"; //使用json串形式保存 document.setObject(jsonObject); @@ -3140,7 +3141,7 @@ void Window::backupFile() if (tabIndex < m_qlistTemFile.size()) { m_qlistTemFile.replace(tabIndex, byteArray); } else { - qWarning() << "backupFile: tabIndex" << tabIndex << "out of range (size" << m_qlistTemFile.size() << "), appending"; + qCWarning(appLog) << "backupFile: tabIndex" << tabIndex << "out of range (size" << m_qlistTemFile.size() << "), appending"; m_qlistTemFile.append(byteArray); } } @@ -3186,16 +3187,16 @@ void Window::backupFile() //删除自动备份文件 if (QFileInfo(m_autoBackupDir).exists()) { - qInfo() << "autoBackupDir exist, remove it"; + qCInfo(appLog) << "autoBackupDir exist, remove it"; QDir(m_autoBackupDir).removeRecursively(); } - qInfo() << "end backupFile()"; + qCInfo(appLog) << "end backupFile()"; } bool Window::closeAllFiles() { - qInfo() << "begin closeAllFiles()"; + qCInfo(appLog) << "begin closeAllFiles()"; // 先关闭所有待加载标签页(无需保存提示) QMap pendingCopy = m_pendingTabs; @@ -3217,7 +3218,7 @@ bool Window::closeAllFiles() m_tabbar->setCurrentIndex(i - closedTabCount); if (!closeTab()) { - qDebug() << "closeTab() failed, return false"; + qCDebug(appLog) << "closeTab() failed, return false"; // 取消操作时,停留在当前标签页 return false; } else { @@ -3225,13 +3226,13 @@ bool Window::closeAllFiles() ++closedTabCount; } } - qInfo() << "end closeAllFiles()"; + qCInfo(appLog) << "end closeAllFiles()"; return true; } bool Window::saveAllFloatingFiles() { - qInfo() << "begin saveAllFloatingFiles()"; + qCInfo(appLog) << "begin saveAllFloatingFiles()"; QMap wrappers = m_wrappers; for (int i = wrappers.count() - 1; i >= 0; i--) { const QString &filePath = m_tabbar->truePathAt(i); @@ -3242,7 +3243,7 @@ bool Window::saveAllFloatingFiles() QFileInfo finfo(filePath); if (!finfo.exists()) { - qWarning() << "File not exist:" << filePath; + qCWarning(appLog) << "File not exist:" << filePath; m_tabbar->setCurrentIndex(i); DDialog *dialog = createDialog(tr("Do you want to save this file?"), ""); int res = dialog->exec(); @@ -3263,7 +3264,7 @@ bool Window::saveAllFloatingFiles() } } } - qInfo() << "end saveAllFloatingFiles()"; + qCInfo(appLog) << "end saveAllFloatingFiles()"; return true; } @@ -3278,17 +3279,17 @@ bool Window::saveAllFloatingFiles() void Window::addTemFileTab(const QString &qstrPath, const QString &qstrName, const QString &qstrTruePath, const QString &lastModifiedTime, bool bIsTemFile, int index, int restoreCursorPosition) { - qInfo() << "begin addTemFileTab()"; + qCInfo(appLog) << "begin addTemFileTab()"; if (qstrPath.isEmpty() || !Utils::fileExists(qstrPath)) { - qWarning() << "qstrPath is empty or file not exists"; + qCWarning(appLog) << "qstrPath is empty or file not exists"; return; } // 若为MIMETYPE不支持的文件,给出无效文件提示 修复bug 132653 if (!Utils::isMimeTypeSupport(qstrPath)) { - qDebug() << "file is not support, show invalid file tip"; + qCDebug(appLog) << "file is not support, show invalid file tip"; if (currentWrapper() == nullptr) { - qDebug() << "current wrapper is null, create a new one"; + qCDebug(appLog) << "current wrapper is null, create a new one"; this->addBlankTab(); } @@ -3297,7 +3298,7 @@ void Window::addTemFileTab(const QString &qstrPath, const QString &qstrName, con strFileName = Utils::lineFeed(strFileName, m_editorWidget->currentWidget()->width() - FLOATTIP_MARGIN, m_editorWidget->currentWidget()->font(), 2); DMessageManager::instance()->sendMessage(m_editorWidget->currentWidget(), QIcon(":/images/warning.svg"), strFileName); - qDebug() << "return from addTemFileTab()"; + qCDebug(appLog) << "return from addTemFileTab()"; return; } @@ -3318,16 +3319,16 @@ void Window::addTemFileTab(const QString &qstrPath, const QString &qstrName, con //set m_tModifiedDateTime in wrapper again. if (bIsTemFile && !lastModifiedTime.isEmpty()) { wrapper->setLastModifiedTime(lastModifiedTime); - qDebug() << "set last modified time in wrapper"; + qCDebug(appLog) << "set last modified time in wrapper"; } m_wrappers[qstrPath] = wrapper; showNewEditor(wrapper); - qInfo() << "end addTemFileTab()"; + qCInfo(appLog) << "end addTemFileTab()"; } void Window::addPendingTab(const PendingTabInfo &info, int index) { - qInfo() << "addPendingTab:" << info.filepath << info.displayName; + qCInfo(appLog) << "addPendingTab:" << info.filepath << info.displayName; // 阻止信号:addTab 内部会调用 setCurrentIndex 触发 currentChanged, // 导致 handleCurrentChanged 立即加载 pending 标签页,懒加载失效 m_tabbar->blockSignals(true); @@ -3356,10 +3357,10 @@ bool Window::loadPendingTab(const QString &filepath) } PendingTabInfo info = m_pendingTabs.take(filepath); - qInfo() << "loadPendingTab: loading" << info.filepath; + qCInfo(appLog) << "loadPendingTab: loading" << info.filepath; if (!Utils::fileExists(info.filepath)) { - qWarning() << "loadPendingTab: file does not exist" << info.filepath; + qCWarning(appLog) << "loadPendingTab: file does not exist" << info.filepath; m_pendingTabs.insert(info.filepath, info); return false; } @@ -3376,7 +3377,7 @@ bool Window::loadPendingTab(const QString &filepath) // 检查文件是否成功加载(addTemFileTab 可能因 MimeType 不支持等原因 early return) EditWrapper *wrapper = m_wrappers.value(info.filepath); if (!wrapper) { - qWarning() << "loadPendingTab: addTemFileTab failed, restoring pending info"; + qCWarning(appLog) << "loadPendingTab: addTemFileTab failed, restoring pending info"; // 恢复 pending 信息和占位标签 m_pendingTabs.insert(info.filepath, info); addPendingTab(info, existingIndex); @@ -3398,7 +3399,7 @@ QMap Window::getWrappers() void Window::setChildrenFocus(bool ok) { - qDebug() << "setChildrenFocus" << ok; + qCDebug(appLog) << "setChildrenFocus" << ok; if (ok) { DIconButton *addButton = m_tabbar->findChild("AddButton"); DIconButton *optionBtn = titlebar()->findChild("DTitlebarDWindowOptionButton"); @@ -3436,7 +3437,7 @@ void Window::setChildrenFocus(bool ok) if (maxBtn) maxBtn->setFocusPolicy(Qt::NoFocus); if (closeBtn) closeBtn->setFocusPolicy(Qt::NoFocus); } - qDebug() << "setChildrenFocus end"; + qCDebug(appLog) << "setChildrenFocus end"; } void Window::addBlankTab() @@ -3446,11 +3447,11 @@ void Window::addBlankTab() void Window::addBlankTab(const QString &blankFile) { - qInfo() << "begin addBlankTab()"; + qCInfo(appLog) << "begin addBlankTab()"; QString blankTabPath; if (blankFile.isEmpty()) { - qInfo() << "blankFile is empty, create a new blank file"; + qCInfo(appLog) << "blankFile is empty, create a new blank file"; const QString &fileName = QString("blank_file_%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss-zzz")); blankTabPath = QDir(m_blankFileDir).filePath(fileName); @@ -3458,7 +3459,7 @@ void Window::addBlankTab(const QString &blankFile) QDir().mkpath(m_blankFileDir); } } else { - qInfo() << "blankFile is not empty, use it"; + qCInfo(appLog) << "blankFile is not empty, use it"; blankTabPath = blankFile; } @@ -3468,13 +3469,13 @@ void Window::addBlankTab(const QString &blankFile) wrapper->updatePath(blankTabPath); if (!blankFile.isEmpty() && Utils::fileExists(blankFile)) { - qInfo() << "blankFile exists, copy it to blankTabPath"; + qCInfo(appLog) << "blankFile exists, copy it to blankTabPath"; wrapper->openFile(blankTabPath, blankTabPath); } m_wrappers[blankTabPath] = wrapper; showNewEditor(wrapper); - qInfo() << "end addBlankTab()"; + qCInfo(appLog) << "end addBlankTab()"; } /** @@ -3486,10 +3487,10 @@ void Window::addBlankTab(const QString &blankFile) */ void Window::handleTabCloseRequested(int index) { - qDebug() << "handleTabCloseRequested" << index; + qCDebug(appLog) << "handleTabCloseRequested" << index; // 延迟执行关闭标签页 if (!m_delayCloseTabTimer.isActive()) { - qDebug() << "m_delayCloseTabTimer is not active"; + qCDebug(appLog) << "m_delayCloseTabTimer is not active"; // 记录关闭标签索引 m_requestCloseTabIndex = index; @@ -3497,14 +3498,14 @@ void Window::handleTabCloseRequested(int index) static const int s_nDelayTime = 10; m_delayCloseTabTimer.start(s_nDelayTime, this); } - qDebug() << "handleTabCloseRequested end"; + qCDebug(appLog) << "handleTabCloseRequested end"; } void Window::handleTabsClosed(QStringList tabList) { - qDebug() << "handleTabsClosed, size=" << tabList.size(); + qCDebug(appLog) << "handleTabsClosed, size=" << tabList.size(); if (tabList.isEmpty()) { - qDebug() << "tabList is empty, return"; + qCDebug(appLog) << "tabList is empty, return"; return; } @@ -3513,27 +3514,27 @@ void Window::handleTabsClosed(QStringList tabList) m_tabbar->setCurrentIndex(index); closeTab(); } - qDebug() << "handleTabsClosed end"; + qCDebug(appLog) << "handleTabsClosed end"; } void Window::handleCurrentChanged(const int &index) { - qDebug() << "handleCurrentChanged" << index; + qCDebug(appLog) << "handleCurrentChanged" << index; if (m_findBar->isVisible()) { - qDebug() << "m_findBar is visible"; + qCDebug(appLog) << "m_findBar is visible"; m_findBar->hide(); } if (m_replaceBar->isVisible()) { - qDebug() << "m_replaceBar is visible"; + qCDebug(appLog) << "m_replaceBar is visible"; m_replaceBar->hide(); } m_findBar->slotUpdateMatchCount(0, 0); m_replaceBar->slotUpdateMatchCount(0, 0); if (m_jumpLineBar->isVisible()) { - qDebug() << "m_jumpLineBar is visible"; + qCDebug(appLog) << "m_jumpLineBar is visible"; m_jumpLineBar->hide(); } @@ -3542,7 +3543,7 @@ void Window::handleCurrentChanged(const int &index) } if (currentWrapper()) { - qDebug() << "current wrapper is not null"; + qCDebug(appLog) << "current wrapper is not null"; currentWrapper()->checkForReload(); checkTabbarForReload(); } @@ -3554,7 +3555,7 @@ void Window::handleCurrentChanged(const int &index) if (!m_bBatchAddingPendingTabs && isPendingTab(filepath)) { if (!loadPendingTab(filepath)) { // 文件不存在或加载失败,移除该标签页 - qWarning() << "Failed to load pending tab:" << filepath; + qCWarning(appLog) << "Failed to load pending tab:" << filepath; handleTabCloseRequested(index); return; } @@ -3564,7 +3565,7 @@ void Window::handleCurrentChanged(const int &index) bool bIsContains = false; EditWrapper *wrapper = m_wrappers.value(filepath); if (!wrapper || !wrapper->textEditor()) { - qWarning() << "Failed to get wrapper or text editor in handleCurrentChanged"; + qCWarning(appLog) << "Failed to get wrapper or text editor in handleCurrentChanged"; // Attempt to remove potentially problematic widget if wrapper is null but was in m_wrappers if (!wrapper && m_editorWidget) { // Find widget by path if possible, or handle error @@ -3574,13 +3575,13 @@ void Window::handleCurrentChanged(const int &index) wrapper->textEditor()->setFocus(); for (int i = 0; i < m_editorWidget->count(); i++) { if (m_editorWidget->widget(i) == wrapper) { - qDebug() << "wrapper is already in m_editorWidget"; + qCDebug(appLog) << "wrapper is already in m_editorWidget"; bIsContains = true; } } if (!bIsContains) { - qDebug() << "wrapper is not in m_editorWidget, add it"; + qCDebug(appLog) << "wrapper is not in m_editorWidget, add it"; m_editorWidget->addWidget(wrapper); } @@ -3588,78 +3589,78 @@ void Window::handleCurrentChanged(const int &index) } if (currentWrapper() != nullptr) { - qDebug() << "current wrapper is not null, show bottom bar"; + qCDebug(appLog) << "current wrapper is not null, show bottom bar"; currentWrapper()->bottomBar()->show(); currentWrapper()->bottomBar()->updateSize(BottomBar::defaultHeight(), false); } - qDebug() << "handleCurrentChanged end"; + qCDebug(appLog) << "handleCurrentChanged end"; } void Window::handleJumpLineBarExit() { - qDebug() << "handleJumpLineBarExit"; + qCDebug(appLog) << "handleJumpLineBarExit"; if (currentWrapper() != nullptr) { - qDebug() << "current wrapper is not null"; + qCDebug(appLog) << "current wrapper is not null"; QTimer::singleShot(0, currentWrapper()->textEditor(), SLOT(setFocus())); } - qDebug() << "handleJumpLineBarExit end"; + qCDebug(appLog) << "handleJumpLineBarExit end"; } void Window::handleJumpLineBarJumpToLine(const QString &filepath, int line, bool focusEditor) { - qDebug() << "handleJumpLineBarJumpToLine" << filepath << line << focusEditor; + qCDebug(appLog) << "handleJumpLineBarJumpToLine" << filepath << line << focusEditor; if (m_wrappers.contains(filepath)) { getTextEditor(filepath)->jumpToLine(line, true); if (focusEditor) { - qDebug() << "focus editor"; + qCDebug(appLog) << "focus editor"; QTimer::singleShot(0, getTextEditor(filepath), SLOT(setFocus())); } } - qDebug() << "handleJumpLineBarJumpToLine end"; + qCDebug(appLog) << "handleJumpLineBarJumpToLine end"; } void Window::handleBackToPosition(const QString &file, int row, int column, int scrollOffset) { - qDebug() << "handleBackToPosition" << file << row << column << scrollOffset; + qCDebug(appLog) << "handleBackToPosition" << file << row << column << scrollOffset; if (m_wrappers.contains(file)) { EditWrapper* wrapper = m_wrappers.value(file); if (!wrapper || !wrapper->textEditor()) { - qWarning() << "Failed to get wrapper or text editor in handleBackToPosition"; + qCWarning(appLog) << "Failed to get wrapper or text editor in handleBackToPosition"; return; } wrapper->textEditor()->scrollToLine(scrollOffset, row, column); } - qDebug() << "handleBackToPosition end"; + qCDebug(appLog) << "handleBackToPosition end"; } void Window::handleFindNextSearchKeyword(const QString &keyword) { - qDebug() << "handleFindNextSearchKeyword" << keyword; + qCDebug(appLog) << "handleFindNextSearchKeyword" << keyword; handleFindKeyword(keyword, true); - qDebug() << "handleFindNextSearchKeyword end"; + qCDebug(appLog) << "handleFindNextSearchKeyword end"; } void Window::handleFindPrevSearchKeyword(const QString &keyword) { - qDebug() << "handleFindPrevSearchKeyword" << keyword; + qCDebug(appLog) << "handleFindPrevSearchKeyword" << keyword; handleFindKeyword(keyword, false); - qDebug() << "handleFindPrevSearchKeyword end"; + qCDebug(appLog) << "handleFindPrevSearchKeyword end"; } void Window::handleFindKeyword(const QString &keyword, bool state) { - qDebug() << "handleFindKeyword" << keyword << state; + qCDebug(appLog) << "handleFindKeyword" << keyword << state; EditWrapper *wrapper = currentWrapper(); m_keywordForSearch = keyword; wrapper->textEditor()->saveMarkStatus(); wrapper->textEditor()->updateCursorKeywordSelection(m_keywordForSearch, state); if (QString::compare(m_keywordForSearch, m_keywordForSearchAll, Qt::CaseInsensitive) != 0) { - qDebug() << "m_keywordForSearchAll is not equal to m_keywordForSearch, clear it"; + qCDebug(appLog) << "m_keywordForSearchAll is not equal to m_keywordForSearch, clear it"; m_keywordForSearchAll.clear(); wrapper->textEditor()->clearFindMatchSelections(); } else { - qDebug() << "m_keywordForSearchAll is equal to m_keywordForSearch, highlight it"; + qCDebug(appLog) << "m_keywordForSearchAll is equal to m_keywordForSearch, highlight it"; wrapper->textEditor()->highlightKeywordInView(m_keywordForSearchAll); } @@ -3671,26 +3672,26 @@ void Window::handleFindKeyword(const QString &keyword, bool state) // 变更查询字符串位置后(可能滚屏),刷新当前界面的代码高亮效果 wrapper->OnUpdateHighlighter(); - qDebug() << "handleFindKeyword end"; + qCDebug(appLog) << "handleFindKeyword end"; } void Window::slotFindbarClose() { - qDebug() << "slotFindbarClose"; + qCDebug(appLog) << "slotFindbarClose"; EditWrapper *wrapper = currentWrapper(); if (!wrapper) { - qWarning() << "No current wrapper, ignore find bar close"; + qCWarning(appLog) << "No current wrapper, ignore find bar close"; return; } BottomBar *bottomBar = wrapper->bottomBar(); if (!bottomBar) { - qWarning() << "No bottom bar, ignore find bar close"; + qCWarning(appLog) << "No bottom bar, ignore find bar close"; return; } if (bottomBar->isHidden()) { - qDebug() << "bottom bar is hidden, show it"; + qCDebug(appLog) << "bottom bar is hidden, show it"; bottomBar->show(); } @@ -3699,28 +3700,28 @@ void Window::slotFindbarClose() textEditor->setFocus(); textEditor->tellFindBarClose(); } else { - qWarning() << "No text editor, ignore find bar close focus update"; + qCWarning(appLog) << "No text editor, ignore find bar close focus update"; } - qDebug() << "slotFindbarClose end"; + qCDebug(appLog) << "slotFindbarClose end"; } void Window::slotReplacebarClose() { - qDebug() << "slotReplacebarClose"; + qCDebug(appLog) << "slotReplacebarClose"; EditWrapper *wrapper = currentWrapper(); if (!wrapper) { - qWarning() << "No current wrapper, ignore replace bar close"; + qCWarning(appLog) << "No current wrapper, ignore replace bar close"; return; } BottomBar *bottomBar = wrapper->bottomBar(); if (!bottomBar) { - qWarning() << "No bottom bar, ignore replace bar close"; + qCWarning(appLog) << "No bottom bar, ignore replace bar close"; return; } if (bottomBar->isHidden()) { - qDebug() << "bottom bar is hidden, show it"; + qCDebug(appLog) << "bottom bar is hidden, show it"; bottomBar->show(); } @@ -3729,20 +3730,20 @@ void Window::slotReplacebarClose() textEditor->setFocus(); textEditor->tellFindBarClose(); } else { - qWarning() << "No text editor, ignore replace bar close focus update"; + qCWarning(appLog) << "No text editor, ignore replace bar close focus update"; } - qDebug() << "slotReplacebarClose end"; + qCDebug(appLog) << "slotReplacebarClose end"; } void Window::slotSwitchToReplaceBar() { - qDebug() << "slotSwitchToReplaceBar - switching from find bar to replace bar"; + qCDebug(appLog) << "slotSwitchToReplaceBar - switching from find bar to replace bar"; // 只读模式下禁止切换到替换栏(BUG 378209) EditWrapper *curWrapper = currentWrapper(); if (curWrapper && curWrapper->textEditor() && curWrapper->textEditor()->getReadOnlyMode()) { showNotify(tr("Read-Only mode is on")); - qDebug() << "slotSwitchToReplaceBar: Read-Only mode is on, cannot switch to replace bar"; + qCDebug(appLog) << "slotSwitchToReplaceBar: Read-Only mode is on, cannot switch to replace bar"; return; } @@ -3753,7 +3754,7 @@ void Window::slotSwitchToReplaceBar() if (m_findBar && m_findBar->isVisible()) { searchText = m_findBar->getCurrentSearchText(); - qDebug() << "Got search text from find bar:" << searchText; + qCDebug(appLog) << "Got search text from find bar:" << searchText; // 获取当前编辑器的位置信息 EditWrapper *wrapper = currentWrapper(); @@ -3763,16 +3764,16 @@ void Window::slotSwitchToReplaceBar() row = cursor.blockNumber(); column = cursor.columnNumber(); scrollOffset = wrapper->textEditor()->verticalScrollBar()->value(); - qDebug() << "Current position - file:" << currentFile << "row:" << row << "column:" << column; + qCDebug(appLog) << "Current position - file:" << currentFile << "row:" << row << "column:" << column; if (!searchText.isEmpty()) { // 检查当前光标是否有选中文本,且选中文本与搜索文本匹配 QTextCursor currentCursor = wrapper->textEditor()->textCursor(); if (currentCursor.hasSelection() && currentCursor.selectedText() == searchText) { - qDebug() << "Current selection matches search text, using it as search pointer"; + qCDebug(appLog) << "Current selection matches search text, using it as search pointer"; // 直接将当前选中文本设置为搜索指针 wrapper->textEditor()->setFindHighlightSelection(currentCursor); } else { - qDebug() << "No matching selection, setting search pointer from current position"; + qCDebug(appLog) << "No matching selection, setting search pointer from current position"; // 没有匹配的选中文本,从当前位置搜索 wrapper->textEditor()->updateCursorKeywordSelection(searchText, true); } @@ -3781,92 +3782,92 @@ void Window::slotSwitchToReplaceBar() // 隐藏查找栏 m_findBar->hide(); - qDebug() << "Find bar hidden"; + qCDebug(appLog) << "Find bar hidden"; } // 弹出替换栏并传递搜索文本 if (currentWrapper() == nullptr) { - qDebug() << "No current wrapper, cannot popup replace bar"; + qCDebug(appLog) << "No current wrapper, cannot popup replace bar"; return; } if (currentWrapper()->textEditor()->document()->isEmpty()) { - qDebug() << "Current document is empty, cannot popup replace bar"; + qCDebug(appLog) << "Current document is empty, cannot popup replace bar"; return; } // 激活替换栏并传递搜索文本 m_replaceBar->activeInput(searchText, currentFile, row, column, scrollOffset); - qDebug() << "Replace bar activated with search text:" << searchText; + qCDebug(appLog) << "Replace bar activated with search text:" << searchText; } void Window::handleReplaceAll(const QString &replaceText, const QString &withText) { - qDebug() << "handleReplaceAll" << replaceText << withText; + qCDebug(appLog) << "handleReplaceAll" << replaceText << withText; EditWrapper *wrapper = currentWrapper(); wrapper->textEditor()->replaceAll(replaceText, withText); - qDebug() << "handleReplaceAll end"; + qCDebug(appLog) << "handleReplaceAll end"; } void Window::handleReplaceNext(const QString &file, const QString &replaceText, const QString &withText) { - qDebug() << "handleReplaceNext" << file << replaceText << withText; + qCDebug(appLog) << "handleReplaceNext" << file << replaceText << withText; Q_UNUSED(file); m_keywordForSearch = replaceText; m_keywordForSearchAll = replaceText; EditWrapper *wrapper = currentWrapper(); wrapper->textEditor()->replaceNext(replaceText, withText); - qDebug() << "handleReplaceNext end"; + qCDebug(appLog) << "handleReplaceNext end"; } void Window::handleReplaceRest(const QString &replaceText, const QString &withText) { - qDebug() << "handleReplaceRest" << replaceText << withText; + qCDebug(appLog) << "handleReplaceRest" << replaceText << withText; EditWrapper *wrapper = currentWrapper(); wrapper->textEditor()->replaceRest(replaceText, withText); - qDebug() << "handleReplaceRest end"; + qCDebug(appLog) << "handleReplaceRest end"; } void Window::handleReplaceSkip(QString file, QString keyword) { - qDebug() << "handleReplaceSkip" << file << keyword; + qCDebug(appLog) << "handleReplaceSkip" << file << keyword; EditWrapper *wrapper = currentWrapper(); handleUpdateSearchKeyword(m_replaceBar, file, keyword, Qt::CaseSensitive); if (QString::compare(m_keywordForSearch, m_keywordForSearchAll, Qt::CaseInsensitive) != 0) { m_keywordForSearchAll.clear(); wrapper->textEditor()->clearFindMatchSelections(); - qDebug() << "m_keywordForSearchAll is not equal to m_keywordForSearch, clear it"; + qCDebug(appLog) << "m_keywordForSearchAll is not equal to m_keywordForSearch, clear it"; } else { wrapper->textEditor()->highlightKeywordInView(m_keywordForSearchAll, Qt::CaseSensitive); - qDebug() << "m_keywordForSearchAll is equal to m_keywordForSearch, highlight it"; + qCDebug(appLog) << "m_keywordForSearchAll is equal to m_keywordForSearch, highlight it"; } #if 0 EditWrapper *wrapper = currentWrapper(); wrapper->textEditor()->updateCursorKeywordSelection(m_keywordForSearchAll, true); wrapper->textEditor()->renderAllSelections(); #endif - qDebug() << "handleReplaceSkip end"; + qCDebug(appLog) << "handleReplaceSkip end"; } void Window::handleRemoveSearchKeyword() { - qDebug() << "handleRemoveSearchKeyword"; + qCDebug(appLog) << "handleRemoveSearchKeyword"; if (currentWrapper() != nullptr) { - qDebug() << "remove keywords"; + qCDebug(appLog) << "remove keywords"; currentWrapper()->textEditor()->removeKeywords(); } - qDebug() << "handleRemoveSearchKeyword end"; + qCDebug(appLog) << "handleRemoveSearchKeyword end"; } void Window::handleUpdateSearchKeyword(QWidget *widget, const QString &file, const QString &keyword, Qt::CaseSensitivity caseFlag) { - qDebug() << "handleUpdateSearchKeyword" << file << keyword << caseFlag; + qCDebug(appLog) << "handleUpdateSearchKeyword" << file << keyword << caseFlag; if (file == m_tabbar->currentPath() && m_wrappers.contains(file)) { - qDebug() << "update search keyword"; + qCDebug(appLog) << "update search keyword"; EditWrapper* wrapper = m_wrappers.value(file); if (!wrapper || !wrapper->textEditor()) { - qWarning() << "Failed to get wrapper or text editor in handleUpdateSearchKeyword"; + qCWarning(appLog) << "Failed to get wrapper or text editor in handleUpdateSearchKeyword"; return; } @@ -3878,24 +3879,24 @@ void Window::handleUpdateSearchKeyword(QWidget *widget, const QString &file, con auto *findBarWidget = qobject_cast(widget); if (findBarWidget != nullptr) { - qDebug() << "find bar widget is not null"; + qCDebug(appLog) << "find bar widget is not null"; if (emptyKeyword) { findBarWidget->setMismatchAlert(false); - qDebug() << "empty keyword, set mismatch alert false"; + qCDebug(appLog) << "empty keyword, set mismatch alert false"; } else { findBarWidget->setMismatchAlert(!findKeyword); - qDebug() << "not empty keyword, set mismatch alert " << !findKeyword; + qCDebug(appLog) << "not empty keyword, set mismatch alert " << !findKeyword; } } else { - qDebug() << "find bar widget is null"; + qCDebug(appLog) << "find bar widget is null"; auto *replaceBarWidget = qobject_cast(widget); if (replaceBarWidget != nullptr) { if (emptyKeyword) { replaceBarWidget->setMismatchAlert(false); - qDebug() << "empty keyword, set mismatch alert false"; + qCDebug(appLog) << "empty keyword, set mismatch alert false"; } else { replaceBarWidget->setMismatchAlert(!findKeyword); - qDebug() << "not empty keyword, set mismatch alert " << !findKeyword; + qCDebug(appLog) << "not empty keyword, set mismatch alert " << !findKeyword; } } } @@ -3904,16 +3905,16 @@ void Window::handleUpdateSearchKeyword(QWidget *widget, const QString &file, con wrapper->textEditor()->updateLeftAreaWidget(); // 在设置查询字符串并跳转后,及时刷新代码高亮效果 wrapper->OnUpdateHighlighter(); - qDebug() << "handleUpdateSearchKeyword end"; + qCDebug(appLog) << "handleUpdateSearchKeyword end"; } void Window::loadTheme(const QString &path) { - qInfo() << "Loading theme:" << path; + qCInfo(appLog) << "Loading theme:" << path; QFileInfo fileInfo(path); if (!fileInfo.exists()) { - qWarning() << "Theme file not exists!" << path; + qCWarning(appLog) << "Theme file not exists!" << path; return; } @@ -3937,33 +3938,33 @@ void Window::loadTheme(const QString &path) const QString &frameNormalColor = jsonMap["app-colors"].toMap()["themebar-frame-normal"].toString(); m_themePanel->setFrameColor(frameSelectedColor, frameNormalColor); m_settings->settings->option("advance.editor.theme")->setValue(path); - qDebug() << "load theme end"; + qCDebug(appLog) << "load theme end"; } void Window::showNewEditor(EditWrapper *wrapper) { - qDebug() << "show new editor"; + qCDebug(appLog) << "show new editor"; m_editorWidget->addWidget(wrapper); m_editorWidget->setCurrentWidget(wrapper); - qDebug() << "show new editor end"; + qCDebug(appLog) << "show new editor end"; } void Window::showNotify(const QString &message, bool warning) { - qDebug() << "show notify" << message << warning; + qCDebug(appLog) << "show notify" << message << warning; //DMainWindow::sendMessage(QIcon(":/images/ok.svg"), message); //如果是第一次打开编辑器,需要创建一个空白编辑显示框窗体 if (currentWrapper() == nullptr) { - qDebug() << "current wrapper is null"; + qCDebug(appLog) << "current wrapper is null"; this->addBlankTab(); } currentWrapper()->showNotify(message, warning); - qDebug() << "show notify end"; + qCDebug(appLog) << "show notify end"; } int Window::getBlankFileIndex() { - qDebug() << "get blank file index"; + qCDebug(appLog) << "get blank file index"; // get blank tab index list. QList tabIndexes; @@ -3986,7 +3987,7 @@ int Window::getBlankFileIndex() // Return 1 if no blank file exists. if (tabIndexes.size() == 0) { - qDebug() << "no blank file, return 1"; + qCDebug(appLog) << "no blank file, return 1"; return 1; } @@ -3999,13 +4000,13 @@ int Window::getBlankFileIndex() // Last, return biggest index as blank file index. int lastIndex = tabIndexes.size() + 1; - qDebug() << "last blank file index is " << lastIndex; + qCDebug(appLog) << "last blank file index is " << lastIndex; return lastIndex; } DDialog *Window::createDialog(const QString &title, const QString &content) { - qDebug() << "create dialog"; + qCDebug(appLog) << "create dialog"; DDialog *dialog = new DDialog(title, content, this); //dialog->setWindowFlags(dialog->windowFlags() | Qt::WindowStaysOnBottomHint); dialog->setWindowModality(Qt::ApplicationModal); @@ -4015,21 +4016,21 @@ DDialog *Window::createDialog(const QString &title, const QString &content) dialog->addButton(QString(tr("Discard")), false, DDialog::ButtonNormal); dialog->addButton(QString(tr("Save")), true, DDialog::ButtonRecommend); - qDebug() << "create dialog end"; + qCDebug(appLog) << "create dialog end"; return dialog; } void Window::slotLoadContentTheme(DGuiApplicationHelper::ColorType themeType) { - qDebug() << "slot load content theme"; + qCDebug(appLog) << "slot load content theme"; if (themeType == DGuiApplicationHelper::ColorType::LightType) { - qDebug() << "load light theme"; + qCDebug(appLog) << "load light theme"; loadTheme(DEEPIN_THEME); if (DGuiApplicationHelper::instance()->paletteType() == DGuiApplicationHelper::ColorType::UnknownType) { DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::ColorType::UnknownType); } } else if (themeType == DGuiApplicationHelper::ColorType::DarkType) { - qDebug() << "load dark theme"; + qCDebug(appLog) << "load dark theme"; loadTheme(DEEPIN_DARK_THEME); if (DGuiApplicationHelper::instance()->paletteType() == DGuiApplicationHelper::ColorType::UnknownType) { DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::ColorType::UnknownType); @@ -4047,49 +4048,49 @@ void Window::slotLoadContentTheme(DGuiApplicationHelper::ColorType themeType) QString qstrHighlightColor = palette().color(QPalette::Active, QPalette::HighlightedText).name(); m_tabbar->setTabPalette(qstrColor, qstrHighlightColor); - qDebug() << "slot setting reset theme end"; + qCDebug(appLog) << "slot setting reset theme end"; } void Window::slotSettingResetTheme(const QString &path) { - qDebug() << "slot setting reset theme"; + qCDebug(appLog) << "slot setting reset theme"; if (path == DEEPIN_THEME) { if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::LightType) { - qDebug() << "light theme, return"; + qCDebug(appLog) << "light theme, return"; return; } else { DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::LightType); - qDebug() << "set light theme"; + qCDebug(appLog) << "set light theme"; } } else if (path == DEEPIN_DARK_THEME) { if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::DarkType) { - qDebug() << "dark theme, return"; + qCDebug(appLog) << "dark theme, return"; return; } else { DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::DarkType); - qDebug() << "set dark theme"; + qCDebug(appLog) << "set dark theme"; } } - qDebug() << "slot setting reset theme end"; + qCDebug(appLog) << "slot setting reset theme end"; } void Window::slot_saveReadingPath() { - qDebug() << "slot save reading path"; + qCDebug(appLog) << "slot save reading path"; m_reading_list.clear(); m_reading_list.append(currentWrapper()->textEditor()); - qDebug() << "slot save reading path end"; + qCDebug(appLog) << "slot save reading path end"; } void Window::slot_beforeReplace(QString _) { - qDebug() << "slot before replace"; + qCDebug(appLog) << "slot before replace"; currentWrapper()->textEditor()->beforeReplace(_); } void Window::slot_setTitleFocus() { - qDebug() << "slot set title focus"; + qCDebug(appLog) << "slot set title focus"; QMap::Iterator it = m_wrappers.begin(); for (; it != m_wrappers.end(); it++) { it.value()->bottomBar()->setChildrenFocus(true); @@ -4116,12 +4117,12 @@ void Window::slot_setTitleFocus() QWidget::setTabOrder(quitFullBtn, maxBtn); QWidget::setTabOrder(maxBtn, closeBtn); currentWrapper()->bottomBar()->setChildrenFocus(true, closeBtn); - qDebug() << "slot set title focus end"; + qCDebug(appLog) << "slot set title focus end"; } void Window::slotClearDoubleCharaterEncode() { - qDebug() << "slot clear double charater encode"; + qCDebug(appLog) << "slot clear double charater encode"; //赛迪方要求不能出现以下字符,但是编码库中存在,所以手动去掉 QStringList shouldBeEmpty; shouldBeEmpty << "\uE768" << "\uE769" << "\uE76A" << "\uE76B" << "\uE76D" << "\uE76E" << "\uE76F" << "\uE766" << "\uE767" << "\uE770" @@ -4144,42 +4145,42 @@ void Window::slotClearDoubleCharaterEncode() for (const QString &strTemp : shouldBeEmpty) { handleReplaceAll(strTemp, " "); } - qDebug() << "slot clear double charater encode end"; + qCDebug(appLog) << "slot clear double charater encode end"; } void Window::slotSigThemeChanged(const QString &path) { - qDebug() << "slot sig theme changed"; + qCDebug(appLog) << "slot sig theme changed"; if (path == DEEPIN_THEME) { if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::LightType) { - qDebug() << "light theme, return"; + qCDebug(appLog) << "light theme, return"; return; } else { DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::LightType); } } else if (path == DEEPIN_DARK_THEME) { if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::DarkType) { - qDebug() << "dark theme, return"; + qCDebug(appLog) << "dark theme, return"; return; } else { DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::DarkType); } } - qDebug() << "slot sig theme changed end"; + qCDebug(appLog) << "slot sig theme changed end"; } void Window::slotSigAdjustFont(QString fontName) { - qDebug() << "slot sig adjust font" << fontName; + qCDebug(appLog) << "slot sig adjust font" << fontName; for (EditWrapper *wrapper : m_wrappers.values()) { wrapper->textEditor()->setFontFamily(fontName); } - qDebug() << "slot sig adjust font end"; + qCDebug(appLog) << "slot sig adjust font end"; } void Window::slotSigAdjustFontSize(qreal fontSize) { - qDebug() << "slot sig adjust font size" << fontSize; + qCDebug(appLog) << "slot sig adjust font size" << fontSize; for (EditWrapper *wrapper : m_wrappers.values()) { wrapper->textEditor()->setFontSize(fontSize); wrapper->bottomBar()->setScaleLabelText(fontSize); @@ -4187,118 +4188,118 @@ void Window::slotSigAdjustFontSize(qreal fontSize) } m_fontSize = fontSize; - qDebug() << "slot sig adjust font size end"; + qCDebug(appLog) << "slot sig adjust font size end"; } void Window::slotSigAdjustTabSpaceNumber(int number) { - qDebug() << "slot sig adjust tab space number" << number; + qCDebug(appLog) << "slot sig adjust tab space number" << number; for (EditWrapper *wrapper : m_wrappers.values()) { wrapper->textEditor()->setTabSpaceNumber(number); } - qDebug() << "slot sig adjust tab space number end"; + qCDebug(appLog) << "slot sig adjust tab space number end"; } void Window::slotSigAdjustWordWrap(bool enable) { - qDebug() << "slot sig adjust word wrap" << enable; + qCDebug(appLog) << "slot sig adjust word wrap" << enable; for (EditWrapper *wrapper : m_wrappers.values()) { TextEdit *textedit = wrapper->textEditor(); textedit->setLineWrapMode(enable); } - qDebug() << "slot sig adjust word wrap end"; + qCDebug(appLog) << "slot sig adjust word wrap end"; } void Window::slotSigSetLineNumberShow(bool bIsShow) { - qDebug() << "slot sig set line number show" << bIsShow; + qCDebug(appLog) << "slot sig set line number show" << bIsShow; for (EditWrapper *wrapper : m_wrappers.values()) { wrapper->setLineNumberShow(bIsShow); } - qDebug() << "slot sig set line number show end"; + qCDebug(appLog) << "slot sig set line number show end"; } void Window::slotSigAdjustBookmark(bool bIsShow) { - qDebug() << "slot sig adjust bookmark" << bIsShow; + qCDebug(appLog) << "slot sig adjust bookmark" << bIsShow; for (EditWrapper *wrapper : m_wrappers.values()) { TextEdit *textedit = wrapper->textEditor(); textedit->setBookmarkFlagVisable(bIsShow); } - qDebug() << "slot sig adjust bookmark end"; + qCDebug(appLog) << "slot sig adjust bookmark end"; } void Window::slotSigShowBlankCharacter(bool bIsShow) { - qDebug() << "slot sig show blank character" << bIsShow; + qCDebug(appLog) << "slot sig show blank character" << bIsShow; for (EditWrapper *wrapper : m_wrappers.values()) { wrapper->setShowBlankCharacter(bIsShow); } - qDebug() << "slot sig show blank character end"; + qCDebug(appLog) << "slot sig show blank character end"; } void Window::slotSigHightLightCurrentLine(bool bIsShow) { - qDebug() << "slot sig hight light current line" << bIsShow; + qCDebug(appLog) << "slot sig hight light current line" << bIsShow; for (EditWrapper *wrapper : m_wrappers.values()) { wrapper->textEditor()->setHighLineCurrentLine(bIsShow); } - qDebug() << "slot sig hight light current line end"; + qCDebug(appLog) << "slot sig hight light current line end"; } void Window::slotSigShowCodeFlodFlag(bool bIsShow) { - qDebug() << "slot sig show code flod flag" << bIsShow; + qCDebug(appLog) << "slot sig show code flod flag" << bIsShow; for (EditWrapper *wrapper : m_wrappers.values()) { TextEdit *textedit = wrapper->textEditor(); textedit->setCodeFlodFlagVisable(bIsShow); } - qDebug() << "slot sig show code flod flag end"; + qCDebug(appLog) << "slot sig show code flod flag end"; } void Window::slotSigChangeWindowSize(QString mode) { - qDebug() << "slot sig change window size" << mode; + qCDebug(appLog) << "slot sig change window size" << mode; if (mode == "fullscreen") { - qDebug() << "slot sig change window size fullscreen"; + qCDebug(appLog) << "slot sig change window size fullscreen"; this->showFullScreen(); } else if (mode == "window_maximum") { - qDebug() << "slot sig change window size window_maximum"; + qCDebug(appLog) << "slot sig change window size window_maximum"; this->showNormal(); this->showMaximized(); } else { - qDebug() << "slot sig change window size window_minimum"; + qCDebug(appLog) << "slot sig change window size window_minimum"; this->showNormal(); } - qDebug() << "slot sig change window size end"; + qCDebug(appLog) << "slot sig change window size end"; } void Window::handleFocusWindowChanged(QWindow *w) { - qDebug() << "handle focus window changed"; + qCDebug(appLog) << "handle focus window changed"; if (windowHandle() != w || !currentWrapper() || !isActiveWindow()) { - qDebug() << "handle focus window changed return"; + qCDebug(appLog) << "handle focus window changed return"; return; } currentWrapper()->checkForReload(); checkTabbarForReload(); - qDebug() << "handle focus window changed end"; + qCDebug(appLog) << "handle focus window changed end"; } void Window::updateThemePanelGeomerty() { - qDebug() << "update theme panel geomerty"; + qCDebug(appLog) << "update theme panel geomerty"; int yOffset = isFullScreen() ? 0 : titlebar()->height(); QRect themePanelRect(0, yOffset, 250, height() - yOffset); themePanelRect.moveRight(rect().right()); m_themePanel->setGeometry(themePanelRect); - qDebug() << "update theme panel geomerty end"; + qCDebug(appLog) << "update theme panel geomerty end"; } void Window::checkTabbarForReload() { - qDebug() << "check tabbar for reload"; + qCDebug(appLog) << "check tabbar for reload"; /* 修复99423 bug暂且屏蔽;拖拽出只读tab文件项,只读字样消失 int cur = m_tabbar->currentIndex(); QFileInfo fi(m_tabbar->truePathAt(cur)); @@ -4306,10 +4307,10 @@ void Window::checkTabbarForReload() QFileInfo fi; if (m_tabbar->currentPath().contains("backup-files")) { fi.setFile(m_tabbar->truePathAt(m_tabbar->currentIndex())); - qDebug() << "check tabbar for reload backup-files" << fi.filePath(); + qCDebug(appLog) << "check tabbar for reload backup-files" << fi.filePath(); } else { fi.setFile(m_tabbar->currentPath()); - qDebug() << "check tabbar for reload normal" << fi.filePath(); + qCDebug(appLog) << "check tabbar for reload normal" << fi.filePath(); } QString tabName = m_tabbar->currentName(); @@ -4318,19 +4319,19 @@ void Window::checkTabbarForReload() EditWrapper *wrapper = m_wrappers.value(m_tabbar->currentPath()); if (!wrapper || !wrapper->textEditor()) { - qWarning() << "Failed to get wrapper or text editor in checkTabbarForReload"; + qCWarning(appLog) << "Failed to get wrapper or text editor in checkTabbarForReload"; return; } if (fi.exists() && !fi.isWritable()) { - qDebug() << "check tabbar for reload backup-files not writable"; + qCDebug(appLog) << "check tabbar for reload backup-files not writable"; tabName.append(readOnlyStr); if (m_tabbar->currentName() != tabName) { m_tabbar->setTabText(m_tabbar->currentIndex(), tabName); } wrapper->textEditor()->setReadOnlyPermission(true); } else { - qDebug() << "check tabbar for reload backup-files writable"; + qCDebug(appLog) << "check tabbar for reload backup-files writable"; tabName.remove(readOnlyStr); if (m_tabbar->currentName() != tabName) { m_tabbar->setTabText(m_tabbar->currentIndex(), tabName); @@ -4342,25 +4343,25 @@ void Window::checkTabbarForReload() //m_tabbar->setTabText(m_tabbar->currentIndex(), tabName); //判断是否需要阻塞系统关机 emit sigJudgeBlockShutdown(); - qDebug() << "check tabbar for reload end"; + qCDebug(appLog) << "check tabbar for reload end"; StartManager::instance()->delayMallocTrim(); } void Window::resizeEvent(QResizeEvent *e) { if (m_themePanel->isVisible()) { - qDebug() << "resize event update theme panel geomerty"; + qCDebug(appLog) << "resize event update theme panel geomerty"; updateThemePanelGeomerty(); } if (!isMaximized() && !isFullScreen()) { - qDebug() << "resize event update window size"; + qCDebug(appLog) << "resize event update window size"; m_settings->settings->option("advance.window.window_width")->setValue(rect().width()); m_settings->settings->option("advance.window.window_height")->setValue(rect().height()); if (m_needMoveToCenter) { Dtk::Widget::moveToCenter(this); m_needMoveToCenter = false; - qDebug() << "resize event update window size move to center"; + qCDebug(appLog) << "resize event update window size move to center"; } } @@ -4383,30 +4384,30 @@ void Window::resizeEvent(QResizeEvent *e) void Window::closeEvent(QCloseEvent *e) { - qDebug() << "close event"; + qCDebug(appLog) << "close event"; PerformanceMonitor::closeAppStart(); if (StartManager::instance()->isMultiWindow()) { - qDebug() << "close event multi window"; + qCDebug(appLog) << "close event multi window"; if (!closeAllFiles()) { e->ignore(); - qDebug() << "close event ignore"; + qCDebug(appLog) << "close event ignore"; return; } } else { // 是否记录上次打开的文件 - qDebug() << "close event single window"; + qCDebug(appLog) << "close event single window"; bool save_tab_before_close = m_settings->settings->option("advance.startup.save_tab_before_close")->value().toBool(); if (!save_tab_before_close) { // 不记录,关闭所有标签页,没保存的文件提示保存 - qDebug() << "close event save tab before close false"; + qCDebug(appLog) << "close event save tab before close false"; if (!closeAllFiles()) { e->ignore(); - qDebug() << "close event ignore"; + qCDebug(appLog) << "close event ignore"; return; } } else { - qDebug() << "close event save tab before close true"; + qCDebug(appLog) << "close event save tab before close true"; // 记录,没保存的文件不提示保存,除非磁盘上文件已删除 // 单个窗口时,没有记录单独关闭窗口,需要记录窗口信息。 for (auto itr = m_wrappers.begin(); itr != m_wrappers.end(); ++itr) { @@ -4426,7 +4427,7 @@ void Window::closeEvent(QCloseEvent *e) // WARNING: 调用 QProcess::startDetached() 前同步配置,防止多线程对 qgetenv() 中的 environmentMutex 加锁 // 导致创建进程 fork() 时保留了 environmentMutex 锁状态,使得父子进程陷入资源竞态,阻塞状态。 if (m_settings->settings) { - qDebug() << "close event sync settings"; + qCDebug(appLog) << "close event sync settings"; m_settings->settings->sync(); } @@ -4434,7 +4435,7 @@ void Window::closeEvent(QCloseEvent *e) m_bPrintProcessing = false; if (IflytekAiAssistant::instance()->valid()) { - qDebug() << "close event iflytek ai assistant valid"; + qCDebug(appLog) << "close event iflytek ai assistant valid"; IflytekAiAssistant::instance()->stopTtsDirectly(); } @@ -4464,28 +4465,28 @@ void Window::closeEvent(QCloseEvent *e) void Window::hideEvent(QHideEvent *event) { - qDebug() << "hide event"; + qCDebug(appLog) << "hide event"; if (this->isVisible()) { - qDebug() << "hide event is visible"; + qCDebug(appLog) << "hide event is visible"; if (currentWrapper() != nullptr) { currentWrapper()->textEditor()->setFocus(); - qDebug() << "hide event set focus"; + qCDebug(appLog) << "hide event set focus"; } } //如果查找浮窗正显示着,则隐藏 if (m_findBar->isVisible()) { - qDebug() << "hide event hide find bar"; + qCDebug(appLog) << "hide event hide find bar"; // m_findBar->hide(); if (currentWrapper() != nullptr) { currentWrapper()->bottomBar()->show(); - qDebug() << "hide event show bottom bar"; + qCDebug(appLog) << "hide event show bottom bar"; } } //如果替换浮窗正显示着,则隐藏 #if 0 if (m_replaceBar->isVisible()) { - qDebug() << "hide event hide replace bar"; + qCDebug(appLog) << "hide event hide replace bar"; //m_replaceBar->hide(); if (currentWrapper() != nullptr) { currentWrapper()->m_bottomBar->show(); @@ -4498,112 +4499,112 @@ void Window::hideEvent(QHideEvent *event) void Window::keyPressEvent(QKeyEvent *e) { QString key = Utils::getKeyshortcut(e); - qDebug() << "key press event" << key; + qCDebug(appLog) << "key press event" << key; if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "decrementfontsize") || key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "incrementfontsize") || key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "togglefullscreen")) { currentWrapper()->textEditor()->setCodeFoldWidgetHide(true); - qDebug() << "key press event toggle full screen"; + qCDebug(appLog) << "key press event toggle full screen"; } if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "addblanktab")) { - qDebug() << "key press event add blank tab"; + qCDebug(appLog) << "key press event add blank tab"; addBlankTab(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "newwindow")) { - qDebug() << "key press event new window"; + qCDebug(appLog) << "key press event new window"; emit newWindow(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "savefile")) { - qDebug() << "key press event save file"; + qCDebug(appLog) << "key press event save file"; saveFile(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "saveasfile")) { - qDebug() << "key press event save as file"; + qCDebug(appLog) << "key press event save as file"; saveAsFile(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "selectnexttab")) { - qDebug() << "key press event select next tab"; + qCDebug(appLog) << "key press event select next tab"; m_tabbar->nextTab(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "selectprevtab")) { - qDebug() << "key press event select previous tab"; + qCDebug(appLog) << "key press event select previous tab"; m_tabbar->previousTab(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "closetab")) { - qDebug() << "key press event close tab"; + qCDebug(appLog) << "key press event close tab"; closeTab(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "restoretab")) { - qDebug() << "key press event restore tab"; + qCDebug(appLog) << "key press event restore tab"; restoreTab(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "closeothertabs")) { - qDebug() << "key press event close other tabs"; + qCDebug(appLog) << "key press event close other tabs"; m_tabbar->closeOtherTabs(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "openfile")) { - qDebug() << "key press event open file"; + qCDebug(appLog) << "key press event open file"; openFile(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "incrementfontsize")) { - qDebug() << "key press event increment font size"; + qCDebug(appLog) << "key press event increment font size"; incrementFontSize(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "decrementfontsize")) { - qDebug() << "key press event decrement font size"; + qCDebug(appLog) << "key press event decrement font size"; decrementFontSize(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "resetfontsize")) { - qDebug() << "key press event reset font size"; + qCDebug(appLog) << "key press event reset font size"; resetFontSize(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "togglefullscreen")) { - qDebug() << "key press event toggle full screen"; + qCDebug(appLog) << "key press event toggle full screen"; DIconButton *minBtn = titlebar()->findChild("DTitlebarDWindowMinButton"); DIconButton *quitFullBtn = titlebar()->findChild("DTitlebarDWindowQuitFullscreenButton"); quitFullBtn->setFocusPolicy(Qt::TabFocus); DIconButton *maxBtn = titlebar()->findChild("DTitlebarDWindowMaxButton"); if (minBtn->hasFocus() || maxBtn->hasFocus()) { - qDebug() << "min or max button has focus"; + qCDebug(appLog) << "min or max button has focus"; toggleFullscreen(); quitFullBtn->setFocus(); } else { - qDebug() << "quit full screen button has focus"; + qCDebug(appLog) << "quit full screen button has focus"; toggleFullscreen(); } } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "find")) { - qDebug() << "key press event popup find bar"; + qCDebug(appLog) << "key press event popup find bar"; popupFindBar(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "findNext")) { - qDebug() << "key press event handle find next search keyword"; + qCDebug(appLog) << "key press event handle find next search keyword"; handleFindNextSearchKeyword(m_keywordForSearch); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "findPrev")) { - qDebug() << "key press event handle find prev search keyword"; + qCDebug(appLog) << "key press event handle find prev search keyword"; handleFindPrevSearchKeyword(m_keywordForSearch); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "replace")) { - qDebug() << "key press event popup replace bar"; + qCDebug(appLog) << "key press event popup replace bar"; popupReplaceBar(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "jumptoline")) { - qDebug() << "key press event popup jump line bar"; + qCDebug(appLog) << "key press event popup jump line bar"; popupJumpLineBar(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "saveposition")) { - qDebug() << "key press event save position"; + qCDebug(appLog) << "key press event save position"; remberPositionSave(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "restoreposition")) { - qDebug() << "key press event restore position"; + qCDebug(appLog) << "key press event restore position"; remberPositionRestore(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "escape")) { - qDebug() << "key press event press escape"; + qCDebug(appLog) << "key press event press escape"; emit pressEsc(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "displayshortcuts")) { - qDebug() << "key press event display shortcuts"; + qCDebug(appLog) << "key press event display shortcuts"; displayShortcuts(); } else if (key == Utils::getKeyshortcutFromKeymap(m_settings, "window", "print")) { - qDebug() << "key press event popup print dialog"; + qCDebug(appLog) << "key press event popup print dialog"; popupPrintDialog(); } else { - qDebug() << "key press event post event to window widget"; + qCDebug(appLog) << "key press event post event to window widget"; // Post event to window widget if match Alt+0 ~ Alt+9 QRegularExpression re("^Alt\\+\\d"); QRegularExpressionMatch match = re.match(key); if (match.hasMatch()) { auto tabIndex = key.replace("Alt+", "").toInt(); if (tabIndex == 9) { - qDebug() << "tab index is 9"; + qCDebug(appLog) << "tab index is 9"; if (m_tabbar->count() > 1) { activeTab(m_tabbar->count() - 1); } } else { - qDebug() << "tab index is " << tabIndex; + qCDebug(appLog) << "tab index is " << tabIndex; if (tabIndex <= m_tabbar->count()) { activeTab(tabIndex - 1); } @@ -4615,7 +4616,7 @@ void Window::keyPressEvent(QKeyEvent *e) void Window::keyReleaseEvent(QKeyEvent *keyEvent) { if ((keyEvent->modifiers() | Qt::ShiftModifier) || (keyEvent->modifiers() | Qt::ControlModifier)) { - qDebug() << "key release event ignore"; + qCDebug(appLog) << "key release event ignore"; // if (nullptr != m_shortcutViewProcess) { // int count = Utils::getProcessCountByName("deepin-shortcut-viewer"); // if (count > 0) { @@ -4630,18 +4631,18 @@ void Window::keyReleaseEvent(QKeyEvent *keyEvent) void Window::dragEnterEvent(QDragEnterEvent *event) { - qDebug() << "drag enter event"; + qCDebug(appLog) << "drag enter event"; // Accept drag event if mime type is url. event->accept(); } void Window::dropEvent(QDropEvent *event) { - qDebug() << "drop event"; + qCDebug(appLog) << "drop event"; const QMimeData *mimeData = event->mimeData(); if (mimeData->hasUrls()) { - qDebug() << "drop event has urls"; + qCDebug(appLog) << "drop event has urls"; QStringList supportfileNames; QStringList otherfiles; for (auto url : mimeData->urls()) { @@ -4663,7 +4664,7 @@ void Window::dropEvent(QDropEvent *event) addTab(var, true); } } - qDebug() << "drop event end"; + qCDebug(appLog) << "drop event end"; } /** @@ -4671,59 +4672,59 @@ void Window::dropEvent(QDropEvent *event) */ void Window::timerEvent(QTimerEvent *e) { - qDebug() << "timer event"; + qCDebug(appLog) << "timer event"; // 处理延迟关闭标签事件 if (e->timerId() == m_delayCloseTabTimer.timerId()) { - qDebug() << "timer event delay close tab"; + qCDebug(appLog) << "timer event delay close tab"; m_delayCloseTabTimer.stop(); // 判断当前处理的标签页是否合法 if (0 <= m_requestCloseTabIndex && m_requestCloseTabIndex < m_tabbar->count()) { activeTab(m_requestCloseTabIndex); closeTab(); - qDebug() << "timer event close tab"; + qCDebug(appLog) << "timer event close tab"; } } - qDebug() << "timer event end"; + qCDebug(appLog) << "timer event end"; } bool Window::findBarIsVisiable() { - qDebug() << "find bar is visiable"; + qCDebug(appLog) << "find bar is visiable"; if (m_findBar->isVisible()) { - qDebug() << "find bar is visiable true"; + qCDebug(appLog) << "find bar is visiable true"; return true; } else { - qDebug() << "find bar is visiable false"; + qCDebug(appLog) << "find bar is visiable false"; return false; } } bool Window::replaceBarIsVisiable() { - qDebug() << "replace bar is visiable"; + qCDebug(appLog) << "replace bar is visiable"; return m_replaceBar == nullptr ? false : m_replaceBar->isVisible(); } QString Window::getKeywordForSearchAll() { - qDebug() << "get keyword for search all"; + qCDebug(appLog) << "get keyword for search all"; return m_keywordForSearchAll; } QString Window::getKeywordForSearch() { - qDebug() << "get keyword for search"; + qCDebug(appLog) << "get keyword for search"; return m_keywordForSearch; } void Window::setPrintEnabled(bool enabled) { - qDebug() << "set print enabled"; + qCDebug(appLog) << "set print enabled"; for (int i = 0; i < m_menu->actions().count(); i++) { if (!m_menu->actions().at(i)->text().compare(QString("Print"))) { m_menu->actions().at(i)->setEnabled(enabled); - qDebug() << "has Print, return"; + qCDebug(appLog) << "has Print, return"; return; } } @@ -4731,6 +4732,6 @@ void Window::setPrintEnabled(bool enabled) QStackedWidget *Window::getStackedWgt() { - qDebug() << "get stacked wgt"; + qCDebug(appLog) << "get stacked wgt"; return m_editorWidget; } From eb3fcca73e194549667cc67435ef40ea796fc8f0 Mon Sep 17 00:00:00 2001 From: zhanghongyuan Date: Thu, 22 Oct 2026 11:39:33 +0800 Subject: [PATCH 2/3] fix(log): defer encoding locale init to first use to avoid pre-main logging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The static initializer getLocaleNum() logged via qCDebug before main() runs, before MLogger applies dynamic log rules, leaking debug lines at info/warning levels. Convert to lazy initialization. Log: 修复 info/warning 级别下启动期日志泄漏 --- src/common/encoding.cpp | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/common/encoding.cpp b/src/common/encoding.cpp index e413e7fea..c55795621 100644 --- a/src/common/encoding.cpp +++ b/src/common/encoding.cpp @@ -156,10 +156,23 @@ static unsigned int getLocaleNum() return code; } /*************************/ -static unsigned int localeNum = getLocaleNum(); -static const std::string encodingItem[ENCODING_MAX_ITEM_NUM] = {encodingTable[localeNum][0], - encodingTable[localeNum][1], - encodingTable[localeNum][2]}; +// 延迟到首次使用时初始化,避免在 main() 之前的静态初始化阶段打日志 +// (此时动态日志规则尚未生效,qCDebug 会在 info/warning 级别泄漏) +static unsigned int currentLocaleNum() +{ + static unsigned int num = getLocaleNum(); + return num; +} + +static const std::string *encodingItems() +{ + static const std::string items[ENCODING_MAX_ITEM_NUM] = { + encodingTable[currentLocaleNum()][0], + encodingTable[currentLocaleNum()][1], + encodingTable[currentLocaleNum()][2]}; + return items; +} +#define encodingItem (encodingItems()) /*************************/ static const std::string detectCharsetLatin (const char *text) { @@ -796,7 +809,7 @@ const QString detectCharset (const QByteArray& byteArray) if (charset.empty()) { qCDebug(appLog) << "charset is empty"; - switch (localeNum) + switch (currentLocaleNum()) { case LATIN1: /* Windows-1252 */ From cd4ed0da005d9441977a98362d9e13846641fa03 Mon Sep 17 00:00:00 2001 From: zhanghongyuan Date: Thu, 22 Oct 2026 21:52:52 +0800 Subject: [PATCH 3/3] fix(log): drop QT_NO_DEBUG_OUTPUT in Release so dynamic debug level works MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QT_NO_DEBUG_OUTPUT makes QLoggingCategoryMacroHolder:: IsOutputEnabled statically false at compile time, turning qCDebug into a hard no-op. The packaged Release deb therefore can only ever print qCInfo/qCWarning even with the debug mode switched to the debug level. Disabled categorized logs cost one boolean check per call (Qt lazily evaluates arguments), so keep them compiled in; deepin-reader, the reference implementation, does not compile them out either. Log: 修复打包版 Release 构建调试模式无法输出 debug 级日志 --- src/CMakeLists.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 09202327c..ac9012870 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -79,9 +79,9 @@ link_directories(${chardet_LIBRARY_DIRS}) # Tell CMake to create the executable add_executable(deepin-editor ${SRCS} deepin-editor.qrc) -if(CMAKE_BUILD_TYPE STREQUAL "Release") - target_compile_definitions(deepin-editor PRIVATE QT_NO_DEBUG_OUTPUT) -endif() +# 注意:不要在 Release 下定义 QT_NO_DEBUG_OUTPUT——它会把 qCDebug 编译成硬性空操作 +# (编译期 IsOutputEnabled=false),导致调试模式动态开到 debug 级也无法输出 qCDebug 日志; +# 分类日志关闭时仅有一次布尔判断开销(Qt 惰性求值),参数不会被计算 target_link_libraries(deepin-editor ${LINK_LIBS} ${chardet_LIBRARY_DIRS}