diff options
author | saturneric <[email protected]> | 2024-07-26 16:24:34 +0000 |
---|---|---|
committer | saturneric <[email protected]> | 2024-07-26 16:24:34 +0000 |
commit | 37a62a8d0b590710b902376ca3320cc05e954b63 (patch) | |
tree | 349ecff21e5cf53d8eedbae7886404417ecdad05 | |
parent | fix: correct urls at appdata.xml (diff) | |
download | GpgFrontend-37a62a8d0b590710b902376ca3320cc05e954b63.tar.gz GpgFrontend-37a62a8d0b590710b902376ca3320cc05e954b63.zip |
feat: remove spdlog and clean up log
110 files changed, 683 insertions, 1643 deletions
diff --git a/.gitmodules b/.gitmodules index 6d7f2301..389b56f2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ [submodule "third_party/qt-aes"] path = third_party/qt-aes url = https://github.com/bricke/Qt-AES.git -[submodule "third_party/spdlog"] - path = third_party/spdlog - url = https://github.com/gabime/spdlog.git [submodule "third_party/mimalloc"] path = third_party/mimalloc url = https://github.com/microsoft/mimalloc.git diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ab6d0dbb..2802859f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -23,6 +23,7 @@ # # SPDX-License-Identifier: GPL-3.0-or-later +# if(APPLE) add_compile_definitions("_GNU_SOURCE") endif() @@ -30,6 +31,7 @@ endif() # Introduce GpgME find_package(Gpgme REQUIRED) + # Introduce OpenSSL if (APPLE) # Define possible OpenSSL directories @@ -54,15 +56,18 @@ endif() find_package(OpenSSL REQUIRED) + # Set Build Information configure_file(${CMAKE_SOURCE_DIR}/src/GpgFrontend.h.in ${CMAKE_SOURCE_DIR}/src/GpgFrontend.h @ONLY) configure_file(${CMAKE_SOURCE_DIR}/src/GpgFrontendBuildInfo.h.in ${CMAKE_SOURCE_DIR}/src/GpgFrontendBuildInfo.h @ONLY) configure_file(${CMAKE_SOURCE_DIR}/src/GpgFrontendBuildInstallInfo.h.in ${CMAKE_SOURCE_DIR}/src/GpgFrontendBuildInstallInfo.h @ONLY) configure_file(${CMAKE_SOURCE_DIR}/src/sdk/GFSDKBuildInfo.h.in ${CMAKE_SOURCE_DIR}/src/sdk/GFSDKBuildInfo.h @ONLY) + if (APPLE) configure_file(${CMAKE_SOURCE_DIR}/resource/plist/ExportOptions.plist.in ${CMAKE_BINARY_DIR}/ExportOptions.plist @ONLY) endif () + # Set Runtime Output Directory if (NOT XCODE_BUILD) # Set Binary Output Path @@ -72,13 +77,8 @@ else () set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_BUILD_TYPE}) endif () -# configure for output path and resources -if (BUILD_APPLICATION) - aux_source_directory(. BASE_SOURCE) - set(APP_ICON_RESOURCE_WINDOWS "${CMAKE_SOURCE_DIR}/gpgfrontend.rc") - set_property(SOURCE gpgfrontend.rc APPEND PROPERTY OBJECT_DEPENDS ${CMAKE_SOURCE_DIR}/gpgfrontend.ico) -endif () +# Print modules if (BUILD_CORE) # core depends pinentry message("[+] Build Pinentry") @@ -105,6 +105,13 @@ if (BUILD_TEST) add_subdirectory(test) endif () +# configure for output path and resources +if (BUILD_APPLICATION) + aux_source_directory(. BASE_SOURCE) + set(APP_ICON_RESOURCE_WINDOWS "${CMAKE_SOURCE_DIR}/gpgfrontend.rc") + set_property(SOURCE gpgfrontend.rc APPEND PROPERTY OBJECT_DEPENDS ${CMAKE_SOURCE_DIR}/gpgfrontend.ico) +endif () + if (BUILD_APPLICATION) # Set Resource Output Path if (${CMAKE_BUILD_TYPE} STREQUAL "Release") @@ -482,7 +489,6 @@ if (LINUX AND LINUX_INSTALL_SOFTWARE) include(GNUInstallDirs) set(GPGFRONTEND_INSTALL_LIBRARIES mimalloc - spdlog gpgfrontend_core gpgfrontend_ui gpgfrontend_test diff --git a/src/GpgFrontendContext.h b/src/GpgFrontendContext.h index 00bbcfbe..c4c10690 100644 --- a/src/GpgFrontendContext.h +++ b/src/GpgFrontendContext.h @@ -38,7 +38,6 @@ using GFCxtSPtr = std::shared_ptr<GpgFrontendContext>; struct GpgFrontendContext { int argc; char** argv; - spdlog::level::level_enum log_level; bool gather_external_gnupg_info; bool load_default_gpg_context; diff --git a/src/app.cpp b/src/app.cpp index 9aa72894..54875f86 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -34,7 +34,6 @@ // main #include "init.h" -#include "main.h" namespace GpgFrontend { @@ -50,20 +49,18 @@ constexpr int kCrashCode = ~0; ///< auto StartApplication(const GFCxtWPtr& p_ctx) -> int { GFCxtSPtr ctx = p_ctx.lock(); if (ctx == nullptr) { - GF_MAIN_LOG_ERROR("cannot get gpgfrontend context."); + qWarning("cannot get gpgfrontend context."); return -1; } auto* app = ctx->GetApp(); if (app == nullptr) { - GF_MAIN_LOG_ERROR("cannot get qapplication from gpgfrontend context."); + qWarning("cannot get QApplication from gpgfrontend context."); return -1; } - GF_MAIN_LOG_DEBUG("start running gui application"); - /** - * internationalisation. loop to restart main window + * internationalization. loop to restart main window * with changed translation when settings change. */ int return_from_event_loop_code; @@ -79,13 +76,8 @@ auto StartApplication(const GFCxtWPtr& p_ctx) -> int { // finally create main window return_from_event_loop_code = GpgFrontend::UI::RunGpgFrontendUI(app); - GF_MAIN_LOG_DEBUG("try to destroy modules system and core"); - restart_count++; - GF_MAIN_LOG_DEBUG( - "restart loop refresh, event loop code: {}, restart count: {}", - return_from_event_loop_code, restart_count); } while (return_from_event_loop_code == GpgFrontend::kRestartCode && restart_count < 99); @@ -94,17 +86,10 @@ auto StartApplication(const GFCxtWPtr& p_ctx) -> int { // then shutdown the core GpgFrontend::DestroyGpgFrontendCore(); - GF_MAIN_LOG_DEBUG("core and modules system destroyed"); - - // log for debug - GF_MAIN_LOG_INFO("GpgFrontend is about to exit."); // deep restart mode if (return_from_event_loop_code == GpgFrontend::kDeepRestartCode || return_from_event_loop_code == kCrashCode) { - // log for debug - GF_MAIN_LOG_DEBUG( - "deep restart or cash loop status caught, restart a new application"); QProcess::startDetached(qApp->arguments()[0], qApp->arguments()); }; diff --git a/src/cmd.cpp b/src/cmd.cpp index d41b6de0..1f3182fe 100644 --- a/src/cmd.cpp +++ b/src/cmd.cpp @@ -28,11 +28,9 @@ #include "cmd.h" -#include "core/utils/BuildInfoUtils.h" -#include "main.h" +#include <qglobal.h> -// std -#include <iostream> +#include "core/utils/BuildInfoUtils.h" // GpgFrontend #include "GpgFrontendContext.h" @@ -60,30 +58,29 @@ auto PrintVersion() -> int { return 0; } -auto ParseLogLevel(const QString& log_level) -> spdlog::level::level_enum { - if (log_level == "trace") { - return spdlog::level::trace; - } +auto ParseLogLevel(const QString& log_level) -> int { if (log_level == "debug") { - return spdlog::level::debug; - } - if (log_level == "info") { - return spdlog::level::info; + QLoggingCategory::setFilterRules( + "core.debug=true\nui.debug=true\ntest.debug=true\nmodule.debug=true"); + } else if (log_level == "info") { + QLoggingCategory::setFilterRules( + "*.debug=false\ncore.info=true\nui.info=true\ntest.info=" + "true\nmodule.info=true"); + } else if (log_level == "warning") { + QLoggingCategory::setFilterRules("*.debug=false\n*.info=false\n"); + } else if (log_level == "critical") { + QLoggingCategory::setFilterRules( + "*.debug=false\n*.info=false\n*.warning=false\n"); + } else { + qWarning() << "unknown log level: " << log_level; } - if (log_level == "warn") { - return spdlog::level::warn; - } - if (log_level == "error") { - return spdlog::level::err; - } - - return spdlog::level::info; + return 0; } auto RunTest(const GFCxtWPtr& p_ctx) -> int { GpgFrontend::GFCxtSPtr const ctx = p_ctx.lock(); if (ctx == nullptr) { - GF_MAIN_LOG_ERROR("cannot get gpgfrontend context for test running"); + qWarning("cannot get gpgfrontend context for test running"); return -1; } @@ -36,7 +36,7 @@ namespace GpgFrontend { auto PrintVersion() -> int; -auto ParseLogLevel(const QString& level) -> spdlog::level::level_enum; +auto ParseLogLevel(const QString& level) -> int; auto RunTest(const GFCxtWPtr&) -> int; diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index a5be5827..5725aab0 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -23,7 +23,7 @@ # # SPDX-License-Identifier: GPL-3.0-or-later - +# gather source files aux_source_directory(./function/result_analyse CORE_SOURCE) aux_source_directory(./function/basic CORE_SOURCE) aux_source_directory(./function/gpg CORE_SOURCE) @@ -37,13 +37,23 @@ aux_source_directory(./utils/aes CORE_SOURCE) aux_source_directory(./utils CORE_SOURCE) aux_source_directory(. CORE_SOURCE) + # define libgpgfrontend_core set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) + add_library(gpgfrontend_core SHARED ${CORE_SOURCE}) + +# generate headers set(_export_file "${CMAKE_CURRENT_SOURCE_DIR}/GpgFrontendCoreExport.h") generate_export_header(gpgfrontend_core EXPORT_FILE_NAME "${_export_file}") +# compile definitions +target_compile_definitions(gpgfrontend_core PUBLIC GF_CORE) + + +# link options + target_link_libraries(gpgfrontend_core PUBLIC mimalloc) if(MINGW) set_target_properties(mimalloc @@ -70,15 +80,6 @@ if (MINGW) target_link_libraries(gpgfrontend_core PUBLIC bcrypt) endif () -# spdlog -target_link_libraries(gpgfrontend_core PRIVATE spdlog) -if(MINGW) - set_target_properties(spdlog - PROPERTIES - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}" - ) -endif() # configure libarchive if(NOT MINGW) diff --git a/src/core/GpgCoreInit.cpp b/src/core/GpgCoreInit.cpp index 2952d6e4..f8f529a6 100644 --- a/src/core/GpgCoreInit.cpp +++ b/src/core/GpgCoreInit.cpp @@ -78,7 +78,6 @@ auto SearchGpgconfPath(const QList<QString>& candidate_paths) -> QString { auto SearchKeyDatabasePath(const QList<QString>& candidate_paths) -> QString { for (const auto& path : candidate_paths) { - GF_CORE_LOG_DEBUG("searh for candidate key database path: {}", path); if (VerifyKeyDatabasePath(QFileInfo(path))) { return path; } @@ -97,8 +96,6 @@ auto InitGpgME(const QString& gpgconf_path, const QString& gnupg_path) -> bool { #endif if (!gnupg_path.isEmpty()) { - GF_CORE_LOG_DEBUG("gpgme set engine info, gpgconf path: {}, gnupg path: {}", - gpgconf_path, gnupg_path); CheckGpgError(gpgme_set_engine_info(GPGME_PROTOCOL_GPGCONF, gpgconf_path.toUtf8(), nullptr)); CheckGpgError(gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP, @@ -121,15 +118,6 @@ auto InitGpgME(const QString& gpgconf_path, const QString& gnupg_path) -> bool { continue; } - GF_CORE_LOG_DEBUG( - "gpg context engine info: {} {} {} {}", - gpgme_get_protocol_name(engine_info->protocol), - QString(engine_info->file_name == nullptr ? "null" - : engine_info->file_name), - QString(engine_info->home_dir == nullptr ? "null" - : engine_info->home_dir), - QString(engine_info->version ? "null" : engine_info->version)); - switch (engine_info->protocol) { case GPGME_PROTOCOL_OpenPGP: find_openpgp = true; @@ -183,12 +171,11 @@ auto InitGpgME(const QString& gpgconf_path, const QString& gnupg_path) -> bool { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", QString{"0.0.0"}); - GF_CORE_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); // conditional check: only support gpg 2.1.x now if (!(GFCompareSoftwareVersion(gnupg_version, "2.1.0") >= 0 && find_gpgconf && find_openpgp && find_cms)) { - GF_CORE_LOG_ERROR("gpgme env check failed, abort"); + qCWarning(core, "gpgme env check failed, abort"); return false; } @@ -249,8 +236,8 @@ auto DetectGpgConfPath() -> QString { #endif if (!VerifyGpgconfPath(QFileInfo(gnupg_install_fs_path))) { - GF_CORE_LOG_ERROR("core loaded custom gpgconf path is illegal: {}", - gnupg_install_fs_path); + qCWarning(core) << "core loaded custom gpgconf path is illegal: " + << gnupg_install_fs_path; gnupg_install_fs_path = ""; } } @@ -260,15 +247,11 @@ auto DetectGpgConfPath() -> QString { #ifdef MACOS gnupg_install_fs_path = SearchGpgconfPath( {"/usr/local/bin/gpgconf", "/opt/homebrew/bin/gpgconf"}); - GF_CORE_LOG_DEBUG("core loaded searched gpgconf path: {}", - gnupg_install_fs_path); #endif #ifdef WINDOWS gnupg_install_fs_path = SearchGpgconfPath({"C:/Program Files (x86)/gnupg/bin"}); - GF_CORE_LOG_DEBUG("core loaded searched gpgconf path: {}", - gnupg_install_fs_path); #endif } @@ -290,12 +273,12 @@ void InitGpgFrontendCore(CoreInitArgs args) { Module::UpsertRTValue("core", "env.state.all", 0); // initialize locale environment - GF_CORE_LOG_DEBUG("locale: {}", setlocale(LC_CTYPE, nullptr)); + qCDebug(core, "locale info: %s", setlocale(LC_CTYPE, nullptr)); auto gpgconf_install_fs_path = DetectGpgConfPath(); auto gnupg_install_fs_path = DetectGnuPGPath(gpgconf_install_fs_path); - GF_CORE_LOG_INFO("detected gpgconf path: {}", gpgconf_install_fs_path); - GF_CORE_LOG_INFO("detected gnupg path: {}", gnupg_install_fs_path); + qCInfo(core) << "detected gpgconf path: " << gpgconf_install_fs_path; + qCInfo(core) << "detected gnupg path: " << gnupg_install_fs_path; // initialize library gpgme if (!InitGpgME(gpgconf_install_fs_path, gnupg_install_fs_path)) { @@ -334,11 +317,6 @@ void InitGpgFrontendCore(CoreInitArgs args) { QString::fromLocal8Bit(qgetenv("container")) != "flatpak") .toBool(); - GF_CORE_LOG_DEBUG("core loaded if use custom key databse path: {}", - use_custom_key_database_path); - GF_CORE_LOG_DEBUG("core loaded custom key databse path: {}", - custom_key_database_path); - // check key database path QString key_database_fs_path; // user defined @@ -346,21 +324,17 @@ void InitGpgFrontendCore(CoreInitArgs args) { !custom_key_database_path.isEmpty()) { key_database_fs_path = custom_key_database_path; if (VerifyKeyDatabasePath(QFileInfo(key_database_fs_path))) { - GF_CORE_LOG_ERROR( - "core loaded custom gpg key database is illegal: {}", - key_database_fs_path); + qCWarning(core) + << "core loaded custom gpg key database is illegal: " + << key_database_fs_path; } else { use_custom_key_database_path = true; - GF_CORE_LOG_DEBUG("core loaded custom gpg key database path: {}", - key_database_fs_path); } } else { #if defined(LINUX) || defined(MACOS) use_custom_key_database_path = true; key_database_fs_path = SearchKeyDatabasePath({QDir::home().path() + "/.gnupg"}); - GF_CORE_LOG_DEBUG("core loaded searched key database path: {}", - key_database_fs_path); #endif } @@ -377,13 +351,11 @@ void InitGpgFrontendCore(CoreInitArgs args) { if (dir_info.exists() && dir_info.isDir() && dir_info.isReadable() && dir_info.isWritable()) { args.db_path = dir_info.absoluteFilePath(); - GF_CORE_LOG_INFO("using key database path: {}", - args.db_path); } else { - GF_CORE_LOG_ERROR( - "custom key database path: {}, is not point to " - "an accessible directory", - key_database_fs_path); + qCWarning(core) + << "custom key database path: " << key_database_fs_path + << ", is not point to " + "an accessible directory"; } } @@ -404,7 +376,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { // exit if failed if (!ctx.Good()) { - GF_CORE_LOG_ERROR("default gnupg context init error, abort"); + qCWarning(core, "default gnupg context init error, abort"); CoreSignalStation::GetInstance()->SignalBadGnupgEnv( QCoreApplication::tr("GpgME Context initiation failed")); return -1; @@ -415,11 +387,12 @@ void InitGpgFrontendCore(CoreInitArgs args) { if (args.load_default_gpg_context) { if (!GpgKeyGetter::GetInstance().FlushKeyCache()) { CoreSignalStation::GetInstance()->SignalBadGnupgEnv( - QCoreApplication::tr("Gpg Key Detabase initiation failed")); + QCoreApplication::tr("Gpg Key Database initiation failed")); }; } - GF_CORE_LOG_DEBUG( + qCDebug( + core, "basic env checking finished, including gpgme, ctx, and key infos"); Module::UpsertRTValue("core", "env.state.basic", 1); diff --git a/src/core/GpgFrontendCore.cpp b/src/core/GpgFrontendCore.cpp index 82ed09f4..ab589abc 100644 --- a/src/core/GpgFrontendCore.cpp +++ b/src/core/GpgFrontendCore.cpp @@ -27,3 +27,5 @@ */ #include "core/GpgFrontendCore.h" + +Q_LOGGING_CATEGORY(core, "core")
\ No newline at end of file diff --git a/src/core/GpgFrontendCore.h b/src/core/GpgFrontendCore.h index f07824cf..0310804c 100644 --- a/src/core/GpgFrontendCore.h +++ b/src/core/GpgFrontendCore.h @@ -30,3 +30,11 @@ // Qt #include <QtCore> + +// declare area of core +#ifdef GF_CORE + +// declare logging category +Q_DECLARE_LOGGING_CATEGORY(core) + +#endif
\ No newline at end of file diff --git a/src/core/function/ArchiveFileOperator.cpp b/src/core/function/ArchiveFileOperator.cpp index 475ef434..b3c0f21d 100644 --- a/src/core/function/ArchiveFileOperator.cpp +++ b/src/core/function/ArchiveFileOperator.cpp @@ -46,14 +46,14 @@ auto CopyData(struct archive *ar, struct archive *aw) -> int { r = archive_read_data_block(ar, &buff, &size, &offset); if (r == ARCHIVE_EOF) return (ARCHIVE_OK); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_read_data_block() failed: {}", - archive_error_string(ar)); + qCWarning(core) << "archive_read_data_block() failed: " + << archive_error_string(ar); return (r); } r = archive_write_data_block(aw, buff, size, offset); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_write_data_block() failed: {}", - archive_error_string(aw)); + qCWarning(core) << "archive_write_data_block() failed: " + << archive_error_string(aw); return (r); } } @@ -113,8 +113,8 @@ void ArchiveFileOperator::NewArchive2DataExchanger( #endif if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_read_disk_open() failed: {}, abort...", - archive_error_string(disk)); + qCWarning(core, "archive_read_disk_open() failed: %s, abort...", + archive_error_string(disk)); archive_read_free(disk); archive_write_free(archive); return -1; @@ -125,8 +125,9 @@ void ArchiveFileOperator::NewArchive2DataExchanger( r = archive_read_next_header2(disk, entry); if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR( - "archive_read_next_header2() failed, ret: {}, explain: {}", r, + qCWarning( + core, + "archive_read_next_header2() failed, ret: %d, explain: %s", r, archive_error_string(disk)); ret = -1; break; @@ -164,17 +165,17 @@ void ArchiveFileOperator::NewArchive2DataExchanger( r = archive_write_header(archive, entry); if (r < ARCHIVE_OK) { - GF_CORE_LOG_ERROR( - "archive_write_header() failed, ret: {}, explain: {} ", r, - archive_error_string(archive)); + qCWarning(core, + "archive_write_header() failed, ret: %d, explain: %s", + r, archive_error_string(archive)); continue; } if (r == ARCHIVE_FATAL) { - GF_CORE_LOG_ERROR( - "archive_write_header() failed, ret: {}, explain: {}, " - "abort ...", - r, archive_error_string(archive)); + qCWarning(core, + "archive_write_header() failed, ret: %d, explain: %s, " + "abort ...", + r, archive_error_string(archive)); ret = -1; break; } @@ -201,7 +202,6 @@ void ArchiveFileOperator::NewArchive2DataExchanger( void ArchiveFileOperator::ExtractArchiveFromDataExchanger( std::shared_ptr<GFDataExchanger> ex, const QString &target_path, const OperationCallback &cb) { - GF_CORE_LOG_INFO("target path: {}", target_path); RunIOOperaAsync( [=](const DataObjectPtr &data_object) -> GFError { auto *archive = archive_read_new(); @@ -209,17 +209,17 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( auto r = archive_read_support_filter_all(archive); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR( - "archive_read_support_filter_all(), ret: {}, reason: {}", r, - archive_error_string(archive)); + qCWarning(core, + "archive_read_support_filter_all(), ret: %d, reason: %s", r, + archive_error_string(archive)); return r; } r = archive_read_support_format_all(archive); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR( - "archive_read_support_format_all(), ret: {}, reason: {}", r, - archive_error_string(archive)); + qCWarning(core, + "archive_read_support_format_all(), ret: %d, reason: %s", r, + archive_error_string(archive)); return r; } @@ -230,16 +230,16 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( nullptr); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_read_open(), ret: {}, reason: {}", r, - archive_error_string(archive)); + qCWarning(core, "archive_read_open(), ret: %d, reason: %s", r, + archive_error_string(archive)); return r; } r = archive_write_disk_set_options(ext, 0); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR( - "archive_write_disk_set_options(), ret: {}, reason: {}", r, - archive_error_string(archive)); + qCWarning(core, + "archive_write_disk_set_options(), ret: %d, reason: %s", r, + archive_error_string(archive)); return r; } @@ -248,8 +248,8 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( r = archive_read_next_header(archive, &entry); if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_read_next_header(), ret: {}, reason: {}", - r, archive_error_string(archive)); + qCWarning(core, "archive_read_next_header(), ret: %d, reason: %s", + r, archive_error_string(archive)); break; } @@ -267,8 +267,8 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( r = archive_write_header(ext, entry); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_write_header(), ret: {}, reason: {}", r, - archive_error_string(archive)); + qCWarning(core, "archive_write_header(), ret: %d, reason: %s", r, + archive_error_string(archive)); } else { r = CopyData(archive, ext); } @@ -276,13 +276,13 @@ void ArchiveFileOperator::ExtractArchiveFromDataExchanger( r = archive_read_free(archive); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_read_free(), ret: {}, reason: {}", r, - archive_error_string(archive)); + qCWarning(core, "archive_read_free(), ret: %d, reason: %s", r, + archive_error_string(archive)); } r = archive_write_free(ext); if (r != ARCHIVE_OK) { - GF_CORE_LOG_ERROR("archive_read_free(), ret: {}, reason: {}", r, - archive_error_string(archive)); + qCWarning(core, "archive_read_free(), ret: %d, reason: %s", r, + archive_error_string(archive)); } return 0; @@ -302,8 +302,8 @@ void ArchiveFileOperator::ListArchive(const QString &archive_path) { 10240); // Note 1 if (r != ARCHIVE_OK) return; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { - GF_CORE_LOG_DEBUG("File: {}", archive_entry_pathname(entry)); - GF_CORE_LOG_DEBUG("File Path: {}", archive_entry_pathname(entry)); + qCDebug(core, core, "File: %s", archive_entry_pathname(entry)); + qCDebug(core, core, "File Path: %s", archive_entry_pathname(entry)); archive_read_data_skip(a); // Note 2 } r = archive_read_free(a); // Note 3 diff --git a/src/core/function/CacheManager.cpp b/src/core/function/CacheManager.cpp index 4dd12f59..e71936fe 100644 --- a/src/core/function/CacheManager.cpp +++ b/src/core/function/CacheManager.cpp @@ -107,7 +107,6 @@ class CacheManager::Impl : public QObject { durable_cache_storage_.insert(key, value); if (!key_storage_.contains(key)) { - GF_CORE_LOG_DEBUG("register new key of cache", key); key_storage_.push_back(key); } @@ -126,8 +125,8 @@ class CacheManager::Impl : public QObject { return {}; } - auto LoadDurableCache(const QString& key, QJsonDocument default_value) - -> QJsonDocument { + auto LoadDurableCache(const QString& key, + QJsonDocument default_value) -> QJsonDocument { auto data_object_key = get_data_object_key(key); if (!durable_cache_storage_.exists(key)) { durable_cache_storage_.insert( @@ -165,7 +164,7 @@ class CacheManager::Impl : public QObject { * */ void slot_flush_cache_storage() { - GF_CORE_LOG_TRACE("write cache to file system..."); + qCDebug(core, "write cache to file system..."); for (const auto& cache : durable_cache_storage_.mirror()) { auto key = get_data_object_key(cache.first); @@ -216,7 +215,7 @@ class CacheManager::Impl : public QObject { * */ void load_all_cache_storage() { - GF_CORE_LOG_DEBUG("start to load all cache from file system"); + qCDebug(core, "start to load all cache from file system"); auto stored_data = GpgFrontend::DataObjectOperator::GetInstance().GetDataObject(drk_key_); @@ -259,9 +258,8 @@ auto CacheManager::LoadDurableCache(const QString& key) -> QJsonDocument { return p_->LoadDurableCache(key); } -auto CacheManager::LoadDurableCache(const QString& key, - QJsonDocument default_value) - -> QJsonDocument { +auto CacheManager::LoadDurableCache( + const QString& key, QJsonDocument default_value) -> QJsonDocument { return p_->LoadDurableCache(key, std::move(default_value)); } diff --git a/src/core/function/DataObjectOperator.cpp b/src/core/function/DataObjectOperator.cpp index cbf21f8e..dbf92cd1 100644 --- a/src/core/function/DataObjectOperator.cpp +++ b/src/core/function/DataObjectOperator.cpp @@ -36,7 +36,6 @@ namespace GpgFrontend { void DataObjectOperator::init_app_secure_key() { - GF_CORE_LOG_INFO("initializing application secure key..."); WriteFile(app_secure_key_path_, PassphraseGenerator::GetInstance().Generate(256).toUtf8()); QFile::setPermissions(app_secure_key_path_, @@ -50,8 +49,8 @@ DataObjectOperator::DataObjectOperator(int channel) QByteArray key; if (!ReadFile(app_secure_key_path_, key)) { - GF_CORE_LOG_ERROR("failed to read app secure key file: {}", - app_secure_key_path_); + qCWarning(core) << "failed to read app secure key file: " + << app_secure_key_path_; // unsafe mode key = {}; } @@ -85,8 +84,6 @@ auto DataObjectOperator::SaveDataObj(const QString& key, QAESEncryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO) .encode(value.toJson(), hash_key_); - GF_CORE_LOG_TRACE("saving data object {} to disk {} , size: {} bytes", - hash_obj_key, target_obj_path, encoded_data.size()); // recreate if not exists if (!QDir(app_data_objs_path_).exists()) { @@ -94,7 +91,7 @@ auto DataObjectOperator::SaveDataObj(const QString& key, } if (!WriteFile(target_obj_path, encoded_data)) { - GF_CORE_LOG_ERROR("failed to write data object to disk: {}", key); + qCWarning(core) << "failed to write data object to disk: " << key; } return key.isEmpty() ? hash_obj_key : QString(); } @@ -102,20 +99,19 @@ auto DataObjectOperator::SaveDataObj(const QString& key, auto DataObjectOperator::GetDataObject(const QString& key) -> std::optional<QJsonDocument> { try { - GF_CORE_LOG_TRACE("try to get data object from disk, key: {}", key); auto hash_obj_key = QCryptographicHash::hash(hash_key_ + key.toUtf8(), QCryptographicHash::Sha256) .toHex(); const auto obj_path = app_data_objs_path_ + "/" + hash_obj_key; if (!QFileInfo(obj_path).exists()) { - GF_CORE_LOG_WARN("data object not found from disk, key: {}", key); + qCWarning(core) << "data object not found from disk, key: " << key; return {}; } QByteArray encoded_data; if (!ReadFile(obj_path, encoded_data)) { - GF_CORE_LOG_ERROR("failed to read data object from disk, key: {}", key); + qCWarning(core) << "failed to read data object from disk, key: " << key; return {}; } @@ -124,11 +120,11 @@ auto DataObjectOperator::GetDataObject(const QString& key) auto decoded_data = encryption.removePadding(encryption.decode(encoded_data, hash_key_)); - GF_CORE_LOG_TRACE("data object has been decoded, key: {}, data: {}", key, - decoded_data); + return QJsonDocument::fromJson(decoded_data); } catch (...) { - GF_CORE_LOG_ERROR("failed to get data object, caught exception: {}", key); + qCWarning(core) << "failed to get data object:" << key + << " caught exception."; return {}; } } diff --git a/src/core/function/GlobalSettingStation.cpp b/src/core/function/GlobalSettingStation.cpp index 45ab11f9..e123f249 100644 --- a/src/core/function/GlobalSettingStation.cpp +++ b/src/core/function/GlobalSettingStation.cpp @@ -40,13 +40,11 @@ class GlobalSettingStation::Impl { * */ explicit Impl() noexcept { - GF_CORE_LOG_INFO("app path: {}", GetAppDir()); - GF_CORE_LOG_INFO("app working path: {}", working_path_); + qCInfo(core) << "app path: " << GetAppDir(); + qCInfo(core) << "app working path: " << working_path_; auto portable_file_path = working_path_ + "/PORTABLE.txt"; if (QFileInfo(portable_file_path).exists()) { - GF_CORE_LOG_INFO( - "dectected portable mode, reconfiguring config and data path..."); Module::UpsertRTValue("core", "env.state.portable", 1); app_data_path_ = working_path_; @@ -56,11 +54,11 @@ class GlobalSettingStation::Impl { portable_mode_ = true; } - GF_CORE_LOG_INFO("app data path: {}", app_data_path_); - GF_CORE_LOG_INFO("app log path: {}", app_log_path_); + qCInfo(core) << "app data path: " << app_data_path_; + qCInfo(core) << "app log path: " << app_log_path_; #ifdef WINDOWS - GF_CORE_LOG_INFO("app config path: {}", app_config_path_); + qCInfo(core) << "app config path: " << app_config_path_; #endif #ifdef WINDOWS diff --git a/src/core/function/KeyPackageOperator.cpp b/src/core/function/KeyPackageOperator.cpp index d185b0ef..d4642cf7 100644 --- a/src/core/function/KeyPackageOperator.cpp +++ b/src/core/function/KeyPackageOperator.cpp @@ -28,6 +28,7 @@ #include "KeyPackageOperator.h" +#include <qglobal.h> #include <qt-aes/qaesencryption.h> #include "core/function/KeyPackageOperator.h" @@ -44,7 +45,7 @@ namespace GpgFrontend { auto KeyPackageOperator::GeneratePassphrase(const QString& phrase_path, QString& phrase) -> bool { phrase = PassphraseGenerator::GetInstance().Generate(256); - GF_CORE_LOG_DEBUG("generated passphrase: {} bytes", phrase.size()); + qCDebug(core, "generated passphrase: %lld bytes", phrase.size()); return WriteFile(phrase_path, phrase.toUtf8()); } @@ -53,13 +54,11 @@ void KeyPackageOperator::GenerateKeyPackage(const QString& key_package_path, const KeyArgsList& keys, QString& phrase, bool secret, const OperationCallback& cb) { - GF_CORE_LOG_DEBUG("generating key package: {}", key_package_name); - GpgKeyImportExporter::GetInstance().ExportAllKeys( keys, secret, true, [=](GpgError err, const DataObjectPtr& data_obj) { if (CheckGpgError(err) != GPG_ERR_NO_ERROR) { - GF_LOG_ERROR("export keys error, reason: {}", - DescribeGpgErrCode(err).second); + qCWarning(core) << "export keys error, reason: " + << DescribeGpgErrCode(err).second; cb(-1, data_obj); return; } @@ -78,7 +77,6 @@ void KeyPackageOperator::GenerateKeyPackage(const QString& key_package_path, QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); auto encoded_data = encryption.encode(data, hash_key); - GF_CORE_LOG_DEBUG("writing key package, name: {}", key_package_name); cb(WriteFile(key_package_path, encoded_data) ? 0 : -1, TransferParams()); @@ -91,20 +89,18 @@ void KeyPackageOperator::ImportKeyPackage(const QString& key_package_path, const OperationCallback& cb) { RunOperaAsync( [=](const DataObjectPtr& data_object) -> GFError { - GF_CORE_LOG_DEBUG("importing key package: {}", key_package_path); - QByteArray encrypted_data; ReadFile(key_package_path, encrypted_data); if (encrypted_data.isEmpty()) { - GF_CORE_LOG_ERROR("failed to read key package: {}", key_package_path); + qCWarning(core) << "failed to read key package: " << key_package_path; return -1; }; QByteArray passphrase; ReadFile(phrase_path, passphrase); if (passphrase.size() != 256) { - GF_CORE_LOG_ERROR("passphrase size mismatch: {}", phrase_path); + qCWarning(core) << "passphrase size mismatch: " << phrase_path; return -1; } diff --git a/src/core/function/LoggerManager.cpp b/src/core/function/LoggerManager.cpp deleted file mode 100644 index c7088128..00000000 --- a/src/core/function/LoggerManager.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright (C) 2021 Saturneric <[email protected]> - * - * This file is part of GpgFrontend. - * - * GpgFrontend is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GpgFrontend is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. - * - * The initial version of the source code is inherited from - * the gpg4usb project, which is under GPL-3.0-or-later. - * - * All the source code of GpgFrontend was modified and released by - * Saturneric <[email protected]> starting on May 12, 2021. - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#include "LoggerManager.h" - -#include <spdlog/async.h> -#include <spdlog/common.h> -#include <spdlog/sinks/rotating_file_sink.h> -#include <spdlog/sinks/stdout_color_sinks.h> - -#include "core/function/GlobalSettingStation.h" - -namespace GpgFrontend { - -std::shared_ptr<spdlog::logger> LoggerManager::default_logger = nullptr; -spdlog::level::level_enum LoggerManager::default_log_level = - spdlog::level::debug; - -LoggerManager::LoggerManager(int channel) - : SingletonFunctionObject<LoggerManager>(channel) { - spdlog::init_thread_pool(1024, 2); - spdlog::flush_every(std::chrono::seconds(5)); -} - -LoggerManager::~LoggerManager() { -#ifdef WINDOWS - // Under VisualStudio, this must be called before main finishes to workaround - // a known VS issue - spdlog::drop_all(); - spdlog::shutdown(); -#endif - - if (default_logger) default_logger = nullptr; -} - -auto LoggerManager::GetLogger(const QString& id) - -> std::shared_ptr<spdlog::logger> { - auto m_it = logger_map_.find(id); - if (m_it == logger_map_.end()) return GetDefaultLogger(); - return m_it->second; -} - -auto LoggerManager::RegisterAsyncLogger(const QString& id, - spdlog::level::level_enum level) - -> std::shared_ptr<spdlog::logger> { - // get the log directory - auto log_file_path = - GlobalSettingStation::GetInstance().GetLogDir() + "/" + id + ".log"; - - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::stderr_color_sink_mt>()); - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::rotating_file_sink_mt>( - log_file_path.toUtf8().constData(), 1048576 * 32, 8)); - - // logger - auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::async_logger>( - id.toStdString(), begin(sinks), end(sinks), spdlog::thread_pool()); - logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - logger->set_level(level); - - // flush policy -#ifdef DEBUG - logger->flush_on(spdlog::level::trace); -#else - logger->flush_on(spdlog::level::err); -#endif - - logger_map_[id] = logger; - return logger; -} - -auto LoggerManager::RegisterSyncLogger(const QString& id, - spdlog::level::level_enum level) - -> std::shared_ptr<spdlog::logger> { - // get the log directory - auto log_file_path = - GlobalSettingStation::GetInstance().GetLogDir() + "/" + id + ".log"; - - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::stderr_color_sink_mt>()); - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::rotating_file_sink_mt>( - log_file_path.toUtf8().constData(), 1048576 * 32, 8)); - - // logger - auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::logger>( - id.toStdString(), begin(sinks), end(sinks)); - logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - logger->set_level(level); - - logger_map_[id] = logger; - return logger; -} - -auto LoggerManager::GetDefaultLogger() -> std::shared_ptr<spdlog::logger> { - if (default_logger == nullptr) { - // sinks - std::vector<spdlog::sink_ptr> sinks; - sinks.push_back(GpgFrontend::SecureCreateSharedObject< - spdlog::sinks::stderr_color_sink_mt>()); - - // logger - auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::logger>( - "default", begin(sinks), end(sinks)); - logger->set_pattern( - "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); - - // set the level of logger - logger->set_level(default_log_level); - spdlog::set_default_logger(logger); - default_logger = logger; - } - return default_logger; -} - -void LoggerManager::SetDefaultLogLevel(spdlog::level::level_enum level) { - default_log_level = level; -} -} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/LoggerManager.h b/src/core/function/LoggerManager.h deleted file mode 100644 index 78fecc3c..00000000 --- a/src/core/function/LoggerManager.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (C) 2021 Saturneric <[email protected]> - * - * This file is part of GpgFrontend. - * - * GpgFrontend is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GpgFrontend is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. - * - * The initial version of the source code is inherited from - * the gpg4usb project, which is under GPL-3.0-or-later. - * - * All the source code of GpgFrontend was modified and released by - * Saturneric <[email protected]> starting on May 12, 2021. - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#pragma once - -#include "core/function/basic/GpgFunctionObject.h" - -namespace spdlog { -class logger; -} - -namespace GpgFrontend { - -class GPGFRONTEND_CORE_EXPORT LoggerManager - : public SingletonFunctionObject<LoggerManager> { - public: - explicit LoggerManager(int channel); - - ~LoggerManager() override; - - auto RegisterAsyncLogger(const QString& id, spdlog::level::level_enum) - -> std::shared_ptr<spdlog::logger>; - - auto RegisterSyncLogger(const QString& id, spdlog::level::level_enum) - -> std::shared_ptr<spdlog::logger>; - - auto GetLogger(const QString& id) -> std::shared_ptr<spdlog::logger>; - - static auto GetDefaultLogger() -> std::shared_ptr<spdlog::logger>; - - static void SetDefaultLogLevel(spdlog::level::level_enum); - - private: - static spdlog::level::level_enum default_log_level; - static std::shared_ptr<spdlog::logger> default_logger; - - std::map<QString, std::shared_ptr<spdlog::logger>> logger_map_; -}; - -} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/SecureMemoryAllocator.h b/src/core/function/SecureMemoryAllocator.h index e86d54d6..77295f53 100644 --- a/src/core/function/SecureMemoryAllocator.h +++ b/src/core/function/SecureMemoryAllocator.h @@ -29,7 +29,6 @@ #pragma once #include "core/GpgFrontendCoreExport.h" -#include "core/utils/LogUtils.h" namespace GpgFrontend { diff --git a/src/core/function/basic/ChannelObject.cpp b/src/core/function/basic/ChannelObject.cpp index 18449ddb..1d9d60b5 100644 --- a/src/core/function/basic/ChannelObject.cpp +++ b/src/core/function/basic/ChannelObject.cpp @@ -39,7 +39,7 @@ ChannelObject::ChannelObject(int channel, QString type) #ifdef DEBUG ChannelObject::~ChannelObject() noexcept { - // using iostream instead of spdlog bacause at this time spdlog may have + // using iostream instead of log bacause at this time log object may have // already been destroyed. QTextStream(stdout) << "releasing channel object: " << this->type_ << Qt::endl; diff --git a/src/core/function/basic/GpgFunctionObject.cpp b/src/core/function/basic/GpgFunctionObject.cpp index e9e444f1..2e531c15 100644 --- a/src/core/function/basic/GpgFunctionObject.cpp +++ b/src/core/function/basic/GpgFunctionObject.cpp @@ -44,8 +44,8 @@ std::mutex g_function_object_mutex_map_lock; std::map<size_t, FunctionObjectTypeLockInfo> g_function_object_mutex_map; namespace GpgFrontend { -auto GetGlobalFunctionObjectChannelLock(const std::type_info& type, int channel) - -> std::mutex& { +auto GetGlobalFunctionObjectChannelLock(const std::type_info& type, + int channel) -> std::mutex& { std::lock_guard<std::mutex> lock_guard(g_function_object_mutex_map_lock); auto& channel_map = g_function_object_mutex_map[type.hash_code()]; return channel_map.channel_lock_map[channel]; @@ -64,24 +64,17 @@ auto GetGlobalFunctionObjectTypeLock(const std::type_info& type) * @param channel * @return T& */ -auto GetChannelObjectInstance(const std::type_info& type, int channel) - -> ChannelObject* { - GF_DEFAULT_LOG_TRACE("try to get instance of type: {} at channel: {}", - type.name(), channel); - +auto GetChannelObjectInstance(const std::type_info& type, + int channel) -> ChannelObject* { // lock this channel std::lock_guard<std::mutex> guard( GetGlobalFunctionObjectChannelLock(type, channel)); auto* p_storage = SingletonStorageCollection::GetInstance(false)->GetSingletonStorage(type); - GF_DEFAULT_LOG_TRACE("get singleton storage result, p_storage: {}", - static_cast<void*>(p_storage)); auto* p_pbj = static_cast<ChannelObject*>(p_storage->FindObjectInChannel(channel)); - GF_DEFAULT_LOG_TRACE("find channel object result, channel {}, p_pbj: {}", - channel, static_cast<void*>(p_pbj)); return p_pbj; } @@ -95,8 +88,6 @@ auto CreateChannelObjectInstance(const std::type_info& type, int channel, auto* p_storage = SingletonStorageCollection::GetInstance(false)->GetSingletonStorage(type); - GF_DEFAULT_LOG_TRACE("create channel object, channel {}, type: {}", channel, - type.name()); // do create object of this channel return p_storage->SetObjectInChannel(channel, std::move(channel_object)); diff --git a/src/core/function/basic/SingletonStorage.cpp b/src/core/function/basic/SingletonStorage.cpp index eab71e0f..fd583820 100644 --- a/src/core/function/basic/SingletonStorage.cpp +++ b/src/core/function/basic/SingletonStorage.cpp @@ -53,8 +53,7 @@ class SingletonStorage::Impl { std::shared_lock<std::shared_mutex> lock(instances_mutex_); ins_it = instances_map_.find(channel); if (ins_it == instances_map_.end()) { - GF_DEFAULT_LOG_TRACE("cannot find channel object, channel: {}", - channel); + qCDebug(core, "cannot find channel object, channel: %d", channel); return nullptr; } return ins_it->second.get(); @@ -72,14 +71,14 @@ class SingletonStorage::Impl { auto SetObjectInChannel(int channel, ChannelObjectPtr p_obj) -> GpgFrontend::ChannelObject* { - GF_DEFAULT_LOG_TRACE( - "set channel object, type: {} in channel: {}, address: {}", - typeid(p_obj.get()).name(), channel, static_cast<void*>(p_obj.get())); + qCDebug(core, "set channel object, type: %s in channel: %d, address: %p", + typeid(p_obj.get()).name(), channel, + static_cast<void*>(p_obj.get())); assert(p_obj != nullptr); if (p_obj == nullptr) { - GF_DEFAULT_LOG_ERROR( - "cannot set a nullptr as a channel obejct of channel: {}", channel); + qCWarning(core, "cannot set a nullptr as a channel object of channel: %d", + channel); return nullptr; } @@ -87,17 +86,16 @@ class SingletonStorage::Impl { auto* raw_obj = p_obj.get(); { - GF_DEFAULT_LOG_TRACE( - "register channel object to instances map, " - "channel: {}, address: {}", - channel, static_cast<void*>(p_obj.get())); + qCDebug(core, + "register channel object to instances map, " + "channel: %d, address: %p", + channel, static_cast<void*>(p_obj.get())); std::unique_lock<std::shared_mutex> lock(instances_mutex_); instances_map_[channel] = std::move(p_obj); } - GF_DEFAULT_LOG_TRACE( - "set channel: {} success, current channel object address: {}", channel, - static_cast<void*>(raw_obj)); + qCDebug(core, "set channel: %d success, current channel object address: %p", + channel, static_cast<void*>(raw_obj)); return raw_obj; } diff --git a/src/core/function/basic/SingletonStorageCollection.cpp b/src/core/function/basic/SingletonStorageCollection.cpp index c22b5242..1eee087a 100644 --- a/src/core/function/basic/SingletonStorageCollection.cpp +++ b/src/core/function/basic/SingletonStorageCollection.cpp @@ -49,9 +49,9 @@ class SingletonStorageCollection::Impl { static auto GetInstance(bool force_refresh) -> SingletonStorageCollection* { if (force_refresh || global_instance == nullptr) { global_instance = SecureCreateUniqueObject<SingletonStorageCollection>(); - GF_DEFAULT_LOG_TRACE( - "a new global singleton storage collection created, address: {}", - static_cast<void*>(global_instance.get())); + qCDebug(core, + "a new global singleton storage collection created, address: %p", + static_cast<void*>(global_instance.get())); } return global_instance.get(); } @@ -80,10 +80,6 @@ class SingletonStorageCollection::Impl { } if (ins_it == storages_map_.end()) { auto storage = SecureCreateUniqueObject<SingletonStorage>(); - GF_DEFAULT_LOG_TRACE( - "hash: {} created, singleton storage address: {} type_name: {}", - hash, static_cast<void*>(storage.get()), type_id.name()); - { std::unique_lock<std::shared_mutex> lock(storages_mutex_); storages_map_.insert({hash, std::move(storage)}); @@ -110,8 +106,9 @@ auto GpgFrontend::SingletonStorageCollection::GetInstance(bool force_refresh) } void SingletonStorageCollection::Destroy() { - GF_DEFAULT_LOG_TRACE( - "global singleton storage collection is about to destroy, address: {}", + qCDebug( + core, + "global singleton storage collection is about to destroy, address: %p", static_cast<void*>(global_instance.get())); return SingletonStorageCollection::Impl::Destroy(); } diff --git a/src/core/function/gpg/GpgAdvancedOperator.cpp b/src/core/function/gpg/GpgAdvancedOperator.cpp index cb8fec00..18b38460 100644 --- a/src/core/function/gpg/GpgAdvancedOperator.cpp +++ b/src/core/function/gpg/GpgAdvancedOperator.cpp @@ -39,10 +39,9 @@ void GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache( OperationCallback cb) { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", QString{}); - GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); + qCWarning(core, "cannot get valid gpgconf path from rt, abort."); cb(-1, TransferParams()); return; } @@ -51,7 +50,6 @@ void GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache( {gpgconf_path, QStringList{"--reload", "gpg-agent"}, [=](int exit_code, const QString & /*p_out*/, const QString & /*p_err*/) { - GF_CORE_LOG_DEBUG("gpgconf reload exit code: {}", exit_code); cb(exit_code == 0 ? 0 : -1, TransferParams()); }}); } @@ -60,10 +58,9 @@ void GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents( OperationCallback cb) { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", QString{}); - GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); + qCWarning(core, "cannot get valid gpgconf path from rt, abort."); cb(-1, TransferParams()); return; } @@ -71,7 +68,7 @@ void GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents( GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, QStringList{"--reload"}, [=](int exit_code, const QString &, const QString &) { - GF_CORE_LOG_DEBUG("gpgconf reload exit code: {}", exit_code); + qCDebug(core, "gpgconf reload exit code: %d", exit_code); cb(exit_code == 0 ? 0 : -1, TransferParams()); }}); } @@ -79,59 +76,53 @@ void GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents( void GpgFrontend::GpgAdvancedOperator::KillAllGpgComponents() { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", QString{}); - GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); + qCWarning(core, "cannot get valid gpgconf path from rt, abort."); return; } GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, QStringList{"--verbose", "--kill", "all"}, [=](int exit_code, const QString &p_out, const QString &p_err) { - GF_CORE_LOG_DEBUG("gpgconf --kill all command got exit code: {}", - exit_code); bool success = true; if (exit_code != 0) { success = false; - GF_CORE_LOG_ERROR( - "gpgconf execute error, process stderr: {}, process stdout: {}", - p_err, p_out); + qCWarning(core) << "gpgconf execute error, process stderr: " << p_err + << ", process stdout: " << p_out; return; } - GF_CORE_LOG_DEBUG("gpgconf --kill --all execute result: {}", success); + qCDebug(core, "gpgconf --kill --all execute result: %d", success); }}); } void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", QString{}); - GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); + qCWarning(core, "cannot get valid gpgconf path from rt, abort."); return; } GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, QStringList{"--verbose", "--kill", "all"}, [=](int exit_code, const QString &p_out, const QString &p_err) { - GF_CORE_LOG_DEBUG("gpgconf --kill all command got exit code: {}", - exit_code); + qCDebug(core, "gpgconf --kill all command got exit code: %d", + exit_code); bool success = true; if (exit_code != 0) { success = false; - GF_CORE_LOG_ERROR( - "gpgconf execute error, process stderr: {}, process stdout: {}", - p_err, p_out); + qCWarning(core) << "gpgconf execute error, process stderr: " << p_err + << ", process stdout: " << p_out; return; } - GF_CORE_LOG_DEBUG("gpgconf --kill --all execute result: {}", success); + qCDebug(core, "gpgconf --kill --all execute result: %d", success); if (!success) { - GF_CORE_LOG_ERROR( - "restart all component after core initilized failed"); + qCWarning(core, + "restart all component after core initilized failed"); Module::UpsertRTValue( "core", "gpg_advanced_operator.restart_gpg_components", false); return; @@ -150,10 +141,9 @@ void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() { void GpgFrontend::GpgAdvancedOperator::ResetConfigures(OperationCallback cb) { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gpgconf_path", QString{}); - GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); if (gpgconf_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); + qCWarning(core, "cannot get valid gpgconf path from rt, abort."); cb(-1, TransferParams()); return; } @@ -161,7 +151,7 @@ void GpgFrontend::GpgAdvancedOperator::ResetConfigures(OperationCallback cb) { GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, QStringList{"--apply-defaults"}, [=](int exit_code, const QString &, const QString &) { - GF_CORE_LOG_DEBUG("gpgconf apply-defaults exit code: {}", exit_code); + qCDebug(core, "gpgconf apply-defaults exit code: %d", exit_code); cb(exit_code == 0 ? 0 : -1, TransferParams()); }}); } @@ -174,14 +164,12 @@ void GpgFrontend::GpgAdvancedOperator::StartGpgAgent(OperationCallback cb) { const auto gpg_agent_path = Module::RetrieveRTValueTypedOrDefault<>( kGnuPGInfoGatheringModuleID, "gnupg.gpg_agent_path", QString{}); - GF_CORE_LOG_DEBUG("got gnupg agent path from rt: {}", gpg_agent_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( kGnuPGInfoGatheringModuleID, "gnupg.home_path", QString{}); - GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (gpg_agent_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid gpg agent path from rt, abort."); + qCWarning(core, "cannot get valid gpg agent path from rt, abort."); cb(-1, TransferParams()); return; } @@ -189,7 +177,7 @@ void GpgFrontend::GpgAdvancedOperator::StartGpgAgent(OperationCallback cb) { GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpg_agent_path, QStringList{"--homedir", home_path, "--daemon"}, [=](int exit_code, const QString &, const QString &) { - GF_CORE_LOG_DEBUG("gpgconf daemon exit code: {}", exit_code); + qCDebug(core, "gpgconf daemon exit code: %d", exit_code); cb(exit_code >= 0 ? 0 : -1, TransferParams()); }}); } @@ -202,14 +190,12 @@ void GpgFrontend::GpgAdvancedOperator::StartDirmngr(OperationCallback cb) { const auto dirmngr_path = Module::RetrieveRTValueTypedOrDefault<>( kGnuPGInfoGatheringModuleID, "gnupg.dirmngr_path", QString{}); - GF_CORE_LOG_DEBUG("got gnupg dirmngr path from rt: {}", dirmngr_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( kGnuPGInfoGatheringModuleID, "gnupg.home_path", QString{}); - GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (dirmngr_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid dirmngr path from rt, abort."); + qCWarning(core, "cannot get valid dirmngr path from rt, abort."); cb(-1, TransferParams()); return; } @@ -217,7 +203,7 @@ void GpgFrontend::GpgAdvancedOperator::StartDirmngr(OperationCallback cb) { GpgFrontend::GpgCommandExecutor::ExecuteSync( {dirmngr_path, QStringList{"--homedir", home_path, "--daemon"}, [=](int exit_code, const QString &, const QString &) { - GF_CORE_LOG_DEBUG("gpgconf daemon exit code: {}", exit_code); + qCDebug(core, "gpgconf daemon exit code: %d", exit_code); cb(exit_code >= 0 ? 0 : -1, TransferParams()); }}); } @@ -230,14 +216,12 @@ void GpgFrontend::GpgAdvancedOperator::StartKeyBoxd(OperationCallback cb) { const auto keyboxd_path = Module::RetrieveRTValueTypedOrDefault<>( kGnuPGInfoGatheringModuleID, "gnupg.keyboxd_path", QString{}); - GF_CORE_LOG_DEBUG("got gnupg keyboxd path from rt: {}", keyboxd_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( kGnuPGInfoGatheringModuleID, "gnupg.home_path", QString{}); - GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (keyboxd_path.isEmpty()) { - GF_CORE_LOG_ERROR("cannot get valid keyboxd path from rt, abort."); + qCWarning(core, "cannot get valid keyboxd path from rt, abort."); cb(-1, TransferParams()); return; } @@ -245,7 +229,7 @@ void GpgFrontend::GpgAdvancedOperator::StartKeyBoxd(OperationCallback cb) { GpgFrontend::GpgCommandExecutor::ExecuteSync( {keyboxd_path, QStringList{"--homedir", home_path, "--daemon"}, [=](int exit_code, const QString &, const QString &) { - GF_CORE_LOG_DEBUG("gpgconf daemon exit code: {}", exit_code); + qCDebug(core, "gpgconf daemon exit code: %d", exit_code); cb(exit_code >= 0 ? 0 : -1, TransferParams()); }}); } diff --git a/src/core/function/gpg/GpgBasicOperator.cpp b/src/core/function/gpg/GpgBasicOperator.cpp index 8b62aad0..d7106a33 100644 --- a/src/core/function/gpg/GpgBasicOperator.cpp +++ b/src/core/function/gpg/GpgBasicOperator.cpp @@ -251,10 +251,9 @@ void GpgBasicOperator::Sign(const KeyArgsList& signers, cb, "gpgme_op_sign", "2.1.0"); } -auto GpgBasicOperator::SignSync(const KeyArgsList& signers, - const GFBuffer& in_buffer, GpgSignMode mode, - bool ascii) - -> std::tuple<GpgError, DataObjectPtr> { +auto GpgBasicOperator::SignSync( + const KeyArgsList& signers, const GFBuffer& in_buffer, GpgSignMode mode, + bool ascii) -> std::tuple<GpgError, DataObjectPtr> { return RunGpgOperaSync( [=](const DataObjectPtr& data_object) -> GpgError { if (signers.empty()) return GPG_ERR_CANCELED; @@ -391,15 +390,14 @@ void GpgBasicOperator::SetSigners(const KeyArgsList& signers, bool ascii) { gpgme_signers_clear(ctx); for (const GpgKey& key : signers) { - GF_CORE_LOG_DEBUG("key fpr: {}", key.GetFingerprint()); + qCDebug(core) << "signer's key fpr: " << key.GetFingerprint(); if (key.IsHasActualSigningCapability()) { - GF_CORE_LOG_DEBUG("signer"); auto error = gpgme_signers_add(ctx, gpgme_key_t(key)); CheckGpgError(error); } } if (signers.size() != gpgme_signers_count(ctx_.DefaultContext())) - GF_CORE_LOG_DEBUG("not all signers added"); + qCDebug(core, "not all signers added"); } auto GpgBasicOperator::GetSigners(bool ascii) -> std::unique_ptr<KeyArgsList> { diff --git a/src/core/function/gpg/GpgCommandExecutor.cpp b/src/core/function/gpg/GpgCommandExecutor.cpp index 66c18ae1..5e0f3826 100644 --- a/src/core/function/gpg/GpgCommandExecutor.cpp +++ b/src/core/function/gpg/GpgCommandExecutor.cpp @@ -27,6 +27,8 @@ */ #include "GpgCommandExecutor.h" +#include <qglobal.h> + #include "core/model/DataObject.h" #include "core/module/Module.h" #include "core/thread/Task.h" @@ -41,18 +43,14 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) const auto &interact_function = context.int_func; const auto &cmd_executor_callback = context.cb_func; - const QString joined_argument = arguments.join(" "); - - GF_CORE_LOG_DEBUG("building task: called cmd {} arguments size: {}", cmd, - arguments.size()); - Thread::Task::TaskCallback result_callback = - [cmd, joined_argument](int /*rtn*/, const DataObjectPtr &data_object) { - GF_CORE_LOG_DEBUG( - "data object args count of cmd executor result callback: {}", - data_object->GetObjectSize()); + [cmd](int /*rtn*/, const DataObjectPtr &data_object) { + qCDebug(core, + "data object args count of cmd executor result callback: %ld", + data_object->GetObjectSize()); + if (!data_object->Check<int, QString, GpgCommandExecutorCallback>()) { - GF_CORE_LOG_ERROR("data object checking failed"); + qCWarning(core, "data object checking failed"); return; } @@ -61,22 +59,17 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) auto callback = ExtractParams<GpgCommandExecutorCallback>(data_object, 2); - // call callback - GF_CORE_LOG_DEBUG( - "calling custom callback from caller of cmd {} {}, " - "exit_code: {}", - cmd, joined_argument, exit_code); callback(exit_code, process_stdout, {}); }; Thread::Task::TaskRunnable runner = - [joined_argument](const DataObjectPtr &data_object) -> int { - GF_CORE_LOG_DEBUG("process runner called, data object size: {}", - data_object->GetObjectSize()); + [](const DataObjectPtr &data_object) -> int { + qCDebug(core, "process runner called, data object size: %lu", + data_object->GetObjectSize()); if (!data_object->Check<QString, QStringList, GpgCommandExecutorInteractor, GpgCommandExecutorCallback>()) { - GF_CORE_LOG_ERROR("data object checking failed"); + qCWarning(core, "data object checking failed"); return -1; } @@ -86,6 +79,7 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) auto interact_func = ExtractParams<GpgCommandExecutorInteractor>(data_object, 2); auto callback = ExtractParams<GpgCommandExecutorCallback>(data_object, 3); + const QString joined_argument = arguments.join(" "); // create process auto *cmd_process = new QProcess(); @@ -106,26 +100,23 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) QObject::connect( cmd_process, &QProcess::started, [cmd, joined_argument]() -> void { - GF_CORE_LOG_DEBUG( - "\n== Process Execute Started ==\nCommand: {}\nArguments: " - "{}\n========================", - cmd, joined_argument); + qCDebug(core) << "\n== Process Execute Started ==\nCommand: " << cmd + << "\nArguments: " << joined_argument + << " \n========================"; }); QObject::connect( cmd_process, &QProcess::readyReadStandardOutput, [interact_func, cmd_process]() { interact_func(cmd_process); }); - QObject::connect( - cmd_process, &QProcess::errorOccurred, - [=](QProcess::ProcessError error) { - GF_CORE_LOG_ERROR( - "caught error while executing command: {} {}, error: {}", cmd, - joined_argument, error); - }); + QObject::connect(cmd_process, &QProcess::errorOccurred, + [=](QProcess::ProcessError error) { + qCWarning(core) + << "caught error while executing command: " << cmd + << joined_argument << ", error:" << error; + }); - GF_CORE_LOG_DEBUG( - "\n== Process Execute Ready ==\nCommand: {}\nArguments: " - "{}\n========================", - cmd, joined_argument); + qCDebug(core) << "\n== Process Execute Ready ==\nCommand: " << cmd + << "\nArguments: " << joined_argument + << "\n========================"; cmd_process->start(); cmd_process->waitForFinished(); @@ -133,15 +124,13 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) QString process_stdout = cmd_process->readAllStandardOutput(); int exit_code = cmd_process->exitCode(); - GF_CORE_LOG_DEBUG( - "\n==== Process Execution Summary ====\n" - "Command: {}\n" - "Arguments: {}\n" - "Exit Code: {}\n" - "---- Standard Output ----\n" - "{}\n" - "===============================", - cmd, joined_argument, exit_code, process_stdout); + qCDebug(core) << "\n==== Process Execution Summary ====\n" + << "Command: " << cmd << "\n" + << "Arguments: " << joined_argument << "\n" + << "Exit Code: " << exit_code << "\n" + << "---- Standard Output ----\n" + << process_stdout << "\n" + << "==============================="; cmd_process->close(); cmd_process->deleteLater(); @@ -177,7 +166,7 @@ void GpgCommandExecutor::ExecuteSync(ExecuteContext context) { // to arvoid dead lock issue we need to check if current thread is the same as // target thread. if it is, we can't call exec() because it will block the // current thread. - GF_CORE_LOG_TRACE("blocking until gpg command finish..."); + qCDebug(core, "blocking until gpg command finish..."); // block until task finished // this is to keep reference vaild until task finished looper.exec(); @@ -185,9 +174,6 @@ void GpgCommandExecutor::ExecuteSync(ExecuteContext context) { void GpgCommandExecutor::ExecuteConcurrentlyAsync(ExecuteContexts contexts) { for (auto &context : contexts) { - const auto &cmd = context.cmd; - GF_CORE_LOG_INFO("gpg concurrently called cmd {}", cmd); - Thread::Task *task = BuildTaskFromExecCtx(context); if (context.task_runner != nullptr) { @@ -208,15 +194,15 @@ void GpgCommandExecutor::ExecuteConcurrentlySync(ExecuteContexts contexts) { for (auto &context : contexts) { const auto &cmd = context.cmd; - GF_CORE_LOG_DEBUG("gpg concurrently called cmd: {}", cmd); + qCDebug(core) << "gpg concurrently called cmd: " << cmd; Thread::Task *task = BuildTaskFromExecCtx(context); QObject::connect(task, &Thread::Task::SignalTaskEnd, [&]() { --remaining_tasks; - GF_CORE_LOG_DEBUG("remaining tasks: {}", remaining_tasks); + qCDebug(core, "remaining tasks: %lld", remaining_tasks); if (remaining_tasks <= 0) { - GF_CORE_LOG_DEBUG("no remaining task, quit"); + qCDebug(core, "no remaining task, quit"); looper.quit(); } }); @@ -232,7 +218,7 @@ void GpgCommandExecutor::ExecuteConcurrentlySync(ExecuteContexts contexts) { target_task_runner->PostTask(task); } - GF_CORE_LOG_TRACE("blocking until concurrent gpg commands finish..."); + qCDebug(core, "blocking until concurrent gpg commands finish..."); // block until task finished // this is to keep reference vaild until task finished looper.exec(); diff --git a/src/core/function/gpg/GpgContext.cpp b/src/core/function/gpg/GpgContext.cpp index 7dec318e..16898375 100644 --- a/src/core/function/gpg/GpgContext.cpp +++ b/src/core/function/gpg/GpgContext.cpp @@ -77,8 +77,8 @@ class GpgContext::Impl { [[nodiscard]] auto Good() const -> bool { return good_; } - auto SetPassphraseCb(const gpgme_ctx_t &ctx, gpgme_passphrase_cb_t cb) - -> bool { + auto SetPassphraseCb(const gpgme_ctx_t &ctx, + gpgme_passphrase_cb_t cb) -> bool { if (gpgme_get_pinentry_mode(ctx) != GPGME_PINENTRY_MODE_LOOPBACK) { if (CheckGpgError(gpgme_set_pinentry_mode( ctx, GPGME_PINENTRY_MODE_LOOPBACK)) != GPG_ERR_NO_ERROR) { @@ -130,26 +130,26 @@ class GpgContext::Impl { passphrase_info != nullptr ? passphrase_info : "", prev_was_bad != 0, ask_for_new)); - GF_CORE_LOG_DEBUG( - "custom passphrase cb called, uid: {}, info: {}, last_was_bad: {}", - uid_hint == nullptr ? "<empty>" : QString{uid_hint}, - passphrase_info == nullptr ? "<empty>" : QString{passphrase_info}, - prev_was_bad); + qCDebug(core) << "custom passphrase cb called, uid: " + << (uid_hint == nullptr ? "<empty>" : QString{uid_hint}) + << ", info: " + << (passphrase_info == nullptr ? "<empty>" + : QString{passphrase_info}) + << ", last_was_bad: " << prev_was_bad; QEventLoop looper; QObject::connect(CoreSignalStation::GetInstance(), &CoreSignalStation::SignalUserInputPassphraseCallback, &looper, &QEventLoop::quit); - emit CoreSignalStation::GetInstance()->SignalNeedUserInputPassphrase( - context); + emit CoreSignalStation::GetInstance() -> SignalNeedUserInputPassphrase( + context); looper.exec(); ResetCacheValue("PinentryContext"); auto passphrase = context->GetPassphrase().toStdString(); auto passpahrase_size = passphrase.size(); - GF_CORE_LOG_DEBUG("get passphrase from pinentry size: {}", - passpahrase_size); + qCDebug(core, "get passphrase from pinentry size: %lu", passpahrase_size); size_t res = 0; if (passpahrase_size > 0) { @@ -162,15 +162,15 @@ class GpgContext::Impl { res += gpgme_io_write(fd, "\n", 1); - GF_CORE_LOG_DEBUG("custom passphrase cd is about to return, res: {}", res); + qCDebug(core, "custom passphrase cd is about to return, res: %ld", res); return res == passpahrase_size + 1 ? 0 : gpgme_error_from_errno(GPG_ERR_CANCELED); } - static auto TestStatusCb(void *hook, const char *keyword, const char *args) - -> gpgme_error_t { - GF_CORE_LOG_DEBUG("keyword {}", keyword); + static auto TestStatusCb(void *hook, const char *keyword, + const char *args) -> gpgme_error_t { + qCDebug(core, "keyword %s", keyword); return GPG_ERR_NO_ERROR; } @@ -188,10 +188,11 @@ class GpgContext::Impl { const auto gpgme_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.version", QString{"0.0.0"}); - GF_CORE_LOG_DEBUG("got gpgme version version from rt: {}", gpgme_version); + qCDebug(core) << "got gpgme version version from rt: " << gpgme_version; if (gpgme_get_keylist_mode(ctx) == 0) { - GF_CORE_LOG_ERROR( + qCWarning( + core, "ctx is not a valid pointer, reported by gpgme_get_keylist_mode"); return false; } @@ -210,8 +211,8 @@ class GpgContext::Impl { const auto database_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.database_path", QString{}); - GF_CORE_LOG_DEBUG("ctx set engine info, db path: {}, app path: {}", - database_path, app_path); + qCDebug(core) << "ctx set engine info, db path: " << database_path + << ", app path: " << app_path; auto app_path_buffer = app_path.toUtf8(); auto database_path_buffer = database_path.toUtf8(); @@ -232,23 +233,22 @@ class GpgContext::Impl { assert(ctx != nullptr); if (args.custom_gpgconf && !args.custom_gpgconf_path.isEmpty()) { - GF_CORE_LOG_DEBUG("set custom gpgconf path: {}", - args.custom_gpgconf_path); + qCDebug(core) << "set custom gpgconf path: " << args.custom_gpgconf_path; auto err = gpgme_ctx_set_engine_info(ctx, GPGME_PROTOCOL_GPGCONF, args.custom_gpgconf_path.toUtf8(), nullptr); if (CheckGpgError(err) != GPG_ERR_NO_ERROR) { - GF_CORE_LOG_ERROR("set gpg context engine info error: {}", - DescribeGpgErrCode(err).second); + qCWarning(core) << "set gpg context engine info error: " + << DescribeGpgErrCode(err).second; return false; } } // set context offline mode - GF_CORE_LOG_DEBUG("gpg context: offline mode: {}", args_.offline_mode); - GF_CORE_LOG_DEBUG("gpg context: auto import missing key: {}", - args_.auto_import_missing_key); + qCDebug(core, "gpg context: offline mode: %d", args_.offline_mode); + qCDebug(core, "gpg context: auto import missing key: %d", + args_.auto_import_missing_key); gpgme_set_offline(ctx, args_.offline_mode ? 1 : 0); // set option auto import missing key @@ -260,19 +260,19 @@ class GpgContext::Impl { } if (!set_ctx_key_list_mode(ctx)) { - GF_CORE_LOG_DEBUG("set ctx key list mode failed"); + qCDebug(core, "set ctx key list mode failed"); return false; } // for unit test if (args_.test_mode) { if (!SetPassphraseCb(ctx, TestPassphraseCb)) { - GF_CORE_LOG_ERROR("set passphrase cb failed, test"); + qCWarning(core, "set passphrase cb failed, test"); return false; }; } else if (!args_.use_pinentry) { if (!SetPassphraseCb(ctx, CustomPassphraseCb)) { - GF_CORE_LOG_DEBUG("set passphrase cb failed, custom"); + qCDebug(core, "set passphrase cb failed, custom"); return false; } } @@ -283,7 +283,7 @@ class GpgContext::Impl { } if (!set_ctx_openpgp_engine_info(ctx)) { - GF_CORE_LOG_ERROR("set gpgme context openpgp engine info failed"); + qCWarning(core, "set gpgme context openpgp engine info failed"); return false; } @@ -293,15 +293,15 @@ class GpgContext::Impl { auto binary_ctx_initialize(const GpgContextInitArgs &args) -> bool { gpgme_ctx_t p_ctx; if (auto err = CheckGpgError(gpgme_new(&p_ctx)); err != GPG_ERR_NO_ERROR) { - GF_CORE_LOG_ERROR("get new gpg context error: {}", - DescribeGpgErrCode(err).second); + qCWarning(core) << "get new gpg context error: " + << DescribeGpgErrCode(err).second; return false; } assert(p_ctx != nullptr); binary_ctx_ref_ = p_ctx; if (!common_ctx_initialize(binary_ctx_ref_, args)) { - GF_CORE_LOG_ERROR("get new ctx failed, binary"); + qCWarning(core, "get new ctx failed, binary"); return false; } @@ -312,7 +312,7 @@ class GpgContext::Impl { auto default_ctx_initialize(const GpgContextInitArgs &args) -> bool { gpgme_ctx_t p_ctx; if (CheckGpgError(gpgme_new(&p_ctx)) != GPG_ERR_NO_ERROR) { - GF_CORE_LOG_ERROR("get new ctx failed, default"); + qCWarning(core, "get new ctx failed, default"); return false; } assert(p_ctx != nullptr); diff --git a/src/core/function/gpg/GpgContext.h b/src/core/function/gpg/GpgContext.h index 2a8f6fdd..0fcf3e43 100644 --- a/src/core/function/gpg/GpgContext.h +++ b/src/core/function/gpg/GpgContext.h @@ -40,7 +40,7 @@ namespace GpgFrontend { * */ struct GpgContextInitArgs { - QString db_path = {}; ///< + QString db_path; ///< bool test_mode = false; ///< bool offline_mode = false; ///< @@ -63,7 +63,7 @@ class GPGFRONTEND_CORE_EXPORT GpgContext explicit GpgContext(GpgContextInitArgs args, int channel); - virtual ~GpgContext() override; + ~GpgContext(); [[nodiscard]] auto Good() const -> bool; diff --git a/src/core/function/gpg/GpgFileOpera.cpp b/src/core/function/gpg/GpgFileOpera.cpp index ad506c4a..9ada4afa 100644 --- a/src/core/function/gpg/GpgFileOpera.cpp +++ b/src/core/function/gpg/GpgFileOpera.cpp @@ -69,10 +69,9 @@ void GpgFileOpera::EncryptFile(const KeyArgsList& keys, const QString& in_path, cb, "gpgme_op_encrypt", "2.1.0"); } -auto GpgFileOpera::EncryptFileSync(const KeyArgsList& keys, - const QString& in_path, bool ascii, - const QString& out_path) - -> std::tuple<GpgError, DataObjectPtr> { +auto GpgFileOpera::EncryptFileSync( + const KeyArgsList& keys, const QString& in_path, bool ascii, + const QString& out_path) -> std::tuple<GpgError, DataObjectPtr> { return RunGpgOperaSync( [=](const DataObjectPtr& data_object) -> GpgError { std::vector<gpgme_key_t> recipients(keys.begin(), keys.end()); @@ -111,7 +110,7 @@ void GpgFileOpera::EncryptDirectory(const KeyArgsList& keys, GpgData data_in(ex); GpgData data_out(out_path, false); - GF_CORE_LOG_DEBUG("encrypt directory start"); + qCDebug(core, "encrypt directory start"); auto* ctx = ascii ? ctx_.DefaultContext() : ctx_.BinaryContext(); auto err = CheckGpgError(gpgme_op_encrypt(ctx, recipients.data(), @@ -119,15 +118,14 @@ void GpgFileOpera::EncryptDirectory(const KeyArgsList& keys, data_in, data_out)); data_object->Swap({GpgEncryptResult(gpgme_op_encrypt_result(ctx))}); - GF_CORE_LOG_DEBUG("encrypt directory finished, err: {}", err); + qCDebug(core, "encrypt directory finished, err: %d", err); return err; }, cb, "gpgme_op_encrypt", "2.1.0"); ArchiveFileOperator::NewArchive2DataExchanger( in_path, ex, [=](GFError err, const DataObjectPtr&) { - GF_CORE_LOG_DEBUG("new archive 2 data exchanger operation, err: {}", - err); + qCDebug(core, "new archive 2 data exchanger operation, err: %d", err); if (decltype(ex) p_ex = w_ex.lock(); err < 0 && p_ex != nullptr) { ex->CloseWrite(); } @@ -176,8 +174,8 @@ void GpgFileOpera::DecryptArchive(const QString& in_path, ArchiveFileOperator::ExtractArchiveFromDataExchanger( ex, out_path, [](GFError err, const DataObjectPtr&) { - GF_CORE_LOG_DEBUG( - "extract archive from data exchanger operation, err: {}", err); + qCDebug(core, "extract archive from data exchanger operation, err: %d", + err); }); RunGpgOperaAsync( @@ -331,11 +329,10 @@ void GpgFileOpera::EncryptSignFile(const KeyArgsList& keys, cb, "gpgme_op_encrypt_sign", "2.1.0"); } -auto GpgFileOpera::EncryptSignFileSync(const KeyArgsList& keys, - const KeyArgsList& signer_keys, - const QString& in_path, bool ascii, - const QString& out_path) - -> std::tuple<GpgError, DataObjectPtr> { +auto GpgFileOpera::EncryptSignFileSync( + const KeyArgsList& keys, const KeyArgsList& signer_keys, + const QString& in_path, bool ascii, + const QString& out_path) -> std::tuple<GpgError, DataObjectPtr> { return RunGpgOperaSync( [=](const DataObjectPtr& data_object) -> GpgError { GpgError err; @@ -399,7 +396,7 @@ void GpgFileOpera::EncryptSignDirectory(const KeyArgsList& keys, ArchiveFileOperator::NewArchive2DataExchanger( in_path, ex, [=](GFError err, const DataObjectPtr&) { - GF_CORE_LOG_DEBUG("new archive 2 fd operation, err: {}", err); + qCDebug(core, "new archive 2 fd operation, err: %d", err); if (decltype(ex) p_ex = w_ex.lock(); err < 0 && p_ex != nullptr) { ex->CloseWrite(); } @@ -459,7 +456,7 @@ void GpgFileOpera::DecryptVerifyArchive(const QString& in_path, ArchiveFileOperator::ExtractArchiveFromDataExchanger( ex, out_path, [](GFError err, const DataObjectPtr&) { - GF_CORE_LOG_DEBUG("extract archive from ex operation, err: {}", err); + qCDebug(core, "extract archive from ex operation, err: %d", err); }); RunGpgOperaAsync( @@ -545,19 +542,18 @@ void GpgFileOpera::EncryptDerectorySymmetric(const QString& in_path, bool ascii, ArchiveFileOperator::NewArchive2DataExchanger( in_path, ex, [=](GFError err, const DataObjectPtr&) { - GF_CORE_LOG_DEBUG("new archive 2 fd operation, err: {}", err); + qCDebug(core, "new archive 2 fd operation, err: %d", err); }); } -auto GpgFileOpera::EncryptDerectorySymmetricSync(const QString& in_path, - bool ascii, - const QString& out_path) - -> std::tuple<GpgError, DataObjectPtr> { +auto GpgFileOpera::EncryptDerectorySymmetricSync( + const QString& in_path, bool ascii, + const QString& out_path) -> std::tuple<GpgError, DataObjectPtr> { auto ex = std::make_shared<GFDataExchanger>(kDataExchangerSize); ArchiveFileOperator::NewArchive2DataExchanger( in_path, ex, [=](GFError err, const DataObjectPtr&) { - GF_CORE_LOG_DEBUG("new archive 2 fd operation, err: {}", err); + qCDebug(core, "new archive 2 fd operation, err: %d", err); }); return RunGpgOperaSync( diff --git a/src/core/function/gpg/GpgKeyGetter.cpp b/src/core/function/gpg/GpgKeyGetter.cpp index 870e68b3..8b78b754 100644 --- a/src/core/function/gpg/GpgKeyGetter.cpp +++ b/src/core/function/gpg/GpgKeyGetter.cpp @@ -42,9 +42,7 @@ namespace GpgFrontend { class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { public: explicit Impl(int channel) - : SingletonFunctionObject<GpgKeyGetter::Impl>(channel) { - GF_CORE_LOG_DEBUG("called channel: {}", channel); - } + : SingletonFunctionObject<GpgKeyGetter::Impl>(channel) {} auto GetKey(const QString& fpr, bool use_cache) -> GpgKey { // find in cache first @@ -56,7 +54,8 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { gpgme_key_t p_key = nullptr; gpgme_get_key(ctx_.DefaultContext(), fpr.toUtf8(), &p_key, 1); if (p_key == nullptr) { - GF_CORE_LOG_WARN("GpgKeyGetter GetKey Private _p_key Null fpr", fpr); + qCWarning(core) << "GpgKeyGetter GetKey Private _p_key Null, fpr: " + << fpr; return GetPubkey(fpr, true); } return GpgKey(std::move(p_key)); @@ -72,7 +71,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { gpgme_key_t p_key = nullptr; gpgme_get_key(ctx_.DefaultContext(), fpr.toUtf8(), &p_key, 0); if (p_key == nullptr) - GF_CORE_LOG_WARN("GpgKeyGetter GetKey _p_key Null", fpr); + qCWarning(core) << "GpgKeyGetter GetKey _p_key Null, fpr: " << fpr; return GpgKey(std::move(p_key)); } @@ -109,8 +108,6 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { } auto FlushKeyCache() -> bool { - GF_CORE_LOG_DEBUG("flush key channel called, channel: {}", GetChannel()); - // clear the keys cache keys_cache_.clear(); keys_search_cache_.clear(); @@ -145,17 +142,12 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { } } - GF_CORE_LOG_DEBUG("flush key channel cache address: {} object address: {}", - static_cast<void*>(&keys_search_cache_), - static_cast<void*>(this)); - // for debug assert(CheckGpgError2ErrCode(err, GPG_ERR_EOF) == GPG_ERR_EOF); err = gpgme_op_keylist_end(ctx_.DefaultContext()); assert(CheckGpgError2ErrCode(err, GPG_ERR_EOF) == GPG_ERR_NO_ERROR); - GF_CORE_LOG_DEBUG("flush key channel done, channel: {}", GetChannel()); return true; } @@ -239,9 +231,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { GpgKeyGetter::GpgKeyGetter(int channel) : SingletonFunctionObject<GpgKeyGetter>(channel), - p_(SecureCreateUniqueObject<Impl>(channel)) { - GF_CORE_LOG_DEBUG("called channel: {}", channel); -} + p_(SecureCreateUniqueObject<Impl>(channel)) {} GpgKeyGetter::~GpgKeyGetter() = default; diff --git a/src/core/function/gpg/GpgKeyImportExporter.cpp b/src/core/function/gpg/GpgKeyImportExporter.cpp index ef8cb112..55953cb5 100644 --- a/src/core/function/gpg/GpgKeyImportExporter.cpp +++ b/src/core/function/gpg/GpgKeyImportExporter.cpp @@ -93,9 +93,6 @@ auto GpgKeyImportExporter::ExportKey(const GpgKey& key, bool secret, bool ascii, auto err = gpgme_op_export_keys(ctx, keys_array.data(), mode, data_out); if (gpgme_err_code(err) != GPG_ERR_NO_ERROR) return {}; - GF_CORE_LOG_DEBUG( - "operation of exporting a key finished, ascii: {}, read_bytes: {}", ascii, - gpgme_data_seek(data_out, 0, SEEK_END)); return {err, data_out.Read2GFBuffer()}; } @@ -127,10 +124,6 @@ void GpgKeyImportExporter::ExportKeys(const KeyArgsList& keys, bool secret, auto err = gpgme_op_export_keys(ctx, keys_array.data(), mode, data_out); if (gpgme_err_code(err) != GPG_ERR_NO_ERROR) return {}; - GF_CORE_LOG_DEBUG( - "operation of exporting keys finished, ascii: {}, read_bytes: {}", - ascii, gpgme_data_seek(data_out, 0, SEEK_END)); - data_object->Swap({data_out.Read2GFBuffer()}); return err; }, @@ -161,9 +154,6 @@ void GpgKeyImportExporter::ExportAllKeys(const KeyArgsList& keys, bool secret, auto err = gpgme_op_export_keys(ctx, keys_array.data(), mode, data_out); if (gpgme_err_code(err) != GPG_ERR_NO_ERROR) return {}; - GF_CORE_LOG_DEBUG( - "operation of exporting keys finished, ascii: {}, read_bytes: {}", - ascii, gpgme_data_seek(data_out, 0, SEEK_END)); auto buffer = data_out.Read2GFBuffer(); if (secret) { @@ -175,10 +165,6 @@ void GpgKeyImportExporter::ExportAllKeys(const KeyArgsList& keys, bool secret, data_out_secret); if (gpgme_err_code(err) != GPG_ERR_NO_ERROR) return {}; - GF_CORE_LOG_DEBUG( - "operation of exporting secret keys finished, " - "ascii: {}, read_bytes: {}", - ascii, gpgme_data_seek(data_out_secret, 0, SEEK_END)); buffer.Append(data_out_secret.Read2GFBuffer()); } diff --git a/src/core/function/gpg/GpgKeyManager.cpp b/src/core/function/gpg/GpgKeyManager.cpp index b5efe141..93a864ca 100644 --- a/src/core/function/gpg/GpgKeyManager.cpp +++ b/src/core/function/gpg/GpgKeyManager.cpp @@ -73,10 +73,9 @@ auto GpgFrontend::GpgKeyManager::RevSign( return true; } -auto GpgFrontend::GpgKeyManager::SetExpire(const GpgFrontend::GpgKey& key, - std::unique_ptr<GpgSubKey>& subkey, - std::unique_ptr<QDateTime>& expires) - -> bool { +auto GpgFrontend::GpgKeyManager::SetExpire( + const GpgFrontend::GpgKey& key, std::unique_ptr<GpgSubKey>& subkey, + std::unique_ptr<QDateTime>& expires) -> bool { unsigned long expires_time = 0; if (expires != nullptr) expires_time = expires->toSecsSinceEpoch(); @@ -95,81 +94,83 @@ auto GpgFrontend::GpgKeyManager::SetExpire(const GpgFrontend::GpgKey& key, auto GpgFrontend::GpgKeyManager::SetOwnerTrustLevel(const GpgKey& key, int trust_level) -> bool { if (trust_level < 0 || trust_level > 5) { - GF_CORE_LOG_ERROR("illegal owner trust level: {}", trust_level); + qCWarning(core, "illegal owner trust level: %d", trust_level); } - AutomatonNextStateHandler next_state_handler = [](AutomatonState state, - QString status, - QString args) { - GF_CORE_LOG_DEBUG("next_state_handler state: {}, gpg_status: {}, args: {}", - state, status, args); - auto tokens = args.split(' '); + AutomatonNextStateHandler next_state_handler = + [](AutomatonState state, QString status, QString args) { + qCDebug(core) << "next_state_handler state: " + << static_cast<unsigned int>(state) + << ", gpg_status: " << status << ", args: " << args; - switch (state) { - case AS_START: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_COMMAND; - } - return AS_ERROR; - case AS_COMMAND: - if (status == "GET_LINE" && args == "edit_ownertrust.value") { - return AS_VALUE; - } - return AS_ERROR; - case AS_VALUE: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_QUIT; - } else if (status == "GET_BOOL" && - args == "edit_ownertrust.set_ultimate.okay") { - return AS_REALLY_ULTIMATE; - } - return AS_ERROR; - case AS_REALLY_ULTIMATE: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_QUIT; - } - return AS_ERROR; - case AS_QUIT: - if (status == "GET_LINE" && args == "keyedit.save.okay") { - return AS_SAVE; - } - return AS_ERROR; - case AS_ERROR: - if (status == "GET_LINE" && args == "keyedit.prompt") { - return AS_QUIT; - } - return AS_ERROR; - default: - return AS_ERROR; - }; - }; + auto tokens = args.split(' '); - AutomatonActionHandler action_handler = - [trust_level](AutomatonHandelStruct& handler, AutomatonState state) { - GF_CORE_LOG_DEBUG("action_handler state: {}", state); switch (state) { + case AS_START: + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_COMMAND; + } + return AS_ERROR; case AS_COMMAND: - return QString("trust"); + if (status == "GET_LINE" && args == "edit_ownertrust.value") { + return AS_VALUE; + } + return AS_ERROR; case AS_VALUE: - handler.SetSuccess(true); - return QString::number(trust_level); + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_QUIT; + } else if (status == "GET_BOOL" && + args == "edit_ownertrust.set_ultimate.okay") { + return AS_REALLY_ULTIMATE; + } + return AS_ERROR; case AS_REALLY_ULTIMATE: - handler.SetSuccess(true); - return QString("Y"); + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_QUIT; + } + return AS_ERROR; case AS_QUIT: - return QString("quit"); - case AS_SAVE: - handler.SetSuccess(true); - return QString("Y"); - case AS_START: + if (status == "GET_LINE" && args == "keyedit.save.okay") { + return AS_SAVE; + } + return AS_ERROR; case AS_ERROR: - return QString(""); + if (status == "GET_LINE" && args == "keyedit.prompt") { + return AS_QUIT; + } + return AS_ERROR; default: - return QString(""); - } - return QString(""); + return AS_ERROR; + }; }; + AutomatonActionHandler action_handler = [trust_level]( + AutomatonHandelStruct& handler, + AutomatonState state) { + qCDebug(core, "action_handler state: %d", static_cast<unsigned int>(state)); + switch (state) { + case AS_COMMAND: + return QString("trust"); + case AS_VALUE: + handler.SetSuccess(true); + return QString::number(trust_level); + case AS_REALLY_ULTIMATE: + handler.SetSuccess(true); + return QString("Y"); + case AS_QUIT: + return QString("quit"); + case AS_SAVE: + handler.SetSuccess(true); + return QString("Y"); + case AS_START: + case AS_ERROR: + return QString(""); + default: + return QString(""); + } + return QString(""); + }; + auto key_fpr = key.GetFingerprint(); AutomatonHandelStruct handel_struct(key_fpr); handel_struct.SetHandler(next_state_handler, action_handler); @@ -185,21 +186,19 @@ auto GpgFrontend::GpgKeyManager::SetOwnerTrustLevel(const GpgKey& key, auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, const char* status, - const char* args, int fd) - -> gpgme_error_t { + const char* args, + int fd) -> gpgme_error_t { auto* handle_struct = static_cast<AutomatonHandelStruct*>(handle); QString status_s = status; QString args_s = args; - GF_CORE_LOG_DEBUG( - "cb start status: {}, args: {}, fd: {}, handle struct state: {}", - status_s, args_s, fd, handle_struct->CuurentStatus()); if (status_s == "KEY_CONSIDERED") { auto tokens = QString(args).split(' '); if (tokens.empty() || tokens[0] != handle_struct->KeyFpr()) { - GF_CORE_LOG_ERROR("handle struct key fpr {} mismatch token: {}, exit...", - handle_struct->KeyFpr(), tokens[0]); + qCWarning(core) << "handle struct key fpr " << handle_struct->KeyFpr() + << "mismatch token: " << tokens[0] << ", exit..."; + return -1; } @@ -207,13 +206,13 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, } if (status_s == "GOT_IT" || status_s.isEmpty()) { - GF_CORE_LOG_DEBUG("status GOT_IT, continue..."); + qCDebug(core, "status GOT_IT, continue..."); return 0; } AutomatonState next_state = handle_struct->NextState(status_s, args_s); if (next_state == AS_ERROR) { - GF_CORE_LOG_DEBUG("handle struct next state caught error, skipping..."); + qCDebug(core, "handle struct next state caught error, skipping..."); return GPG_ERR_FALSE; } @@ -224,8 +223,7 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, // set state and preform action handle_struct->SetStatus(next_state); Command cmd = handle_struct->Action(); - GF_CORE_LOG_DEBUG("handle struct action done, next state: {}, action cmd: {}", - next_state, cmd); + if (!cmd.isEmpty()) { auto btye_array = cmd.toUtf8(); gpgme_io_write(fd, btye_array, btye_array.size()); diff --git a/src/core/function/gpg/GpgKeyManager.h b/src/core/function/gpg/GpgKeyManager.h index 8b4d41b2..85dc6be5 100644 --- a/src/core/function/gpg/GpgKeyManager.h +++ b/src/core/function/gpg/GpgKeyManager.h @@ -105,7 +105,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyManager AS_ERROR, AS_QUIT, }; - + struct AutomatonHandelStruct; using AutomatonActionHandler = diff --git a/src/core/function/gpg/GpgKeyOpera.cpp b/src/core/function/gpg/GpgKeyOpera.cpp index 14d58a10..0205ea2f 100644 --- a/src/core/function/gpg/GpgKeyOpera.cpp +++ b/src/core/function/gpg/GpgKeyOpera.cpp @@ -61,7 +61,7 @@ void GpgKeyOpera::DeleteKeys(KeyIdArgsListPtr key_ids) { GPGME_DELETE_ALLOW_SECRET | GPGME_DELETE_FORCE)); assert(gpg_err_code(err) == GPG_ERR_NO_ERROR); } else { - GF_CORE_LOG_WARN("GpgKeyOpera DeleteKeys get key failed", tmp); + qCWarning(core) << "GpgKeyOpera DeleteKeys get key failed: " << tmp; } } } @@ -113,14 +113,12 @@ void GpgKeyOpera::GenerateRevokeCert(const GpgKey& key, output_path, "--gen-revoke", key.GetFingerprint()}, [=](int exit_code, const QString& p_out, const QString& p_err) { if (exit_code != 0) { - GF_CORE_LOG_ERROR( - "gnupg gen revoke execute error, process stderr: {}, process " - "stdout: {}", - p_err, p_out); + qCWarning(core) << "gnupg gen revoke execute error, process stderr: " + << p_err << ", process stdout: " << p_out; } else { - GF_CORE_LOG_DEBUG( - "gnupg gen revoke exit_code: {}, process stdout size: {}", - exit_code, p_out.size()); + qCDebug(core, + "gnupg gen revoke exit_code: %d, process stdout size: %lld", + exit_code, p_out.size()); } }, nullptr, @@ -128,7 +126,6 @@ void GpgKeyOpera::GenerateRevokeCert(const GpgKey& key, // Code From Gpg4Win while (proc->canReadLine()) { const QString line = QString::fromUtf8(proc->readLine()).trimmed(); - GF_CORE_LOG_DEBUG("line: {}", line); if (line == QLatin1String("[GNUPG:] GET_BOOL gen_revoke.okay")) { proc->write("y\n"); } else if (line == QLatin1String("[GNUPG:] GET_LINE " @@ -162,8 +159,8 @@ void GpgKeyOpera::GenerateKey(const std::shared_ptr<GenKeyInfo>& params, auto userid = params->GetUserid(); auto algo = params->GetAlgo() + params->GetKeySizeStr(); - GF_CORE_LOG_DEBUG("params: {} {}", params->GetAlgo(), - params->GetKeySizeStr()); + qCDebug(core) << "params: " << params->GetAlgo() + << params->GetKeySizeStr(); unsigned long expires = QDateTime::currentDateTime().secsTo(params->GetExpireTime()); @@ -178,8 +175,9 @@ void GpgKeyOpera::GenerateKey(const std::shared_ptr<GenKeyInfo>& params, if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("key generation args: {} {} {} {}", userid, algo, - expires, flags); + qCDebug(core) << "key generation args: " << userid << algo << expires + << flags; + err = gpgme_op_createkey(ctx.DefaultContext(), userid.toUtf8(), algo.toUtf8(), 0, expires, nullptr, flags); @@ -202,8 +200,8 @@ auto GpgKeyOpera::GenerateKeySync(const std::shared_ptr<GenKeyInfo>& params) auto userid = params->GetUserid(); auto algo = params->GetAlgo() + params->GetKeySizeStr(); - GF_CORE_LOG_DEBUG("params: {} {}", params->GetAlgo(), - params->GetKeySizeStr()); + qCDebug(core) << "params: " << params->GetAlgo() + << params->GetKeySizeStr(); unsigned long expires = QDateTime::currentDateTime().secsTo(params->GetExpireTime()); @@ -218,8 +216,9 @@ auto GpgKeyOpera::GenerateKeySync(const std::shared_ptr<GenKeyInfo>& params) if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("key generation args: {} {} {} {}", userid, algo, - expires, flags); + qCDebug(core) << "key generation args: " << userid << algo << expires + << flags; + err = gpgme_op_createkey(ctx.DefaultContext(), userid.toUtf8(), algo.toUtf8(), 0, expires, nullptr, flags); @@ -242,8 +241,8 @@ void GpgKeyOpera::GenerateSubkey(const GpgKey& key, [key, &ctx = ctx_, params](const DataObjectPtr& data_object) -> GpgError { if (!params->IsSubKey()) return GPG_ERR_CANCELED; - GF_CORE_LOG_DEBUG("generate subkey algo {}, key size {}", - params->GetAlgo(), params->GetKeySizeStr()); + qCDebug(core) << "generate subkey algo: " << params->GetAlgo() + << "key size: " << params->GetKeySizeStr(); auto algo = params->GetAlgo() + params->GetKeySizeStr(); unsigned long expires = @@ -257,8 +256,9 @@ void GpgKeyOpera::GenerateSubkey(const GpgKey& key, if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("subkey generation args: {} {} {} {}", key.GetId(), - algo, expires, flags); + qCDebug(core) << "subkey generation args: " << key.GetId() << algo + << expires << flags; + auto err = gpgme_op_createsubkey(ctx.DefaultContext(), static_cast<gpgme_key_t>(key), algo.toUtf8(), 0, expires, flags); @@ -281,8 +281,8 @@ auto GpgKeyOpera::GenerateSubkeySync(const GpgKey& key, [key, &ctx = ctx_, params](const DataObjectPtr& data_object) -> GpgError { if (!params->IsSubKey()) return GPG_ERR_CANCELED; - GF_CORE_LOG_DEBUG("generate subkey algo {} key size {}", - params->GetAlgo(), params->GetKeySizeStr()); + qCDebug(core) << "generate subkey algo: " << params->GetAlgo() + << " key size: " << params->GetKeySizeStr(); auto algo = params->GetAlgo() + params->GetKeySizeStr(); unsigned long expires = @@ -296,8 +296,7 @@ auto GpgKeyOpera::GenerateSubkeySync(const GpgKey& key, if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("args: {} {} {} {}", key.GetId(), algo, expires, - flags); + qCDebug(core) << " args: " << key.GetId() << algo << expires << flags; auto err = gpgme_op_createsubkey(ctx.DefaultContext(), static_cast<gpgme_key_t>(key), @@ -337,8 +336,9 @@ void GpgKeyOpera::GenerateKeyWithSubkey( if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("key generation args: {}", userid, algo, expires, - flags); + qCDebug(core) << "key generation args: " << userid << algo << expires + << flags; + err = gpgme_op_createkey(ctx.DefaultContext(), userid, algo, 0, expires, nullptr, flags); @@ -358,16 +358,11 @@ void GpgKeyOpera::GenerateKeyWithSubkey( auto key = GpgKeyGetter::GetInstance().GetKey(genkey_result.GetFingerprint()); if (!key.IsGood()) { - GF_CORE_LOG_ERROR("cannot get key which has been generate, fpr: {}", - genkey_result.GetFingerprint()); + qCWarning(core) << "cannot get key which has been generate, fpr: " + << genkey_result.GetFingerprint(); return err; } - GF_CORE_LOG_DEBUG( - "try to generate subkey of key: {}, algo {} key size {}", - key.GetId(), subkey_params->GetAlgo(), - subkey_params->GetKeySizeStr()); - algo = (subkey_params->GetAlgo() + subkey_params->GetKeySizeStr()) .toUtf8(); expires = @@ -380,8 +375,8 @@ void GpgKeyOpera::GenerateKeyWithSubkey( if (subkey_params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (subkey_params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("subkey generation args: {} {} {} {}", key.GetId(), - algo, expires, flags); + qCDebug(core) << "subkey generation args: " << key.GetId() << algo + << expires << flags; err = gpgme_op_createsubkey(ctx.DefaultContext(), static_cast<gpgme_key_t>(key), algo, 0, @@ -422,8 +417,9 @@ auto GpgKeyOpera::GenerateKeyWithSubkeySync( if (params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("key generation args: {}", userid, algo, expires, - flags); + qCDebug(core) << "key generation args: " << userid << algo << expires + << flags; + err = gpgme_op_createkey(ctx.DefaultContext(), userid, algo, 0, expires, nullptr, flags); @@ -443,15 +439,14 @@ auto GpgKeyOpera::GenerateKeyWithSubkeySync( auto key = GpgKeyGetter::GetInstance().GetKey(genkey_result.GetFingerprint()); if (!key.IsGood()) { - GF_CORE_LOG_ERROR("cannot get key which has been generate, fpr: {}", - genkey_result.GetFingerprint()); + qCWarning(core) << "cannot get key which has been generate, fpr: " + << genkey_result.GetFingerprint(); return err; } - GF_CORE_LOG_DEBUG( - "try to generate subkey of key: {}, algo {} key size {}", - key.GetId(), subkey_params->GetAlgo(), - subkey_params->GetKeySizeStr()); + qCDebug(core) << "try to generate subkey of key: " << key.GetId() + << ", algo :" << subkey_params->GetAlgo() + << ", key size: " << subkey_params->GetKeySizeStr(); algo = (subkey_params->GetAlgo() + subkey_params->GetKeySizeStr()) .toUtf8(); @@ -465,8 +460,8 @@ auto GpgKeyOpera::GenerateKeyWithSubkeySync( if (subkey_params->IsNonExpired()) flags |= GPGME_CREATE_NOEXPIRE; if (subkey_params->IsNoPassPhrase()) flags |= GPGME_CREATE_NOPASSWD; - GF_CORE_LOG_DEBUG("subkey generation args: {} {} {} {}", key.GetId(), - algo, expires, flags); + qCDebug(core) << "subkey generation args: " << key.GetId() << algo + << expires << flags; err = gpgme_op_createsubkey(ctx.DefaultContext(), static_cast<gpgme_key_t>(key), algo, 0, @@ -495,15 +490,14 @@ void GpgKeyOpera::ModifyPassword(const GpgKey& key, callback, "gpgme_op_passwd", "2.0.15"); } -auto GpgKeyOpera::ModifyTOFUPolicy(const GpgKey& key, - gpgme_tofu_policy_t tofu_policy) - -> GpgError { +auto GpgKeyOpera::ModifyTOFUPolicy( + const GpgKey& key, gpgme_tofu_policy_t tofu_policy) -> GpgError { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", QString{"2.0.0"}); - GF_CORE_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); + qCDebug(core) << "got gnupg version from rt: " << gnupg_version; if (GFCompareSoftwareVersion(gnupg_version, "2.1.10") < 0) { - GF_CORE_LOG_ERROR("operator not support"); + qCWarning(core, "operator not support"); return GPG_ERR_NOT_SUPPORTED; } diff --git a/src/core/function/gpg/GpgUIDOperator.cpp b/src/core/function/gpg/GpgUIDOperator.cpp index 6c0373de..4477dd2f 100644 --- a/src/core/function/gpg/GpgUIDOperator.cpp +++ b/src/core/function/gpg/GpgUIDOperator.cpp @@ -48,17 +48,17 @@ auto GpgUIDOperator::RevUID(const GpgKey& key, const QString& uid) -> bool { return CheckGpgError(err) == GPG_ERR_NO_ERROR; } -auto GpgUIDOperator::SetPrimaryUID(const GpgKey& key, const QString& uid) - -> bool { +auto GpgUIDOperator::SetPrimaryUID(const GpgKey& key, + const QString& uid) -> bool { auto err = CheckGpgError(gpgme_op_set_uid_flag( ctx_.DefaultContext(), static_cast<gpgme_key_t>(key), uid.toUtf8(), "primary", nullptr)); return CheckGpgError(err) == GPG_ERR_NO_ERROR; } auto GpgUIDOperator::AddUID(const GpgKey& key, const QString& name, - const QString& comment, const QString& email) - -> bool { - GF_CORE_LOG_DEBUG("new uuid: {} {} {}", name, comment, email); + const QString& comment, + const QString& email) -> bool { + qCDebug(core) << "new uuid:" << name << comment << email; return AddUID(key, QString("%1(%2)<%3>").arg(name).arg(comment).arg(email)); } diff --git a/src/core/model/DataObject.h b/src/core/model/DataObject.h index 6b41a051..28678ca3 100644 --- a/src/core/model/DataObject.h +++ b/src/core/model/DataObject.h @@ -70,10 +70,6 @@ class GPGFRONTEND_CORE_EXPORT DataObject { for (size_t i = 0; i < type_list.size(); ++i) { if (std::type_index(*type_list[i]) != std::type_index((*this)[i].type())) { - GF_CORE_LOG_ERROR( - "value of index {} in data object is type: {}, " - "not expected type: {}", - i, ((*this)[i]).type().name(), type_list[i]->name()); return false; } } diff --git a/src/core/model/GFDataExchanger.cpp b/src/core/model/GFDataExchanger.cpp index abf79c6b..1ce03352 100644 --- a/src/core/model/GFDataExchanger.cpp +++ b/src/core/model/GFDataExchanger.cpp @@ -28,8 +28,6 @@ #include "GFDataExchanger.h" -#include "core/utils/LogUtils.h" - namespace GpgFrontend { auto GFDataExchanger::Write(const std::byte* buffer, size_t size) -> ssize_t { @@ -49,7 +47,8 @@ auto GFDataExchanger::Write(const std::byte* buffer, size_t size) -> ssize_t { write_bytes++; } } catch (...) { - GF_CORE_LOG_ERROR( + qCWarning( + core, "gf data exchanger caught exception when it writes to queue, abort..."); } diff --git a/src/core/model/GpgDecryptResult.cpp b/src/core/model/GpgDecryptResult.cpp index 3568bfd9..57a83656 100644 --- a/src/core/model/GpgDecryptResult.cpp +++ b/src/core/model/GpgDecryptResult.cpp @@ -55,9 +55,9 @@ auto GpgDecryptResult::Recipients() -> std::vector<GpgRecipient> { try { result.emplace_back(reci); } catch (...) { - GF_CORE_LOG_ERROR( - "caught exception when processing invalid_recipients, " - "maybe nullptr of fpr"); + qCWarning(core, + "caught exception when processing invalid_recipients, " + "maybe nullptr of fpr"); } } return result; diff --git a/src/core/model/GpgEncryptResult.cpp b/src/core/model/GpgEncryptResult.cpp index 843cf7eb..7017432b 100644 --- a/src/core/model/GpgEncryptResult.cpp +++ b/src/core/model/GpgEncryptResult.cpp @@ -55,9 +55,9 @@ auto GpgEncryptResult::InvalidRecipients() try { result.emplace_back(QString{invalid_key->fpr}, invalid_key->reason); } catch (...) { - GF_CORE_LOG_ERROR( - "caught exception when processing invalid_recipients, " - "maybe nullptr of fpr"); + qCWarning(core, + "caught exception when processing invalid_recipients, " + "maybe nullptr of fpr"); } } return result; diff --git a/src/core/model/GpgGenKeyInfo.cpp b/src/core/model/GpgGenKeyInfo.cpp index 157cbfbf..47451253 100644 --- a/src/core/model/GpgGenKeyInfo.cpp +++ b/src/core/model/GpgGenKeyInfo.cpp @@ -30,13 +30,10 @@ #include <cassert> -#include "core/utils/LogUtils.h" - namespace GpgFrontend { void GenKeyInfo::SetAlgo(const QString &t_algo_args) { auto algo_args = t_algo_args.toLower(); - GF_CORE_LOG_DEBUG("set algo args: {}", algo_args); // reset all options reset_options(); @@ -127,7 +124,7 @@ void GenKeyInfo::SetAlgo(const QString &t_algo_args) { suggest_size_addition_step_ = -1; SetKeyLength(-1); } else { - SPDLOG_ERROR("unsupported genkey algo arguments: {}", algo_args); + qCWarning(core) << "unsupported genkey algo arguments: " << algo_args; return; } diff --git a/src/core/model/GpgSignResult.cpp b/src/core/model/GpgSignResult.cpp index 4a0e5f35..50f6cfb7 100644 --- a/src/core/model/GpgSignResult.cpp +++ b/src/core/model/GpgSignResult.cpp @@ -55,9 +55,9 @@ auto GpgSignResult::InvalidSigners() try { result.emplace_back(QString{invalid_key->fpr}, invalid_key->reason); } catch (...) { - GF_CORE_LOG_ERROR( - "caught exception when processing invalid_signers, " - "maybe nullptr of fpr"); + qCWarning(core, + "caught exception when processing invalid_signers, " + "maybe nullptr of fpr"); } } return result; diff --git a/src/core/model/SettingsObject.cpp b/src/core/model/SettingsObject.cpp index 09824f12..48eb65ff 100644 --- a/src/core/model/SettingsObject.cpp +++ b/src/core/model/SettingsObject.cpp @@ -35,20 +35,17 @@ namespace GpgFrontend { SettingsObject::SettingsObject(QString settings_name) : settings_name_(std::move(settings_name)) { try { - GF_CORE_LOG_DEBUG("loading settings from: {}", this->settings_name_); auto json_optional = DataObjectOperator::GetInstance().GetDataObject(settings_name_); if (json_optional.has_value() && json_optional->isObject()) { - GF_CORE_LOG_DEBUG("settings object: {} loaded.", settings_name_); QJsonObject::operator=(json_optional.value().object()); } else { - GF_CORE_LOG_DEBUG("settings object: {} not found.", settings_name_); QJsonObject::operator=({}); } } catch (std::exception& e) { - GF_CORE_LOG_ERROR("load setting object error: {}", e.what()); + qCWarning(core) << "load setting object error: {}" << e.what(); } } diff --git a/src/core/module/Event.cpp b/src/core/module/Event.cpp index 4b0b989b..a1fd2fdc 100644 --- a/src/core/module/Event.cpp +++ b/src/core/module/Event.cpp @@ -42,7 +42,6 @@ class Event::Impl { for (const auto& param : params) { AddParameter(param); } - GF_CORE_LOG_DEBUG("create event {}", event_identifier_); } auto operator[](const QString& key) const -> std::optional<ParameterValue> { @@ -83,20 +82,16 @@ class Event::Impl { void ExecuteCallback(ListenerIdentifier listener_id, const DataObjectPtr& data_object) { - GF_CORE_LOG_DEBUG("try to execute callback for event {} with listener {}", - event_identifier_, listener_id); if (callback_) { - GF_CORE_LOG_DEBUG("executing callback for event {} with listener {}", - event_identifier_, listener_id); if (!QMetaObject::invokeMethod( callback_thread_, [callback = callback_, event_identifier = event_identifier_, listener_id, data_object]() { callback(event_identifier, listener_id, data_object); })) { - GF_CORE_LOG_ERROR( - "failed to invoke callback for event {} with listener {}", - event_identifier_, listener_id); + qCWarning(core) << "failed to invoke callback for event: " + << event_identifier_ + << " with listener:" << listener_id; } } } diff --git a/src/core/module/GlobalModuleContext.cpp b/src/core/module/GlobalModuleContext.cpp index e67e48f9..26c13a1b 100644 --- a/src/core/module/GlobalModuleContext.cpp +++ b/src/core/module/GlobalModuleContext.cpp @@ -54,8 +54,8 @@ class GlobalModuleContext::Impl { // Search for the module in the register table. auto module_info_opt = search_module_register_table(module_id); if (!module_info_opt.has_value()) { - GF_CORE_LOG_ERROR("cannot find module id {} at register table", - module_id); + qCWarning(core) << "cannot find module id " << module_id + << " at register table"; return nullptr; } @@ -67,11 +67,11 @@ class GlobalModuleContext::Impl { auto module_info_opt = search_module_register_table(module->GetModuleIdentifier()); if (!module_info_opt.has_value()) { - GF_CORE_LOG_ERROR( - "cannot find module id {} at register table, fallbacking to " - "default " - "channel", - module->GetModuleIdentifier()); + qCWarning(core) << "cannot find module id " + << module->GetModuleIdentifier() + << " at register table, fallback to " + "default channel"; + return GetDefaultChannel(module); } @@ -99,20 +99,17 @@ class GlobalModuleContext::Impl { } auto RegisterModule(const ModulePtr& module, bool integrated_module) -> bool { - GF_CORE_LOG_DEBUG("attempting to register module: {}", - module->GetModuleIdentifier()); // Check if the module is null or already registered. if (module == nullptr || module_register_table_.find(module->GetModuleIdentifier()) != module_register_table_.end()) { - GF_CORE_LOG_ERROR( - "module is null or have already registered this module"); + qCWarning(core, "module is null or have already registered this module"); return false; } if (module->Register() != 0) { - GF_CORE_LOG_ERROR("register module {} failed", - module->GetModuleIdentifier()); + qCWarning(core) << "register module " << module->GetModuleIdentifier() + << " failed"; return false; } @@ -132,19 +129,15 @@ class GlobalModuleContext::Impl { // Register the module with its identifier. module_register_table_[module->GetModuleIdentifier()] = register_info; - GF_CORE_LOG_DEBUG("successfully registered module: {}", - module->GetModuleIdentifier()); return true; } auto ActiveModule(ModuleIdentifier module_id) -> bool { - GF_CORE_LOG_DEBUG("attempting to activate module: {}", module_id); - // Search for the module in the register table. auto module_info_opt = search_module_register_table(module_id); if (!module_info_opt.has_value()) { - GF_CORE_LOG_ERROR("cannot find module id {} at register table", - module_id); + qCWarning(core) << "cannot find module id " << module_id + << " at register table"; return false; } @@ -153,9 +146,8 @@ class GlobalModuleContext::Impl { // try to get module from module info auto module = module_info->module; if (module == nullptr) { - GF_CORE_LOG_ERROR( - "module id {} at register table is releated to a null module", - module_id); + qCWarning(core) << "module id:" << module_id + << " at register table is related to a null module"; return false; } @@ -165,19 +157,15 @@ class GlobalModuleContext::Impl { module_info->activate = true; } - GF_CORE_LOG_DEBUG("module activation status: {}", module_info->activate); return module_info->activate; } auto ListenEvent(ModuleIdentifier module_id, EventIdentifier event) -> bool { - GF_CORE_LOG_DEBUG("module: {} is attempting to listen to event {}", - module_id, event); - // module -> event auto module_info_opt = search_module_register_table(module_id); if (!module_info_opt.has_value()) { - GF_CORE_LOG_ERROR("cannot find module id {} at register table", - module_id); + qCWarning(core) << "cannot find module id" << module_id + << "at register table"; return false; } @@ -186,7 +174,6 @@ class GlobalModuleContext::Impl { if (met_it == module_events_table_.end()) { module_events_table_[event] = std::unordered_set<ModuleIdentifier>(); met_it = module_events_table_.find(event); - GF_CORE_LOG_DEBUG("new event {} of module system created", event); } module_info_opt.value()->listening_event_ids.push_back(event); @@ -204,8 +191,8 @@ class GlobalModuleContext::Impl { // search for the module in the register table. auto module_info_opt = search_module_register_table(module_id); if (!module_info_opt.has_value()) { - GF_CORE_LOG_ERROR("cannot find module id {} at register table", - module_id); + qCWarning(core) << "cannot find module id " << module_id + << " at register table"; return false; } @@ -228,15 +215,13 @@ class GlobalModuleContext::Impl { auto TriggerEvent(const EventReference& event) -> bool { auto event_id = event->GetIdentifier(); - GF_CORE_LOG_DEBUG("attempting to trigger event: {}", event_id); // Find the set of listeners associated with the given event in the table auto met_it = module_events_table_.find(event_id); if (met_it == module_events_table_.end()) { // Log a warning if the event is not registered and nobody is listening - GF_CORE_LOG_WARN( - "event {} is not listening by anyone and not registered as well", - event_id); + qCInfo(core) << "event: " << event_id + << " is not listening by anyone and not registered as well."; return false; } @@ -246,15 +231,10 @@ class GlobalModuleContext::Impl { // Check if the set of listeners is empty if (listeners_set.empty()) { // Log a warning if nobody is listening to this event - GF_CORE_LOG_WARN("event {} is not listening by anyone", - event->GetIdentifier()); + qCInfo(core) << "event: " << event_id << " is not listening by anyone"; return false; } - // Log the number of listeners for this event - GF_CORE_LOG_DEBUG("event {}'s current listeners size: {}", - event->GetIdentifier(), listeners_set.size()); - // register trigger id index table module_on_triggering_events_table_[event->GetTriggerIdentifier()] = event; @@ -265,8 +245,8 @@ class GlobalModuleContext::Impl { // Log an error if the module is not found in the registration table if (!module_info_opt.has_value()) { - GF_CORE_LOG_ERROR("cannot find module id {} at register table", - listener_module_id); + qCWarning(core) << "cannot find module id: " << listener_module_id + << " at register table"; continue; } @@ -274,11 +254,6 @@ class GlobalModuleContext::Impl { auto module_info = module_info_opt.value(); auto module = module_info->module; - GF_CORE_LOG_DEBUG( - "module {} is listening to event {}, activate state: {}", - module_info->module->GetModuleIdentifier(), event->GetIdentifier(), - module_info->activate); - // Check if the module is activated if (!module_info->activate) continue; @@ -289,9 +264,9 @@ class GlobalModuleContext::Impl { [listener_module_id, event_id](int code, DataObjectPtr) { if (code < 0) { // Log an error if the module execution fails - GF_CORE_LOG_ERROR( - "module {} execution failed of event {}: exec return code {}", - listener_module_id, event_id, code); + qCWarning(core) << "module " << listener_module_id + << "execution failed of event " << event_id + << ": exec return code: " << code; } }; diff --git a/src/core/module/Module.cpp b/src/core/module/Module.cpp index 8faae4e0..ea2fea08 100644 --- a/src/core/module/Module.cpp +++ b/src/core/module/Module.cpp @@ -34,8 +34,6 @@ #include "sdk/GFSDKModule.h" #include "utils/BuildInfoUtils.h" - - namespace GpgFrontend::Module { class Module::Impl { @@ -61,9 +59,9 @@ class Module::Impl { *required_symbol.pointer = reinterpret_cast<void*>(module_library.resolve(required_symbol.name)); if (*required_symbol.pointer == nullptr) { - GF_CORE_LOG_WARN( - "illegal module: {}, reason: cannot load symbol: {}, abort...", - module_library.fileName(), required_symbol.name); + qCWarning(core) << "illegal module: " << module_library.fileName() + << ", reason cannot load symbol: " + << required_symbol.name << ", abort..."; return; } } @@ -74,39 +72,38 @@ class Module::Impl { qt_env_ver_ = GFUnStrDup(get_qt_ver_api_()); if (!module_identifier_regex_exp_.match(identifier_).hasMatch()) { - GF_CORE_LOG_WARN( - "illegal module: {}, reasson invalid module id, abort...", - identifier_); + qCWarning(core) << "illegal module: " << identifier_ + << ", reason invalid module id, abort..."; return; } if (!module_version_regex_exp_.match(version_).hasMatch()) { - GF_CORE_LOG_WARN( - "illegal module: {}, reasson invalid version: {}, abort...", - identifier_, version_); + qCWarning(core) << "illegal module: " << identifier_ + << ", reason invalid version: " << version_ + << ", abort..."; return; } if (!module_version_regex_exp_.match(gf_sdk_ver_).hasMatch()) { - GF_CORE_LOG_WARN( - "illegal module: {}, reasson invalid sdk version: {}, abort...", - identifier_, gf_sdk_ver_); + qCWarning(core) << "illegal module: " << identifier_ + << ", reason invalid sdk version: " << gf_sdk_ver_ + << ", abort..."; return; } if (GFCompareSoftwareVersion(gf_sdk_ver_, GetProjectVersion()) > 0) { - GF_CORE_LOG_WARN( - "uncompatible module: {}, sdk version: {} greater than " - "current sdk version: {}, abort...", - identifier_, gf_sdk_ver_, GetProjectVersion()); + qCWarning(core) << "uncompatible module: " << identifier_ + << ", reason sdk version: " << gf_sdk_ver_ + << "current sdk version: " << GetProjectVersion() + << ", abort..."; return; } auto qt_env_ver_regex_match = module_version_regex_exp_.match(qt_env_ver_); if (!qt_env_ver_regex_match.hasMatch()) { - GF_CORE_LOG_WARN( - "illegal module: {}, reasson invalid qt env version: {}, abort...", - identifier_, qt_env_ver_); + qCWarning(core) << "illegal module: " << identifier_ + << ", reason invalid qt env version: " << qt_env_ver_ + << ", abort..."; return; } @@ -115,19 +112,13 @@ class Module::Impl { if (qt_env_ver_major != QString::number(QT_VERSION_MAJOR) + "." || qt_env_ver_minor != QString::number(QT_VERSION_MINOR) + ".") { - GF_CORE_LOG_WARN( - "uncompatible module: {}, qt version: {} is not binary uncompatible " - "with application's qt env version: {}, abort...", - identifier_, qt_env_ver_, QString::fromUtf8(QT_VERSION_STR)); + qCWarning(core) << "uncompatible module: " << identifier_ + << ", reason sdk version: " << qt_env_ver_ + << "current sdk version: " + << QString::fromUtf8(QT_VERSION_STR) << ", abort..."; return; } - GF_CORE_LOG_INFO( - "module loaded, id: {}, version: {}, " - "sdk version: {}, qt env version: {}, hash: {}, path: {}", - identifier_, version_, gf_sdk_ver_, qt_env_ver_, module_hash_, - module_library_path_); - ::GFModuleMetaData* p_meta_data = get_metadata_api_(); while (p_meta_data != nullptr) { diff --git a/src/core/module/ModuleInit.cpp b/src/core/module/ModuleInit.cpp index cfeff3df..0e41e949 100644 --- a/src/core/module/ModuleInit.cpp +++ b/src/core/module/ModuleInit.cpp @@ -39,11 +39,8 @@ namespace GpgFrontend::Module { void LoadModuleFromPath(const QString& mods_path, bool integrated) { - for (const auto& module_library_name : - QDir(mods_path).entryList(QStringList() << "*.so" - << "*.dll" - << "*.dylib", - QDir::Files)) { + for (const auto& module_library_name : QDir(mods_path).entryList( + QStringList() << "*.so" << "*.dll" << "*.dylib", QDir::Files)) { ModuleManager::GetInstance().LoadModule( mods_path + "/" + module_library_name, integrated); } @@ -70,18 +67,15 @@ auto LoadIntegratedMods() -> bool { mods_path = "/app/modules"; } - GF_CORE_LOG_DEBUG("try loading integrated modules at path: {} ...", - mods_path); if (!QDir(mods_path).exists()) { - GF_CORE_LOG_WARN( - "integrated module directory at path {} not found, abort...", - mods_path); + qCWarning(core) << "integrated module directory at path " << mods_path + << " not found, abort..."; return false; } LoadModuleFromPath(mods_path, true); - GF_CORE_LOG_DEBUG("load integrated modules done."); + qCDebug(core, "load integrated modules done."); return true; } @@ -89,16 +83,14 @@ auto LoadExternalMods() -> bool { auto mods_path = GpgFrontend::GlobalSettingStation::GetInstance().GetModulesDir(); - GF_CORE_LOG_DEBUG("try loading external modules at path: {} ...", mods_path); if (!QDir(mods_path).exists()) { - GF_CORE_LOG_WARN("external module directory at path {} not found, abort...", - mods_path); + qCWarning(core) << "external module directory at path " << mods_path + << " not found, abort..."; return false; } LoadModuleFromPath(mods_path, false); - GF_CORE_LOG_DEBUG("load integrated modules done."); return true; } diff --git a/src/core/module/ModuleInit.h b/src/core/module/ModuleInit.h index e7e86f0f..c4f121ba 100644 --- a/src/core/module/ModuleInit.h +++ b/src/core/module/ModuleInit.h @@ -28,15 +28,11 @@ #pragma once -#include <spdlog/spdlog.h> - #include "core/GpgFrontendCoreExport.h" namespace GpgFrontend::Module { -struct ModuleInitArgs { - spdlog::level::level_enum log_level; -}; +struct ModuleInitArgs {}; /** * @brief init the module library diff --git a/src/core/module/ModuleManager.cpp b/src/core/module/ModuleManager.cpp index d07ca989..ad4f9ceb 100644 --- a/src/core/module/ModuleManager.cpp +++ b/src/core/module/ModuleManager.cpp @@ -60,19 +60,17 @@ class ModuleManager::Impl { [=](GpgFrontend::DataObjectPtr) -> int { QLibrary module_library(module_library_path); if (!module_library.load()) { - GF_CORE_LOG_WARN( - "module manager failed to load module, " - "reason: broken library: {} ", - module_library.fileName()); + qCWarning(core) << "module manager failed to load module, " + "reason: broken library: " + << module_library.fileName(); return -1; } auto module = SecureCreateSharedObject<Module>(module_library); if (!module->IsGood()) { - GF_CORE_LOG_WARN( - "module manager failed to load module, " - "reason: illegal module: {}", - module_library.fileName()); + qCWarning(core) << "module manager failed to load module, " + "reason: illegal module: " + << module_library.fileName(); return -1; } @@ -231,13 +229,13 @@ auto UpsertRTValue(const QString& namespace_, const QString& key, std::any(value)); } -auto ListenRTPublishEvent(QObject* o, Namespace n, Key k, LPCallback c) - -> bool { +auto ListenRTPublishEvent(QObject* o, Namespace n, Key k, + LPCallback c) -> bool { return ModuleManager::GetInstance().ListenRTPublish(o, n, k, c); } -auto ListRTChildKeys(const QString& namespace_, const QString& key) - -> std::vector<Key> { +auto ListRTChildKeys(const QString& namespace_, + const QString& key) -> std::vector<Key> { return ModuleManager::GetInstance().ListRTChildKeys(namespace_, key); } @@ -296,8 +294,8 @@ auto ModuleManager::UpsertRTValue(Namespace n, Key k, std::any v) -> bool { return p_->UpsertRTValue(n, k, v); } -auto ModuleManager::RetrieveRTValue(Namespace n, Key k) - -> std::optional<std::any> { +auto ModuleManager::RetrieveRTValue(Namespace n, + Key k) -> std::optional<std::any> { return p_->RetrieveRTValue(n, k); } @@ -306,8 +304,8 @@ auto ModuleManager::ListenRTPublish(QObject* o, Namespace n, Key k, return p_->ListenPublish(o, n, k, c); } -auto ModuleManager::ListRTChildKeys(const QString& n, const QString& k) - -> std::vector<Key> { +auto ModuleManager::ListRTChildKeys(const QString& n, + const QString& k) -> std::vector<Key> { return p_->ListRTChildKeys(n, k); } diff --git a/src/core/thread/FileReadTask.cpp b/src/core/thread/FileReadTask.cpp index 49a3f540..78cd99e9 100644 --- a/src/core/thread/FileReadTask.cpp +++ b/src/core/thread/FileReadTask.cpp @@ -41,17 +41,15 @@ FileReadTask::FileReadTask(QString path) auto FileReadTask::Run() -> int { if (QFileInfo(read_file_path_).isFile()) { - GF_CORE_LOG_DEBUG("read open file: {}", read_file_path_); - target_file_.setFileName(read_file_path_); target_file_.open(QIODevice::ReadOnly); if (!(target_file_.isOpen() && target_file_.isReadable())) { - GF_CORE_LOG_ERROR("file not open or not readable"); + qCWarning(core, "file not open or not readable"); if (target_file_.isOpen()) target_file_.close(); return -1; } - GF_CORE_LOG_DEBUG("started reading: {}", read_file_path_); + slot_read_bytes(); } else { emit SignalFileBytesReadEnd(); @@ -64,10 +62,8 @@ void FileReadTask::slot_read_bytes() { if (QByteArray read_buffer; !target_file_.atEnd() && (read_buffer = target_file_.read(kBufferSize)).size() > 0) { - GF_CORE_LOG_DEBUG("io thread read bytes: {}", read_buffer.size()); emit SignalFileBytesRead(std::move(read_buffer)); } else { - GF_CORE_LOG_DEBUG("io thread read bytes end"); emit SignalFileBytesReadEnd(); // announce finish task emit SignalTaskShouldEnd(0); @@ -75,7 +71,6 @@ void FileReadTask::slot_read_bytes() { } FileReadTask::~FileReadTask() { - GF_CORE_LOG_DEBUG("close file: {}", read_file_path_); if (target_file_.isOpen()) target_file_.close(); } diff --git a/src/core/thread/Task.cpp b/src/core/thread/Task.cpp index dc0cfe94..14818aca 100644 --- a/src/core/thread/Task.cpp +++ b/src/core/thread/Task.cpp @@ -38,7 +38,6 @@ class Task::Impl { public: Impl(Task *parent, QString name) : parent_(parent), uuid_(generate_uuid()), name_(std::move(name)) { - GF_CORE_LOG_TRACE("task {} created", GetFullID()); init(); } @@ -51,8 +50,6 @@ class Task::Impl { callback_([](int, const DataObjectPtr &) {}), callback_thread_(QThread::currentThread()), data_object_(std::move(data_object)) { - GF_CORE_LOG_TRACE("task {} created with runnable, callback_thread_: {}", - GetFullID(), static_cast<void *>(callback_thread_)); init(); } @@ -65,13 +62,10 @@ class Task::Impl { callback_(std::move(callback)), callback_thread_(QThread::currentThread()), data_object_(std::move(data_object)) { - GF_CORE_LOG_TRACE( - "task {} created with runnable and callback, callback_thread_: {}", - GetFullID(), static_cast<void *>(callback_thread_)); init(); } - ~Impl() { GF_CORE_LOG_TRACE("task {} destroyed", GetFullID()); } + ~Impl() = default; /** * @brief @@ -95,13 +89,7 @@ class Task::Impl { * @return int */ auto Run() -> int { - GF_CORE_LOG_TRACE("task {} is in classical runnable and callback mode", - GetFullID()); - if (runnable_) return runnable_(data_object_); - - GF_CORE_LOG_WARN("no runnable in task, do callback operation, task: {}", - GetFullID()); return 0; } @@ -137,9 +125,6 @@ class Task::Impl { DataObjectPtr data_object_ = nullptr; ///< void init() { - GF_CORE_LOG_TRACE("task {} created, parent: {}, impl: {}", name_, - static_cast<void *>(parent_), static_cast<void *>(this)); - // HoldOnLifeCycle(false); @@ -156,17 +141,11 @@ class Task::Impl { SetRTN(rtn); try { if (callback_) { - GF_CORE_LOG_TRACE( - "task callback {} is starting with runnerable rtn: {}", - GetFullID(), rtn); - callback_(rtn_, data_object_); - GF_CORE_LOG_TRACE("task callback {} finished, rtn: {}", - GetFullID(), rtn); } } catch (...) { - GF_CORE_LOG_ERROR("task {} callback caught exception, rtn: {}", - GetFullID(), rtn); + qCWarning(core) << "task: {}, " << GetFullID() + << "callback caught exception, rtn: " << rtn; } emit parent_->SignalTaskEnd(); }); @@ -214,11 +193,7 @@ void Task::SafelyRun() { emit SignalRun(); } int Task::Run() { return p_->Run(); } -void Task::run() { - GF_CORE_LOG_TRACE("interface run() of task {} was called by thread: {}", - GetFullID(), QThread::currentThread()->currentThreadId()); - this->SafelyRun(); -} +void Task::run() { this->SafelyRun(); } Task::TaskHandler::TaskHandler(Task *task) : task_(task) {} @@ -238,14 +213,11 @@ auto Task::TaskHandler::GetTask() -> Task * { void Task::slot_exception_safe_run() noexcept { auto rtn = p_->GetRTN(); try { - GF_CORE_LOG_TRACE("task runnable {} is starting...", GetFullID()); - // Run() will set rtn by itself rtn = this->Run(); - GF_CORE_LOG_TRACE("task runnable {} finished, rtn: {}", GetFullID()); } catch (...) { - GF_CORE_LOG_ERROR("exception was caught at task: {}", GetFullID()); + qCWarning(core) << "exception was caught at task: {}" << GetFullID(); } // raise signal to anounce after runnable returned diff --git a/src/core/thread/TaskRunner.cpp b/src/core/thread/TaskRunner.cpp index 8e381384..0837b7b8 100644 --- a/src/core/thread/TaskRunner.cpp +++ b/src/core/thread/TaskRunner.cpp @@ -38,21 +38,19 @@ class TaskRunner::Impl : public QThread { void PostTask(Task* task) { if (task == nullptr) { - GF_CORE_LOG_ERROR("task posted is null"); + qCWarning(core, "task posted is null"); return; } task->setParent(nullptr); task->moveToThread(this); - GF_CORE_LOG_TRACE("runner starts task: {} at thread: {}", task->GetFullID(), - this->currentThreadId()); task->SafelyRun(); } auto RegisterTask(const QString& name, const Task::TaskRunnable& runnerable, - const Task::TaskCallback& cb, DataObjectPtr params) - -> Task::TaskHandler { + const Task::TaskCallback& cb, + DataObjectPtr params) -> Task::TaskHandler { auto* raw_task = new Task(runnerable, name, std::move(params), cb); raw_task->setParent(nullptr); raw_task->moveToThread(this); @@ -65,9 +63,6 @@ class TaskRunner::Impl : public QThread { pending_tasks_.remove(raw_task->GetFullID()); }); - GF_CORE_LOG_TRACE("runner starts task: {} at thread: {}", - raw_task->GetFullID(), this->currentThreadId()); - return Task::TaskHandler(raw_task); } @@ -78,7 +73,7 @@ class TaskRunner::Impl : public QThread { void PostConcurrentTask(Task* task) { if (task == nullptr) { - GF_CORE_LOG_ERROR("task posted is null"); + qCWarning(core, "task posted is null"); return; } @@ -93,8 +88,6 @@ class TaskRunner::Impl : public QThread { concurrent_thread->start(); - GF_CORE_LOG_TRACE("runner starts task concurrenctly: {}", - task->GetFullID()); task->SafelyRun(); } @@ -143,8 +136,8 @@ auto TaskRunner::IsRunning() -> bool { return p_->isRunning(); } auto TaskRunner::RegisterTask(const QString& name, const Task::TaskRunnable& runnable, - const Task::TaskCallback& cb, DataObjectPtr p_pbj) - -> Task::TaskHandler { + const Task::TaskCallback& cb, + DataObjectPtr p_pbj) -> Task::TaskHandler { return p_->RegisterTask(name, runnable, cb, p_pbj); } } // namespace GpgFrontend::Thread diff --git a/src/core/utils/AsyncUtils.cpp b/src/core/utils/AsyncUtils.cpp index 3c007fb6..7d746bbc 100644 --- a/src/core/utils/AsyncUtils.cpp +++ b/src/core/utils/AsyncUtils.cpp @@ -42,12 +42,10 @@ auto RunGpgOperaAsync(const GpgOperaRunnable& runnable, -> Thread::Task::TaskHandler { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", minial_version); - GF_CORE_LOG_DEBUG("got gnupg version from rt: {}, operation: {}", - gnupg_version, operation); if (GFCompareSoftwareVersion(gnupg_version, minial_version) < 0) { - GF_CORE_LOG_ERROR("operaton {} not support for gnupg version: {}", - operation, gnupg_version); + qCWarning(core) << "operation" << operation + << " not support for gnupg version: " << gnupg_version; callback(GPG_ERR_NOT_SUPPORTED, TransferParams()); return Thread::Task::TaskHandler(nullptr); } @@ -82,12 +80,10 @@ auto RunGpgOperaSync(const GpgOperaRunnable& runnable, const QString& operation, -> std::tuple<GpgError, DataObjectPtr> { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", minial_version); - GF_CORE_LOG_DEBUG("got gnupg version from rt: {}, operation: {}", - gnupg_version, operation); if (GFCompareSoftwareVersion(gnupg_version, minial_version) < 0) { - GF_CORE_LOG_ERROR("operaton {} not support for gnupg version: {}", - operation, gnupg_version); + qCWarning(core) << "operation" << operation + << " not support for gnupg version: " << gnupg_version; return {GPG_ERR_NOT_SUPPORTED, TransferParams()}; } @@ -125,8 +121,8 @@ auto RunIOOperaAsync(const OperaRunnable& runnable, } auto RunOperaAsync(const OperaRunnable& runnable, - const OperationCallback& callback, const QString& operation) - -> Thread::Task::TaskHandler { + const OperationCallback& callback, + const QString& operation) -> Thread::Task::TaskHandler { auto handler = Thread::TaskRunnerGetter::GetInstance() .GetTaskRunner(Thread::TaskRunnerGetter::kTaskRunnerType_Default) diff --git a/src/core/utils/GpgUtils.cpp b/src/core/utils/GpgUtils.cpp index 0d00b13e..1d81b272 100644 --- a/src/core/utils/GpgUtils.cpp +++ b/src/core/utils/GpgUtils.cpp @@ -50,9 +50,9 @@ auto GetGpgmeErrorString(gpgme_error_t err) -> QString { auto CheckGpgError(GpgError err) -> GpgError { auto err_code = gpg_err_code(err); if (err_code != GPG_ERR_NO_ERROR) { - GF_CORE_LOG_ERROR( - "gpg operation failed [error code: {}], source: {} description: {}", - err_code, gpgme_strsource(err), GetGpgmeErrorString(err)); + qCWarning(core) << "gpg operation failed [error code: " << err_code + << "], source: " << gpgme_strsource(err) + << " description: " << GetGpgmeErrorString(err); } return err_code; } @@ -61,13 +61,15 @@ auto CheckGpgError2ErrCode(GpgError err, GpgError predict) -> GpgErrorCode { auto err_code = gpg_err_code(err); if (err_code != gpg_err_code(predict)) { if (err_code == GPG_ERR_NO_ERROR) { - GF_CORE_LOG_WARN("[Warning {}] Source: {} description: {} predict: {}", - gpg_err_code(err), gpgme_strsource(err), - GetGpgmeErrorString(err), GetGpgmeErrorString(predict)); + qCInfo(core) << "[Warning " << gpg_err_code(err) + << "] Source: " << gpgme_strsource(err) + << " description: " << GetGpgmeErrorString(err) + << " predict: " << GetGpgmeErrorString(predict); } else { - GF_CORE_LOG_ERROR("[Error {}] Source: {} description: {} predict: {}", - gpg_err_code(err), gpgme_strsource(err), - GetGpgmeErrorString(err), GetGpgmeErrorString(predict)); + qCWarning(core) << "[Error " << gpg_err_code(err) + << "] Source: " << gpgme_strsource(err) + << " description: " << GetGpgmeErrorString(err) + << " predict: " << GetGpgmeErrorString(predict); } } return err_code; @@ -79,8 +81,9 @@ auto DescribeGpgErrCode(GpgError err) -> GpgErrorDesc { auto CheckGpgError(GpgError err, const QString& /*comment*/) -> GpgError { if (gpg_err_code(err) != GPG_ERR_NO_ERROR) { - GF_CORE_LOG_WARN("[Error {}] Source: {} description: {}", gpg_err_code(err), - gpgme_strsource(err), GetGpgmeErrorString(err)); + qCWarning(core) << "[Error " << gpg_err_code(err) + << "] Source: " << gpgme_strsource(err) + << " description: " << GetGpgmeErrorString(err); } return err; } diff --git a/src/core/utils/IOUtils.cpp b/src/core/utils/IOUtils.cpp index 0be11755..409cff19 100644 --- a/src/core/utils/IOUtils.cpp +++ b/src/core/utils/IOUtils.cpp @@ -49,7 +49,7 @@ auto GetFileChecksum(const QString& file_name, auto ReadFile(const QString& file_name, QByteArray& data) -> bool { QFile file(file_name); if (!file.open(QIODevice::ReadOnly)) { - GF_CORE_LOG_ERROR("failed to open file: {}", file_name); + qCWarning(core) << "failed to open file: " << file_name; return false; } data = file.readAll(); @@ -60,7 +60,7 @@ auto ReadFile(const QString& file_name, QByteArray& data) -> bool { auto WriteFile(const QString& file_name, const QByteArray& data) -> bool { QFile file(file_name); if (!file.open(QIODevice::WriteOnly)) { - GF_CORE_LOG_ERROR("failed to open file for writing: {}", file_name); + qCWarning(core) << "failed to open file for writing: " << file_name; return false; } file.write(data); @@ -100,20 +100,17 @@ auto CalculateHash(const QString& file_path) -> QString { << Qt::endl; // md5 - ss << "- " - << "MD5" << QCoreApplication::tr(": ") + ss << "- " << "MD5" << QCoreApplication::tr(": ") << GetFileChecksum(file_path, QCryptographicHash::Md5).toHex() << Qt::endl; // sha1 - ss << "- " - << "SHA1" << QCoreApplication::tr(": ") + ss << "- " << "SHA1" << QCoreApplication::tr(": ") << GetFileChecksum(file_path, QCryptographicHash::Sha1).toHex() << Qt::endl; // sha1 - ss << "- " - << "SHA256" << QCoreApplication::tr(": ") + ss << "- " << "SHA256" << QCoreApplication::tr(": ") << GetFileChecksum(file_path, QCryptographicHash::Sha256).toHex() << Qt::endl; @@ -147,8 +144,8 @@ auto CreateTempFileAndWriteData(const GFBuffer& data) -> QString { return temp_file; } -auto TargetFilePreCheck(const QString& path, bool read) - -> std::tuple<bool, QString> { +auto TargetFilePreCheck(const QString& path, + bool read) -> std::tuple<bool, QString> { QFileInfo const file_info(path); if (read) { @@ -184,16 +181,16 @@ auto CalculateBinaryChacksum(const QString& path) -> QString { // check file info and access rights QFileInfo info(path); if (!info.exists() || !info.isFile() || !info.isReadable()) { - GF_CORE_LOG_ERROR("get info for file {} error, exists: {}", info.filePath(), - info.exists()); + qCWarning(core) << "get info for file: " << info.filePath() + << " error, exists: " << info.exists(); return {}; } // open and read file QFile f(info.filePath()); if (!f.open(QIODevice::ReadOnly)) { - GF_CORE_LOG_ERROR("open {} to calculate checksum error: {}", - path.toStdString(), f.errorString().toStdString()); + qCWarning(core) << "open " << path + << "to calculate checksum error: " << f.errorString(); return {}; } @@ -204,8 +201,8 @@ auto CalculateBinaryChacksum(const QString& path) -> QString { while (!f.atEnd()) { QByteArray const buffer = f.read(buffer_size); if (buffer.isEmpty()) { - GF_CORE_LOG_ERROR("error reading file {} during checksum calculation", - path.toStdString()); + qCWarning(core) << "error reading file: " << path + << " during checksum calculation"; return {}; } hash_sha.addData(buffer); diff --git a/src/core/utils/LocalizedUtils.cpp b/src/core/utils/LocalizedUtils.cpp index e5c9b434..f38b004b 100644 --- a/src/core/utils/LocalizedUtils.cpp +++ b/src/core/utils/LocalizedUtils.cpp @@ -28,8 +28,6 @@ #include "LocalizedUtils.h" -#include "core/utils/LogUtils.h" - namespace GpgFrontend { auto GetLocalizedDateByTimestamp(time_t timestamp) -> QString { diff --git a/src/core/utils/LogUtils.cpp b/src/core/utils/LogUtils.cpp deleted file mode 100644 index fbf0c8d3..00000000 --- a/src/core/utils/LogUtils.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (C) 2021 Saturneric <[email protected]> - * - * This file is part of GpgFrontend. - * - * GpgFrontend is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GpgFrontend is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. - * - * The initial version of the source code is inherited from - * the gpg4usb project, which is under GPL-3.0-or-later. - * - * All the source code of GpgFrontend was modified and released by - * Saturneric <[email protected]> starting on May 12, 2021. - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#include "LogUtils.h" - -#include "core/function/LoggerManager.h" - -namespace GpgFrontend { - -auto GetDefaultLogger() -> std::shared_ptr<spdlog::logger> { - return LoggerManager::GetDefaultLogger(); -} - -auto GetCoreLogger() -> std::shared_ptr<spdlog::logger> { - return LoggerManager::GetInstance().GetLogger("core"); -} - -auto GetLogger(const QString& id) -> std::shared_ptr<spdlog::logger> { - return LoggerManager::GetInstance().GetLogger(id); -} - -void SetDefaultLogLevel(spdlog::level::level_enum level) { - return LoggerManager::SetDefaultLogLevel(level); -} - -void RegisterAsyncLogger(const QString& id, spdlog::level::level_enum level) { - LoggerManager::GetInstance().RegisterAsyncLogger(id, level); -} - -void RegisterSyncLogger(const QString& id, spdlog::level::level_enum level) { - LoggerManager::GetInstance().RegisterSyncLogger(id, level); -} - -} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/LogUtils.h b/src/core/utils/LogUtils.h deleted file mode 100644 index e8dc6f3b..00000000 --- a/src/core/utils/LogUtils.h +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright (C) 2021 Saturneric <[email protected]> - * - * This file is part of GpgFrontend. - * - * GpgFrontend is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GpgFrontend is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. - * - * The initial version of the source code is inherited from - * the gpg4usb project, which is under GPL-3.0-or-later. - * - * All the source code of GpgFrontend was modified and released by - * Saturneric <[email protected]> starting on May 12, 2021. - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#pragma once - -// spdlog library configuration -#undef SPDLOG_ACTIVE_LEVEL -#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE -#include <spdlog/spdlog.h> - -// logger fmt -#include "core/GpgFrontendCoreExport.h" - -template <> -struct fmt::formatter<QString> { - // Parses format specifications. - constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - // Formats the QString qstr and writes it to the output. - template <typename FormatContext> - auto format(const QString& qstr, FormatContext& ctx) const - -> decltype(ctx.out()) { - // Convert QString to UTF-8 QString (to handle Unicode characters - // correctly) - QByteArray utf8_array = qstr.toUtf8(); - return fmt::format_to(ctx.out(), "{}", utf8_array.constData()); - } -}; - -template <> -struct fmt::formatter<QByteArray> { - // Parses format specifications. - constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - // Formats the QString qstr and writes it to the output. - template <typename FormatContext> - auto format(const QByteArray& qarray, FormatContext& ctx) const - -> decltype(ctx.out()) { - // Convert QString to UTF-8 QString (to handle Unicode characters - // correctly) - return fmt::format_to(ctx.out(), "{}", qarray.constData()); - } -}; - -namespace GpgFrontend { - -/** - * @brief - * - * @return std::shared_ptr<spdlog::logger> - */ -auto GPGFRONTEND_CORE_EXPORT GetDefaultLogger() - -> std::shared_ptr<spdlog::logger>; - -/** - * @brief - * - * @return std::shared_ptr<spdlog::logger> - */ -auto GPGFRONTEND_CORE_EXPORT GetCoreLogger() -> std::shared_ptr<spdlog::logger>; - -/** - * @brief - * - * @return std::shared_ptr<spdlog::logger> - */ -auto GPGFRONTEND_CORE_EXPORT GetLogger(const QString&) - -> std::shared_ptr<spdlog::logger>; - -/** - * @brief Set the Default Log Level object - * - * @return auto - */ -void GPGFRONTEND_CORE_EXPORT SetDefaultLogLevel(spdlog::level::level_enum); - -/** - * @brief - * - * @return auto - */ -void GPGFRONTEND_CORE_EXPORT RegisterAsyncLogger(const QString&, - spdlog::level::level_enum); - -/** - * @brief - * - * @return auto - */ -void GPGFRONTEND_CORE_EXPORT RegisterSyncLogger(const QString&, - spdlog::level::level_enum); - -} // namespace GpgFrontend - -#define GF_DEFAULT_LOG_TRACE(...) \ - SPDLOG_LOGGER_TRACE(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) -#define GF_DEFAULT_LOG_DEBUG(...) \ - SPDLOG_LOGGER_DEBUG(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) -#define GF_DEFAULT_LOG_INFO(...) \ - SPDLOG_LOGGER_INFO(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) -#define GF_DEFAULT_LOG_WARN(...) \ - SPDLOG_LOGGER_WARN(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) -#define GF_DEFAULT_LOG_ERROR(...) \ - SPDLOG_LOGGER_ERROR(GpgFrontend::GetDefaultLogger(), __VA_ARGS__) - -#define GF_CORE_LOG_TRACE(...) \ - SPDLOG_LOGGER_TRACE(GpgFrontend::GetCoreLogger(), __VA_ARGS__) -#define GF_CORE_LOG_DEBUG(...) \ - SPDLOG_LOGGER_DEBUG(GpgFrontend::GetCoreLogger(), __VA_ARGS__) -#define GF_CORE_LOG_INFO(...) \ - SPDLOG_LOGGER_INFO(GpgFrontend::GetCoreLogger(), __VA_ARGS__) -#define GF_CORE_LOG_WARN(...) \ - SPDLOG_LOGGER_WARN(GpgFrontend::GetCoreLogger(), __VA_ARGS__) -#define GF_CORE_LOG_ERROR(...) \ - SPDLOG_LOGGER_ERROR(GpgFrontend::GetCoreLogger(), __VA_ARGS__) - -#define GF_LOG_TRACE(ID, ...) \ - SPDLOG_LOGGER_TRACE(GpgFrontend::GetLogger(ID), __VA_ARGS__) -#define GF_LOG_DEBUG(ID, ...) \ - SPDLOG_LOGGER_DEBUG(GpgFrontend::GetLogger(ID), __VA_ARGS__) -#define GF_LOG_INFO(ID, ...) \ - SPDLOG_LOGGER_INFO(GpgFrontend::GetLogger(ID), __VA_ARGS__) -#define GF_LOG_WARN(ID, ...) \ - SPDLOG_LOGGER_WARN(GpgFrontend::GetLogger(ID), __VA_ARGS__) -#define GF_LOG_ERROR(ID, ...) \ - SPDLOG_LOGGER_ERROR(GpgFrontend::GetLogger(ID), __VA_ARGS__) diff --git a/src/init.cpp b/src/init.cpp index da89be1f..792df6ca 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -33,12 +33,10 @@ #include "core/function/gpg/GpgAdvancedOperator.h" #include "core/module/ModuleInit.h" #include "core/thread/TaskRunnerGetter.h" -#include "core/utils/LogUtils.h" #include "ui/GpgFrontendUIInit.h" // main #include "GpgFrontendContext.h" -#include "main.h" namespace GpgFrontend { @@ -54,22 +52,6 @@ int setenv(const char *name, const char *value, int overwrite) { } #endif -void InitLoggingSystem(const GFCxtSPtr &ctx) { -#ifdef DEBUG - RegisterSyncLogger("core", ctx->log_level); - RegisterSyncLogger("main", ctx->log_level); - RegisterSyncLogger("module", ctx->log_level); - RegisterSyncLogger("ui", ctx->log_level); - RegisterSyncLogger("test", ctx->log_level); -#else - RegisterAsyncLogger("core", ctx->log_level); - RegisterAsyncLogger("main", ctx->log_level); - RegisterAsyncLogger("module", ctx->log_level); - RegisterAsyncLogger("ui", ctx->log_level); - RegisterAsyncLogger("test", ctx->log_level); -#endif -} - void InitGlobalPathEnv() { // read settings bool use_custom_gnupg_install_path = @@ -87,13 +69,12 @@ void InitGlobalPathEnv() { // add custom gnupg install path into env $PATH if (use_custom_gnupg_install_path && !custom_gnupg_install_path.isEmpty()) { QString path_value = getenv("PATH"); - GF_MAIN_LOG_DEBUG("Current System PATH: {}", path_value); + setenv("PATH", (QDir(custom_gnupg_install_path).absolutePath() + ":" + path_value) .toUtf8(), 1); QString modified_path_value = getenv("PATH"); - GF_MAIN_LOG_DEBUG("Modified System PATH: {}", modified_path_value); } if (GlobalSettingStation::GetInstance() @@ -102,7 +83,6 @@ void InitGlobalPathEnv() { .toBool()) { qputenv("GPGME_DEBUG", QString("9:%1").arg(QDir::currentPath() + "/gpgme.log").toUtf8()); - GF_CORE_LOG_DEBUG("GPGME_DEBUG ENV: {}", qgetenv("GPGME_DEBUG")); } } @@ -112,19 +92,11 @@ void InitGlobalBasicEnv(const GFCxtWPtr &p_ctx, bool gui_mode) { return; } - // init default locale of application - InitLocale(); - - // initialize logging system - SetDefaultLogLevel(ctx->log_level); - InitLoggingSystem(ctx); - // change path to search for related InitGlobalPathEnv(); // should load module system first Module::ModuleInitArgs module_init_args; - module_init_args.log_level = ctx->log_level; Module::LoadGpgFrontendModules(module_init_args); // then preload ui @@ -149,12 +121,12 @@ void InitLocale() { // read from settings file auto lang = settings.value("basic/lang").toString(); - GF_UI_LOG_INFO("current system default locale: {}", QLocale().name()); - GF_UI_LOG_INFO("locale settings from config: {}", lang); + qInfo() << "current system default locale: " << QLocale().name(); + qInfo() << "locale settings from config: " << lang; auto target_locale = lang.trimmed().isEmpty() ? QLocale::system() : QLocale(lang); - GF_UI_LOG_INFO("application's target locale: {}", target_locale.name()); + qInfo() << "application's target locale: " << target_locale.name(); QLocale::setDefault(target_locale); } @@ -33,13 +33,6 @@ namespace GpgFrontend { /** - * @brief - * - * @param args - */ -void InitLoggingSystem(const GFCxtSPtr &); - -/** * @brief init global PATH env * */ diff --git a/src/main.cpp b/src/main.cpp index a99f3e30..8ab17a40 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -50,6 +50,18 @@ auto main(int argc, char* argv[]) -> int { argc, argv); ctx->InitApplication(); + qSetMessagePattern( + "[%{time yyyyMMdd h:mm:ss.zzz}] [%{category}] " + "[%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-" + "critical}C%{endif}%{if-fatal}F%{endif}] [%{threadid}] %{file}:%{line} - " + "%{message}"); + +#ifdef RELEASE + QLoggingCategory::setFilterRules("*.debug=false\n*.info=false\n"); +#else + QLoggingCategory::setFilterRules("*.debug=false"); +#endif + auto rtn = 0; // initialize qt resources @@ -67,14 +79,12 @@ auto main(int argc, char* argv[]) -> int { parser.process(*ctx->GetApp()); - ctx->log_level = spdlog::level::info; - if (parser.isSet("v")) { return GpgFrontend::PrintVersion(); } if (parser.isSet("l")) { - ctx->log_level = GpgFrontend::ParseLogLevel(parser.value("l")); + GpgFrontend::ParseLogLevel(parser.value("l")); } if (parser.isSet("t")) { diff --git a/src/pinentry/CMakeLists.txt b/src/pinentry/CMakeLists.txt index a800b0f4..db2b0b4f 100644 --- a/src/pinentry/CMakeLists.txt +++ b/src/pinentry/CMakeLists.txt @@ -35,6 +35,9 @@ endif() add_library(gpgfrontend_pinentry SHARED ${PINENTRY_SOURCE}) + +# link options + target_link_libraries(gpgfrontend_pinentry PUBLIC gpgfrontend_core) if(GPGFRONTEND_QT5_BUILD) @@ -55,14 +58,13 @@ if (XCODE_BUILD) XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "${GPGFRONTEND_XOCDE_CODE_SIGN_IDENTITY}") endif () -# spdlog -target_link_libraries(gpgfrontend_pinentry PRIVATE spdlog) # using std c++ 17 target_compile_features(gpgfrontend_pinentry PUBLIC cxx_std_17) + +# set lib output path if (${CMAKE_BUILD_TYPE} STREQUAL "Debug") - # lib output path set_target_properties(gpgfrontend_pinentry PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/lib RUNTIME_OUTPUT_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/lib) diff --git a/src/sdk/CMakeLists.txt b/src/sdk/CMakeLists.txt index 765c0e73..5f1dc65a 100644 --- a/src/sdk/CMakeLists.txt +++ b/src/sdk/CMakeLists.txt @@ -34,8 +34,7 @@ add_library(gpgfrontend_module_sdk SHARED ${MODULE_SDK_SOURCE}) set(_export_file_sdk "${CMAKE_CURRENT_SOURCE_DIR}/GFSDKExport.h") generate_export_header(gpgfrontend_module_sdk EXPORT_FILE_NAME "${_export_file_sdk}") target_include_directories(gpgfrontend_module_sdk PRIVATE - ${CMAKE_CURRENT_BINARY_DIR}/gpgfrontend_module_sdk_autogen/include - ${CMAKE_SOURCE_DIR}/third_party/spdlog/include) + ${CMAKE_CURRENT_BINARY_DIR}/gpgfrontend_module_sdk_autogen/include) target_include_directories(gpgfrontend_module_sdk PUBLIC sdk) diff --git a/src/sdk/GFSDKLog.cpp b/src/sdk/GFSDKLog.cpp index 603cc325..bc1ce7b8 100644 --- a/src/sdk/GFSDKLog.cpp +++ b/src/sdk/GFSDKLog.cpp @@ -28,20 +28,16 @@ #include "GFSDKLog.h" -#include "core/utils/LogUtils.h" +#include <qglobal.h> -#define MODULE_LOG_TRACE(...) GF_LOG_TRACE("module", __VA_ARGS__) -#define MODULE_LOG_DEBUG(...) GF_LOG_DEBUG("module", __VA_ARGS__) -#define MODULE_LOG_INFO(...) GF_LOG_INFO("module", __VA_ARGS__) -#define MODULE_LOG_WARN(...) GF_LOG_WARN("module", __VA_ARGS__) -#define MODULE_LOG_ERROR(...) GF_LOG_ERROR("module", __VA_ARGS__) +Q_LOGGING_CATEGORY(module, "module") -void GFModuleLogTrace(const char* l) { MODULE_LOG_TRACE(l); } +void GFModuleLogTrace(const char* l) { qCDebug(module) << QString(l); } -void GFModuleLogDebug(const char* l) { MODULE_LOG_DEBUG(l); } +void GFModuleLogDebug(const char* l) { qCDebug(module) << QString(l); } -void GFModuleLogInfo(const char* l) { MODULE_LOG_INFO(l); } +void GFModuleLogInfo(const char* l) { qCInfo(module) << QString(l); } -void GFModuleLogWarn(const char* l) { MODULE_LOG_WARN(l); } +void GFModuleLogWarn(const char* l) { qCWarning(module) << QString(l); } -void GFModuleLogError(const char* l) { MODULE_LOG_ERROR(l); } +void GFModuleLogError(const char* l) { qCCritical(module) << QString(l); } diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 221483dc..0ad259bd 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -28,14 +28,23 @@ aux_source_directory(./core TEST_SOURCE) aux_source_directory(. TEST_SOURCE) + +# define test library add_library(gpgfrontend_test SHARED ${TEST_SOURCE}) +# generate headers set(_export_file "${CMAKE_CURRENT_SOURCE_DIR}/GpgFrontendTestExport.h") generate_export_header(gpgfrontend_test EXPORT_FILE_NAME "${_export_file}") +# compile definitions +target_compile_definitions(gpgfrontend_test PUBLIC GF_TEST) + + +# link options + target_link_libraries(gpgfrontend_test PRIVATE gtest) + target_link_libraries(gpgfrontend_test PRIVATE gpgfrontend_core) -target_link_libraries(gpgfrontend_test PRIVATE spdlog) if (XCODE_BUILD) set_target_properties(gpgfrontend_test diff --git a/src/test/GpgFrontendTest.cpp b/src/test/GpgFrontendTest.cpp index 95b4179a..2ad7ada7 100644 --- a/src/test/GpgFrontendTest.cpp +++ b/src/test/GpgFrontendTest.cpp @@ -29,6 +29,7 @@ #include "GpgFrontendTest.h" #include <gtest/gtest.h> +#include <qglobal.h> #include "core/GpgConstants.h" #include "core/function/GlobalSettingStation.h" @@ -37,6 +38,8 @@ #include "core/function/gpg/GpgKeyImportExporter.h" #include "core/utils/IOUtils.h" +Q_LOGGING_CATEGORY(test, "test") + namespace GpgFrontend::Test { auto GenerateRandomString(size_t length) -> QString { @@ -56,8 +59,6 @@ auto GenerateRandomString(size_t length) -> QString { void ConfigureGpgContext() { auto db_path = QDir(QDir::tempPath() + "/" + GenerateRandomString(12)); - GF_TEST_LOG_DEBUG("setting up new database path for test case: {}", - db_path.path()); if (db_path.exists()) db_path.rmdir("."); db_path.mkpath("."); @@ -84,7 +85,7 @@ void ImportPrivateKeys(const QString& data_path, QSettings settings) { GpgKeyImportExporter::GetInstance(kGpgFrontendDefaultChannel) .ImportKey(gf_buffer); } else { - GF_TEST_LOG_ERROR("read from key file failed: {}", key_file); + qCWarning(test) << "read from key file failed: " << key_file; } } } @@ -95,8 +96,8 @@ void SetupGlobalTestEnv() { auto test_config_path = test_path + "/conf/test.ini"; auto test_data_path = test_path + "/data"; - GF_TEST_LOG_INFO("test config file path: {}", test_config_path); - GF_TEST_LOG_INFO("test data file path: {}", test_data_path); + qCInfo(test) << "test config file path: " << test_config_path; + qCInfo(test) << "test data file path: " << test_data_path; ImportPrivateKeys(test_data_path, QSettings(test_config_path, QSettings::IniFormat)); diff --git a/src/test/GpgFrontendTest.h b/src/test/GpgFrontendTest.h index 405eee90..3c1ecbfd 100644 --- a/src/test/GpgFrontendTest.h +++ b/src/test/GpgFrontendTest.h @@ -30,8 +30,13 @@ #include "GpgFrontendTestExport.h" -// Core -#include "core/utils/LogUtils.h" +// declare area of test +#ifdef GF_TEST + +// declare logging category +Q_DECLARE_LOGGING_CATEGORY(test) + +#endif namespace GpgFrontend::Test { @@ -42,10 +47,4 @@ struct GpgFrontendContext { auto GPGFRONTEND_TEST_EXPORT ExecuteAllTestCase(GpgFrontendContext args) -> int; -#define GF_TEST_LOG_TRACE(...) GF_LOG_TRACE("test", __VA_ARGS__) -#define GF_TEST_LOG_DEBUG(...) GF_LOG_DEBUG("test", __VA_ARGS__) -#define GF_TEST_LOG_INFO(...) GF_LOG_INFO("test", __VA_ARGS__) -#define GF_TEST_LOG_WARN(...) GF_LOG_WARN("test", __VA_ARGS__) -#define GF_TEST_LOG_ERROR(...) GF_LOG_ERROR("test", __VA_ARGS__) - } // namespace GpgFrontend::Test diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 7db2b627..bb201390 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -43,10 +43,16 @@ aux_source_directory(function UI_SOURCE) # define libgpgfrontend_ui set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) + add_library(gpgfrontend_ui SHARED ${UI_SOURCE}) + +# generate headers set(_export_file "${CMAKE_CURRENT_SOURCE_DIR}/GpgFrontendUIExport.h") generate_export_header(gpgfrontend_ui EXPORT_FILE_NAME "${_export_file}") +# compile definitions +target_compile_definitions(gpgfrontend_ui PUBLIC GF_UI) + if(GPGFRONTEND_QT5_BUILD) # link Qt target_link_libraries(gpgfrontend_ui @@ -69,8 +75,7 @@ target_precompile_headers(gpgfrontend_ui PUBLIC GpgFrontendUI.h) # add ui generator include path target_include_directories(gpgfrontend_ui PUBLIC - ${CMAKE_CURRENT_BINARY_DIR}/gpgfrontend_ui_autogen/include - ${CMAKE_SOURCE_DIR}/third_party/spdlog/include) + ${CMAKE_CURRENT_BINARY_DIR}/gpgfrontend_ui_autogen/include) # using std c++ 17 target_compile_features(gpgfrontend_ui PUBLIC cxx_std_17) diff --git a/src/ui/GpgFrontendApplication.cpp b/src/ui/GpgFrontendApplication.cpp index 900d4735..3ee7ab7d 100644 --- a/src/ui/GpgFrontendApplication.cpp +++ b/src/ui/GpgFrontendApplication.cpp @@ -57,7 +57,7 @@ bool GpgFrontendApplication::notify(QObject *receiver, QEvent *event) { try { return QApplication::notify(receiver, event); } catch (const std::exception &ex) { - GF_UI_LOG_ERROR("exception was caught in notify: {}", ex.what()); + qCWarning(ui, "exception was caught in notify: {}", ex.what()); QMessageBox::information( nullptr, tr("Standard Exception Thrown"), tr("Oops, an standard exception was thrown " @@ -66,7 +66,7 @@ bool GpgFrontendApplication::notify(QObject *receiver, QEvent *event) { "be the negligence of the programmer, " "please report this problem if you can.")); } catch (...) { - GF_UI_LOG_ERROR("unknown exception was caught in notify"); + qCWarning(ui, "unknown exception was caught in notify"); QMessageBox::information( nullptr, tr("Unhandled Exception Thrown"), tr("Oops, an unhandled exception was thrown " diff --git a/src/main.h b/src/ui/GpgFrontendUI.cpp index a394e676..359eb6d2 100644 --- a/src/main.h +++ b/src/ui/GpgFrontendUI.cpp @@ -26,13 +26,6 @@ * */ -#pragma once +#include "GpgFrontendUI.h" -#include "core/utils/LogUtils.h" -#include "core/utils/MemoryUtils.h" - -#define GF_MAIN_LOG_TRACE(...) GF_LOG_TRACE("main", __VA_ARGS__) -#define GF_MAIN_LOG_DEBUG(...) GF_LOG_DEBUG("main", __VA_ARGS__) -#define GF_MAIN_LOG_INFO(...) GF_LOG_INFO("main", __VA_ARGS__) -#define GF_MAIN_LOG_WARN(...) GF_LOG_WARN("main", __VA_ARGS__) -#define GF_MAIN_LOG_ERROR(...) GF_LOG_ERROR("main", __VA_ARGS__)
\ No newline at end of file +Q_LOGGING_CATEGORY(ui, "ui")
\ No newline at end of file diff --git a/src/ui/GpgFrontendUI.h b/src/ui/GpgFrontendUI.h index b3115795..a4793672 100644 --- a/src/ui/GpgFrontendUI.h +++ b/src/ui/GpgFrontendUI.h @@ -33,16 +33,13 @@ */ #include <QtWidgets> -// Core -#include "GpgFrontend.h" -#include "core/GpgFrontendCore.h" -#include "core/utils/LogUtils.h" - // UI #include "ui/GpgFrontendUIExport.h" -#define GF_UI_LOG_TRACE(...) GF_LOG_TRACE("ui", __VA_ARGS__) -#define GF_UI_LOG_DEBUG(...) GF_LOG_DEBUG("ui", __VA_ARGS__) -#define GF_UI_LOG_INFO(...) GF_LOG_INFO("ui", __VA_ARGS__) -#define GF_UI_LOG_WARN(...) GF_LOG_WARN("ui", __VA_ARGS__) -#define GF_UI_LOG_ERROR(...) GF_LOG_ERROR("ui", __VA_ARGS__) +// declare area of ui +#ifdef GF_UI + +// declare logging category +Q_DECLARE_LOGGING_CATEGORY(ui) + +#endif diff --git a/src/ui/GpgFrontendUIInit.cpp b/src/ui/GpgFrontendUIInit.cpp index b3050a63..b779c335 100644 --- a/src/ui/GpgFrontendUIInit.cpp +++ b/src/ui/GpgFrontendUIInit.cpp @@ -48,7 +48,7 @@ QList<QByteArray> loaded_qm_datum; extern void InitUITranslations(); void WaitEnvCheckingProcess() { - GF_UI_LOG_DEBUG("need to waiting for env checking process"); + qCDebug(ui, "need to waiting for env checking process"); // create and show loading window before starting the main window auto* waiting_dialog = new QProgressDialog(); @@ -67,7 +67,6 @@ void WaitEnvCheckingProcess() { QApplication::connect(CoreSignalStation::GetInstance(), &CoreSignalStation::SignalGoodGnupgEnv, waiting_dialog, [=]() { - GF_UI_LOG_DEBUG("gpg env loaded successfuly"); waiting_dialog->finished(0); waiting_dialog->deleteLater(); }); @@ -79,19 +78,19 @@ void WaitEnvCheckingProcess() { &QEventLoop::quit); QApplication::connect(waiting_dialog, &QProgressDialog::canceled, [=]() { - GF_UI_LOG_DEBUG("cancel clicked on waiting dialog"); + qCDebug(ui, "cancel clicked on waiting dialog"); QApplication::quit(); exit(0); }); auto env_state = Module::RetrieveRTValueTypedOrDefault<>("core", "env.state.basic", 0); - GF_UI_LOG_DEBUG("ui is ready to waiting for env initialized, env_state: {}", - env_state); + qCDebug(ui, "ui is ready to waiting for env initialized, env_state: %d", + env_state); // check twice to avoid some unlucky sitations if (env_state == 1) { - GF_UI_LOG_DEBUG("env state turned initialized before the looper start"); + qCDebug(ui, "env state turned initialized before the looper start"); waiting_dialog->finished(0); waiting_dialog->deleteLater(); return; @@ -159,8 +158,6 @@ void InitGpgFrontendUI(QApplication* /*app*/) { settings.value("proxy/username", QString{}).toString(); QString const proxy_password = settings.value("proxy/password", QString{}).toString(); - GF_UI_LOG_DEBUG("proxy settings: type {}, host {}, port: {}", proxy_type, - proxy_host, proxy_port); QNetworkProxy::ProxyType proxy_type_qt = QNetworkProxy::NoProxy; if (proxy_type == "HTTP") { @@ -189,7 +186,7 @@ void InitGpgFrontendUI(QApplication* /*app*/) { QNetworkProxy::setApplicationProxy(proxy); } catch (...) { - GF_UI_LOG_ERROR("setting operation error: proxy setings"); + qCWarning(ui, "setting operation error: proxy setings"); // no proxy by default QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy); } @@ -210,7 +207,7 @@ auto RunGpgFrontendUI(QApplication* app) -> int { // pre-check, if application need to restart if (CommonUtils::GetInstance()->isApplicationNeedRestart()) { - GF_UI_LOG_DEBUG("application need to restart, before main window init"); + qCDebug(ui, "application need to restart, before main window init."); return kDeepRestartCode; } @@ -218,7 +215,6 @@ auto RunGpgFrontendUI(QApplication* app) -> int { main_window->Init(); // show main windows - GF_UI_LOG_DEBUG("main window is ready to show"); main_window->show(); // start the main event loop @@ -241,9 +237,6 @@ void InitUITranslations() { auto* translator = new QTranslator(QCoreApplication::instance()); if (translator->load(QLocale(), QLatin1String("qt"), QLatin1String("_"), QLatin1String(":/i18n_qt"), QLatin1String(".qm"))) { - GF_UI_LOG_DEBUG("load qt translation file done, locale: {}", - QLocale().name()); - QCoreApplication::installTranslator(translator); registered_translators.append(translator); } @@ -251,8 +244,6 @@ void InitUITranslations() { translator = new QTranslator(QCoreApplication::instance()); if (translator->load(QLocale(), QLatin1String("qtbase"), QLatin1String("_"), QLatin1String(":/i18n_qt"), QLatin1String(".qm"))) { - GF_UI_LOG_DEBUG("load qtbase translation file done, locale: {}", - QLocale().name()); QCoreApplication::installTranslator(translator); registered_translators.append(translator); } @@ -261,8 +252,6 @@ void InitUITranslations() { if (translator->load(QLocale(), QLatin1String(PROJECT_NAME), QLatin1String("."), QLatin1String(":/i18n"), QLatin1String(".qm"))) { - GF_UI_LOG_DEBUG("load target translation file done, locale: {}", - QLocale().name()); QCoreApplication::installTranslator(translator); registered_translators.append(translator); } @@ -273,8 +262,6 @@ auto InstallTranslatorFromQMData(const QByteArray& data) -> bool { if (translator->load(reinterpret_cast<uchar*>(const_cast<char*>(data.data())), data.size())) { - GF_UI_LOG_DEBUG("load target translation file done, locale: {}", - QLocale().name()); QCoreApplication::installTranslator(translator); registered_translators.append(translator); loaded_qm_datum.append(data); diff --git a/src/ui/UserInterfaceUtils.cpp b/src/ui/UserInterfaceUtils.cpp index 06b784cc..1d54c3cd 100644 --- a/src/ui/UserInterfaceUtils.cpp +++ b/src/ui/UserInterfaceUtils.cpp @@ -80,7 +80,6 @@ void ImportUnknownKeyFromKeyserver( auto key_ids = std::make_unique<KeyIdArgsList>(); auto *signature = verify_result.GetSignatures(); while (signature != nullptr) { - GF_UI_LOG_DEBUG("signature fpr: {}", signature->fpr); key_ids->push_back(signature->fpr); signature = signature->next; } @@ -232,8 +231,6 @@ void CommonUtils::WaitForOpera(QWidget *parent, QTimer::singleShot(64, parent, [=]() { opera([dialog]() { if (dialog != nullptr) { - GF_UI_LOG_DEBUG("called operating waiting cb, dialog: {}", - static_cast<void *>(dialog)); dialog->close(); dialog->accept(); } @@ -328,18 +325,17 @@ void CommonUtils::SlotExecuteCommand( &QEventLoop::quit); connect(cmd_process, &QProcess::errorOccurred, &looper, &QEventLoop::quit); connect(cmd_process, &QProcess::started, - []() -> void { GF_UI_LOG_DEBUG("process started"); }); + []() -> void { qCDebug(ui, "process started"); }); connect(cmd_process, &QProcess::readyReadStandardOutput, [interact_func, cmd_process]() { interact_func(cmd_process); }); connect(cmd_process, &QProcess::errorOccurred, this, - [=]() -> void { GF_UI_LOG_ERROR("error in process"); }); + [=]() -> void { qCWarning(ui, "error in process"); }); connect(cmd_process, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, [=](int, QProcess::ExitStatus status) { - if (status == QProcess::NormalExit) - GF_UI_LOG_DEBUG("succeed in executing command: {}", cmd); - else - GF_UI_LOG_WARN("error in executing command: {}", cmd); + if (status != QProcess::NormalExit) { + qCWarning(ui) << "error in executing command: " << cmd; + } }); cmd_process->setProgram(cmd); @@ -365,11 +361,11 @@ void CommonUtils::SlotExecuteGpgCommand( &WaitingDialog::deleteLater); connect(gpg_process, &QProcess::errorOccurred, &looper, &QEventLoop::quit); connect(gpg_process, &QProcess::started, - []() -> void { GF_UI_LOG_DEBUG("gpg process started"); }); + []() -> void { qCDebug(ui, "gpg process started"); }); connect(gpg_process, &QProcess::readyReadStandardOutput, [interact_func, gpg_process]() { interact_func(gpg_process); }); connect(gpg_process, &QProcess::errorOccurred, this, [=]() -> void { - GF_UI_LOG_ERROR("Error in Process"); + qCWarning(ui, "Error in Process"); dialog->close(); QMessageBox::critical(nullptr, tr("Failure"), tr("Failed to execute command.")); @@ -388,7 +384,6 @@ void CommonUtils::SlotExecuteGpgCommand( const auto app_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.app_path", QString{}); - GF_UI_LOG_DEBUG("got gnupg app path from rt: {}", app_path); gpg_process->setProgram(app_path); gpg_process->setArguments(arguments); @@ -409,8 +404,6 @@ void CommonUtils::SlotImportKeyFromKeyServer( "please set a default keyserver first")); return; } - GF_UI_LOG_DEBUG("set target key server to default Key Server: {}", - target_keyserver); auto *thread = QThread::create([target_keyserver, key_ids, callback]() { QUrl target_keyserver_url(target_keyserver); @@ -426,8 +419,6 @@ void CommonUtils::SlotImportKeyFromKeyServer( target_keyserver_url.host() + "/pks/lookup?op=get&search=0x" + key_id + "&options=mr"); - GF_UI_LOG_DEBUG("request url: {}", req_url.toString()); - // Waiting for reply auto request = QNetworkRequest(req_url); request.setHeader(QNetworkRequest::UserAgentHeader, @@ -498,21 +489,19 @@ void CommonUtils::slot_update_key_from_server_finished( bool success, QString err_msg, QByteArray buffer, std::shared_ptr<GpgImportInformation> info) { if (!success) { - GF_UI_LOG_ERROR("get err from reply: {}", buffer); + qCWarning(ui) << "get err from reply: " << buffer; QMessageBox::critical(nullptr, tr("Error"), err_msg); return; } // refresh the key database - emit UISignalStation::GetInstance()->SignalKeyDatabaseRefresh(); + emit UISignalStation::GetInstance() -> SignalKeyDatabaseRefresh(); // show details (new KeyImportDetailDialog(std::move(info), this))->exec(); } void CommonUtils::SlotRestartApplication(int code) { - GF_UI_LOG_DEBUG("application need restart, code: {}", code); - if (code == 0) { std::exit(0); } else { @@ -540,7 +529,6 @@ void CommonUtils::AddKey2Favourtie(const GpgKey &key) { QJsonArray key_array; if (json_data.isArray()) key_array = json_data.array(); - GF_UI_LOG_DEBUG("add key to favorites, key fpr: {}", key.GetFingerprint()); key_array.push_back(key.GetFingerprint()); json_data.setArray(key_array); } @@ -554,8 +542,6 @@ void CommonUtils::RemoveKeyFromFavourite(const GpgKey &key) { QJsonArray key_array; if (json_data.isArray()) key_array = json_data.array(); - GF_UI_LOG_DEBUG("remove key from favorites, key fpr: {}", - key.GetFingerprint()); auto fingerprint = key.GetFingerprint(); QJsonArray new_key_array; for (auto &&item : key_array) { diff --git a/src/ui/dialog/GeneralDialog.cpp b/src/ui/dialog/GeneralDialog.cpp index 2015322f..91ede794 100644 --- a/src/ui/dialog/GeneralDialog.cpp +++ b/src/ui/dialog/GeneralDialog.cpp @@ -52,21 +52,14 @@ void GpgFrontend::UI::GeneralDialog::slot_restore_settings() noexcept { if (window_state.window_save) { int x = window_state.x; int y = window_state.y; - GF_UI_LOG_DEBUG("stored dialog pos, x: {}, y: {}", x, y); QPoint relative_pos = {x, y}; QPoint pos = parent_rect_.topLeft() + relative_pos; - GF_UI_LOG_DEBUG("relative dialog pos, x: {}, y: {}", relative_pos.x(), - relative_pos.y()); int width = window_state.width; int height = window_state.height; - GF_UI_LOG_DEBUG("stored dialog size, width: {}, height: {}", width, - height); QRect target_rect = {pos.x(), pos.y(), width, height}; - GF_UI_LOG_DEBUG("dialog stored target rect, width: {}, height: {}", width, - height); // check for valid if (width > 0 && height > 0 && screen_rect_.contains(target_rect)) { @@ -76,7 +69,7 @@ void GpgFrontend::UI::GeneralDialog::slot_restore_settings() noexcept { } } catch (...) { - GF_UI_LOG_ERROR("error at restoring settings"); + qCWarning(ui, "error at restoring settings"); } } @@ -86,14 +79,8 @@ void GpgFrontend::UI::GeneralDialog::slot_save_settings() noexcept { update_rect_cache(); - GF_UI_LOG_DEBUG("dialog pos, x: {}, y: {}", rect_.x(), rect_.y()); - GF_UI_LOG_DEBUG("dialog size, width: {}, height: {}", rect_.width(), - rect_.height()); - // window position relative to parent auto relative_pos = rect_.topLeft() - parent_rect_.topLeft(); - GF_UI_LOG_DEBUG("store dialog pos, x: {}, y: {}", relative_pos.x(), - relative_pos.y()); WindowStateSO window_state; window_state.x = relative_pos.x(); @@ -105,18 +92,13 @@ void GpgFrontend::UI::GeneralDialog::slot_save_settings() noexcept { general_windows_state.Store(window_state.Json()); } catch (...) { - GF_UI_LOG_ERROR("general dialog: {}, caught exception", name_); + qCWarning(ui) << "general dialog: " << name_ << ", caught exception"; } } void GpgFrontend::UI::GeneralDialog::setPosCenterOfScreen() { update_rect_cache(); - int screen_width = screen_rect_.width(); - int screen_height = screen_rect_.height(); - GF_UI_LOG_DEBUG("dialog current screen available geometry", screen_width, - screen_height); - // update rect of current dialog rect_ = this->geometry(); this->move(screen_rect_.center() - @@ -131,16 +113,6 @@ void GpgFrontend::UI::GeneralDialog::movePosition2CenterOfParent() { // update cache update_rect_cache(); - // log for debug - GF_UI_LOG_DEBUG("parent pos x: {} y: {}", parent_rect_.x(), parent_rect_.y()); - GF_UI_LOG_DEBUG("parent size width: {}, height: {}", parent_rect_.width(), - parent_rect_.height()); - GF_UI_LOG_DEBUG("parent center pos x: {}, y: {}", parent_rect_.center().x(), - parent_rect_.center().y()); - GF_UI_LOG_DEBUG("dialog pos x: {} y: {}", rect_.x(), rect_.y()); - GF_UI_LOG_DEBUG("dialog size width: {} height: {}", rect_.width(), - rect_.height()); - if (parent_rect_.topLeft() != QPoint{0, 0} && parent_rect_.size() != QSize{0, 0}) { if (rect_.width() <= 0) rect_.setWidth(100); @@ -149,10 +121,6 @@ void GpgFrontend::UI::GeneralDialog::movePosition2CenterOfParent() { QPoint target_position = parent_rect_.center() - QPoint(rect_.width() / 2, rect_.height() / 2); - GF_UI_LOG_DEBUG( - "update position to parent's center, target pos, x:{}, y: {}", - target_position.x(), target_position.y()); - this->move(target_position); } else { setPosCenterOfScreen(); @@ -207,9 +175,6 @@ auto GpgFrontend::UI::GeneralDialog::isRectRestored() -> bool { * */ void GpgFrontend::UI::GeneralDialog::showEvent(QShowEvent *event) { - GF_UI_LOG_DEBUG("General Dialog named {} is about to show, caught show event", - name_); - // default position strategy if (!isRectRestored()) movePosition2CenterOfParent(); diff --git a/src/ui/dialog/Wizard.cpp b/src/ui/dialog/Wizard.cpp index e65366dd..cb43c966 100644 --- a/src/ui/dialog/Wizard.cpp +++ b/src/ui/dialog/Wizard.cpp @@ -60,7 +60,7 @@ void Wizard::slot_wizard_accepted() { auto settings = GlobalSettingStation::GetInstance().GetSettings(); settings.setValue("wizard/show_wizard", false); } catch (...) { - GF_UI_LOG_ERROR("setting operation error"); + qCWarning(ui, "setting operation error"); } if (field("openHelp").toBool()) { emit SignalOpenHelp("docu.html#content"); diff --git a/src/ui/dialog/controller/GnuPGControllerDialog.cpp b/src/ui/dialog/controller/GnuPGControllerDialog.cpp index 1874e255..b09b7280 100644 --- a/src/ui/dialog/controller/GnuPGControllerDialog.cpp +++ b/src/ui/dialog/controller/GnuPGControllerDialog.cpp @@ -100,9 +100,6 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) this, tr("Open Directory"), {}, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - GF_UI_LOG_DEBUG("key database path selected: {}", - selected_custom_key_database_path); - custom_key_database_path_ = selected_custom_key_database_path; // announce the restart @@ -120,9 +117,6 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) this, tr("Open Directory"), {}, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - GF_UI_LOG_DEBUG("gnupg install path selected: {}", - selected_custom_gnupg_install_path); - custom_gnupg_path_ = selected_custom_gnupg_install_path; // announce the restart @@ -177,8 +171,6 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) void GnuPGControllerDialog::SlotAccept() { apply_settings(); - GF_UI_LOG_DEBUG("gnupg controller apply done"); - GF_UI_LOG_DEBUG("restart needed: {}", get_restart_needed()); if (get_restart_needed() != 0) { emit SignalRestartNeeded(get_restart_needed()); } @@ -198,8 +190,6 @@ void GnuPGControllerDialog::slot_update_custom_key_database_path_label( .GetSettings() .value("gnupg/custom_key_database_path") .toString(); - GF_UI_LOG_DEBUG("selected_custom_key_database_path from settings: {}", - custom_key_database_path); custom_key_database_path_ = custom_key_database_path; } @@ -217,7 +207,6 @@ void GnuPGControllerDialog::slot_update_custom_key_database_path_label( if (ui_->currentKeyDatabasePathLabel->text().isEmpty()) { const auto database_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.database_path", QString{}); - GF_UI_LOG_DEBUG("got gpgme.ctx.database_path from rt: {}", database_path); ui_->currentKeyDatabasePathLabel->setText(database_path); } } @@ -236,8 +225,6 @@ void GnuPGControllerDialog::slot_update_custom_gnupg_install_path_label( .GetSettings() .value("gnupg/custom_gnupg_install_path") .toString(); - GF_UI_LOG_DEBUG("custom_gnupg_install_path from settings: {}", - custom_gnupg_install_path); custom_gnupg_path_ = custom_gnupg_install_path; } @@ -256,7 +243,6 @@ void GnuPGControllerDialog::slot_update_custom_gnupg_install_path_label( if (ui_->currentCustomGnuPGInstallPathLabel->text().isEmpty()) { const auto gnupg_path = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.app_path", QString{}); - GF_UI_LOG_DEBUG("got gnupg home path from rt: {}", gnupg_path); auto dir = QFileInfo(gnupg_path).path(); ui_->currentCustomGnuPGInstallPathLabel->setText(dir); } @@ -351,7 +337,6 @@ auto GnuPGControllerDialog::get_restart_needed() const -> int { } void GnuPGControllerDialog::slot_set_restart_needed(int mode) { - GF_UI_LOG_INFO("announce restart needed, mode: {}", mode); this->restart_mode_ = mode; } diff --git a/src/ui/dialog/controller/ModuleControllerDialog.cpp b/src/ui/dialog/controller/ModuleControllerDialog.cpp index 4c727b48..6c0e6d0a 100644 --- a/src/ui/dialog/controller/ModuleControllerDialog.cpp +++ b/src/ui/dialog/controller/ModuleControllerDialog.cpp @@ -105,7 +105,6 @@ ModuleControllerDialog::ModuleControllerDialog(QWidget* parent) void ModuleControllerDialog::slot_load_module_details( Module::ModuleIdentifier module_id) { - GF_UI_LOG_DEBUG("loading module details, module id: {}", module_id); auto module = module_manager_->SearchModule(module_id); SettingsObject so(QString("module.%1.so").arg(module_id)); ModuleSO module_so(so); @@ -122,8 +121,6 @@ void ModuleControllerDialog::slot_load_module_details( module_so.module_id = module_id; module_so.module_hash = module->GetModuleHash(); module_so.auto_activate = false; - GF_UI_LOG_DEBUG("reseting module settings object, module id: {}", - module_id); so.Store(module_so.ToJson()); } diff --git a/src/ui/dialog/help/AboutDialog.cpp b/src/ui/dialog/help/AboutDialog.cpp index b4410942..14cb76ad 100644 --- a/src/ui/dialog/help/AboutDialog.cpp +++ b/src/ui/dialog/help/AboutDialog.cpp @@ -59,9 +59,6 @@ AboutDialog::AboutDialog(const QString& default_tab_name, QWidget* parent) } } - connect(tab_widget, &QTabWidget::currentChanged, this, - [&](int index) { GF_UI_LOG_DEBUG("current index: {}", index); }); - int default_index = 0; for (int i = 0; i < tab_widget->count(); i++) { if (tab_widget->tabText(i) == default_tab_name) { @@ -91,7 +88,6 @@ void AboutDialog::showEvent(QShowEvent* ev) { QDialog::showEvent(ev); } InfoTab::InfoTab(QWidget* parent) : QWidget(parent) { const auto gpgme_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.version", QString{"2.0.0"}); - GF_UI_LOG_DEBUG("got gpgme version from rt: {}", gpgme_version); auto pixmap = QPixmap(":/icons/gpgfrontend_logo.png"); pixmap = pixmap.scaled(128, 128); diff --git a/src/ui/dialog/import_export/KeyServerImportDialog.cpp b/src/ui/dialog/import_export/KeyServerImportDialog.cpp index 575a97e4..af00549d 100644 --- a/src/ui/dialog/import_export/KeyServerImportDialog.cpp +++ b/src/ui/dialog/import_export/KeyServerImportDialog.cpp @@ -110,7 +110,7 @@ KeyServerImportDialog::KeyServerImportDialog(QWidget* parent) main_layout->addLayout(buttons_layout, 6, 0, 1, 3); this->setLayout(main_layout); - this->setWindowTitle(tr("Import Keys from Keyserver")); + this->setWindowTitle(tr("Import Keys from key server")); this->setModal(true); movePosition2CenterOfParent(); @@ -132,7 +132,7 @@ auto KeyServerImportDialog::create_combo_box() -> QComboBox* { } combo_box->setCurrentText(key_server.GetTargetServer()); } catch (...) { - GF_UI_LOG_ERROR("setting operation error", "server_list", "default_server"); + qCWarning(ui, "setting operation error server_list default_server"); } return combo_box; @@ -208,16 +208,12 @@ void KeyServerImportDialog::slot_search() { void KeyServerImportDialog::slot_search_finished( QNetworkReply::NetworkError error, QByteArray buffer) { - GF_UI_LOG_DEBUG("search result {} {}", error, buffer.size()); - keys_table_->clearContents(); keys_table_->setRowCount(0); auto stream = QTextStream(buffer); if (error != QNetworkReply::NoError) { - GF_UI_LOG_DEBUG("error from reply: {}", error); - switch (error) { case QNetworkReply::ContentNotFoundError: set_message(tr("Not Key Found"), true); @@ -414,7 +410,6 @@ void KeyServerImportDialog::slot_import_finished( set_loading(false); if (!success) { - GF_UI_LOG_ERROR("error from reply: {}", buffer); set_message(err_msg, true); return; } diff --git a/src/ui/dialog/import_export/KeyUploadDialog.cpp b/src/ui/dialog/import_export/KeyUploadDialog.cpp index 7ab34c49..ed408bab 100644 --- a/src/ui/dialog/import_export/KeyUploadDialog.cpp +++ b/src/ui/dialog/import_export/KeyUploadDialog.cpp @@ -74,7 +74,7 @@ void KeyUploadDialog::SlotUpload() { if (CheckGpgError(err) == GPG_ERR_USER_1 || data_obj == nullptr || !data_obj->Check<GFBuffer>()) { - GF_CORE_LOG_ERROR("data object checking failed"); + qCWarning(ui, "data object checking failed"); QMessageBox::critical(this, tr("Error"), tr("Unknown error occurred")); // Done @@ -139,11 +139,9 @@ void KeyUploadDialog::slot_upload_finished() { this->close(); QByteArray response = reply->readAll(); - GF_UI_LOG_DEBUG("upload response: {}", response); auto error = reply->error(); if (error != QNetworkReply::NoError) { - GF_UI_LOG_DEBUG("error from reply: {}", reply->errorString()); QString message; switch (error) { case QNetworkReply::ContentNotFoundError: diff --git a/src/ui/dialog/key_generate/KeygenDialog.cpp b/src/ui/dialog/key_generate/KeygenDialog.cpp index 7585d6f0..cbaebb13 100644 --- a/src/ui/dialog/key_generate/KeygenDialog.cpp +++ b/src/ui/dialog/key_generate/KeygenDialog.cpp @@ -257,16 +257,12 @@ void KeyGenDialog::slot_authentication_box_changed(int state) { } void KeyGenDialog::slot_activated_key_type(int index) { - GF_UI_LOG_DEBUG("key type index changed: {}", index); - // check assert(gen_key_info_->GetSupportedKeyAlgo().size() > static_cast<size_t>(index)); const auto [name, key_algo, subkey_algo] = gen_key_info_->GetSupportedKeyAlgo()[index]; - GF_UI_LOG_DEBUG("target key algo changed, name: {}, key: {}, subkey: {}", - name, key_algo, subkey_algo); assert(!key_algo.isEmpty()); gen_key_info_->SetAlgo(key_algo); diff --git a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp index eecf2a1d..25da4291 100644 --- a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp +++ b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp @@ -305,7 +305,7 @@ void SubkeyGenerateDialog::slot_key_gen_accept() { CommonUtils::RaiseMessageBox(this, err); if (CheckGpgError(err) == GPG_ERR_NO_ERROR) { emit UISignalStation::GetInstance() - ->SignalKeyDatabaseRefresh(); + -> SignalKeyDatabaseRefresh(); } }); }); @@ -358,8 +358,6 @@ void SubkeyGenerateDialog::slot_authentication_box_changed(int state) { } void SubkeyGenerateDialog::slot_activated_key_type(int index) { - GF_UI_LOG_DEBUG("key type index changed: {}", index); - // check assert(gen_key_info_->GetSupportedSubkeyAlgo().size() > static_cast<size_t>(index)); diff --git a/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp b/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp index 74f827aa..10a1ac00 100644 --- a/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp @@ -366,7 +366,6 @@ void KeyPairOperaTab::slot_modify_tofu_policy() { this, tr("Modify TOFU Policy(Default is Auto)"), tr("Policy for the Key Pair:"), items, 0, false, &ok); if (ok && !item.isEmpty()) { - GF_UI_LOG_DEBUG("selected policy: {}", item); gpgme_tofu_policy_t tofu_policy = GPGME_TOFU_POLICY_AUTO; if (item == tr("Policy Auto")) { tofu_policy = GPGME_TOFU_POLICY_AUTO; @@ -445,7 +444,7 @@ void KeyPairOperaTab::slot_import_revoke_cert() { return; } - emit UISignalStation::GetInstance()->SignalKeyRevoked(m_key_.GetId()); + emit UISignalStation::GetInstance() -> SignalKeyRevoked(m_key_.GetId()); CommonUtils::GetInstance()->SlotImportKeys(nullptr, rev_file.readAll()); } } // namespace GpgFrontend::UI diff --git a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp index 2a9a4c96..1d463aad 100644 --- a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp @@ -175,9 +175,6 @@ void KeyPairSubkeyTab::slot_refresh_subkey_list() { this->buffered_subkeys_.push_back(std::move(sub_key)); } - GF_UI_LOG_DEBUG("buffered_subkeys_ refreshed size", - this->buffered_subkeys_.size()); - subkey_list_->setRowCount(buffered_subkeys_.size()); for (const auto& subkeys : buffered_subkeys_) { @@ -211,12 +208,10 @@ void KeyPairSubkeyTab::slot_refresh_subkey_list() { } } - GF_UI_LOG_DEBUG("subkey_list_ item {} refreshed", row); - row++; } - GF_UI_LOG_DEBUG("subkey_list_ refreshed"); + qCDebug(ui, "subkey_list_ refreshed"); if (subkey_list_->rowCount() > 0) { subkey_list_->selectRow(0); @@ -309,8 +304,6 @@ void KeyPairSubkeyTab::create_subkey_opera_menu() { } void KeyPairSubkeyTab::slot_edit_subkey() { - GF_UI_LOG_DEBUG("fpr {}", get_selected_subkey().GetFingerprint()); - auto* dialog = new KeySetExpireDateDialog( key_.GetId(), get_selected_subkey().GetFingerprint(), this); dialog->show(); diff --git a/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp b/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp index 47cae8c1..5b0a8271 100644 --- a/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp @@ -228,7 +228,6 @@ void KeyPairUIDTab::slot_refresh_tofu_info() { continue; } auto tofu_infos = uid.GetTofuInfos(); - GF_UI_LOG_DEBUG("tofu info size: {}", tofu_infos->size()); if (tofu_infos->empty()) { tofu_tabs_->hide(); } else { @@ -383,7 +382,6 @@ void KeyPairUIDTab::slot_del_uid() { if (ret == QMessageBox::Yes) { for (const auto& uid : *selected_uids) { - GF_UI_LOG_DEBUG("uid: {}", uid); if (!GpgUIDOperator::GetInstance().RevUID(m_key_, uid)) { QMessageBox::critical( nullptr, tr("Operation Failed"), diff --git a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp index 43fb6f3b..9ab1350c 100644 --- a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp +++ b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp @@ -58,18 +58,10 @@ KeySetExpireDateDialog::KeySetExpireDateDialog(const KeyId& key_id, } void KeySetExpireDateDialog::slot_confirm() { - GF_UI_LOG_DEBUG("confirm called, date: {}, time: {}", - ui_->dateEdit->date().toString(), - ui_->timeEdit->time().toString()); auto datetime = QDateTime(ui_->dateEdit->date(), ui_->timeEdit->time()); std::unique_ptr<QDateTime> expires = nullptr; if (ui_->noExpirationCheckBox->checkState() == Qt::Unchecked) { expires = std::make_unique<QDateTime>(datetime.toLocalTime()); - - GF_UI_LOG_DEBUG("keyid: {}", m_key_.GetId(), m_subkey_, - expires->toSecsSinceEpoch()); - } else { - GF_UI_LOG_DEBUG("keyid: {}", m_key_.GetId(), m_subkey_, "Non Expired"); } auto err = GpgKeyOpera::GetInstance().SetExpire(m_key_, m_subkey_, expires); diff --git a/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp b/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp index 983e7e2d..07c7b688 100644 --- a/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp +++ b/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp @@ -104,13 +104,9 @@ void KeyUIDSignDialog::slot_sign_key(bool clicked) { // Set Signers auto key_ids = m_key_list_->GetChecked(); auto keys = GpgKeyGetter::GetInstance().GetKeys(key_ids); - - GF_UI_LOG_DEBUG("key info got"); auto expires = std::make_unique<QDateTime>(expires_edit_->dateTime()); - GF_UI_LOG_DEBUG("sign start"); for (const auto& uid : *m_uids_) { - GF_UI_LOG_DEBUG("sign uid: {}", uid); // Sign For mKey if (!GpgKeyManager::GetInstance().SignKey(m_key_, *keys, uid, expires)) { QMessageBox::critical( diff --git a/src/ui/dialog/settings/SettingsAppearance.cpp b/src/ui/dialog/settings/SettingsAppearance.cpp index f09f9823..6f9961c0 100644 --- a/src/ui/dialog/settings/SettingsAppearance.cpp +++ b/src/ui/dialog/settings/SettingsAppearance.cpp @@ -141,16 +141,9 @@ void AppearanceTab::SetSettings() { auto target_theme_index = ui_->themeComboBox->findText(theme); if (theme.isEmpty() || target_theme_index == -1) { #ifdef QT5_BUILD - GF_UI_LOG_DEBUG( - "There is not valid theme found from settings, " - "using current theme (qt5): {}", - QApplication::style()->metaObject()->className()); ui_->themeComboBox->setCurrentIndex(ui_->themeComboBox->findText( QApplication::style()->metaObject()->className())); #else - GF_UI_LOG_DEBUG( - "There is not valid theme found from settings, using current theme: {}", - QApplication::style()->name()); ui_->themeComboBox->setCurrentIndex( ui_->themeComboBox->findText(QApplication::style()->name())); #endif diff --git a/src/ui/dialog/settings/SettingsDialog.cpp b/src/ui/dialog/settings/SettingsDialog.cpp index 70b8c7b0..0f171dea 100644 --- a/src/ui/dialog/settings/SettingsDialog.cpp +++ b/src/ui/dialog/settings/SettingsDialog.cpp @@ -112,7 +112,6 @@ void SettingsDialog::SlotAccept() { key_server_tab_->ApplySettings(); network_tab_->ApplySettings(); - GF_UI_LOG_DEBUG("ui restart status: {}", restart_mode_); if (restart_mode_ != kNonRestartCode) { emit SignalRestartNeeded(restart_mode_); } @@ -125,8 +124,6 @@ auto SettingsDialog::ListLanguages() -> QHash<QString, QString> { auto filenames = QDir(QLatin1String(":/i18n")).entryList(); for (const auto& file : filenames) { - GF_UI_LOG_DEBUG("get locale from locale directory: {}", file); - auto start = file.indexOf('.') + 1; auto end = file.lastIndexOf('.'); if (start < 0 || end < 0 || start >= end) continue; diff --git a/src/ui/dialog/settings/SettingsGeneral.cpp b/src/ui/dialog/settings/SettingsGeneral.cpp index 3a6cbf70..81557b0d 100644 --- a/src/ui/dialog/settings/SettingsGeneral.cpp +++ b/src/ui/dialog/settings/SettingsGeneral.cpp @@ -136,7 +136,6 @@ void GeneralTab::SetSettings() { auto lang_key = settings.value("basic/lang").toString(); auto lang_value = lang_.value(lang_key); - GF_UI_LOG_DEBUG("lang settings current: {}", lang_value); if (!lang_.empty()) { ui_->langSelectBox->setCurrentIndex( ui_->langSelectBox->findText(lang_value)); diff --git a/src/ui/dialog/settings/SettingsKeyServer.cpp b/src/ui/dialog/settings/SettingsKeyServer.cpp index fb6e624c..d3e4578c 100644 --- a/src/ui/dialog/settings/SettingsKeyServer.cpp +++ b/src/ui/dialog/settings/SettingsKeyServer.cpp @@ -78,7 +78,6 @@ KeyserverTab::KeyserverTab(QWidget* parent) connect(ui_->keyServerListTable, &QTableWidget::itemChanged, [=](QTableWidgetItem* item) { - GF_UI_LOG_DEBUG("item edited: {}", item->column()); if (item->column() != 1) return; const auto row_size = ui_->keyServerListTable->rowCount(); // Update Actions @@ -180,8 +179,6 @@ void KeyserverTab::ApplySettings() { } void KeyserverTab::slot_refresh_table() { - GF_UI_LOG_INFO("start refreshing key server table"); - ui_->keyServerListTable->blockSignals(true); ui_->keyServerListTable->setRowCount(key_server_str_list_.size()); diff --git a/src/ui/function/GenerateRevokeCertification.cpp b/src/ui/function/GenerateRevokeCertification.cpp index 9f8afcff..f9b655a3 100644 --- a/src/ui/function/GenerateRevokeCertification.cpp +++ b/src/ui/function/GenerateRevokeCertification.cpp @@ -48,14 +48,12 @@ auto GenerateRevokeCertification::Exec(const GpgKey& key, output_path, "--gen-revoke", key.GetFingerprint()}, [=](int exit_code, const QString& p_out, const QString& p_err) { if (exit_code != 0) { - GF_UI_LOG_ERROR( - "gnupg gen revoke execute error, process stderr: {}, process " - "stdout: {}", - p_err, p_out); + qCWarning(ui) << "gnupg gen revoke execute error, process stderr: " + << p_err << ", process stdout: " << p_out; } else { - GF_UI_LOG_DEBUG( - "gnupg gen revoke exit_code: {}, process stdout size: {}", - exit_code, p_out.size()); + qCDebug(ui, + "gnupg gen revoke exit_code: %d, process stdout size: %lld", + exit_code, p_out.size()); } }, nullptr, @@ -63,7 +61,6 @@ auto GenerateRevokeCertification::Exec(const GpgKey& key, // Code From Gpg4Win while (proc->canReadLine()) { const QString line = QString::fromUtf8(proc->readLine()).trimmed(); - GF_UI_LOG_DEBUG("line: {}", line); if (line == QLatin1String("[GNUPG:] GET_BOOL gen_revoke.okay")) { proc->write("y\n"); } else if (line == QLatin1String("[GNUPG:] GET_LINE " diff --git a/src/ui/function/RaisePinentry.cpp b/src/ui/function/RaisePinentry.cpp index 7c68d67c..b119c5f8 100644 --- a/src/ui/function/RaisePinentry.cpp +++ b/src/ui/function/RaisePinentry.cpp @@ -39,8 +39,6 @@ auto FindTopMostWindow(QWidget* fallback) -> QWidget* { QList<QWidget*> top_widgets = QApplication::topLevelWidgets(); foreach (QWidget* widget, top_widgets) { if (widget->isActiveWindow()) { - GF_UI_LOG_TRACE("find a topmost widget, address: {}", - static_cast<void*>(widget)); return widget; } } @@ -52,12 +50,6 @@ RaisePinentry::RaisePinentry(QWidget* parent, : QWidget(parent), context_(std::move(context)) {} auto RaisePinentry::Exec() -> int { - GF_UI_LOG_DEBUG( - "setting pinetry's arguments, context uids: {}, passphrase info: {}, " - "prev_was_bad: {}", - context_->GetUidsInfo(), context_->GetPassphraseInfo(), - context_->IsPreWasBad()); - bool ask_for_new = context_->IsAskForNew() && context_->GetPassphraseInfo().isEmpty() && context_->GetUidsInfo().isEmpty(); @@ -95,15 +87,13 @@ auto RaisePinentry::Exec() -> int { pinentry->setOkText(tr("Confirm")); pinentry->setCancelText(tr("Cancel")); - GF_UI_LOG_DEBUG("buddled pinentry is ready to start..."); connect(pinentry, &PinEntryDialog::finished, this, [pinentry, this](int result) { bool ret = result != 0; - GF_UI_LOG_DEBUG("buddled pinentry finished, ret: {}", ret); if (!ret) { emit CoreSignalStation::GetInstance() - ->SignalUserInputPassphraseCallback({}); + -> SignalUserInputPassphraseCallback({}); return -1; } @@ -111,7 +101,7 @@ auto RaisePinentry::Exec() -> int { context_->SetPassphrase(pin); emit CoreSignalStation::GetInstance() - ->SignalUserInputPassphraseCallback(context_); + -> SignalUserInputPassphraseCallback(context_); return 0; }); connect(pinentry, &PinEntryDialog::finished, this, &QWidget::deleteLater); diff --git a/src/ui/function/SetOwnerTrustLevel.cpp b/src/ui/function/SetOwnerTrustLevel.cpp index 87f4cb61..29697eaa 100644 --- a/src/ui/function/SetOwnerTrustLevel.cpp +++ b/src/ui/function/SetOwnerTrustLevel.cpp @@ -54,7 +54,6 @@ auto SetOwnerTrustLevel::Exec(const QString& key_id) -> bool { key.GetOwnerTrustLevel(), false, &ok); if (ok && !item.isEmpty()) { - GF_UI_LOG_DEBUG("selected owner trust policy: {}", item); int trust_level = 0; // Unknown Level if (item == tr("Ultimate")) { trust_level = 5; @@ -86,7 +85,7 @@ auto SetOwnerTrustLevel::Exec(const QString& key_id) -> bool { } // update key database and refresh ui - emit UISignalStation::GetInstance()->SignalKeyDatabaseRefresh(); + emit UISignalStation::GetInstance() -> SignalKeyDatabaseRefresh(); return true; } diff --git a/src/ui/main_window/GeneralMainWindow.cpp b/src/ui/main_window/GeneralMainWindow.cpp index 3d662332..3c689dfe 100644 --- a/src/ui/main_window/GeneralMainWindow.cpp +++ b/src/ui/main_window/GeneralMainWindow.cpp @@ -45,10 +45,7 @@ GpgFrontend::UI::GeneralMainWindow::GeneralMainWindow(QString name, GpgFrontend::UI::GeneralMainWindow::~GeneralMainWindow() = default; void GpgFrontend::UI::GeneralMainWindow::closeEvent(QCloseEvent *event) { - GF_UI_LOG_DEBUG("main window close event caught, event type: {}", - event->type()); slot_save_settings(); - QMainWindow::closeEvent(event); } @@ -56,9 +53,6 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { try { WindowStateSO window_state(SettingsObject(name_ + "_state")); - GF_UI_LOG_DEBUG("restore main window state: {}", - window_state.window_state_data); - if (!window_state.window_state_data.isEmpty()) { // state sets pos & size of dock-widgets this->restoreState( @@ -73,9 +67,6 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { size_ = {window_state.width, window_state.height}; if (this->parent() != nullptr) { - GF_UI_LOG_DEBUG("parent address: {}", - static_cast<void *>(this->parent())); - QPoint parent_pos = {0, 0}; QSize parent_size = {0, 0}; @@ -91,12 +82,6 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { parent_size = parent_window->size(); } - GF_UI_LOG_DEBUG("parent pos x: {} y: {}", parent_pos.x(), - parent_pos.y()); - - GF_UI_LOG_DEBUG("parent size width: {} height: {}", parent_size.width(), - parent_size.height()); - if (parent_pos != QPoint{0, 0}) { QPoint const parent_center{parent_pos.x() + parent_size.width() / 2, parent_pos.y() + parent_size.height() / 2}; @@ -127,13 +112,12 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { icon_style_ = toolButtonStyle(); } catch (...) { - GF_UI_LOG_ERROR("general main window: {}, caught exception", name_); + qCWarning(ui) << "general main window: " << name_ << ", caught exception"; } } void GpgFrontend::UI::GeneralMainWindow::slot_save_settings() noexcept { try { - GF_UI_LOG_DEBUG("save main window state, name: {}", name_); SettingsObject general_windows_state(name_ + "_state"); // update geo of current dialog @@ -150,7 +134,7 @@ void GpgFrontend::UI::GeneralMainWindow::slot_save_settings() noexcept { general_windows_state.Store(window_state.Json()); } catch (...) { - GF_UI_LOG_ERROR("general main window: {}, caught exception", name_); + qCWarning(ui) << "general main window: " << name_ << ", caught exception"; } } @@ -158,11 +142,6 @@ void GeneralMainWindow::setPosCenterOfScreen() { // update cache update_rect_cache(); - int screen_width = screen_rect_.width(); - int screen_height = screen_rect_.height(); - GF_UI_LOG_DEBUG("dialog current screen available geometry", screen_width, - screen_height); - // update rect of current dialog rect_ = this->geometry(); this->move(screen_rect_.center() - @@ -173,16 +152,6 @@ void GeneralMainWindow::movePosition2CenterOfParent() { // update cache update_rect_cache(); - // log for debug - GF_UI_LOG_DEBUG("parent pos x: {} y: {}", parent_rect_.x(), parent_rect_.y()); - GF_UI_LOG_DEBUG("parent size width: {}, height: {}", parent_rect_.width(), - parent_rect_.height()); - GF_UI_LOG_DEBUG("parent center pos x: {}, y: {}", parent_rect_.center().x(), - parent_rect_.center().y()); - GF_UI_LOG_DEBUG("dialog pos x: {} y: {}", rect_.x(), rect_.y()); - GF_UI_LOG_DEBUG("dialog size width: {} height: {}", rect_.width(), - rect_.height()); - if (parent_rect_.topLeft() != QPoint{0, 0} && parent_rect_.size() != QSize{0, 0}) { if (rect_.width() <= 0) rect_.setWidth(100); @@ -191,10 +160,6 @@ void GeneralMainWindow::movePosition2CenterOfParent() { QPoint target_position = parent_rect_.center() - QPoint(rect_.width() / 2, rect_.height() / 2); - GF_UI_LOG_DEBUG( - "update position to parent's center, target pos, x:{}, y: {}", - target_position.x(), target_position.y()); - this->move(target_position); } else { setPosCenterOfScreen(); diff --git a/src/ui/main_window/KeyMgmt.cpp b/src/ui/main_window/KeyMgmt.cpp index bb158a2b..09746140 100644 --- a/src/ui/main_window/KeyMgmt.cpp +++ b/src/ui/main_window/KeyMgmt.cpp @@ -413,7 +413,7 @@ void KeyMgmt::SlotExportKeyToClipboard() { } if (data_obj == nullptr || !data_obj->Check<GFBuffer>()) { - GF_CORE_LOG_ERROR("data object checking failed"); + qCWarning(ui, "data object checking failed"); QMessageBox::critical(this, tr("Error"), tr("Unknown error occurred")); return; @@ -572,7 +572,6 @@ void KeyMgmt::SlotImportKeyPackage() { return; } - GF_UI_LOG_INFO("importing key package: {}", key_package_file_name); CommonUtils::WaitForOpera( this, tr("Importing"), [=](const OperaWaitingHd& op_hd) { KeyPackageOperator::ImportKeyPackage( diff --git a/src/ui/main_window/MainWindow.cpp b/src/ui/main_window/MainWindow.cpp index 868112a0..1e795325 100644 --- a/src/ui/main_window/MainWindow.cpp +++ b/src/ui/main_window/MainWindow.cpp @@ -136,9 +136,9 @@ void MainWindow::Init() noexcept { Module::ListenRTPublishEvent( this, kVersionCheckingModuleID, "version.loading_done", [=](Module::Namespace, Module::Key, int, std::any) { - GF_UI_LOG_DEBUG( - "version-checking version.loading_done changed, calling slot " - "version upgrade"); + qCDebug(ui, + "version-checking version.loading_done changed, calling slot " + "version upgrade"); this->slot_version_upgrade_notify(); }); @@ -155,7 +155,7 @@ void MainWindow::Init() noexcept { if (show_wizard) slot_start_wizard(); } catch (...) { - GF_UI_LOG_ERROR(tr("Critical error occur while loading GpgFrontend.")); + qCWarning(ui) << tr("Critical error occur while loading GpgFrontend."); QMessageBox::critical( nullptr, tr("Loading Failed"), tr("Critical error occur while loading GpgFrontend.")); @@ -165,8 +165,6 @@ void MainWindow::Init() noexcept { } void MainWindow::restore_settings() { - GF_UI_LOG_DEBUG("restore settings for main windows"); - KeyServerSO key_server(SettingsObject("key_server")); if (key_server.server_list.empty()) key_server.ResetDefaultServerList(); if (key_server.default_server < 0) key_server.default_server = 0; @@ -181,8 +179,6 @@ void MainWindow::restore_settings() { prohibit_update_checking_ = settings.value("network/prohibit_update_check").toBool(); - - GF_UI_LOG_DEBUG("settings restored"); } void MainWindow::recover_editor_unsaved_pages_from_cache() { @@ -193,9 +189,6 @@ void MainWindow::recover_editor_unsaved_pages_from_cache() { return; } - GF_UI_LOG_DEBUG("plan ot recover unsaved page from cache, page array: {}", - json_data.toJson()); - bool first = true; auto unsaved_page_array = json_data.array(); @@ -211,10 +204,6 @@ void MainWindow::recover_editor_unsaved_pages_from_cache() { auto title = unsaved_page_json["title"].toString(); auto content = unsaved_page_json["content"].toString(); - GF_UI_LOG_DEBUG( - "recovering unsaved page from cache, page title: {}, content size", - title, content.size()); - if (first) { edit_->SlotCloseTab(); first = false; diff --git a/src/ui/main_window/MainWindowFileSlotFunction.cpp b/src/ui/main_window/MainWindowFileSlotFunction.cpp index bc3accfa..3d151ce6 100644 --- a/src/ui/main_window/MainWindowFileSlotFunction.cpp +++ b/src/ui/main_window/MainWindowFileSlotFunction.cpp @@ -282,7 +282,6 @@ void MainWindow::SlotFileDecrypt(const QString& path) { } auto out_path = SetExtensionOfOutputFile(path, kDECRYPT, true); - GF_UI_LOG_DEBUG("file decrypt target output path: {}", out_path); if (QFileInfo(out_path).exists()) { auto ret = QMessageBox::warning( this, tr("Warning"), @@ -332,7 +331,6 @@ void MainWindow::SlotArchiveDecrypt(const QString& path) { } auto out_path = SetExtensionOfOutputFileForArchive(path, kDECRYPT, true); - GF_UI_LOG_DEBUG("archive decrypt target output path: {}", out_path); if (QFileInfo(out_path).exists()) { auto ret = QMessageBox::warning( this, tr("Warning"), @@ -493,9 +491,6 @@ void MainWindow::SlotFileVerify(const QString& path) { return; } - GF_UI_LOG_DEBUG("verification data file path: {}", data_file_path); - GF_UI_LOG_DEBUG("verification signature file path: {}", sign_file_path); - CommonUtils::WaitForOpera( this, tr("Verifying"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().VerifyFile( @@ -817,7 +812,6 @@ void MainWindow::SlotArchiveDecryptVerify(const QString& path) { auto out_path = SetExtensionOfOutputFileForArchive(path, kDECRYPT_VERIFY, true); - GF_UI_LOG_INFO("out_path: {}", out_path); check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, tr("Error"), diff --git a/src/ui/main_window/MainWindowGpgOperaFunction.cpp b/src/ui/main_window/MainWindowGpgOperaFunction.cpp index 3cef497d..d197e336 100644 --- a/src/ui/main_window/MainWindowGpgOperaFunction.cpp +++ b/src/ui/main_window/MainWindowGpgOperaFunction.cpp @@ -295,14 +295,6 @@ void MainWindow::SlotEncryptSign() { auto signer_key_ids = signers_picker->GetCheckedSigners(); auto signer_keys = GpgKeyGetter::GetInstance().GetKeys(signer_key_ids); - for (const auto& key : *keys) { - GF_UI_LOG_DEBUG("keys {}", key.GetEmail()); - } - - for (const auto& signer : *signer_keys) { - GF_UI_LOG_DEBUG("signers {}", signer.GetEmail()); - } - // data to transfer into task auto buffer = GFBuffer(edit_->CurTextPage()->GetTextPage()->toPlainText()); diff --git a/src/ui/main_window/MainWindowSlotFunction.cpp b/src/ui/main_window/MainWindowSlotFunction.cpp index e0df6710..f1754be7 100644 --- a/src/ui/main_window/MainWindowSlotFunction.cpp +++ b/src/ui/main_window/MainWindowSlotFunction.cpp @@ -63,14 +63,14 @@ void MainWindow::slot_append_selected_keys() { auto key_ids = m_key_list_->GetSelected(); if (key_ids->empty()) { - GF_UI_LOG_ERROR("no key is selected to export"); + qCWarning(ui, "no key is selected to export"); return; } auto key = GpgKeyGetter::GetInstance().GetKey(key_ids->front()); if (!key.IsGood()) { - GF_UI_LOG_ERROR("selected key for exporting is invalid, key id: {}", - key_ids->front()); + qCWarning(ui) << "selected key for exporting is invalid, key id: " + << key_ids->front(); return; } @@ -88,7 +88,7 @@ void MainWindow::slot_append_keys_create_datetime() { auto key_ids = m_key_list_->GetSelected(); if (key_ids->empty()) { - GF_UI_LOG_ERROR("no key is selected"); + qCWarning(ui, "no key is selected"); return; } @@ -112,7 +112,7 @@ void MainWindow::slot_append_keys_expire_datetime() { auto key_ids = m_key_list_->GetSelected(); if (key_ids->empty()) { - GF_UI_LOG_ERROR("no key is selected"); + qCWarning(ui, "no key is selected"); return; } @@ -202,7 +202,6 @@ void MainWindow::slot_show_key_details() { void MainWindow::slot_add_key_2_favourite() { auto key_ids = m_key_list_->GetSelected(); if (key_ids->empty()) return; - GF_UI_LOG_DEBUG("get selected key id: {}", key_ids->front()); auto key = GpgKeyGetter::GetInstance().GetKey(key_ids->front()); if (!key.IsGood()) return; @@ -265,15 +264,14 @@ void MainWindow::SlotOpenFile(const QString& path) { } void MainWindow::slot_version_upgrade_notify() { - GF_UI_LOG_DEBUG( + qCDebug( + ui, "slot version upgrade notify called, checking version info from rt..."); + auto is_loading_done = Module::RetrieveRTValueTypedOrDefault<>( kVersionCheckingModuleID, "version.loading_done", false); - - GF_UI_LOG_DEBUG("checking version info from rt, is loading done state: {}", - is_loading_done); if (!is_loading_done) { - GF_UI_LOG_ERROR("invalid version info from rt, loading hasn't done yet"); + qCWarning(ui, "invalid version info from rt, loading hasn't done yet"); return; } @@ -289,12 +287,6 @@ void MainWindow::slot_version_upgrade_notify() { auto latest_version = Module::RetrieveRTValueTypedOrDefault<>( kVersionCheckingModuleID, "version.latest_version", QString{}); - GF_UI_LOG_DEBUG( - "got version info from rt, need upgrade: {}, with drawn: {}, " - "current version released: {}", - is_need_upgrade, is_current_a_withdrawn_version, - is_current_version_released); - if (is_need_upgrade) { statusBar()->showMessage( tr("GpgFrontend Upgradeable (New Version: %1).").arg(latest_version), diff --git a/src/ui/main_window/MainWindowSlotUI.cpp b/src/ui/main_window/MainWindowSlotUI.cpp index 39ceedc6..d2b39ee7 100644 --- a/src/ui/main_window/MainWindowSlotUI.cpp +++ b/src/ui/main_window/MainWindowSlotUI.cpp @@ -98,7 +98,6 @@ void MainWindow::slot_disable_tab_actions(int number) { add_pgp_header_act_->setDisabled(disable); if (edit_->CurFilePage() != nullptr) { - GF_UI_LOG_DEBUG("edit current page is file page"); auto* file_page = edit_->CurFilePage(); emit file_page->SignalCurrentTabChanged(); } @@ -109,9 +108,6 @@ void MainWindow::slot_open_settings_dialog() { connect(dialog, &SettingsDialog::finished, this, [&]() -> void { AppearanceSO appearance(SettingsObject("general_settings_state")); - GF_UI_LOG_DEBUG("tool bar icon_size: {}, {}", - appearance.tool_bar_icon_width, - appearance.tool_bar_icon_height); this->setToolButtonStyle(appearance.tool_bar_button_style); import_button_->setToolButtonStyle(appearance.tool_bar_button_style); @@ -182,14 +178,10 @@ void MainWindow::slot_cut_pgp_header() { edit_->SlotFillTextEditWithText(content.trimmed()); } -void MainWindow::SlotSetRestartNeeded(int mode) { - GF_UI_LOG_DEBUG("restart mode: {}", mode); - this->restart_mode_ = mode; -} +void MainWindow::SlotSetRestartNeeded(int mode) { this->restart_mode_ = mode; } void MainWindow::SlotUpdateCryptoMenuStatus(unsigned int type) { MainWindow::CryptoMenu::OperationType opera_type = type; - GF_UI_LOG_DEBUG("update crypto menu status, type: {}", opera_type); // refresh status to disable all verify_act_->setDisabled(true); diff --git a/src/ui/thread/KeyServerImportTask.cpp b/src/ui/thread/KeyServerImportTask.cpp index 8bcb2eab..e3662db2 100644 --- a/src/ui/thread/KeyServerImportTask.cpp +++ b/src/ui/thread/KeyServerImportTask.cpp @@ -44,8 +44,6 @@ GpgFrontend::UI::KeyServerImportTask::KeyServerImportTask( if (keyserver_url_.isEmpty()) { KeyServerSO key_server(SettingsObject("general_settings_state")); keyserver_url_ = key_server.GetTargetServer(); - GF_UI_LOG_DEBUG("key server import task sets key server url: {}", - keyserver_url_); } } @@ -71,8 +69,9 @@ void GpgFrontend::UI::KeyServerImportTask::dealing_reply_from_server() { auto buffer = reply_->readAll(); if (network_reply != QNetworkReply::NoError) { - GF_UI_LOG_ERROR("key import error, message from key server reply: ", - buffer); + qCWarning(ui) << "key import error, message from key server reply: " + << buffer; + QString err_msg; switch (network_reply) { case QNetworkReply::ContentNotFoundError: diff --git a/src/ui/thread/ListedKeyServerTestTask.cpp b/src/ui/thread/ListedKeyServerTestTask.cpp index 5f7e2dca..1d492735 100644 --- a/src/ui/thread/ListedKeyServerTestTask.cpp +++ b/src/ui/thread/ListedKeyServerTestTask.cpp @@ -48,7 +48,6 @@ auto GpgFrontend::UI::ListedKeyServerTestTask::Run() -> int { size_t index = 0; for (const auto& url : urls_) { auto key_url = QUrl{url}; - GF_UI_LOG_DEBUG("key server request: {}", key_url.host()); auto request = QNetworkRequest(key_url); request.setHeader(QNetworkRequest::UserAgentHeader, @@ -59,12 +58,10 @@ auto GpgFrontend::UI::ListedKeyServerTestTask::Run() -> int { connect(network_reply, &QNetworkReply::finished, this, [this, index, network_reply]() { - GF_UI_LOG_DEBUG("key server domain reply: {}", urls_[index]); this->slot_process_network_reply(index, network_reply); }); connect(timer, &QTimer::timeout, this, [this, index, network_reply]() { - GF_UI_LOG_DEBUG("timeout for key server: {}", urls_[index]); if (network_reply->isRunning()) { network_reply->abort(); this->slot_process_network_reply(index, network_reply); diff --git a/src/ui/thread/ProxyConnectionTestTask.cpp b/src/ui/thread/ProxyConnectionTestTask.cpp index c1d2f3e6..7d2c496f 100644 --- a/src/ui/thread/ProxyConnectionTestTask.cpp +++ b/src/ui/thread/ProxyConnectionTestTask.cpp @@ -51,12 +51,10 @@ auto GpgFrontend::UI::ProxyConnectionTestTask::Run() -> int { connect(network_reply, &QNetworkReply::finished, this, [this, network_reply]() { - GF_UI_LOG_DEBUG("key server domain reply: {} received", url_); this->slot_process_network_reply(network_reply); }); connect(timer, &QTimer::timeout, this, [this, network_reply]() { - GF_UI_LOG_DEBUG("timeout for key server: {}", url_); if (network_reply->isRunning()) { network_reply->abort(); this->slot_process_network_reply(network_reply); @@ -70,8 +68,6 @@ auto GpgFrontend::UI::ProxyConnectionTestTask::Run() -> int { void GpgFrontend::UI::ProxyConnectionTestTask::slot_process_network_reply( QNetworkReply* reply) { auto buffer = reply->readAll(); - GF_UI_LOG_DEBUG("key server domain reply: {}, buffer size: {}", url_, - buffer.size()); if (reply->error() == QNetworkReply::NoError && !buffer.isEmpty()) { result_ = "Reachable"; diff --git a/src/ui/widgets/FilePage.cpp b/src/ui/widgets/FilePage.cpp index d99bfc53..f44aa12b 100644 --- a/src/ui/widgets/FilePage.cpp +++ b/src/ui/widgets/FilePage.cpp @@ -117,7 +117,6 @@ void FilePage::SlotGoPath() { } void FilePage::keyPressEvent(QKeyEvent* event) { - GF_UI_LOG_DEBUG("file page notices key press by user: {}", event->key()); if (ui_->pathEdit->hasFocus() && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)) { SlotGoPath(); diff --git a/src/ui/widgets/FileTreeView.cpp b/src/ui/widgets/FileTreeView.cpp index de22ec83..c40741d4 100644 --- a/src/ui/widgets/FileTreeView.cpp +++ b/src/ui/widgets/FileTreeView.cpp @@ -63,12 +63,11 @@ FileTreeView::FileTreeView(QWidget* parent, const QString& target_path) void FileTreeView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { QTreeView::selectionChanged(selected, deselected); - GF_UI_LOG_DEBUG( - "file tree view selected changed, selected: {}, deselected: {}", - selected.size(), deselected.size()); + qCDebug(ui, "file tree view selected changed, selected: {}, deselected: {}", + selected.size(), deselected.size()); + if (!selected.indexes().empty()) { selected_path_ = dir_model_->filePath(selected.indexes().first()); - GF_UI_LOG_DEBUG("file tree view selected target path: {}", selected_path_); emit SignalSelectedChanged(selected_path_); } else { selected_path_ = QString(); @@ -83,7 +82,6 @@ void FileTreeView::SlotGoPath(const QString& target_path) { auto file_info = QFileInfo(target_path); if (file_info.isDir() && file_info.isReadable() && file_info.isExecutable()) { current_path_ = file_info.absoluteFilePath(); - GF_UI_LOG_DEBUG("file tree view set target path: {}", current_path_); this->setRootIndex(dir_model_->index(file_info.filePath())); dir_model_->setRootPath(file_info.filePath()); slot_adjust_column_widths(); @@ -116,7 +114,6 @@ void FileTreeView::SlotUpLevel() { auto target_path = dir_model_->fileInfo(current_root).absoluteFilePath(); if (auto parent_path = QDir(target_path); parent_path.cdUp()) { target_path = parent_path.absolutePath(); - GF_UI_LOG_DEBUG("file tree view go parent path: {}", target_path); this->SlotGoPath(target_path); } current_path_ = target_path; @@ -145,9 +142,7 @@ auto FileTreeView::GetPathByClickPoint(const QPoint& point) -> QString { return {}; } - auto index_path = dir_model_->fileInfo(index).absoluteFilePath(); - GF_UI_LOG_DEBUG("file tree view right click on: {}", index_path); - return index_path; + return dir_model_->fileInfo(index).absoluteFilePath(); } auto FileTreeView::GetSelectedPath() -> QString { return selected_path_; } @@ -162,8 +157,6 @@ auto FileTreeView::SlotDeleteSelectedItem() -> void { if (ret == QMessageBox::Cancel) return; - GF_UI_LOG_DEBUG("delete item: {}", data.toString()); - if (!dir_model_->remove(index)) { QMessageBox::critical(this, tr("Error"), tr("Unable to delete the file or folder.")); @@ -207,7 +200,6 @@ void FileTreeView::SlotTouch() { QLineEdit::Normal, new_file_name, &ok); if (ok && !new_file_name.isEmpty()) { auto file_path = root_path + "/" + new_file_name; - GF_UI_LOG_DEBUG("new file path: {}", file_path); QFile new_file(file_path); if (!new_file.open(QIODevice::WriteOnly | QIODevice::NewOnly)) { @@ -229,7 +221,6 @@ void FileTreeView::SlotTouchBelowAtSelectedItem() { QLineEdit::Normal, new_file_name, &ok); if (ok && !new_file_name.isEmpty()) { auto file_path = root_path + "/" + new_file_name; - GF_UI_LOG_DEBUG("new file path: {}", file_path); QFile new_file(file_path); if (!new_file.open(QIODevice::WriteOnly | QIODevice::NewOnly)) { @@ -272,7 +263,7 @@ void FileTreeView::SlotRenameSelectedItem() { if (ok && !text.isEmpty()) { auto file_info = QFileInfo(selected_path_); auto new_name_path = file_info.absolutePath() + "/" + text; - GF_UI_LOG_DEBUG("new filename path: {}", new_name_path); + if (!QDir().rename(file_info.absoluteFilePath(), new_name_path)) { QMessageBox::critical(this, tr("Error"), tr("Unable to rename the file or folder.")); @@ -355,8 +346,6 @@ void FileTreeView::slot_show_custom_context_menu(const QPoint& point) { auto target_path = this->GetPathByClickPoint(point); auto select_path = GetSelectedPath(); - GF_UI_LOG_DEBUG("file tree view, target path: {}, select path: {}", - target_path, select_path); if (target_path.isEmpty() && !select_path.isEmpty()) { target_path = select_path; } @@ -404,8 +393,9 @@ void FileTreeView::slot_calculate_hash() { return; } auto result = ExtractParams<QString>(data_object, 0); - emit UISignalStation::GetInstance()->SignalRefreshInfoBoard( - result, InfoBoardStatus::INFO_ERROR_OK); + emit UISignalStation::GetInstance() + -> SignalRefreshInfoBoard(result, + InfoBoardStatus::INFO_ERROR_OK); }, "calculate_file_hash"); }); diff --git a/src/ui/widgets/InfoBoardWidget.cpp b/src/ui/widgets/InfoBoardWidget.cpp index 425e6ccd..10b8ad83 100644 --- a/src/ui/widgets/InfoBoardWidget.cpp +++ b/src/ui/widgets/InfoBoardWidget.cpp @@ -115,7 +115,6 @@ void InfoBoardWidget::AssociateTabWidget(QTabWidget* tab) { void InfoBoardWidget::AddOptionalAction(const QString& name, const std::function<void()>& action) { - GF_UI_LOG_DEBUG("add option action: {}", name); auto* action_button = new QPushButton(name); auto* layout = new QHBoxLayout(); layout->setContentsMargins(5, 0, 5, 0); @@ -165,7 +164,6 @@ void InfoBoardWidget::slot_copy() { void InfoBoardWidget::slot_save() { auto file_path = QFileDialog::getSaveFileName( this, tr("Save Information Board's Content"), {}, tr("Text (*.txt)")); - GF_UI_LOG_DEBUG("file path: {}", file_path); if (file_path.isEmpty()) return; QFile file(file_path); diff --git a/src/ui/widgets/KeyList.cpp b/src/ui/widgets/KeyList.cpp index 74aa29cc..f3db2d15 100644 --- a/src/ui/widgets/KeyList.cpp +++ b/src/ui/widgets/KeyList.cpp @@ -350,7 +350,7 @@ auto KeyList::GetSelected() -> KeyIdArgsListPtr { auto* key_table = qobject_cast<KeyTable*>(ui_->keyGroupTab->currentWidget()); if (key_table == nullptr) { - GF_UI_LOG_ERROR("fail to get current key table, nullptr"); + qCWarning(ui, "fail to get current key table, nullptr"); return ret; } @@ -360,7 +360,7 @@ auto KeyList::GetSelected() -> KeyIdArgsListPtr { } if (ret->empty()) { - GF_UI_LOG_WARN("nothing is selected at key list"); + qCWarning(ui, "nothing is selected at key list"); } return ret; } @@ -389,15 +389,13 @@ void KeyList::contextMenuEvent(QContextMenuEvent* event) { auto* key_table = qobject_cast<KeyTable*>(ui_->keyGroupTab->currentWidget()); if (key_table == nullptr) { - GF_UI_LOG_DEBUG("m_key_list_ is nullptr, key group tab number: {}", - ui_->keyGroupTab->count()); + qCDebug(ui, "m_key_list_ is nullptr, key group tab number: %d", + ui_->keyGroupTab->count()); return; } QString current_tab_widget_obj_name = ui_->keyGroupTab->widget(ui_->keyGroupTab->currentIndex())->objectName(); - GF_UI_LOG_DEBUG("current tab widget object name: {}", - current_tab_widget_obj_name); if (current_tab_widget_obj_name == "favourite") { auto actions = popup_menu_->actions(); for (QAction* action : actions) { @@ -470,7 +468,7 @@ void KeyList::dropEvent(QDropEvent* event) { QFile file; file.setFileName(tmp.toLocalFile()); if (!file.open(QIODevice::ReadOnly)) { - GF_UI_LOG_ERROR("couldn't open file: {}", tmp.toString()); + qCWarning(ui) << "couldn't open file: " << tmp.toString(); } auto in_buffer = file.readAll(); this->import_keys(in_buffer); @@ -553,8 +551,6 @@ void KeyList::slot_sync_with_key_server() { CommonUtils::SlotImportKeyFromKeyServer( key_ids, [=](const QString& key_id, const QString& status, size_t current_index, size_t all_index) { - GF_UI_LOG_DEBUG("import key: {} {} {} {}", key_id, status, - current_index, all_index); auto key = GpgKeyGetter::GetInstance().GetKey(key_id); auto status_str = tr("Sync [%1/%2] %3 %4") @@ -577,8 +573,6 @@ void KeyList::filter_by_keyword() { auto keyword = ui_->searchBarEdit->text(); keyword = keyword.trimmed(); - GF_UI_LOG_DEBUG("get new keyword of search bar: {}", keyword); - for (int i = 0; i < ui_->keyGroupTab->count(); i++) { auto* key_table = qobject_cast<KeyTable*>(ui_->keyGroupTab->widget(i)); // refresh arguments diff --git a/src/ui/widgets/PlainTextEditorPage.cpp b/src/ui/widgets/PlainTextEditorPage.cpp index 874bbf3b..57910f9d 100644 --- a/src/ui/widgets/PlainTextEditorPage.cpp +++ b/src/ui/widgets/PlainTextEditorPage.cpp @@ -164,7 +164,7 @@ void PlainTextEditorPage::ReadFile() { [=]() { emit read_task->SignalTaskShouldEnd(0); }); connect(read_task, &FileReadTask::SignalFileBytesReadEnd, this, [=]() { // set the UI - GF_UI_LOG_DEBUG("signal file bytes read end rised"); + qCDebug(ui, "signal file bytes read end rised"); this->read_done_ = true; text_page->setEnabled(true); text_page->document()->setModified(false); @@ -186,8 +186,6 @@ auto BinaryToString(const QByteArray &source) -> QString { } void PlainTextEditorPage::slot_insert_text(QByteArray bytes_data) { - GF_UI_LOG_TRACE("inserting data read to editor, data size: {}", - bytes_data.size()); read_bytes_ += bytes_data.size(); // insert the text to the text page diff --git a/src/ui/widgets/TextEdit.cpp b/src/ui/widgets/TextEdit.cpp index a0dba5f5..9cecfb38 100644 --- a/src/ui/widgets/TextEdit.cpp +++ b/src/ui/widgets/TextEdit.cpp @@ -120,7 +120,6 @@ void TextEdit::SlotNewFileTab() { void TextEdit::SlotOpenFile(const QString& path) { QFile file(path); - GF_UI_LOG_DEBUG("main window editor is opening file at path: {}", path); auto result = file.open(QIODevice::ReadOnly | QIODevice::Text); if (result) { auto* page = new PlainTextEditorPage(path); @@ -510,7 +509,6 @@ QHash<int, QString> TextEdit::UnsavedDocuments() const { if (ep != nullptr && ep->ReadDone() && ep->GetTextPage()->document()->isModified()) { QString doc_name = tab_widget_->tabText(i); - GF_UI_LOG_DEBUG("unsaved: {}", doc_name); // remove * before name of modified doc doc_name.remove(0, 2); @@ -601,8 +599,8 @@ void TextEdit::slot_file_page_path_changed(const QString& path) const { } tab_widget_->setTabText(index, m_path); - emit UISignalStation::GetInstance()->SignalMainWindowlUpdateBasicalOperaMenu( - 0); + emit UISignalStation::GetInstance() + -> SignalMainWindowlUpdateBasicalOperaMenu(0); } void TextEdit::slot_save_status_to_cache_for_revovery() { @@ -614,17 +612,11 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { bool restore_text_editor_page = settings.value("basic/restore_text_editor_page", false).toBool(); if (!restore_text_editor_page) { - GF_UI_LOG_DEBUG("restore_text_editor_page is false, ignoring..."); + qCDebug(ui, "restore_text_editor_page is false, ignoring..."); return; } int tab_count = tab_widget_->count(); - GF_UI_LOG_DEBUG( - "restore_text_editor_page is true, pan to save pages, current tabs " - "count: " - "{}", - tab_count); - std::vector<std::tuple<int, QString, QString>> unsaved_pages; for (int i = 0; i < tab_count; i++) { @@ -643,9 +635,7 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { continue; } - auto raw_text = document->toRawText(); - GF_UI_LOG_DEBUG("unsaved page index: {}, tab title: {}", i, tab_title); - unsaved_pages.emplace_back(i, tab_title, raw_text); + unsaved_pages.emplace_back(i, tab_title, document->toRawText()); } CacheObject cache("editor_unsaved_pages"); diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt index 8752a291..3c0b07ab 100644 --- a/third_party/CMakeLists.txt +++ b/third_party/CMakeLists.txt @@ -27,8 +27,6 @@ # json set(JSON_BuildTests OFF CACHE INTERNAL "") -add_subdirectory(spdlog EXCLUDE_FROM_ALL) - if (MINGW) add_subdirectory(libarchive EXCLUDE_FROM_ALL) endif() diff --git a/third_party/spdlog b/third_party/spdlog deleted file mode 160000 -Subproject eb3220622e73a4889eee355ffa37972b3cac3df |