diff options
author | saturneric <[email protected]> | 2024-01-12 06:02:37 +0000 |
---|---|---|
committer | saturneric <[email protected]> | 2024-01-12 06:02:37 +0000 |
commit | bf538056b24a68b8fd235b1c50991ee8eb46a776 (patch) | |
tree | e1bab54095b80df62b321fb5bd69453f9f951b05 /src | |
parent | feat: improve api and ui of keys import and export (diff) | |
download | GpgFrontend-bf538056b24a68b8fd235b1c50991ee8eb46a776.tar.gz GpgFrontend-bf538056b24a68b8fd235b1c50991ee8eb46a776.zip |
refactor: use QString instead of std::string and improve threading system
Diffstat (limited to 'src')
189 files changed, 2313 insertions, 2533 deletions
diff --git a/src/core/GpgCoreInit.cpp b/src/core/GpgCoreInit.cpp index 5a3b2d6d..3ad5bce6 100644 --- a/src/core/GpgCoreInit.cpp +++ b/src/core/GpgCoreInit.cpp @@ -50,36 +50,30 @@ namespace GpgFrontend { void DestroyGpgFrontendCore() { SingletonStorageCollection::Destroy(); } -auto VerifyGpgconfPath(const std::filesystem::path& gnupg_install_fs_path) - -> bool { - return gnupg_install_fs_path.is_absolute() && - std::filesystem::exists(gnupg_install_fs_path) && - std::filesystem::is_regular_file(gnupg_install_fs_path); +auto VerifyGpgconfPath(const QFileInfo& gnupg_install_fs_path) -> bool { + return gnupg_install_fs_path.isAbsolute() && gnupg_install_fs_path.exists() && + gnupg_install_fs_path.isFile(); } -auto VerifyKeyDatabasePath(const std::filesystem::path& key_database_fs_path) - -> bool { - return key_database_fs_path.is_absolute() && - std::filesystem::exists(key_database_fs_path) && - std::filesystem::is_directory(key_database_fs_path); +auto VerifyKeyDatabasePath(const QFileInfo& key_database_fs_path) -> bool { + return key_database_fs_path.isAbsolute() && key_database_fs_path.exists() && + key_database_fs_path.isDir(); } -auto SearchGpgconfPath(const std::vector<std::string>& candidate_paths) - -> std::filesystem::path { +auto SearchGpgconfPath(const QList<QString>& candidate_paths) -> QString { for (const auto& path : candidate_paths) { - if (VerifyGpgconfPath(std::filesystem::path{path})) { - return std::filesystem::path{path}; + if (VerifyGpgconfPath(QFileInfo(path))) { + return path; } } return {}; } -auto SearchKeyDatabasePath(const std::vector<std::string>& candidate_paths) - -> std::filesystem::path { +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(std::filesystem::path{path})) { - return std::filesystem::path{path}; + if (VerifyKeyDatabasePath(QFileInfo(path))) { + return path; } } return {}; @@ -88,7 +82,7 @@ auto SearchKeyDatabasePath(const std::vector<std::string>& candidate_paths) auto InitGpgME() -> bool { // init gpgme subsystem and get gpgme library version Module::UpsertRTValue("core", "gpgme.version", - std::string(gpgme_check_version(nullptr))); + QString(gpgme_check_version(nullptr))); gpgme_set_locale(nullptr, LC_CTYPE, setlocale(LC_CTYPE, nullptr)); #ifdef LC_MESSAGES @@ -115,11 +109,11 @@ auto InitGpgME() -> bool { GF_CORE_LOG_DEBUG( "gpg context engine info: {} {} {} {}", gpgme_get_protocol_name(engine_info->protocol), - std::string(engine_info->file_name == nullptr ? "null" - : engine_info->file_name), - std::string(engine_info->home_dir == nullptr ? "null" - : engine_info->home_dir), - std::string(engine_info->version ? "null" : engine_info->version)); + 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: @@ -127,19 +121,19 @@ auto InitGpgME() -> bool { Module::UpsertRTValue("core", "gpgme.engine.openpgp", 1); Module::UpsertRTValue("core", "gpgme.ctx.app_path", - std::string(engine_info->file_name)); + QString(engine_info->file_name)); Module::UpsertRTValue("core", "gpgme.ctx.gnupg_version", - std::string(engine_info->version)); - Module::UpsertRTValue("core", "gpgme.ctx.database_path", - std::string(engine_info->home_dir == nullptr - ? "default" - : engine_info->home_dir)); + QString(engine_info->version)); + Module::UpsertRTValue( + "core", "gpgme.ctx.database_path", + QString(engine_info->home_dir == nullptr ? "default" + : engine_info->home_dir)); break; case GPGME_PROTOCOL_CMS: find_cms = true; Module::UpsertRTValue("core", "gpgme.engine.cms", 1); Module::UpsertRTValue("core", "gpgme.ctx.cms_path", - std::string(engine_info->file_name)); + QString(engine_info->file_name)); break; case GPGME_PROTOCOL_GPGCONF: @@ -147,13 +141,13 @@ auto InitGpgME() -> bool { Module::UpsertRTValue("core", "gpgme.engine.gpgconf", 1); Module::UpsertRTValue("core", "gpgme.ctx.gpgconf_path", - std::string(engine_info->file_name)); + QString(engine_info->file_name)); break; case GPGME_PROTOCOL_ASSUAN: Module::UpsertRTValue("core", "gpgme.engine.assuan", 1); Module::UpsertRTValue("core", "gpgme.ctx.assuan_path", - std::string(engine_info->file_name)); + QString(engine_info->file_name)); break; case GPGME_PROTOCOL_G13: break; @@ -173,7 +167,7 @@ auto InitGpgME() -> bool { gpgme_release(p_ctx); const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gnupg_version", std::string{"0.0.0"}); + "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 @@ -226,7 +220,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { auto custom_key_database_path = GlobalSettingStation::GetInstance().LookupSettings( - "general.custom_key_database_path", std::string{}); + "general.custom_key_database_path", QString{}); auto use_custom_gnupg_install_path = GlobalSettingStation::GetInstance().LookupSettings( @@ -234,7 +228,7 @@ void InitGpgFrontendCore(CoreInitArgs args) { auto custom_gnupg_install_path = GlobalSettingStation::GetInstance().LookupSettings( - "general.custom_gnupg_install_path", std::string{}); + "general.custom_gnupg_install_path", QString{}); auto use_pinentry_as_password_input_dialog = GpgFrontend::GlobalSettingStation::GetInstance().LookupSettings( @@ -245,25 +239,25 @@ void InitGpgFrontendCore(CoreInitArgs args) { GF_CORE_LOG_DEBUG("core loaded custom key databse path: {}", custom_key_database_path); - std::filesystem::path gnupg_install_fs_path; + QString gnupg_install_fs_path; // user defined - if (!custom_gnupg_install_path.empty()) { + if (!custom_gnupg_install_path.isEmpty()) { // check gpgconf path gnupg_install_fs_path = custom_gnupg_install_path; #ifdef WINDOWS - custom_gnupg_install_fs_path /= "gpgconf.exe"; + gnupg_install_fs_path += "/gpgconf.exe"; #else - gnupg_install_fs_path /= "gpgconf"; + gnupg_install_fs_path += "/gpgconf"; #endif - if (!VerifyGpgconfPath(gnupg_install_fs_path)) { + if (!VerifyGpgconfPath(QFileInfo(gnupg_install_fs_path))) { use_custom_gnupg_install_path = false; GF_CORE_LOG_ERROR( "core loaded custom gpgconf path is illegal: {}", - gnupg_install_fs_path.u8string()); + gnupg_install_fs_path); } else { GF_CORE_LOG_DEBUG("core loaded custom gpgconf path: {}", - gnupg_install_fs_path.u8string()); + gnupg_install_fs_path); } } else { #ifdef MACOS @@ -271,32 +265,32 @@ void InitGpgFrontendCore(CoreInitArgs args) { 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.u8string()); + gnupg_install_fs_path); #endif } // check key database path - std::filesystem::path key_database_fs_path; + QString key_database_fs_path; // user defined - if (!custom_key_database_path.empty()) { + if (!custom_key_database_path.isEmpty()) { key_database_fs_path = custom_key_database_path; - if (VerifyKeyDatabasePath(key_database_fs_path)) { + if (VerifyKeyDatabasePath(QFileInfo(key_database_fs_path))) { GF_CORE_LOG_ERROR( "core loaded custom gpg key database is illegal: {}", - key_database_fs_path.u8string()); + 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.u8string()); + key_database_fs_path); } } else { #ifdef MACOS use_custom_key_database_path = true; - key_database_fs_path = SearchKeyDatabasePath( - {QDir::home().filesystemPath() / ".gnupg"}); + key_database_fs_path = + SearchKeyDatabasePath({QDir::home().path() + "/.gnupg"}); GF_CORE_LOG_DEBUG("core loaded searched key database path: {}", - key_database_fs_path.u8string()); + key_database_fs_path); #endif } @@ -308,15 +302,14 @@ void InitGpgFrontendCore(CoreInitArgs args) { // set key database path if (use_custom_key_database_path && - !key_database_fs_path.empty()) { - args.db_path = key_database_fs_path.u8string(); + !key_database_fs_path.isEmpty()) { + args.db_path = key_database_fs_path; } // set custom gnupg path if (use_custom_gnupg_install_path) { args.custom_gpgconf = true; - args.custom_gpgconf_path = - gnupg_install_fs_path.u8string(); + args.custom_gpgconf_path = gnupg_install_fs_path; } args.offline_mode = forbid_all_gnupg_connection; diff --git a/src/core/GpgFrontendCore.h b/src/core/GpgFrontendCore.h index 1d00aac6..3aaa8ab4 100644 --- a/src/core/GpgFrontendCore.h +++ b/src/core/GpgFrontendCore.h @@ -41,6 +41,9 @@ #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE #include <spdlog/spdlog.h> +// logger fmt +#include "log/QtLoggerFmt.h" + // gpgme library #include <gpgme.h> diff --git a/src/core/function/CacheManager.cpp b/src/core/function/CacheManager.cpp index cf1417fb..88d3bddd 100644 --- a/src/core/function/CacheManager.cpp +++ b/src/core/function/CacheManager.cpp @@ -29,7 +29,6 @@ #include "CacheManager.h" #include <algorithm> -#include <boost/format.hpp> #include <shared_mutex> #include <utility> @@ -73,7 +72,7 @@ class ThreadSafeMap { return *this; } - auto remove(std::string key) -> bool { + auto remove(QString key) -> bool { std::unique_lock lock(mutex_); auto it = map_->find(key); if (it != map_->end()) { @@ -102,14 +101,14 @@ class CacheManager::Impl : public QObject { load_all_cache_storage(); } - void SaveCache(std::string key, const nlohmann::json& value, bool flush) { + void SaveCache(QString key, const nlohmann::json& value, bool flush) { auto data_object_key = get_data_object_key(key); cache_storage_.insert(key, value); - if (std::find(key_storage_.begin(), key_storage_.end(), key) == - key_storage_.end()) { + if (std::find(key_storage_.begin(), key_storage_.end(), + key.toStdString()) == key_storage_.end()) { GF_CORE_LOG_DEBUG("register new key of cache", key); - key_storage_.push_back(key); + key_storage_.push_back(key.toStdString()); } if (flush) { @@ -117,7 +116,7 @@ class CacheManager::Impl : public QObject { } } - auto LoadCache(const std::string& key) -> nlohmann::json { + auto LoadCache(const QString& key) -> nlohmann::json { auto data_object_key = get_data_object_key(key); if (!cache_storage_.exists(key)) { @@ -131,7 +130,7 @@ class CacheManager::Impl : public QObject { return {}; } - auto LoadCache(const std::string& key, nlohmann::json default_value) + auto LoadCache(const QString& key, nlohmann::json default_value) -> nlohmann::json { auto data_object_key = get_data_object_key(key); if (!cache_storage_.exists(key)) { @@ -146,7 +145,7 @@ class CacheManager::Impl : public QObject { return {}; } - auto ResetCache(const std::string& key) -> bool { + auto ResetCache(const QString& key) -> bool { auto data_object_key = get_data_object_key(key); return cache_storage_.remove(key); } @@ -170,19 +169,19 @@ class CacheManager::Impl : public QObject { } private: - ThreadSafeMap<std::string, nlohmann::json> cache_storage_; + ThreadSafeMap<QString, nlohmann::json> cache_storage_; nlohmann::json key_storage_; QTimer* flush_timer_; - const std::string drk_key_ = "__cache_manage_data_register_key_list"; + const QString drk_key_ = "__cache_manage_data_register_key_list"; /** * @brief Get the data object key object * * @param key - * @return std::string + * @return QString */ - static auto get_data_object_key(std::string key) -> std::string { - return (boost::format("__cache_data_%1%") % key).str(); + static auto get_data_object_key(QString key) -> QString { + return QString("__cache_data_%1").arg(key); } /** @@ -192,7 +191,7 @@ class CacheManager::Impl : public QObject { * @param default_value * @return nlohmann::json */ - static auto load_cache_storage(std::string key, nlohmann::json default_value) + static auto load_cache_storage(QString key, nlohmann::json default_value) -> nlohmann::json { auto data_object_key = get_data_object_key(std::move(key)); auto stored_data = @@ -228,7 +227,7 @@ class CacheManager::Impl : public QObject { } for (const auto& key : registered_key_list) { - load_cache_storage(key, {}); + load_cache_storage(QString::fromStdString(key), {}); } key_storage_ = registered_key_list; @@ -239,7 +238,7 @@ class CacheManager::Impl : public QObject { * * @param key */ - void register_cache_key(const std::string& key) {} + void register_cache_key(const QString& key) {} }; CacheManager::CacheManager(int channel) @@ -248,21 +247,21 @@ CacheManager::CacheManager(int channel) CacheManager::~CacheManager() = default; -void CacheManager::SaveCache(std::string key, const nlohmann::json& value, +void CacheManager::SaveCache(QString key, const nlohmann::json& value, bool flush) { p_->SaveCache(std::move(key), value, flush); } -auto CacheManager::LoadCache(std::string key) -> nlohmann::json { +auto CacheManager::LoadCache(QString key) -> nlohmann::json { return p_->LoadCache(key); } -auto CacheManager::LoadCache(std::string key, nlohmann::json default_value) +auto CacheManager::LoadCache(QString key, nlohmann::json default_value) -> nlohmann::json { return p_->LoadCache(key, std::move(default_value)); } -auto CacheManager::ResetCache(std::string key) -> bool { +auto CacheManager::ResetCache(QString key) -> bool { return p_->ResetCache(key); } diff --git a/src/core/function/CacheManager.h b/src/core/function/CacheManager.h index 0cb893a2..9e95096d 100644 --- a/src/core/function/CacheManager.h +++ b/src/core/function/CacheManager.h @@ -42,15 +42,13 @@ class GPGFRONTEND_CORE_EXPORT CacheManager ~CacheManager() override; - void SaveCache(std::string key, const nlohmann::json& value, - bool flush = false); + void SaveCache(QString key, const nlohmann::json& value, bool flush = false); - auto LoadCache(std::string key) -> nlohmann::json; + auto LoadCache(QString key) -> nlohmann::json; - auto LoadCache(std::string key, nlohmann::json default_value) - -> nlohmann::json; + auto LoadCache(QString key, nlohmann::json default_value) -> nlohmann::json; - auto ResetCache(std::string key) -> bool; + auto ResetCache(QString key) -> bool; private: class Impl; diff --git a/src/core/function/CharsetOperator.cpp b/src/core/function/CharsetOperator.cpp index 40978701..023fcd10 100644 --- a/src/core/function/CharsetOperator.cpp +++ b/src/core/function/CharsetOperator.cpp @@ -28,109 +28,19 @@ #include "core/function/CharsetOperator.h" -#include <unicode/ucnv.h> -#include <unicode/ucsdet.h> -#include <unicode/ustring.h> -#include <unicode/utypes.h> - -#include <cstddef> - #include "core/utils/LogUtils.h" namespace GpgFrontend { -auto CharsetOperator::Detect(const std::string &buffer) +auto CharsetOperator::Detect(const QString &buffer) -> CharsetOperator::CharsetInfo { - const UCharsetMatch *ucm; - UErrorCode status = U_ZERO_ERROR; - UCharsetDetector *csd = ucsdet_open(&status); - - status = U_ZERO_ERROR; - if (U_FAILURE(status) != 0) { - GF_CORE_LOG_ERROR("failed to open charset detector: {}", - u_errorName(status)); - return {"unknown", "unknown", 0}; - } - - status = U_ZERO_ERROR; - ucsdet_setText(csd, buffer.data(), buffer.size(), &status); - if (U_FAILURE(status) != 0) { - GF_CORE_LOG_ERROR("failed to set text to charset detector: {}", - u_errorName(status)); - return {"unknown", "unknown", 0}; - } - - status = U_ZERO_ERROR; - ucm = ucsdet_detect(csd, &status); - - if (U_FAILURE(status) != 0) return {"unknown", "unknown", 0}; - - status = U_ZERO_ERROR; - const char *name = ucsdet_getName(ucm, &status); - if (U_FAILURE(status) != 0) return {"unknown", "unknown", 0}; - - status = U_ZERO_ERROR; - int confidence = ucsdet_getConfidence(ucm, &status); - if (U_FAILURE(status) != 0) return {name, "unknown", 0}; - - status = U_ZERO_ERROR; - const char *language = ucsdet_getLanguage(ucm, &status); - if (U_FAILURE(status) != 0) return {name, "unknown", confidence}; - - GF_CORE_LOG_DEBUG("detected charset: {} {} {}", name, language, confidence); - return {name, language, confidence}; + // TODO + return {"", "", 0}; } -auto CharsetOperator::Convert2Utf8(const std::string &buffer, - std::string &out_buffer, - std::string from_charset_name) -> bool { - UErrorCode status = U_ZERO_ERROR; - const auto from_encode = std::string("utf-8"); - const auto &to_encode = from_charset_name; - - GF_CORE_LOG_DEBUG("Converting buffer: {}", buffer.size()); - - // test if the charset is supported - UConverter *conv = ucnv_open(from_encode.c_str(), &status); - ucnv_close(conv); - if (U_FAILURE(status) != 0) { - GF_CORE_LOG_ERROR("failed to open converter: {}, from encode: {}", - u_errorName(status), from_encode); - return false; - } - - // test if the charset is supported - conv = ucnv_open(to_encode.c_str(), &status); - ucnv_close(conv); - if (U_FAILURE(status) != 0) { - GF_CORE_LOG_ERROR("failed to open converter: {}, to encode: {}", - u_errorName(status), to_encode); - return false; - } - - status = U_ZERO_ERROR; - int32_t target_limit = 0; - int32_t target_capacity = 0; - - target_capacity = - ucnv_convert(from_encode.c_str(), to_encode.c_str(), nullptr, - target_limit, buffer.data(), buffer.size(), &status); - - if (status == U_BUFFER_OVERFLOW_ERROR) { - status = U_ZERO_ERROR; - out_buffer.clear(); - out_buffer.resize(target_capacity); - ucnv_convert(from_encode.c_str(), to_encode.c_str(), out_buffer.data(), - out_buffer.size(), buffer.data(), buffer.size(), &status); - } - - if (U_FAILURE(status) != 0) { - GF_CORE_LOG_ERROR("failed to convert to utf-8: {}", u_errorName(status)); - return false; - } - - GF_CORE_LOG_DEBUG("converted buffer: {} bytes", out_buffer.size()); - return true; +auto CharsetOperator::Convert2Utf8(const QString &buffer, QString &out_buffer, + QString from_charset_name) -> bool { + // TODO } } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/CharsetOperator.h b/src/core/function/CharsetOperator.h index c7092797..c005f8b6 100644 --- a/src/core/function/CharsetOperator.h +++ b/src/core/function/CharsetOperator.h @@ -34,11 +34,11 @@ namespace GpgFrontend { class GPGFRONTEND_CORE_EXPORT CharsetOperator { public: - using CharsetInfo = std::tuple<std::string, std::string, int>; + using CharsetInfo = std::tuple<QString, QString, int>; - static auto Detect(const std::string &buffer) -> CharsetInfo; + static auto Detect(const QString &buffer) -> CharsetInfo; - static auto Convert2Utf8(const std::string &buffer, std::string &out_buffer, - std::string from_charset_name) -> bool; + static auto Convert2Utf8(const QString &buffer, QString &out_buffer, + QString from_charset_name) -> bool; }; } // namespace GpgFrontend diff --git a/src/core/function/CoreSignalStation.h b/src/core/function/CoreSignalStation.h index f4d6a142..e0a11fa3 100644 --- a/src/core/function/CoreSignalStation.h +++ b/src/core/function/CoreSignalStation.h @@ -32,6 +32,8 @@ namespace GpgFrontend { +class GpgPassphraseContext; + /** * @brief * @@ -54,13 +56,13 @@ class GPGFRONTEND_CORE_EXPORT CoreSignalStation : public QObject { * @brief * */ - void SignalNeedUserInputPassphrase(); + void SignalNeedUserInputPassphrase(QSharedPointer<GpgPassphraseContext>); /** * @brief * */ - void SignalUserInputPassphraseCallback(QByteArray); + void SignalUserInputPassphraseCallback(QSharedPointer<GpgPassphraseContext>); /** * @brief diff --git a/src/core/function/DataObjectOperator.cpp b/src/core/function/DataObjectOperator.cpp index 437e6f11..f756e3e7 100644 --- a/src/core/function/DataObjectOperator.cpp +++ b/src/core/function/DataObjectOperator.cpp @@ -30,8 +30,6 @@ #include <qt-aes/qaesencryption.h> -#include <boost/date_time.hpp> - #include "core/function/PassphraseGenerator.h" #include "core/utils/IOUtils.h" @@ -39,8 +37,8 @@ namespace GpgFrontend { void DataObjectOperator::init_app_secure_key() { GF_CORE_LOG_TRACE("initializing application secure key"); - WriteFileStd(app_secure_key_path_, - PassphraseGenerator::GetInstance().Generate(256)); + WriteFile(app_secure_key_path_.c_str(), + PassphraseGenerator::GetInstance().Generate(256).toUtf8()); std::filesystem::permissions( app_secure_key_path_, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); @@ -54,42 +52,37 @@ DataObjectOperator::DataObjectOperator(int channel) init_app_secure_key(); } - std::string key; - if (!ReadFileStd(app_secure_key_path_.u8string(), key)) { + QByteArray key; + if (!ReadFile(app_secure_key_path_.c_str(), key)) { GF_CORE_LOG_ERROR("failed to read app secure key file: {}", app_secure_key_path_.u8string()); throw std::runtime_error("failed to read app secure key file"); } - hash_key_ = QCryptographicHash::hash(QByteArray::fromStdString(key), - QCryptographicHash::Sha256); + hash_key_ = QCryptographicHash::hash(key, QCryptographicHash::Sha256); GF_CORE_LOG_TRACE("app secure key loaded {} bytes", hash_key_.size()); if (!exists(app_data_objs_path_)) create_directory(app_data_objs_path_); } -auto DataObjectOperator::SaveDataObj(const std::string& _key, - const nlohmann::json& value) - -> std::string { - std::string hash_obj_key = {}; - if (_key.empty()) { +auto DataObjectOperator::SaveDataObj(const QString& _key, + const nlohmann::json& value) -> QString { + QByteArray hash_obj_key = {}; + if (_key.isEmpty()) { hash_obj_key = QCryptographicHash::hash( - hash_key_ + QByteArray::fromStdString( - PassphraseGenerator::GetInstance().Generate(32) + - to_iso_extended_string( - boost::posix_time::second_clock::local_time())), + hash_key_ + .append( + PassphraseGenerator::GetInstance().Generate(32).toUtf8()) + .append(QDateTime::currentDateTime().toString().toUtf8()), QCryptographicHash::Sha256) - .toHex() - .toStdString(); + .toHex(); } else { - hash_obj_key = - QCryptographicHash::hash(hash_key_ + QByteArray::fromStdString(_key), - QCryptographicHash::Sha256) - .toHex() - .toStdString(); + hash_obj_key = QCryptographicHash::hash(hash_key_.append(_key.toUtf8()), + QCryptographicHash::Sha256) + .toHex(); } - const auto obj_path = app_data_objs_path_ / hash_obj_key; + const auto obj_path = app_data_objs_path_ / hash_obj_key.toStdString(); QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); @@ -98,17 +91,17 @@ auto DataObjectOperator::SaveDataObj(const std::string& _key, GF_CORE_LOG_TRACE("saving data object {} to {} , size: {} bytes", hash_obj_key, obj_path.u8string(), encoded.size()); - WriteFileStd(obj_path.u8string(), encoded.toStdString()); + WriteFile(obj_path.c_str(), encoded); - return _key.empty() ? hash_obj_key : std::string(); + return _key.isEmpty() ? hash_obj_key : QString(); } -auto DataObjectOperator::GetDataObject(const std::string& _key) +auto DataObjectOperator::GetDataObject(const QString& _key) -> std::optional<nlohmann::json> { try { GF_CORE_LOG_TRACE("get data object from disk {}", _key); auto hash_obj_key = - QCryptographicHash::hash(hash_key_ + QByteArray::fromStdString(_key), + QCryptographicHash::hash(hash_key_.append(_key.toUtf8()), QCryptographicHash::Sha256) .toHex() .toStdString(); @@ -120,21 +113,20 @@ auto DataObjectOperator::GetDataObject(const std::string& _key) return {}; } - std::string buffer; - if (!ReadFileStd(obj_path.u8string(), buffer)) { + QByteArray encoded_data; + if (!ReadFile(obj_path.c_str(), encoded_data)) { GF_CORE_LOG_ERROR("failed to read data object, key: {}", _key); return {}; } - auto encoded = QByteArray::fromStdString(buffer); QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); GF_CORE_LOG_TRACE("decrypting data object {} , hash key size: {}", - encoded.size(), hash_key_.size()); + encoded_data.size(), hash_key_.size()); auto decoded = - encryption.removePadding(encryption.decode(encoded, hash_key_)); + encryption.removePadding(encryption.decode(encoded_data, hash_key_)); GF_CORE_LOG_TRACE("data object decoded: {}", _key); @@ -145,25 +137,24 @@ auto DataObjectOperator::GetDataObject(const std::string& _key) } } -auto DataObjectOperator::GetDataObjectByRef(const std::string& _ref) +auto DataObjectOperator::GetDataObjectByRef(const QString& _ref) -> std::optional<nlohmann::json> { if (_ref.size() != 64) return {}; try { const auto& hash_obj_key = _ref; - const auto obj_path = app_data_objs_path_ / hash_obj_key; + const auto obj_path = app_data_objs_path_ / hash_obj_key.toStdString(); if (!std::filesystem::exists(obj_path)) return {}; - std::string buffer; - if (!ReadFileStd(obj_path.u8string(), buffer)) return {}; - auto encoded = QByteArray::fromStdString(buffer); + QByteArray encoded_data; + if (!ReadFile(obj_path.c_str(), encoded_data)) return {}; QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); auto decoded = - encryption.removePadding(encryption.decode(encoded, hash_key_)); + encryption.removePadding(encryption.decode(encoded_data, hash_key_)); return nlohmann::json::parse(decoded.toStdString()); } catch (...) { diff --git a/src/core/function/DataObjectOperator.h b/src/core/function/DataObjectOperator.h index 06455211..a262bfc2 100644 --- a/src/core/function/DataObjectOperator.h +++ b/src/core/function/DataObjectOperator.h @@ -28,7 +28,6 @@ #pragma once -#include <boost/format.hpp> #include <nlohmann/json.hpp> #include <optional> @@ -48,13 +47,11 @@ class GPGFRONTEND_CORE_EXPORT DataObjectOperator explicit DataObjectOperator( int channel = SingletonFunctionObject::GetDefaultChannel()); - auto SaveDataObj(const std::string &_key, const nlohmann::json &value) - -> std::string; + auto SaveDataObj(const QString &_key, const nlohmann::json &value) -> QString; - auto GetDataObject(const std::string &_key) -> std::optional<nlohmann::json>; + auto GetDataObject(const QString &_key) -> std::optional<nlohmann::json>; - auto GetDataObjectByRef(const std::string &_ref) - -> std::optional<nlohmann::json>; + auto GetDataObjectByRef(const QString &_ref) -> std::optional<nlohmann::json>; private: /** @@ -75,9 +72,7 @@ class GPGFRONTEND_CORE_EXPORT DataObjectOperator ///< object is ///< stored - std::random_device rd_; ///< Random device - std::mt19937 mt_ = std::mt19937(rd_()); ///< Mersenne twister - QByteArray hash_key_; ///< Hash key + QByteArray hash_key_; ///< Hash key }; } // namespace GpgFrontend diff --git a/src/core/function/GlobalSettingStation.cpp b/src/core/function/GlobalSettingStation.cpp index 09dd1c90..53220a18 100644 --- a/src/core/function/GlobalSettingStation.cpp +++ b/src/core/function/GlobalSettingStation.cpp @@ -109,11 +109,11 @@ class GlobalSettingStation::Impl { return ui_cfg_.getRoot(); } - [[nodiscard]] auto GetLogFilesSize() const -> std::string { + [[nodiscard]] auto GetLogFilesSize() const -> QString { return GetHumanFriendlyFileSize(GetFileSizeByPath(app_log_path_, "*.log")); } - [[nodiscard]] auto GetDataObjectsFilesSize() const -> std::string { + [[nodiscard]] auto GetDataObjectsFilesSize() const -> QString { return GetHumanFriendlyFileSize( GetFileSizeByPath(app_data_objs_path_, "*")); } @@ -132,10 +132,10 @@ class GlobalSettingStation::Impl { * @return libconfig::Setting& */ template <typename T> - auto LookupSettings(std::string path, T default_value) noexcept -> T { + auto LookupSettings(QString path, T default_value) noexcept -> T { T value = default_value; try { - value = static_cast<T>(GetMainSettings().lookup(path)); + value = static_cast<T>(GetMainSettings().lookup(path.toStdString())); } catch (...) { GF_CORE_LOG_WARN("setting not found: {}", path); } @@ -252,7 +252,7 @@ class GlobalSettingStation::Impl { #ifdef LINUX_INSTALL_BUILD std::filesystem::path app_locale_path_ = - std::string(APP_LOCALE_PATH); ///< Program Data Location + QString(APP_LOCALE_PATH); ///< Program Data Location #else std::filesystem::path app_locale_path_ = app_resource_path_ / "locales"; ///< Program Data Location @@ -325,11 +325,11 @@ auto GlobalSettingStation::GetCertsDir() const -> std::filesystem::path { return p_->GetCertsDir(); } -auto GlobalSettingStation::GetLogFilesSize() const -> std::string { +auto GlobalSettingStation::GetLogFilesSize() const -> QString { return p_->GetLogFilesSize(); } -auto GlobalSettingStation::GetDataObjectsFilesSize() const -> std::string { +auto GlobalSettingStation::GetDataObjectsFilesSize() const -> QString { return p_->GetDataObjectsFilesSize(); } diff --git a/src/core/function/GlobalSettingStation.h b/src/core/function/GlobalSettingStation.h index 06f37264..5611161b 100644 --- a/src/core/function/GlobalSettingStation.h +++ b/src/core/function/GlobalSettingStation.h @@ -122,16 +122,16 @@ class GPGFRONTEND_CORE_EXPORT GlobalSettingStation /** * @brief Get the Log Files Size object * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetLogFilesSize() const -> std::string; + [[nodiscard]] auto GetLogFilesSize() const -> QString; /** * @brief Get the Data Objects Files Size object * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetDataObjectsFilesSize() const -> std::string; + [[nodiscard]] auto GetDataObjectsFilesSize() const -> QString; /** * @brief clear all log files @@ -158,10 +158,10 @@ class GPGFRONTEND_CORE_EXPORT GlobalSettingStation * @return The setting value. */ template <typename T> - auto LookupSettings(std::string path, T default_value) noexcept -> T { + auto LookupSettings(QString path, T default_value) noexcept -> T { T value = default_value; try { - value = static_cast<T>(GetMainSettings().lookup(path)); + value = static_cast<T>(GetMainSettings().lookup(path.toStdString())); } catch (...) { GF_CORE_LOG_WARN("setting not found: {}", path); } @@ -175,12 +175,12 @@ class GPGFRONTEND_CORE_EXPORT GlobalSettingStation * @return The setting value. */ template <typename T> - auto SaveSettings(std::string path, libconfig::Setting::Type type, + auto SaveSettings(QString path, libconfig::Setting::Type type, T value) noexcept -> T { try { - if (!GetMainSettings().exists(path)) { + if (!GetMainSettings().exists(path.toStdString())) { // TODO - GetMainSettings().add(path, type); + GetMainSettings().add(path.toStdString(), type); } } catch (...) { GF_CORE_LOG_WARN("setting not found: {}", path); diff --git a/src/core/function/KeyPackageOperator.cpp b/src/core/function/KeyPackageOperator.cpp index 5b591ff3..929bfda1 100644 --- a/src/core/function/KeyPackageOperator.cpp +++ b/src/core/function/KeyPackageOperator.cpp @@ -30,8 +30,6 @@ #include <qt-aes/qaesencryption.h> -#include <boost/format.hpp> - #include "core/function/KeyPackageOperator.h" #include "core/function/PassphraseGenerator.h" #include "core/function/gpg/GpgKeyGetter.h" @@ -43,16 +41,16 @@ namespace GpgFrontend { auto KeyPackageOperator::GeneratePassphrase( - const std::filesystem::path& phrase_path, std::string& phrase) -> bool { + const std::filesystem::path& phrase_path, QString& phrase) -> bool { phrase = PassphraseGenerator::GetInstance().Generate(256); GF_CORE_LOG_DEBUG("generated passphrase: {} bytes", phrase.size()); - return WriteFileStd(phrase_path, phrase); + return WriteFile(phrase_path.c_str(), phrase.toUtf8()); } void KeyPackageOperator::GenerateKeyPackage( const std::filesystem::path& key_package_path, - const std::string& key_package_name, const KeyArgsList& keys, - std::string& phrase, bool secret, const OperationCallback& cb) { + const QString& key_package_name, const KeyArgsList& keys, QString& phrase, + bool secret, const OperationCallback& cb) { GF_CORE_LOG_DEBUG("generating key package: {}", key_package_name); GpgKeyImportExporter::GetInstance().ExportKeys( @@ -70,16 +68,16 @@ void KeyPackageOperator::GenerateKeyPackage( } auto gf_buffer = ExtractParams<GFBuffer>(data_obj, 0); - auto key = QByteArray::fromStdString(phrase); + auto data = gf_buffer.ConvertToQByteArray().toBase64(); - auto hash_key = - QCryptographicHash::hash(key, QCryptographicHash::Sha256); + auto hash_key = QCryptographicHash::hash(phrase.toUtf8(), + QCryptographicHash::Sha256); 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(WriteFileStd(key_package_path, encoded_data.toStdString()) ? 0 : -1, + cb(WriteFile(key_package_path.c_str(), encoded_data) ? 0 : -1, TransferParams()); return; }); @@ -91,26 +89,26 @@ auto KeyPackageOperator::ImportKeyPackage( -> std::tuple<bool, std::shared_ptr<GpgImportInformation>> { GF_CORE_LOG_DEBUG("importing key package: {}", key_package_path.u8string()); - std::string encrypted_data; - ReadFileStd(key_package_path, encrypted_data); + QByteArray encrypted_data; + ReadFile(key_package_path.c_str(), encrypted_data); - if (encrypted_data.empty()) { + if (encrypted_data.isEmpty()) { GF_CORE_LOG_ERROR("failed to read key package: {}", key_package_path.u8string()); return {false, nullptr}; }; - std::string passphrase; - ReadFileStd(phrase_path, passphrase); + QByteArray passphrase; + ReadFile(phrase_path.c_str(), passphrase); GF_CORE_LOG_DEBUG("passphrase: {} bytes", passphrase.size()); if (passphrase.size() != 256) { GF_CORE_LOG_ERROR("failed to read passphrase: {}", phrase_path.u8string()); return {false, nullptr}; } - auto hash_key = QCryptographicHash::hash( - QByteArray::fromStdString(passphrase), QCryptographicHash::Sha256); - auto encoded = QByteArray::fromStdString(encrypted_data); + auto hash_key = + QCryptographicHash::hash(passphrase, QCryptographicHash::Sha256); + auto encoded = encrypted_data; QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); @@ -130,22 +128,18 @@ auto KeyPackageOperator::ImportKeyPackage( return {true, import_info}; } -auto KeyPackageOperator::GenerateKeyPackageName() -> std::string { +auto KeyPackageOperator::GenerateKeyPackageName() -> QString { return generate_key_package_name(); } /** * @brief generate key package name * - * @return std::string key package name + * @return QString key package name */ -auto KeyPackageOperator::generate_key_package_name() -> std::string { - std::random_device rd_; ///< Random device - auto mt_ = std::mt19937(rd_()); ///< Mersenne twister - - std::uniform_int_distribution<int> dist(999, 99999); - auto file_string = boost::format("KeyPackage_%1%") % dist(mt_); - return file_string.str(); +auto KeyPackageOperator::generate_key_package_name() -> QString { + return QString("KeyPackage_%1%") + .arg(QRandomGenerator::global()->bounded(999, 99999)); } } // namespace GpgFrontend diff --git a/src/core/function/KeyPackageOperator.h b/src/core/function/KeyPackageOperator.h index 0bc51eff..abfb59b6 100644 --- a/src/core/function/KeyPackageOperator.h +++ b/src/core/function/KeyPackageOperator.h @@ -29,6 +29,7 @@ #pragma once #include "core/function/gpg/GpgKeyImportExporter.h" +#include "core/typedef/CoreTypedef.h" namespace GpgFrontend { @@ -47,14 +48,14 @@ class GPGFRONTEND_CORE_EXPORT KeyPackageOperator { * @return false if passphrase was not generated and saved */ static auto GeneratePassphrase(const std::filesystem::path &phrase_path, - std::string &phrase) -> bool; + QString &phrase) -> bool; /** * @brief generate the name of the key package * - * @return std::string name of the key package + * @return QString name of the key package */ - static auto GenerateKeyPackageName() -> std::string; + static auto GenerateKeyPackageName() -> QString; /** * @brief generate key package @@ -68,8 +69,8 @@ class GPGFRONTEND_CORE_EXPORT KeyPackageOperator { * @return false if key package was not generated */ static void GenerateKeyPackage(const std::filesystem::path &key_package_path, - const std::string &key_package_name, - const KeyArgsList &keys, std::string &phrase, + const QString &key_package_name, + const KeyArgsList &keys, QString &phrase, bool secret, const OperationCallback &cb); /** @@ -89,8 +90,8 @@ class GPGFRONTEND_CORE_EXPORT KeyPackageOperator { /** * @brief generate key package name * - * @return std::string key package name + * @return QString key package name */ - static auto generate_key_package_name() -> std::string; + static auto generate_key_package_name() -> QString; }; } // namespace GpgFrontend diff --git a/src/core/function/LoggerManager.cpp b/src/core/function/LoggerManager.cpp index cac373ed..c800224a 100644 --- a/src/core/function/LoggerManager.cpp +++ b/src/core/function/LoggerManager.cpp @@ -58,18 +58,19 @@ LoggerManager::~LoggerManager() { if (default_logger) default_logger = nullptr; } -auto LoggerManager::GetLogger(const std::string& id) +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 std::string& id, +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); + auto log_file_path = + (GlobalSettingStation::GetInstance().GetLogDir() / id.toStdString()); log_file_path.replace_extension(".log"); // sinks @@ -82,7 +83,7 @@ auto LoggerManager::RegisterAsyncLogger(const std::string& id, // logger auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::async_logger>( - id, begin(sinks), end(sinks), spdlog::thread_pool()); + id.toStdString(), begin(sinks), end(sinks), spdlog::thread_pool()); logger->set_pattern( "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); @@ -100,11 +101,12 @@ auto LoggerManager::RegisterAsyncLogger(const std::string& id, return logger; } -auto LoggerManager::RegisterSyncLogger(const std::string& id, +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); + auto log_file_path = + (GlobalSettingStation::GetInstance().GetLogDir() / id.toStdString()); log_file_path.replace_extension(".log"); // sinks @@ -117,7 +119,7 @@ auto LoggerManager::RegisterSyncLogger(const std::string& id, // logger auto logger = GpgFrontend::SecureCreateSharedObject<spdlog::logger>( - id, begin(sinks), end(sinks)); + id.toStdString(), begin(sinks), end(sinks)); logger->set_pattern( "[%H:%M:%S.%e] [T:%t] [%=6n] %^[%=8l]%$ [%s:%#] [%!] -> %v (+%ius)"); diff --git a/src/core/function/LoggerManager.h b/src/core/function/LoggerManager.h index 531e6efe..78fecc3c 100644 --- a/src/core/function/LoggerManager.h +++ b/src/core/function/LoggerManager.h @@ -43,13 +43,13 @@ class GPGFRONTEND_CORE_EXPORT LoggerManager ~LoggerManager() override; - auto RegisterAsyncLogger(const std::string& id, spdlog::level::level_enum) + auto RegisterAsyncLogger(const QString& id, spdlog::level::level_enum) -> std::shared_ptr<spdlog::logger>; - auto RegisterSyncLogger(const std::string& id, spdlog::level::level_enum) + auto RegisterSyncLogger(const QString& id, spdlog::level::level_enum) -> std::shared_ptr<spdlog::logger>; - auto GetLogger(const std::string& id) -> std::shared_ptr<spdlog::logger>; + auto GetLogger(const QString& id) -> std::shared_ptr<spdlog::logger>; static auto GetDefaultLogger() -> std::shared_ptr<spdlog::logger>; @@ -59,7 +59,7 @@ class GPGFRONTEND_CORE_EXPORT LoggerManager static spdlog::level::level_enum default_log_level; static std::shared_ptr<spdlog::logger> default_logger; - std::map<std::string, std::shared_ptr<spdlog::logger>> logger_map_; + std::map<QString, std::shared_ptr<spdlog::logger>> logger_map_; }; } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/PassphraseGenerator.cpp b/src/core/function/PassphraseGenerator.cpp index 6d0db65d..b7f1e877 100644 --- a/src/core/function/PassphraseGenerator.cpp +++ b/src/core/function/PassphraseGenerator.cpp @@ -28,23 +28,21 @@ #include "PassphraseGenerator.h" -#include <boost/format.hpp> - namespace GpgFrontend { -auto PassphraseGenerator::Generate(int len) -> std::string { - std::uniform_int_distribution<int> dist(999, 99999); - - auto file_string = boost::format("KeyPackage_%1%") % dist(mt_); +auto PassphraseGenerator::Generate(int len) -> QString { + auto file_string = QString("KeyPackage_%1") + .arg(QRandomGenerator::global()->bounded(999, 99999)); static const char kAlphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; - std::string tmp_str; + QString tmp_str; tmp_str.reserve(len); for (int i = 0; i < len; ++i) { - tmp_str += kAlphanum[dist(mt_) % (sizeof(kAlphanum) - 1)]; + tmp_str += kAlphanum[QRandomGenerator::global()->bounded( + static_cast<quint32>(sizeof(kAlphanum)))]; } return tmp_str; } diff --git a/src/core/function/PassphraseGenerator.h b/src/core/function/PassphraseGenerator.h index 19ecbb08..2e5925b6 100644 --- a/src/core/function/PassphraseGenerator.h +++ b/src/core/function/PassphraseGenerator.h @@ -53,9 +53,9 @@ class GPGFRONTEND_CORE_EXPORT PassphraseGenerator * @brief generate passphrase * * @param len length of the passphrase - * @return std::string passphrase + * @return QString passphrase */ - auto Generate(int len) -> std::string; + auto Generate(int len) -> QString; private: std::random_device rd_; ///< Random device diff --git a/src/core/function/basic/ChannelObject.cpp b/src/core/function/basic/ChannelObject.cpp index ddbfa603..18449ddb 100644 --- a/src/core/function/basic/ChannelObject.cpp +++ b/src/core/function/basic/ChannelObject.cpp @@ -34,14 +34,15 @@ namespace GpgFrontend { ChannelObject::ChannelObject() noexcept = default; -ChannelObject::ChannelObject(int channel, std::string type) +ChannelObject::ChannelObject(int channel, QString type) : channel_(channel), type_(std::move(type)) {} #ifdef DEBUG ChannelObject::~ChannelObject() noexcept { // using iostream instead of spdlog bacause at this time spdlog may have // already been destroyed. - std::cout << "releasing channel object: " << this->type_ << std::endl; + QTextStream(stdout) << "releasing channel object: " << this->type_ + << Qt::endl; } #else ChannelObject::~ChannelObject() noexcept = default; diff --git a/src/core/function/basic/ChannelObject.h b/src/core/function/basic/ChannelObject.h index 18317ee2..27be55c4 100644 --- a/src/core/function/basic/ChannelObject.h +++ b/src/core/function/basic/ChannelObject.h @@ -55,7 +55,7 @@ class GPGFRONTEND_CORE_EXPORT ChannelObject { * * @param channel */ - explicit ChannelObject(int channel, std::string type); + explicit ChannelObject(int channel, QString type); /** * @brief Get the Default Channel object @@ -80,7 +80,7 @@ class GPGFRONTEND_CORE_EXPORT ChannelObject { private: int channel_ = kGpgFrontendDefaultChannel; ///< The channel id - std::string type_; + QString type_; }; template <typename Derived> diff --git a/src/core/function/gpg/GpgAdvancedOperator.cpp b/src/core/function/gpg/GpgAdvancedOperator.cpp index 9195c55e..ce08e03a 100644 --- a/src/core/function/gpg/GpgAdvancedOperator.cpp +++ b/src/core/function/gpg/GpgAdvancedOperator.cpp @@ -39,10 +39,10 @@ auto GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() -> bool { bool success = false; const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gpgconf_path", std::string{}); + "core", "gpgme.ctx.gpgconf_path", QString{}); GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); - if (gpgconf_path.empty()) { + if (gpgconf_path.isEmpty()) { GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return false; } @@ -50,8 +50,8 @@ auto GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() -> bool { GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, {"--reload", "gpg-agent"}, - [&](int exit_code, const std::string & /*p_out*/, - const std::string & /*p_err*/) { + [&](int exit_code, const QString & /*p_out*/, + const QString & /*p_err*/) { if (exit_code == 0) { GF_CORE_LOG_DEBUG("gpgconf reload exit code: {}", exit_code); success = true; @@ -64,10 +64,10 @@ auto GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() -> bool { bool success = false; const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gpgconf_path", std::string{}); + "core", "gpgme.ctx.gpgconf_path", QString{}); GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); - if (gpgconf_path.empty()) { + if (gpgconf_path.isEmpty()) { GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return false; } @@ -75,7 +75,7 @@ auto GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() -> bool { GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, {"--reload"}, - [&](int exit_code, const std::string &p_out, const std::string &p_err) { + [&](int exit_code, const QString &p_out, const QString &p_err) { if (exit_code == 0) { success = true; } else { @@ -90,10 +90,10 @@ auto GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() -> bool { void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() { const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gpgconf_path", std::string{}); + "core", "gpgme.ctx.gpgconf_path", QString{}); GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); - if (gpgconf_path.empty()) { + if (gpgconf_path.isEmpty()) { GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return; } @@ -101,7 +101,7 @@ void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() { GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, {"--verbose", "--kill", "all"}, - [&](int exit_code, const std::string &p_out, const std::string &p_err) { + [&](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; @@ -152,10 +152,10 @@ auto GpgFrontend::GpgAdvancedOperator::ResetConfigures() -> bool { bool success = false; const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gpgconf_path", std::string{}); + "core", "gpgme.ctx.gpgconf_path", QString{}); GF_CORE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); - if (gpgconf_path.empty()) { + if (gpgconf_path.isEmpty()) { GF_CORE_LOG_ERROR("cannot get valid gpgconf path from rt, abort."); return false; } @@ -163,7 +163,7 @@ auto GpgFrontend::GpgAdvancedOperator::ResetConfigures() -> bool { GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpgconf_path, {"--apply-defaults"}, - [&](int exit_code, const std::string &p_out, const std::string &p_err) { + [&](int exit_code, const QString &p_out, const QString &p_err) { if (exit_code == 0) { success = true; } else { @@ -182,15 +182,15 @@ auto GpgFrontend::GpgAdvancedOperator::StartGpgAgent() -> bool { const auto gpg_agent_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - "gnupg.gpg_agent_path", std::string{}); + "gnupg.gpg_agent_path", QString{}); GF_CORE_LOG_DEBUG("got gnupg agent path from rt: {}", gpg_agent_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - "gnupg.home_path", std::string{}); + "gnupg.home_path", QString{}); GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); - if (gpg_agent_path.empty()) { + if (gpg_agent_path.isEmpty()) { GF_CORE_LOG_ERROR("cannot get valid gpg agent path from rt, abort."); return false; } @@ -198,7 +198,7 @@ auto GpgFrontend::GpgAdvancedOperator::StartGpgAgent() -> bool { GpgFrontend::GpgCommandExecutor::ExecuteSync( {gpg_agent_path, {"--homedir", home_path, "--daemon"}, - [&](int exit_code, const std::string &p_out, const std::string &p_err) { + [&](int exit_code, const QString &p_out, const QString &p_err) { if (exit_code == 0) { success = true; GF_CORE_LOG_INFO("start gpg-agent successfully"); @@ -225,15 +225,15 @@ auto GpgFrontend::GpgAdvancedOperator::StartDirmngr() -> bool { const auto dirmngr_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - "gnupg.dirmngr_path", std::string{}); + "gnupg.dirmngr_path", QString{}); GF_CORE_LOG_DEBUG("got gnupg dirmngr path from rt: {}", dirmngr_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - "gnupg.home_path", std::string{}); + "gnupg.home_path", QString{}); GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); - if (dirmngr_path.empty()) { + if (dirmngr_path.isEmpty()) { GF_CORE_LOG_ERROR("cannot get valid dirmngr path from rt, abort."); return false; } @@ -241,7 +241,7 @@ auto GpgFrontend::GpgAdvancedOperator::StartDirmngr() -> bool { GpgFrontend::GpgCommandExecutor::ExecuteSync( {dirmngr_path, {"--homedir", home_path, "--daemon"}, - [&](int exit_code, const std::string &p_out, const std::string &p_err) { + [&](int exit_code, const QString &p_out, const QString &p_err) { if (exit_code == 0) { success = true; GF_CORE_LOG_INFO("start dirmngr successfully"); @@ -267,15 +267,15 @@ auto GpgFrontend::GpgAdvancedOperator::StartKeyBoxd() -> bool { const auto keyboxd_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - "gnupg.keyboxd_path", std::string{}); + "gnupg.keyboxd_path", QString{}); GF_CORE_LOG_DEBUG("got gnupg keyboxd path from rt: {}", keyboxd_path); const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - "gnupg.home_path", std::string{}); + "gnupg.home_path", QString{}); GF_CORE_LOG_DEBUG("got gnupg home path from rt: {}", home_path); - if (keyboxd_path.empty()) { + if (keyboxd_path.isEmpty()) { GF_CORE_LOG_ERROR("cannot get valid keyboxd path from rt, abort."); return false; } @@ -283,7 +283,7 @@ auto GpgFrontend::GpgAdvancedOperator::StartKeyBoxd() -> bool { GpgFrontend::GpgCommandExecutor::ExecuteSync( {keyboxd_path, {"--homedir", home_path, "--daemon"}, - [&](int exit_code, const std::string &p_out, const std::string &p_err) { + [&](int exit_code, const QString &p_out, const QString &p_err) { if (exit_code == 0) { success = true; GF_CORE_LOG_INFO("start keyboxd successfully"); diff --git a/src/core/function/gpg/GpgBasicOperator.cpp b/src/core/function/gpg/GpgBasicOperator.cpp index fd81c093..f7a4df58 100644 --- a/src/core/function/gpg/GpgBasicOperator.cpp +++ b/src/core/function/gpg/GpgBasicOperator.cpp @@ -47,6 +47,8 @@ void GpgBasicOperator::Encrypt(KeyArgsList keys, GFBuffer in_buffer, bool ascii, const GpgOperationCallback& cb) { RunGpgOperaAsync( [=](const DataObjectPtr& data_object) -> GpgError { + if (keys.empty()) return GPG_ERR_CANCELED; + std::vector<gpgme_key_t> recipients(keys.begin(), keys.end()); // Last entry data_in array has to be nullptr @@ -117,6 +119,8 @@ void GpgBasicOperator::Sign(KeyArgsList signers, GFBuffer in_buffer, const GpgOperationCallback& cb) { RunGpgOperaAsync( [=](const DataObjectPtr& data_object) -> GpgError { + if (signers.empty()) return GPG_ERR_CANCELED; + GpgError err; // Set Singers of this opera @@ -162,6 +166,8 @@ void GpgBasicOperator::EncryptSign(KeyArgsList keys, KeyArgsList signers, const GpgOperationCallback& cb) { RunGpgOperaAsync( [=](const DataObjectPtr& data_object) -> GpgError { + if (keys.empty() || signers.empty()) return GPG_ERR_CANCELED; + GpgError err; std::vector<gpgme_key_t> recipients(keys.begin(), keys.end()); diff --git a/src/core/function/gpg/GpgCommandExecutor.cpp b/src/core/function/gpg/GpgCommandExecutor.cpp index fd6d6099..713d9aba 100644 --- a/src/core/function/gpg/GpgCommandExecutor.cpp +++ b/src/core/function/gpg/GpgCommandExecutor.cpp @@ -27,7 +27,6 @@ */ #include "GpgCommandExecutor.h" -#include <boost/format.hpp> #include <utility> #include "core/function/basic/GpgFunctionObject.h" @@ -45,11 +44,7 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) const auto &interact_function = context.int_func; const auto &cmd_executor_callback = context.cb_func; - const std::string joined_argument = std::accumulate( - std::begin(arguments), std::end(arguments), std::string(), - [](const std::string &a, const std::string &b) -> std::string { - return a + (a.length() > 0 ? " " : "") + b; - }); + const QString joined_argument = QStringList::fromVector(arguments).join(" "); GF_CORE_LOG_DEBUG("building task: called cmd {} arguments size: {}", cmd, arguments.size()); @@ -59,13 +54,12 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) GF_CORE_LOG_DEBUG( "data object args count of cmd executor result callback: {}", data_object->GetObjectSize()); - if (!data_object - ->Check<int, std::string, GpgCommandExecutorCallback>()) { + if (!data_object->Check<int, QString, GpgCommandExecutorCallback>()) { throw std::runtime_error("invalid data object size"); } auto exit_code = ExtractParams<int>(data_object, 0); - auto process_stdout = ExtractParams<std::string>(data_object, 1); + auto process_stdout = ExtractParams<QString>(data_object, 1); auto callback = ExtractParams<GpgCommandExecutorCallback>(data_object, 2); @@ -82,15 +76,15 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) GF_CORE_LOG_DEBUG("process runner called, data object size: {}", data_object->GetObjectSize()); - if (!data_object->Check<std::string, std::vector<std::string>, + if (!data_object->Check<QString, std::vector<QString>, GpgCommandExecutorInteractor, GpgCommandExecutorCallback>()) { throw std::runtime_error("invalid data object size"); } // get arguments - auto cmd = ExtractParams<std::string>(data_object, 0); - auto arguments = ExtractParams<std::vector<std::string>>(data_object, 1); + auto cmd = ExtractParams<QString>(data_object, 0); + auto arguments = ExtractParams<std::vector<QString>>(data_object, 1); auto interact_func = ExtractParams<GpgCommandExecutorInteractor>(data_object, 2); auto callback = ExtractParams<GpgCommandExecutorCallback>(data_object, 3); @@ -103,12 +97,12 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) // set process channel mode // this is to make sure we can get all output from stdout and stderr cmd_process->setProcessChannelMode(QProcess::MergedChannels); - cmd_process->setProgram(QString::fromStdString(cmd)); + cmd_process->setProgram(cmd); // set arguments QStringList q_arguments; for (const auto &argument : arguments) { - q_arguments.append(QString::fromStdString(argument)); + q_arguments.append(argument); } cmd_process->setArguments(q_arguments); @@ -138,8 +132,7 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) cmd_process->start(); cmd_process->waitForFinished(); - std::string process_stdout = - cmd_process->readAllStandardOutput().toStdString(); + QString process_stdout = cmd_process->readAllStandardOutput(); int exit_code = cmd_process->exitCode(); GF_CORE_LOG_DEBUG( @@ -160,17 +153,14 @@ auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context) }; return new Thread::Task( - std::move(runner), - (boost::format("GpgCommamdExecutor(%1%){%2%}") % cmd % joined_argument) - .str(), + std::move(runner), QString("GpgCommamdExecutor(%1){%2}").arg(cmd), TransferParams(cmd, arguments, interact_function, cmd_executor_callback), std::move(result_callback)); } GpgCommandExecutor::ExecuteContext::ExecuteContext( - std::string cmd, std::vector<std::string> arguments, - GpgCommandExecutorCallback callback, Module::TaskRunnerPtr task_runner, - GpgCommandExecutorInteractor int_func) + QString cmd, QList<QString> arguments, GpgCommandExecutorCallback callback, + Module::TaskRunnerPtr task_runner, GpgCommandExecutorInteractor int_func) : cmd(std::move(cmd)), arguments(std::move(arguments)), cb_func(std::move(callback)), diff --git a/src/core/function/gpg/GpgCommandExecutor.h b/src/core/function/gpg/GpgCommandExecutor.h index f017fdfb..995fb603 100644 --- a/src/core/function/gpg/GpgCommandExecutor.h +++ b/src/core/function/gpg/GpgCommandExecutor.h @@ -32,8 +32,7 @@ namespace GpgFrontend { -using GpgCommandExecutorCallback = - std::function<void(int, std::string, std::string)>; +using GpgCommandExecutorCallback = std::function<void(int, QString, QString)>; using GpgCommandExecutorInteractor = std::function<void(QProcess *)>; /** @@ -43,21 +42,21 @@ using GpgCommandExecutorInteractor = std::function<void(QProcess *)>; class GPGFRONTEND_CORE_EXPORT GpgCommandExecutor { public: struct ExecuteContext { - const std::string cmd; - const std::vector<std::string> arguments; - const GpgCommandExecutorCallback cb_func; - const GpgCommandExecutorInteractor int_func; + QString cmd; + QList<QString> arguments; + GpgCommandExecutorCallback cb_func; + GpgCommandExecutorInteractor int_func; Module::TaskRunnerPtr task_runner = nullptr; ExecuteContext( - std::string cmd, std::vector<std::string> arguments, - GpgCommandExecutorCallback callback = [](int, std::string, - std::string) {}, + QString cmd, QList<QString> arguments, + GpgCommandExecutorCallback callback = [](int, const QString &, + const QString &) {}, Module::TaskRunnerPtr task_runner = nullptr, GpgCommandExecutorInteractor int_func = [](QProcess *) {}); }; - using ExecuteContexts = std::vector<ExecuteContext>; + using ExecuteContexts = QList<ExecuteContext>; /** * @brief Excuting a command diff --git a/src/core/function/gpg/GpgContext.cpp b/src/core/function/gpg/GpgContext.cpp index 30134191..df525534 100644 --- a/src/core/function/gpg/GpgContext.cpp +++ b/src/core/function/gpg/GpgContext.cpp @@ -36,6 +36,7 @@ #include "core/function/CoreSignalStation.h" #include "core/function/basic/GpgFunctionObject.h" +#include "core/model/GpgPassphraseContext.h" #include "core/module/ModuleManager.h" #include "core/utils/GpgUtils.h" #include "utils/MemoryUtils.h" @@ -91,7 +92,7 @@ class GpgContext::Impl { const char *passphrase_info, int last_was_bad, int fd) -> gpgme_error_t { size_t res; - std::string pass = "abcdefg\n"; + QString pass = "abcdefg\n"; auto pass_len = pass.size(); size_t off = 0; @@ -105,38 +106,42 @@ class GpgContext::Impl { } static auto CustomPassphraseCb(void *hook, const char *uid_hint, - const char *passphrase_info, int last_was_bad, + const char *passphrase_info, int prev_was_bad, int fd) -> gpgme_error_t { - std::string passphrase; + auto context = + QSharedPointer<GpgPassphraseContext>(new GpgPassphraseContext( + uid_hint != nullptr ? uid_hint : "", + passphrase_info != nullptr ? passphrase_info : "", + prev_was_bad != 0)); GF_CORE_LOG_DEBUG( "custom passphrase cb called, uid: {}, info: {}, last_was_bad: {}", - uid_hint == nullptr ? "<empty>" : std::string{uid_hint}, - passphrase_info == nullptr ? "<empty>" : std::string{passphrase_info}, - last_was_bad); - - emit CoreSignalStation::GetInstance()->SignalNeedUserInputPassphrase(); + uid_hint == nullptr ? "<empty>" : QString{uid_hint}, + passphrase_info == nullptr ? "<empty>" : QString{passphrase_info}, + prev_was_bad); QEventLoop looper; - QObject::connect( - CoreSignalStation::GetInstance(), - &CoreSignalStation::SignalUserInputPassphraseCallback, &looper, - [&](const QByteArray &buffer) { passphrase = buffer.toStdString(); }); QObject::connect(CoreSignalStation::GetInstance(), &CoreSignalStation::SignalUserInputPassphraseCallback, &looper, &QEventLoop::quit); + + emit CoreSignalStation::GetInstance()->SignalNeedUserInputPassphrase( + context); looper.exec(); + auto passphrase = context->GetPassphrase().toStdString(); auto passpahrase_size = passphrase.size(); GF_CORE_LOG_DEBUG("get passphrase from pinentry size: {}", passpahrase_size); - size_t off = 0; size_t res = 0; - do { - res = gpgme_io_write(fd, &passphrase[off], passpahrase_size - off); - if (res > 0) off += res; - } while (res > 0 && off != passpahrase_size); + if (passpahrase_size > 0) { + size_t off = 0; + do { + res = gpgme_io_write(fd, &passphrase[off], passpahrase_size - off); + if (res > 0) off += res; + } while (res > 0 && off != passpahrase_size); + } res += gpgme_io_write(fd, "\n", 1); @@ -165,7 +170,7 @@ class GpgContext::Impl { assert(ctx != nullptr); const auto gpgme_version = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.version", std::string{"0.0.0"}); + "core", "gpgme.version", QString{"0.0.0"}); GF_CORE_LOG_DEBUG("got gpgme version version from rt: {}", gpgme_version); if (gpgme_get_keylist_mode(ctx) == 0) { @@ -184,21 +189,21 @@ class GpgContext::Impl { static auto set_ctx_openpgp_engine_info(gpgme_ctx_t ctx) -> bool { const auto app_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.app_path", std::string{}); + "core", "gpgme.ctx.app_path", QString{}); const auto database_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.database_path", std::string{}); + "core", "gpgme.ctx.database_path", QString{}); GF_CORE_LOG_DEBUG("ctx set engine info, db path: {}, app path: {}", database_path, app_path); - const char *app_path_c_str = app_path.c_str(); - const char *db_path_c_str = database_path.c_str(); + const char *app_path_c_str = app_path.toUtf8(); + const char *db_path_c_str = database_path.toUtf8(); - if (app_path.empty()) { + if (app_path.isEmpty()) { app_path_c_str = nullptr; } - if (database_path.empty()) { + if (database_path.isEmpty()) { db_path_c_str = nullptr; } @@ -215,12 +220,12 @@ class GpgContext::Impl { const GpgContextInitArgs &args) -> bool { assert(ctx != nullptr); - if (args.custom_gpgconf && !args.custom_gpgconf_path.empty()) { + if (args.custom_gpgconf && !args.custom_gpgconf_path.isEmpty()) { GF_CORE_LOG_DEBUG("set custom gpgconf path: {}", args.custom_gpgconf_path); auto err = gpgme_ctx_set_engine_info(ctx, GPGME_PROTOCOL_GPGCONF, - args.custom_gpgconf_path.c_str(), nullptr); + args.custom_gpgconf_path.toUtf8(), nullptr); assert(CheckGpgError(err) == GPG_ERR_NO_ERROR); if (CheckGpgError(err) != GPG_ERR_NO_ERROR) { @@ -262,9 +267,8 @@ class GpgContext::Impl { } // set custom gpg key db path - if (!args_.db_path.empty()) { - Module::UpsertRTValue("core", "gpgme.ctx.database_path", - std::string(args_.db_path)); + if (!args_.db_path.isEmpty()) { + Module::UpsertRTValue("core", "gpgme.ctx.database_path", args_.db_path); } if (!set_ctx_openpgp_engine_info(ctx)) { diff --git a/src/core/function/gpg/GpgContext.h b/src/core/function/gpg/GpgContext.h index 16dd7c4a..d473a341 100644 --- a/src/core/function/gpg/GpgContext.h +++ b/src/core/function/gpg/GpgContext.h @@ -38,14 +38,14 @@ namespace GpgFrontend { * */ struct GpgContextInitArgs { - std::string db_path = {}; ///< + QString db_path = {}; ///< bool test_mode = false; ///< bool offline_mode = false; ///< bool auto_import_missing_key = false; ///< - bool custom_gpgconf = false; ///< - std::string custom_gpgconf_path; ///< + bool custom_gpgconf = false; ///< + QString custom_gpgconf_path; ///< bool use_pinentry = false; ///< }; diff --git a/src/core/function/gpg/GpgKeyGetter.cpp b/src/core/function/gpg/GpgKeyGetter.cpp index 5c5ed039..e22979d7 100644 --- a/src/core/function/gpg/GpgKeyGetter.cpp +++ b/src/core/function/gpg/GpgKeyGetter.cpp @@ -46,7 +46,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { GF_CORE_LOG_DEBUG("called channel: {}", channel); } - auto GetKey(const std::string& fpr, bool use_cache) -> GpgKey { + auto GetKey(const QString& fpr, bool use_cache) -> GpgKey { // find in cache first if (use_cache) { auto key = get_key_in_cache(fpr); @@ -54,7 +54,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { } gpgme_key_t p_key = nullptr; - gpgme_get_key(ctx_.DefaultContext(), fpr.c_str(), &p_key, 1); + 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); return GetPubkey(fpr, true); @@ -62,7 +62,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { return GpgKey(std::move(p_key)); } - auto GetPubkey(const std::string& fpr, bool use_cache) -> GpgKey { + auto GetPubkey(const QString& fpr, bool use_cache) -> GpgKey { // find in cache first if (use_cache) { auto key = get_key_in_cache(fpr); @@ -70,7 +70,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { } gpgme_key_t p_key = nullptr; - gpgme_get_key(ctx_.DefaultContext(), fpr.c_str(), &p_key, 0); + gpgme_get_key(ctx_.DefaultContext(), fpr.toUtf8(), &p_key, 0); if (p_key == nullptr) GF_CORE_LOG_WARN("GpgKeyGetter GetKey _p_key Null", fpr); return GpgKey(std::move(p_key)); @@ -181,7 +181,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { * @brief cache the keys with key id * */ - std::map<std::string, GpgKey> keys_cache_; + std::map<QString, GpgKey> keys_cache_; /** * @brief shared mutex for the keys cache @@ -195,7 +195,7 @@ class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> { * @param id * @return GpgKey */ - auto get_key_in_cache(const std::string& key_id) -> GpgKey { + auto get_key_in_cache(const QString& key_id) -> GpgKey { std::lock_guard<std::mutex> lock(keys_cache_mutex_); if (keys_cache_.find(key_id) != keys_cache_.end()) { std::lock_guard<std::mutex> lock(ctx_mutex_); @@ -216,12 +216,11 @@ GpgKeyGetter::GpgKeyGetter(int channel) GpgKeyGetter::~GpgKeyGetter() = default; -auto GpgKeyGetter::GetKey(const std::string& key_id, bool use_cache) -> GpgKey { +auto GpgKeyGetter::GetKey(const QString& key_id, bool use_cache) -> GpgKey { return p_->GetKey(key_id, use_cache); } -auto GpgKeyGetter::GetPubkey(const std::string& key_id, bool use_cache) - -> GpgKey { +auto GpgKeyGetter::GetPubkey(const QString& key_id, bool use_cache) -> GpgKey { return p_->GetPubkey(key_id, use_cache); } diff --git a/src/core/function/gpg/GpgKeyGetter.h b/src/core/function/gpg/GpgKeyGetter.h index 275de8df..91138623 100644 --- a/src/core/function/gpg/GpgKeyGetter.h +++ b/src/core/function/gpg/GpgKeyGetter.h @@ -59,7 +59,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter * @param fpr * @return GpgKey */ - auto GetKey(const std::string& key_id, bool use_cache = true) -> GpgKey; + auto GetKey(const QString& key_id, bool use_cache = true) -> GpgKey; /** * @brief Get the Keys object @@ -75,7 +75,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter * @param fpr * @return GpgKey */ - auto GetPubkey(const std::string& key_id, bool use_cache = true) -> GpgKey; + auto GetPubkey(const QString& key_id, bool use_cache = true) -> GpgKey; /** * @brief Get all the keys by receiving a linked list diff --git a/src/core/function/gpg/GpgKeyImportExporter.h b/src/core/function/gpg/GpgKeyImportExporter.h index 80764df8..14b2b2bf 100644 --- a/src/core/function/gpg/GpgKeyImportExporter.h +++ b/src/core/function/gpg/GpgKeyImportExporter.h @@ -31,7 +31,6 @@ #include "core/function/basic/GpgFunctionObject.h" #include "core/function/gpg/GpgContext.h" #include "core/model/GFBuffer.h" -#include "core/typedef/CoreTypedef.h" #include "core/typedef/GpgTypedef.h" namespace GpgFrontend { diff --git a/src/core/function/gpg/GpgKeyManager.cpp b/src/core/function/gpg/GpgKeyManager.cpp index 38ebd040..e6ff7214 100644 --- a/src/core/function/gpg/GpgKeyManager.cpp +++ b/src/core/function/gpg/GpgKeyManager.cpp @@ -41,7 +41,7 @@ GpgFrontend::GpgKeyManager::GpgKeyManager(int channel) auto GpgFrontend::GpgKeyManager::SignKey( const GpgFrontend::GpgKey& target, GpgFrontend::KeyArgsList& keys, - const std::string& uid, + const QString& uid, const std::unique_ptr<boost::posix_time::ptime>& expires) -> bool { GpgBasicOperator::GetInstance().SetSigners(keys, true); @@ -56,7 +56,7 @@ auto GpgFrontend::GpgKeyManager::SignKey( auto err = CheckGpgError( gpgme_op_keysign(ctx_.DefaultContext(), static_cast<gpgme_key_t>(target), - uid.c_str(), expires_time_t, flags)); + uid.toUtf8(), expires_time_t, flags)); return CheckGpgError(err) == GPG_ERR_NO_ERROR; } @@ -71,7 +71,7 @@ auto GpgFrontend::GpgKeyManager::RevSign( assert(signing_key.IsGood()); auto err = CheckGpgError( gpgme_op_revsig(ctx_.DefaultContext(), gpgme_key_t(key), - gpgme_key_t(signing_key), sign_id.second.c_str(), 0)); + gpgme_key_t(signing_key), sign_id.second.toUtf8(), 0)); if (CheckGpgError(err) != GPG_ERR_NO_ERROR) return false; } return true; @@ -88,7 +88,7 @@ auto GpgFrontend::GpgKeyManager::SetExpire( const char* sub_fprs = nullptr; - if (subkey != nullptr) sub_fprs = subkey->GetFingerprint().c_str(); + if (subkey != nullptr) sub_fprs = subkey->GetFingerprint().toUtf8(); auto err = CheckGpgError(gpgme_op_setexpire(ctx_.DefaultContext(), static_cast<gpgme_key_t>(key), @@ -104,12 +104,11 @@ auto GpgFrontend::GpgKeyManager::SetOwnerTrustLevel(const GpgKey& key, } AutomatonNextStateHandler next_state_handler = [](AutomatonState state, - std::string status, - std::string args) { + QString status, + QString args) { GF_CORE_LOG_DEBUG("next_state_handler state: {}, gpg_status: {}, args: {}", state, status, args); - std::vector<std::string> tokens; - boost::split(tokens, args, boost::is_any_of(" ")); + auto tokens = args.split(' '); switch (state) { case AS_START: @@ -155,25 +154,25 @@ auto GpgFrontend::GpgKeyManager::SetOwnerTrustLevel(const GpgKey& key, GF_CORE_LOG_DEBUG("action_handler state: {}", state); switch (state) { case AS_COMMAND: - return std::string("trust"); + return QString("trust"); case AS_VALUE: handler.SetSuccess(true); - return std::to_string(trust_level); + return QString::number(trust_level); case AS_REALLY_ULTIMATE: handler.SetSuccess(true); - return std::string("Y"); + return QString("Y"); case AS_QUIT: - return std::string("quit"); + return QString("quit"); case AS_SAVE: handler.SetSuccess(true); - return std::string("Y"); + return QString("Y"); case AS_START: case AS_ERROR: - return std::string(""); + return QString(""); default: - return std::string(""); + return QString(""); } - return std::string(""); + return QString(""); }; auto key_fpr = key.GetFingerprint(); @@ -193,15 +192,14 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, const char* args, int fd) -> gpgme_error_t { auto handle_struct = static_cast<AutomatonHandelStruct*>(handle); - std::string status_s = status; - std::string args_s = args; + 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") { - std::vector<std::string> tokens; - boost::split(tokens, args, boost::is_any_of(" ")); + auto tokens = QString(args).split(' '); if (tokens.empty() || tokens[0] != handle_struct->KeyFpr()) { GF_CORE_LOG_ERROR("handle struct key fpr {} mismatch token: {}, exit...", @@ -212,7 +210,7 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, return 0; } - if (status_s == "GOT_IT" || status_s.empty()) { + if (status_s == "GOT_IT" || status_s.isEmpty()) { GF_CORE_LOG_DEBUG("status GOT_IT, continue..."); return 0; } @@ -232,8 +230,9 @@ auto GpgFrontend::GpgKeyManager::interactor_cb_fnc(void* handle, Command cmd = handle_struct->Action(); GF_CORE_LOG_DEBUG("handle struct action done, next state: {}, action cmd: {}", next_state, cmd); - if (!cmd.empty()) { - gpgme_io_write(fd, cmd.c_str(), cmd.size()); + if (!cmd.isEmpty()) { + auto btye_array = cmd.toUtf8(); + gpgme_io_write(fd, btye_array, btye_array.size()); gpgme_io_write(fd, "\n", 1); } else if (status_s == "GET_LINE") { // avoid trapping in this state diff --git a/src/core/function/gpg/GpgKeyManager.h b/src/core/function/gpg/GpgKeyManager.h index bf0f5c02..39570d96 100644 --- a/src/core/function/gpg/GpgKeyManager.h +++ b/src/core/function/gpg/GpgKeyManager.h @@ -63,7 +63,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyManager * @param expires expire date and time of the signature * @return if successful */ - auto SignKey(const GpgKey& target, KeyArgsList& keys, const std::string& uid, + auto SignKey(const GpgKey& target, KeyArgsList& keys, const QString& uid, const std::unique_ptr<boost::posix_time::ptime>& expires) -> bool; @@ -101,7 +101,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyManager static auto interactor_cb_fnc(void* handle, const char* status, const char* args, int fd) -> gpgme_error_t; - using Command = std::string; + using Command = QString; using AutomatonState = enum { AS_START, AS_COMMAND, @@ -117,7 +117,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyManager using AutomatonActionHandler = std::function<Command(AutomatonHandelStruct&, AutomatonState)>; using AutomatonNextStateHandler = - std::function<AutomatonState(AutomatonState, std::string, std::string)>; + std::function<AutomatonState(AutomatonState, QString, QString)>; struct AutomatonHandelStruct { void SetStatus(AutomatonState next_state) { current_state_ = next_state; } @@ -127,7 +127,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyManager next_state_handler_ = std::move(next_state_handler); action_handler_ = std::move(action_handler); } - auto NextState(std::string gpg_status, std::string args) -> AutomatonState { + auto NextState(QString gpg_status, QString args) -> AutomatonState { return next_state_handler_(current_state_, std::move(gpg_status), std::move(args)); } @@ -137,9 +137,9 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyManager [[nodiscard]] auto Success() const -> bool { return success_; } - auto KeyFpr() -> std::string { return key_fpr_; } + auto KeyFpr() -> QString { return key_fpr_; } - explicit AutomatonHandelStruct(std::string key_fpr) + explicit AutomatonHandelStruct(QString key_fpr) : key_fpr_(std::move(key_fpr)) {} private: @@ -147,7 +147,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyManager AutomatonNextStateHandler next_state_handler_; AutomatonActionHandler action_handler_; bool success_ = false; - std::string key_fpr_; + QString key_fpr_; }; GpgContext& ctx_ = diff --git a/src/core/function/gpg/GpgKeyOpera.cpp b/src/core/function/gpg/GpgKeyOpera.cpp index 90852b42..88419237 100644 --- a/src/core/function/gpg/GpgKeyOpera.cpp +++ b/src/core/function/gpg/GpgKeyOpera.cpp @@ -33,7 +33,6 @@ #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/date_time/posix_time/conversion.hpp> -#include <boost/format.hpp> #include <boost/process/async_pipe.hpp> #include <memory> @@ -91,17 +90,15 @@ auto GpgKeyOpera::SetExpire(const GpgKey& key, const SubkeyId& subkey_fpr, std::chrono::system_clock::now()); } - GF_CORE_LOG_DEBUG(key.GetId(), subkey_fpr, expires_time); - GpgError err; - if (key.GetFingerprint() == subkey_fpr || subkey_fpr.empty()) { + if (key.GetFingerprint() == subkey_fpr || subkey_fpr.isEmpty()) { err = gpgme_op_setexpire(ctx_.DefaultContext(), static_cast<gpgme_key_t>(key), expires_time, nullptr, 0); } else { err = gpgme_op_setexpire(ctx_.DefaultContext(), static_cast<gpgme_key_t>(key), - expires_time, subkey_fpr.c_str(), 0); + expires_time, subkey_fpr.toUtf8(), 0); } return err; @@ -114,15 +111,15 @@ auto GpgKeyOpera::SetExpire(const GpgKey& key, const SubkeyId& subkey_fpr, * @return the process doing this job */ void GpgKeyOpera::GenerateRevokeCert(const GpgKey& key, - const std::string& output_path) { + const QString& output_path) { const auto app_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.app_path", std::string{}); + "core", "gpgme.ctx.app_path", QString{}); // get all components GpgCommandExecutor::ExecuteSync( {app_path, {"--command-fd", "0", "--status-fd", "1", "--no-tty", "-o", output_path, "--gen-revoke", key.GetFingerprint()}, - [=](int exit_code, const std::string& p_out, const std::string& p_err) { + [=](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 " @@ -171,13 +168,13 @@ void GpgKeyOpera::GenerateKey(const std::shared_ptr<GenKeyInfo>& params, RunGpgOperaAsync( [&ctx = ctx_, params](const DataObjectPtr& data_object) -> GpgError { auto userid_utf8 = params->GetUserid(); - const char* userid = userid_utf8.c_str(); + const char* userid = userid_utf8.toUtf8(); auto algo_utf8 = params->GetAlgo() + params->GetKeySizeStr(); GF_CORE_LOG_DEBUG("params: {} {}", params->GetAlgo(), params->GetKeySizeStr()); - const char* algo = algo_utf8.c_str(); + const char* algo = algo_utf8.toUtf8(); unsigned long expires = 0; expires = to_time_t(boost::posix_time::ptime(params->GetExpireTime())) - std::chrono::system_clock::to_time_t( @@ -227,7 +224,7 @@ void GpgKeyOpera::GenerateSubkey(const GpgKey& key, params->GetAlgo(), params->GetKeySizeStr()); auto algo_utf8 = (params->GetAlgo() + params->GetKeySizeStr()); - const char* algo = algo_utf8.c_str(); + const char* algo = algo_utf8.toUtf8(); unsigned long expires = 0; expires = to_time_t(boost::posix_time::ptime(params->GetExpireTime())) - @@ -262,10 +259,10 @@ void GpgKeyOpera::GenerateKeyWithSubkey( [&ctx = ctx_, params, subkey_params](const DataObjectPtr& data_object) -> GpgError { auto userid_utf8 = params->GetUserid(); - const char* userid = userid_utf8.c_str(); + const char* userid = userid_utf8.toUtf8(); auto algo_utf8 = params->GetAlgo() + params->GetKeySizeStr(); - const char* algo = algo_utf8.c_str(); + const char* algo = algo_utf8.toUtf8(); unsigned long expires = 0; expires = to_time_t(boost::posix_time::ptime(params->GetExpireTime())) - std::chrono::system_clock::to_time_t( @@ -310,7 +307,7 @@ void GpgKeyOpera::GenerateKeyWithSubkey( subkey_params->GetKeySizeStr()); algo_utf8 = (subkey_params->GetAlgo() + subkey_params->GetKeySizeStr()); - algo = algo_utf8.c_str(); + algo = algo_utf8.toUtf8(); expires = 0; expires = to_time_t(boost::posix_time::ptime( @@ -359,7 +356,7 @@ auto GpgKeyOpera::ModifyTOFUPolicy(const GpgKey& key, gpgme_tofu_policy_t tofu_policy) -> GpgError { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gnupg_version", std::string{"2.0.0"}); + "core", "gpgme.ctx.gnupg_version", QString{"2.0.0"}); GF_CORE_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); if (CompareSoftwareVersion(gnupg_version, "2.1.10") < 0) { diff --git a/src/core/function/gpg/GpgKeyOpera.h b/src/core/function/gpg/GpgKeyOpera.h index 5039aa9e..83320cdd 100644 --- a/src/core/function/gpg/GpgKeyOpera.h +++ b/src/core/function/gpg/GpgKeyOpera.h @@ -91,7 +91,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyOpera * @param key * @param output_file_name */ - void GenerateRevokeCert(const GpgKey& key, const std::string& output_path); + void GenerateRevokeCert(const GpgKey& key, const QString& output_path); /** * @brief diff --git a/src/core/function/gpg/GpgUIDOperator.cpp b/src/core/function/gpg/GpgUIDOperator.cpp index 63afb40c..6c0373de 100644 --- a/src/core/function/gpg/GpgUIDOperator.cpp +++ b/src/core/function/gpg/GpgUIDOperator.cpp @@ -28,8 +28,6 @@ #include "GpgUIDOperator.h" -#include <boost/format.hpp> - #include "core/GpgModel.h" #include "core/utils/GpgUtils.h" @@ -38,31 +36,30 @@ namespace GpgFrontend { GpgUIDOperator::GpgUIDOperator(int channel) : SingletonFunctionObject<GpgUIDOperator>(channel) {} -auto GpgUIDOperator::AddUID(const GpgKey& key, const std::string& uid) -> bool { +auto GpgUIDOperator::AddUID(const GpgKey& key, const QString& uid) -> bool { auto err = gpgme_op_adduid(ctx_.DefaultContext(), - static_cast<gpgme_key_t>(key), uid.c_str(), 0); + static_cast<gpgme_key_t>(key), uid.toUtf8(), 0); return CheckGpgError(err) == GPG_ERR_NO_ERROR; } -auto GpgUIDOperator::RevUID(const GpgKey& key, const std::string& uid) -> bool { +auto GpgUIDOperator::RevUID(const GpgKey& key, const QString& uid) -> bool { auto err = CheckGpgError(gpgme_op_revuid( - ctx_.DefaultContext(), static_cast<gpgme_key_t>(key), uid.c_str(), 0)); + ctx_.DefaultContext(), static_cast<gpgme_key_t>(key), uid.toUtf8(), 0)); return CheckGpgError(err) == GPG_ERR_NO_ERROR; } -auto GpgUIDOperator::SetPrimaryUID(const GpgKey& key, const std::string& uid) +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.c_str(), + 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 std::string& name, - const std::string& comment, - const std::string& email) -> bool { +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); - auto uid = boost::format("%1%(%2%)<%3%>") % name % comment % email; - return AddUID(key, uid.str()); + return AddUID(key, QString("%1(%2)<%3>").arg(name).arg(comment).arg(email)); } } // namespace GpgFrontend diff --git a/src/core/function/gpg/GpgUIDOperator.h b/src/core/function/gpg/GpgUIDOperator.h index 982f8d08..b2cec8bc 100644 --- a/src/core/function/gpg/GpgUIDOperator.h +++ b/src/core/function/gpg/GpgUIDOperator.h @@ -53,7 +53,7 @@ class GPGFRONTEND_CORE_EXPORT GpgUIDOperator * @param uid uid args(combine name&comment&email) * @return if successful */ - auto AddUID(const GpgKey& key, const std::string& uid) -> bool; + auto AddUID(const GpgKey& key, const QString& uid) -> bool; /** * create a new uid in certain key pair @@ -63,8 +63,8 @@ class GPGFRONTEND_CORE_EXPORT GpgUIDOperator * @param email * @return */ - auto AddUID(const GpgKey& key, const std::string& name, - const std::string& comment, const std::string& email) -> bool; + auto AddUID(const GpgKey& key, const QString& name, const QString& comment, + const QString& email) -> bool; /** * Revoke(Delete) UID from certain key pair @@ -72,7 +72,7 @@ class GPGFRONTEND_CORE_EXPORT GpgUIDOperator * @param uid target uid * @return if successful */ - auto RevUID(const GpgKey& key, const std::string& uid) -> bool; + auto RevUID(const GpgKey& key, const QString& uid) -> bool; /** * Set one of a uid of a key pair as primary @@ -80,7 +80,7 @@ class GPGFRONTEND_CORE_EXPORT GpgUIDOperator * @param uid target uid * @return if successful */ - auto SetPrimaryUID(const GpgKey& key, const std::string& uid) -> bool; + auto SetPrimaryUID(const GpgKey& key, const QString& uid) -> bool; private: GpgContext& ctx_ = diff --git a/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp b/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp index 6f79d442..e52394b3 100644 --- a/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp @@ -41,54 +41,54 @@ void GpgFrontend::GpgDecryptResultAnalyse::doAnalyse() { stream_ << "# " << _("Decrypt Operation") << " "; if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { - stream_ << "- " << _("Success") << " " << std::endl; + stream_ << "- " << _("Success") << " " << Qt::endl; } else { stream_ << "- " << _("Failed") << ": " << gpgme_strerror(error_) - << std::endl; + << Qt::endl; setStatus(-1); if (result != nullptr && result->unsupported_algorithm != nullptr) { - stream_ << std::endl; + stream_ << Qt::endl; stream_ << "## " << _("Unsupported Algo") << ": " - << result->unsupported_algorithm << std::endl; + << result->unsupported_algorithm << Qt::endl; } } if (result != nullptr && result->recipients != nullptr) { - stream_ << std::endl; + stream_ << Qt::endl; - stream_ << "## " << _("Gernal State") << ": " << std::endl; + stream_ << "## " << _("Gernal State") << ": " << Qt::endl; if (result->file_name != nullptr) { stream_ << "- " << _("File Name") << ": " << result->file_name - << std::endl; + << Qt::endl; } stream_ << "- " << _("MIME") << ": " - << (result->is_mime == 0 ? _("false") : _("true")) << std::endl; + << (result->is_mime == 0 ? _("false") : _("true")) << Qt::endl; stream_ << "- " << _("Message Integrity Protection") << ": " << (result->legacy_cipher_nomdc == 0 ? _("true") : _("false")) - << std::endl; + << Qt::endl; if (result->legacy_cipher_nomdc == 1) setStatus(0); /// < unsafe situation if (result->symkey_algo != nullptr) { stream_ << "- " << _("Symmetric Encryption Algorithm") << ": " - << result->symkey_algo << std::endl; + << result->symkey_algo << Qt::endl; } if (result->session_key != nullptr) { stream_ << "- " << _("Session Key") << ": " << result->session_key - << std::endl; + << Qt::endl; } stream_ << "- " << _("German Encryption Standards") << ": " - << (result->is_de_vs == 0 ? _("false") : _("true")) << std::endl; + << (result->is_de_vs == 0 ? _("false") : _("true")) << Qt::endl; - stream_ << std::endl << std::endl; + stream_ << Qt::endl << Qt::endl; auto *recipient = result->recipients; auto index = 0; if (recipient != nullptr) { - stream_ << "## " << _("Recipient(s)") << ": " << std::endl << std::endl; + stream_ << "## " << _("Recipient(s)") << ": " << Qt::endl << Qt::endl; } while (recipient != nullptr) { @@ -96,35 +96,35 @@ void GpgFrontend::GpgDecryptResultAnalyse::doAnalyse() { if (recipient->keyid == nullptr) return; stream_ << "### " << _("Recipient") << " [" << ++index << "]: "; print_recipient(stream_, recipient); - stream_ << std::endl - << "---------------------------------------" << std::endl - << std::endl; + stream_ << Qt::endl + << "---------------------------------------" << Qt::endl + << Qt::endl; recipient = recipient->next; } - stream_ << std::endl; + stream_ << Qt::endl; } - stream_ << std::endl; + stream_ << Qt::endl; } void GpgFrontend::GpgDecryptResultAnalyse::print_recipient( - std::stringstream &stream, gpgme_recipient_t recipient) { + QTextStream &stream, gpgme_recipient_t recipient) { auto key = GpgFrontend::GpgKeyGetter::GetInstance().GetKey(recipient->keyid); if (key.IsGood()) { stream << key.GetName(); - if (!key.GetComment().empty()) stream << "(" << key.GetComment() << ")"; - if (!key.GetEmail().empty()) stream << "<" << key.GetEmail() << ">"; + if (!key.GetComment().isEmpty()) stream << "(" << key.GetComment() << ")"; + if (!key.GetEmail().isEmpty()) stream << "<" << key.GetEmail() << ">"; } else { stream << "<" << _("unknown") << ">"; setStatus(0); } - stream << std::endl; + stream << Qt::endl; - stream << "- " << _("Key ID") << ": " << recipient->keyid << std::endl; + stream << "- " << _("Key ID") << ": " << recipient->keyid << Qt::endl; stream << "- " << _("Public Key Algo") << ": " - << gpgme_pubkey_algo_name(recipient->pubkey_algo) << std::endl; + << gpgme_pubkey_algo_name(recipient->pubkey_algo) << Qt::endl; stream << "- " << _("Status") << ": " << gpgme_strerror(recipient->status) - << std::endl; + << Qt::endl; } diff --git a/src/core/function/result_analyse/GpgDecryptResultAnalyse.h b/src/core/function/result_analyse/GpgDecryptResultAnalyse.h index fe0aab7b..7ff9859f 100644 --- a/src/core/function/result_analyse/GpgDecryptResultAnalyse.h +++ b/src/core/function/result_analyse/GpgDecryptResultAnalyse.h @@ -62,7 +62,7 @@ class GPGFRONTEND_CORE_EXPORT GpgDecryptResultAnalyse * @param stream * @param recipient */ - void print_recipient(std::stringstream &stream, gpgme_recipient_t recipient); + void print_recipient(QTextStream &stream, gpgme_recipient_t recipient); GpgError error_; ///< GpgDecryptResult result_; ///< diff --git a/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp b/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp index 201dfddb..358e0787 100644 --- a/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp @@ -40,41 +40,41 @@ void GpgFrontend::GpgEncryptResultAnalyse::doAnalyse() { stream_ << "# " << _("Encrypt Operation") << " "; if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { - stream_ << "- " << _("Success") << " " << std::endl; + stream_ << "- " << _("Success") << " " << Qt::endl; } else { stream_ << "- " << _("Failed") << ": " << gpgme_strerror(error_) - << std::endl; + << Qt::endl; setStatus(-1); } if ((~status_) == 0) { - stream_ << std::endl; + stream_ << Qt::endl; const auto *result = result_.GetRaw(); if (result != nullptr) { - stream_ << "## " << _("Invalid Recipients") << ": " << std::endl - << std::endl; + stream_ << "## " << _("Invalid Recipients") << ": " << Qt::endl + << Qt::endl; auto *inv_reci = result->invalid_recipients; auto index = 0; while (inv_reci != nullptr) { stream_ << "### " << _("Recipients") << " " << ++index << ": " - << std::endl; + << Qt::endl; stream_ << "- " << _("Fingerprint") << ": " << inv_reci->fpr - << std::endl; + << Qt::endl; stream_ << "- " << _("Reason") << ": " - << gpgme_strerror(inv_reci->reason) << std::endl; - stream_ << std::endl << std::endl; + << gpgme_strerror(inv_reci->reason) << Qt::endl; + stream_ << Qt::endl << Qt::endl; inv_reci = inv_reci->next; } } - stream_ << std::endl; + stream_ << Qt::endl; } - stream_ << std::endl; + stream_ << Qt::endl; } } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/result_analyse/GpgResultAnalyse.cpp b/src/core/function/result_analyse/GpgResultAnalyse.cpp index 87027560..4c1f44e7 100644 --- a/src/core/function/result_analyse/GpgResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgResultAnalyse.cpp @@ -28,9 +28,8 @@ #include "GpgResultAnalyse.h" -auto GpgFrontend::GpgResultAnalyse::GetResultReport() const - -> const std::string { - return stream_.str(); +auto GpgFrontend::GpgResultAnalyse::GetResultReport() const -> const QString { + return *stream_.string(); } auto GpgFrontend::GpgResultAnalyse::GetStatus() const -> int { return status_; } diff --git a/src/core/function/result_analyse/GpgResultAnalyse.h b/src/core/function/result_analyse/GpgResultAnalyse.h index 3f22db09..d93a824f 100644 --- a/src/core/function/result_analyse/GpgResultAnalyse.h +++ b/src/core/function/result_analyse/GpgResultAnalyse.h @@ -44,9 +44,9 @@ class GPGFRONTEND_CORE_EXPORT GpgResultAnalyse { /** * @brief Get the Result Report object * - * @return const std::string + * @return const QString */ - [[nodiscard]] auto GetResultReport() const -> const std::string; + [[nodiscard]] auto GetResultReport() const -> const QString; /** * @brief Get the Status object @@ -75,9 +75,10 @@ class GPGFRONTEND_CORE_EXPORT GpgResultAnalyse { */ void setStatus(int m_status); - std::stringstream stream_; ///< - int status_ = 1; ///< - bool analysed_ = false; ///< + QString buffer_; + QTextStream stream_ = QTextStream(&buffer_); ///< + int status_ = 1; ///< + bool analysed_ = false; ///< }; } // namespace GpgFrontend diff --git a/src/core/function/result_analyse/GpgSignResultAnalyse.cpp b/src/core/function/result_analyse/GpgSignResultAnalyse.cpp index efaceb1d..a7251923 100644 --- a/src/core/function/result_analyse/GpgSignResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgSignResultAnalyse.cpp @@ -43,22 +43,21 @@ void GpgSignResultAnalyse::doAnalyse() { stream_ << "# " << _("Sign Operation") << " "; if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { - stream_ << "- " << _("Success") << " " << std::endl; + stream_ << "- " << _("Success") << " " << Qt::endl; } else { - stream_ << "- " << _("Failed") << " " << gpgme_strerror(error_) - << std::endl; + stream_ << "- " << _("Failed") << " " << gpgme_strerror(error_) << Qt::endl; setStatus(-1); } if (result != nullptr && (result->signatures != nullptr || result->invalid_signers != nullptr)) { - stream_ << std::endl; + stream_ << Qt::endl; auto *new_sign = result->signatures; auto index = 0; while (new_sign != nullptr) { stream_ << "## " << _("New Signature") << " [" << ++index - << "]: " << std::endl; + << "]: " << Qt::endl; stream_ << "- " << _("Sign Mode") << ": "; if (new_sign->type == GPGME_SIG_MODE_NORMAL) { @@ -69,57 +68,56 @@ void GpgSignResultAnalyse::doAnalyse() { stream_ << _("Detach"); } - stream_ << std::endl; + stream_ << Qt::endl; auto singer_key = GpgKeyGetter::GetInstance().GetKey(new_sign->fpr); if (singer_key.IsGood()) { stream_ << "- " << _("Signer") << ": " - << singer_key.GetUIDs()->front().GetUID() << std::endl; + << singer_key.GetUIDs()->front().GetUID() << Qt::endl; } else { stream_ << "- " << _("Signer") << ": " - << "<unknown>" << std::endl; + << "<unknown>" << Qt::endl; } stream_ << "- " << _("Public Key Algo") << ": " - << gpgme_pubkey_algo_name(new_sign->pubkey_algo) << std::endl; + << gpgme_pubkey_algo_name(new_sign->pubkey_algo) << Qt::endl; stream_ << "- " << _("Hash Algo") << ": " - << gpgme_hash_algo_name(new_sign->hash_algo) << std::endl; + << gpgme_hash_algo_name(new_sign->hash_algo) << Qt::endl; stream_ << "- " << _("Date") << "(" << _("UTC") << ")" << ": " - << boost::posix_time::to_iso_extended_string( - boost::posix_time::from_time_t(new_sign->timestamp)) - << std::endl; + << QDateTime::fromSecsSinceEpoch(new_sign->timestamp).toString() + << Qt::endl; stream_ << "- " << _("Date") << "(" << _("Localized") << ")" << ": " << GetFormatedDateByTimestamp(new_sign->timestamp) - << std::endl; + << Qt::endl; - stream_ << std::endl - << "---------------------------------------" << std::endl - << std::endl; + stream_ << Qt::endl + << "---------------------------------------" << Qt::endl + << Qt::endl; new_sign = new_sign->next; } auto *invalid_signer = result->invalid_signers; - stream_ << std::endl; + stream_ << Qt::endl; if (invalid_signer != nullptr) { - stream_ << "## " << _("Invalid Signers") << ": " << std::endl; + stream_ << "## " << _("Invalid Signers") << ": " << Qt::endl; } index = 0; while (invalid_signer != nullptr) { setStatus(0); - stream_ << "### " << _("Signer") << " [" << ++index << "]: " << std::endl - << std::endl; + stream_ << "### " << _("Signer") << " [" << ++index << "]: " << Qt::endl + << Qt::endl; stream_ << "- " << _("Fingerprint") << ": " << invalid_signer->fpr - << std::endl; + << Qt::endl; stream_ << "- " << _("Reason") << ": " - << gpgme_strerror(invalid_signer->reason) << std::endl; - stream_ << "---------------------------------------" << std::endl; + << gpgme_strerror(invalid_signer->reason) << Qt::endl; + stream_ << "---------------------------------------" << Qt::endl; invalid_signer = invalid_signer->next; } - stream_ << std::endl; + stream_ << Qt::endl; } } diff --git a/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp b/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp index cfd7f3f1..38d751dd 100644 --- a/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp @@ -28,8 +28,6 @@ #include "GpgVerifyResultAnalyse.h" -#include <boost/format.hpp> - #include "GpgFrontend.h" #include "core/GpgModel.h" #include "core/function/gpg/GpgKeyGetter.h" @@ -46,41 +44,39 @@ void GpgFrontend::GpgVerifyResultAnalyse::doAnalyse() { stream_ << "# " << _("Verify Operation") << " "; if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { - stream_ << " - " << _("Success") << " " << std::endl; + stream_ << " - " << _("Success") << " " << Qt::endl; } else { stream_ << " - " << _("Failed") << ": " << gpgme_strerror(error_) - << std::endl; + << Qt::endl; setStatus(-1); } if (result != nullptr && result->signatures != nullptr) { - stream_ << std::endl; + stream_ << Qt::endl; auto *sign = result->signatures; stream_ << "-> " << _("Signed On") << "(" << _("UTC") << ")" - << " " - << boost::posix_time::to_iso_extended_string( - boost::posix_time::from_time_t(sign->timestamp)) - << std::endl; + << " " << QDateTime::fromSecsSinceEpoch(sign->timestamp).toString() + << Qt::endl; stream_ << "-> " << _("Signed On") << "(" << _("Localized") << ")" - << " " << GetFormatedDateByTimestamp(sign->timestamp) << std::endl; + << " " << GetFormatedDateByTimestamp(sign->timestamp) << Qt::endl; - stream_ << std::endl << "## " << _("Signatures List") << ":" << std::endl; - stream_ << std::endl; + stream_ << Qt::endl << "## " << _("Signatures List") << ":" << Qt::endl; + stream_ << Qt::endl; bool can_continue = true; int count = 1; while ((sign != nullptr) && can_continue) { - stream_ << "### " << boost::format(_("Signature [%1%]:")) % count++ - << std::endl; + stream_ << "### " << QString(_("Signature [%1]:")).arg(count++) + << Qt::endl; stream_ << "- " << _("Status") << ": "; switch (gpg_err_code(sign->status)) { case GPG_ERR_BAD_SIGNATURE: - stream_ << _("A Bad Signature.") << std::endl; + stream_ << _("A Bad Signature.") << Qt::endl; print_signer(stream_, sign); - stream_ << _("This Signature is invalid.") << std::endl; + stream_ << _("This Signature is invalid.") << Qt::endl; can_continue = false; setStatus(-1); break; @@ -109,18 +105,18 @@ void GpgFrontend::GpgVerifyResultAnalyse::doAnalyse() { } if ((sign->summary & GPGME_SIGSUM_VALID) != 0) { - stream_ << _("Signature Fully Valid.") << std::endl; + stream_ << _("Signature Fully Valid.") << Qt::endl; } else { - stream_ << _("Signature Not Fully Valid.") << std::endl; + stream_ << _("Signature Not Fully Valid.") << Qt::endl; stream_ << _("(Adjust Trust Level to make it Fully Vaild)") - << std::endl; + << Qt::endl; } if ((sign->status & GPGME_SIGSUM_KEY_MISSING) == 0U) { if (!print_signer(stream_, sign)) setStatus(0); } else { stream_ << _("Key is NOT present with ID 0x") << sign->fpr - << std::endl; + << Qt::endl; } setStatus(1); @@ -128,20 +124,20 @@ void GpgFrontend::GpgVerifyResultAnalyse::doAnalyse() { break; case GPG_ERR_NO_PUBKEY: stream_ << _("A signature could NOT be verified due to a Missing Key") - << std::endl; + << Qt::endl; setStatus(-2); break; case GPG_ERR_CERT_REVOKED: stream_ << _("A signature is valid but the key used to verify the " "signature has been revoked") - << std::endl; + << Qt::endl; if (!print_signer(stream_, sign)) { setStatus(0); } setStatus(-1); break; case GPG_ERR_SIG_EXPIRED: - stream_ << _("A signature is valid but expired") << std::endl; + stream_ << _("A signature is valid but expired") << Qt::endl; if (!print_signer(stream_, sign)) { setStatus(0); } @@ -150,7 +146,7 @@ void GpgFrontend::GpgVerifyResultAnalyse::doAnalyse() { case GPG_ERR_KEY_EXPIRED: stream_ << _("A signature is valid but the key used to " "verify the signature has expired.") - << std::endl; + << Qt::endl; if (!print_signer(stream_, sign)) { setStatus(0); } @@ -158,63 +154,62 @@ void GpgFrontend::GpgVerifyResultAnalyse::doAnalyse() { case GPG_ERR_GENERAL: stream_ << _("There was some other error which prevented " "the signature verification.") - << std::endl; + << Qt::endl; status_ = -1; can_continue = false; break; default: - auto fpr = std::string(sign->fpr); + auto fpr = QString(sign->fpr); stream_ << _("Error for key with fingerprint") << " " << GpgFrontend::BeautifyFingerprint(fpr); setStatus(-1); } - stream_ << std::endl; + stream_ << Qt::endl; sign = sign->next; } - stream_ << std::endl; + stream_ << Qt::endl; } else { stream_ << "-> " << _("Could not find information that can be used for verification.") - << std::endl; + << Qt::endl; setStatus(0); return; } } -auto GpgFrontend::GpgVerifyResultAnalyse::print_signer( - std::stringstream &stream, gpgme_signature_t sign) -> bool { +auto GpgFrontend::GpgVerifyResultAnalyse::print_signer(QTextStream &stream, + gpgme_signature_t sign) + -> bool { bool key_found = true; auto key = GpgFrontend::GpgKeyGetter::GetInstance().GetKey(sign->fpr); if (!key.IsGood()) { stream << "- " << _("Signed By") << ": " - << "<" << _("Unknown") << ">" << std::endl; + << "<" << _("Unknown") << ">" << Qt::endl; setStatus(0); key_found = false; } else { stream << "- " << _("Signed By") << ": " << key.GetUIDs()->front().GetUID() - << std::endl; + << Qt::endl; } if (sign->pubkey_algo != 0U) { stream << "- " << _("Public Key Algo") << ": " - << gpgme_pubkey_algo_name(sign->pubkey_algo) << std::endl; + << gpgme_pubkey_algo_name(sign->pubkey_algo) << Qt::endl; } if (sign->hash_algo != 0U) { stream << "- " << _("Hash Algo") << ": " - << gpgme_hash_algo_name(sign->hash_algo) << std::endl; + << gpgme_hash_algo_name(sign->hash_algo) << Qt::endl; } if (sign->timestamp != 0U) { stream << "- " << _("Date") << "(" << _("UTC") << ")" - << ": " - << boost::posix_time::to_iso_extended_string( - boost::posix_time::from_time_t(sign->timestamp)) - << std::endl; + << ": " << QDateTime::fromSecsSinceEpoch(sign->timestamp).toString() + << Qt::endl; stream << "- " << _("Date") << "(" << _("Localized") << ")" - << ": " << GetFormatedDateByTimestamp(sign->timestamp) << std::endl; + << ": " << GetFormatedDateByTimestamp(sign->timestamp) << Qt::endl; } - stream << std::endl; + stream << Qt::endl; return key_found; } diff --git a/src/core/function/result_analyse/GpgVerifyResultAnalyse.h b/src/core/function/result_analyse/GpgVerifyResultAnalyse.h index 266f9b24..054083a1 100644 --- a/src/core/function/result_analyse/GpgVerifyResultAnalyse.h +++ b/src/core/function/result_analyse/GpgVerifyResultAnalyse.h @@ -76,7 +76,7 @@ class GPGFRONTEND_CORE_EXPORT GpgVerifyResultAnalyse : public GpgResultAnalyse { * @return true * @return false */ - auto print_signer(std::stringstream &stream, gpgme_signature_t sign) -> bool; + auto print_signer(QTextStream &stream, gpgme_signature_t sign) -> bool; GpgError error_; ///< GpgVerifyResult result_; ///< diff --git a/src/core/log/QtLoggerFmt.h b/src/core/log/QtLoggerFmt.h new file mode 100644 index 00000000..3cb38160 --- /dev/null +++ b/src/core/log/QtLoggerFmt.h @@ -0,0 +1,51 @@ +/** + * 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 + +template <> +struct fmt::formatter<QString> { + // Parses format specifications. + constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + auto it = std::find(ctx.begin(), ctx.end(), '}'); + if (it != ctx.end() && *it != '}') { + throw fmt::format_error("invalid format specifier for QString"); + } + return it; + } + + // 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 utf8Str = qstr.toUtf8(); + return fmt::format_to(ctx.out(), "{}", utf8Str.constData()); + } +}; diff --git a/src/core/model/GFBuffer.cpp b/src/core/model/GFBuffer.cpp index 117a6f12..c65ae689 100644 --- a/src/core/model/GFBuffer.cpp +++ b/src/core/model/GFBuffer.cpp @@ -33,12 +33,6 @@ namespace GpgFrontend { GFBuffer::GFBuffer() : buffer_(SecureCreateSharedObject<std::vector<std::byte>>()) {} -GFBuffer::GFBuffer(const std::string& str) - : buffer_(SecureCreateSharedObject<std::vector<std::byte>>()) { - std::transform(str.begin(), str.end(), std::back_inserter(*buffer_), - [](const char c) { return static_cast<std::byte>(c); }); -} - GFBuffer::GFBuffer(const char* c_str) : buffer_(SecureCreateSharedObject<std::vector<std::byte>>()) { if (c_str == nullptr) { @@ -81,8 +75,4 @@ auto GFBuffer::ConvertToQByteArray() const -> QByteArray { auto GFBuffer::Empty() const -> bool { return this->Size() == 0; } -auto GFBuffer::ConvertToStdString() const -> std::string { - return {reinterpret_cast<const char*>(buffer_->data()), buffer_->size()}; -} - } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/model/GFBuffer.h b/src/core/model/GFBuffer.h index 7cd5cbc5..d947401e 100644 --- a/src/core/model/GFBuffer.h +++ b/src/core/model/GFBuffer.h @@ -37,8 +37,6 @@ class GPGFRONTEND_CORE_EXPORT GFBuffer { public: GFBuffer(); - explicit GFBuffer(const std::string& str); - explicit GFBuffer(const char* c_str); explicit GFBuffer(QByteArray buffer); @@ -57,8 +55,6 @@ class GPGFRONTEND_CORE_EXPORT GFBuffer { [[nodiscard]] auto ConvertToQByteArray() const -> QByteArray; - [[nodiscard]] auto ConvertToStdString() const -> std::string; - private: std::shared_ptr<std::vector<std::byte>> buffer_; }; diff --git a/src/core/model/GpgData.cpp b/src/core/model/GpgData.cpp index 15b01595..e3d5e666 100644 --- a/src/core/model/GpgData.cpp +++ b/src/core/model/GpgData.cpp @@ -127,29 +127,6 @@ GpgData::~GpgData() { } } -auto GpgData::Read2Buffer() -> ByteArrayPtr { - gpgme_off_t ret = gpgme_data_seek(*this, 0, SEEK_SET); - ByteArrayPtr out_buffer = std::make_unique<std::string>(); - - if (ret != 0) { - GpgError const err = gpgme_err_code_from_errno(errno); - assert(gpgme_err_code(err) == GPG_ERR_NO_ERROR); - } else { - std::array<std::byte, kBufferSize + 2> buf; - - while ((ret = gpgme_data_read(*this, buf.data(), kBufferSize)) > 0) { - const size_t size = out_buffer->size(); - out_buffer->resize(static_cast<int>(size + ret)); - memcpy(out_buffer->data() + size, buf.data(), ret); - } - if (ret < 0) { - GpgError const err = gpgme_err_code_from_errno(errno); - assert(gpgme_err_code(err) == GPG_ERR_NO_ERROR); - } - } - return out_buffer; -} - auto GpgData::Read2GFBuffer() -> GFBuffer { gpgme_off_t ret = gpgme_data_seek(*this, 0, SEEK_SET); GFBuffer out_buffer; diff --git a/src/core/model/GpgData.h b/src/core/model/GpgData.h index 9a55a18c..f0ef2a49 100644 --- a/src/core/model/GpgData.h +++ b/src/core/model/GpgData.h @@ -102,13 +102,6 @@ class GPGFRONTEND_CORE_EXPORT GpgData { * * @return ByteArrayPtr */ - auto Read2Buffer() -> ByteArrayPtr; - - /** - * @brief - * - * @return ByteArrayPtr - */ auto Read2GFBuffer() -> GFBuffer; private: diff --git a/src/core/model/GpgEncryptResult.cpp b/src/core/model/GpgEncryptResult.cpp index f135dac9..843cf7eb 100644 --- a/src/core/model/GpgEncryptResult.cpp +++ b/src/core/model/GpgEncryptResult.cpp @@ -48,12 +48,12 @@ auto GpgEncryptResult::GetRaw() -> gpgme_encrypt_result_t { } auto GpgEncryptResult::InvalidRecipients() - -> std::vector<std::tuple<std::string, GpgError>> { - std::vector<std::tuple<std::string, GpgError>> result; + -> std::vector<std::tuple<QString, GpgError>> { + std::vector<std::tuple<QString, GpgError>> result; for (auto* invalid_key = result_ref_->invalid_recipients; invalid_key != nullptr; invalid_key = invalid_key->next) { try { - result.emplace_back(std::string{invalid_key->fpr}, invalid_key->reason); + result.emplace_back(QString{invalid_key->fpr}, invalid_key->reason); } catch (...) { GF_CORE_LOG_ERROR( "caught exception when processing invalid_recipients, " diff --git a/src/core/model/GpgEncryptResult.h b/src/core/model/GpgEncryptResult.h index 4ce282cb..61fca710 100644 --- a/src/core/model/GpgEncryptResult.h +++ b/src/core/model/GpgEncryptResult.h @@ -38,7 +38,7 @@ class GPGFRONTEND_CORE_EXPORT GpgEncryptResult { auto GetRaw() -> gpgme_encrypt_result_t; - auto InvalidRecipients() -> std::vector<std::tuple<std::string, GpgError>>; + auto InvalidRecipients() -> std::vector<std::tuple<QString, GpgError>>; explicit GpgEncryptResult(gpgme_encrypt_result_t); diff --git a/src/core/model/GpgGenKeyInfo.cpp b/src/core/model/GpgGenKeyInfo.cpp index 578f64fc..3e705f16 100644 --- a/src/core/model/GpgGenKeyInfo.cpp +++ b/src/core/model/GpgGenKeyInfo.cpp @@ -29,16 +29,14 @@ #include "GpgGenKeyInfo.h" #include <algorithm> -#include <boost/format.hpp> #include <cassert> #include "core/utils/LogUtils.h" namespace GpgFrontend { -void GenKeyInfo::SetAlgo(const std::string &t_algo_args) { - auto algo_args = t_algo_args; - boost::algorithm::to_lower(algo_args); +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 @@ -131,9 +129,9 @@ void GenKeyInfo::reset_options() { passphrase_.clear(); } -auto GenKeyInfo::GetKeySizeStr() const -> std::string { +auto GenKeyInfo::GetKeySizeStr() const -> QString { if (key_size_ > 0) { - return std::to_string(key_size_); + return QString::number(key_size_); } return {}; } @@ -224,12 +222,10 @@ void GenKeyInfo::SetIsSubKey(bool m_sub_key) { /** * @brief Get the Userid object * - * @return std::string + * @return QString */ -[[nodiscard]] auto GenKeyInfo::GetUserid() const -> std::string { - auto uid_format = boost::format("%1%(%2%)<%3%>") % this->name_ % - this->comment_ % this->email_; - return uid_format.str(); +[[nodiscard]] auto GenKeyInfo::GetUserid() const -> QString { + return QString("%1(%2)<%3>").arg(name_).arg(comment_).arg(email_); } /** @@ -237,57 +233,53 @@ void GenKeyInfo::SetIsSubKey(bool m_sub_key) { * * @param m_name */ -void GenKeyInfo::SetName(const std::string &m_name) { this->name_ = m_name; } +void GenKeyInfo::SetName(const QString &m_name) { this->name_ = m_name; } /** * @brief Set the Email object * * @param m_email */ -void GenKeyInfo::SetEmail(const std::string &m_email) { - this->email_ = m_email; -} +void GenKeyInfo::SetEmail(const QString &m_email) { this->email_ = m_email; } /** * @brief Set the Comment object * * @param m_comment */ -void GenKeyInfo::SetComment(const std::string &m_comment) { +void GenKeyInfo::SetComment(const QString &m_comment) { this->comment_ = m_comment; } /** * @brief Get the Name object * - * @return std::string + * @return QString */ -[[nodiscard]] auto GenKeyInfo::GetName() const -> std::string { return name_; } +[[nodiscard]] auto GenKeyInfo::GetName() const -> QString { return name_; } /** * @brief Get the Email object * - * @return std::string + * @return QString */ -[[nodiscard]] auto GenKeyInfo::GetEmail() const -> std::string { - return email_; -} +[[nodiscard]] auto GenKeyInfo::GetEmail() const -> QString { return email_; } /** * @brief Get the Comment object * - * @return std::string + * @return QString */ -[[nodiscard]] auto GenKeyInfo::GetComment() const -> std::string { +[[nodiscard]] auto GenKeyInfo::GetComment() const -> QString { return comment_; } /** * @brief Get the Algo object * - * @return const std::string& + * @return const QString& */ -[[nodiscard]] auto GenKeyInfo::GetAlgo() const -> const std::string & { +[[nodiscard]] auto GenKeyInfo::GetAlgo() const -> const QString & { return algo_; } @@ -410,9 +402,9 @@ void GenKeyInfo::SetAllowAuthentication(bool m_allow_authentication) { /** * @brief Get the Pass Phrase object * - * @return const std::string& + * @return const QString& */ -[[nodiscard]] auto GenKeyInfo::GetPassPhrase() const -> const std::string & { +[[nodiscard]] auto GenKeyInfo::GetPassPhrase() const -> const QString & { return passphrase_; } @@ -421,7 +413,7 @@ void GenKeyInfo::SetAllowAuthentication(bool m_allow_authentication) { * * @param m_pass_phrase */ -void GenKeyInfo::SetPassPhrase(const std::string &m_pass_phrase) { +void GenKeyInfo::SetPassPhrase(const QString &m_pass_phrase) { GenKeyInfo::passphrase_ = m_pass_phrase; } diff --git a/src/core/model/GpgGenKeyInfo.h b/src/core/model/GpgGenKeyInfo.h index e155b4ba..cf12e8b4 100644 --- a/src/core/model/GpgGenKeyInfo.h +++ b/src/core/model/GpgGenKeyInfo.h @@ -34,7 +34,7 @@ namespace GpgFrontend { class GPGFRONTEND_CORE_EXPORT GenKeyInfo { public: - using KeyGenAlgo = std::tuple<std::string, std::string, std::string>; + using KeyGenAlgo = std::tuple<QString, QString, QString>; /** * @brief Construct a new Gen Key Info object @@ -47,14 +47,14 @@ class GPGFRONTEND_CORE_EXPORT GenKeyInfo { /** * @brief Get the Supported Key Algo object * - * @return const std::vector<std::string>& + * @return const std::vector<QString>& */ static auto GetSupportedKeyAlgo() -> const std::vector<KeyGenAlgo> &; /** * @brief Get the Supported Subkey Algo object * - * @return const std::vector<std::string>& + * @return const std::vector<QString>& */ static auto GetSupportedSubkeyAlgo() -> const std::vector<KeyGenAlgo> &; @@ -76,72 +76,72 @@ class GPGFRONTEND_CORE_EXPORT GenKeyInfo { /** * @brief Get the Userid object * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetUserid() const -> std::string; + [[nodiscard]] auto GetUserid() const -> QString; /** * @brief Set the Name object * * @param m_name */ - void SetName(const std::string &m_name); + void SetName(const QString &m_name); /** * @brief Set the Email object * * @param m_email */ - void SetEmail(const std::string &m_email); + void SetEmail(const QString &m_email); /** * @brief Set the Comment object * * @param m_comment */ - void SetComment(const std::string &m_comment); + void SetComment(const QString &m_comment); /** * @brief Get the Name object * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetName() const -> std::string; + [[nodiscard]] auto GetName() const -> QString; /** * @brief Get the Email object * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetEmail() const -> std::string; + [[nodiscard]] auto GetEmail() const -> QString; /** * @brief Get the Comment object * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetComment() const -> std::string; + [[nodiscard]] auto GetComment() const -> QString; /** * @brief Get the Algo object * - * @return const std::string& + * @return const QString& */ - [[nodiscard]] auto GetAlgo() const -> const std::string &; + [[nodiscard]] auto GetAlgo() const -> const QString &; /** * @brief Set the Algo object * * @param m_algo */ - void SetAlgo(const std::string &); + void SetAlgo(const QString &); /** * @brief Get the Key Size Str object * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetKeySizeStr() const -> std::string; + [[nodiscard]] auto GetKeySizeStr() const -> QString; /** * @brief Get the Key Size object @@ -272,16 +272,16 @@ class GPGFRONTEND_CORE_EXPORT GenKeyInfo { /** * @brief Get the Pass Phrase object * - * @return const std::string& + * @return const QString& */ - [[nodiscard]] auto GetPassPhrase() const -> const std::string &; + [[nodiscard]] auto GetPassPhrase() const -> const QString &; /** * @brief Set the Pass Phrase object * * @param m_pass_phrase */ - void SetPassPhrase(const std::string &m_pass_phrase); + void SetPassPhrase(const QString &m_pass_phrase); /** * @brief @@ -338,11 +338,11 @@ class GPGFRONTEND_CORE_EXPORT GenKeyInfo { private: bool subkey_ = false; ///< - std::string name_; ///< - std::string email_; ///< - std::string comment_; ///< + QString name_; ///< + QString email_; ///< + QString comment_; ///< - std::string algo_; ///< + QString algo_; ///< int key_size_ = 2048; boost::posix_time::ptime expired_ = boost::posix_time::second_clock::local_time() + @@ -356,7 +356,7 @@ class GPGFRONTEND_CORE_EXPORT GenKeyInfo { int suggest_size_addition_step_ = 1024; ///< int suggest_min_key_size_ = 1024; ///< - std::string passphrase_; ///< + QString passphrase_; ///< bool allow_encryption_ = true; ///< bool allow_change_encryption_ = true; ///< diff --git a/src/core/model/GpgGenerateKeyResult.cpp b/src/core/model/GpgGenerateKeyResult.cpp index 990024de..f7ebf14e 100644 --- a/src/core/model/GpgGenerateKeyResult.cpp +++ b/src/core/model/GpgGenerateKeyResult.cpp @@ -42,7 +42,7 @@ GpgGenerateKeyResult::GpgGenerateKeyResult(gpgme_genkey_result_t r) auto GpgGenerateKeyResult::IsGood() -> bool { return result_ref_ != nullptr; } -auto GpgGenerateKeyResult::GetFingerprint() -> std::string const { +auto GpgGenerateKeyResult::GetFingerprint() -> QString const { return result_ref_->fpr; } diff --git a/src/core/model/GpgGenerateKeyResult.h b/src/core/model/GpgGenerateKeyResult.h index 3601da8b..f312d415 100644 --- a/src/core/model/GpgGenerateKeyResult.h +++ b/src/core/model/GpgGenerateKeyResult.h @@ -37,7 +37,7 @@ class GPGFRONTEND_CORE_EXPORT GpgGenerateKeyResult { public: auto IsGood() -> bool; - auto GetFingerprint() -> std::string const; + auto GetFingerprint() -> QString const; explicit GpgGenerateKeyResult(gpgme_genkey_result_t); diff --git a/src/core/model/GpgImportInformation.h b/src/core/model/GpgImportInformation.h index 87d23bf9..5f85a338 100644 --- a/src/core/model/GpgImportInformation.h +++ b/src/core/model/GpgImportInformation.h @@ -42,7 +42,7 @@ class GPGFRONTEND_CORE_EXPORT GpgImportInformation { */ class GpgImportedKey { public: - std::string fpr; ///< + QString fpr; ///< int import_status; ///< }; diff --git a/src/core/model/GpgKey.cpp b/src/core/model/GpgKey.cpp index 6e2f1083..73c67045 100644 --- a/src/core/model/GpgKey.cpp +++ b/src/core/model/GpgKey.cpp @@ -71,23 +71,21 @@ GpgKey::operator gpgme_key_t() const { return key_ref_.get(); } auto GpgKey::IsGood() const -> bool { return key_ref_ != nullptr; } -auto GpgKey::GetId() const -> std::string { return key_ref_->subkeys->keyid; } +auto GpgKey::GetId() const -> QString { return key_ref_->subkeys->keyid; } -auto GpgKey::GetName() const -> std::string { return key_ref_->uids->name; }; +auto GpgKey::GetName() const -> QString { return key_ref_->uids->name; }; -auto GpgKey::GetEmail() const -> std::string { return key_ref_->uids->email; } +auto GpgKey::GetEmail() const -> QString { return key_ref_->uids->email; } -auto GpgKey::GetComment() const -> std::string { - return key_ref_->uids->comment; -} +auto GpgKey::GetComment() const -> QString { return key_ref_->uids->comment; } -auto GpgKey::GetFingerprint() const -> std::string { return key_ref_->fpr; } +auto GpgKey::GetFingerprint() const -> QString { return key_ref_->fpr; } -auto GpgKey::GetProtocol() const -> std::string { +auto GpgKey::GetProtocol() const -> QString { return gpgme_get_protocol_name(key_ref_->protocol); } -auto GpgKey::GetOwnerTrust() const -> std::string { +auto GpgKey::GetOwnerTrust() const -> QString { switch (key_ref_->owner_trust) { case GPGME_VALIDITY_UNKNOWN: return _("Unknown"); @@ -123,7 +121,7 @@ auto GpgKey::GetOwnerTrustLevel() const -> int { return 0; } -auto GpgKey::GetPublicKeyAlgo() const -> std::string { +auto GpgKey::GetPublicKeyAlgo() const -> QString { return gpgme_pubkey_algo_name(key_ref_->subkeys->pubkey_algo); } diff --git a/src/core/model/GpgKey.h b/src/core/model/GpgKey.h index 5d53c9d2..09224304 100644 --- a/src/core/model/GpgKey.h +++ b/src/core/model/GpgKey.h @@ -52,51 +52,51 @@ class GPGFRONTEND_CORE_EXPORT GpgKey { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetId() const -> std::string; + [[nodiscard]] auto GetId() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetName() const -> std::string; + [[nodiscard]] auto GetName() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetEmail() const -> std::string; + [[nodiscard]] auto GetEmail() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetComment() const -> std::string; + [[nodiscard]] auto GetComment() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetFingerprint() const -> std::string; + [[nodiscard]] auto GetFingerprint() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetProtocol() const -> std::string; + [[nodiscard]] auto GetProtocol() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetOwnerTrust() const -> std::string; + [[nodiscard]] auto GetOwnerTrust() const -> QString; /** * @brief @@ -108,9 +108,9 @@ class GPGFRONTEND_CORE_EXPORT GpgKey { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetPublicKeyAlgo() const -> std::string; + [[nodiscard]] auto GetPublicKeyAlgo() const -> QString; /** * @brief diff --git a/src/core/model/GpgKeySignature.cpp b/src/core/model/GpgKeySignature.cpp index 14dc8f1a..eef46816 100644 --- a/src/core/model/GpgKeySignature.cpp +++ b/src/core/model/GpgKeySignature.cpp @@ -56,9 +56,9 @@ gpgme_error_t GpgKeySignature::GetStatus() const { return signature_ref_->status; } -std::string GpgKeySignature::GetKeyID() const { return signature_ref_->keyid; } +QString GpgKeySignature::GetKeyID() const { return signature_ref_->keyid; } -std::string GpgKeySignature::GetPubkeyAlgo() const { +QString GpgKeySignature::GetPubkeyAlgo() const { return gpgme_pubkey_algo_name(signature_ref_->pubkey_algo); } @@ -70,13 +70,11 @@ boost::posix_time::ptime GpgKeySignature::GetExpireTime() const { return boost::posix_time::from_time_t(signature_ref_->expires); } -std::string GpgKeySignature::GetUID() const { return signature_ref_->uid; } +QString GpgKeySignature::GetUID() const { return signature_ref_->uid; } -std::string GpgKeySignature::GetName() const { return signature_ref_->name; } +QString GpgKeySignature::GetName() const { return signature_ref_->name; } -std::string GpgKeySignature::GetEmail() const { return signature_ref_->email; } +QString GpgKeySignature::GetEmail() const { return signature_ref_->email; } -std::string GpgKeySignature::GetComment() const { - return signature_ref_->comment; -} +QString GpgKeySignature::GetComment() const { return signature_ref_->comment; } } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/model/GpgKeySignature.h b/src/core/model/GpgKeySignature.h index fa000749..a15db99d 100644 --- a/src/core/model/GpgKeySignature.h +++ b/src/core/model/GpgKeySignature.h @@ -86,16 +86,16 @@ class GPGFRONTEND_CORE_EXPORT GpgKeySignature { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetKeyID() const -> std::string; + [[nodiscard]] auto GetKeyID() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetPubkeyAlgo() const -> std::string; + [[nodiscard]] auto GetPubkeyAlgo() const -> QString; /** * @brief Create a time object @@ -114,30 +114,30 @@ class GPGFRONTEND_CORE_EXPORT GpgKeySignature { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetUID() const -> std::string; + [[nodiscard]] auto GetUID() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetName() const -> std::string; + [[nodiscard]] auto GetName() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetEmail() const -> std::string; + [[nodiscard]] auto GetEmail() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetComment() const -> std::string; + [[nodiscard]] auto GetComment() const -> QString; /** * @brief Construct a new Gpg Key Signature object diff --git a/src/core/model/GpgPassphraseContext.cpp b/src/core/model/GpgPassphraseContext.cpp new file mode 100644 index 00000000..45aab442 --- /dev/null +++ b/src/core/model/GpgPassphraseContext.cpp @@ -0,0 +1,57 @@ +/** + * 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 "GpgPassphraseContext.h" + +namespace GpgFrontend { + +GpgPassphraseContext::GpgPassphraseContext(const QString& uids_info, + const QString& passphrase_info, + bool prev_was_bad) + : passphrase_info_(passphrase_info), + uids_info_(uids_info), + prev_was_bad_(prev_was_bad) {} + +GpgPassphraseContext::GpgPassphraseContext() = default; + +auto GpgPassphraseContext::GetPassphrase() const -> QString { + return passphrase_; +} + +void GpgPassphraseContext::SetPassphrase(const QString& passphrase) { + passphrase_ = passphrase; +} + +auto GpgPassphraseContext::GetUidsInfo() const -> QString { return uids_info_; } + +auto GpgPassphraseContext::GetPassphraseInfo() const -> QString { + return passphrase_info_; +} + +auto GpgPassphraseContext::IsPreWasBad() const -> bool { return prev_was_bad_; } +} // namespace GpgFrontend diff --git a/src/core/model/GpgPassphraseContext.h b/src/core/model/GpgPassphraseContext.h new file mode 100644 index 00000000..5eaf5b2f --- /dev/null +++ b/src/core/model/GpgPassphraseContext.h @@ -0,0 +1,60 @@ +#include <utility> + +/** + * 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 + +namespace GpgFrontend { + +class GPGFRONTEND_CORE_EXPORT GpgPassphraseContext : public QObject { + Q_OBJECT + public: + GpgPassphraseContext(const QString& uids_info, const QString& passphrase_info, + bool prev_was_bad); + + GpgPassphraseContext(); + + void SetPassphrase(const QString& passphrase); + + [[nodiscard]] auto GetPassphrase() const -> QString; + + [[nodiscard]] auto GetUidsInfo() const -> QString; + + [[nodiscard]] auto GetPassphraseInfo() const -> QString; + + [[nodiscard]] auto IsPreWasBad() const -> bool; + + private: + QString passphrase_info_; + QString uids_info_; + QString passphrase_; + bool prev_was_bad_; +}; + +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/model/GpgRecipient.cpp b/src/core/model/GpgRecipient.cpp index 34c50edc..54de43bc 100644 --- a/src/core/model/GpgRecipient.cpp +++ b/src/core/model/GpgRecipient.cpp @@ -33,8 +33,8 @@ namespace GpgFrontend { GpgRecipient::GpgRecipient() = default; GpgRecipient::GpgRecipient(gpgme_recipient_t r) { - this->keyid = std::string{r->keyid}; - this->pubkey_algo = std::string{gpgme_pubkey_algo_name(r->pubkey_algo)}; + this->keyid = QString{r->keyid}; + this->pubkey_algo = QString{gpgme_pubkey_algo_name(r->pubkey_algo)}; this->status = r->status; } } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/model/GpgRecipient.h b/src/core/model/GpgRecipient.h index 9c686817..a436c1d7 100644 --- a/src/core/model/GpgRecipient.h +++ b/src/core/model/GpgRecipient.h @@ -35,10 +35,10 @@ namespace GpgFrontend { struct GPGFRONTEND_CORE_EXPORT GpgRecipient { /* The key ID of key for which the text was encrypted. */ - std::string keyid; + QString keyid; /* The public key algorithm of the recipient key. */ - std::string pubkey_algo; + QString pubkey_algo; /* The status of the recipient. */ GpgError status; diff --git a/src/core/model/GpgSignResult.cpp b/src/core/model/GpgSignResult.cpp index 90d337b7..4a0e5f35 100644 --- a/src/core/model/GpgSignResult.cpp +++ b/src/core/model/GpgSignResult.cpp @@ -48,12 +48,12 @@ auto GpgSignResult::GetRaw() -> gpgme_sign_result_t { } auto GpgSignResult::InvalidSigners() - -> std::vector<std::tuple<std::string, GpgError>> { - std::vector<std::tuple<std::string, GpgError>> result; + -> std::vector<std::tuple<QString, GpgError>> { + std::vector<std::tuple<QString, GpgError>> result; for (auto* invalid_key = result_ref_->invalid_signers; invalid_key != nullptr; invalid_key = invalid_key->next) { try { - result.emplace_back(std::string{invalid_key->fpr}, invalid_key->reason); + result.emplace_back(QString{invalid_key->fpr}, invalid_key->reason); } catch (...) { GF_CORE_LOG_ERROR( "caught exception when processing invalid_signers, " diff --git a/src/core/model/GpgSignResult.h b/src/core/model/GpgSignResult.h index 14537971..ccb0361f 100644 --- a/src/core/model/GpgSignResult.h +++ b/src/core/model/GpgSignResult.h @@ -39,7 +39,7 @@ class GPGFRONTEND_CORE_EXPORT GpgSignResult { auto GetRaw() -> gpgme_sign_result_t; - auto InvalidSigners() -> std::vector<std::tuple<std::string, GpgError>>; + auto InvalidSigners() -> std::vector<std::tuple<QString, GpgError>>; explicit GpgSignResult(gpgme_sign_result_t); diff --git a/src/core/model/GpgSignature.cpp b/src/core/model/GpgSignature.cpp index 727942f5..64bf7e37 100644 --- a/src/core/model/GpgSignature.cpp +++ b/src/core/model/GpgSignature.cpp @@ -82,18 +82,18 @@ auto GpgSignature::GetSummary() const -> gpgme_error_t { /** * @brief * - * @return std::string + * @return QString */ -auto GpgSignature::GetPubkeyAlgo() const -> std::string { +auto GpgSignature::GetPubkeyAlgo() const -> QString { return gpgme_pubkey_algo_name(signature_ref_->pubkey_algo); } /** * @brief * - * @return std::string + * @return QString */ -auto GpgSignature::GetHashAlgo() const -> std::string { +auto GpgSignature::GetHashAlgo() const -> QString { return gpgme_hash_algo_name(signature_ref_->hash_algo); } @@ -118,9 +118,9 @@ auto GpgSignature::GetExpireTime() const -> boost::posix_time::ptime { /** * @brief * - * @return std::string + * @return QString */ -auto GpgSignature::GetFingerprint() const -> std::string { +auto GpgSignature::GetFingerprint() const -> QString { return signature_ref_->fpr; } diff --git a/src/core/model/GpgSignature.h b/src/core/model/GpgSignature.h index 4e01d728..68ecf094 100644 --- a/src/core/model/GpgSignature.h +++ b/src/core/model/GpgSignature.h @@ -64,16 +64,16 @@ class GPGFRONTEND_CORE_EXPORT GpgSignature { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetPubkeyAlgo() const -> std::string; + [[nodiscard]] auto GetPubkeyAlgo() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetHashAlgo() const -> std::string; + [[nodiscard]] auto GetHashAlgo() const -> QString; /** * @brief Create a time object @@ -92,9 +92,9 @@ class GPGFRONTEND_CORE_EXPORT GpgSignature { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetFingerprint() const -> std::string; + [[nodiscard]] auto GetFingerprint() const -> QString; /** * @brief Construct a new Gpg Signature object diff --git a/src/core/model/GpgSubKey.cpp b/src/core/model/GpgSubKey.cpp index e4103d50..ccf50e76 100644 --- a/src/core/model/GpgSubKey.cpp +++ b/src/core/model/GpgSubKey.cpp @@ -47,13 +47,11 @@ auto GpgSubKey::operator==(const GpgSubKey& o) const -> bool { return GetFingerprint() == o.GetFingerprint(); } -auto GpgSubKey::GetID() const -> std::string { return subkey_ref_->keyid; } +auto GpgSubKey::GetID() const -> QString { return subkey_ref_->keyid; } -auto GpgSubKey::GetFingerprint() const -> std::string { - return subkey_ref_->fpr; -} +auto GpgSubKey::GetFingerprint() const -> QString { return subkey_ref_->fpr; } -auto GpgSubKey::GetPubkeyAlgo() const -> std::string { +auto GpgSubKey::GetPubkeyAlgo() const -> QString { return gpgme_pubkey_algo_name(subkey_ref_->pubkey_algo); } diff --git a/src/core/model/GpgSubKey.h b/src/core/model/GpgSubKey.h index f70f7e9c..2556d915 100644 --- a/src/core/model/GpgSubKey.h +++ b/src/core/model/GpgSubKey.h @@ -41,23 +41,23 @@ class GPGFRONTEND_CORE_EXPORT GpgSubKey { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetID() const -> std::string; + [[nodiscard]] auto GetID() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetFingerprint() const -> std::string; + [[nodiscard]] auto GetFingerprint() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetPubkeyAlgo() const -> std::string; + [[nodiscard]] auto GetPubkeyAlgo() const -> QString; /** * @brief diff --git a/src/core/model/GpgTOFUInfo.cpp b/src/core/model/GpgTOFUInfo.cpp index 4e99ebf5..251affc2 100644 --- a/src/core/model/GpgTOFUInfo.cpp +++ b/src/core/model/GpgTOFUInfo.cpp @@ -85,9 +85,9 @@ auto GpgTOFUInfo::GetEncrLast() const -> unsigned long { /** * @brief * - * @return std::string + * @return QString */ -auto GpgTOFUInfo::GetDescription() const -> std::string { +auto GpgTOFUInfo::GetDescription() const -> QString { return tofu_info_ref_->description; } diff --git a/src/core/model/GpgTOFUInfo.h b/src/core/model/GpgTOFUInfo.h index c9f52bca..ec4c49b7 100644 --- a/src/core/model/GpgTOFUInfo.h +++ b/src/core/model/GpgTOFUInfo.h @@ -86,9 +86,9 @@ class GPGFRONTEND_CORE_EXPORT GpgTOFUInfo { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetDescription() const -> std::string; + [[nodiscard]] auto GetDescription() const -> QString; /** * @brief Construct a new Gpg T O F U Info object diff --git a/src/core/model/GpgUID.cpp b/src/core/model/GpgUID.cpp index 4327ae6a..e0d9d3a6 100644 --- a/src/core/model/GpgUID.cpp +++ b/src/core/model/GpgUID.cpp @@ -37,13 +37,13 @@ GpgUID::GpgUID(gpgme_user_id_t uid) GpgUID::GpgUID(GpgUID &&o) noexcept { swap(uid_ref_, o.uid_ref_); } -auto GpgUID::GetName() const -> std::string { return uid_ref_->name; } +auto GpgUID::GetName() const -> QString { return uid_ref_->name; } -auto GpgUID::GetEmail() const -> std::string { return uid_ref_->email; } +auto GpgUID::GetEmail() const -> QString { return uid_ref_->email; } -auto GpgUID::GetComment() const -> std::string { return uid_ref_->comment; } +auto GpgUID::GetComment() const -> QString { return uid_ref_->comment; } -auto GpgUID::GetUID() const -> std::string { return uid_ref_->uid; } +auto GpgUID::GetUID() const -> QString { return uid_ref_->uid; } auto GpgUID::GetRevoked() const -> bool { return uid_ref_->revoked; } diff --git a/src/core/model/GpgUID.h b/src/core/model/GpgUID.h index b8ed8d14..14b4db3f 100644 --- a/src/core/model/GpgUID.h +++ b/src/core/model/GpgUID.h @@ -41,30 +41,30 @@ class GPGFRONTEND_CORE_EXPORT GpgUID { /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetName() const -> std::string; + [[nodiscard]] auto GetName() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetEmail() const -> std::string; + [[nodiscard]] auto GetEmail() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetComment() const -> std::string; + [[nodiscard]] auto GetComment() const -> QString; /** * @brief * - * @return std::string + * @return QString */ - [[nodiscard]] auto GetUID() const -> std::string; + [[nodiscard]] auto GetUID() const -> QString; /** * @brief diff --git a/src/core/module/Event.cpp b/src/core/module/Event.cpp index b2a4417a..7707262f 100644 --- a/src/core/module/Event.cpp +++ b/src/core/module/Event.cpp @@ -34,7 +34,7 @@ namespace GpgFrontend::Module { class Event::Impl { public: - Impl(std::string event_id, std::initializer_list<ParameterInitializer> params, + Impl(QString event_id, std::initializer_list<ParameterInitializer> params, EventCallback callback) : event_identifier_(std::move(event_id)), callback_(std::move(callback)), @@ -45,8 +45,7 @@ class Event::Impl { GF_CORE_LOG_DEBUG("create event {}", event_identifier_); } - auto operator[](const std::string& key) const - -> std::optional<ParameterValue> { + auto operator[](const QString& key) const -> std::optional<ParameterValue> { auto it_data = data_.find(key); if (it_data != data_.end()) { return it_data->second; @@ -66,11 +65,11 @@ class Event::Impl { return this->event_identifier_ < other.p_->event_identifier_; } - explicit operator std::string() const { return event_identifier_; } + explicit operator QString() const { return event_identifier_; } auto GetIdentifier() -> EventIdentifier { return event_identifier_; } - void AddParameter(const std::string& key, const ParameterValue& value) { + void AddParameter(const QString& key, const ParameterValue& value) { data_[key] = value; } @@ -100,12 +99,12 @@ class Event::Impl { private: EventIdentifier event_identifier_; - std::map<std::string, ParameterValue> data_; + std::map<QString, ParameterValue> data_; EventCallback callback_; QThread* callback_thread_ = nullptr; ///< }; -Event::Event(const std::string& event_id, +Event::Event(const QString& event_id, std::initializer_list<ParameterInitializer> params, EventCallback callback) : p_(SecureCreateUniqueObject<Impl>(event_id, params, @@ -125,15 +124,13 @@ auto Event::Event::operator<(const Event& other) const -> bool { return this->p_ < other.p_; } -Event::Event::operator std::string() const { - return static_cast<std::string>(*p_); -} +Event::Event::operator QString() const { return static_cast<QString>(*p_); } auto Event::Event::GetIdentifier() -> EventIdentifier { return p_->GetIdentifier(); } -void Event::AddParameter(const std::string& key, const ParameterValue& value) { +void Event::AddParameter(const QString& key, const ParameterValue& value) { p_->AddParameter(key, value); } diff --git a/src/core/module/Event.h b/src/core/module/Event.h index 774a72d1..92268216 100644 --- a/src/core/module/Event.h +++ b/src/core/module/Event.h @@ -40,29 +40,28 @@ namespace GpgFrontend::Module { class Event; using EventRefrernce = std::shared_ptr<Event>; -using EventIdentifier = std::string; +using EventIdentifier = QString; using Evnets = std::vector<Event>; class GPGFRONTEND_CORE_EXPORT Event { public: using ParameterValue = std::any; - using EventIdentifier = std::string; - using ListenerIdentifier = std::string; + using EventIdentifier = QString; + using ListenerIdentifier = QString; using EventCallback = std::function<void(EventIdentifier, ListenerIdentifier, DataObjectPtr)>; struct ParameterInitializer { - std::string key; + QString key; ParameterValue value; }; - explicit Event(const std::string&, + explicit Event(const QString&, std::initializer_list<ParameterInitializer> = {}, EventCallback = nullptr); ~Event(); - auto operator[](const std::string& key) const - -> std::optional<ParameterValue>; + auto operator[](const QString& key) const -> std::optional<ParameterValue>; auto operator==(const Event& other) const -> bool; @@ -72,11 +71,11 @@ class GPGFRONTEND_CORE_EXPORT Event { auto operator<=(const Event& other) const -> bool; - explicit operator std::string() const; + explicit operator QString() const; auto GetIdentifier() -> EventIdentifier; - void AddParameter(const std::string& key, const ParameterValue& value); + void AddParameter(const QString& key, const ParameterValue& value); void ExecuteCallback(ListenerIdentifier, DataObjectPtr); diff --git a/src/core/module/GlobalModuleContext.cpp b/src/core/module/GlobalModuleContext.cpp index a86879ab..cac3dfbb 100644 --- a/src/core/module/GlobalModuleContext.cpp +++ b/src/core/module/GlobalModuleContext.cpp @@ -29,7 +29,6 @@ #include "GlobalModuleContext.h" #include <boost/date_time.hpp> -#include <boost/format.hpp> #include <boost/random.hpp> #include <set> #include <unordered_map> @@ -269,12 +268,11 @@ class GlobalModuleContext::Impl { Thread::TaskRunnerGetter::GetInstance() .GetTaskRunner(Thread::TaskRunnerGetter::kTaskRunnerType_Module) - ->PostTask( - new Thread::Task(exec_runnerable, - (boost::format("event/%1%/module/exec/%2%") % - event_id % listener_module_id) - .str(), - nullptr, exec_callback)); + ->PostTask(new Thread::Task(exec_runnerable, + QString("event/%1/module/exec/%2") + .arg(event_id) + .arg(listener_module_id), + nullptr, exec_callback)); } // Return true to indicate successful execution of all modules diff --git a/src/core/module/GlobalModuleContext.h b/src/core/module/GlobalModuleContext.h index 48c0b7ee..1c971bb5 100644 --- a/src/core/module/GlobalModuleContext.h +++ b/src/core/module/GlobalModuleContext.h @@ -42,7 +42,7 @@ class GlobalRegisterTable; class Module; class ModuleManager; -using ModuleIdentifier = std::string; +using ModuleIdentifier = QString; using ModulePtr = std::shared_ptr<Module>; using ModuleRawPtr = Module*; diff --git a/src/core/module/GlobalRegisterTable.cpp b/src/core/module/GlobalRegisterTable.cpp index b9fa3a1e..de058091 100644 --- a/src/core/module/GlobalRegisterTable.cpp +++ b/src/core/module/GlobalRegisterTable.cpp @@ -45,8 +45,7 @@ class GlobalRegisterTable::Impl { public: struct RTNode { std::optional<std::any> value = std::nullopt; - std::unordered_map<std::string, SecureUniquePtr<RTNode>> - children; + std::unordered_map<QString, SecureUniquePtr<RTNode>> children; int version = 0; const std::type_info* type = nullptr; }; @@ -54,9 +53,7 @@ class GlobalRegisterTable::Impl { explicit Impl(GlobalRegisterTable* parent) : parent_(parent) {} auto PublishKV(const Namespace& n, const Key& k, std::any v) -> bool { - std::istringstream iss(k); - std::string segment; - + QStringList const segments = k.split('.'); int version = 0; { @@ -66,7 +63,7 @@ class GlobalRegisterTable::Impl { .first->second; RTNode* current = root_rt_node.get(); - while (std::getline(iss, segment, '.')) { + for (const QString& segment : segments) { current = current->children .emplace(segment, SecureCreateUniqueObject<RTNode>()) .first->second.get(); @@ -74,7 +71,7 @@ class GlobalRegisterTable::Impl { current->value = v; current->type = &v.type(); - current->version++; + version = ++current->version; } emit parent_->SignalPublish(n, k, version, v); @@ -82,17 +79,16 @@ class GlobalRegisterTable::Impl { } auto LookupKV(const Namespace& n, const Key& k) -> std::optional<std::any> { - std::istringstream iss(k); - std::string segment; + QStringList const segments = k.split('.'); std::optional<std::any> rtn = std::nullopt; { - std::shared_lock lock(lock_); + std::shared_lock const lock(lock_); auto it = global_register_table_.find(n); if (it == global_register_table_.end()) return std::nullopt; RTNode* current = it->second.get(); - while (std::getline(iss, segment, '.')) { + for (const QString& segment : segments) { auto it = current->children.find(segment); if (it == current->children.end()) return std::nullopt; current = it->second.get(); @@ -103,8 +99,7 @@ class GlobalRegisterTable::Impl { } auto ListChildKeys(const Namespace& n, const Key& k) -> std::vector<Key> { - std::istringstream iss(k); - std::string segment; + QStringList const segments = k.split('.'); std::vector<Key> rtn; { @@ -113,7 +108,7 @@ class GlobalRegisterTable::Impl { if (it == global_register_table_.end()) return {}; RTNode* current = it->second.get(); - while (std::getline(iss, segment, '.')) { + for (const QString& segment : segments) { auto it = current->children.find(segment); if (it == current->children.end()) return {}; current = it->second.get(); diff --git a/src/core/module/GlobalRegisterTable.h b/src/core/module/GlobalRegisterTable.h index c4685337..db68c888 100644 --- a/src/core/module/GlobalRegisterTable.h +++ b/src/core/module/GlobalRegisterTable.h @@ -36,8 +36,8 @@ namespace GpgFrontend::Module { -using Namespace = std::string; -using Key = std::string; +using Namespace = QString; +using Key = QString; using LPCallback = std::function<void(Namespace, Key, int, std::any)>; class GlobalRegisterTable : public QObject { diff --git a/src/core/module/Module.cpp b/src/core/module/Module.cpp index e62d0ee7..241b448e 100644 --- a/src/core/module/Module.cpp +++ b/src/core/module/Module.cpp @@ -28,7 +28,6 @@ #include "Module.h" -#include <boost/format.hpp> #include <utility> #include "core/module/GlobalModuleContext.h" diff --git a/src/core/module/Module.h b/src/core/module/Module.h index fe672698..2742475e 100644 --- a/src/core/module/Module.h +++ b/src/core/module/Module.h @@ -37,9 +37,9 @@ class Module; class GlobalModuleContext; class ModuleManager; -using ModuleIdentifier = std::string; -using ModuleVersion = std::string; -using ModuleMetaData = std::map<std::string, std::string>; +using ModuleIdentifier = QString; +using ModuleVersion = QString; +using ModuleMetaData = std::map<QString, QString>; using ModulePtr = std::shared_ptr<Module>; using TaskRunnerPtr = std::shared_ptr<Thread::TaskRunner>; diff --git a/src/core/module/ModuleManager.cpp b/src/core/module/ModuleManager.cpp index 420bc611..4c1cf098 100644 --- a/src/core/module/ModuleManager.cpp +++ b/src/core/module/ModuleManager.cpp @@ -28,7 +28,6 @@ #include "ModuleManager.h" -#include <boost/format.hpp> #include <memory> #include <utility> @@ -104,8 +103,7 @@ class ModuleManager::Impl { return grt_->ListenPublish(o, n, k, c); } - auto ListRTChildKeys(const std::string& n, const std::string& k) - -> std::vector<Key> { + auto ListRTChildKeys(const QString& n, const QString& k) -> std::vector<Key> { return grt_->ListChildKeys(n, k); } @@ -123,7 +121,7 @@ auto IsModuleAcivate(ModuleIdentifier id) -> bool { return ModuleManager::GetInstance().IsModuleActivated(id); } -auto UpsertRTValue(const std::string& namespace_, const std::string& key, +auto UpsertRTValue(const QString& namespace_, const QString& key, const std::any& value) -> bool { return ModuleManager::GetInstance().UpsertRTValue(namespace_, key, std::any(value)); @@ -134,7 +132,7 @@ auto ListenRTPublishEvent(QObject* o, Namespace n, Key k, LPCallback c) return ModuleManager::GetInstance().ListenRTPublish(o, n, k, c); } -auto ListRTChildKeys(const std::string& namespace_, const std::string& key) +auto ListRTChildKeys(const QString& namespace_, const QString& key) -> std::vector<Key> { return ModuleManager::GetInstance().ListRTChildKeys(namespace_, key); } @@ -176,7 +174,7 @@ auto ModuleManager::ListenRTPublish(QObject* o, Namespace n, Key k, return p_->ListenPublish(o, n, k, c); } -auto ModuleManager::ListRTChildKeys(const std::string& n, const std::string& k) +auto ModuleManager::ListRTChildKeys(const QString& n, const QString& k) -> std::vector<Key> { return p_->ListRTChildKeys(n, k); } diff --git a/src/core/module/ModuleManager.h b/src/core/module/ModuleManager.h index bf00c87c..93b89e95 100644 --- a/src/core/module/ModuleManager.h +++ b/src/core/module/ModuleManager.h @@ -50,12 +50,12 @@ class GlobalModuleContext; class ModuleManager; using EventRefrernce = std::shared_ptr<Event>; -using ModuleIdentifier = std::string; +using ModuleIdentifier = QString; using ModulePtr = std::shared_ptr<Module>; using ModuleMangerPtr = std::shared_ptr<ModuleManager>; using GMCPtr = std::shared_ptr<GlobalModuleContext>; -using Namespace = std::string; -using Key = std::string; +using Namespace = QString; +using Key = QString; using LPCallback = std::function<void(Namespace, Key, int, std::any)>; class GPGFRONTEND_CORE_EXPORT ModuleManager @@ -83,8 +83,7 @@ class GPGFRONTEND_CORE_EXPORT ModuleManager auto ListenRTPublish(QObject*, Namespace, Key, LPCallback) -> bool; - auto ListRTChildKeys(const std::string&, const std::string&) - -> std::vector<Key>; + auto ListRTChildKeys(const QString&, const QString&) -> std::vector<Key>; private: class Impl; @@ -130,8 +129,8 @@ auto GPGFRONTEND_CORE_EXPORT IsModuleAcivate(ModuleIdentifier) -> bool; * @return true * @return false */ -auto GPGFRONTEND_CORE_EXPORT UpsertRTValue(const std::string& namespace_, - const std::string& key, +auto GPGFRONTEND_CORE_EXPORT UpsertRTValue(const QString& namespace_, + const QString& key, const std::any& value) -> bool; /** @@ -150,12 +149,12 @@ auto GPGFRONTEND_CORE_EXPORT ListenRTPublishEvent(QObject*, Namespace, Key, * @param key * @return std::vector<Key> */ -auto GPGFRONTEND_CORE_EXPORT ListRTChildKeys(const std::string& namespace_, - const std::string& key) +auto GPGFRONTEND_CORE_EXPORT ListRTChildKeys(const QString& namespace_, + const QString& key) -> std::vector<Key>; template <typename T> -auto RetrieveRTValueTyped(const std::string& namespace_, const std::string& key) +auto RetrieveRTValueTyped(const QString& namespace_, const QString& key) -> std::optional<T> { auto any_value = ModuleManager::GetInstance().RetrieveRTValue(namespace_, key); @@ -166,9 +165,9 @@ auto RetrieveRTValueTyped(const std::string& namespace_, const std::string& key) } template <typename T> -auto RetrieveRTValueTypedOrDefault(const std::string& namespace_, - const std::string& key, - const T& defaultValue) -> T { +auto RetrieveRTValueTypedOrDefault(const QString& namespace_, + const QString& key, const T& defaultValue) + -> T { auto any_value = ModuleManager::GetInstance().RetrieveRTValue(namespace_, key); if (any_value && any_value->type() == typeid(T)) { diff --git a/src/core/thread/FileReadTask.cpp b/src/core/thread/FileReadTask.cpp index 98dbf718..38a0ab37 100644 --- a/src/core/thread/FileReadTask.cpp +++ b/src/core/thread/FileReadTask.cpp @@ -32,27 +32,18 @@ namespace GpgFrontend::UI { constexpr size_t kBufferSize = 8192; -FileReadTask::FileReadTask(std::string path) : Task("file_read_task") { +FileReadTask::FileReadTask(QString path) : Task("file_read_task") { HoldOnLifeCycle(true); connect(this, &FileReadTask::SignalFileBytesReadNext, this, &FileReadTask::read_bytes); - -#ifdef WINDOWS - std::filesystem::path read_file_path( - QString::fromStdString(path).toStdU16String()); -#else - std::filesystem::path read_file_path( - QString::fromStdString(path).toStdString()); -#endif - read_file_path_ = read_file_path; + read_file_path_ = path; } void FileReadTask::Run() { - if (is_regular_file(read_file_path_)) { - GF_CORE_LOG_DEBUG("read open file: {}", read_file_path_.u8string()); + if (QFileInfo(read_file_path_).isFile()) { + GF_CORE_LOG_DEBUG("read open file: {}", read_file_path_); - target_file_.setFileName( - QString::fromStdString(read_file_path_.u8string())); + target_file_.setFileName(read_file_path_); target_file_.open(QIODevice::ReadOnly); if (!(target_file_.isOpen() && target_file_.isReadable())) { @@ -60,7 +51,7 @@ void FileReadTask::Run() { if (target_file_.isOpen()) target_file_.close(); return; } - GF_CORE_LOG_DEBUG("started reading: {}", read_file_path_.u8string()); + GF_CORE_LOG_DEBUG("started reading: {}", read_file_path_); read_bytes(); } else { emit SignalFileBytesReadEnd(); @@ -82,7 +73,7 @@ void FileReadTask::read_bytes() { } FileReadTask::~FileReadTask() { - GF_CORE_LOG_DEBUG("close file: {}", read_file_path_.u8string()); + GF_CORE_LOG_DEBUG("close file: {}", read_file_path_); if (target_file_.isOpen()) target_file_.close(); } diff --git a/src/core/thread/FileReadTask.h b/src/core/thread/FileReadTask.h index e7eb1370..b7ff964b 100644 --- a/src/core/thread/FileReadTask.h +++ b/src/core/thread/FileReadTask.h @@ -40,7 +40,7 @@ namespace GpgFrontend::UI { class GPGFRONTEND_CORE_EXPORT FileReadTask : public GpgFrontend::Thread::Task { Q_OBJECT public: - explicit FileReadTask(std::string path); + explicit FileReadTask(QString path); virtual ~FileReadTask() override; @@ -52,7 +52,7 @@ class GPGFRONTEND_CORE_EXPORT FileReadTask : public GpgFrontend::Thread::Task { void SignalFileBytesReadNext(); private: - std::filesystem::path read_file_path_; + QString read_file_path_; QFile target_file_; QEventLoop looper; diff --git a/src/core/thread/Task.cpp b/src/core/thread/Task.cpp index 848f9cfc..459fb55a 100644 --- a/src/core/thread/Task.cpp +++ b/src/core/thread/Task.cpp @@ -42,13 +42,13 @@ namespace GpgFrontend::Thread { class Task::Impl { public: - Impl(Task *parent, std::string name) + Impl(Task *parent, QString name) : parent_(parent), uuid_(generate_uuid()), name_(name) { GF_CORE_LOG_TRACE("task {} created", GetFullID()); init(); } - Impl(Task *parent, TaskRunnable runnable, std::string name, + Impl(Task *parent, TaskRunnable runnable, QString name, DataObjectPtr data_object) : parent_(parent), uuid_(generate_uuid()), @@ -62,7 +62,7 @@ class Task::Impl { init(); } - Impl(Task *parent, TaskRunnable runnable, std::string name, + Impl(Task *parent, TaskRunnable runnable, QString name, DataObjectPtr data_object, TaskCallback callback) : parent_(parent), uuid_(generate_uuid()), @@ -82,11 +82,13 @@ class Task::Impl { /** * @brief * - * @return std::string + * @return QString */ - std::string GetFullID() const { return uuid_ + "/" + name_; } + [[nodiscard]] auto GetFullID() const -> QString { + return uuid_ + "/" + name_; + } - std::string GetUUID() const { return uuid_; } + auto GetUUID() const -> QString { return uuid_; } void Run() { GF_CORE_LOG_TRACE("task {} is using default runnable and callback mode", @@ -114,8 +116,8 @@ class Task::Impl { private: Task *const parent_; - const std::string uuid_; - const std::string name_; + const QString uuid_; + const QString name_; TaskRunnable runnable_; ///< TaskCallback callback_; ///< int rtn_ = 0; ///< @@ -163,10 +165,10 @@ class Task::Impl { /** * @brief * - * @return std::string + * @return QString */ - static auto generate_uuid() -> std::string { - return boost::uuids::to_string(boost::uuids::random_generator()()); + static auto generate_uuid() -> QString { + return QUuid::createUuid().toString(); } /** @@ -205,14 +207,18 @@ class Task::Impl { parent_ = this->parent_]() { GF_CORE_LOG_TRACE("calling callback of task {}", parent_->GetFullID()); +#ifdef RELEASE try { +#endif callback(rtn, data_object); +#ifdef RELEASE } catch (...) { GF_CORE_LOG_ERROR( "unknown exception was caught when execute " "callback of task {}", parent_->GetFullID()); } +#endif // raise signal, announcing this task comes to an end GF_CORE_LOG_TRACE( "for task {}, its life comes to an end whether its " @@ -264,12 +270,12 @@ class Task::Impl { } }; -Task::Task(std::string name) : p_(new Impl(this, name)) {} +Task::Task(QString name) : p_(new Impl(this, name)) {} -Task::Task(TaskRunnable runnable, std::string name, DataObjectPtr data_object) +Task::Task(TaskRunnable runnable, QString name, DataObjectPtr data_object) : p_(SecureCreateUniqueObject<Impl>(this, runnable, name, data_object)) {} -Task::Task(TaskRunnable runnable, std::string name, DataObjectPtr data_object, +Task::Task(TaskRunnable runnable, QString name, DataObjectPtr data_object, TaskCallback callback) : p_(SecureCreateUniqueObject<Impl>(this, runnable, name, data_object, callback)) {} @@ -279,11 +285,11 @@ Task::~Task() = default; /** * @brief * - * @return std::string + * @return QString */ -std::string Task::GetFullID() const { return p_->GetFullID(); } +QString Task::GetFullID() const { return p_->GetFullID(); } -std::string Task::GetUUID() const { return p_->GetUUID(); } +QString Task::GetUUID() const { return p_->GetUUID(); } void Task::HoldOnLifeCycle(bool hold_on) { p_->HoldOnLifeCycle(hold_on); } diff --git a/src/core/thread/Task.h b/src/core/thread/Task.h index 8f157917..281c37e6 100644 --- a/src/core/thread/Task.h +++ b/src/core/thread/Task.h @@ -43,19 +43,20 @@ class GPGFRONTEND_CORE_EXPORT Task : public QObject, public QRunnable { using TaskRunnable = std::function<int(DataObjectPtr)>; ///< using TaskCallback = std::function<void(int, DataObjectPtr)>; ///< + using TaskTrigger = std::function<void()>; /** * @brief Construct a new Task object * */ - explicit Task(std::string name); + explicit Task(QString name); /** * @brief Construct a new Task object * * @param callback The callback function to be executed. */ - explicit Task(TaskRunnable runnable, std::string name, + explicit Task(TaskRunnable runnable, QString name, DataObjectPtr data_object = nullptr); /** @@ -63,14 +64,14 @@ class GPGFRONTEND_CORE_EXPORT Task : public QObject, public QRunnable { * * @param runnable */ - explicit Task(TaskRunnable runnable, std::string name, DataObjectPtr data, + explicit Task(TaskRunnable runnable, QString name, DataObjectPtr data, TaskCallback callback); ~Task() override; - [[nodiscard]] auto GetUUID() const -> std::string; + [[nodiscard]] auto GetUUID() const -> QString; - [[nodiscard]] auto GetFullID() const -> std::string; + [[nodiscard]] auto GetFullID() const -> QString; void HoldOnLifeCycle(bool hold_on); diff --git a/src/core/thread/TaskRunner.cpp b/src/core/thread/TaskRunner.cpp index dbd14225..19587e70 100644 --- a/src/core/thread/TaskRunner.cpp +++ b/src/core/thread/TaskRunner.cpp @@ -28,12 +28,6 @@ #include "core/thread/TaskRunner.h" -#include <QtConcurrent> -#include <boost/uuid/uuid.hpp> -#include <boost/uuid/uuid_generators.hpp> -#include <boost/uuid/uuid_io.hpp> -#include <utility> - #include "core/thread/Task.h" namespace GpgFrontend::Thread { @@ -56,7 +50,32 @@ class TaskRunner::Impl : public QThread { task->SafelyRun(); } - void PostTask(const std::string& name, const Task::TaskRunnable& runnerable, + std::tuple<QPointer<Task>, Task::TaskTrigger> RegisterTask( + const QString& name, const Task::TaskRunnable& runnerable, + const Task::TaskCallback& cb, DataObjectPtr params) { + auto raw_task = SecureCreateQSharedObject<Task>(runnerable, name, + std::move(params), cb); + raw_task->setParent(nullptr); + raw_task->moveToThread(this); + + connect(raw_task.get(), &Task::SignalRun, this, [this, raw_task]() { + pending_tasks_[raw_task->GetFullID()] = raw_task; + }); + + connect(raw_task.get(), &Task::SignalTaskEnd, this, [this, raw_task]() { + pending_tasks_.remove(raw_task->GetFullID()); + }); + + GF_CORE_LOG_TRACE("runner starts task: {} at thread: {}", + raw_task->GetFullID(), this->currentThreadId()); + + QPointer<Task> const task = raw_task.get(); + return {nullptr, [task]() { + if (task != nullptr) task->SafelyRun(); + }}; + } + + void PostTask(const QString& name, const Task::TaskRunnable& runnerable, const Task::TaskCallback& cb, DataObjectPtr params) { PostTask(new Task(runnerable, name, std::move(params), cb)); } @@ -89,9 +108,7 @@ class TaskRunner::Impl : public QThread { } private: - static auto generate_uuid() -> std::string { - return boost::uuids::to_string(boost::uuids::random_generator()()); - } + QMap<QString, QSharedPointer<Task>> pending_tasks_; }; TaskRunner::TaskRunner() : p_(SecureCreateUniqueObject<Impl>()) {} @@ -104,8 +121,7 @@ TaskRunner::~TaskRunner() { void TaskRunner::PostTask(Task* task) { p_->PostTask(task); } -void TaskRunner::PostTask(const std::string& name, - const Task::TaskRunnable& runner, +void TaskRunner::PostTask(const QString& name, const Task::TaskRunnable& runner, const Task::TaskCallback& cb, DataObjectPtr params) { p_->PostTask(name, runner, cb, std::move(params)); } @@ -129,4 +145,9 @@ auto TaskRunner::GetThread() -> QThread* { return p_.get(); } auto TaskRunner::IsRunning() -> bool { return p_->isRunning(); } +std::tuple<QPointer<Task>, Task::TaskTrigger> TaskRunner::RegisterTask( + const QString& name, const Task::TaskRunnable& runnable, + const Task::TaskCallback& cb, DataObjectPtr p_pbj) { + return p_->RegisterTask(name, runnable, cb, p_pbj); +} } // namespace GpgFrontend::Thread diff --git a/src/core/thread/TaskRunner.h b/src/core/thread/TaskRunner.h index 26eba61f..91241a06 100644 --- a/src/core/thread/TaskRunner.h +++ b/src/core/thread/TaskRunner.h @@ -47,7 +47,7 @@ class GPGFRONTEND_CORE_EXPORT TaskRunner : public QObject { * @brief Destroy the Task Runner object * */ - virtual ~TaskRunner() override; + ~TaskRunner() override; /** * @brief @@ -91,12 +91,21 @@ class GPGFRONTEND_CORE_EXPORT TaskRunner : public QObject { * @param runner * @param cb */ - void PostTask(const std::string&, const Task::TaskRunnable&, + void PostTask(const QString&, const Task::TaskRunnable&, const Task::TaskCallback&, DataObjectPtr); /** * @brief * + * @return std::tuple<QPointer<Task>, TaskTrigger> + */ + std::tuple<QPointer<Task>, Task::TaskTrigger> RegisterTask( + const QString&, const Task::TaskRunnable&, const Task::TaskCallback&, + DataObjectPtr); + + /** + * @brief + * * @param task */ void PostConcurrentTask(Task* task); diff --git a/src/core/typedef/CoreTypedef.h b/src/core/typedef/CoreTypedef.h index 41ff7b43..51c6d11a 100644 --- a/src/core/typedef/CoreTypedef.h +++ b/src/core/typedef/CoreTypedef.h @@ -33,16 +33,16 @@ namespace GpgFrontend { using GFError = uint32_t; -using ByteArray = std::string; ///< -using ByteArrayPtr = std::shared_ptr<ByteArray>; ///< -using StdBypeArrayPtr = std::shared_ptr<ByteArray>; ///< -using BypeArrayRef = ByteArray&; ///< -using ConstBypeArrayRef = const ByteArray&; ///< -using BypeArrayConstRef = const ByteArray&; ///< -using StringArgsPtr = std::unique_ptr<std::vector<std::string>>; ///< -using StringArgsRef = std::vector<std::string>&; ///< - /// - /// +using ByteArray = QByteArray; ///< +using ByteArrayPtr = std::shared_ptr<ByteArray>; ///< +using StdBypeArrayPtr = std::shared_ptr<ByteArray>; ///< +using BypeArrayRef = ByteArray&; ///< +using ConstBypeArrayRef = const ByteArray&; ///< +using BypeArrayConstRef = const ByteArray&; ///< +using StringArgsPtr = std::unique_ptr<std::vector<QString>>; ///< +using StringArgsRef = std::vector<QString>&; ///< + /// + /// using OperaRunnable = std::function<GFError(DataObjectPtr)>; using OperationCallback = std::function<void(GFError, DataObjectPtr)>; diff --git a/src/core/typedef/GpgTypedef.h b/src/core/typedef/GpgTypedef.h index 7ef02827..cf0887bf 100644 --- a/src/core/typedef/GpgTypedef.h +++ b/src/core/typedef/GpgTypedef.h @@ -41,23 +41,23 @@ class GpgTOFUInfo; using GpgError = gpgme_error_t; ///< gpgme error using GpgErrorCode = gpg_err_code_t; -using GpgErrorDesc = std::pair<std::string, std::string>; +using GpgErrorDesc = std::pair<QString, QString>; -using KeyId = std::string; ///< -using SubkeyId = std::string; ///< -using KeyIdArgsList = std::vector<KeyId>; ///< -using KeyIdArgsListPtr = std::unique_ptr<KeyIdArgsList>; ///< -using UIDArgsList = std::vector<std::string>; ///< -using UIDArgsListPtr = std::unique_ptr<UIDArgsList>; ///< -using SignIdArgsList = std::vector<std::pair<std::string, std::string>>; ///< -using SignIdArgsListPtr = std::unique_ptr<SignIdArgsList>; ///< -using KeyFprArgsListPtr = std::unique_ptr<std::vector<std::string>>; ///< -using KeyArgsList = std::vector<GpgKey>; ///< -using KeyListPtr = std::shared_ptr<KeyArgsList>; ///< -using GpgKeyLinkList = std::list<GpgKey>; ///< -using KeyLinkListPtr = std::unique_ptr<GpgKeyLinkList>; ///< -using KeyPtr = std::unique_ptr<GpgKey>; ///< -using KeyPtrArgsList = const std::initializer_list<KeyPtr>; ///< +using KeyId = QString; ///< +using SubkeyId = QString; ///< +using KeyIdArgsList = std::vector<KeyId>; ///< +using KeyIdArgsListPtr = std::unique_ptr<KeyIdArgsList>; ///< +using UIDArgsList = std::vector<QString>; ///< +using UIDArgsListPtr = std::unique_ptr<UIDArgsList>; ///< +using SignIdArgsList = std::vector<std::pair<QString, QString>>; ///< +using SignIdArgsListPtr = std::unique_ptr<SignIdArgsList>; ///< +using KeyFprArgsListPtr = std::unique_ptr<std::vector<QString>>; ///< +using KeyArgsList = std::vector<GpgKey>; ///< +using KeyListPtr = std::shared_ptr<KeyArgsList>; ///< +using GpgKeyLinkList = std::list<GpgKey>; ///< +using KeyLinkListPtr = std::unique_ptr<GpgKeyLinkList>; ///< +using KeyPtr = std::unique_ptr<GpgKey>; ///< +using KeyPtrArgsList = const std::initializer_list<KeyPtr>; ///< using GpgSignMode = gpgme_sig_mode_t; diff --git a/src/core/utils/AsyncUtils.cpp b/src/core/utils/AsyncUtils.cpp index c22ffd6d..f5289b19 100644 --- a/src/core/utils/AsyncUtils.cpp +++ b/src/core/utils/AsyncUtils.cpp @@ -36,9 +36,9 @@ namespace GpgFrontend { -void RunGpgOperaAsync(GpgOperaRunnable runnable, GpgOperationCallback callback, - const std::string& operation, - const std::string& minial_version) { +auto RunGpgOperaAsync(GpgOperaRunnable runnable, GpgOperationCallback callback, + const QString& operation, const QString& minial_version) + -> std::tuple<QPointer<Thread::Task>, Thread::Task::TaskTrigger> { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( "core", "gpgme.ctx.gnupg_version", minial_version); GF_CORE_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); @@ -46,12 +46,12 @@ void RunGpgOperaAsync(GpgOperaRunnable runnable, GpgOperationCallback callback, if (CompareSoftwareVersion(gnupg_version, "2.0.15") < 0) { GF_CORE_LOG_ERROR("operator not support"); callback(GPG_ERR_NOT_SUPPORTED, TransferParams()); - return; + return {nullptr, {}}; } - Thread::TaskRunnerGetter::GetInstance() + return Thread::TaskRunnerGetter::GetInstance() .GetTaskRunner(Thread::TaskRunnerGetter::kTaskRunnerType_GPG) - ->PostTask( + ->RegisterTask( operation, [=](const DataObjectPtr& data_object) -> int { auto custom_data_object = TransferParams(); @@ -67,11 +67,12 @@ void RunGpgOperaAsync(GpgOperaRunnable runnable, GpgOperationCallback callback, TransferParams()); } -void RunIOOperaAsync(OperaRunnable runnable, OperationCallback callback, - const std::string& operation) { - Thread::TaskRunnerGetter::GetInstance() +auto RunIOOperaAsync(OperaRunnable runnable, OperationCallback callback, + const QString& operation) + -> std::tuple<QPointer<Thread::Task>, Thread::Task::TaskTrigger> { + return Thread::TaskRunnerGetter::GetInstance() .GetTaskRunner(Thread::TaskRunnerGetter::kTaskRunnerType_IO) - ->PostTask( + ->RegisterTask( operation, [=](const DataObjectPtr& data_object) -> int { auto custom_data_object = TransferParams(); diff --git a/src/core/utils/AsyncUtils.h b/src/core/utils/AsyncUtils.h index 6d79d9c1..4ca94628 100644 --- a/src/core/utils/AsyncUtils.h +++ b/src/core/utils/AsyncUtils.h @@ -29,6 +29,7 @@ #pragma once #include "core/GpgFrontendCore.h" +#include "core/thread/Task.h" #include "core/typedef/CoreTypedef.h" #include "core/typedef/GpgTypedef.h" @@ -42,9 +43,11 @@ namespace GpgFrontend { * @param operation * @param minial_version */ -void GPGFRONTEND_CORE_EXPORT RunGpgOperaAsync( - GpgOperaRunnable runnable, GpgOperationCallback callback, - const std::string& operation, const std::string& minial_version); +auto GPGFRONTEND_CORE_EXPORT RunGpgOperaAsync(GpgOperaRunnable runnable, + GpgOperationCallback callback, + const QString& operation, + const QString& minial_version) + -> std::tuple<QPointer<Thread::Task>, Thread::Task::TaskTrigger>; /** * @brief @@ -53,7 +56,8 @@ void GPGFRONTEND_CORE_EXPORT RunGpgOperaAsync( * @param callback * @param operation */ -void GPGFRONTEND_CORE_EXPORT RunIOOperaAsync(OperaRunnable runnable, +auto GPGFRONTEND_CORE_EXPORT RunIOOperaAsync(OperaRunnable runnable, OperationCallback callback, - const std::string& operation); + const QString& operation) + -> std::tuple<QPointer<Thread::Task>, Thread::Task::TaskTrigger>; } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/CacheUtils.cpp b/src/core/utils/CacheUtils.cpp index 32c7ac66..575634ae 100644 --- a/src/core/utils/CacheUtils.cpp +++ b/src/core/utils/CacheUtils.cpp @@ -32,18 +32,18 @@ namespace GpgFrontend { -void SetTempCacheValue(const std::string& key, const std::string& value) { - nlohmann::json cache_json = value; +void SetTempCacheValue(const QString& key, const QString& value) { + nlohmann::json cache_json = value.toStdString(); CacheManager::GetInstance().SaveCache(key, cache_json); } -auto GetTempCacheValue(const std::string& key) -> std::string { +auto GetTempCacheValue(const QString& key) -> QString { nlohmann::json cache_json = ""; cache_json = CacheManager::GetInstance().LoadCache(key, cache_json); - return cache_json.template get<std::string>(); + return QString::fromStdString(cache_json.template get<std::string>()); } -void ResetTempCacheValue(const std::string& key) { +void ResetTempCacheValue(const QString& key) { CacheManager::GetInstance().ResetCache(key); } diff --git a/src/core/utils/CacheUtils.h b/src/core/utils/CacheUtils.h index 018618e8..67a41335 100644 --- a/src/core/utils/CacheUtils.h +++ b/src/core/utils/CacheUtils.h @@ -34,23 +34,22 @@ namespace GpgFrontend { * @brief set a temp cache under a certain key * */ -void GPGFRONTEND_CORE_EXPORT SetTempCacheValue(const std::string &, - const std::string &); +void GPGFRONTEND_CORE_EXPORT SetTempCacheValue(const QString &, + const QString &); /** * @brief after get the temp cache, its value will be imediately ease in * storage * - * @return std::string + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT GetTempCacheValue(const std::string &) - -> std::string; +auto GPGFRONTEND_CORE_EXPORT GetTempCacheValue(const QString &) -> QString; /** * @brief imediately ease temp cache in storage * - * @return std::string + * @return QString */ -void GPGFRONTEND_CORE_EXPORT ResetTempCacheValue(const std::string &); +void GPGFRONTEND_CORE_EXPORT ResetTempCacheValue(const QString &); } // namespace GpgFrontend diff --git a/src/core/utils/CommonUtils.cpp b/src/core/utils/CommonUtils.cpp index 0eb4933e..0e6eaf64 100644 --- a/src/core/utils/CommonUtils.cpp +++ b/src/core/utils/CommonUtils.cpp @@ -33,44 +33,34 @@ namespace GpgFrontend { -auto BeautifyFingerprint(BypeArrayConstRef fingerprint) -> std::string { +auto BeautifyFingerprint(QString fingerprint) -> QString { auto len = fingerprint.size(); - std::stringstream out; + QTextStream out; decltype(len) count = 0; while (count < len) { if ((count != 0U) && !(count % 5)) out << " "; out << fingerprint[count]; count++; } - return out.str(); + return out.readAll(); } -auto CompareSoftwareVersion(const std::string& a, const std::string& b) -> int { - auto remove_prefix = [](const std::string& version) { - return version.front() == 'v' ? version.substr(1) : version; +auto CompareSoftwareVersion(const QString& a, const QString& b) -> int { + auto remove_prefix = [](const QString& version) { + return version.startsWith('v') ? version.mid(1) : version; }; - std::string real_version_a = remove_prefix(a); - std::string real_version_b = remove_prefix(b); + auto real_version_a = remove_prefix(a); + auto real_version_b = remove_prefix(b); - std::vector<std::string> split_a; - std::vector<std::string> split_b; - boost::split(split_a, real_version_a, boost::is_any_of(".")); - boost::split(split_b, real_version_b, boost::is_any_of(".")); + QStringList split_a = real_version_a.split('.'); + QStringList split_b = real_version_b.split('.'); const auto min_depth = std::min(split_a.size(), split_b.size()); - for (auto i = 0U; i < min_depth; ++i) { - int num_a = 0; - int num_b = 0; - - try { - num_a = boost::lexical_cast<int>(split_a[i]); - num_b = boost::lexical_cast<int>(split_b[i]); - } catch (boost::bad_lexical_cast&) { - // Handle exception if needed - return 0; - } + for (int i = 0; i < min_depth; ++i) { + int const num_a = split_a[i].toInt(); + int const num_b = split_b[i].toInt(); if (num_a != num_b) { return (num_a > num_b) ? 1 : -1; diff --git a/src/core/utils/CommonUtils.h b/src/core/utils/CommonUtils.h index 0f8b9454..a45c6056 100644 --- a/src/core/utils/CommonUtils.h +++ b/src/core/utils/CommonUtils.h @@ -36,13 +36,19 @@ namespace GpgFrontend { * @brief * * @param fingerprint - * @return std::string + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT BeautifyFingerprint(BypeArrayConstRef fingerprint) - -> std::string; +auto GPGFRONTEND_CORE_EXPORT BeautifyFingerprint(QString fingerprint) + -> QString; -auto GPGFRONTEND_CORE_EXPORT CompareSoftwareVersion(const std::string& a, - const std::string& b) - -> int; +/** + * @brief + * + * @param a + * @param b + * @return int + */ +auto GPGFRONTEND_CORE_EXPORT CompareSoftwareVersion(const QString& a, + const QString& b) -> int; } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/FilesystemUtils.cpp b/src/core/utils/FilesystemUtils.cpp index 84c8caf4..0d878759 100644 --- a/src/core/utils/FilesystemUtils.cpp +++ b/src/core/utils/FilesystemUtils.cpp @@ -30,26 +30,26 @@ namespace GpgFrontend { -auto GetOnlyFileNameWithPath(const std::string &path) -> std::string { +auto GetOnlyFileNameWithPath(const QString &path) -> QString { // Create a path object from given string - std::filesystem::path path_obj(path); + std::filesystem::path path_obj(path.toStdString()); // Check if file name in the path object has extension if (path_obj.has_filename()) { // Fetch the extension from path object and return - return (path_obj.parent_path() / path_obj.stem()).u8string(); + return (path_obj.parent_path() / path_obj.stem()).c_str(); } // In case of no extension return empty string return {}; } -auto GetFileExtension(const std::string &path) -> std::string { +auto GetFileExtension(const QString &path) -> QString { // Create a path object from given string - std::filesystem::path path_obj(path); + std::filesystem::path path_obj(path.toStdString()); // Check if file name in the path object has extension if (path_obj.has_extension()) { // Fetch the extension from path object and return - return path_obj.extension().u8string(); + return path_obj.extension().c_str(); } // In case of no extension return empty string return {}; @@ -60,10 +60,10 @@ auto GetFileExtension(const std::string &path) -> std::string { * */ auto GetFileSizeByPath(const std::filesystem::path &path, - const std::string &filename_pattern) -> int64_t { + const QString &filename_pattern) -> int64_t { auto dir = QDir(QString::fromStdString(path.u8string())); - QFileInfoList file_list = dir.entryInfoList( - QStringList() << QString::fromStdString(filename_pattern), QDir::Files); + QFileInfoList const file_list = + dir.entryInfoList(QStringList() << filename_pattern, QDir::Files); qint64 total_size = 0; for (const QFileInfo &file_info : file_list) { @@ -76,7 +76,7 @@ auto GetFileSizeByPath(const std::filesystem::path &path, * @brief * */ -auto GetHumanFriendlyFileSize(int64_t size) -> std::string { +auto GetHumanFriendlyFileSize(int64_t size) -> QString { auto num = static_cast<double>(size); QStringList list; list << "KB" @@ -91,7 +91,7 @@ auto GetHumanFriendlyFileSize(int64_t size) -> std::string { unit = i.next(); num /= 1024.0; } - return (QString().setNum(num, 'f', 2) + " " + unit).toStdString(); + return (QString().setNum(num, 'f', 2) + " " + unit); } /** @@ -99,11 +99,11 @@ auto GetHumanFriendlyFileSize(int64_t size) -> std::string { * */ void DeleteAllFilesByPattern(const std::filesystem::path &path, - const std::string &filename_pattern) { + const QString &filename_pattern) { auto dir = QDir(QString::fromStdString(path.u8string())); - QStringList log_files = dir.entryList( - QStringList() << QString::fromStdString(filename_pattern), QDir::Files); + QStringList const log_files = + dir.entryList(QStringList() << filename_pattern, QDir::Files); for (const auto &file : log_files) { QFile::remove(dir.absoluteFilePath(file)); diff --git a/src/core/utils/FilesystemUtils.h b/src/core/utils/FilesystemUtils.h index e38078a5..addd37ac 100644 --- a/src/core/utils/FilesystemUtils.h +++ b/src/core/utils/FilesystemUtils.h @@ -34,19 +34,18 @@ namespace GpgFrontend { * @brief Get the file extension object * * @param path - * @return std::string + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT GetFileExtension(const std::string& path) - -> std::string; +auto GPGFRONTEND_CORE_EXPORT GetFileExtension(const QString& path) -> QString; /** * @brief Get the only file name with path object * * @param path - * @return std::string + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT GetOnlyFileNameWithPath(const std::string& path) - -> std::string; +auto GPGFRONTEND_CORE_EXPORT GetOnlyFileNameWithPath(const QString& path) + -> QString; /** * @brief Get the File Size By Path object @@ -56,17 +55,16 @@ auto GPGFRONTEND_CORE_EXPORT GetOnlyFileNameWithPath(const std::string& path) * @return int64_t */ auto GPGFRONTEND_CORE_EXPORT GetFileSizeByPath( - const std::filesystem::path& path, const std::string& filename_pattern) + const std::filesystem::path& path, const QString& filename_pattern) -> int64_t; /** * @brief Get the Human Readable File Size object * * @param size - * @return std::string + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT GetHumanFriendlyFileSize(int64_t size) - -> std::string; +auto GPGFRONTEND_CORE_EXPORT GetHumanFriendlyFileSize(int64_t size) -> QString; /** * @brief @@ -75,6 +73,6 @@ auto GPGFRONTEND_CORE_EXPORT GetHumanFriendlyFileSize(int64_t size) * @param filename_pattern */ void GPGFRONTEND_CORE_EXPORT DeleteAllFilesByPattern( - const std::filesystem::path& path, const std::string& filename_pattern); + const std::filesystem::path& path, const QString& filename_pattern); } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/GpgUtils.cpp b/src/core/utils/GpgUtils.cpp index d6dd6e04..7ee78a31 100644 --- a/src/core/utils/GpgUtils.cpp +++ b/src/core/utils/GpgUtils.cpp @@ -32,26 +32,9 @@ namespace GpgFrontend { -inline void Ltrim(std::string& s) { - s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { - return !std::isspace(ch); - })); -} - -inline void Rtrim(std::string& s) { - s.erase(std::find_if(s.rbegin(), s.rend(), - [](unsigned char ch) { return !std::isspace(ch); }) - .base(), - s.end()); -} +inline auto Trim(QString& s) -> QString { return s.trimmed(); } -inline auto Trim(std::string& s) -> std::string { - Ltrim(s); - Rtrim(s); - return s; -} - -auto GetGpgmeErrorString(size_t buffer_size, gpgme_error_t err) -> std::string { +auto GetGpgmeErrorString(size_t buffer_size, gpgme_error_t err) -> QString { std::vector<char> buffer(buffer_size); gpgme_error_t const ret = gpgme_strerror_r(err, buffer.data(), buffer.size()); @@ -62,7 +45,7 @@ auto GetGpgmeErrorString(size_t buffer_size, gpgme_error_t err) -> std::string { return {buffer.data()}; } -auto GetGpgmeErrorString(gpgme_error_t err) -> std::string { +auto GetGpgmeErrorString(gpgme_error_t err) -> QString { return GetGpgmeErrorString(64, err); } @@ -96,7 +79,7 @@ auto DescribeGpgErrCode(GpgError err) -> GpgErrorDesc { return {gpgme_strsource(err), GetGpgmeErrorString(err)}; } -auto CheckGpgError(GpgError err, const std::string& /*comment*/) -> GpgError { +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)); @@ -104,7 +87,7 @@ auto CheckGpgError(GpgError err, const std::string& /*comment*/) -> GpgError { return err; } -auto TextIsSigned(BypeArrayRef text) -> int { +auto TextIsSigned(QString text) -> int { using boost::algorithm::ends_with; using boost::algorithm::starts_with; @@ -113,23 +96,23 @@ auto TextIsSigned(BypeArrayRef text) -> int { ends_with(trim_text, PGP_SIGNED_END)) { return 2; } - if (text.find(PGP_SIGNED_BEGIN) != std::string::npos && - text.find(PGP_SIGNED_END) != std::string::npos) { + if (text.contains(PGP_SIGNED_BEGIN) && text.contains(PGP_SIGNED_END)) { return 1; } return 0; } -auto SetExtensionOfOutputFile(std::filesystem::path path, GpgOperation opera, - bool ascii) -> std::filesystem::path { - std::string extension; +auto SetExtensionOfOutputFile(const QString& path, GpgOperation opera, + bool ascii) -> QString { + QString new_extension; + QString current_extension = QFileInfo(path).suffix(); if (ascii) { switch (opera) { case kENCRYPT: case kSIGN: case kENCRYPT_SIGN: - extension = path.extension().string() + ".asc"; + new_extension = current_extension + ".asc"; break; default: break; @@ -138,29 +121,34 @@ auto SetExtensionOfOutputFile(std::filesystem::path path, GpgOperation opera, switch (opera) { case kENCRYPT: case kENCRYPT_SIGN: - extension = path.extension().string() + ".gpg"; + new_extension = current_extension + ".gpg"; break; case kSIGN: - extension = path.extension().string() + ".sig"; + new_extension = current_extension + ".sig"; break; default: break; } } - return path.replace_extension(extension); + + if (!new_extension.isEmpty()) { + return QFileInfo(path).path() + "/" + QFileInfo(path).completeBaseName() + + "." + new_extension; + } + + return path; } -auto SetExtensionOfOutputFileForArchive(std::filesystem::path path, - GpgOperation opera, bool ascii) - -> std::filesystem::path { - std::string extension; +auto SetExtensionOfOutputFileForArchive(const QString& path, GpgOperation opera, + bool ascii) -> QString { + QString extension; if (ascii) { switch (opera) { case kENCRYPT: case kENCRYPT_SIGN: - extension += ".tar.asc"; - return path.replace_extension(extension); + extension = ".tar.asc"; + break; default: break; } @@ -168,13 +156,22 @@ auto SetExtensionOfOutputFileForArchive(std::filesystem::path path, switch (opera) { case kENCRYPT: case kENCRYPT_SIGN: - extension += ".tar.gpg"; - return path.replace_extension(extension); + extension = ".tar.gpg"; + break; default: break; } } - return path.parent_path(); + + if (!extension.isEmpty()) { + auto last_dot_index = path.lastIndexOf('.'); + if (last_dot_index != -1) { + return path.left(last_dot_index) + extension; + } + return path + extension; + } + + return path; // 如果没有匹配的操作,则返回原始路径 } } // namespace GpgFrontend diff --git a/src/core/utils/GpgUtils.h b/src/core/utils/GpgUtils.h index 2165d614..328de031 100644 --- a/src/core/utils/GpgUtils.h +++ b/src/core/utils/GpgUtils.h @@ -52,8 +52,7 @@ auto GPGFRONTEND_CORE_EXPORT CheckGpgError(GpgError err) -> GpgError; * @return GpgError */ auto GPGFRONTEND_CORE_EXPORT CheckGpgError(GpgError gpgmeError, - const std::string& comment) - -> GpgError; + const QString& comment) -> GpgError; /** * @brief @@ -91,10 +90,9 @@ auto GPGFRONTEND_CORE_EXPORT TextIsSigned(BypeArrayRef text) -> int; * @param ascii * @return std::filesystem::path */ -auto GPGFRONTEND_CORE_EXPORT SetExtensionOfOutputFile(std::filesystem::path, +auto GPGFRONTEND_CORE_EXPORT SetExtensionOfOutputFile(const QString& path, GpgOperation opera, - bool ascii) - -> std::filesystem::path; + bool ascii) -> QString; /** * @brief @@ -105,7 +103,6 @@ auto GPGFRONTEND_CORE_EXPORT SetExtensionOfOutputFile(std::filesystem::path, * @return std::filesystem::path */ auto GPGFRONTEND_CORE_EXPORT SetExtensionOfOutputFileForArchive( - std::filesystem::path path, GpgOperation opera, bool ascii) - -> std::filesystem::path; + const QString& path, GpgOperation opera, bool ascii) -> QString; } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/IOUtils.cpp b/src/core/utils/IOUtils.cpp index 8720e4e9..fc667cb4 100644 --- a/src/core/utils/IOUtils.cpp +++ b/src/core/utils/IOUtils.cpp @@ -40,7 +40,7 @@ namespace GpgFrontend { 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.toStdString()); + GF_CORE_LOG_ERROR("failed to open file: {}", file_name); return false; } data = file.readAll(); @@ -51,7 +51,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: {}", file_name.toStdString()); + GF_CORE_LOG_ERROR("failed to open file: {}", file_name); return false; } file.write(data); @@ -59,147 +59,81 @@ auto WriteFile(const QString& file_name, const QByteArray& data) -> bool { return true; } -auto ReadFileStd(const std::filesystem::path& file_name, std::string& data) - -> bool { +auto ReadFileGFBuffer(const QString& file_name) -> std::tuple<bool, GFBuffer> { QByteArray byte_data; -#ifdef WINDOWS - bool res = ReadFile(QString::fromStdU16String(file_name.u16string()).toUtf8(), - byte_data); -#else - bool res = ReadFile(QString::fromStdString(file_name.u8string()).toUtf8(), - byte_data); -#endif - data = byte_data.toStdString(); - return res; -} - -auto ReadFileGFBuffer(const std::filesystem::path& file_name) - -> std::tuple<bool, GFBuffer> { - QByteArray byte_data; -#ifdef WINDOWS - const bool res = ReadFile( - QString::fromStdU16String(file_name.u16string()).toUtf8(), byte_data); -#else - const bool res = ReadFile( - QString::fromStdString(file_name.u8string()).toUtf8(), byte_data); -#endif + const bool res = ReadFile(file_name, byte_data); return {res, GFBuffer(byte_data)}; } -auto WriteFileStd(const std::filesystem::path& file_name, - const std::string& data) -> bool { - return WriteFile(QString::fromStdString(file_name.u8string()).toUtf8(), - QByteArray::fromStdString(data)); -} - -auto WriteFileGFBuffer(const std::filesystem::path& file_name, GFBuffer data) - -> bool { - return WriteFile( - QString::fromStdString(file_name.u8string()).toUtf8(), - QByteArray::fromRawData(reinterpret_cast<const char*>(data.Data()), - static_cast<qsizetype>(data.Size()))); +auto WriteFileGFBuffer(const QString& file_name, GFBuffer data) -> bool { + return WriteFile(file_name, data.ConvertToQByteArray()); } -auto CalculateHash(const std::filesystem::path& file_path) -> std::string { +auto CalculateHash(const QString& file_path) -> QString { // Returns empty QByteArray() on failure. - QFileInfo const info(QString::fromStdString(file_path.string())); - std::stringstream ss; + QFileInfo const info(file_path); + QString buffer; + QTextStream ss(&buffer); if (info.isFile() && info.isReadable()) { - ss << "[#] " << _("File Hash Information") << std::endl; - ss << " " << _("filename") << _(": ") - << file_path.filename().u8string().c_str() << std::endl; + ss << "[#] " << _("File Hash Information") << Qt::endl; + ss << " " << _("filename") << _(": ") << info.fileName() << Qt::endl; QFile f(info.filePath()); if (f.open(QFile::ReadOnly)) { // read all data auto buffer = f.readAll(); ss << " " << _("file size(bytes)") << _(": ") << buffer.size() - << std::endl; + << Qt::endl; // md5 auto hash_md5 = QCryptographicHash(QCryptographicHash::Md5); hash_md5.addData(buffer); - auto md5 = hash_md5.result().toHex().toStdString(); + auto md5 = hash_md5.result().toHex(); GF_CORE_LOG_DEBUG("md5 {}", md5); ss << " " - << "md5" << _(": ") << md5 << std::endl; + << "md5" << _(": ") << md5 << Qt::endl; // sha1 auto hash_sha1 = QCryptographicHash(QCryptographicHash::Sha1); hash_sha1.addData(buffer); - auto sha1 = hash_sha1.result().toHex().toStdString(); + auto sha1 = hash_sha1.result().toHex(); GF_CORE_LOG_DEBUG("sha1 {}", sha1); ss << " " - << "sha1" << _(": ") << sha1 << std::endl; + << "sha1" << _(": ") << sha1 << Qt::endl; // sha1 auto hash_sha256 = QCryptographicHash(QCryptographicHash::Sha256); hash_sha256.addData(buffer); - auto sha256 = hash_sha256.result().toHex().toStdString(); + auto sha256 = hash_sha256.result().toHex(); GF_CORE_LOG_DEBUG("sha256 {}", sha256); ss << " " - << "sha256" << _(": ") << sha256 << std::endl; + << "sha256" << _(": ") << sha256 << Qt::endl; - ss << std::endl; + ss << Qt::endl; } } else { - ss << "[#] " << _("Error in Calculating File Hash ") << std::endl; + ss << "[#] " << _("Error in Calculating File Hash ") << Qt::endl; } - return ss.str(); -} - -auto ReadAllDataInFile(const std::string& utf8_path) -> std::string { - std::string data; - ReadFileStd(utf8_path, data); - return data; -} - -auto WriteBufferToFile(const std::string& utf8_path, - const std::string& out_buffer) -> bool { - return WriteFileStd(utf8_path, out_buffer); -} - -auto ConvertPathByOS(const std::string& path) -> std::filesystem::path { -#ifdef WINDOWS - return {QString::fromStdString(path).toStdU16String()}; -#else - return {path}; -#endif -} - -auto ConvertPathByOS(const QString& path) -> std::filesystem::path { -#ifdef WINDOWS - return {path.toStdU16String()}; -#else - return {path.toStdString()}; -#endif + return ss.readAll(); } -auto GetTempFilePath() -> std::filesystem::path { - std::filesystem::path const temp_dir = std::filesystem::temp_directory_path(); - boost::uuids::uuid const uuid = boost::uuids::random_generator()(); - std::string const filename = boost::uuids::to_string(uuid) + ".data"; - std::filesystem::path const temp_file = temp_dir / filename; - return temp_dir / filename; +auto GetTempFilePath() -> QString { + QString const temp_dir = QDir::tempPath(); + QString const filename = QUuid::createUuid().toString() + ".data"; + return temp_dir + "/" + filename; } -auto CreateTempFileAndWriteData(const std::string& data) - -> std::filesystem::path { +auto CreateTempFileAndWriteData(const QString& data) -> QString { auto temp_file = GetTempFilePath(); - std::ofstream file_stream(temp_file, std::ios::out | std::ios::trunc); - if (!file_stream.is_open()) { - throw std::runtime_error("Unable to open temporary file."); - } - file_stream << data; - file_stream.close(); - return temp_file.string(); + WriteFile(temp_file, data.toUtf8()); + return temp_file; } -auto TargetFilePreCheck(const std::filesystem::path& path, bool read) - -> std::tuple<bool, std::string> { +auto TargetFilePreCheck(const QString& path, bool read) + -> std::tuple<bool, QString> { QFileInfo const file_info(path); if (read) { @@ -220,11 +154,13 @@ auto TargetFilePreCheck(const std::filesystem::path& path, bool read) return {true, _("Success")}; } -auto GetFullExtension(std::filesystem::path path) -> std::string { - const auto filename = path.filename().string(); - std::string extension(std::find(filename.begin(), filename.end(), '.'), - filename.end()); - return extension; +auto GetFullExtension(const QString& path) -> QString { + QString const filename = QFileInfo(path).fileName(); + + auto const dot_index = filename.indexOf('.'); + if (dot_index == -1) return {}; + + return filename.mid(dot_index); } } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/IOUtils.h b/src/core/utils/IOUtils.h index 40e6923d..42c663c3 100644 --- a/src/core/utils/IOUtils.h +++ b/src/core/utils/IOUtils.h @@ -33,34 +33,13 @@ namespace GpgFrontend { /** - * @brief read file content using std struct - * - * - * @param file_name file name - * @param data data read from file - * @return - */ -auto GPGFRONTEND_CORE_EXPORT ReadFileStd(const std::filesystem::path &file_name, - std::string &data) -> bool; - -/** * @brief * * @param file_name * @return GFBuffer */ -auto GPGFRONTEND_CORE_EXPORT ReadFileGFBuffer( - const std::filesystem::path &file_name) -> std::tuple<bool, GFBuffer>; - -/** - * @brief write file content using std struct - * - * @param file_name file name - * @param data data to write to file - * @return - */ -auto GPGFRONTEND_CORE_EXPORT WriteFileStd( - const std::filesystem::path &file_name, const std::string &data) -> bool; +auto GPGFRONTEND_CORE_EXPORT ReadFileGFBuffer(const QString &file_name) + -> std::tuple<bool, GFBuffer>; /** * @brief @@ -70,8 +49,8 @@ auto GPGFRONTEND_CORE_EXPORT WriteFileStd( * @return true * @return false */ -auto GPGFRONTEND_CORE_EXPORT WriteFileGFBuffer( - const std::filesystem::path &file_name, GFBuffer data) -> bool; +auto GPGFRONTEND_CORE_EXPORT WriteFileGFBuffer(const QString &file_name, + GFBuffer data) -> bool; /** * @brief read file content @@ -100,17 +79,7 @@ auto GPGFRONTEND_CORE_EXPORT WriteFile(const QString &file_name, * @param file_path * @return */ -auto GPGFRONTEND_CORE_EXPORT -CalculateHash(const std::filesystem::path &file_path) -> std::string; - -/** - * @brief - * - * @param path - * @return std::string - */ -auto GPGFRONTEND_CORE_EXPORT ReadAllDataInFile(const std::string &path) - -> std::string; +auto GPGFRONTEND_CORE_EXPORT CalculateHash(const QString &file_path) -> QString; /** * @brief @@ -120,61 +89,42 @@ auto GPGFRONTEND_CORE_EXPORT ReadAllDataInFile(const std::string &path) * @return true * @return false */ -auto GPGFRONTEND_CORE_EXPORT WriteBufferToFile(const std::string &path, - const std::string &out_buffer) +auto GPGFRONTEND_CORE_EXPORT WriteBufferToFile(const QString &path, + const QString &out_buffer) -> bool; /** * @brief * - * @param path - * @return std::filesystem::path - */ -auto GPGFRONTEND_CORE_EXPORT ConvertPathByOS(const std::string &path) - -> std::filesystem::path; - -/** - * @brief - * - * @return std::filesystem::path - */ -auto GPGFRONTEND_CORE_EXPORT ConvertPathByOS(const QString &) - -> std::filesystem::path; - -/** - * @brief - * - * @return std::filesystem::path + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT GetTempFilePath() -> std::filesystem::path; +auto GPGFRONTEND_CORE_EXPORT GetTempFilePath() -> QString; /** * @brief * * @param data - * @return std::filesystem::path + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT CreateTempFileAndWriteData(const std::string &data) - -> std::filesystem::path; +auto GPGFRONTEND_CORE_EXPORT CreateTempFileAndWriteData(const QString &data) + -> QString; /** * @brief * * @param path * @param read - * @return std::tuple<bool, std::string> + * @return std::tuple<bool, QString> */ -auto GPGFRONTEND_CORE_EXPORT -TargetFilePreCheck(const std::filesystem::path &path, bool read) - -> std::tuple<bool, std::string>; +auto GPGFRONTEND_CORE_EXPORT TargetFilePreCheck(const QString &path, bool read) + -> std::tuple<bool, QString>; /** * @brief * * @param path - * @return std::string + * @return QString */ -auto GPGFRONTEND_CORE_EXPORT GetFullExtension(std::filesystem::path path) - -> std::string; +auto GPGFRONTEND_CORE_EXPORT GetFullExtension(QString path) -> QString; } // namespace GpgFrontend diff --git a/src/core/utils/LocalizedUtils.cpp b/src/core/utils/LocalizedUtils.cpp index e1c3d859..b8c91039 100644 --- a/src/core/utils/LocalizedUtils.cpp +++ b/src/core/utils/LocalizedUtils.cpp @@ -32,9 +32,7 @@ namespace GpgFrontend { -auto GetFormatedDateByTimestamp(time_t timestamp) -> std::string { - QDateTime date; - date.setSecsSinceEpoch(timestamp); - return QLocale::system().toString(date).toStdString(); +auto GetFormatedDateByTimestamp(time_t timestamp) -> QString { + return QLocale::system().toString(QDateTime::fromSecsSinceEpoch(timestamp)); } } // namespace GpgFrontend diff --git a/src/core/utils/LocalizedUtils.h b/src/core/utils/LocalizedUtils.h index ff09ac60..d7aaf0c8 100644 --- a/src/core/utils/LocalizedUtils.h +++ b/src/core/utils/LocalizedUtils.h @@ -30,6 +30,6 @@ namespace GpgFrontend { -auto GPGFRONTEND_CORE_EXPORT GetFormatedDateByTimestamp(time_t) -> std::string; +auto GPGFRONTEND_CORE_EXPORT GetFormatedDateByTimestamp(time_t) -> QString; }
\ No newline at end of file diff --git a/src/core/utils/LogUtils.cpp b/src/core/utils/LogUtils.cpp index f95ade9a..fbf0c8d3 100644 --- a/src/core/utils/LogUtils.cpp +++ b/src/core/utils/LogUtils.cpp @@ -40,7 +40,7 @@ auto GetCoreLogger() -> std::shared_ptr<spdlog::logger> { return LoggerManager::GetInstance().GetLogger("core"); } -auto GetLogger(const std::string& id) -> std::shared_ptr<spdlog::logger> { +auto GetLogger(const QString& id) -> std::shared_ptr<spdlog::logger> { return LoggerManager::GetInstance().GetLogger(id); } @@ -48,13 +48,11 @@ void SetDefaultLogLevel(spdlog::level::level_enum level) { return LoggerManager::SetDefaultLogLevel(level); } -void RegisterAsyncLogger(const std::string& id, - spdlog::level::level_enum level) { +void RegisterAsyncLogger(const QString& id, spdlog::level::level_enum level) { LoggerManager::GetInstance().RegisterAsyncLogger(id, level); } -void RegisterSyncLogger(const std::string& id, - spdlog::level::level_enum level) { +void RegisterSyncLogger(const QString& id, spdlog::level::level_enum level) { LoggerManager::GetInstance().RegisterSyncLogger(id, level); } diff --git a/src/core/utils/LogUtils.h b/src/core/utils/LogUtils.h index 0ed618f9..d838e830 100644 --- a/src/core/utils/LogUtils.h +++ b/src/core/utils/LogUtils.h @@ -50,7 +50,7 @@ auto GPGFRONTEND_CORE_EXPORT GetCoreLogger() -> std::shared_ptr<spdlog::logger>; * * @return std::shared_ptr<spdlog::logger> */ -auto GPGFRONTEND_CORE_EXPORT GetLogger(const std::string &) +auto GPGFRONTEND_CORE_EXPORT GetLogger(const QString &) -> std::shared_ptr<spdlog::logger>; /** @@ -65,7 +65,7 @@ void GPGFRONTEND_CORE_EXPORT SetDefaultLogLevel(spdlog::level::level_enum); * * @return auto */ -void GPGFRONTEND_CORE_EXPORT RegisterAsyncLogger(const std::string &, +void GPGFRONTEND_CORE_EXPORT RegisterAsyncLogger(const QString &, spdlog::level::level_enum); /** @@ -73,7 +73,7 @@ void GPGFRONTEND_CORE_EXPORT RegisterAsyncLogger(const std::string &, * * @return auto */ -void GPGFRONTEND_CORE_EXPORT RegisterSyncLogger(const std::string &, +void GPGFRONTEND_CORE_EXPORT RegisterSyncLogger(const QString &, spdlog::level::level_enum); } // namespace GpgFrontend diff --git a/src/core/utils/MemoryUtils.h b/src/core/utils/MemoryUtils.h index 800f2163..76c75fc6 100644 --- a/src/core/utils/MemoryUtils.h +++ b/src/core/utils/MemoryUtils.h @@ -159,4 +159,21 @@ auto SecureCreateSharedObject(Args &&...args) -> std::shared_ptr<T> { } } +template <typename T, typename... Args> +auto SecureCreateQSharedObject(Args &&...args) -> QSharedPointer<T> { + void *mem = SecureMemoryAllocator::Allocate(sizeof(T)); + if (!mem) throw std::bad_alloc(); + + try { + T *obj = new (mem) T(std::forward<Args>(args)...); + return QSharedPointer<T>(obj, [](T *ptr) { + ptr->~T(); + SecureMemoryAllocator::Deallocate(ptr); + }); + } catch (...) { + SecureMemoryAllocator::Deallocate(mem); + throw; + } +} + }; // namespace GpgFrontend
\ No newline at end of file diff --git a/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp b/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp index c257a977..9f9216ac 100644 --- a/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp +++ b/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp @@ -29,7 +29,6 @@ #include "GnuPGInfoGatheringModule.h" #include <boost/algorithm/string.hpp> -#include <boost/format.hpp> #include <boost/format/format_fwd.hpp> #include <nlohmann/json.hpp> #include <string> @@ -42,9 +41,9 @@ namespace GpgFrontend::Module::Integrated::GnuPGInfoGatheringModule { -std::optional<std::string> check_binary_chacksum(std::filesystem::path path) { +auto CheckBinaryChacksum(QString path) -> std::optional<QString> { // check file info and access rights - QFileInfo info(QString::fromStdString(path.u8string())); + QFileInfo info(path); if (!info.exists() || !info.isFile() || !info.isReadable()) { MODULE_LOG_ERROR("get info for file {} error, exists: {}", info.filePath().toStdString(), info.exists()); @@ -54,8 +53,8 @@ std::optional<std::string> check_binary_chacksum(std::filesystem::path path) { // open and read file QFile f(info.filePath()); if (!f.open(QIODevice::ReadOnly)) { - MODULE_LOG_ERROR("open {} to calculate check sum error: {}", - path.u8string(), f.errorString().toStdString()); + MODULE_LOG_ERROR("open {} to calculate check sum error: {}", path, + f.errorString().toStdString()); return {}; } @@ -66,10 +65,7 @@ std::optional<std::string> check_binary_chacksum(std::filesystem::path path) { auto hash_sha = QCryptographicHash(QCryptographicHash::Sha256); // md5 hash_sha.addData(buffer); - auto sha = hash_sha.result().toHex().toStdString(); - MODULE_LOG_DEBUG("checksum for file {} is {}", path.u8string(), sha); - - return sha.substr(0, 6); + return QString(hash_sha.result().toHex()).left(6); } GnuPGInfoGatheringModule::GnuPGInfoGatheringModule() @@ -97,11 +93,11 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { event->GetIdentifier()); const auto gpgme_version = RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.version", std::string{"0.0.0"}); + "core", "gpgme.version", QString{"0.0.0"}); MODULE_LOG_DEBUG("got gpgme version from rt: {}", gpgme_version); const auto gpgconf_path = RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gpgconf_path", std::string{}); + "core", "gpgme.ctx.gpgconf_path", QString{}); MODULE_LOG_DEBUG("got gpgconf path from rt: {}", gpgconf_path); MODULE_LOG_DEBUG("start to load extra info at module gnupginfogathering..."); @@ -110,8 +106,8 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { GpgCommandExecutor::ExecuteSync( {gpgconf_path, {"--list-components"}, - [this, gpgme_version, gpgconf_path]( - int exit_code, const std::string &p_out, const std::string &p_err) { + [this, gpgme_version, gpgconf_path](int exit_code, const QString &p_out, + const QString &p_err) { MODULE_LOG_DEBUG( "gpgconf components exit_code: {} process stdout size: {}", exit_code, p_out.size()); @@ -128,7 +124,7 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { GpgComponentInfo c_i_gpgme; c_i_gpgme.name = "gpgme"; c_i_gpgme.desc = "GPG Made Easy"; - c_i_gpgme.version = gpgme_version; + c_i_gpgme.version = gpgme_version.toStdString(); c_i_gpgme.path = _("Embedded In"); c_i_gpgme.binary_checksum = "/"; @@ -136,47 +132,42 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { c_i_gpgconf.name = "gpgconf"; c_i_gpgconf.desc = "GPG Configure"; c_i_gpgconf.version = "/"; - c_i_gpgconf.path = gpgconf_path; - auto gpgconf_binary_checksum = check_binary_chacksum(gpgconf_path); - c_i_gpgconf.binary_checksum = gpgconf_binary_checksum.has_value() - ? gpgconf_binary_checksum.value() - : "/"; + c_i_gpgconf.path = gpgconf_path.toStdString(); + auto gpgconf_binary_checksum = CheckBinaryChacksum(gpgconf_path); + c_i_gpgconf.binary_checksum = (gpgconf_binary_checksum.has_value() + ? gpgconf_binary_checksum.value() + : QString("/")) + .toStdString(); component_infos.push_back(c_i_gpgme); component_infos.push_back(c_i_gpgconf); nlohmann::json const jsonlized_gpgme_component_info = c_i_gpgme; nlohmann::json const jsonlized_gpgconf_component_info = c_i_gpgconf; - UpsertRTValue( - GetModuleIdentifier(), "gnupg.components.gpgme", - static_cast<std::string>(jsonlized_gpgme_component_info.dump())); - UpsertRTValue( - GetModuleIdentifier(), "gnupg.components.gpgconf", - static_cast<std::string>(jsonlized_gpgme_component_info.dump())); + UpsertRTValue(GetModuleIdentifier(), "gnupg.components.gpgme", + QString::fromStdString(static_cast<std::string>( + jsonlized_gpgme_component_info.dump()))); + UpsertRTValue(GetModuleIdentifier(), "gnupg.components.gpgconf", + QString::fromStdString(static_cast<std::string>( + jsonlized_gpgme_component_info.dump()))); - std::vector<std::string> line_split_list; - boost::split(line_split_list, p_out, boost::is_any_of("\n")); + auto line_split_list = p_out.split("\n"); for (const auto &line : line_split_list) { - std::vector<std::string> info_split_list; - boost::split(info_split_list, line, boost::is_any_of(":")); + auto info_split_list = line.split(":"); if (info_split_list.size() != 3) continue; - auto component_name = info_split_list[0]; - auto component_desc = info_split_list[1]; - auto component_path = info_split_list[2]; - - boost::algorithm::trim(component_name); - boost::algorithm::trim(component_desc); - boost::algorithm::trim(component_path); + auto component_name = info_split_list[0].trimmed(); + auto component_desc = info_split_list[1].trimmed(); + auto component_path = info_split_list[2].trimmed(); #ifdef WINDOWS // replace some special substrings on windows platform - boost::replace_all(component_path, "%3a", ":"); + component_path.replace("%3a", ":"); #endif - auto binary_checksum = check_binary_chacksum(component_path); + auto binary_checksum = CheckBinaryChacksum(component_path); MODULE_LOG_DEBUG( "gnupg component name: {} desc: {} checksum: {} path: {} ", @@ -184,39 +175,41 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { binary_checksum.has_value() ? binary_checksum.value() : "/", component_path); - std::string version = "/"; + QString version = "/"; if (component_name == "gpg") { version = RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gnupg_version", std::string{"2.0.0"}); + "core", "gpgme.ctx.gnupg_version", QString{"2.0.0"}); } if (component_name == "gpg-agent") { UpsertRTValue(GetModuleIdentifier(), "gnupg.gpg_agent_path", - std::string(component_path)); + QString(component_path)); } if (component_name == "dirmngr") { UpsertRTValue(GetModuleIdentifier(), "gnupg.dirmngr_path", - std::string(component_path)); + QString(component_path)); } if (component_name == "keyboxd") { UpsertRTValue(GetModuleIdentifier(), "gnupg.keyboxd_path", - std::string(component_path)); + QString(component_path)); } { GpgComponentInfo c_i; - c_i.name = component_name; - c_i.desc = component_desc; - c_i.version = version; - c_i.path = component_path; + c_i.name = component_name.toStdString(); + c_i.desc = component_desc.toStdString(); + c_i.version = version.toStdString(); + c_i.path = component_path.toStdString(); c_i.binary_checksum = - binary_checksum.has_value() ? binary_checksum.value() : "/"; + (binary_checksum.has_value() ? binary_checksum.value() + : QString("/")) + .toStdString(); nlohmann::json const jsonlized_component_info = c_i; - UpsertRTValue( - GetModuleIdentifier(), - (boost::format("gnupg.components.%1%") % component_name).str(), - static_cast<std::string>(jsonlized_component_info.dump())); + UpsertRTValue(GetModuleIdentifier(), + QString("gnupg.components.%1").arg(component_name), + QString::fromStdString(static_cast<std::string>( + jsonlized_component_info.dump()))); component_infos.push_back(c_i); } @@ -229,8 +222,7 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { exec_contexts.emplace_back(GpgCommandExecutor::ExecuteContext{ gpgconf_path, {"--list-dirs"}, - [this](int exit_code, const std::string &p_out, - const std::string &p_err) { + [this](int exit_code, const QString &p_out, const QString &p_err) { MODULE_LOG_DEBUG( "gpgconf configurations exit_code: {} process stdout size: {}", exit_code, p_out.size()); @@ -243,25 +235,21 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { return; } - std::vector<std::string> line_split_list; - boost::split(line_split_list, p_out, boost::is_any_of("\n")); + auto line_split_list = p_out.split("\n"); for (const auto &line : line_split_list) { - std::vector<std::string> info_split_list; - boost::split(info_split_list, line, boost::is_any_of(":")); + auto info_split_list = line.split(":"); MODULE_LOG_DEBUG("gpgconf info line: {} info size: {}", line, info_split_list.size()); if (info_split_list.size() != 2) continue; - auto configuration_name = info_split_list[0]; - auto configuration_value = info_split_list[1]; - boost::algorithm::trim(configuration_name); - boost::algorithm::trim(configuration_value); + auto configuration_name = info_split_list[0].trimmed(); + auto configuration_value = info_split_list[1].trimmed(); #ifdef WINDOWS // replace some special substrings on windows platform - boost::replace_all(configuration_value, "%3a", ":"); + configuration_value.replace("%3a", ":"); #endif // record gnupg home path @@ -270,10 +258,9 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { configuration_value); } - UpsertRTValue( - GetModuleIdentifier(), - (boost::format("gnupg.dirs.%1%") % configuration_name).str(), - configuration_value); + UpsertRTValue(GetModuleIdentifier(), + QString("gnupg.dirs.%1").arg(configuration_name), + configuration_value); } }, getTaskRunner()}); @@ -285,10 +272,10 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { for (const auto &component : components) { auto component_info_json = RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - (boost::format("gnupg.components.%1%") % component).str(), - std::string{}); + QString("gnupg.components.%1").arg(component), QString{}); - auto jsonlized_component_info = nlohmann::json::parse(component_info_json); + auto jsonlized_component_info = + nlohmann::json::parse(component_info_json.toStdString()); auto component_info = jsonlized_component_info.get<GpgComponentInfo>(); MODULE_LOG_DEBUG("gpgconf check options ready, component: {}", component_info.name); @@ -299,9 +286,9 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { exec_contexts.emplace_back(GpgCommandExecutor::ExecuteContext{ gpgconf_path, - {"--list-options", component_info.name}, - [this, component_info](int exit_code, const std::string &p_out, - const std::string &p_err) { + {"--list-options", component_info.name.c_str()}, + [this, component_info](int exit_code, const QString &p_out, + const QString &p_err) { MODULE_LOG_DEBUG( "gpgconf {} avaliable options exit_code: {} process stdout " "size: {} ", @@ -317,12 +304,10 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { std::vector<GpgOptionsInfo> options_infos; - std::vector<std::string> line_split_list; - boost::split(line_split_list, p_out, boost::is_any_of("\n")); + auto line_split_list = p_out.split("\n"); for (const auto &line : line_split_list) { - std::vector<std::string> info_split_list; - boost::split(info_split_list, line, boost::is_any_of(":")); + auto info_split_list = line.split(":"); MODULE_LOG_DEBUG( "component {} avaliable options line: {} info size: {}", @@ -333,55 +318,36 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { // The format of each line is: // name:flags:level:description:type:alt-type:argname:default:argdef:value - auto option_name = info_split_list[0]; - boost::algorithm::trim(option_name); - - auto option_flags = info_split_list[1]; - boost::algorithm::trim(option_flags); - - auto option_level = info_split_list[2]; - boost::algorithm::trim(option_level); - - auto option_desc = info_split_list[3]; - boost::algorithm::trim(option_desc); - - auto option_type = info_split_list[4]; - boost::algorithm::trim(option_type); - - auto option_alt_type = info_split_list[5]; - boost::algorithm::trim(option_alt_type); - - auto option_argname = info_split_list[6]; - boost::algorithm::trim(option_argname); - - auto option_default = info_split_list[7]; - boost::algorithm::trim(option_default); - - auto option_argdef = info_split_list[8]; - boost::algorithm::trim(option_argdef); - - auto option_value = info_split_list[9]; - boost::algorithm::trim(option_value); + auto option_name = info_split_list[0].trimmed(); + auto option_flags = info_split_list[1].trimmed(); + auto option_level = info_split_list[2].trimmed(); + auto option_desc = info_split_list[3].trimmed(); + auto option_type = info_split_list[4].trimmed(); + auto option_alt_type = info_split_list[5].trimmed(); + auto option_argname = info_split_list[6].trimmed(); + auto option_default = info_split_list[7].trimmed(); + auto option_argdef = info_split_list[8].trimmed(); + auto option_value = info_split_list[9].trimmed(); GpgOptionsInfo info; - info.name = option_name; - info.flags = option_flags; - info.level = option_level; - info.description = option_desc; - info.type = option_type; - info.alt_type = option_alt_type; - info.argname = option_argname; - info.default_value = option_default; - info.argdef = option_argdef; - info.value = option_value; + info.name = option_name.toStdString(); + info.flags = option_flags.toStdString(); + info.level = option_level.toStdString(); + info.description = option_desc.toStdString(); + info.type = option_type.toStdString(); + info.alt_type = option_alt_type.toStdString(); + info.argname = option_argname.toStdString(); + info.default_value = option_default.toStdString(); + info.argdef = option_argdef.toStdString(); + info.value = option_value.toStdString(); nlohmann::json const jsonlized_option_info = info; - UpsertRTValue( - GetModuleIdentifier(), - (boost::format("gnupg.components.%1%.options.%2%") % - component_info.name % option_name) - .str(), - static_cast<std::string>(jsonlized_option_info.dump())); + UpsertRTValue(GetModuleIdentifier(), + QString("gnupg.components.%1%.options.%2%") + .arg(component_info.name.c_str()) + .arg(option_name), + QString::fromStdString(static_cast<std::string>( + jsonlized_option_info.dump()))); options_infos.push_back(info); } }, diff --git a/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h b/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h index 9aaa2005..943832c3 100644 --- a/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h +++ b/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h @@ -37,12 +37,12 @@ namespace GpgFrontend::Module::Integrated::GnuPGInfoGatheringModule { */ class GpgInfo { public: - std::string GnuPGHomePath; ///< value of ---homedir + QString GnuPGHomePath; ///< value of ---homedir - std::map<std::string, std::vector<std::string>> ComponentsInfo; ///< - std::map<std::string, std::vector<std::string>> ConfigurationsInfo; ///< - std::map<std::string, std::vector<std::string>> OptionsInfo; ///< - std::map<std::string, std::vector<std::string>> AvailableOptionsInfo; ///< + std::map<QString, std::vector<QString>> ComponentsInfo; ///< + std::map<QString, std::vector<QString>> ConfigurationsInfo; ///< + std::map<QString, std::vector<QString>> OptionsInfo; ///< + std::map<QString, std::vector<QString>> AvailableOptionsInfo; ///< }; /** diff --git a/src/module/integrated/version_checking_module/SoftwareVersion.h b/src/module/integrated/version_checking_module/SoftwareVersion.h index 513ab1b9..43f718fa 100644 --- a/src/module/integrated/version_checking_module/SoftwareVersion.h +++ b/src/module/integrated/version_checking_module/SoftwareVersion.h @@ -36,16 +36,16 @@ namespace GpgFrontend::Module::Integrated::VersionCheckingModule { * */ struct SoftwareVersion { - std::string latest_version; ///< - std::string current_version; ///< + QString latest_version; ///< + QString current_version; ///< bool latest_prerelease_version_from_remote = false; ///< bool latest_draft_from_remote = false; ///< bool current_version_is_a_prerelease = false; ///< bool current_version_is_drafted = false; ///< bool loading_done = false; ///< bool current_version_publish_in_remote = false; ///< - std::string publish_date; ///< - std::string release_note; ///< + QString publish_date; ///< + QString release_note; ///< /** * @brief @@ -80,6 +80,6 @@ struct SoftwareVersion { [[nodiscard]] bool CurrentVersionReleased() const; private: - static int version_compare(const std::string& a, const std::string& b); + static int version_compare(const QString& a, const QString& b); }; } // namespace GpgFrontend::Module::Integrated::VersionCheckingModule diff --git a/src/module/integrated/version_checking_module/VersionCheckTask.cpp b/src/module/integrated/version_checking_module/VersionCheckTask.cpp index bacce396..edc22cc1 100644 --- a/src/module/integrated/version_checking_module/VersionCheckTask.cpp +++ b/src/module/integrated/version_checking_module/VersionCheckTask.cpp @@ -39,7 +39,7 @@ namespace GpgFrontend::Module::Integrated::VersionCheckingModule { VersionCheckTask::VersionCheckTask() : Task("version_check_task"), network_manager_(new QNetworkAccessManager(this)), - current_version_(std::string("v") + VERSION_MAJOR + "." + VERSION_MINOR + + current_version_(QString("v") + VERSION_MAJOR + "." + VERSION_MINOR + "." + VERSION_PATCH) { HoldOnLifeCycle(true); qRegisterMetaType<SoftwareVersion>("SoftwareVersion"); @@ -50,11 +50,11 @@ void VersionCheckTask::Run() { try { using namespace nlohmann; MODULE_LOG_DEBUG("current version: {}", current_version_); - std::string latest_version_url = + QString latest_version_url = "https://api.github.com/repos/saturneric/gpgfrontend/releases/latest"; QNetworkRequest latest_request; - latest_request.setUrl(QUrl(latest_version_url.c_str())); + latest_request.setUrl(QUrl(latest_version_url)); latest_reply_ = network_manager_->get(latest_request); connect(latest_reply_, &QNetworkReply::finished, this, &VersionCheckTask::slot_parse_latest_version_info); @@ -82,14 +82,15 @@ void VersionCheckTask::slot_parse_latest_version_info() { auto latest_reply_json = nlohmann::json::parse(latest_reply_bytes_.toStdString()); - std::string latest_version = latest_reply_json["tag_name"]; + QString latest_version = + QString::fromStdString(latest_reply_json["tag_name"]); MODULE_LOG_INFO("latest version from Github: {}", latest_version); QRegularExpression re(R"(^[vV](\d+\.)?(\d+\.)?(\*|\d+))"); - auto version_match = re.match(latest_version.c_str()); + auto version_match = re.match(latest_version); if (version_match.hasMatch()) { - latest_version = version_match.captured(0).toStdString(); + latest_version = version_match.captured(0); MODULE_LOG_DEBUG("latest version matched: {}", latest_version); } else { latest_version = current_version_; @@ -98,8 +99,9 @@ void VersionCheckTask::slot_parse_latest_version_info() { bool prerelease = latest_reply_json["prerelease"]; bool draft = latest_reply_json["draft"]; - std::string publish_date = latest_reply_json["published_at"]; - std::string release_note = latest_reply_json["body"]; + auto publish_date = + QString::fromStdString(latest_reply_json["published_at"]); + auto release_note = QString::fromStdString(latest_reply_json["body"]); version_.latest_version = latest_version; version_.latest_prerelease_version_from_remote = prerelease; version_.latest_draft_from_remote = draft; @@ -116,12 +118,12 @@ void VersionCheckTask::slot_parse_latest_version_info() { } try { - std::string current_version_url = + QString current_version_url = "https://api.github.com/repos/saturneric/gpgfrontend/releases/tags/" + current_version_; QNetworkRequest current_request; - current_request.setUrl(QUrl(current_version_url.c_str())); + current_request.setUrl(QUrl(current_version_url)); current_reply_ = network_manager_->get(current_request); connect(current_reply_, &QNetworkReply::finished, this, diff --git a/src/module/integrated/version_checking_module/VersionCheckTask.h b/src/module/integrated/version_checking_module/VersionCheckTask.h index 6f13932a..13f00765 100644 --- a/src/module/integrated/version_checking_module/VersionCheckTask.h +++ b/src/module/integrated/version_checking_module/VersionCheckTask.h @@ -88,7 +88,7 @@ class VersionCheckTask : public Thread::Task { QNetworkReply* latest_reply_ = nullptr; ///< latest version info reply QNetworkReply* current_reply_ = nullptr; ///< current version info reply QNetworkAccessManager* network_manager_; ///< - std::string current_version_; + QString current_version_; SoftwareVersion version_; }; diff --git a/src/pinentry/pinentry.cpp b/src/pinentry/pinentry.cpp index ca3ec346..4a5f1408 100644 --- a/src/pinentry/pinentry.cpp +++ b/src/pinentry/pinentry.cpp @@ -396,62 +396,50 @@ char *pinentry_get_title(pinentry_t pe) { just one data line which should not be escaped in any represent a numeric signed decimal value. Extra data is currently ignored but should not be send at all. */ -int pinentry_inq_quality(pinentry_t pin, const char *passphrase, - size_t length) { - assuan_context_t ctx = (assuan_context_t)pin->ctx_assuan; - const char prefix[] = "INQUIRE QUALITY "; - char *command; - char *line; - size_t linelen; - int gotvalue = 0; - int value = 0; - int rc; +int pinentry_inq_quality(const QString &passphrase) { + int score = 0; + + score += std::min(40, static_cast<int>(passphrase.length()) * 2); + + bool has_upper = false; + bool has_lower = false; + bool has_digit = false; + bool has_special = false; + for (const auto ch : passphrase) { + if (ch.isUpper()) has_upper = true; + if (ch.isLower()) has_lower = true; + if (ch.isDigit()) has_digit = true; + if (!ch.isLetterOrNumber()) has_special = true; + } - if (!ctx) return 0; /* Can't run the callback. */ + int const variety_count = + static_cast<int>(has_upper) + static_cast<int>(has_lower) + + static_cast<int>(has_digit) + static_cast<int>(has_special); + score += variety_count * 10; - if (length > 300) - length = 300; /* Limit so that it definitely fits into an Assuan - line. */ + for (size_t i = 0; i < passphrase.length() - 1; ++i) { + if (passphrase[i] == passphrase[i + 1]) { + score -= 5; + } + } - command = - GpgFrontend::SecureMallocAsType<char>(strlen(prefix) + 3 * length + 1); - if (!command) return 0; - strcpy(command, prefix); - copy_and_escape(command + strlen(command), passphrase, length); - rc = assuan_write_line(ctx, command); - GpgFrontend::SecureFree(command); - if (rc) { - fprintf(stderr, "ASSUAN WRITE LINE failed: rc=%d\n", rc); - return 0; + std::unordered_map<QChar, int> char_count; + for (const auto ch : passphrase) { + char_count[ch]++; + } + for (auto &p : char_count) { + if (p.second > 1) { + score -= (p.second - 1) * 3; + } } - for (;;) { - do { - rc = assuan_read_line(ctx, &line, &linelen); - if (rc) { - fprintf(stderr, "ASSUAN READ LINE failed: rc=%d\n", rc); - return 0; - } - } while (*line == '#' || !linelen); - if (line[0] == 'E' && line[1] == 'N' && line[2] == 'D' && - (!line[3] || line[3] == ' ')) - break; /* END command received*/ - if (line[0] == 'C' && line[1] == 'A' && line[2] == 'N' && - (!line[3] || line[3] == ' ')) - break; /* CAN command received*/ - if (line[0] == 'E' && line[1] == 'R' && line[2] == 'R' && - (!line[3] || line[3] == ' ')) - break; /* ERR command received*/ - if (line[0] != 'D' || line[1] != ' ' || linelen < 3 || gotvalue) continue; - gotvalue = 1; - value = atoi(line + 2); + QString const lower_password = passphrase.toLower(); + if (lower_password.contains("password") || + lower_password.contains("123456")) { + score -= 30; } - if (value < -100) - value = -100; - else if (value > 100) - value = 100; - return value; + return std::max(-100, std::min(100, score)); } /* Run a checkpin inquiry */ diff --git a/src/pinentry/pinentry.h b/src/pinentry/pinentry.h index 0c91a24e..80452e93 100644 --- a/src/pinentry/pinentry.h +++ b/src/pinentry/pinentry.h @@ -303,8 +303,7 @@ const char *pinentry_get_pgmname(void); char *pinentry_get_title(pinentry_t pe); /* Run a quality inquiry for PASSPHRASE of LENGTH. */ -int pinentry_inq_quality(pinentry_t pin, const char *passphrase, - std::size_t length); +int pinentry_inq_quality(const QString &passphrase); /* Run a checkpin inquiry for PASSPHRASE of LENGTH. Returns NULL, if the passphrase satisfies the constraints. Otherwise, returns a malloced error diff --git a/src/pinentry/pinentrydialog.cpp b/src/pinentry/pinentrydialog.cpp index 27d75c8b..01c6d85f 100644 --- a/src/pinentry/pinentrydialog.cpp +++ b/src/pinentry/pinentrydialog.cpp @@ -23,12 +23,9 @@ * SPDX-License-Identifier: GPL-2.0+ */ -#include <qnamespace.h> +#include "pinentrydialog.h" -#include "pinentry.h" -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif +#include <qnamespace.h> #include <QAccessible> #include <QAction> @@ -53,7 +50,8 @@ #include "accessibility.h" #include "capslock/capslock.h" -#include "pinentrydialog.h" +#include "core/utils/MemoryUtils.h" +#include "pinentry.h" #include "pinlineedit.h" #include "util.h" @@ -166,7 +164,7 @@ PinEntryDialog::PinEntryDialog(QWidget *parent, const char *name, int timeout, if (!repeatString.isNull()) { mGenerateButton = new QPushButton{this}; - mGenerateButton->setIcon(QIcon(QLatin1String(":/password-generate.svg"))); + mGenerateButton->setIcon(QIcon(QLatin1String(":password-generate.svg"))); mGenerateButton->setVisible(false); l->addWidget(mGenerateButton); } @@ -174,8 +172,8 @@ PinEntryDialog::PinEntryDialog(QWidget *parent, const char *name, int timeout, } /* Set up the show password action */ - const QIcon visibility_icon = QIcon(QLatin1String(":/visibility.svg")); - const QIcon hide_icon = QIcon(QLatin1String(":/hint.svg")); + const QIcon visibility_icon = QIcon(QLatin1String(":visibility.svg")); + const QIcon hide_icon = QIcon(QLatin1String(":hint.svg")); #if QT_VERSION >= 0x050200 if (!visibility_icon.isNull() && !hide_icon.isNull()) { mVisiActionEdit = @@ -304,6 +302,7 @@ PinEntryDialog::PinEntryDialog(QWidget *parent, const char *name, int timeout, checkCapsLock(); setAttribute(Qt::WA_DeleteOnClose); + setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); /* This is mostly an issue on Windows where this results in the pinentry popping up nicely with an animation and @@ -359,7 +358,7 @@ QString PinEntryDialog::description() const { return _desc->text(); } void PinEntryDialog::setError(const QString &txt) { if (!txt.isNull()) { _icon->setPixmap( - applicationIconPixmap(QIcon{QStringLiteral(":/data-error.svg")})); + applicationIconPixmap(QIcon{QStringLiteral(":data-error.svg")})); } _error->setText(txt); _error->setVisible(!txt.isEmpty()); @@ -487,14 +486,13 @@ void PinEntryDialog::updateQuality(const QString &txt) { _disable_echo_allowed = false; - if (!_have_quality_bar || !_pinentry_info) { + if (!_have_quality_bar) { return; } const QByteArray utf8_pin = txt.toUtf8(); const char *pin = utf8_pin.constData(); length = strlen(pin); - percent = - length != 0 ? pinentry_inq_quality(_pinentry_info.get(), pin, length) : 0; + percent = length != 0 ? pinentry_inq_quality(txt) : 0; if (length == 0) { _quality_bar->reset(); } else { @@ -510,8 +508,9 @@ void PinEntryDialog::updateQuality(const QString &txt) { } } -void PinEntryDialog::setPinentryInfo(pinentry_t peinfo) { - _pinentry_info = std::unique_ptr<struct pinentry>(peinfo); +void PinEntryDialog::setPinentryInfo(struct pinentry peinfo) { + _pinentry_info = + GpgFrontend::SecureCreateUniqueObject<struct pinentry>(peinfo); } void PinEntryDialog::focusChanged(QWidget *old, QWidget *now) { @@ -570,7 +569,7 @@ void PinEntryDialog::toggleVisibility() { if (sender() != mVisiCB) { if (_edit->echoMode() == QLineEdit::Password) { if (mVisiActionEdit != nullptr) { - mVisiActionEdit->setIcon(QIcon(QLatin1String(":/hint.svg"))); + mVisiActionEdit->setIcon(QIcon(QLatin1String(":hint.svg"))); mVisiActionEdit->setToolTip(mHideTT); } _edit->setEchoMode(QLineEdit::Normal); @@ -579,7 +578,7 @@ void PinEntryDialog::toggleVisibility() { } } else { if (mVisiActionEdit != nullptr) { - mVisiActionEdit->setIcon(QIcon(QLatin1String(":/visibility.svg"))); + mVisiActionEdit->setIcon(QIcon(QLatin1String(":visibility.svg"))); mVisiActionEdit->setToolTip(mVisibilityTT); } _edit->setEchoMode(QLineEdit::Password); diff --git a/src/pinentry/pinentrydialog.h b/src/pinentry/pinentrydialog.h index 55f672d4..9f405b10 100644 --- a/src/pinentry/pinentrydialog.h +++ b/src/pinentry/pinentrydialog.h @@ -31,6 +31,7 @@ #include <QStyle> #include <QTimer> +#include "core/function/SecureMemoryAllocator.h" #include "pinentry.h" class QIcon; @@ -103,7 +104,7 @@ class PinEntryDialog : public QDialog { void setConstraintsOptions(const ConstraintsOptions &options); - void setPinentryInfo(pinentry_t); + void setPinentryInfo(struct pinentry); bool timedOut() const; @@ -152,8 +153,8 @@ class PinEntryDialog : public QDialog { bool _disable_echo_allowed = true; bool mEnforceConstraints = false; bool mFormatPassphrase = false; - std::unique_ptr<struct pinentry> _pinentry_info = - std::make_unique<struct pinentry>(); + + GpgFrontend::SecureUniquePtr<struct pinentry> _pinentry_info = nullptr; QTimer *_timer = nullptr; QString mVisibilityTT; QString mHideTT; diff --git a/src/test/GpgFrontendTest.cpp b/src/test/GpgFrontendTest.cpp index f030ed12..b7f59336 100644 --- a/src/test/GpgFrontendTest.cpp +++ b/src/test/GpgFrontendTest.cpp @@ -35,7 +35,6 @@ #include <filesystem> #include "core/GpgConstants.h" -#include "core/GpgCoreInit.h" #include "core/function/GlobalSettingStation.h" #include "core/function/basic/ChannelObject.h" #include "core/function/gpg/GpgContext.h" @@ -44,14 +43,14 @@ namespace GpgFrontend::Test { -auto GenerateRandomString(size_t length) -> std::string { - const std::string characters = +auto GenerateRandomString(size_t length) -> QString { + const QString characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; std::random_device random_device; std::mt19937 generator(random_device()); std::uniform_int_distribution<> distribution(0, characters.size() - 1); - std::string random_string; + QString random_string; for (size_t i = 0; i < length; ++i) { random_string += characters[distribution(generator)]; } @@ -60,31 +59,26 @@ auto GenerateRandomString(size_t length) -> std::string { } void ConfigureGpgContext() { - auto db_path = - std::filesystem::temp_directory_path() / GenerateRandomString(12); + auto db_path = QDir(QDir::tempPath() + "/" + GenerateRandomString(12)); GF_TEST_LOG_DEBUG("setting up new database path for test case: {}", - db_path.string()); + db_path.path()); - if (!std::filesystem::exists(db_path)) { - std::filesystem::create_directory(db_path); - } else { - std::filesystem::remove_all(db_path); - std::filesystem::create_directory(db_path); - } + if (db_path.exists()) db_path.rmdir("."); + db_path.mkdir("."); GpgContext::CreateInstance( kGpgFrontendDefaultChannel, [=]() -> ChannelObjectPtr { GpgContextInitArgs args; args.test_mode = true; args.offline_mode = true; - args.db_path = db_path.string(); + args.db_path = db_path.path(); return ConvertToChannelObjectPtr<>(SecureCreateUniqueObject<GpgContext>( args, kGpgFrontendDefaultChannel)); }); } -void ImportPrivateKeys(const std::filesystem::path& data_path, +void ImportPrivateKeys(const QString& data_path, const libconfig::Setting& config) { if (config.exists("load_keys.private_keys")) { auto& private_keys = config.lookup("load_keys.private_keys"); @@ -92,11 +86,16 @@ void ImportPrivateKeys(const std::filesystem::path& data_path, if (private_key.exists("filename")) { std::string filename; private_key.lookupValue("filename", filename); - auto data_file_path = data_path / filename; - std::string data = ReadAllDataInFile(data_file_path.string()); - auto secret_key_copy = SecureCreateSharedObject<std::string>(data); - GpgKeyImportExporter::GetInstance(kGpgFrontendDefaultChannel) - .ImportKey(secret_key_copy); + auto data_file_path = + data_path + "/" + QString::fromStdString(filename); + + auto [success, gf_buffer] = ReadFileGFBuffer(data_file_path); + if (success) { + GpgKeyImportExporter::GetInstance(kGpgFrontendDefaultChannel) + .ImportKey(gf_buffer); + } else { + GF_TEST_LOG_ERROR("read from file faild: {}", data_file_path); + } } } } @@ -115,7 +114,7 @@ void SetupGlobalTestEnv() { ASSERT_NO_THROW(cfg.readFile(test_config_path.c_str())); auto& root = cfg.getRoot(); - ImportPrivateKeys(test_data_path, root); + ImportPrivateKeys(test_data_path.c_str(), root); } auto ExecuteAllTestCase(GpgFrontendContext args) -> int { diff --git a/src/test/core/GpgCoreTestBasicOpera.cpp b/src/test/core/GpgCoreTestBasicOpera.cpp index 90645ddd..e525afa9 100644 --- a/src/test/core/GpgCoreTestBasicOpera.cpp +++ b/src/test/core/GpgCoreTestBasicOpera.cpp @@ -180,7 +180,7 @@ TEST_F(GpgCoreTest, CoreEncryptDecrTest_KeyNotFound_ResultAnalyse) { GpgDecryptResultAnalyse analyse{err, d_result}; analyse.Analyse(); ASSERT_EQ(analyse.GetStatus(), -1); - ASSERT_FALSE(analyse.GetResultReport().empty()); + ASSERT_FALSE(analyse.GetResultReport().isEmpty()); // stop waiting callback_called_flag = true; diff --git a/src/test/core/GpgCoreTestFileBasicOpera.cpp b/src/test/core/GpgCoreTestFileBasicOpera.cpp index 029ff6fc..e409570f 100644 --- a/src/test/core/GpgCoreTestFileBasicOpera.cpp +++ b/src/test/core/GpgCoreTestFileBasicOpera.cpp @@ -51,7 +51,7 @@ TEST_F(GpgCoreTest, CoreFileEncryptDecrTest) { auto output_file = GetTempFilePath(); GpgFileOpera::GetInstance().EncryptFile( - {encrypt_key}, input_file, true, output_file, + {encrypt_key}, input_file.toStdString(), true, output_file.toStdString(), [output_file, &callback_called_flag](GpgError err, const DataObjectPtr& data_obj) { ASSERT_TRUE((data_obj->Check<GpgEncryptResult>())); @@ -62,7 +62,7 @@ TEST_F(GpgCoreTest, CoreFileEncryptDecrTest) { auto decrpypt_output_file = GetTempFilePath(); GpgFileOpera::GetInstance().DecryptFile( - output_file, decrpypt_output_file, + output_file.toStdString(), decrpypt_output_file.toStdString(), [decrpypt_output_file, &callback_called_flag]( GpgError err, const DataObjectPtr& data_obj) { auto d_result = ExtractParams<GpgDecryptResult>(data_obj, 0); @@ -96,7 +96,7 @@ TEST_F(GpgCoreTest, CoreFileEncryptSymmetricDecrTest) { auto output_file = GetTempFilePath(); GpgFileOpera::GetInstance().EncryptFileSymmetric( - input_file, true, output_file, + input_file.toStdString(), true, output_file.toStdString(), [&callback_called_flag, output_file](GpgError err, const DataObjectPtr& data_obj) { ASSERT_TRUE((data_obj->Check<GpgEncryptResult>())); @@ -106,7 +106,7 @@ TEST_F(GpgCoreTest, CoreFileEncryptSymmetricDecrTest) { auto decrpypt_output_file = GetTempFilePath(); GpgFileOpera::GetInstance().DecryptFile( - output_file, decrpypt_output_file, + output_file.toStdString(), decrpypt_output_file.toStdString(), [&callback_called_flag, decrpypt_output_file]( GpgError err, const DataObjectPtr& data_obj) { ASSERT_TRUE((data_obj->Check<GpgDecryptResult>())); @@ -143,7 +143,7 @@ TEST_F(GpgCoreTest, CoreFileSignVerifyNormalTest) { auto output_file = GetTempFilePath(); GpgFileOpera::GetInstance().SignFile( - {sign_key}, input_file, true, output_file, + {sign_key}, input_file.toStdString(), true, output_file.toStdString(), [&callback_called_flag, input_file, output_file]( GpgError err, const DataObjectPtr& data_obj) { ASSERT_TRUE((data_obj->Check<GpgSignResult>())); @@ -152,7 +152,7 @@ TEST_F(GpgCoreTest, CoreFileSignVerifyNormalTest) { ASSERT_EQ(CheckGpgError(err), GPG_ERR_NO_ERROR); GpgFileOpera::GetInstance().VerifyFile( - input_file, output_file, + input_file.toStdString(), output_file.toStdString(), [&callback_called_flag](GpgError err, const DataObjectPtr& data_obj) { auto d_result = ExtractParams<GpgVerifyResult>(data_obj, 0); @@ -188,7 +188,8 @@ TEST_F(GpgCoreTest, CoreFileEncryptSignDecrVerifyTest) { ASSERT_TRUE(sign_key.IsHasActualSigningCapability()); GpgFileOpera::GetInstance().EncryptSignFile( - {encrypt_key}, {sign_key}, input_file, true, output_file, + {encrypt_key}, {sign_key}, input_file.toStdString(), true, + output_file.toStdString(), [&callback_called_flag, output_file](GpgError err, const DataObjectPtr& data_obj) { ASSERT_TRUE((data_obj->Check<GpgEncryptResult, GpgSignResult>())); @@ -200,7 +201,7 @@ TEST_F(GpgCoreTest, CoreFileEncryptSignDecrVerifyTest) { auto decrpypt_output_file = GetTempFilePath(); GpgFileOpera::GetInstance().DecryptVerifyFile( - output_file, decrpypt_output_file, + output_file.toStdString(), decrpypt_output_file.toStdString(), [&callback_called_flag, decrpypt_output_file]( GpgError err, const DataObjectPtr& data_obj) { ASSERT_TRUE( diff --git a/src/test/core/GpgCoreTestKeyModel.cpp b/src/test/core/GpgCoreTestKeyModel.cpp index 3618bcb9..1f3a5292 100644 --- a/src/test/core/GpgCoreTestKeyModel.cpp +++ b/src/test/core/GpgCoreTestKeyModel.cpp @@ -45,13 +45,13 @@ TEST_F(GpgCoreTest, CoreInitTest) { } TEST_F(GpgCoreTest, GpgDataTest) { - auto data_buff = std::string( + auto data_buff = QString( "cqEh8fyKWtmiXrW2zzlszJVGJrpXDDpzgP7ZELGxhfZYFi8rMrSVKDwrpFZBSWMG"); GpgData data(data_buff.data(), data_buff.size()); - auto out_buffer = data.Read2Buffer(); - ASSERT_EQ(out_buffer->size(), 64); + auto out_buffer = data.Read2GFBuffer(); + ASSERT_EQ(out_buffer.Size(), 64); } TEST_F(GpgCoreTest, GpgKeyTest) { @@ -79,7 +79,7 @@ TEST_F(GpgCoreTest, GpgKeyTest) { ASSERT_FALSE(key.IsHasActualAuthenticationCapability()); ASSERT_EQ(key.GetName(), "GpgFrontendTest"); - ASSERT_TRUE(key.GetComment().empty()); + ASSERT_TRUE(key.GetComment().isEmpty()); ASSERT_EQ(key.GetEmail(), "[email protected]"); ASSERT_EQ(key.GetId(), "81704859182661FB"); ASSERT_EQ(key.GetFingerprint(), "9490795B78F8AFE9F93BD09281704859182661FB"); @@ -138,7 +138,7 @@ TEST_F(GpgCoreTest, GpgUIDTest) { auto& uid = uids->front(); ASSERT_EQ(uid.GetName(), "GpgFrontendTest"); - ASSERT_TRUE(uid.GetComment().empty()); + ASSERT_TRUE(uid.GetComment().isEmpty()); ASSERT_EQ(uid.GetEmail(), "[email protected]"); ASSERT_EQ(uid.GetUID(), "GpgFrontendTest <[email protected]>"); ASSERT_FALSE(uid.GetInvalid()); @@ -157,7 +157,7 @@ TEST_F(GpgCoreTest, GpgKeySignatureTest) { auto& signature = signatures->front(); ASSERT_EQ(signature.GetName(), "GpgFrontendTest"); - ASSERT_TRUE(signature.GetComment().empty()); + ASSERT_TRUE(signature.GetComment().isEmpty()); ASSERT_EQ(signature.GetEmail(), "[email protected]"); ASSERT_EQ(signature.GetKeyID(), "81704859182661FB"); ASSERT_EQ(signature.GetPubkeyAlgo(), "RSA"); diff --git a/src/test/core/GpgCoreTestKeygen.cpp b/src/test/core/GpgCoreTestKeygen.cpp index 476279ac..93544d85 100644 --- a/src/test/core/GpgCoreTestKeygen.cpp +++ b/src/test/core/GpgCoreTestKeygen.cpp @@ -73,7 +73,7 @@ TEST_F(GpgCoreTest, GenerateKeyTest) { GpgKeyOpera::GetInstance(kGpgFrontendDefaultChannel).DeleteKey(fpr); callback_called_flag = true; - ASSERT_FALSE(fpr.empty()); + ASSERT_FALSE(fpr.isEmpty()); }); int retry_count = 1000; @@ -118,7 +118,7 @@ TEST_F(GpgCoreTest, GenerateKeyTest_1) { GpgKeyOpera::GetInstance(kGpgFrontendDefaultChannel).DeleteKey(fpr); callback_called_flag = true; - ASSERT_FALSE(fpr.empty()); + ASSERT_FALSE(fpr.isEmpty()); }); int retry_count = 2000; @@ -157,7 +157,7 @@ TEST_F(GpgCoreTest, GenerateKeyTest_4) { GpgKeyOpera::GetInstance(kGpgFrontendDefaultChannel).DeleteKey(fpr); callback_called_flag = true; - ASSERT_FALSE(fpr.empty()); + ASSERT_FALSE(fpr.isEmpty()); }); int retry_count = 2000; @@ -196,7 +196,7 @@ TEST_F(GpgCoreTest, GenerateKeyTest_5) { GpgKeyOpera::GetInstance(kGpgFrontendDefaultChannel).DeleteKey(fpr); callback_called_flag = true; - ASSERT_FALSE(fpr.empty()); + ASSERT_FALSE(fpr.isEmpty()); }); int retry_count = 1000; diff --git a/src/ui/GpgFrontendUIInit.cpp b/src/ui/GpgFrontendUIInit.cpp index e896229f..5734dc29 100644 --- a/src/ui/GpgFrontendUIInit.cpp +++ b/src/ui/GpgFrontendUIInit.cpp @@ -136,20 +136,18 @@ void InitGpgFrontendUI(QApplication* /*app*/) { // if enable proxy for application if (proxy_enable) { try { - std::string proxy_type = - GlobalSettingStation::GetInstance().LookupSettings("proxy.proxy_type", - std::string{}); - std::string proxy_host = - GlobalSettingStation::GetInstance().LookupSettings("proxy.proxy_host", - std::string{}); + QString proxy_type = GlobalSettingStation::GetInstance().LookupSettings( + "proxy.proxy_type", QString{}); + QString proxy_host = GlobalSettingStation::GetInstance().LookupSettings( + "proxy.proxy_host", QString{}); int proxy_port = GlobalSettingStation::GetInstance().LookupSettings("proxy.port", 0); - std::string proxy_username = + QString proxy_username = GlobalSettingStation::GetInstance().LookupSettings("proxy.username", - std::string{}); - std::string proxy_password = + QString{}); + QString proxy_password = GlobalSettingStation::GetInstance().LookupSettings("proxy.password", - std::string{}); + QString{}); GF_UI_LOG_DEBUG("proxy settings: type {}, host {}, port: {}", proxy_type, proxy_host, proxy_port); @@ -166,13 +164,13 @@ void InitGpgFrontendUI(QApplication* /*app*/) { QNetworkProxy proxy; if (proxy_type_qt != QNetworkProxy::DefaultProxy) { proxy.setType(proxy_type_qt); - proxy.setHostName(QString::fromStdString(proxy_host)); + proxy.setHostName(proxy_host); proxy.setPort(proxy_port); - if (!proxy_username.empty()) { - proxy.setUser(QString::fromStdString(proxy_username)); + if (!proxy_username.isEmpty()) { + proxy.setUser(proxy_username); } - if (!proxy_password.empty()) { - proxy.setPassword(QString::fromStdString(proxy_password)); + if (!proxy_password.isEmpty()) { + proxy.setPassword(proxy_password); } } else { proxy.setType(proxy_type_qt); @@ -193,6 +191,9 @@ void InitGpgFrontendUI(QApplication* /*app*/) { 0) { WaitEnvCheckingProcess(); } + + qRegisterMetaType<QSharedPointer<GpgPassphraseContext> >( + "QSharedPointer<GpgPassphraseContext>"); } auto RunGpgFrontendUI(QApplication* app) -> int { @@ -259,35 +260,35 @@ void InitLocale() { #ifndef WINDOWS if (!lang.empty()) { - std::string lc = lang + ".UTF-8"; + QString lc = QString::fromStdString(lang) + ".UTF-8"; // set LC_ALL - auto* locale_name = setlocale(LC_ALL, lc.c_str()); + auto* locale_name = setlocale(LC_ALL, lc.toUtf8()); if (locale_name == nullptr) GF_UI_LOG_WARN("set LC_ALL failed, lc: {}", lc); auto* language = getenv("LANGUAGE"); // set LANGUAGE - std::string language_env = language == nullptr ? "en" : language; + QString language_env = language == nullptr ? "en" : language; language_env.insert(0, lang + ":"); GF_UI_LOG_DEBUG("language env: {}", language_env); - if (setenv("LANGUAGE", language_env.c_str(), 1) != 0) { + if (setenv("LANGUAGE", language_env.toUtf8(), 1) != 0) { GF_UI_LOG_WARN("set LANGUAGE {} failed", language_env); }; } #else if (!lang.empty()) { - std::string lc = lang; + QString lc = QString::fromStdString(lang); // set LC_ALL - auto* locale_name = setlocale(LC_ALL, lc.c_str()); + auto* locale_name = setlocale(LC_ALL, lc.toUtf8()); if (locale_name == nullptr) GF_UI_LOG_WARN("set LC_ALL failed, lc: {}", lc); auto language = getenv("LANGUAGE"); // set LANGUAGE - std::string language_env = language == nullptr ? "en" : language; + QString language_env = language == nullptr ? "en" : language; language_env.insert(0, lang + ":"); language_env.insert(0, "LANGUAGE="); GF_UI_LOG_DEBUG("language env: {}", language_env); - if (putenv(language_env.c_str())) { + if (putenv(language_env.toUtf8())) { GF_UI_LOG_WARN("set LANGUAGE {} failed", language_env); }; } diff --git a/src/ui/UISignalStation.h b/src/ui/UISignalStation.h index 83e7a02c..aee61300 100644 --- a/src/ui/UISignalStation.h +++ b/src/ui/UISignalStation.h @@ -30,6 +30,10 @@ #include "ui/widgets/InfoBoardWidget.h" +namespace GpgFrontend { +class GpgPassphraseContext; +} + namespace GpgFrontend::UI { /** @@ -88,13 +92,13 @@ class UISignalStation : public QObject { * @brief * */ - void SignalNeedUserInputPassphrase(); + void SignalNeedUserInputPassphrase(QSharedPointer<GpgPassphraseContext>); /** * @brief * */ - void SignalUserInputPassphraseCallback(QByteArray); + void SignalUserInputPassphraseCallback(QSharedPointer<GpgPassphraseContext>); /** * @brief diff --git a/src/ui/UserInterfaceUtils.cpp b/src/ui/UserInterfaceUtils.cpp index c7c198b3..b6b1fa9e 100644 --- a/src/ui/UserInterfaceUtils.cpp +++ b/src/ui/UserInterfaceUtils.cpp @@ -94,15 +94,13 @@ void import_unknown_key_from_keyserver( } void refresh_info_board(InfoBoardWidget *info_board, int status, - const std::string &report_text) { + const QString &report_text) { if (status < 0) - info_board->SlotRefresh(QString::fromStdString(report_text), - INFO_ERROR_CRITICAL); + info_board->SlotRefresh(report_text, INFO_ERROR_CRITICAL); else if (status > 0) - info_board->SlotRefresh(QString::fromStdString(report_text), INFO_ERROR_OK); + info_board->SlotRefresh(report_text, INFO_ERROR_OK); else - info_board->SlotRefresh(QString::fromStdString(report_text), - INFO_ERROR_WARN); + info_board->SlotRefresh(report_text, INFO_ERROR_WARN); } void process_result_analyse(TextEdit *edit, InfoBoardWidget *info_board, @@ -123,12 +121,11 @@ void process_result_analyse(TextEdit *edit, InfoBoardWidget *info_board, result_analyse_a.GetResultReport() + result_analyse_b.GetResultReport()); } -void process_operation(QWidget *parent, const std::string &waiting_title, +void process_operation(QWidget *parent, const QString &waiting_title, const Thread::Task::TaskRunnable func, const Thread::Task::TaskCallback callback, DataObjectPtr data_object) { - auto *dialog = - new WaitingDialog(QString::fromStdString(waiting_title), parent); + auto *dialog = new WaitingDialog(waiting_title, parent); auto *process_task = new Thread::Task(std::move(func), waiting_title, data_object, std::move(callback)); @@ -226,11 +223,11 @@ CommonUtils::CommonUtils() : QWidget(nullptr) { } void CommonUtils::WaitForOpera(QWidget *parent, - const std::string &waiting_dialog_title, + const QString &waiting_dialog_title, const OperaWaitingCb &opera) { QEventLoop looper; QPointer<WaitingDialog> const dialog = - new WaitingDialog(QString::fromStdString(waiting_dialog_title), parent); + new WaitingDialog(waiting_dialog_title, parent); connect(dialog, &QDialog::finished, &looper, &QEventLoop::quit); connect(dialog, &QDialog::finished, dialog, &QDialog::deleteLater); dialog->show(); @@ -279,15 +276,14 @@ void CommonUtils::RaiseFailureMessageBox(QWidget *parent, GpgError err) { QMessageBox::critical( parent, _("Failure"), - QString::fromStdString( - (boost::format(_("Gpg Operation failed.\n\nError code: %1%\nSource: " - " %2%\nDescription: %3%")) % - err_code % desc.first % desc.second) - .str())); + QString(_("Gpg Operation failed.\n\nError code: %1%\nSource: " + " %2%\nDescription: %3%")) + .arg(err_code) + .arg(desc.first) + .arg(desc.second)); } -void CommonUtils::SlotImportKeys(QWidget *parent, - const std::string &in_buffer) { +void CommonUtils::SlotImportKeys(QWidget *parent, const QString &in_buffer) { auto info = GpgKeyImportExporter::GetInstance().ImportKey(GFBuffer(in_buffer)); emit SignalKeyStatusUpdated(); @@ -307,7 +303,7 @@ void CommonUtils::SlotImportKeyFromFile(QWidget *parent) { _("Failed to open file: ") + file_name); return; } - SlotImportKeys(parent, key_buffer.toStdString()); + SlotImportKeys(parent, key_buffer); } } @@ -318,12 +314,11 @@ void CommonUtils::SlotImportKeyFromKeyServer(QWidget *parent) { void CommonUtils::SlotImportKeyFromClipboard(QWidget *parent) { QClipboard *cb = QApplication::clipboard(); - SlotImportKeys(parent, - cb->text(QClipboard::Clipboard).toUtf8().toStdString()); + SlotImportKeys(parent, cb->text(QClipboard::Clipboard)); } void CommonUtils::SlotExecuteCommand( - const std::string &cmd, const QStringList &arguments, + const QString &cmd, const QStringList &arguments, const std::function<void(QProcess *)> &interact_func) { QEventLoop looper; auto *cmd_process = new QProcess(&looper); @@ -348,7 +343,7 @@ void CommonUtils::SlotExecuteCommand( GF_UI_LOG_WARN("error in executing command: {}", cmd); }); - cmd_process->setProgram(QString::fromStdString(cmd)); + cmd_process->setProgram(cmd); cmd_process->setArguments(arguments); cmd_process->start(); looper.exec(); @@ -393,10 +388,10 @@ void CommonUtils::SlotExecuteGpgCommand( }); const auto app_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.app_path", std::string{}); + "core", "gpgme.ctx.app_path", QString{}); GF_UI_LOG_DEBUG("got gnupg app path from rt: {}", app_path); - gpg_process->setProgram(app_path.c_str()); + gpg_process->setProgram(app_path); gpg_process->setArguments(arguments); gpg_process->start(); looper.exec(); @@ -407,7 +402,7 @@ void CommonUtils::SlotExecuteGpgCommand( void CommonUtils::SlotImportKeyFromKeyServer( const KeyIdArgsList &key_ids, const ImportCallbackFunctiopn &callback) { // target key server that we need to import key from it - std::string target_keyserver; + QString target_keyserver; try { SettingsObject key_server_json("key_server"); @@ -425,7 +420,7 @@ void CommonUtils::SlotImportKeyFromKeyServer( throw std::runtime_error("default_server index out of range"); } target_keyserver = - key_server_list[target_key_server_index].get<std::string>(); + key_server_list[target_key_server_index].get<std::string>().c_str(); GF_UI_LOG_DEBUG("set target key server to default Key Server: {}", target_keyserver); @@ -438,7 +433,7 @@ void CommonUtils::SlotImportKeyFromKeyServer( } auto *thread = QThread::create([target_keyserver, key_ids, callback]() { - QUrl target_keyserver_url(target_keyserver.c_str()); + QUrl target_keyserver_url(target_keyserver); auto network_manager = std::make_unique<QNetworkAccessManager>(); // LOOP @@ -447,9 +442,9 @@ void CommonUtils::SlotImportKeyFromKeyServer( for (const auto &key_id : key_ids) { // New Req Url - QUrl req_url( - target_keyserver_url.scheme() + "://" + target_keyserver_url.host() + - "/pks/lookup?op=get&search=0x" + key_id.c_str() + "&options=mr"); + QUrl req_url(target_keyserver_url.scheme() + "://" + + target_keyserver_url.host() + + "/pks/lookup?op=get&search=0x" + key_id + "&options=mr"); GF_UI_LOG_DEBUG("request url: {}", req_url.toString().toStdString()); @@ -460,7 +455,7 @@ void CommonUtils::SlotImportKeyFromKeyServer( loop.exec(); // Detect status - std::string status; + QString status; auto error = reply->error(); if (error != QNetworkReply::NoError) { switch (error) { @@ -525,7 +520,7 @@ void CommonUtils::slot_popup_passphrase_input_dialog() { dialog->resize(500, 80); dialog->exec(); - SetTempCacheValue("__key_passphrase", dialog->textValue().toStdString()); + SetTempCacheValue("__key_passphrase", dialog->textValue()); // send signal // emit SignalUserInputPassphraseDone(); @@ -552,8 +547,8 @@ bool CommonUtils::KeyExistsinFavouriteList(const GpgKey &key) { CacheManager::GetInstance().SaveCache("favourite_key_pair", nlohmann::json::array()); } - return std::find(key_array.begin(), key_array.end(), key.GetFingerprint()) != - key_array.end(); + return std::find(key_array.begin(), key_array.end(), + key.GetFingerprint().toStdString()) != key_array.end(); } void CommonUtils::AddKey2Favourtie(const GpgKey &key) { @@ -562,7 +557,7 @@ void CommonUtils::AddKey2Favourtie(const GpgKey &key) { CacheManager::GetInstance().SaveCache("favourite_key_pair", nlohmann::json::array()); } - key_array.push_back(key.GetFingerprint()); + key_array.push_back(key.GetFingerprint().toStdString()); CacheManager::GetInstance().SaveCache("favourite_key_pair", key_array, true); } @@ -573,10 +568,11 @@ void CommonUtils::RemoveKeyFromFavourite(const GpgKey &key) { nlohmann::json::array(), true); return; } - auto it = std::find(key_array.begin(), key_array.end(), key.GetFingerprint()); + auto it = std::find(key_array.begin(), key_array.end(), + key.GetFingerprint().toStdString()); if (it != key_array.end()) { - auto rm_it = - std::remove(key_array.begin(), key_array.end(), key.GetFingerprint()); + auto rm_it = std::remove(key_array.begin(), key_array.end(), + key.GetFingerprint().toStdString()); key_array.erase(rm_it, key_array.end()); CacheManager::GetInstance().SaveCache("favourite_key_pair", key_array); } diff --git a/src/ui/UserInterfaceUtils.h b/src/ui/UserInterfaceUtils.h index 2bbaa106..365b5ff1 100644 --- a/src/ui/UserInterfaceUtils.h +++ b/src/ui/UserInterfaceUtils.h @@ -76,7 +76,7 @@ void import_unknown_key_from_keyserver( * @param report_text */ void refresh_info_board(InfoBoardWidget* info_board, int status, - const std::string& report_text); + const QString& report_text); /** * @brief @@ -108,7 +108,7 @@ void process_result_analyse(TextEdit* edit, InfoBoardWidget* info_board, * @param func */ void process_operation( - QWidget* parent, const std::string& waiting_title, + QWidget* parent, const QString& waiting_title, GpgFrontend::Thread::Task::TaskRunnable func, GpgFrontend::Thread::Task::TaskCallback callback = nullptr, DataObjectPtr data_object = nullptr); @@ -120,8 +120,8 @@ void process_operation( * @param key_id * @param key_server */ -void import_key_from_keyserver(QWidget* parent, const std::string& key_id, - const std::string& key_server); +void import_key_from_keyserver(QWidget* parent, const QString& key_id, + const QString& key_server); /** * @brief @@ -135,7 +135,7 @@ class CommonUtils : public QWidget { * */ using ImportCallbackFunctiopn = std::function<void( - const std::string&, const std::string&, size_t, size_t)>; + const QString&, const QString&, size_t, size_t)>; /** * @brief Construct a new Common Utils object @@ -155,7 +155,7 @@ class CommonUtils : public QWidget { * * @param err */ - static void WaitForOpera(QWidget* parent, const std::string&, + static void WaitForOpera(QWidget* parent, const QString&, const OperaWaitingCb&); /** @@ -228,7 +228,7 @@ class CommonUtils : public QWidget { * @param parent * @param in_buffer */ - void SlotImportKeys(QWidget* parent, const std::string& in_buffer); + void SlotImportKeys(QWidget* parent, const QString& in_buffer); /** * @brief @@ -278,7 +278,7 @@ class CommonUtils : public QWidget { * @param arguments * @param interact_func */ - void SlotExecuteCommand(const std::string& cmd, const QStringList& arguments, + void SlotExecuteCommand(const QString& cmd, const QStringList& arguments, const std::function<void(QProcess*)>& interact_func); /** diff --git a/src/ui/dialog/GeneralDialog.cpp b/src/ui/dialog/GeneralDialog.cpp index d48e878d..498e2941 100644 --- a/src/ui/dialog/GeneralDialog.cpp +++ b/src/ui/dialog/GeneralDialog.cpp @@ -30,7 +30,7 @@ #include "ui/struct/SettingsObject.h" -GpgFrontend::UI::GeneralDialog::GeneralDialog(std::string name, QWidget *parent) +GpgFrontend::UI::GeneralDialog::GeneralDialog(QString name, QWidget *parent) : QDialog(parent), name_(std::move(name)) { slot_restore_settings(); connect(this, &QDialog::finished, this, &GeneralDialog::slot_save_settings); @@ -47,8 +47,8 @@ void GpgFrontend::UI::GeneralDialog::slot_restore_settings() noexcept { // Restore window size & location if (window_save) { - int x = general_windows_state.Check("window_pos").Check("x", 0), - y = general_windows_state.Check("window_pos").Check("y", 0); + int x = general_windows_state.Check("window_pos").Check("x", 0); + int y = general_windows_state.Check("window_pos").Check("y", 0); GF_UI_LOG_DEBUG("stored dialog pos, x: {}, y: {}", x, y); QPoint relative_pos = {x, y}; @@ -56,19 +56,19 @@ void GpgFrontend::UI::GeneralDialog::slot_restore_settings() noexcept { GF_UI_LOG_DEBUG("relative dialog pos, x: {}, y: {}", relative_pos.x(), relative_pos.y()); - int width = general_windows_state.Check("window_size").Check("width", 0), - height = - general_windows_state.Check("window_size").Check("height", 0); + int width = general_windows_state.Check("window_size").Check("width", 0); + int height = + general_windows_state.Check("window_size").Check("height", 0); GF_UI_LOG_DEBUG("stored dialog size, width: {}, height: {}", width, height); - QRect target_rect_ = {pos.x(), pos.y(), 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_)) { - this->setGeometry(target_rect_); + if (width > 0 && height > 0 && screen_rect_.contains(target_rect)) { + this->setGeometry(target_rect); this->rect_restored_ = true; } } @@ -101,7 +101,7 @@ void GpgFrontend::UI::GeneralDialog::slot_save_settings() noexcept { general_windows_state["window_save"] = true; } catch (...) { - GF_UI_LOG_ERROR(name_, "error"); + GF_UI_LOG_ERROR("general dialog: {}, caught exception", name_); } } @@ -194,7 +194,9 @@ void GpgFrontend::UI::GeneralDialog::update_rect_cache() { * @brief * */ -bool GpgFrontend::UI::GeneralDialog::isRectRestored() { return rect_restored_; } +auto GpgFrontend::UI::GeneralDialog::isRectRestored() -> bool { + return rect_restored_; +} /** * @brief @@ -207,5 +209,5 @@ void GpgFrontend::UI::GeneralDialog::showEvent(QShowEvent *event) { // default position strategy if (!isRectRestored()) movePosition2CenterOfParent(); - QWidget::showEvent(event); + QDialog::showEvent(event); }
\ No newline at end of file diff --git a/src/ui/dialog/GeneralDialog.h b/src/ui/dialog/GeneralDialog.h index 741b6109..604c8475 100644 --- a/src/ui/dialog/GeneralDialog.h +++ b/src/ui/dialog/GeneralDialog.h @@ -38,7 +38,7 @@ class GeneralDialog : public QDialog { * * @param name */ - explicit GeneralDialog(std::string name, QWidget* parent = nullptr); + explicit GeneralDialog(QString name, QWidget* parent = nullptr); /** * @@ -86,7 +86,7 @@ class GeneralDialog : public QDialog { */ void update_rect_cache(); - std::string name_; ///< + QString name_; ///< QRect rect_; QRect parent_rect_; QRect screen_rect_; diff --git a/src/ui/dialog/QuitDialog.cpp b/src/ui/dialog/QuitDialog.cpp index 7ad6f835..c02f5898 100755 --- a/src/ui/dialog/QuitDialog.cpp +++ b/src/ui/dialog/QuitDialog.cpp @@ -28,8 +28,6 @@ #include "QuitDialog.h" -#include <boost/format.hpp> - namespace GpgFrontend::UI { QuitDialog::QuitDialog(QWidget* parent, const QHash<int, QString>& unsavedDocs) @@ -83,10 +81,10 @@ QuitDialog::QuitDialog(QWidget* parent, const QHash<int, QString>& unsavedDocs) warn_icon->setPixmap(pixmap); const auto info = - boost::format(_("%1% files contain unsaved information.<br/>Save the " - "changes before closing?")) % - std::to_string(row); - auto* warn_label = new QLabel(QString::fromStdString(info.str())); + QString(_("%1 files contain unsaved information.<br/>Save the " + "changes before closing?")) + .arg(row); + auto* warn_label = new QLabel(info); auto* warn_box_layout = new QHBoxLayout(); warn_box_layout->addWidget(warn_icon); warn_box_layout->addWidget(warn_label); diff --git a/src/ui/dialog/details/VerifyDetailsDialog.cpp b/src/ui/dialog/details/VerifyDetailsDialog.cpp index f77660a5..00251d4a 100644 --- a/src/ui/dialog/details/VerifyDetailsDialog.cpp +++ b/src/ui/dialog/details/VerifyDetailsDialog.cpp @@ -28,8 +28,6 @@ #include "VerifyDetailsDialog.h" -#include <boost/format.hpp> - #include "core/GpgModel.h" namespace GpgFrontend::UI { @@ -67,27 +65,21 @@ void VerifyDetailsDialog::slot_refresh() { // Get timestamp of signature of current text QDateTime timestamp; -#ifdef GPGFRONTEND_GUI_QT6 timestamp.setSecsSinceEpoch(to_time_t(signatures[0].GetCreateTime())); -#else - timestamp.setTime_t(sign->timestamp); -#endif // Set the title widget depending on sign status if (gpg_err_code(signatures[0].GetStatus()) == GPG_ERR_BAD_SIGNATURE) { m_vbox_layout->addWidget(new QLabel(_("Error Validating signature"))); } else if (input_signature_ != nullptr) { - const auto info = (boost::format(_("File was signed on %1%")) % - QLocale::system().toString(timestamp).toStdString()) - .str() + + const auto info = QString(_("File was signed on %1")) + .arg(QLocale::system().toString(timestamp)) + "<br/>" + _("It Contains") + ": " + "<br/><br/>"; - m_vbox_layout->addWidget(new QLabel(info.c_str())); + m_vbox_layout->addWidget(new QLabel(info)); } else { - const auto info = (boost::format(_("Signed on %1%")) % - QLocale::system().toString(timestamp).toStdString()) - .str() + - "<br/>" + _("It Contains") + ": " + "<br/><br/>"; - m_vbox_layout->addWidget(new QLabel(info.c_str())); + const auto info = + QString(_("Signed on %1%")).arg(QLocale::system().toString(timestamp)) + + "<br/>" + _("It Contains") + ": " + "<br/><br/>"; + m_vbox_layout->addWidget(new QLabel(info)); } // Add information box for every single key for (const auto& signature : signatures) { diff --git a/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp b/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp index 0c3af463..992258ae 100644 --- a/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp +++ b/src/ui/dialog/gnupg/GnuPGControllerDialog.cpp @@ -96,10 +96,10 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); GF_UI_LOG_DEBUG("key databse path selected: {}", - selected_custom_key_database_path.toStdString()); + selected_custom_key_database_path); if (!check_custom_gnupg_key_database_path( - selected_custom_key_database_path.toStdString())) { + selected_custom_key_database_path)) { return; } @@ -132,11 +132,10 @@ GnuPGControllerDialog::GnuPGControllerDialog(QWidget* parent) QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); GF_UI_LOG_DEBUG("gnupg install path selected: {}", - selected_custom_gnupg_install_path.toStdString()); + selected_custom_gnupg_install_path); // notify the user and precheck - if (!check_custom_gnupg_path( - selected_custom_gnupg_install_path.toStdString())) { + if (!check_custom_gnupg_path(selected_custom_gnupg_install_path)) { return; } @@ -207,20 +206,19 @@ void GnuPGControllerDialog::slot_update_custom_key_database_path_label( this->slot_set_restart_needed(kDeepRestartCode); const auto database_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.database_path", std::string{}); + "core", "gpgme.ctx.database_path", QString{}); GF_UI_LOG_DEBUG("got gpgme.ctx.database_path from rt: {}", database_path); if (state != Qt::CheckState::Checked) { - ui_->currentKeyDatabasePathLabel->setText( - QString::fromStdString(database_path)); + ui_->currentKeyDatabasePathLabel->setText(database_path); // hide label (not necessary to show the default path) this->ui_->currentKeyDatabasePathLabel->setHidden(true); } else { // read from settings file - std::string custom_key_database_path = + QString custom_key_database_path = GlobalSettingStation::GetInstance().LookupSettings( - "general.custom_key_database_path", std::string{}); + "general.custom_key_database_path", QString{}); GF_UI_LOG_DEBUG("selected_custom_key_database_path from settings: {}", custom_key_database_path); @@ -229,9 +227,8 @@ void GnuPGControllerDialog::slot_update_custom_key_database_path_label( check_custom_gnupg_key_database_path(custom_key_database_path); // set label value - if (!custom_key_database_path.empty()) { - ui_->currentKeyDatabasePathLabel->setText( - QString::fromStdString(custom_key_database_path)); + if (!custom_key_database_path.isEmpty()) { + ui_->currentKeyDatabasePathLabel->setText(custom_key_database_path); this->ui_->currentKeyDatabasePathLabel->setHidden(false); } else { this->ui_->currentKeyDatabasePathLabel->setHidden(true); @@ -246,20 +243,19 @@ void GnuPGControllerDialog::slot_update_custom_gnupg_install_path_label( const auto home_path = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - "gnupg.home_path", std::string{}); + "gnupg.home_path", QString{}); GF_UI_LOG_DEBUG("got gnupg home path from rt: {}", home_path); if (state != Qt::CheckState::Checked) { - ui_->currentCustomGnuPGInstallPathLabel->setText( - QString::fromStdString(home_path)); + ui_->currentCustomGnuPGInstallPathLabel->setText(home_path); // hide label (not necessary to show the default path) this->ui_->currentCustomGnuPGInstallPathLabel->setHidden(true); } else { // read from settings file - std::string custom_gnupg_install_path = + QString custom_gnupg_install_path = GlobalSettingStation::GetInstance().LookupSettings( - "general.custom_gnupg_install_path", std::string{}); + "general.custom_gnupg_install_path", QString{}); GF_UI_LOG_DEBUG("custom_gnupg_install_path from settings: {}", custom_gnupg_install_path); @@ -268,9 +264,9 @@ void GnuPGControllerDialog::slot_update_custom_gnupg_install_path_label( check_custom_gnupg_path(custom_gnupg_install_path); // set label value - if (!custom_gnupg_install_path.empty()) { + if (!custom_gnupg_install_path.isEmpty()) { ui_->currentCustomGnuPGInstallPathLabel->setText( - QString::fromStdString(custom_gnupg_install_path)); + custom_gnupg_install_path); this->ui_->currentCustomGnuPGInstallPathLabel->setHidden(false); } else { this->ui_->currentCustomGnuPGInstallPathLabel->setHidden(true); @@ -367,16 +363,14 @@ void GnuPGControllerDialog::slot_set_restart_needed(int mode) { this->restart_needed_ = mode; } -bool GnuPGControllerDialog::check_custom_gnupg_path(std::string path) { - QString path_qstr = QString::fromStdString(path); - - if (path_qstr.isEmpty()) { +bool GnuPGControllerDialog::check_custom_gnupg_path(QString path) { + if (path.isEmpty()) { QMessageBox::critical(this, _("Illegal GnuPG Path"), _("Target GnuPG Path is empty.")); return false; } - QFileInfo dir_info(path_qstr); + QFileInfo dir_info(path); if (!dir_info.exists() || !dir_info.isReadable() || !dir_info.isDir()) { QMessageBox::critical( this, _("Illegal GnuPG Path"), @@ -384,15 +378,15 @@ bool GnuPGControllerDialog::check_custom_gnupg_path(std::string path) { return false; } - QDir dir(path_qstr); + QDir dir(path); if (!dir.isAbsolute()) { QMessageBox::critical(this, _("Illegal GnuPG Path"), _("Target GnuPG Path is not an absolute path.")); } #ifdef WINDOWS - QFileInfo gpgconf_info(path_qstr + "/gpgconf.exe"); + QFileInfo gpgconf_info(path + "/gpgconf.exe"); #else - QFileInfo gpgconf_info(path_qstr + "/gpgconf"); + QFileInfo gpgconf_info(path + "/gpgconf"); #endif if (!gpgconf_info.exists() || !gpgconf_info.isExecutable() || @@ -406,17 +400,15 @@ bool GnuPGControllerDialog::check_custom_gnupg_path(std::string path) { return true; } -bool GnuPGControllerDialog::check_custom_gnupg_key_database_path( - std::string path) { - QString selected_custom_key_database_path = QString::fromStdString(path); - - if (selected_custom_key_database_path.isEmpty()) { +auto GnuPGControllerDialog::check_custom_gnupg_key_database_path(QString path) + -> bool { + if (path.isEmpty()) { QMessageBox::critical(this, _("Illegal GnuPG Key Database Path"), _("Target GnuPG Key Database Path is empty.")); return false; } - QFileInfo dir_info(selected_custom_key_database_path); + QFileInfo dir_info(path); if (!dir_info.exists() || !dir_info.isReadable() || !dir_info.isDir()) { QMessageBox::critical(this, _("Illegal GnuPG Key Database Path"), _("Target GnuPG Key Database Path is not an " diff --git a/src/ui/dialog/gnupg/GnuPGControllerDialog.h b/src/ui/dialog/gnupg/GnuPGControllerDialog.h index d437550c..9da25728 100644 --- a/src/ui/dialog/gnupg/GnuPGControllerDialog.h +++ b/src/ui/dialog/gnupg/GnuPGControllerDialog.h @@ -100,8 +100,8 @@ class GnuPGControllerDialog : public GeneralDialog { void apply_settings(); - bool check_custom_gnupg_path(std::string); + bool check_custom_gnupg_path(QString); - bool check_custom_gnupg_key_database_path(std::string); + bool check_custom_gnupg_key_database_path(QString); }; } // namespace GpgFrontend::UI diff --git a/src/ui/dialog/help/AboutDialog.cpp b/src/ui/dialog/help/AboutDialog.cpp index 7c534cbf..e38777f3 100644 --- a/src/ui/dialog/help/AboutDialog.cpp +++ b/src/ui/dialog/help/AboutDialog.cpp @@ -80,7 +80,7 @@ void AboutDialog::showEvent(QShowEvent* ev) { QDialog::showEvent(ev); } InfoTab::InfoTab(QWidget* parent) : QWidget(parent) { const auto gpgme_version = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.version", std::string{"2.0.0"}); + "core", "gpgme.version", QString{"2.0.0"}); GF_UI_LOG_DEBUG("got gpgme version from rt: {}", gpgme_version); auto* pixmap = new QPixmap(":gpgfrontend-logo.png"); @@ -101,7 +101,7 @@ InfoTab::InfoTab(QWidget* parent) : QWidget(parent) { _("or send a mail to my mailing list at") + " <a " + "href=\"mailto:[email protected]\">[email protected]</a>." + "<br><br> " + _("Built with Qt") + " " + qVersion() + ", " + OPENSSL_VERSION_TEXT + - " " + _("and") + " " + "GPGME" + " " + gpgme_version.c_str() + "<br>" + + " " + _("and") + " " + "GPGME" + " " + gpgme_version + "<br>" + _("Built at") + " " + BUILD_TIMESTAMP + "</center>"); auto* layout = new QGridLayout(); @@ -124,7 +124,7 @@ TranslatorsTab::TranslatorsTab(QWidget* parent) : QWidget(parent) { QFile translators_qfile; auto translators_file = GlobalSettingStation::GetInstance().GetResourceDir() / "TRANSLATORS"; - translators_qfile.setFileName(translators_file.u8string().c_str()); + translators_qfile.setFileName(translators_file); #ifdef LINUX if (!translators_qfile.exists()) { translators_qfile.setFileName("/usr/local/share/GpgFrontend/TRANSLATORS"); @@ -254,11 +254,11 @@ void UpdateTab::slot_show_version_status() { auto latest_version = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.version-checking", - "version.latest_version", std::string{}); + "version.latest_version", QString{}); - latest_version_label_->setText( - "<center><b>" + QString(_("Latest Version From Github")) + ": " + - latest_version.c_str() + "</b></center>"); + latest_version_label_->setText("<center><b>" + + QString(_("Latest Version From Github")) + + ": " + latest_version + "</b></center>"); if (is_need_upgrade) { upgrade_label_->setText( diff --git a/src/ui/dialog/help/GnupgTab.cpp b/src/ui/dialog/help/GnupgTab.cpp index ba5e464a..ed47c38c 100644 --- a/src/ui/dialog/help/GnupgTab.cpp +++ b/src/ui/dialog/help/GnupgTab.cpp @@ -32,12 +32,9 @@ #include "GnupgTab.h" -#include <boost/format.hpp> #include <nlohmann/json.hpp> -#include <shared_mutex> #include "core/module/ModuleManager.h" -#include "ui/UserInterfaceUtils.h" #include "ui_GnuPGInfo.h" GpgFrontend::UI::GnupgTab::GnupgTab(QWidget* parent) @@ -87,7 +84,7 @@ GpgFrontend::UI::GnupgTab::GnupgTab(QWidget* parent) void GpgFrontend::UI::GnupgTab::process_software_info() { const auto gnupg_version = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.gnupg_version", std::string{"2.0.0"}); + "core", "gpgme.ctx.gnupg_version", QString{"2.0.0"}); GF_UI_LOG_DEBUG("got gnupg version from rt: {}", gnupg_version); ui_->gnupgVersionLabel->setText( @@ -104,13 +101,12 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { for (auto& component : components) { auto component_info_json = Module::RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - (boost::format("gnupg.components.%1%") % component).str(), - std::string{}); + QString("gnupg.components.%1%").arg(component), QString{}); GF_UI_LOG_DEBUG("got gnupg component {} info from rt, info: {}", component, component_info_json); - auto component_info = nlohmann::json::parse(component_info_json); - + auto component_info = + nlohmann::json::parse(component_info_json.toStdString()); if (!component_info.contains("name")) { GF_UI_LOG_WARN("illegal gnupg component info, json: {}", component_info_json); @@ -152,15 +148,16 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { for (auto& component : components) { auto options = Module::ListRTChildKeys( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - (boost::format("gnupg.components.%1%.options") % component).str()); + QString("gnupg.components.%1%.options").arg(component)); for (auto& option : options) { - const auto option_info = - nlohmann::json::parse(Module::RetrieveRTValueTypedOrDefault( + const auto option_info = nlohmann::json::parse( + Module::RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - (boost::format("gnupg.components.%1%.options.%2%") % component % - option) - .str(), - std::string{})); + QString("gnupg.components.%1%.options.%2%") + .arg(component) + .arg(option), + QString{}) + .toStdString()); if (!option_info.contains("name") || option_info.value("flags", "1") == "1") { continue; @@ -171,23 +168,23 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { ui_->configurationDetailsTable->setRowCount(row); row = 0; - std::string configuration_group; + QString configuration_group; for (auto& component : components) { auto options = Module::ListRTChildKeys( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - (boost::format("gnupg.components.%1%.options") % component).str()); + QString("gnupg.components.%1%.options").arg(component)); for (auto& option : options) { auto option_info_json = Module::RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - (boost::format("gnupg.components.%1%.options.%2%") % component % - option) - .str(), - std::string{}); + QString("gnupg.components.%1%.options.%2%") + .arg(component) + .arg(option), + QString{}); GF_UI_LOG_DEBUG("got gnupg component's option {} info from rt, info: {}", component, option_info_json); - auto option_info = nlohmann::json::parse(option_info_json); + auto option_info = nlohmann::json::parse(option_info_json.toStdString()); if (!option_info.contains("name")) { GF_UI_LOG_WARN("illegal gnupg configuation info, json: {}", @@ -196,16 +193,16 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { } if (option_info.value("flags", "1") == "1") { - configuration_group = option_info.value("name", ""); + configuration_group = + QString::fromStdString(option_info.value("name", "")); continue; } - auto* tmp0 = new QTableWidgetItem(QString::fromStdString(component)); + auto* tmp0 = new QTableWidgetItem(component); tmp0->setTextAlignment(Qt::AlignCenter); ui_->configurationDetailsTable->setItem(row, 0, tmp0); - auto* tmp1 = - new QTableWidgetItem(QString::fromStdString(configuration_group)); + auto* tmp1 = new QTableWidgetItem(configuration_group); tmp1->setTextAlignment(Qt::AlignCenter); ui_->configurationDetailsTable->setItem(row, 1, tmp1); diff --git a/src/ui/dialog/import_export/ExportKeyPackageDialog.cpp b/src/ui/dialog/import_export/ExportKeyPackageDialog.cpp index 66ecb3c9..62631905 100644 --- a/src/ui/dialog/import_export/ExportKeyPackageDialog.cpp +++ b/src/ui/dialog/import_export/ExportKeyPackageDialog.cpp @@ -28,8 +28,6 @@ #include "ExportKeyPackageDialog.h" -#include <boost/format.hpp> - #include "core/GpgModel.h" #include "core/function/KeyPackageOperator.h" #include "core/function/gpg/GpgKeyGetter.h" @@ -43,12 +41,10 @@ GpgFrontend::UI::ExportKeyPackageDialog::ExportKeyPackageDialog( key_ids_(std::move(key_ids)) { ui_->setupUi(this); - ui_->nameValueLabel->setText( - KeyPackageOperator::GenerateKeyPackageName().c_str()); + ui_->nameValueLabel->setText(KeyPackageOperator::GenerateKeyPackageName()); connect(ui_->gnerateNameButton, &QPushButton::clicked, this, [=]() { - ui_->nameValueLabel->setText( - KeyPackageOperator::GenerateKeyPackageName().c_str()); + ui_->nameValueLabel->setText(KeyPackageOperator::GenerateKeyPackageName()); }); connect(ui_->setOutputPathButton, &QPushButton::clicked, this, [=]() { @@ -116,7 +112,7 @@ GpgFrontend::UI::ExportKeyPackageDialog::ExportKeyPackageDialog( this, _("Generating"), [this, keys](const OperaWaitingHd& op_hd) { KeyPackageOperator::GenerateKeyPackage( ui_->outputPathLabel->text().toStdString(), - ui_->nameValueLabel->text().toStdString(), *keys, passphrase_, + ui_->nameValueLabel->text(), *keys, passphrase_, ui_->includeSecretKeyCheckBox->isChecked(), [=](GFError err, const DataObjectPtr&) { // stop waiting diff --git a/src/ui/dialog/import_export/ExportKeyPackageDialog.h b/src/ui/dialog/import_export/ExportKeyPackageDialog.h index 678db8ff..abf7a84c 100644 --- a/src/ui/dialog/import_export/ExportKeyPackageDialog.h +++ b/src/ui/dialog/import_export/ExportKeyPackageDialog.h @@ -55,6 +55,6 @@ class ExportKeyPackageDialog : public GeneralDialog { private: std::shared_ptr<Ui_exportKeyPackageDialog> ui_; ///< KeyIdArgsListPtr key_ids_; ///< - std::string passphrase_; ///< + QString passphrase_; ///< }; } // namespace GpgFrontend::UI diff --git a/src/ui/dialog/import_export/KeyImportDetailDialog.cpp b/src/ui/dialog/import_export/KeyImportDetailDialog.cpp index bf9b325f..7d1303ec 100644 --- a/src/ui/dialog/import_export/KeyImportDetailDialog.cpp +++ b/src/ui/dialog/import_export/KeyImportDetailDialog.cpp @@ -138,14 +138,11 @@ void KeyImportDetailDialog::create_keys_table() { keys_table_->setRowCount(row + 1); auto key = GpgKeyGetter::GetInstance().GetKey(imp_key.fpr); if (!key.IsGood()) continue; - keys_table_->setItem( - row, 0, new QTableWidgetItem(QString::fromStdString(key.GetName()))); - keys_table_->setItem( - row, 1, new QTableWidgetItem(QString::fromStdString(key.GetEmail()))); + keys_table_->setItem(row, 0, new QTableWidgetItem(key.GetName())); + keys_table_->setItem(row, 1, new QTableWidgetItem(key.GetEmail())); keys_table_->setItem( row, 2, new QTableWidgetItem(get_status_string(imp_key.import_status))); - keys_table_->setItem( - row, 3, new QTableWidgetItem(QString::fromStdString(imp_key.fpr))); + keys_table_->setItem(row, 3, new QTableWidgetItem(imp_key.fpr)); row++; } keys_table_->horizontalHeader()->setSectionResizeMode( diff --git a/src/ui/dialog/import_export/KeyServerImportDialog.cpp b/src/ui/dialog/import_export/KeyServerImportDialog.cpp index 53c9e5b6..313c2ed1 100644 --- a/src/ui/dialog/import_export/KeyServerImportDialog.cpp +++ b/src/ui/dialog/import_export/KeyServerImportDialog.cpp @@ -191,9 +191,8 @@ void KeyServerImportDialog::slot_search() { return; } - auto* task = new KeyServerSearchTask( - key_server_combo_box_->currentText().toStdString(), - search_line_edit_->text().toStdString()); + auto* task = new KeyServerSearchTask(key_server_combo_box_->currentText(), + search_line_edit_->text()); connect(task, &KeyServerSearchTask::SignalKeyServerSearchResult, this, &KeyServerImportDialog::slot_search_finished); @@ -381,27 +380,27 @@ void KeyServerImportDialog::slot_search_finished( } void KeyServerImportDialog::slot_import() { - std::vector<std::string> key_ids; + std::vector<QString> key_ids; const int row_count = keys_table_->rowCount(); for (int i = 0; i < row_count; ++i) { if (keys_table_->item(i, 2)->isSelected()) { QString keyid = keys_table_->item(i, 2)->text(); - key_ids.push_back(keyid.toStdString()); + key_ids.push_back(keyid); } } if (!key_ids.empty()) { - SlotImport(key_ids, key_server_combo_box_->currentText().toStdString()); + SlotImport(key_ids, key_server_combo_box_->currentText()); } } void KeyServerImportDialog::SlotImport(const KeyIdArgsListPtr& keys) { // keyserver host url - std::string target_keyserver; + QString target_keyserver; if (key_server_combo_box_ != nullptr) { - target_keyserver = key_server_combo_box_->currentText().toStdString(); + target_keyserver = key_server_combo_box_->currentText(); } - if (target_keyserver.empty()) { + if (target_keyserver.isEmpty()) { try { SettingsObject key_server_json("key_server"); const auto key_server_list = @@ -415,7 +414,7 @@ void KeyServerImportDialog::SlotImport(const KeyIdArgsListPtr& keys) { auto default_key_server = key_server_list[default_key_server_index].get<std::string>(); - target_keyserver = default_key_server; + target_keyserver = QString::fromStdString(default_key_server); } catch (...) { GF_UI_LOG_ERROR("setting operation error", "server_list", "default_server"); @@ -426,15 +425,15 @@ void KeyServerImportDialog::SlotImport(const KeyIdArgsListPtr& keys) { return; } } - std::vector<std::string> key_ids; + std::vector<QString> key_ids; for (const auto& key_id : *keys) { key_ids.push_back(key_id); } SlotImport(key_ids, target_keyserver); } -void KeyServerImportDialog::SlotImport(std::vector<std::string> key_ids, - std::string keyserver_url) { +void KeyServerImportDialog::SlotImport(std::vector<QString> key_ids, + QString keyserver_url) { auto* task = new KeyServerImportTask(std::move(keyserver_url), std::move(key_ids)); diff --git a/src/ui/dialog/import_export/KeyServerImportDialog.h b/src/ui/dialog/import_export/KeyServerImportDialog.h index bbd4634a..564b0878 100644 --- a/src/ui/dialog/import_export/KeyServerImportDialog.h +++ b/src/ui/dialog/import_export/KeyServerImportDialog.h @@ -70,8 +70,7 @@ class KeyServerImportDialog : public GeneralDialog { * @param keyIds * @param keyserverUrl */ - void SlotImport(std::vector<std::string> key_ids_list, - std::string keyserver_url); + void SlotImport(std::vector<QString> key_ids_list, QString keyserver_url); signals: @@ -155,7 +154,6 @@ class KeyServerImportDialog : public GeneralDialog { */ QComboBox* create_combo_box(); - QHBoxLayout* message_layout_; ///< QLineEdit* search_line_edit_{}; ///< diff --git a/src/ui/dialog/import_export/KeyUploadDialog.cpp b/src/ui/dialog/import_export/KeyUploadDialog.cpp index ed46fe9d..4d36654e 100644 --- a/src/ui/dialog/import_export/KeyUploadDialog.cpp +++ b/src/ui/dialog/import_export/KeyUploadDialog.cpp @@ -85,7 +85,7 @@ void KeyUploadDialog::SlotUpload() { void KeyUploadDialog::slot_upload_key_to_server( const GpgFrontend::GFBuffer& keys_data) { - std::string target_keyserver; + QString target_keyserver; try { SettingsObject key_server_json("key_server"); @@ -99,8 +99,8 @@ void KeyUploadDialog::slot_upload_key_to_server( throw std::runtime_error("default_server index out of range"); } - target_keyserver = - key_server_list[default_key_server_index].get<std::string>(); + target_keyserver = QString::fromStdString( + key_server_list[default_key_server_index].get<std::string>()); GF_UI_LOG_DEBUG("set target key server to default key server: {}", target_keyserver); @@ -113,30 +113,29 @@ void KeyUploadDialog::slot_upload_key_to_server( return; } - QUrl req_url(QString::fromStdString(target_keyserver + "/pks/add")); + QUrl req_url(target_keyserver + "/pks/add"); auto* qnam = new QNetworkAccessManager(this); // Building Post Data QByteArray post_data; - auto data = keys_data.ConvertToStdString(); + auto data = keys_data.ConvertToQByteArray(); - boost::algorithm::replace_all(data, "\n", "%0A"); - boost::algorithm::replace_all(data, "\r", "%0D"); - boost::algorithm::replace_all(data, "(", "%28"); - boost::algorithm::replace_all(data, ")", "%29"); - boost::algorithm::replace_all(data, "/", "%2F"); - boost::algorithm::replace_all(data, ":", "%3A"); - boost::algorithm::replace_all(data, "+", "%2B"); - boost::algorithm::replace_all(data, "=", "%3D"); - boost::algorithm::replace_all(data, " ", "+"); + data.replace("\n", "%0A"); + data.replace("\r", "%0D"); + data.replace("(", "%28"); + data.replace(")", "%29"); + data.replace("/", "%2F"); + data.replace(":", "%3A"); + data.replace("+", "%2B"); + data.replace("=", "%3D"); + data.replace(" ", "+"); QNetworkRequest request(req_url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - post_data.append("keytext").append("=").append( - QString::fromStdString(data).toUtf8()); + post_data.append("keytext").append("=").append(data); // Send Post Data QNetworkReply* reply = qnam->post(request, post_data); @@ -174,11 +173,11 @@ void KeyUploadDialog::slot_upload_finished() { } QMessageBox::critical(this, "Upload Failed", message); return; - } else { - QMessageBox::information(this, _("Upload Success"), - _("Upload Public Key Successfully")); - GF_UI_LOG_DEBUG("success while contacting keyserver!"); } + QMessageBox::information(this, _("Upload Success"), + _("Upload Public Key Successfully")); + GF_UI_LOG_DEBUG("success while contacting keyserver!"); + reply->deleteLater(); } diff --git a/src/ui/dialog/key_generate/KeygenDialog.cpp b/src/ui/dialog/key_generate/KeygenDialog.cpp index 30f9b6df..27281b3c 100644 --- a/src/ui/dialog/key_generate/KeygenDialog.cpp +++ b/src/ui/dialog/key_generate/KeygenDialog.cpp @@ -117,9 +117,9 @@ void KeyGenDialog::slot_key_gen_accept() { /** * create the string for key generation */ - gen_key_info_->SetName(name_edit_->text().toStdString()); - gen_key_info_->SetEmail(email_edit_->text().toStdString()); - gen_key_info_->SetComment(comment_edit_->text().toStdString()); + gen_key_info_->SetName(name_edit_->text()); + gen_key_info_->SetEmail(email_edit_->text()); + gen_key_info_->SetComment(comment_edit_->text()); gen_key_info_->SetKeyLength(key_size_spin_box_->value()); @@ -263,10 +263,10 @@ void KeyGenDialog::slot_activated_key_type(int index) { const auto [name, key_algo, subkey_algo] = gen_key_info_->GetSupportedKeyAlgo()[index]; - assert(!key_algo.empty()); + assert(!key_algo.isEmpty()); gen_key_info_->SetAlgo(key_algo); - if (!subkey_algo.empty()) { + if (!subkey_algo.isEmpty()) { if (gen_subkey_info_ == nullptr) { gen_subkey_info_ = SecureCreateSharedObject<GenKeyInfo>(true); } @@ -393,7 +393,7 @@ QGroupBox* KeyGenDialog::create_basic_info_group_box() { key_type_combo_box_ = new QComboBox(this); for (const auto& algo : GenKeyInfo::GetSupportedKeyAlgo()) { - key_type_combo_box_->addItem(QString::fromStdString(std::get<0>(algo))); + key_type_combo_box_->addItem(std::get<0>(algo)); } if (!GenKeyInfo::GetSupportedKeyAlgo().empty()) { key_type_combo_box_->setCurrentIndex(0); diff --git a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp index 912945ad..2d995255 100644 --- a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp +++ b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp @@ -124,7 +124,7 @@ QGroupBox* SubkeyGenerateDialog::create_basic_info_group_box() { no_pass_phrase_check_box_ = new QCheckBox(this); for (const auto& algo : GenKeyInfo::GetSupportedSubkeyAlgo()) { - key_type_combo_box_->addItem(QString::fromStdString(std::get<0>(algo))); + key_type_combo_box_->addItem(std::get<0>(algo)); } if (!GenKeyInfo::GetSupportedSubkeyAlgo().empty()) { key_type_combo_box_->setCurrentIndex(0); diff --git a/src/ui/dialog/keypair_details/KeyNewUIDDialog.cpp b/src/ui/dialog/keypair_details/KeyNewUIDDialog.cpp index 71a2c14b..a548c18d 100644 --- a/src/ui/dialog/keypair_details/KeyNewUIDDialog.cpp +++ b/src/ui/dialog/keypair_details/KeyNewUIDDialog.cpp @@ -90,12 +90,12 @@ void KeyNewUIDDialog::slot_create_new_uid() { auto error_string = error_stream.str(); if (error_string.empty()) { if (GpgUIDOperator::GetInstance().AddUID( - m_key_, name_->text().toStdString(), comment_->text().toStdString(), - email_->text().toStdString())) { + m_key_, name_->text(), comment_->text(), email_->text())) { emit finished(1); emit SignalUIDCreated(); - } else + } else { emit finished(-1); + } } else { /** diff --git a/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp b/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp index 673ff889..2770f9af 100644 --- a/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairDetailTab.cpp @@ -30,18 +30,13 @@ #include "core/GpgModel.h" #include "core/function/gpg/GpgKeyGetter.h" -#include "core/function/gpg/GpgKeyImportExporter.h" #include "core/model/GpgKey.h" #include "core/utils/CommonUtils.h" #include "ui/UISignalStation.h" -#include "ui/dialog/WaitingDialog.h" namespace GpgFrontend::UI { -KeyPairDetailTab::KeyPairDetailTab(const std::string& key_id, QWidget* parent) +KeyPairDetailTab::KeyPairDetailTab(const QString& key_id, QWidget* parent) : QWidget(parent), key_(GpgKeyGetter::GetInstance().GetKey(key_id)) { - GF_UI_LOG_DEBUG(key_.GetEmail(), key_.IsPrivateKey(), key_.IsHasMasterKey(), - key_.GetSubKeys()->front().IsPrivateKey()); - owner_box_ = new QGroupBox(_("Owner")); key_box_ = new QGroupBox(_("Primary Key")); fingerprint_box_ = new QGroupBox(_("Fingerprint")); @@ -69,56 +64,56 @@ KeyPairDetailTab::KeyPairDetailTab(const std::string& key_id, QWidget* parent) primary_key_exist_var_label_ = new QLabel(); auto* mvbox = new QVBoxLayout(); - auto* vboxKD = new QGridLayout(); - auto* vboxOD = new QGridLayout(); - - vboxOD->addWidget(new QLabel(QString(_("Name")) + ": "), 0, 0); - vboxOD->addWidget(new QLabel(QString(_("Email Address")) + ": "), 1, 0); - vboxOD->addWidget(new QLabel(QString(_("Comment")) + ": "), 2, 0); - vboxOD->addWidget(name_var_label_, 0, 1); - vboxOD->addWidget(email_var_label_, 1, 1); - vboxOD->addWidget(comment_var_label_, 2, 1); - - vboxKD->addWidget(new QLabel(QString(_("Key ID")) + ": "), 0, 0); - vboxKD->addWidget(new QLabel(QString(_("Algorithm")) + ": "), 1, 0); - vboxKD->addWidget(new QLabel(QString(_("Key Size")) + ": "), 2, 0); - vboxKD->addWidget(new QLabel(QString(_("Nominal Usage")) + ": "), 3, 0); - vboxKD->addWidget(new QLabel(QString(_("Actual Usage")) + ": "), 4, 0); - vboxKD->addWidget(new QLabel(QString(_("Owner Trust Level")) + ": "), 5, 0); - vboxKD->addWidget(new QLabel(QString(_("Create Date (Local Time)")) + ": "), - 6, 0); - vboxKD->addWidget(new QLabel(QString(_("Expires on (Local Time)")) + ": "), 7, - 0); - vboxKD->addWidget(new QLabel(QString(_("Last Update (Local Time)")) + ": "), - 8, 0); - vboxKD->addWidget(new QLabel(QString(_("Primary Key Existence")) + ": "), 9, - 0); + auto* vbox_kd = new QGridLayout(); + auto* vbox_od = new QGridLayout(); + + vbox_od->addWidget(new QLabel(QString(_("Name")) + ": "), 0, 0); + vbox_od->addWidget(new QLabel(QString(_("Email Address")) + ": "), 1, 0); + vbox_od->addWidget(new QLabel(QString(_("Comment")) + ": "), 2, 0); + vbox_od->addWidget(name_var_label_, 0, 1); + vbox_od->addWidget(email_var_label_, 1, 1); + vbox_od->addWidget(comment_var_label_, 2, 1); + + vbox_kd->addWidget(new QLabel(QString(_("Key ID")) + ": "), 0, 0); + vbox_kd->addWidget(new QLabel(QString(_("Algorithm")) + ": "), 1, 0); + vbox_kd->addWidget(new QLabel(QString(_("Key Size")) + ": "), 2, 0); + vbox_kd->addWidget(new QLabel(QString(_("Nominal Usage")) + ": "), 3, 0); + vbox_kd->addWidget(new QLabel(QString(_("Actual Usage")) + ": "), 4, 0); + vbox_kd->addWidget(new QLabel(QString(_("Owner Trust Level")) + ": "), 5, 0); + vbox_kd->addWidget(new QLabel(QString(_("Create Date (Local Time)")) + ": "), + 6, 0); + vbox_kd->addWidget(new QLabel(QString(_("Expires on (Local Time)")) + ": "), + 7, 0); + vbox_kd->addWidget(new QLabel(QString(_("Last Update (Local Time)")) + ": "), + 8, 0); + vbox_kd->addWidget(new QLabel(QString(_("Primary Key Existence")) + ": "), 9, + 0); key_id_var_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - vboxKD->addWidget(key_id_var_label, 0, 1, 1, 1); - vboxKD->addWidget(algorithm_var_label_, 1, 1, 1, 2); - vboxKD->addWidget(key_size_var_label_, 2, 1, 1, 2); - vboxKD->addWidget(usage_var_label_, 3, 1, 1, 2); - vboxKD->addWidget(actual_usage_var_label_, 4, 1, 1, 2); - vboxKD->addWidget(owner_trust_var_label_, 5, 1, 1, 2); - vboxKD->addWidget(created_var_label_, 6, 1, 1, 2); - vboxKD->addWidget(expire_var_label_, 7, 1, 1, 2); - vboxKD->addWidget(last_update_var_label_, 8, 1, 1, 2); - vboxKD->addWidget(primary_key_exist_var_label_, 9, 1, 1, 2); - - auto* copyKeyIdButton = new QPushButton(_("Copy")); - copyKeyIdButton->setFlat(true); - copyKeyIdButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - vboxKD->addWidget(copyKeyIdButton, 0, 2); - connect(copyKeyIdButton, &QPushButton::clicked, this, [=]() { + vbox_kd->addWidget(key_id_var_label, 0, 1, 1, 1); + vbox_kd->addWidget(algorithm_var_label_, 1, 1, 1, 2); + vbox_kd->addWidget(key_size_var_label_, 2, 1, 1, 2); + vbox_kd->addWidget(usage_var_label_, 3, 1, 1, 2); + vbox_kd->addWidget(actual_usage_var_label_, 4, 1, 1, 2); + vbox_kd->addWidget(owner_trust_var_label_, 5, 1, 1, 2); + vbox_kd->addWidget(created_var_label_, 6, 1, 1, 2); + vbox_kd->addWidget(expire_var_label_, 7, 1, 1, 2); + vbox_kd->addWidget(last_update_var_label_, 8, 1, 1, 2); + vbox_kd->addWidget(primary_key_exist_var_label_, 9, 1, 1, 2); + + auto* copy_key_id_button = new QPushButton(_("Copy")); + copy_key_id_button->setFlat(true); + copy_key_id_button->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + vbox_kd->addWidget(copy_key_id_button, 0, 2); + connect(copy_key_id_button, &QPushButton::clicked, this, [=]() { QString fpr = key_id_var_label->text().trimmed(); QClipboard* cb = QApplication::clipboard(); cb->setText(fpr); }); - owner_box_->setLayout(vboxOD); + owner_box_->setLayout(vbox_od); mvbox->addWidget(owner_box_); - key_box_->setLayout(vboxKD); + key_box_->setLayout(vbox_kd); mvbox->addWidget(key_box_); fingerprint_var_label_ = new QLabel(); @@ -126,21 +121,21 @@ KeyPairDetailTab::KeyPairDetailTab(const std::string& key_id, QWidget* parent) fingerprint_var_label_->setTextInteractionFlags(Qt::TextSelectableByMouse); fingerprint_var_label_->setStyleSheet("margin-left: 0; margin-right: 5;"); fingerprint_var_label_->setAlignment(Qt::AlignCenter); - auto* hboxFP = new QHBoxLayout(); + auto* hbox_fp = new QHBoxLayout(); - hboxFP->addStretch(); - hboxFP->addWidget(fingerprint_var_label_); + hbox_fp->addStretch(); + hbox_fp->addWidget(fingerprint_var_label_); - auto* copyFingerprintButton = new QPushButton(_("Copy")); - copyFingerprintButton->setFlat(true); - copyFingerprintButton->setToolTip(_("copy fingerprint to clipboard")); - connect(copyFingerprintButton, &QPushButton::clicked, this, + auto* copy_fingerprint_button = new QPushButton(_("Copy")); + copy_fingerprint_button->setFlat(true); + copy_fingerprint_button->setToolTip(_("copy fingerprint to clipboard")); + connect(copy_fingerprint_button, &QPushButton::clicked, this, &KeyPairDetailTab::slot_copy_fingerprint); - hboxFP->addWidget(copyFingerprintButton); - hboxFP->addStretch(); + hbox_fp->addWidget(copy_fingerprint_button); + hbox_fp->addStretch(); - fingerprint_box_->setLayout(hboxFP); + fingerprint_box_->setLayout(hbox_fp); mvbox->addWidget(fingerprint_box_); mvbox->addStretch(); @@ -193,50 +188,59 @@ void KeyPairDetailTab::slot_refresh_key_info() { } if (key_.IsExpired()) { - auto paletteExpired = expire_var_label_->palette(); - paletteExpired.setColor(expire_var_label_->foregroundRole(), Qt::red); - expire_var_label_->setPalette(paletteExpired); + auto palette_expired = expire_var_label_->palette(); + palette_expired.setColor(expire_var_label_->foregroundRole(), Qt::red); + expire_var_label_->setPalette(palette_expired); } else { - auto paletteValid = expire_var_label_->palette(); - paletteValid.setColor(expire_var_label_->foregroundRole(), Qt::darkGreen); - expire_var_label_->setPalette(paletteValid); + auto palette_valid = expire_var_label_->palette(); + palette_valid.setColor(expire_var_label_->foregroundRole(), Qt::darkGreen); + expire_var_label_->setPalette(palette_valid); } - name_var_label_->setText(QString::fromStdString(key_.GetName())); - email_var_label_->setText(QString::fromStdString(key_.GetEmail())); + name_var_label_->setText(key_.GetName()); + email_var_label_->setText(key_.GetEmail()); - comment_var_label_->setText(QString::fromStdString(key_.GetComment())); - key_id_var_label->setText(QString::fromStdString(key_.GetId())); + comment_var_label_->setText(key_.GetComment()); + key_id_var_label->setText(key_.GetId()); - std::stringstream usage_steam; + QString buffer; + QTextStream usage_steam(&buffer); - if (key_.IsHasCertificationCapability()) + if (key_.IsHasCertificationCapability()) { usage_steam << _("Certificate") << " "; + } if (key_.IsHasEncryptionCapability()) usage_steam << _("Encrypt") << " "; if (key_.IsHasSigningCapability()) usage_steam << _("Sign") << " "; if (key_.IsHasAuthenticationCapability()) usage_steam << _("Auth") << " "; - usage_var_label_->setText(usage_steam.str().c_str()); + usage_var_label_->setText(usage_steam.readAll()); - std::stringstream actual_usage_steam; + QString buffer_2; + QTextStream actual_usage_steam(&buffer_2); - if (key_.IsHasActualCertificationCapability()) + if (key_.IsHasActualCertificationCapability()) { actual_usage_steam << _("Certificate") << " "; - if (key_.IsHasActualEncryptionCapability()) + } + if (key_.IsHasActualEncryptionCapability()) { actual_usage_steam << _("Encrypt") << " "; - if (key_.IsHasActualSigningCapability()) + } + if (key_.IsHasActualSigningCapability()) { actual_usage_steam << _("Sign") << " "; - if (key_.IsHasActualAuthenticationCapability()) + } + if (key_.IsHasActualAuthenticationCapability()) { actual_usage_steam << _("Auth") << " "; + } - actual_usage_var_label_->setText( - QString::fromStdString(actual_usage_steam.str())); - owner_trust_var_label_->setText(QString::fromStdString(key_.GetOwnerTrust())); + actual_usage_var_label_->setText(actual_usage_steam.readAll()); + owner_trust_var_label_->setText(key_.GetOwnerTrust()); - std::string key_size_val, key_expire_val, key_create_time_val, key_algo_val, - key_last_update_val; + QString key_size_val; + QString key_expire_val; + QString key_create_time_val; + QString key_algo_val; + QString key_last_update_val; - key_size_val = std::to_string(key_.GetPrimaryKeyLength()); + key_size_val = QString::number(key_.GetPrimaryKeyLength()); if (to_time_t(boost::posix_time::ptime(key_.GetExpireTime())) == 0) { expire_var_label_->setText(_("Never Expire")); @@ -272,10 +276,9 @@ void KeyPairDetailTab::slot_refresh_key_info() { #endif } - key_size_var_label_->setText(key_size_val.c_str()); - algorithm_var_label_->setText(key_algo_val.c_str()); - fingerprint_var_label_->setText( - BeautifyFingerprint(key_.GetFingerprint()).c_str()); + key_size_var_label_->setText(key_size_val); + algorithm_var_label_->setText(key_algo_val); + fingerprint_var_label_->setText(BeautifyFingerprint(key_.GetFingerprint())); icon_label_->hide(); exp_label_->hide(); diff --git a/src/ui/dialog/keypair_details/KeyPairDetailTab.h b/src/ui/dialog/keypair_details/KeyPairDetailTab.h index f134af3f..b12f108c 100644 --- a/src/ui/dialog/keypair_details/KeyPairDetailTab.h +++ b/src/ui/dialog/keypair_details/KeyPairDetailTab.h @@ -92,8 +92,7 @@ class KeyPairDetailTab : public QWidget { * @param key_id * @param parent */ - explicit KeyPairDetailTab(const std::string& key_id, - QWidget* parent = nullptr); + explicit KeyPairDetailTab(const QString& key_id, QWidget* parent = nullptr); }; } // namespace GpgFrontend::UI diff --git a/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp b/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp index 4a1d0f8c..df5fc77b 100644 --- a/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairOperaTab.cpp @@ -42,16 +42,16 @@ namespace GpgFrontend::UI { -KeyPairOperaTab::KeyPairOperaTab(const std::string& key_id, QWidget* parent) +KeyPairOperaTab::KeyPairOperaTab(const QString& key_id, QWidget* parent) : QWidget(parent), m_key_(GpgKeyGetter::GetInstance().GetKey(key_id)) { // Set Menu CreateOperaMenu(); - auto m_vbox = new QVBoxLayout(this); + auto* m_vbox = new QVBoxLayout(this); auto* opera_key_box = new QGroupBox(_("General Operations")); auto* vbox_p_k = new QVBoxLayout(); - auto export_h_box_layout = new QHBoxLayout(); + auto* export_h_box_layout = new QHBoxLayout(); vbox_p_k->addLayout(export_h_box_layout); auto* export_public_button = new QPushButton(_("Export Public Key")); @@ -79,7 +79,7 @@ KeyPairOperaTab::KeyPairOperaTab(const std::string& key_id, QWidget* parent) } } - auto advance_h_box_layout = new QHBoxLayout(); + auto* advance_h_box_layout = new QHBoxLayout(); // get settings auto& settings = GlobalSettingStation::GetInstance().GetMainSettings(); @@ -135,23 +135,24 @@ KeyPairOperaTab::KeyPairOperaTab(const std::string& key_id, QWidget* parent) void KeyPairOperaTab::CreateOperaMenu() { key_server_opera_menu_ = new QMenu(this); - auto* uploadKeyPair = new QAction(_("Upload Key Pair to Key Server"), this); - connect(uploadKeyPair, &QAction::triggered, this, + auto* upload_key_pair = new QAction(_("Upload Key Pair to Key Server"), this); + connect(upload_key_pair, &QAction::triggered, this, &KeyPairOperaTab::slot_upload_key_to_server); - if (!(m_key_.IsPrivateKey() && m_key_.IsHasMasterKey())) - uploadKeyPair->setDisabled(true); + if (!(m_key_.IsPrivateKey() && m_key_.IsHasMasterKey())) { + upload_key_pair->setDisabled(true); + } - auto* updateKeyPair = new QAction(_("Sync Key Pair From Key Server"), this); - connect(updateKeyPair, &QAction::triggered, this, + auto* update_key_pair = new QAction(_("Sync Key Pair From Key Server"), this); + connect(update_key_pair, &QAction::triggered, this, &KeyPairOperaTab::slot_update_key_from_server); // when a key has primary key, it should always upload to keyserver. if (m_key_.IsHasMasterKey()) { - updateKeyPair->setDisabled(true); + update_key_pair->setDisabled(true); } - key_server_opera_menu_->addAction(uploadKeyPair); - key_server_opera_menu_->addAction(updateKeyPair); + key_server_opera_menu_->addAction(upload_key_pair); + key_server_opera_menu_->addAction(update_key_pair); secret_key_export_opera_menu_ = new QMenu(this); @@ -187,18 +188,16 @@ void KeyPairOperaTab::slot_export_public_key() { #endif std::replace(file_string.begin(), file_string.end(), ' ', '_'); - auto file_name = - QFileDialog::getSaveFileName( - this, _("Export Key To File"), QString::fromStdString(file_string), - QString(_("Key Files")) + " (*.asc *.txt);;All Files (*)") - .toStdString(); + auto file_name = QFileDialog::getSaveFileName( + this, _("Export Key To File"), file_string, + QString(_("Key Files")) + " (*.asc *.txt);;All Files (*)"); - if (file_name.empty()) return; + if (file_name.isEmpty()) return; if (!WriteFileGFBuffer(file_name, gf_buffer)) { QMessageBox::critical( this, _("Export Error"), - QString(_("Couldn't open %1 for writing")).arg(file_name.c_str())); + QString(_("Couldn't open %1 for writing")).arg(file_name)); return; } } @@ -236,18 +235,16 @@ void KeyPairOperaTab::slot_export_short_private_key() { #endif std::replace(file_string.begin(), file_string.end(), ' ', '_'); - auto file_name = - QFileDialog::getSaveFileName( - this, _("Export Key To File"), QString::fromStdString(file_string), - QString(_("Key Files")) + " (*.asc *.txt);;All Files (*)") - .toStdString(); + auto file_name = QFileDialog::getSaveFileName( + this, _("Export Key To File"), file_string, + QString(_("Key Files")) + " (*.asc *.txt);;All Files (*)"); - if (file_name.empty()) return; + if (file_name.isEmpty()) return; if (!WriteFileGFBuffer(file_name, gf_buffer)) { QMessageBox::critical( this, _("Export Error"), - QString(_("Couldn't open %1 for writing")).arg(file_name.c_str())); + QString(_("Couldn't open %1 for writing")).arg(file_name)); return; } } @@ -282,18 +279,16 @@ void KeyPairOperaTab::slot_export_private_key() { #endif std::replace(file_string.begin(), file_string.end(), ' ', '_'); - auto file_name = - QFileDialog::getSaveFileName( - this, _("Export Key To File"), QString::fromStdString(file_string), - QString(_("Key Files")) + " (*.asc *.txt);;All Files (*)") - .toStdString(); + auto file_name = QFileDialog::getSaveFileName( + this, _("Export Key To File"), file_string, + QString(_("Key Files")) + " (*.asc *.txt);;All Files (*)"); - if (file_name.empty()) return; + if (file_name.isEmpty()) return; if (!WriteFileGFBuffer(file_name, gf_buffer)) { QMessageBox::critical( this, _("Export Error"), - QString(_("Couldn't open %1 for writing")).arg(file_name.c_str())); + QString(_("Couldn't open %1 for writing")).arg(file_name)); return; } } @@ -332,16 +327,15 @@ void KeyPairOperaTab::slot_gen_revoke_cert() { m_key_.GetId() + ").rev"; #endif - QFileDialog dialog(this, "Generate revocation certificate", - QString::fromStdString(file_string), literal); + QFileDialog dialog(this, _("Generate revocation certificate"), file_string, + literal); dialog.setDefaultSuffix(".rev"); dialog.setAcceptMode(QFileDialog::AcceptSave); if (dialog.exec() != 0) m_output_file_name = dialog.selectedFiles().front(); if (!m_output_file_name.isEmpty()) { - GpgKeyOpera::GetInstance().GenerateRevokeCert( - m_key_, m_output_file_name.toStdString()); + GpgKeyOpera::GetInstance().GenerateRevokeCert(m_key_, m_output_file_name); } } diff --git a/src/ui/dialog/keypair_details/KeyPairOperaTab.h b/src/ui/dialog/keypair_details/KeyPairOperaTab.h index 4dee9e8d..100d4a69 100644 --- a/src/ui/dialog/keypair_details/KeyPairOperaTab.h +++ b/src/ui/dialog/keypair_details/KeyPairOperaTab.h @@ -42,7 +42,7 @@ class KeyPairOperaTab : public QWidget { * @param key_id * @param parent */ - KeyPairOperaTab(const std::string& key_id, QWidget* parent); + KeyPairOperaTab(const QString& key_id, QWidget* parent); /** * @brief Create a Opera Menu object diff --git a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp index f6a5410e..3281d0b8 100644 --- a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.cpp @@ -35,52 +35,50 @@ namespace GpgFrontend::UI { -KeyPairSubkeyTab::KeyPairSubkeyTab(const std::string& key_id, QWidget* parent) +KeyPairSubkeyTab::KeyPairSubkeyTab(const QString& key_id, QWidget* parent) : QWidget(parent), key_(GpgKeyGetter::GetInstance().GetKey(key_id)) { - GF_UI_LOG_DEBUG(key_.GetEmail(), key_.IsPrivateKey(), key_.IsHasMasterKey(), - key_.GetSubKeys()->front().IsPrivateKey()); - create_subkey_list(); create_subkey_opera_menu(); list_box_ = new QGroupBox(_("Subkey List")); detail_box_ = new QGroupBox(_("Detail of Selected Subkey")); - auto uidButtonsLayout = new QGridLayout(); + auto* uid_buttons_layout = new QGridLayout(); - auto addSubkeyButton = new QPushButton(_("Generate A New Subkey")); + auto* add_subkey_button = new QPushButton(_("Generate A New Subkey")); if (!key_.IsPrivateKey() || !key_.IsHasMasterKey()) { - addSubkeyButton->setDisabled(true); - setHidden(addSubkeyButton); + add_subkey_button->setDisabled(true); + setHidden(add_subkey_button); } - uidButtonsLayout->addWidget(addSubkeyButton, 0, 1); + uid_buttons_layout->addWidget(add_subkey_button, 0, 1); - auto* baseLayout = new QVBoxLayout(); + auto* base_layout = new QVBoxLayout(); - auto subkeyListLayout = new QGridLayout(); - subkeyListLayout->addWidget(subkey_list_, 0, 0); - subkeyListLayout->addLayout(uidButtonsLayout, 1, 0); - subkeyListLayout->setContentsMargins(0, 10, 0, 0); + auto* subkey_list_layout = new QGridLayout(); + subkey_list_layout->addWidget(subkey_list_, 0, 0); + subkey_list_layout->addLayout(uid_buttons_layout, 1, 0); + subkey_list_layout->setContentsMargins(0, 10, 0, 0); - auto* subkeyDetailLayout = new QGridLayout(); + auto* subkey_detail_layout = new QGridLayout(); - subkeyDetailLayout->addWidget(new QLabel(QString(_("Key ID")) + ": "), 0, 0); - subkeyDetailLayout->addWidget(new QLabel(QString(_("Algorithm")) + ": "), 1, - 0); - subkeyDetailLayout->addWidget(new QLabel(QString(_("Key Size")) + ": "), 2, - 0); - subkeyDetailLayout->addWidget(new QLabel(QString(_("Usage")) + ": "), 3, 0); - subkeyDetailLayout->addWidget( + subkey_detail_layout->addWidget(new QLabel(QString(_("Key ID")) + ": "), 0, + 0); + subkey_detail_layout->addWidget(new QLabel(QString(_("Algorithm")) + ": "), 1, + 0); + subkey_detail_layout->addWidget(new QLabel(QString(_("Key Size")) + ": "), 2, + 0); + subkey_detail_layout->addWidget(new QLabel(QString(_("Usage")) + ": "), 3, 0); + subkey_detail_layout->addWidget( new QLabel(QString(_("Expires On (Local Time)")) + ": "), 4, 0); - subkeyDetailLayout->addWidget( + subkey_detail_layout->addWidget( new QLabel(QString(_("Create Date (Local Time)")) + ": "), 5, 0); - subkeyDetailLayout->addWidget(new QLabel(QString(_("Existence")) + ": "), 6, - 0); - subkeyDetailLayout->addWidget( + subkey_detail_layout->addWidget(new QLabel(QString(_("Existence")) + ": "), 6, + 0); + subkey_detail_layout->addWidget( new QLabel(QString(_("Key in Smart Card")) + ": "), 7, 0); - subkeyDetailLayout->addWidget(new QLabel(QString(_("Fingerprint")) + ": "), 8, - 0); + subkey_detail_layout->addWidget(new QLabel(QString(_("Fingerprint")) + ": "), + 8, 0); key_id_var_label_ = new QLabel(this); key_size_var_label_ = new QLabel(this); @@ -92,34 +90,34 @@ KeyPairSubkeyTab::KeyPairSubkeyTab(const std::string& key_id, QWidget* parent) fingerprint_var_label_ = new QLabel(this); card_key_label_ = new QLabel(this); - subkeyDetailLayout->addWidget(key_id_var_label_, 0, 1, 1, 1); - subkeyDetailLayout->addWidget(key_size_var_label_, 2, 1, 1, 2); - subkeyDetailLayout->addWidget(expire_var_label_, 4, 1, 1, 2); - subkeyDetailLayout->addWidget(algorithm_var_label_, 1, 1, 1, 2); - subkeyDetailLayout->addWidget(created_var_label_, 5, 1, 1, 2); - subkeyDetailLayout->addWidget(usage_var_label_, 3, 1, 1, 2); - subkeyDetailLayout->addWidget(master_key_exist_var_label_, 6, 1, 1, 2); - subkeyDetailLayout->addWidget(card_key_label_, 7, 1, 1, 2); - subkeyDetailLayout->addWidget(fingerprint_var_label_, 8, 1, 1, 2); - - auto* copyKeyIdButton = new QPushButton(_("Copy")); - copyKeyIdButton->setFlat(true); - subkeyDetailLayout->addWidget(copyKeyIdButton, 0, 2); - connect(copyKeyIdButton, &QPushButton::clicked, this, [=]() { + subkey_detail_layout->addWidget(key_id_var_label_, 0, 1, 1, 1); + subkey_detail_layout->addWidget(key_size_var_label_, 2, 1, 1, 2); + subkey_detail_layout->addWidget(expire_var_label_, 4, 1, 1, 2); + subkey_detail_layout->addWidget(algorithm_var_label_, 1, 1, 1, 2); + subkey_detail_layout->addWidget(created_var_label_, 5, 1, 1, 2); + subkey_detail_layout->addWidget(usage_var_label_, 3, 1, 1, 2); + subkey_detail_layout->addWidget(master_key_exist_var_label_, 6, 1, 1, 2); + subkey_detail_layout->addWidget(card_key_label_, 7, 1, 1, 2); + subkey_detail_layout->addWidget(fingerprint_var_label_, 8, 1, 1, 2); + + auto* copy_key_id_button = new QPushButton(_("Copy")); + copy_key_id_button->setFlat(true); + subkey_detail_layout->addWidget(copy_key_id_button, 0, 2); + connect(copy_key_id_button, &QPushButton::clicked, this, [=]() { QString fpr = key_id_var_label_->text().trimmed(); QClipboard* cb = QApplication::clipboard(); cb->setText(fpr); }); - list_box_->setLayout(subkeyListLayout); + list_box_->setLayout(subkey_list_layout); list_box_->setContentsMargins(0, 12, 0, 0); - detail_box_->setLayout(subkeyDetailLayout); + detail_box_->setLayout(subkey_detail_layout); - baseLayout->addWidget(list_box_); - baseLayout->addWidget(detail_box_); - baseLayout->addStretch(); + base_layout->addWidget(list_box_); + base_layout->addWidget(detail_box_); + base_layout->addStretch(); - connect(addSubkeyButton, &QPushButton::clicked, this, + connect(add_subkey_button, &QPushButton::clicked, this, &KeyPairSubkeyTab::slot_add_subkey); connect(subkey_list_, &QTableWidget::itemSelectionChanged, this, &KeyPairSubkeyTab::slot_refresh_subkey_detail); @@ -132,9 +130,9 @@ KeyPairSubkeyTab::KeyPairSubkeyTab(const std::string& key_id, QWidget* parent) &UISignalStation::SignalKeyDatabaseRefreshDone, this, &KeyPairSubkeyTab::slot_refresh_subkey_list); - baseLayout->setContentsMargins(0, 0, 0, 0); + base_layout->setContentsMargins(0, 0, 0, 0); - setLayout(baseLayout); + setLayout(base_layout); setAttribute(Qt::WA_DeleteOnClose, true); slot_refresh_subkey_list(); @@ -184,7 +182,7 @@ void KeyPairSubkeyTab::slot_refresh_subkey_list() { subkey_list_->setRowCount(buffered_subkeys_.size()); for (const auto& subkeys : buffered_subkeys_) { - auto* tmp0 = new QTableWidgetItem(QString::fromStdString(subkeys.GetID())); + auto* tmp0 = new QTableWidgetItem(subkeys.GetID()); tmp0->setTextAlignment(Qt::AlignCenter); subkey_list_->setItem(row, 0, tmp0); @@ -192,8 +190,7 @@ void KeyPairSubkeyTab::slot_refresh_subkey_list() { tmp1->setTextAlignment(Qt::AlignCenter); subkey_list_->setItem(row, 1, tmp1); - auto* tmp2 = - new QTableWidgetItem(QString::fromStdString(subkeys.GetPubkeyAlgo())); + auto* tmp2 = new QTableWidgetItem(subkeys.GetPubkeyAlgo()); tmp2->setTextAlignment(Qt::AlignCenter); subkey_list_->setItem(row, 2, tmp2); @@ -229,55 +226,45 @@ void KeyPairSubkeyTab::slot_refresh_subkey_list() { } void KeyPairSubkeyTab::slot_add_subkey() { - auto dialog = new SubkeyGenerateDialog(key_.GetId(), this); + auto* dialog = new SubkeyGenerateDialog(key_.GetId(), this); dialog->show(); } void KeyPairSubkeyTab::slot_refresh_subkey_detail() { auto& subkey = get_selected_subkey(); - key_id_var_label_->setText(QString::fromStdString(subkey.GetID())); + key_id_var_label_->setText(subkey.GetID()); key_size_var_label_->setText(QString::number(subkey.GetKeyLength())); time_t subkey_time_t = boost::posix_time::to_time_t( boost::posix_time::ptime(subkey.GetExpireTime())); -#ifdef GPGFRONTEND_GUI_QT6 expire_var_label_->setText( subkey_time_t == 0 ? _("Never Expires") : QLocale::system().toString(QDateTime::fromSecsSinceEpoch( to_time_t(subkey.GetExpireTime())))); -#else - expire_var_label_->setText( - subkey_time_t == 0 ? _("Never Expires") - : QLocale::system().toString(QDateTime::fromTime_t( - to_time_t(subkey.GetExpireTime())))); -#endif + if (subkey_time_t != 0 && subkey.GetExpireTime() < boost::posix_time::second_clock::local_time()) { - auto paletteExpired = expire_var_label_->palette(); - paletteExpired.setColor(expire_var_label_->foregroundRole(), Qt::red); - expire_var_label_->setPalette(paletteExpired); + auto palette_expired = expire_var_label_->palette(); + palette_expired.setColor(expire_var_label_->foregroundRole(), Qt::red); + expire_var_label_->setPalette(palette_expired); } else { - auto paletteValid = expire_var_label_->palette(); - paletteValid.setColor(expire_var_label_->foregroundRole(), Qt::darkGreen); - expire_var_label_->setPalette(paletteValid); + auto palette_valid = expire_var_label_->palette(); + palette_valid.setColor(expire_var_label_->foregroundRole(), Qt::darkGreen); + expire_var_label_->setPalette(palette_valid); } - algorithm_var_label_->setText(QString::fromStdString(subkey.GetPubkeyAlgo())); -#ifdef GPGFRONTEND_GUI_QT6 + algorithm_var_label_->setText(subkey.GetPubkeyAlgo()); created_var_label_->setText(QLocale::system().toString( QDateTime::fromSecsSinceEpoch(to_time_t(subkey.GetCreateTime())))); -#else - created_var_label_->setText(QLocale::system().toString( - QDateTime::fromTime_t(to_time_t(subkey.GetCreateTime())))); -#endif std::stringstream usage_steam; - if (subkey.IsHasCertificationCapability()) + if (subkey.IsHasCertificationCapability()) { usage_steam << _("Certificate") << " "; + } if (subkey.IsHasEncryptionCapability()) usage_steam << _("Encrypt") << " "; if (subkey.IsHasSigningCapability()) usage_steam << _("Sign") << " "; if (subkey.IsHasAuthenticationCapability()) usage_steam << _("Auth") << " "; @@ -313,23 +300,22 @@ void KeyPairSubkeyTab::slot_refresh_subkey_detail() { card_key_label_->setPalette(palette_valid); } - fingerprint_var_label_->setText( - QString::fromStdString(BeautifyFingerprint(subkey.GetFingerprint()))); + fingerprint_var_label_->setText(BeautifyFingerprint(subkey.GetFingerprint())); } void KeyPairSubkeyTab::create_subkey_opera_menu() { subkey_opera_menu_ = new QMenu(this); - auto* editSubkeyAct = new QAction(_("Edit Expire Date")); - connect(editSubkeyAct, &QAction::triggered, this, + auto* edit_subkey_act = new QAction(_("Edit Expire Date")); + connect(edit_subkey_act, &QAction::triggered, this, &KeyPairSubkeyTab::slot_edit_subkey); - subkey_opera_menu_->addAction(editSubkeyAct); + subkey_opera_menu_->addAction(edit_subkey_act); } void KeyPairSubkeyTab::slot_edit_subkey() { GF_UI_LOG_DEBUG("fpr {}", get_selected_subkey().GetFingerprint()); - auto dialog = new KeySetExpireDateDialog( + auto* dialog = new KeySetExpireDateDialog( key_.GetId(), get_selected_subkey().GetFingerprint(), this); dialog->show(); } diff --git a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.h b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.h index bde87464..c179c3e9 100644 --- a/src/ui/dialog/keypair_details/KeyPairSubkeyTab.h +++ b/src/ui/dialog/keypair_details/KeyPairSubkeyTab.h @@ -45,7 +45,7 @@ class KeyPairSubkeyTab : public QWidget { * @param key * @param parent */ - KeyPairSubkeyTab(const std::string& key, QWidget* parent); + KeyPairSubkeyTab(const QString& key, QWidget* parent); private: /** diff --git a/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp b/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp index 20d47137..a39d87fc 100644 --- a/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp +++ b/src/ui/dialog/keypair_details/KeyPairUIDTab.cpp @@ -37,7 +37,7 @@ namespace GpgFrontend::UI { -KeyPairUIDTab::KeyPairUIDTab(const std::string& key_id, QWidget* parent) +KeyPairUIDTab::KeyPairUIDTab(const QString& key_id, QWidget* parent) : QWidget(parent), m_key_(GpgKeyGetter::GetInstance().GetKey(key_id)) { create_uid_list(); create_sign_list(); @@ -48,7 +48,7 @@ KeyPairUIDTab::KeyPairUIDTab(const std::string& key_id, QWidget* parent) auto* uid_buttons_layout = new QGridLayout(); auto* add_uid_button = new QPushButton(_("New UID")); - auto manage_uid_button = new QPushButton(_("UID Management")); + auto* manage_uid_button = new QPushButton(_("UID Management")); if (m_key_.IsHasMasterKey()) { manage_uid_button->setMenu(manage_selected_uid_menu_); @@ -184,13 +184,13 @@ void KeyPairUIDTab::slot_refresh_uid_list() { uid_list_->setRowCount(buffered_uids_.size()); for (const auto& uid : buffered_uids_) { - auto* tmp0 = new QTableWidgetItem(QString::fromStdString(uid.GetName())); + auto* tmp0 = new QTableWidgetItem(uid.GetName()); uid_list_->setItem(row, 1, tmp0); - auto* tmp1 = new QTableWidgetItem(QString::fromStdString(uid.GetEmail())); + auto* tmp1 = new QTableWidgetItem(uid.GetEmail()); uid_list_->setItem(row, 2, tmp1); - auto* tmp2 = new QTableWidgetItem(QString::fromStdString(uid.GetComment())); + auto* tmp2 = new QTableWidgetItem(uid.GetComment()); uid_list_->setItem(row, 3, tmp2); auto* tmp3 = new QTableWidgetItem(QString::number(row)); @@ -263,7 +263,7 @@ void KeyPairUIDTab::slot_refresh_sig_list() { sig_list_->setRowCount(buffered_signatures_.size()); for (const auto& sig : buffered_signatures_) { - auto* tmp0 = new QTableWidgetItem(QString::fromStdString(sig.GetKeyID())); + auto* tmp0 = new QTableWidgetItem(sig.GetKeyID()); sig_list_->setItem(sig_row, 0, tmp0); if (gpgme_err_code(sig.GetStatus()) == GPG_ERR_NO_PUBKEY) { @@ -273,12 +273,10 @@ void KeyPairUIDTab::slot_refresh_sig_list() { auto* tmp3 = new QTableWidgetItem("<Unknown>"); sig_list_->setItem(sig_row, 2, tmp3); } else { - auto* tmp2 = - new QTableWidgetItem(QString::fromStdString(sig.GetName())); + auto* tmp2 = new QTableWidgetItem(sig.GetName()); sig_list_->setItem(sig_row, 1, tmp2); - auto* tmp3 = - new QTableWidgetItem(QString::fromStdString(sig.GetEmail())); + auto* tmp3 = new QTableWidgetItem(sig.GetEmail()); sig_list_->setItem(sig_row, 2, tmp3); } #ifdef GPGFRONTEND_GUI_QT6 @@ -385,7 +383,7 @@ void KeyPairUIDTab::slot_del_uid() { QString keynames; for (auto& uid : *selected_uids) { - keynames.append(QString::fromStdString(uid)); + keynames.append(uid); keynames.append("<br/>"); } @@ -405,7 +403,7 @@ void KeyPairUIDTab::slot_del_uid() { QMessageBox::critical( nullptr, _("Operation Failed"), QString(_("An error occurred during the delete %1 operation.")) - .arg(uid.c_str())); + .arg(uid)); } } emit SignalUpdateUIDInfo(); @@ -425,7 +423,7 @@ void KeyPairUIDTab::slot_set_primary_uid() { QString keynames; - keynames.append(QString::fromStdString(selected_uids->front())); + keynames.append(selected_uids->front()); keynames.append("<br/>"); int ret = QMessageBox::warning( @@ -521,7 +519,7 @@ void KeyPairUIDTab::slot_del_uid_single() { QString keynames; - keynames.append(QString::fromStdString(selected_uids->front())); + keynames.append(selected_uids->front()); keynames.append("<br/>"); int ret = QMessageBox::warning( @@ -574,7 +572,7 @@ void KeyPairUIDTab::slot_del_sign() { QString keynames; - keynames.append(QString::fromStdString(selected_signs->front().second)); + keynames.append(selected_signs->front().second); keynames.append("<br/>"); int ret = diff --git a/src/ui/dialog/keypair_details/KeyPairUIDTab.h b/src/ui/dialog/keypair_details/KeyPairUIDTab.h index 0edecafe..3655511d 100644 --- a/src/ui/dialog/keypair_details/KeyPairUIDTab.h +++ b/src/ui/dialog/keypair_details/KeyPairUIDTab.h @@ -45,7 +45,7 @@ class KeyPairUIDTab : public QWidget { * @param key_id * @param parent */ - KeyPairUIDTab(const std::string& key_id, QWidget* parent); + KeyPairUIDTab(const QString& key_id, QWidget* parent); signals: diff --git a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp index f81b85e9..2e5eb6f7 100644 --- a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp +++ b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.cpp @@ -49,7 +49,7 @@ KeySetExpireDateDialog::KeySetExpireDateDialog(const KeyId& key_id, } KeySetExpireDateDialog::KeySetExpireDateDialog(const KeyId& key_id, - std::string subkey_fpr, + QString subkey_fpr, QWidget* parent) : GeneralDialog(typeid(KeySetExpireDateDialog).name(), parent), ui_(GpgFrontend::SecureCreateSharedObject< diff --git a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.h b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.h index bd4647e9..633840ac 100644 --- a/src/ui/dialog/keypair_details/KeySetExpireDateDialog.h +++ b/src/ui/dialog/keypair_details/KeySetExpireDateDialog.h @@ -57,7 +57,7 @@ class KeySetExpireDateDialog : public GeneralDialog { * @param subkey_fpr * @param parent */ - explicit KeySetExpireDateDialog(const KeyId& key_id, std::string subkey_fpr, + explicit KeySetExpireDateDialog(const KeyId& key_id, QString subkey_fpr, QWidget* parent = nullptr); signals: diff --git a/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp b/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp index 97f20289..47b8eb93 100644 --- a/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp +++ b/src/ui/dialog/keypair_details/KeyUIDSignDialog.cpp @@ -125,7 +125,7 @@ void KeyUIDSignDialog::slot_sign_key(bool clicked) { if (!GpgKeyManager::GetInstance().SignKey(m_key_, *keys, uid, expires)) { QMessageBox::critical( nullptr, _("Unsuccessful Operation"), - QString(_("Signature operation failed for UID %1")).arg(uid.c_str())); + QString(_("Signature operation failed for UID %1")).arg(uid)); } } diff --git a/src/ui/dialog/settings/SettingsGeneral.cpp b/src/ui/dialog/settings/SettingsGeneral.cpp index 174c9c39..1d770b52 100644 --- a/src/ui/dialog/settings/SettingsGeneral.cpp +++ b/src/ui/dialog/settings/SettingsGeneral.cpp @@ -30,14 +30,11 @@ #include "core/GpgModel.h" #include "core/function/GlobalSettingStation.h" -#include "core/function/gpg/GpgContext.h" #ifdef SUPPORT_MULTI_LANG #include "SettingsDialog.h" #endif -#include <boost/format.hpp> - #include "ui_GeneralSettings.h" namespace GpgFrontend::UI { @@ -66,14 +63,12 @@ GeneralTab::GeneralTab(QWidget* parent) _("GpgFrontend will restart automatically if you change the language!")); ui_->dataBox->setTitle(_("Data")); - ui_->clearAllLogFilesButton->setText(QString::fromStdString( - (boost::format(_("Clear All Log (Total Size: %s)")) % - GlobalSettingStation::GetInstance().GetLogFilesSize()) - .str())); - ui_->clearAllDataObjectsButton->setText(QString::fromStdString( - (boost::format(_("Clear All Data Objects (Total Size: %s)")) % - GlobalSettingStation::GetInstance().GetDataObjectsFilesSize()) - .str())); + ui_->clearAllLogFilesButton->setText( + QString(_("Clear All Log (Total Size: %1)")) % + GlobalSettingStation::GetInstance().GetLogFilesSize()); + ui_->clearAllDataObjectsButton->setText( + QString(_("Clear All Data Objects (Total Size: %1)")) + .arg(GlobalSettingStation::GetInstance().GetDataObjectsFilesSize())); #ifdef SUPPORT_MULTI_LANG lang_ = SettingsDialog::ListLanguages(); @@ -86,10 +81,9 @@ GeneralTab::GeneralTab(QWidget* parent) connect(ui_->clearAllLogFilesButton, &QPushButton::clicked, this, [=]() { GlobalSettingStation::GetInstance().ClearAllLogFiles(); - ui_->clearAllLogFilesButton->setText(QString::fromStdString( - (boost::format(_("Clear All Log (Total Size: %s)")) % - GlobalSettingStation::GetInstance().GetLogFilesSize()) - .str())); + ui_->clearAllLogFilesButton->setText( + QString(_("Clear All Log (Total Size: %s)")) + .arg(GlobalSettingStation::GetInstance().GetLogFilesSize())); }); connect(ui_->clearAllDataObjectsButton, &QPushButton::clicked, this, [=]() { @@ -102,10 +96,10 @@ GeneralTab::GeneralTab(QWidget* parent) QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { GlobalSettingStation::GetInstance().ClearAllDataObjects(); - ui_->clearAllDataObjectsButton->setText(QString::fromStdString( - (boost::format(_("Clear All Data Objects (Total Size: %s)")) % - GlobalSettingStation::GetInstance().GetDataObjectsFilesSize()) - .str())); + ui_->clearAllDataObjectsButton->setText( + QString(_("Clear All Data Objects (Total Size: %s)")) + .arg(GlobalSettingStation::GetInstance() + .GetDataObjectsFilesSize())); } }); @@ -123,8 +117,9 @@ void GeneralTab::SetSettings() { try { bool clear_gpg_password_cache = settings.lookup("general.clear_gpg_password_cache"); - if (clear_gpg_password_cache) + if (clear_gpg_password_cache) { ui_->clearGpgPasswordCacheCheckBox->setCheckState(Qt::Checked); + } } catch (...) { GF_UI_LOG_ERROR("setting operation error: clear_gpg_password_cache"); } @@ -132,8 +127,9 @@ void GeneralTab::SetSettings() { try { bool restore_text_editor_page = settings.lookup("general.restore_text_editor_page"); - if (restore_text_editor_page) + if (restore_text_editor_page) { ui_->restoreTextEditorPageCheckBox->setCheckState(Qt::Checked); + } } catch (...) { GF_UI_LOG_ERROR("setting operation error: restore_text_editor_page"); } @@ -142,16 +138,17 @@ void GeneralTab::SetSettings() { bool longer_expiration_date = settings.lookup("general.longer_expiration_date"); GF_UI_LOG_DEBUG("longer_expiration_date: {}", longer_expiration_date); - if (longer_expiration_date) + if (longer_expiration_date) { ui_->longerKeyExpirationDateCheckBox->setCheckState(Qt::Checked); + } } catch (...) { GF_UI_LOG_ERROR("setting operation error: longer_expiration_date"); } #ifdef SUPPORT_MULTI_LANG try { - std::string lang_key = settings.lookup("general.lang"); - QString lang_value = lang_.value(lang_key.c_str()); + QString lang_key = QString::fromStdString(settings.lookup("general.lang")); + QString lang_value = lang_.value(lang_key); GF_UI_LOG_DEBUG("lang settings current: {}", lang_value.toStdString()); if (!lang_.empty()) { ui_->langSelectBox->setCurrentIndex( @@ -167,8 +164,9 @@ void GeneralTab::SetSettings() { try { bool confirm_import_keys = settings.lookup("general.confirm_import_keys"); GF_UI_LOG_DEBUG("confirm_import_keys: {}", confirm_import_keys); - if (confirm_import_keys) + if (confirm_import_keys) { ui_->importConfirmationCheckBox->setCheckState(Qt::Checked); + } } catch (...) { GF_UI_LOG_ERROR("setting operation error: confirm_import_keys"); } @@ -183,49 +181,50 @@ void GeneralTab::ApplySettings() { GpgFrontend::GlobalSettingStation::GetInstance().GetMainSettings(); if (!settings.exists("general") || - settings.lookup("general").getType() != libconfig::Setting::TypeGroup) + settings.lookup("general").getType() != libconfig::Setting::TypeGroup) { settings.add("general", libconfig::Setting::TypeGroup); + } auto& general = settings["general"]; - if (!general.exists("longer_expiration_date")) + if (!general.exists("longer_expiration_date")) { general.add("longer_expiration_date", libconfig::Setting::TypeBoolean) = ui_->longerKeyExpirationDateCheckBox->isChecked(); - else { + } else { general["longer_expiration_date"] = ui_->longerKeyExpirationDateCheckBox->isChecked(); } - if (!general.exists("clear_gpg_password_cache")) + if (!general.exists("clear_gpg_password_cache")) { general.add("clear_gpg_password_cache", libconfig::Setting::TypeBoolean) = ui_->clearGpgPasswordCacheCheckBox->isChecked(); - else { + } else { general["clear_gpg_password_cache"] = ui_->clearGpgPasswordCacheCheckBox->isChecked(); } - if (!general.exists("restore_text_editor_page")) + if (!general.exists("restore_text_editor_page")) { general.add("restore_text_editor_page", libconfig::Setting::TypeBoolean) = ui_->restoreTextEditorPageCheckBox->isChecked(); - else { + } else { general["restore_text_editor_page"] = ui_->restoreTextEditorPageCheckBox->isChecked(); } #ifdef SUPPORT_MULTI_LANG - if (!general.exists("lang")) + if (!general.exists("lang")) { general.add("lang", libconfig::Setting::TypeBoolean) = lang_.key(ui_->langSelectBox->currentText()).toStdString(); - else { + } else { general["lang"] = lang_.key(ui_->langSelectBox->currentText()).toStdString(); } #endif - if (!general.exists("confirm_import_keys")) + if (!general.exists("confirm_import_keys")) { general.add("confirm_import_keys", libconfig::Setting::TypeBoolean) = ui_->importConfirmationCheckBox->isChecked(); - else { + } else { general["confirm_import_keys"] = ui_->importConfirmationCheckBox->isChecked(); } diff --git a/src/ui/dialog/settings/SettingsGeneral.h b/src/ui/dialog/settings/SettingsGeneral.h index da2ca864..b7c61e52 100644 --- a/src/ui/dialog/settings/SettingsGeneral.h +++ b/src/ui/dialog/settings/SettingsGeneral.h @@ -85,7 +85,7 @@ class GeneralTab : public QWidget { QHash<QString, QString> lang_; ///< #endif - std::vector<std::string> key_ids_list_; ///< + std::vector<QString> key_ids_list_; ///< KeyList* m_key_list_{}; ///< diff --git a/src/ui/dialog/settings/SettingsKeyServer.cpp b/src/ui/dialog/settings/SettingsKeyServer.cpp index 617955f7..922ca230 100644 --- a/src/ui/dialog/settings/SettingsKeyServer.cpp +++ b/src/ui/dialog/settings/SettingsKeyServer.cpp @@ -134,11 +134,12 @@ void KeyserverTab::SetSettings() { if (default_key_server_index >= key_server_list.size()) { throw std::runtime_error("default_server index out of range"); } - std::string default_key_server = + const auto default_key_server = key_server_list[default_key_server_index].get<std::string>(); - if (!key_server_str_list_.contains(default_key_server.c_str())) + if (!key_server_str_list_.contains(default_key_server.c_str())) { key_server_str_list_.append(default_key_server.c_str()); + } default_key_server_ = QString::fromStdString(default_key_server); } catch (const std::exception& e) { GF_UI_LOG_ERROR("Error reading key-server settings: ", e.what()); diff --git a/src/ui/dialog/settings/SettingsNetwork.cpp b/src/ui/dialog/settings/SettingsNetwork.cpp index f6b96300..211894a1 100644 --- a/src/ui/dialog/settings/SettingsNetwork.cpp +++ b/src/ui/dialog/settings/SettingsNetwork.cpp @@ -101,22 +101,25 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { auto &settings = GlobalSettingStation::GetInstance().GetMainSettings(); try { - std::string proxy_host = settings.lookup("proxy.proxy_host"); - ui_->proxyServerAddressEdit->setText(proxy_host.c_str()); + QString proxy_host = + QString::fromStdString(settings.lookup("proxy.proxy_host")); + ui_->proxyServerAddressEdit->setText(proxy_host); } catch (...) { GF_UI_LOG_ERROR("setting operation error: proxy_host"); } try { - std::string std_username = settings.lookup("proxy.username"); - ui_->usernameEdit->setText(std_username.c_str()); + QString std_username = + QString::fromStdString(settings.lookup("proxy.username")); + ui_->usernameEdit->setText(std_username); } catch (...) { GF_UI_LOG_ERROR("setting operation error: username"); } try { - std::string std_password = settings.lookup("proxy.password"); - ui_->passwordEdit->setText(std_password.c_str()); + QString std_password = + QString::fromStdString(settings.lookup("proxy.password")); + ui_->passwordEdit->setText(std_password); } catch (...) { GF_UI_LOG_ERROR("setting operation error: password"); } @@ -130,8 +133,9 @@ void GpgFrontend::UI::NetworkTab::SetSettings() { ui_->proxyTypeComboBox->setCurrentText("HTTP"); try { - std::string proxy_type = settings.lookup("proxy.proxy_type"); - ui_->proxyTypeComboBox->setCurrentText(proxy_type.c_str()); + QString proxy_type = + QString::fromStdString(settings.lookup("proxy.proxy_type")); + ui_->proxyTypeComboBox->setCurrentText(proxy_type); } catch (...) { GF_UI_LOG_ERROR("setting operation error: proxy_type"); } diff --git a/src/ui/function/GenerateRevokeCertification.cpp b/src/ui/function/GenerateRevokeCertification.cpp index 5d5b1702..b1089d45 100644 --- a/src/ui/function/GenerateRevokeCertification.cpp +++ b/src/ui/function/GenerateRevokeCertification.cpp @@ -38,15 +38,15 @@ GenerateRevokeCertification::GenerateRevokeCertification(QWidget* parent) : QWidget(parent) {} auto GenerateRevokeCertification::Exec(const GpgKey& key, - const std::string& output_path) -> int { + const QString& output_path) -> int { const auto app_path = Module::RetrieveRTValueTypedOrDefault<>( - "core", "gpgme.ctx.app_path", std::string{}); + "core", "gpgme.ctx.app_path", QString{}); // get all components GpgCommandExecutor::ExecuteSync( {app_path, {"--command-fd", "0", "--status-fd", "1", "--no-tty", "-o", std::move(output_path), "--gen-revoke", key.GetFingerprint()}, - [=](int exit_code, const std::string& p_out, const std::string& p_err) { + [=](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 " diff --git a/src/ui/function/GenerateRevokeCertification.h b/src/ui/function/GenerateRevokeCertification.h index 0269a8a7..edc0161b 100644 --- a/src/ui/function/GenerateRevokeCertification.h +++ b/src/ui/function/GenerateRevokeCertification.h @@ -38,7 +38,7 @@ class GenerateRevokeCertification : public QWidget { public: explicit GenerateRevokeCertification(QWidget* parent); - auto Exec(const GpgKey& key, const std::string& output_path) -> int; + auto Exec(const GpgKey& key, const QString& output_path) -> int; }; } // namespace GpgFrontend::UI diff --git a/src/ui/function/RaisePinentry.cpp b/src/ui/function/RaisePinentry.cpp index 1e48e984..8d4c51c4 100644 --- a/src/ui/function/RaisePinentry.cpp +++ b/src/ui/function/RaisePinentry.cpp @@ -28,9 +28,8 @@ #include "RaisePinentry.h" -#include <qwidget.h> - #include "core/function/CoreSignalStation.h" +#include "core/model/GpgPassphraseContext.h" #include "pinentry/pinentrydialog.h" namespace GpgFrontend::UI { @@ -47,50 +46,73 @@ auto FindTopMostWindow(QWidget* fallback) -> QWidget* { return fallback; } -RaisePinentry::RaisePinentry(QWidget* parent) : QWidget(parent) {} +RaisePinentry::RaisePinentry(QWidget* parent, + QSharedPointer<GpgPassphraseContext> context) + : QWidget(parent), context_(std::move(context)) {} auto RaisePinentry::Exec() -> int { - auto* pinentry = - new PinEntryDialog(FindTopMostWindow(this), 0, 0, true, false, QString(), - QString::fromStdString(_("Show passphrase")), - QString::fromStdString(_("Hide passphrase"))); + GF_UI_LOG_DEBUG( + "setting pinetry's arguments, context uids: {}, passphrase info: {}, " + "prev_was_bad: {}", + context_->GetUidsInfo().toStdString(), + context_->GetPassphraseInfo().toStdString(), context_->IsPreWasBad()); + + bool ask_for_new = context_->GetPassphraseInfo().isEmpty() && + context_->GetUidsInfo().isEmpty(); + + auto* pinentry = new PinEntryDialog( + FindTopMostWindow(this), 0, 15, true, ask_for_new, + ask_for_new ? QString(_("Repeat PIN:")) : QString(), + QString(_("Show passphrase")), QString(_("Hide passphrase"))); + + if (context_->IsPreWasBad()) { + pinentry->setError(QString(_("Given PIN was wrong. Please retry."))); + } + + pinentry->setPrompt(QString(_("PIN:"))); + + if (!context_->GetUidsInfo().isEmpty()) { + pinentry->setDescription(QString("Please provide PIN of Key:\n%1\n") + .arg(context_->GetUidsInfo())); + } - GF_UI_LOG_DEBUG("setting pinetry's arguments"); + struct pinentry pinentry_info; + pinentry->setPinentryInfo(pinentry_info); - pinentry->setPrompt(QString::fromStdString(_("PIN:"))); - pinentry->setDescription(QString()); pinentry->setRepeatErrorText( QString::fromStdString(_("Passphrases do not match"))); - pinentry->setGenpinLabel(QString()); - pinentry->setGenpinTT(QString()); - pinentry->setCapsLockHint(QString::fromStdString(_("Caps Lock is on"))); + pinentry->setGenpinLabel(QString("BBBBBBBBB")); + pinentry->setGenpinTT(QString("AAAAAAAA")); + pinentry->setCapsLockHint(QString(_("Caps Lock is on"))); pinentry->setFormattedPassphrase({false, QString()}); pinentry->setConstraintsOptions({false, QString(), QString(), QString()}); - pinentry->setWindowTitle(_("Pinentry")); + pinentry->setWindowTitle(_("Buddled Pinentry")); /* If we reuse the same dialog window. */ pinentry->setPin(QString()); pinentry->setOkText(_("Confirm")); pinentry->setCancelText(_("Cancel")); - GF_UI_LOG_DEBUG("pinentry is ready to start"); - - connect(pinentry, &PinEntryDialog::finished, this, [pinentry](int result) { - bool ret = result != 0; - GF_UI_LOG_DEBUG("pinentry finished, ret: {}", ret); - - if (!ret) { - emit CoreSignalStation::GetInstance()->SignalUserInputPassphraseCallback( - {}); - return -1; - } - - auto pin = pinentry->pin().toUtf8(); - emit CoreSignalStation::GetInstance()->SignalUserInputPassphraseCallback( - pin); - return 0; - }); + 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({}); + return -1; + } + + auto pin = pinentry->pin().toUtf8(); + + context_->SetPassphrase(pin); + emit CoreSignalStation::GetInstance() + ->SignalUserInputPassphraseCallback(context_); + return 0; + }); connect(pinentry, &PinEntryDialog::finished, this, &QWidget::deleteLater); pinentry->open(); diff --git a/src/ui/function/RaisePinentry.h b/src/ui/function/RaisePinentry.h index 8c097c2a..40175dfd 100644 --- a/src/ui/function/RaisePinentry.h +++ b/src/ui/function/RaisePinentry.h @@ -30,6 +30,10 @@ #include "ui/GpgFrontendUI.h" +namespace GpgFrontend { +class GpgPassphraseContext; +} + namespace GpgFrontend::UI { class RaisePinentry : public QWidget { @@ -40,7 +44,7 @@ class RaisePinentry : public QWidget { * * @param parent */ - explicit RaisePinentry(QWidget *parent); + explicit RaisePinentry(QWidget *parent, QSharedPointer<GpgPassphraseContext>); /** * @brief @@ -48,6 +52,9 @@ class RaisePinentry : public QWidget { * @return int */ auto Exec() -> int; + + private: + QSharedPointer<GpgPassphraseContext> context_; }; } // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/function/SetOwnerTrustLevel.cpp b/src/ui/function/SetOwnerTrustLevel.cpp index 290b1436..91917961 100644 --- a/src/ui/function/SetOwnerTrustLevel.cpp +++ b/src/ui/function/SetOwnerTrustLevel.cpp @@ -37,8 +37,8 @@ namespace GpgFrontend::UI { SetOwnerTrustLevel::SetOwnerTrustLevel(QWidget* parent) : QWidget(parent) {} -auto SetOwnerTrustLevel::Exec(const std::string& key_id) -> bool { - if (key_id.empty()) { +auto SetOwnerTrustLevel::Exec(const QString& key_id) -> bool { + if (key_id.isEmpty()) { return false; } diff --git a/src/ui/function/SetOwnerTrustLevel.h b/src/ui/function/SetOwnerTrustLevel.h index 29cece18..e33f787b 100644 --- a/src/ui/function/SetOwnerTrustLevel.h +++ b/src/ui/function/SetOwnerTrustLevel.h @@ -49,7 +49,7 @@ class SetOwnerTrustLevel : public QWidget { * @return true * @return false */ - auto Exec(const std::string& key_id) -> bool; + auto Exec(const QString& key_id) -> bool; }; } // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/main_window/GeneralMainWindow.cpp b/src/ui/main_window/GeneralMainWindow.cpp index 93c5ca4a..ad2f061a 100644 --- a/src/ui/main_window/GeneralMainWindow.cpp +++ b/src/ui/main_window/GeneralMainWindow.cpp @@ -32,7 +32,7 @@ #include "ui/struct/SettingsObject.h" -GpgFrontend::UI::GeneralMainWindow::GeneralMainWindow(std::string name, +GpgFrontend::UI::GeneralMainWindow::GeneralMainWindow(QString name, QWidget *parent) : QMainWindow(parent), name_(std::move(name)) { slot_restore_settings(); @@ -52,27 +52,26 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { try { SettingsObject general_windows_state(name_ + "_state"); - std::string window_state = general_windows_state.Check( - "window_state", saveState().toBase64().toStdString()); + QString window_state = QString::fromStdString(general_windows_state.Check( + "window_state", saveState().toBase64().toStdString())); GF_UI_LOG_DEBUG("restore main window state: {}", window_state); // state sets pos & size of dock-widgets - this->restoreState( - QByteArray::fromBase64(QByteArray::fromStdString(window_state))); + this->restoreState(QByteArray::fromBase64(window_state.toUtf8())); bool window_save = general_windows_state.Check("window_save", true); // Restore window size & location if (window_save) { - int x = general_windows_state.Check("window_pos").Check("x", 100), - y = general_windows_state.Check("window_pos").Check("y", 100); + int x = general_windows_state.Check("window_pos").Check("x", 100); + int y = general_windows_state.Check("window_pos").Check("y", 100); pos_ = {x, y}; int width = - general_windows_state.Check("window_size").Check("width", 800), - height = - general_windows_state.Check("window_size").Check("height", 450); + general_windows_state.Check("window_size").Check("width", 800); + int height = + general_windows_state.Check("window_size").Check("height", 450); size_ = {width, height}; @@ -117,8 +116,8 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { // appearance SettingsObject general_settings_state("general_settings_state"); - int width = general_settings_state.Check("icon_size").Check("width", 24), - height = general_settings_state.Check("icon_size").Check("height", 24); + int width = general_settings_state.Check("icon_size").Check("width", 24); + int height = general_settings_state.Check("icon_size").Check("height", 24); GF_UI_LOG_DEBUG("icon size: {} {}", width, height); icon_size_ = {width, height}; @@ -133,7 +132,7 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { icon_style_ = toolButtonStyle(); } catch (...) { - GF_UI_LOG_ERROR(name_, "error"); + GF_UI_LOG_ERROR("gernal main window: {}, caught exception", name_); } } @@ -168,6 +167,6 @@ void GpgFrontend::UI::GeneralMainWindow::slot_save_settings() noexcept { general_settings_state["icon_style"] = this->toolButtonStyle(); } catch (...) { - GF_UI_LOG_ERROR(name_, "error"); + GF_UI_LOG_ERROR("gernal main window: {}, caught exception", name_); } } diff --git a/src/ui/main_window/GeneralMainWindow.h b/src/ui/main_window/GeneralMainWindow.h index f65b0668..e1ff31bb 100644 --- a/src/ui/main_window/GeneralMainWindow.h +++ b/src/ui/main_window/GeneralMainWindow.h @@ -41,7 +41,7 @@ class GeneralMainWindow : public QMainWindow { * * @param name */ - explicit GeneralMainWindow(std::string name, QWidget* parent = nullptr); + explicit GeneralMainWindow(QString name, QWidget* parent = nullptr); /** * @@ -71,8 +71,8 @@ class GeneralMainWindow : public QMainWindow { void slot_save_settings() noexcept; private: - std::string name_; ///< - QPoint pos_; ///< - QSize size_; ///< + QString name_; ///< + QPoint pos_; ///< + QSize size_; ///< }; } // namespace GpgFrontend::UI diff --git a/src/ui/main_window/KeyMgmt.cpp b/src/ui/main_window/KeyMgmt.cpp index d6e209de..4d51c552 100644 --- a/src/ui/main_window/KeyMgmt.cpp +++ b/src/ui/main_window/KeyMgmt.cpp @@ -320,9 +320,9 @@ void KeyMgmt::delete_keys_with_warning(KeyIdArgsListPtr uidList) { for (const auto& key_id : *uidList) { auto key = GpgKeyGetter::GetInstance().GetKey(key_id); if (!key.IsGood()) continue; - keynames.append(QString::fromStdString(key.GetName())); + keynames.append(key.GetName()); keynames.append("<i> <"); - keynames.append(QString::fromStdString(key.GetEmail())); + keynames.append(key.GetEmail()); keynames.append("> </i><br/>"); } @@ -495,7 +495,7 @@ void KeyMgmt::SlotExportAsOpenSSHFormat() { QString(_("OpenSSH Public Key Files")) + "All Files (*)"); if (!file_name.isEmpty()) { - WriteFileGFBuffer(file_name.toStdString(), gf_buffer); + WriteFileGFBuffer(file_name, gf_buffer); emit SignalStatusBarChanged(QString(_("key(s) exported"))); } }); diff --git a/src/ui/main_window/MainWindow.cpp b/src/ui/main_window/MainWindow.cpp index bff6e7d3..e8280e93 100644 --- a/src/ui/main_window/MainWindow.cpp +++ b/src/ui/main_window/MainWindow.cpp @@ -250,8 +250,8 @@ void MainWindow::recover_editor_unsaved_pages_from_cache() { !unsaved_page_json.contains("content")) { continue; } - std::string title = unsaved_page_json["title"]; - std::string content = unsaved_page_json["content"]; + QString title = QString::fromStdString(unsaved_page_json["title"]); + QString content = QString::fromStdString(unsaved_page_json["content"]); GF_UI_LOG_DEBUG( "recovering unsaved page from cache, page title: {}, content size", diff --git a/src/ui/main_window/MainWindow.h b/src/ui/main_window/MainWindow.h index 7697e2f3..a88ed483 100644 --- a/src/ui/main_window/MainWindow.h +++ b/src/ui/main_window/MainWindow.h @@ -32,6 +32,10 @@ #include "ui/widgets/InfoBoardWidget.h" #include "ui/widgets/TextEdit.h" +namespace GpgFrontend { +class GpgPassphraseContext; +} + namespace GpgFrontend::UI { /** * @brief @@ -117,17 +121,6 @@ class MainWindow : public GeneralMainWindow { void SlotOpenFile(const QString& path); /** - * @details Open dialog for encrypting file. - */ - void SlotFileEncrypt(std::filesystem::path); - - /** - * @brief - * - */ - void SlotDirectoryEncrypt(std::filesystem::path); - - /** * @details encrypt the text of currently active textedit-page * with the currently checked keys */ @@ -165,60 +158,71 @@ class MainWindow : public GeneralMainWindow { void SlotDecryptVerify(); /** + * @details Open dialog for encrypting file. + */ + void SlotFileEncrypt(const QString&); + + /** + * @brief + * + */ + void SlotDirectoryEncrypt(const QString&); + + /** * @brief * * @param path */ - void SlotFileDecrypt(std::filesystem::path path); + void SlotFileDecrypt(const QString& path); /** * @brief * * @param path */ - void SlotArchiveDecrypt(std::filesystem::path path); + void SlotArchiveDecrypt(const QString& path); /** * @brief * * @param path */ - void SlotFileSign(std::filesystem::path path); + void SlotFileSign(const QString& path); /** * @brief * * @param path */ - void SlotFileVerify(std::filesystem::path path); + void SlotFileVerify(const QString& path); /** * @brief * * @param path */ - void SlotFileEncryptSign(std::filesystem::path path); + void SlotFileEncryptSign(const QString& path); /** * @brief * * @param path */ - void SlotDirectoryEncryptSign(std::filesystem::path path); + void SlotDirectoryEncryptSign(const QString& path); /** * @brief * * @param path */ - void SlotFileDecryptVerify(std::filesystem::path path); + void SlotFileDecryptVerify(const QString& path); /** * @brief * * @param path */ - void SlotArchiveDecryptVerify(std::filesystem::path path); + void SlotArchiveDecryptVerify(const QString& path); /** * @details get value of member restartNeeded to needed. @@ -229,7 +233,7 @@ class MainWindow : public GeneralMainWindow { /** * @details Open a new tab for path */ - void SlotRaisePinentry(); + void SlotRaisePinentry(QSharedPointer<GpgPassphraseContext>); private slots: diff --git a/src/ui/main_window/MainWindowFileSlotFunction.cpp b/src/ui/main_window/MainWindowFileSlotFunction.cpp index 69da6678..e698ee6c 100644 --- a/src/ui/main_window/MainWindowFileSlotFunction.cpp +++ b/src/ui/main_window/MainWindowFileSlotFunction.cpp @@ -26,10 +26,7 @@ * */ -#include <boost/format.hpp> - #include "MainWindow.h" -#include "core/function/ArchiveFileOperator.h" #include "core/function/GlobalSettingStation.h" #include "core/function/gpg/GpgFileOpera.h" #include "core/function/gpg/GpgKeyGetter.h" @@ -37,19 +34,19 @@ #include "core/function/result_analyse/GpgEncryptResultAnalyse.h" #include "core/function/result_analyse/GpgSignResultAnalyse.h" #include "core/function/result_analyse/GpgVerifyResultAnalyse.h" -#include "core/thread/Task.h" #include "core/utils/GpgUtils.h" +#include "core/utils/IOUtils.h" #include "ui/UserInterfaceUtils.h" #include "ui/dialog/SignersPicker.h" namespace GpgFrontend::UI { -void MainWindow::SlotFileEncrypt(std::filesystem::path path) { +void MainWindow::SlotFileEncrypt(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")) + .arg(QFileInfo(path).fileName())); return; } @@ -60,12 +57,11 @@ void MainWindow::SlotFileEncrypt(std::filesystem::path path) { SetExtensionOfOutputFile(path, kENCRYPT, !non_ascii_when_export); if (QFile::exists(out_path)) { - auto out_file_name = boost::format(_("The target file %1% already exists, " - "do you need to overwrite it?")) % - out_path.filename(); - auto ret = - QMessageBox::warning(this, _("Warning"), out_file_name.str().c_str(), - QMessageBox::Ok | QMessageBox::Cancel); + auto out_file_name = QString(_("The target file %1 already exists, " + "do you need to overwrite it?")) + .arg(out_path); + auto ret = QMessageBox::warning(this, _("Warning"), out_file_name, + QMessageBox::Ok | QMessageBox::Cancel); if (ret == QMessageBox::Cancel) return; } @@ -73,8 +69,7 @@ void MainWindow::SlotFileEncrypt(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } @@ -92,7 +87,8 @@ void MainWindow::SlotFileEncrypt(std::filesystem::path path) { CommonUtils::WaitForOpera( this, _("Symmetrically Encrypting"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().EncryptFileSymmetric( - path, !non_ascii_when_export, out_path, + path.toStdString(), !non_ascii_when_export, + out_path.toStdString(), [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -125,7 +121,7 @@ void MainWindow::SlotFileEncrypt(std::filesystem::path path) { nullptr, _("Invalid KeyPair"), QString(_("The selected keypair cannot be used for encryption.")) + "<br/><br/>" + _("For example the Following Key:") + " <br/>" + - QString::fromStdString(key.GetUIDs()->front().GetUID())); + key.GetUIDs()->front().GetUID()); return; } } @@ -133,8 +129,9 @@ void MainWindow::SlotFileEncrypt(std::filesystem::path path) { CommonUtils::WaitForOpera( this, _("Encrypting"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().EncryptFile( - {p_keys->begin(), p_keys->end()}, path, !non_ascii_when_export, - out_path, [=](GpgError err, const DataObjectPtr& data_obj) { + {p_keys->begin(), p_keys->end()}, path.toStdString(), + !non_ascii_when_export, out_path.toStdString(), + [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -152,12 +149,12 @@ void MainWindow::SlotFileEncrypt(std::filesystem::path path) { }); } -void MainWindow::SlotDirectoryEncrypt(std::filesystem::path path) { +void MainWindow::SlotDirectoryEncrypt(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")) + .arg(QFileInfo(path).fileName())); return; } @@ -168,12 +165,11 @@ void MainWindow::SlotDirectoryEncrypt(std::filesystem::path path) { !non_ascii_when_export); if (QFile::exists(out_path)) { - auto out_file_name = boost::format(_("The target file %1% already exists, " - "do you need to overwrite it?")) % - out_path.filename(); - auto ret = - QMessageBox::warning(this, _("Warning"), out_file_name.str().c_str(), - QMessageBox::Ok | QMessageBox::Cancel); + auto out_file_name = QString(_("The target file %1 already exists, " + "do you need to overwrite it?")) + .arg(out_path); + auto ret = QMessageBox::warning(this, _("Warning"), out_file_name, + QMessageBox::Ok | QMessageBox::Cancel); if (ret == QMessageBox::Cancel) return; } @@ -181,8 +177,7 @@ void MainWindow::SlotDirectoryEncrypt(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } @@ -201,7 +196,8 @@ void MainWindow::SlotDirectoryEncrypt(std::filesystem::path path) { this, _("Archiving & Symmetrically Encrypting"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().EncryptDerectorySymmetric( - path, !non_ascii_when_export, out_path, + path.toStdString(), !non_ascii_when_export, + out_path.toStdString(), [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -234,7 +230,7 @@ void MainWindow::SlotDirectoryEncrypt(std::filesystem::path path) { nullptr, _("Invalid KeyPair"), QString(_("The selected keypair cannot be used for encryption.")) + "<br/><br/>" + _("For example the Following Key:") + " <br/>" + - QString::fromStdString(key.GetUIDs()->front().GetUID())); + key.GetUIDs()->front().GetUID()); return; } } @@ -242,8 +238,9 @@ void MainWindow::SlotDirectoryEncrypt(std::filesystem::path path) { CommonUtils::WaitForOpera( this, _("Archiving & Encrypting"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().EncryptDirectory( - {p_keys->begin(), p_keys->end()}, path, !non_ascii_when_export, - out_path, [=](GpgError err, const DataObjectPtr& data_obj) { + {p_keys->begin(), p_keys->end()}, path.toStdString(), + !non_ascii_when_export, out_path.toStdString(), + [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -261,17 +258,17 @@ void MainWindow::SlotDirectoryEncrypt(std::filesystem::path path) { }); } -void MainWindow::SlotFileDecrypt(std::filesystem::path path) { +void MainWindow::SlotFileDecrypt(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")) + .arg(QFileInfo(path).fileName())); return; } auto out_path = SetExtensionOfOutputFile(path, kDECRYPT, true); - if (exists(out_path)) { + if (QFileInfo(out_path).exists()) { auto ret = QMessageBox::warning( this, _("Warning"), _("The target file already exists, do you need to overwrite it?"), @@ -283,15 +280,15 @@ void MainWindow::SlotFileDecrypt(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } CommonUtils::WaitForOpera( this, _("Decrypting"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().DecryptFile( - path, out_path, [=](GpgError err, const DataObjectPtr& data_obj) { + path.toStdString(), out_path.toStdString(), + [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -309,17 +306,16 @@ void MainWindow::SlotFileDecrypt(std::filesystem::path path) { }); } -void MainWindow::SlotArchiveDecrypt(std::filesystem::path path) { +void MainWindow::SlotArchiveDecrypt(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")).arg(path)); return; } auto out_path = SetExtensionOfOutputFileForArchive(path, kDECRYPT, true); - if (exists(out_path)) { + if (QFileInfo(out_path).exists()) { auto ret = QMessageBox::warning( this, _("Warning"), _("The target file already exists, do you need to overwrite it?"), @@ -331,15 +327,15 @@ void MainWindow::SlotArchiveDecrypt(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } CommonUtils::WaitForOpera( this, _("Decrypting & Extrating"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().DecryptArchive( - path, out_path, [=](GpgError err, const DataObjectPtr& data_obj) { + path.toStdString(), out_path.toStdString(), + [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -357,12 +353,12 @@ void MainWindow::SlotArchiveDecrypt(std::filesystem::path path) { }); } -void MainWindow::SlotFileSign(std::filesystem::path path) { +void MainWindow::SlotFileSign(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")) + .arg(QFileInfo(path).fileName())); return; } @@ -383,7 +379,7 @@ void MainWindow::SlotFileSign(std::filesystem::path path) { QString(_("The selected key contains a key that does not actually " "have a sign usage.")) + "<br/><br/>" + _("for example the Following Key:") + " <br/>" + - QString::fromStdString(key.GetUIDs()->front().GetUID())); + key.GetUIDs()->front().GetUID()); return; } } @@ -394,13 +390,13 @@ void MainWindow::SlotFileSign(std::filesystem::path path) { auto sig_file_path = SetExtensionOfOutputFile(path, kSIGN, !non_ascii_when_export); - if (exists(sig_file_path)) { - auto ret = QMessageBox::warning( - this, _("Warning"), - QString(_("The signature file \"%1\" exists, " - "do you need to overwrite it?")) - .arg(sig_file_path.filename().u8string().c_str()), - QMessageBox::Ok | QMessageBox::Cancel); + if (QFileInfo(sig_file_path).exists()) { + auto ret = + QMessageBox::warning(this, _("Warning"), + QString(_("The signature file \"%1\" exists, " + "do you need to overwrite it?")) + .arg(sig_file_path), + QMessageBox::Ok | QMessageBox::Cancel); if (ret == QMessageBox::Cancel) return; } @@ -408,8 +404,9 @@ void MainWindow::SlotFileSign(std::filesystem::path path) { CommonUtils::WaitForOpera( this, _("Signing"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().SignFile( - {keys->begin(), keys->end()}, path, !non_ascii_when_export, - sig_file_path, [=](GpgError err, const DataObjectPtr& data_obj) { + {keys->begin(), keys->end()}, path.toStdString(), + !non_ascii_when_export, sig_file_path.toStdString(), + [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -427,43 +424,44 @@ void MainWindow::SlotFileSign(std::filesystem::path path) { }); } -void MainWindow::SlotFileVerify(std::filesystem::path path) { +void MainWindow::SlotFileVerify(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")) + .arg(QFileInfo(path).fileName())); return; } - std::filesystem::path sign_file_path = path; - std::filesystem::path data_file_path; + auto file_info = QFileInfo(path); + QString sign_file_path = path; + QString data_file_path; bool const prossible_singleton_target = - path.extension() == ".gpg" || path.extension() == ".pgp"; + file_info.suffix() == "gpg" || file_info.suffix() == "pgp"; if (prossible_singleton_target) { swap(data_file_path, sign_file_path); } else { - data_file_path = sign_file_path.parent_path() / sign_file_path.stem(); + data_file_path = file_info.path() + "/" + file_info.baseName(); } - if (!prossible_singleton_target && !std::filesystem::exists(data_file_path)) { + auto data_file_info = QFileInfo(data_file_path); + if (!prossible_singleton_target && !data_file_info.exists()) { bool ok; QString const text = QInputDialog::getText( this, _("File to be Verified"), _("Please provide An ABSOLUTE Path \n" "If Data And Signature is COMBINED within a single file, " "KEEP THIS EMPTY: "), - QLineEdit::Normal, data_file_path.u8string().c_str(), &ok); + QLineEdit::Normal, data_file_path, &ok); if (!ok) return; - data_file_path = - text.isEmpty() ? path : std::filesystem::path{text.toStdString()}; + data_file_path = text.isEmpty() ? path : text; } - if (!is_regular_file(data_file_path) || - (!sign_file_path.empty() && !is_regular_file(sign_file_path))) { + if (!data_file_info.isFile() || + (!sign_file_path.isEmpty() && !QFileInfo(sign_file_path).isFile())) { QMessageBox::critical( this, _("Error"), _("Please select the appropriate origin file or signature file. " @@ -471,14 +469,13 @@ void MainWindow::SlotFileVerify(std::filesystem::path path) { return; } - GF_UI_LOG_DEBUG("verification data file path: {}", data_file_path.u8string()); - GF_UI_LOG_DEBUG("verification signature file path: {}", - sign_file_path.u8string()); + 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, _("Verifying"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().VerifyFile( - data_file_path.u8string(), sign_file_path.u8string(), + data_file_path.toStdString(), sign_file_path.toStdString(), [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -504,12 +501,11 @@ void MainWindow::SlotFileVerify(std::filesystem::path path) { }); } -void MainWindow::SlotFileEncryptSign(std::filesystem::path path) { +void MainWindow::SlotFileEncryptSign(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")).arg(path)); return; } @@ -533,7 +529,7 @@ void MainWindow::SlotFileEncryptSign(std::filesystem::path path) { nullptr, _("Invalid KeyPair"), QString(_("The selected keypair cannot be used for encryption.")) + "<br/><br/>" + _("For example the Following Key:") + " <br/>" + - QString::fromStdString(key.GetUIDs()->front().GetUID())); + key.GetUIDs()->front().GetUID()); return; } } @@ -547,8 +543,7 @@ void MainWindow::SlotFileEncryptSign(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } @@ -576,8 +571,8 @@ void MainWindow::SlotFileEncryptSign(std::filesystem::path path) { this, _("Encrypting and Signing"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().EncryptSignFile( {p_keys->begin(), p_keys->end()}, - {p_signer_keys->begin(), p_signer_keys->end()}, path, - !non_ascii_when_export, out_path, + {p_signer_keys->begin(), p_signer_keys->end()}, path.toStdString(), + !non_ascii_when_export, out_path.toStdString(), [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -605,12 +600,11 @@ void MainWindow::SlotFileEncryptSign(std::filesystem::path path) { }); } -void MainWindow::SlotDirectoryEncryptSign(std::filesystem::path path) { +void MainWindow::SlotDirectoryEncryptSign(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")).arg(path)); return; } @@ -634,7 +628,7 @@ void MainWindow::SlotDirectoryEncryptSign(std::filesystem::path path) { nullptr, _("Invalid KeyPair"), QString(_("The selected keypair cannot be used for encryption.")) + "<br/><br/>" + _("For example the Following Key:") + " <br/>" + - QString::fromStdString(key.GetUIDs()->front().GetUID())); + key.GetUIDs()->front().GetUID()); return; } } @@ -648,8 +642,7 @@ void MainWindow::SlotDirectoryEncryptSign(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } @@ -678,8 +671,8 @@ void MainWindow::SlotDirectoryEncryptSign(std::filesystem::path path) { [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().EncryptSignDirectory( {p_keys->begin(), p_keys->end()}, - {p_signer_keys->begin(), p_signer_keys->end()}, path, - !non_ascii_when_export, out_path, + {p_signer_keys->begin(), p_signer_keys->end()}, path.toStdString(), + !non_ascii_when_export, out_path.toStdString(), [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -707,12 +700,11 @@ void MainWindow::SlotDirectoryEncryptSign(std::filesystem::path path) { }); } -void MainWindow::SlotFileDecryptVerify(std::filesystem::path path) { +void MainWindow::SlotFileDecryptVerify(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")).arg(path)); return; } @@ -721,17 +713,16 @@ void MainWindow::SlotFileDecryptVerify(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } - if (QFile::exists(out_path.u8string().c_str())) { + if (QFile::exists(out_path)) { auto ret = QMessageBox::warning(this, _("Warning"), QString(_("The output file %1 already exists, do " "you need to overwrite it?")) - .arg(out_path.filename().u8string().c_str()), + .arg(out_path), QMessageBox::Ok | QMessageBox::Cancel); if (ret == QMessageBox::Cancel) return; @@ -740,7 +731,8 @@ void MainWindow::SlotFileDecryptVerify(std::filesystem::path path) { CommonUtils::WaitForOpera( this, _("Decrypting and Verifying"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().DecryptVerifyFile( - path, out_path, [=](GpgError err, const DataObjectPtr& data_obj) { + path.toStdString(), out_path.toStdString(), + [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); @@ -774,12 +766,11 @@ void MainWindow::SlotFileDecryptVerify(std::filesystem::path path) { }); } -void MainWindow::SlotArchiveDecryptVerify(std::filesystem::path path) { +void MainWindow::SlotArchiveDecryptVerify(const QString& path) { auto check_result = TargetFilePreCheck(path, true); if (!std::get<0>(check_result)) { - QMessageBox::critical( - this, _("Error"), - QString(_("Cannot read from file: %1")).arg(path.filename().c_str())); + QMessageBox::critical(this, _("Error"), + QString(_("Cannot read from file: %1")).arg(path)); return; } @@ -789,17 +780,16 @@ void MainWindow::SlotArchiveDecryptVerify(std::filesystem::path path) { check_result = TargetFilePreCheck(out_path, false); if (!std::get<0>(check_result)) { QMessageBox::critical(this, _("Error"), - QString(_("Cannot write to file: %1")) - .arg(out_path.filename().c_str())); + QString(_("Cannot write to file: %1")).arg(out_path)); return; } - if (QFile::exists(out_path.u8string().c_str())) { + if (QFile::exists(out_path)) { auto ret = QMessageBox::warning(this, _("Warning"), QString(_("The output file %1 already exists, do " "you need to overwrite it?")) - .arg(out_path.filename().u8string().c_str()), + .arg(out_path), QMessageBox::Ok | QMessageBox::Cancel); if (ret == QMessageBox::Cancel) return; @@ -809,7 +799,8 @@ void MainWindow::SlotArchiveDecryptVerify(std::filesystem::path path) { this, _("Decrypting & Verifying & Extracting"), [=](const OperaWaitingHd& op_hd) { GpgFileOpera::GetInstance().DecryptVerifyArchive( - path, out_path, [=](GpgError err, const DataObjectPtr& data_obj) { + path.toStdString(), out_path.toStdString(), + [=](GpgError err, const DataObjectPtr& data_obj) { // stop waiting op_hd(); diff --git a/src/ui/main_window/MainWindowGpgOperaFunction.cpp b/src/ui/main_window/MainWindowGpgOperaFunction.cpp index 1efff3df..cf7e2d68 100644 --- a/src/ui/main_window/MainWindowGpgOperaFunction.cpp +++ b/src/ui/main_window/MainWindowGpgOperaFunction.cpp @@ -98,7 +98,7 @@ void MainWindow::SlotEncrypt() { _("The selected key contains a key that does not actually have a " "encrypt usage.")) + "<br/><br/>" + _("For example the Following Key:") + " <br/>" + - QString::fromStdString(key.GetUIDs()->front().GetUID())); + key.GetUIDs()->front().GetUID()); return; } } @@ -152,7 +152,7 @@ void MainWindow::SlotSign() { _("The selected key contains a key that does not actually have a " "signature usage.")) + "<br/><br/>" + _("For example the Following Key:") + "<br/>" + - key.GetUIDs()->front().GetUID().c_str()); + key.GetUIDs()->front().GetUID()); return; } } @@ -267,7 +267,7 @@ void MainWindow::SlotEncryptSign() { this, _("Invalid KeyPair"), QString(_("The selected keypair cannot be used for encryption.")) + "<br/><br/>" + _("For example the Following Key:") + " <br/>" + - QString::fromStdString(key.GetUIDs()->front().GetUID())); + key.GetUIDs()->front().GetUID()); return; } } diff --git a/src/ui/main_window/MainWindowSlotFunction.cpp b/src/ui/main_window/MainWindowSlotFunction.cpp index 6e87d6b6..698a63b1 100644 --- a/src/ui/main_window/MainWindowSlotFunction.cpp +++ b/src/ui/main_window/MainWindowSlotFunction.cpp @@ -104,11 +104,11 @@ void MainWindow::slot_append_keys_create_datetime() { } auto create_datetime_format_str = - boost::posix_time::to_iso_extended_string(key.GetCreateTime()) + + QString::fromStdString( + boost::posix_time::to_iso_extended_string(key.GetCreateTime())) + " (UTC) " + "\n"; - edit_->SlotAppendText2CurTextPage( - QString::fromStdString(create_datetime_format_str)); + edit_->SlotAppendText2CurTextPage(create_datetime_format_str); } void MainWindow::slot_append_keys_expire_datetime() { @@ -126,11 +126,11 @@ void MainWindow::slot_append_keys_expire_datetime() { } auto create_datetime_format_str = - boost::posix_time::to_iso_extended_string(key.GetCreateTime()) + + QString::fromStdString( + boost::posix_time::to_iso_extended_string(key.GetCreateTime())) + " (UTC) " + "\n"; - edit_->SlotAppendText2CurTextPage( - QString::fromStdString(create_datetime_format_str)); + edit_->SlotAppendText2CurTextPage(create_datetime_format_str); } void MainWindow::slot_append_keys_fingerprint() { @@ -146,8 +146,7 @@ void MainWindow::slot_append_keys_fingerprint() { auto fingerprint_format_str = BeautifyFingerprint(key.GetFingerprint()) + "\n"; - edit_->SlotAppendText2CurTextPage( - QString::fromStdString(fingerprint_format_str)); + edit_->SlotAppendText2CurTextPage(fingerprint_format_str); } void MainWindow::slot_copy_mail_address_to_clipboard() { @@ -160,7 +159,7 @@ void MainWindow::slot_copy_mail_address_to_clipboard() { return; } QClipboard* cb = QApplication::clipboard(); - cb->setText(QString::fromStdString(key.GetEmail())); + cb->setText(key.GetEmail()); } void MainWindow::slot_copy_default_uid_to_clipboard() { @@ -173,7 +172,7 @@ void MainWindow::slot_copy_default_uid_to_clipboard() { return; } QClipboard* cb = QApplication::clipboard(); - cb->setText(QString::fromStdString(key.GetUIDs()->front().GetUID())); + cb->setText(key.GetUIDs()->front().GetUID()); } void MainWindow::slot_copy_key_id_to_clipboard() { @@ -186,7 +185,7 @@ void MainWindow::slot_copy_key_id_to_clipboard() { return; } QClipboard* cb = QApplication::clipboard(); - cb->setText(QString::fromStdString(key.GetId())); + cb->setText(key.GetId()); } void MainWindow::slot_show_key_details() { @@ -294,7 +293,7 @@ void MainWindow::slot_version_upgrade_nofity() { auto latest_version = Module::RetrieveRTValueTypedOrDefault<>( "com.bktus.gpgfrontend.module.integrated.version-checking", - "version.latest_version", std::string{}); + "version.latest_version", QString{}); GF_UI_LOG_DEBUG( "got version info from rt, need upgrade: {}, with drawn: {}, current " @@ -306,7 +305,7 @@ void MainWindow::slot_version_upgrade_nofity() { if (is_need_upgrade) { statusBar()->showMessage( QString(_("GpgFrontend Upgradeable (New Version: %1).")) - .arg(latest_version.c_str()), + .arg(latest_version), 30000); auto* update_button = new QPushButton("Update GpgFrontend", this); connect(update_button, &QPushButton::clicked, [=]() { @@ -321,16 +320,16 @@ void MainWindow::slot_version_upgrade_nofity() { _("This version(%1) may have been withdrawn by the developer due " "to serious problems. Please stop using this version " "immediately and use the latest stable version.")) - .arg(latest_version.c_str()) + + .arg(latest_version) + "<br/>" + QString(_("You can download the latest stable version(%1) on " "Github Releases " "Page.<br/>")) - .arg(latest_version.c_str())); + .arg(latest_version)); } else if (!is_current_version_released) { statusBar()->showMessage( QString(_("This maybe a BETA Version (Latest Stable Version: %1).")) - .arg(latest_version.c_str()), + .arg(latest_version), 30000); } } diff --git a/src/ui/main_window/MainWindowSlotUI.cpp b/src/ui/main_window/MainWindowSlotUI.cpp index 430271ea..772204b1 100644 --- a/src/ui/main_window/MainWindowSlotUI.cpp +++ b/src/ui/main_window/MainWindowSlotUI.cpp @@ -28,6 +28,7 @@ #include "MainWindow.h" #include "core/GpgConstants.h" +#include "core/model/GpgPassphraseContext.h" #include "ui/UserInterfaceUtils.h" #include "ui/dialog/Wizard.h" #include "ui/function/RaisePinentry.h" @@ -49,7 +50,7 @@ void MainWindow::slot_start_wizard() { void MainWindow::slot_import_key_from_edit() { if (edit_->TabCount() == 0 || edit_->SlotCurPageTextEdit() == nullptr) return; CommonUtils::GetInstance()->SlotImportKeys( - this, edit_->CurTextPage()->GetTextPage()->toPlainText().toStdString()); + this, edit_->CurTextPage()->GetTextPage()->toPlainText()); } void MainWindow::slot_open_key_management() { @@ -219,8 +220,9 @@ void MainWindow::SetCryptoMenuStatus( } } -void MainWindow::SlotRaisePinentry() { - auto* function = new RaisePinentry(this); +void MainWindow::SlotRaisePinentry( + QSharedPointer<GpgPassphraseContext> context) { + auto* function = new RaisePinentry(this, context); function->Exec(); } diff --git a/src/ui/main_window/MainWindowUI.cpp b/src/ui/main_window/MainWindowUI.cpp index e710081c..88c198e4 100644 --- a/src/ui/main_window/MainWindowUI.cpp +++ b/src/ui/main_window/MainWindowUI.cpp @@ -187,8 +187,7 @@ void MainWindow::create_actions() { connect(encrypt_act_, &QAction::triggered, this, [this]() { if (edit_->SlotCurPageFileTreeView() != nullptr) { const auto* file_tree_view = edit_->SlotCurPageFileTreeView(); - const auto path_qstr = file_tree_view->GetSelected(); - const auto path = ConvertPathByOS(path_qstr); + const auto path = file_tree_view->GetSelected(); const auto file_info = QFileInfo(path); if (file_info.isFile()) { @@ -214,8 +213,7 @@ void MainWindow::create_actions() { connect(encrypt_sign_act_, &QAction::triggered, this, [this]() { if (edit_->SlotCurPageFileTreeView() != nullptr) { const auto* file_tree_view = edit_->SlotCurPageFileTreeView(); - const auto path_qstr = file_tree_view->GetSelected(); - const auto path = ConvertPathByOS(path_qstr); + const auto path = file_tree_view->GetSelected(); const auto file_info = QFileInfo(path); if (file_info.isFile()) { @@ -240,16 +238,13 @@ void MainWindow::create_actions() { connect(decrypt_act_, &QAction::triggered, this, [this]() { if (edit_->SlotCurPageFileTreeView() != nullptr) { const auto* file_tree_view = edit_->SlotCurPageFileTreeView(); - const auto path_qstr = file_tree_view->GetSelected(); - const auto path = ConvertPathByOS(path_qstr); + const auto path = file_tree_view->GetSelected(); const auto file_info = QFileInfo(path); if (file_info.isFile()) { - const std::string filename = path.filename().string(); - const std::string extension( - std::find(filename.begin(), filename.end(), '.'), filename.end()); + const QString extension = file_info.completeSuffix(); - if (extension == ".tar.gpg" || extension == ".tar.asc") { + if (extension == "tar.gpg" || extension == "tar.asc") { this->SlotArchiveDecrypt(path); } else { this->SlotFileDecrypt(path); @@ -273,14 +268,11 @@ void MainWindow::create_actions() { connect(decrypt_verify_act_, &QAction::triggered, this, [this]() { if (edit_->SlotCurPageFileTreeView() != nullptr) { const auto* file_tree_view = edit_->SlotCurPageFileTreeView(); - const auto path_qstr = file_tree_view->GetSelected(); - const auto path = ConvertPathByOS(path_qstr); + const auto path = file_tree_view->GetSelected(); const auto file_info = QFileInfo(path); if (file_info.isFile()) { - const std::string filename = path.filename().string(); - const std::string extension( - std::find(filename.begin(), filename.end(), '.'), filename.end()); + const QString extension = file_info.completeSuffix(); if (extension == ".tar.gpg" || extension == ".tar.asc") { this->SlotArchiveDecryptVerify(path); @@ -305,8 +297,7 @@ void MainWindow::create_actions() { connect(sign_act_, &QAction::triggered, this, [this]() { if (edit_->SlotCurPageFileTreeView() != nullptr) { const auto* file_tree_view = edit_->SlotCurPageFileTreeView(); - const auto path_qstr = file_tree_view->GetSelected(); - const auto path = ConvertPathByOS(path_qstr); + const auto path = file_tree_view->GetSelected(); const auto file_info = QFileInfo(path); if (file_info.isFile()) this->SlotFileSign(path); @@ -325,8 +316,7 @@ void MainWindow::create_actions() { connect(verify_act_, &QAction::triggered, this, [this]() { if (edit_->SlotCurPageFileTreeView() != nullptr) { const auto* file_tree_view = edit_->SlotCurPageFileTreeView(); - const auto path_qstr = file_tree_view->GetSelected(); - const auto path = ConvertPathByOS(path_qstr); + const auto path = file_tree_view->GetSelected(); const auto file_info = QFileInfo(path); if (file_info.isFile()) this->SlotFileVerify(path); diff --git a/src/ui/struct/SettingsObject.cpp b/src/ui/struct/SettingsObject.cpp index cf11fc5e..d03a4fe3 100644 --- a/src/ui/struct/SettingsObject.cpp +++ b/src/ui/struct/SettingsObject.cpp @@ -29,7 +29,7 @@ #include "SettingsObject.h" nlohmann::json& GpgFrontend::UI::SettingsObject::Check( - const std::string& key, const nlohmann::json& default_value) { + const QString& key, const nlohmann::json& default_value) { // check if the self null if (this->nlohmann::json::is_null()) { GF_UI_LOG_DEBUG("settings object is null, creating new one"); @@ -37,19 +37,20 @@ nlohmann::json& GpgFrontend::UI::SettingsObject::Check( } try { - if (!this->nlohmann::json::contains(key) || - this->nlohmann::json::at(key).is_null() || - this->nlohmann::json::at(key).type_name() != + auto s_key = key.toStdString(); + if (!this->nlohmann::json::contains(s_key) || + this->nlohmann::json::at(s_key).is_null() || + this->nlohmann::json::at(s_key).type_name() != default_value.type_name()) { GF_UI_LOG_DEBUG("added missing key: {}", key); if (default_value.is_null()) { GF_UI_LOG_WARN("default value is null, using empty object"); - this->nlohmann::json::operator[](key) = nlohmann::json::object(); + this->nlohmann::json::operator[](s_key) = nlohmann::json::object(); } else { - this->nlohmann::json::operator[](key) = default_value; + this->nlohmann::json::operator[](s_key) = default_value; } } - return this->nlohmann::json::at(key); + return this->nlohmann::json::at(s_key); } catch (nlohmann::json::exception& e) { GF_UI_LOG_ERROR(e.what()); throw e; @@ -57,23 +58,25 @@ nlohmann::json& GpgFrontend::UI::SettingsObject::Check( } GpgFrontend::UI::SettingsObject GpgFrontend::UI::SettingsObject::Check( - const std::string& key) { + const QString& key) { // check if the self null if (this->nlohmann::json::is_null()) { GF_UI_LOG_DEBUG("settings object is null, creating new one"); this->nlohmann::json::operator=(nlohmann::json::object()); } - if (!nlohmann::json::contains(key) || - this->nlohmann::json::at(key).is_null() || - this->nlohmann::json::at(key).type() != nlohmann::json::value_t::object) { + auto s_key = key.toStdString(); + if (!nlohmann::json::contains(s_key) || + this->nlohmann::json::at(s_key).is_null() || + this->nlohmann::json::at(s_key).type() != + nlohmann::json::value_t::object) { GF_UI_LOG_DEBUG("added missing key: {}", key); - this->nlohmann::json::operator[](key) = nlohmann::json::object(); + this->nlohmann::json::operator[](s_key) = nlohmann::json::object(); } - return SettingsObject{nlohmann::json::operator[](key), false}; + return SettingsObject{nlohmann::json::operator[](s_key), false}; } -GpgFrontend::UI::SettingsObject::SettingsObject(std::string settings_name) +GpgFrontend::UI::SettingsObject::SettingsObject(QString settings_name) : settings_name_(std::move(settings_name)) { try { GF_UI_LOG_DEBUG("loading settings from: {}", this->settings_name_); @@ -95,10 +98,11 @@ GpgFrontend::UI::SettingsObject::SettingsObject(std::string settings_name) } GpgFrontend::UI::SettingsObject::SettingsObject(nlohmann::json _sub_json, bool) - : nlohmann::json(std::move(_sub_json)), settings_name_({}) {} + : nlohmann::json(std::move(_sub_json)) {} GpgFrontend::UI::SettingsObject::~SettingsObject() { - if (!settings_name_.empty()) + if (!settings_name_.isEmpty()) { GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(settings_name_, *this); + } }
\ No newline at end of file diff --git a/src/ui/struct/SettingsObject.h b/src/ui/struct/SettingsObject.h index 8bda90ea..25e459ac 100644 --- a/src/ui/struct/SettingsObject.h +++ b/src/ui/struct/SettingsObject.h @@ -46,7 +46,7 @@ class SettingsObject : public nlohmann::json { * * @param settings_name The name of the settings object */ - explicit SettingsObject(std::string settings_name); + explicit SettingsObject(QString settings_name); /** * @brief Construct a new Settings Object object @@ -68,7 +68,7 @@ class SettingsObject : public nlohmann::json { * @param default_value * @return nlohmann::json& */ - nlohmann::json& Check(const std::string& key, + nlohmann::json& Check(const QString& key, const nlohmann::json& default_value); /** @@ -77,9 +77,9 @@ class SettingsObject : public nlohmann::json { * @param key * @return SettingsObject */ - SettingsObject Check(const std::string& key); + SettingsObject Check(const QString& key); private: - std::string settings_name_; ///< + QString settings_name_; ///< }; } // namespace GpgFrontend::UI diff --git a/src/ui/thread/KeyServerImportTask.cpp b/src/ui/thread/KeyServerImportTask.cpp index e07473a8..4e8a41db 100644 --- a/src/ui/thread/KeyServerImportTask.cpp +++ b/src/ui/thread/KeyServerImportTask.cpp @@ -32,14 +32,14 @@ #include "ui/struct/SettingsObject.h" GpgFrontend::UI::KeyServerImportTask::KeyServerImportTask( - std::string keyserver_url, std::vector<std::string> keyids) + QString keyserver_url, std::vector<QString> keyids) : Task("key_server_import_task"), keyserver_url_(std::move(keyserver_url)), keyids_(std::move(keyids)), manager_(new QNetworkAccessManager(this)) { HoldOnLifeCycle(true); - if (keyserver_url_.empty()) { + if (keyserver_url_.isEmpty()) { try { SettingsObject key_server_json("key_server"); const auto key_server_list = @@ -53,7 +53,7 @@ GpgFrontend::UI::KeyServerImportTask::KeyServerImportTask( auto default_key_server = key_server_list[default_key_server_index].get<std::string>(); - keyserver_url_ = default_key_server; + keyserver_url_ = QString::fromStdString(default_key_server); } catch (...) { GF_UI_LOG_ERROR("setting operation error", "server_list", "default_server"); @@ -67,11 +67,10 @@ GpgFrontend::UI::KeyServerImportTask::KeyServerImportTask( } void GpgFrontend::UI::KeyServerImportTask::Run() { - QUrl const keyserver_url = QUrl(keyserver_url_.c_str()); + QUrl const keyserver_url = QUrl(keyserver_url_); for (const auto& key_id : keyids_) { QUrl const req_url(keyserver_url.scheme() + "://" + keyserver_url.host() + - "/pks/lookup?op=get&search=0x" + key_id.c_str() + - "&options=mr"); + "/pks/lookup?op=get&search=0x" + key_id + "&options=mr"); reply_ = manager_->get(QNetworkRequest(req_url)); connect(reply_, &QNetworkReply::finished, this, diff --git a/src/ui/thread/KeyServerImportTask.h b/src/ui/thread/KeyServerImportTask.h index 5416ca1a..c03283c9 100644 --- a/src/ui/thread/KeyServerImportTask.h +++ b/src/ui/thread/KeyServerImportTask.h @@ -48,8 +48,7 @@ class KeyServerImportTask : public Thread::Task { * @param keyserver_url * @param search_string */ - KeyServerImportTask(std::string keyserver_url, - std::vector<std::string> keyid); + KeyServerImportTask(QString keyserver_url, std::vector<QString> keyid); /** * @brief @@ -76,8 +75,8 @@ class KeyServerImportTask : public Thread::Task { void dealing_reply_from_server(); private: - std::string keyserver_url_; ///< - std::vector<std::string> keyids_; ///< + QString keyserver_url_; ///< + std::vector<QString> keyids_; ///< int result_count_ = 0; QNetworkAccessManager *manager_; ///< diff --git a/src/ui/thread/KeyServerSearchTask.cpp b/src/ui/thread/KeyServerSearchTask.cpp index dfaa6474..b0e253f0 100644 --- a/src/ui/thread/KeyServerSearchTask.cpp +++ b/src/ui/thread/KeyServerSearchTask.cpp @@ -30,8 +30,8 @@ #include <utility> -GpgFrontend::UI::KeyServerSearchTask::KeyServerSearchTask( - std::string keyserver_url, std::string search_string) +GpgFrontend::UI::KeyServerSearchTask::KeyServerSearchTask(QString keyserver_url, + QString search_string) : Task("key_server_search_task"), keyserver_url_(std::move(keyserver_url)), search_string_(std::move(search_string)), @@ -40,10 +40,9 @@ GpgFrontend::UI::KeyServerSearchTask::KeyServerSearchTask( } void GpgFrontend::UI::KeyServerSearchTask::Run() { - QUrl url_from_remote = - QString::fromStdString(keyserver_url_) + - "/pks/lookup?search=" + QString::fromStdString(search_string_) + - "&op=index&options=mr"; + QUrl url_from_remote = keyserver_url_ + + "/pks/lookup?search=" + search_string_ + + "&op=index&options=mr"; reply_ = manager_->get(QNetworkRequest(url_from_remote)); diff --git a/src/ui/thread/KeyServerSearchTask.h b/src/ui/thread/KeyServerSearchTask.h index ea92903f..cfe4e623 100644 --- a/src/ui/thread/KeyServerSearchTask.h +++ b/src/ui/thread/KeyServerSearchTask.h @@ -44,7 +44,7 @@ class KeyServerSearchTask : public Thread::Task { * @param keyserver_url * @param search_string */ - KeyServerSearchTask(std::string keyserver_url, std::string search_string); + KeyServerSearchTask(QString keyserver_url, QString search_string); /** * @brief @@ -67,8 +67,8 @@ class KeyServerSearchTask : public Thread::Task { void dealing_reply_from_server(); private: - std::string keyserver_url_; ///< - std::string search_string_; ///< + QString keyserver_url_; ///< + QString search_string_; ///< QNetworkAccessManager *manager_; ///< QNetworkReply *reply_; ///< diff --git a/src/ui/widgets/FileTreeView.cpp b/src/ui/widgets/FileTreeView.cpp index 8139fbf9..ef0fbf48 100644 --- a/src/ui/widgets/FileTreeView.cpp +++ b/src/ui/widgets/FileTreeView.cpp @@ -386,7 +386,7 @@ void FileTreeView::slot_show_custom_context_menu(const QPoint& point) { void FileTreeView::slot_calculate_hash() { emit UISignalStation::GetInstance()->SignalRefreshInfoBoard( - QString::fromStdString(CalculateHash(this->GetSelectedPath())), + CalculateHash(this->GetSelectedPath().c_str()), InfoBoardStatus::INFO_ERROR_OK); } diff --git a/src/ui/widgets/InfoBoardWidget.cpp b/src/ui/widgets/InfoBoardWidget.cpp index 8dddded5..26530f8d 100644 --- a/src/ui/widgets/InfoBoardWidget.cpp +++ b/src/ui/widgets/InfoBoardWidget.cpp @@ -29,7 +29,6 @@ #include "ui/widgets/InfoBoardWidget.h" #include "core/GpgModel.h" -#include "core/function/GlobalSettingStation.h" #include "ui/UISignalStation.h" #include "ui/struct/SettingsObject.h" #include "ui_InfoBoard.h" @@ -97,9 +96,10 @@ void InfoBoardWidget::SlotRefresh(const QString& text, InfoBoardStatus status) { } void InfoBoardWidget::AssociateTextEdit(QTextEdit* edit) { - if (m_text_page_ != nullptr) + if (m_text_page_ != nullptr) { disconnect(m_text_page_, &QTextEdit::textChanged, this, &InfoBoardWidget::SlotReset); + } this->m_text_page_ = edit; connect(edit, &QTextEdit::textChanged, this, &InfoBoardWidget::SlotReset); } @@ -117,14 +117,14 @@ void InfoBoardWidget::AssociateTabWidget(QTabWidget* tab) { void InfoBoardWidget::AddOptionalAction(const QString& name, const std::function<void()>& action) { GF_UI_LOG_DEBUG("add option: {}", name.toStdString()); - auto actionButton = new QPushButton(name); - auto layout = new QHBoxLayout(); + auto* action_button = new QPushButton(name); + auto* layout = new QHBoxLayout(); layout->setContentsMargins(5, 0, 5, 0); ui_->infoBoard->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); // set margin from surroundings - layout->addWidget(actionButton); + layout->addWidget(action_button); ui_->actionButtonLayout->addLayout(layout); - connect(actionButton, &QPushButton::clicked, this, [=]() { action(); }); + connect(action_button, &QPushButton::clicked, this, [=]() { action(); }); } /** @@ -149,10 +149,11 @@ void InfoBoardWidget::delete_widgets_in_layout(QLayout* layout, QLayoutItem* item; while ((item = layout->layout()->takeAt(start_index)) != nullptr) { layout->removeItem(item); - if (item->layout() != nullptr) + if (item->layout() != nullptr) { delete_widgets_in_layout(item->layout()); - else if (item->widget() != nullptr) + } else if (item->widget() != nullptr) { delete item->widget(); + } delete item; } } diff --git a/src/ui/widgets/KeyList.cpp b/src/ui/widgets/KeyList.cpp index 135a3c6d..0f97a2c9 100644 --- a/src/ui/widgets/KeyList.cpp +++ b/src/ui/widgets/KeyList.cpp @@ -28,7 +28,6 @@ #include "ui/widgets/KeyList.h" -#include <boost/format.hpp> #include <cstddef> #include <mutex> #include <utility> @@ -36,11 +35,9 @@ #include "core/GpgCoreInit.h" #include "core/function/GlobalSettingStation.h" #include "core/function/gpg/GpgKeyGetter.h" -#include "core/model/GpgImportInformation.h" #include "ui/UISignalStation.h" #include "ui/UserInterfaceUtils.h" #include "ui_KeyList.h" -#include "widgets/TextEdit.h" namespace GpgFrontend::UI { @@ -54,7 +51,7 @@ KeyList::KeyList(KeyMenuAbility::AbilityType menu_ability, QWidget* parent) void KeyList::init() { ui_->setupUi(this); - ui_->menuWidget->setHidden(!menu_ability_); + ui_->menuWidget->setHidden(menu_ability_ == 0U); ui_->refreshKeyListButton->setHidden(~menu_ability_ & KeyMenuAbility::REFRESH); ui_->syncButton->setHidden(~menu_ability_ & KeyMenuAbility::SYNC_PUBLIC_KEY); @@ -119,7 +116,7 @@ void KeyList::AddListGroupTab(const QString& name, const QString& id, const KeyTable::KeyTableFilter filter) { GF_UI_LOG_DEBUG("add tab: {}", name.toStdString()); - auto key_list = new QTableWidget(this); + auto* key_list = new QTableWidget(this); if (m_key_list_ == nullptr) { m_key_list_ = key_list; } @@ -146,22 +143,22 @@ void KeyList::AddListGroupTab(const QString& name, const QString& id, key_list->setAlternatingRowColors(true); // Hidden Column For Purpose - if (!(infoType & KeyListColumn::TYPE)) { + if ((infoType & KeyListColumn::TYPE) == 0U) { key_list->setColumnHidden(1, true); } - if (!(infoType & KeyListColumn::NAME)) { + if ((infoType & KeyListColumn::NAME) == 0U) { key_list->setColumnHidden(2, true); } - if (!(infoType & KeyListColumn::EmailAddress)) { + if ((infoType & KeyListColumn::EmailAddress) == 0U) { key_list->setColumnHidden(3, true); } - if (!(infoType & KeyListColumn::Usage)) { + if ((infoType & KeyListColumn::Usage) == 0U) { key_list->setColumnHidden(4, true); } - if (!(infoType & KeyListColumn::Validity)) { + if ((infoType & KeyListColumn::Validity) == 0U) { key_list->setColumnHidden(5, true); } - if (!(infoType & KeyListColumn::FingerPrint)) { + if ((infoType & KeyListColumn::FingerPrint) == 0U) { key_list->setColumnHidden(6, true); } @@ -203,7 +200,7 @@ KeyIdArgsListPtr KeyList::GetChecked(const KeyTable& key_table) { } KeyIdArgsListPtr KeyList::GetChecked() { - auto key_list = + auto* key_list = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); const auto& buffered_keys = m_key_tables_[ui_->keyGroupTab->currentIndex()].buffered_keys_; @@ -217,13 +214,13 @@ KeyIdArgsListPtr KeyList::GetChecked() { } KeyIdArgsListPtr KeyList::GetAllPrivateKeys() { - auto key_list = + auto* key_list = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); const auto& buffered_keys = m_key_tables_[ui_->keyGroupTab->currentIndex()].buffered_keys_; auto ret = std::make_unique<KeyIdArgsList>(); for (int i = 0; i < key_list->rowCount(); i++) { - if (key_list->item(i, 1) && buffered_keys[i].IsPrivateKey()) { + if ((key_list->item(i, 1) != nullptr) && buffered_keys[i].IsPrivateKey()) { ret->push_back(buffered_keys[i].GetId()); } } @@ -234,14 +231,14 @@ KeyIdArgsListPtr KeyList::GetPrivateChecked() { auto ret = std::make_unique<KeyIdArgsList>(); if (ui_->keyGroupTab->size().isEmpty()) return ret; - auto key_list = + auto* key_list = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); const auto& buffered_keys = m_key_tables_[ui_->keyGroupTab->currentIndex()].buffered_keys_; for (int i = 0; i < key_list->rowCount(); i++) { if ((key_list->item(i, 0)->checkState() == Qt::Checked) && - (key_list->item(i, 1))) { + ((key_list->item(i, 1)) != nullptr)) { ret->push_back(buffered_keys[i].GetId()); } } @@ -261,7 +258,7 @@ void KeyList::SetChecked(const KeyIdArgsListPtr& keyIds, } void KeyList::SetChecked(KeyIdArgsListPtr key_ids) { - auto key_list = + auto* key_list = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); if (key_list == nullptr) return; if (!m_key_tables_.empty()) { @@ -278,13 +275,13 @@ KeyIdArgsListPtr KeyList::GetSelected() { auto ret = std::make_unique<KeyIdArgsList>(); if (ui_->keyGroupTab->size().isEmpty()) return ret; - auto key_list = + auto* key_list = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); const auto& buffered_keys = m_key_tables_[ui_->keyGroupTab->currentIndex()].buffered_keys_; for (int i = 0; i < key_list->rowCount(); i++) { - if (key_list->item(i, 0)->isSelected() == 1) { + if (key_list->item(i, 0)->isSelected()) { ret->push_back(buffered_keys[i].GetId()); } } @@ -296,7 +293,7 @@ KeyIdArgsListPtr KeyList::GetSelected() { m_key_list_ = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); for (int i = 0; i < m_key_list_->rowCount(); i++) { - if (m_key_list_->item(i, 1)) { + if (m_key_list_->item(i, 1) != nullptr) { return true; } } @@ -359,22 +356,22 @@ void KeyList::dropEvent(QDropEvent* event) { "\n"); // "always import keys"-CheckBox - auto* checkBox = new QCheckBox(_("Always import without bothering.")); + auto* check_box = new QCheckBox(_("Always import without bothering.")); bool confirm_import_keys = GlobalSettingStation::GetInstance().LookupSettings( "general.confirm_import_keys", true); - if (confirm_import_keys) checkBox->setCheckState(Qt::Checked); + if (confirm_import_keys) check_box->setCheckState(Qt::Checked); // Buttons for ok and cancel - auto* buttonBox = + auto* button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, &QDialogButtonBox::accepted, dialog, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, dialog, &QDialog::reject); + connect(button_box, &QDialogButtonBox::accepted, dialog, &QDialog::accept); + connect(button_box, &QDialogButtonBox::rejected, dialog, &QDialog::reject); auto* vbox = new QVBoxLayout(); vbox->addWidget(label); - vbox->addWidget(checkBox); - vbox->addWidget(buttonBox); + vbox->addWidget(check_box); + vbox->addWidget(button_box); dialog->setLayout(vbox); @@ -385,14 +382,15 @@ void KeyList::dropEvent(QDropEvent* event) { auto& settings = GlobalSettingStation::GetInstance().GetMainSettings(); if (!settings.exists("general") || - settings.lookup("general").getType() != libconfig::Setting::TypeGroup) + settings.lookup("general").getType() != libconfig::Setting::TypeGroup) { settings.add("general", libconfig::Setting::TypeGroup); + } auto& general = settings["general"]; - if (!general.exists("confirm_import_keys")) + if (!general.exists("confirm_import_keys")) { general.add("confirm_import_keys", libconfig::Setting::TypeBoolean) = - checkBox->isChecked(); - else { - general["confirm_import_keys"] = checkBox->isChecked(); + check_box->isChecked(); + } else { + general["confirm_import_keys"] = check_box->isChecked(); } GlobalSettingStation::GetInstance().SyncSettings(); } @@ -404,13 +402,13 @@ void KeyList::dropEvent(QDropEvent* event) { if (!file.open(QIODevice::ReadOnly)) { GF_UI_LOG_ERROR("couldn't open file: {}", tmp.toString().toStdString()); } - QByteArray inBuffer = file.readAll(); - this->import_keys(inBuffer); + QByteArray in_buffer = file.readAll(); + this->import_keys(in_buffer); file.close(); } } else { - QByteArray inBuffer(event->mimeData()->text().toUtf8()); - this->import_keys(inBuffer); + QByteArray in_buffer(event->mimeData()->text().toUtf8()); + this->import_keys(in_buffer); } } @@ -440,13 +438,13 @@ void KeyList::SetDoubleClickedAction( this->m_action_ = std::move(action); } -std::string KeyList::GetSelectedKey() { +QString KeyList::GetSelectedKey() { if (ui_->keyGroupTab->size().isEmpty()) return {}; const auto& buffered_keys = m_key_tables_[ui_->keyGroupTab->currentIndex()].buffered_keys_; for (int i = 0; i < m_key_list_->rowCount(); i++) { - if (m_key_list_->item(i, 0)->isSelected() == 1) { + if (m_key_list_->item(i, 0)->isSelected()) { return buffered_keys[i].GetId(); } } @@ -473,8 +471,9 @@ void KeyList::slot_sync_with_key_server() { { std::lock_guard<std::mutex> guard(buffered_key_list_mutex_); for (const auto& key : *buffered_keys_list_) { - if (!(key.IsPrivateKey() && key.IsHasMasterKey())) + if (!(key.IsPrivateKey() && key.IsHasMasterKey())) { key_ids.push_back(key.GetId()); + } } } @@ -485,16 +484,18 @@ void KeyList::slot_sync_with_key_server() { emit SignalRefreshStatusBar(_("Syncing Key List..."), 3000); CommonUtils::SlotImportKeyFromKeyServer( - key_ids, [=](const std::string& key_id, const std::string& status, + 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); - boost::format status_str = boost::format(_("Sync [%1%/%2%] %3% %4%")) % - current_index % all_index % - key.GetUIDs()->front().GetUID() % status; - emit SignalRefreshStatusBar(status_str.str().c_str(), 1500); + auto status_str = QString(_("Sync [%1/%2] %3 %4")) + .arg(current_index) + .arg(all_index) + .arg(key.GetUIDs()->front().GetUID()) + .arg(status); + emit SignalRefreshStatusBar(status_str, 1500); if (current_index == all_index) { ui_->syncButton->setDisabled(false); @@ -509,10 +510,10 @@ void KeyList::filter_by_keyword() { auto keyword = ui_->searchBarEdit->text(); keyword = keyword.trimmed(); - GF_UI_LOG_DEBUG("get new keyword of search bar: {}", keyword.toStdString()); + GF_UI_LOG_DEBUG("get new keyword of search bar: {}", keyword); for (auto& table : m_key_tables_) { // refresh arguments - table.SetFilterKeyword(keyword.toLower().toStdString()); + table.SetFilterKeyword(keyword.toLower()); table.SetMenuAbility(menu_ability_); } // refresh ui @@ -520,7 +521,7 @@ void KeyList::filter_by_keyword() { } void KeyList::uncheck_all() { - auto key_list = + auto* key_list = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); if (key_list == nullptr) return; if (!m_key_tables_.empty()) { @@ -534,7 +535,7 @@ void KeyList::uncheck_all() { } void KeyList::check_all() { - auto key_list = + auto* key_list = qobject_cast<QTableWidget*>(ui_->keyGroupTab->currentWidget()); if (key_list == nullptr) return; if (!m_key_tables_.empty()) { @@ -548,8 +549,9 @@ void KeyList::check_all() { } KeyIdArgsListPtr& KeyTable::GetChecked() { - if (checked_key_ids_ == nullptr) + if (checked_key_ids_ == nullptr) { checked_key_ids_ = std::make_unique<KeyIdArgsList>(); + } auto& ret = checked_key_ids_; for (size_t i = 0; i < buffered_keys_.size(); i++) { auto key_id = buffered_keys_[i].GetId(); @@ -574,32 +576,24 @@ void KeyTable::Refresh(KeyLinkListPtr m_keys) { // Optimization for copy KeyLinkListPtr keys = nullptr; - if (m_keys == nullptr) + if (m_keys == nullptr) { keys = GpgKeyGetter::GetInstance().FetchKey(); - else + } else { keys = std::move(m_keys); + } auto it = keys->begin(); int row_count = 0; while (it != keys->end()) { // filter by search bar's keyword - if (ability_ & KeyMenuAbility::SEARCH_BAR && !keyword_.empty()) { - auto name = it->GetName(); - std::transform(name.begin(), name.end(), name.begin(), - [](unsigned char c) { return std::tolower(c); }); - - auto email = it->GetEmail(); - std::transform(email.begin(), email.end(), email.begin(), - [](unsigned char c) { return std::tolower(c); }); - - auto comment = it->GetComment(); - std::transform(comment.begin(), comment.end(), comment.begin(), - [](unsigned char c) { return std::tolower(c); }); - - if (name.find(keyword_) == std::string::npos && - email.find(keyword_) == std::string::npos && - comment.find(keyword_) == std::string::npos) { + if (ability_ & KeyMenuAbility::SEARCH_BAR && !keyword_.isEmpty()) { + auto name = it->GetName().toLower(); + auto email = it->GetEmail().toLower(); + auto comment = it->GetComment().toLower(); + + if (!name.contains(keyword_) && !email.contains(keyword_) && + !comment.contains(keyword_)) { it = keys->erase(it); continue; } @@ -654,9 +648,9 @@ void KeyTable::Refresh(KeyLinkListPtr m_keys) { auto* tmp1 = new QTableWidgetItem(type_str); key_list_->setItem(row_index, 1, tmp1); - auto* tmp2 = new QTableWidgetItem(QString::fromStdString(it->GetName())); + auto* tmp2 = new QTableWidgetItem(it->GetName()); key_list_->setItem(row_index, 2, tmp2); - auto* tmp3 = new QTableWidgetItem(QString::fromStdString(it->GetEmail())); + auto* tmp3 = new QTableWidgetItem(it->GetEmail()); key_list_->setItem(row_index, 3, tmp3); QString usage; @@ -671,13 +665,11 @@ void KeyTable::Refresh(KeyLinkListPtr m_keys) { temp_usage->setTextAlignment(Qt::AlignCenter); key_list_->setItem(row_index, 4, temp_usage); - auto* temp_validity = - new QTableWidgetItem(QString::fromStdString(it->GetOwnerTrust())); + auto* temp_validity = new QTableWidgetItem(it->GetOwnerTrust()); temp_validity->setTextAlignment(Qt::AlignCenter); key_list_->setItem(row_index, 5, temp_validity); - auto* temp_fpr = - new QTableWidgetItem(QString::fromStdString(it->GetFingerprint())); + auto* temp_fpr = new QTableWidgetItem(it->GetFingerprint()); temp_fpr->setTextAlignment(Qt::AlignCenter); key_list_->setItem(row_index, 6, temp_fpr); @@ -727,7 +719,7 @@ void KeyTable::SetMenuAbility(KeyMenuAbility::AbilityType ability) { this->ability_ = ability; } -void KeyTable::SetFilterKeyword(std::string keyword) { - this->keyword_ = keyword; +void KeyTable::SetFilterKeyword(QString keyword) { + this->keyword_ = std::move(keyword); } } // namespace GpgFrontend::UI diff --git a/src/ui/widgets/KeyList.h b/src/ui/widgets/KeyList.h index 659957c4..e7da0596 100644 --- a/src/ui/widgets/KeyList.h +++ b/src/ui/widgets/KeyList.h @@ -94,7 +94,7 @@ struct KeyTable { KeyTableFilter filter_; ///< KeyIdArgsListPtr checked_key_ids_; ///< KeyMenuAbility::AbilityType ability_; ///< - std::string keyword_; ///< + QString keyword_; ///< /** * @brief Construct a new Key Table object @@ -158,7 +158,7 @@ struct KeyTable { * @brief * */ - void SetFilterKeyword(std::string keyword); + void SetFilterKeyword(QString keyword); }; /** @@ -277,16 +277,9 @@ class KeyList : public QWidget { /** * @brief Get the Selected Key object * - * @return std::string + * @return QString */ - std::string GetSelectedKey(); - - /** - * @brief - * - * @param keyIds - */ - [[maybe_unused]] static void MarkKeys(QStringList* keyIds); + QString GetSelectedKey(); /** * @brief diff --git a/src/ui/widgets/PlainTextEditorPage.cpp b/src/ui/widgets/PlainTextEditorPage.cpp index d5094dd3..009e627c 100644 --- a/src/ui/widgets/PlainTextEditorPage.cpp +++ b/src/ui/widgets/PlainTextEditorPage.cpp @@ -28,7 +28,6 @@ #include "PlainTextEditorPage.h" -#include <boost/format.hpp> #include <sstream> #include <string> #include <utility> @@ -70,8 +69,8 @@ PlainTextEditorPage::PlainTextEditorPage(QString file_path, QWidget *parent) if (!read_done_) return; auto text = ui_->textPage->document()->toPlainText(); - auto str = boost::format(_("%1% character(s)")) % text.size(); - this->ui_->characterLabel->setText(str.str().c_str()); + auto str = QString(_("%1% character(s)")).arg(text.size()); + this->ui_->characterLabel->setText(str); }); if (full_file_path_.isEmpty()) { @@ -170,7 +169,7 @@ void PlainTextEditorPage::ReadFile() { auto *text_page = this->GetTextPage(); text_page->setReadOnly(true); - const auto target_path = this->full_file_path_.toStdString(); + const auto target_path = this->full_file_path_; auto task_runner = GpgFrontend::Thread::TaskRunnerGetter::GetInstance().GetTaskRunner(); @@ -199,74 +198,72 @@ void PlainTextEditorPage::ReadFile() { task_runner->PostTask(read_task); } -auto BinaryToString(const std::string &source) -> std::string { - static char syms[] = "0123456789ABCDEF"; - std::stringstream ss; - for (unsigned char c : source) - ss << syms[((c >> 4) & 0xf)] << syms[c & 0xf] << " "; - return ss.str(); +auto BinaryToString(const QByteArray &source) -> QString { + static const char kSyms[] = "0123456789ABCDEF"; + QString buffer; + QTextStream ss(&buffer); + for (auto c : source) ss << kSyms[((c >> 4) & 0xf)] << kSyms[c & 0xf] << " "; + return buffer; } void PlainTextEditorPage::slot_insert_text(QByteArray bytes_data) { - std::string data = bytes_data.toStdString(); - - GF_UI_LOG_TRACE("inserting data read to editor, data size: {}", data.size()); - read_bytes_ += data.size(); + GF_UI_LOG_TRACE("inserting data read to editor, data size: {}", + bytes_data.size()); + read_bytes_ += bytes_data.size(); // If binary format is detected, the entire file is converted to binary // format for display. bool if_last_binary_mode = binary_mode_; if (!binary_mode_ && !read_done_) { - detect_encoding(data); + detect_encoding(bytes_data); } if (binary_mode_) { // change formery displayed text to binary format if (if_last_binary_mode != binary_mode_) { - auto text_buffer = - ui_->textPage->document()->toRawText().toLocal8Bit().toStdString(); + auto text_buffer = ui_->textPage->document()->toRawText().toLocal8Bit(); ui_->textPage->clear(); - this->GetTextPage()->insertPlainText(BinaryToString(text_buffer).c_str()); + this->GetTextPage()->insertPlainText(BinaryToString(text_buffer)); this->ui_->lfLabel->setText("None"); } // insert new data - this->GetTextPage()->insertPlainText(BinaryToString(data).c_str()); + this->GetTextPage()->insertPlainText(BinaryToString(bytes_data)); // update the size of the file - auto str = boost::format(_("%1% byte(s)")) % read_bytes_; - this->ui_->characterLabel->setText(str.str().c_str()); + auto str = QString(_("%1 byte(s)")).arg(read_bytes_); + this->ui_->characterLabel->setText(str); } else { // detect crlf/lf line ending - detect_cr_lf(data); + detect_cr_lf(bytes_data); // when reding from a text file // try convert the any of thetext to utf8 - std::string utf8_data; + QString utf8_data; if (!read_done_ && charset_confidence_ > 25) { - CharsetOperator::Convert2Utf8(data, utf8_data, charset_name_); + CharsetOperator::Convert2Utf8(bytes_data, utf8_data, charset_name_); } else { // when editing a text file, do nothing. - utf8_data = data; + utf8_data = bytes_data; } // insert the text to the text page - this->GetTextPage()->insertPlainText(utf8_data.c_str()); + this->GetTextPage()->insertPlainText(utf8_data); auto text = this->GetTextPage()->toPlainText(); - auto str = boost::format(_("%1% character(s)")) % text.size(); - this->ui_->characterLabel->setText(str.str().c_str()); + auto str = QString(_("%1 character(s)")).arg(text.size()); + this->ui_->characterLabel->setText(str); } QTimer::singleShot(25, this, &PlainTextEditorPage::SignalUIBytesDisplayed); } -void PlainTextEditorPage::detect_encoding(const std::string &data) { +void PlainTextEditorPage::detect_encoding(const QString &data) { // skip the binary data to avoid the false detection of the encoding if (binary_mode_) return; // detect the encoding auto charset = CharsetOperator::Detect(data); - this->charset_name_ = std::get<0>(charset).c_str(); - this->language_name_ = std::get<1>(charset).c_str(); + this->charset_name_ = std::get<0>(charset); + this->language_name_ = std::get<1>(charset); this->charset_confidence_ = std::get<2>(charset); // probably there is no need to detect the encoding again @@ -279,11 +276,11 @@ void PlainTextEditorPage::detect_encoding(const std::string &data) { this->ui_->lfLabel->setHidden(true); this->ui_->encodingLabel->setText(_("binary")); } else { - ui_->encodingLabel->setText(this->charset_name_.c_str()); + ui_->encodingLabel->setText(this->charset_name_); } } -void PlainTextEditorPage::detect_cr_lf(const std::string &data) { +void PlainTextEditorPage::detect_cr_lf(const QString &data) { if (binary_mode_) { return; } @@ -291,7 +288,7 @@ void PlainTextEditorPage::detect_cr_lf(const std::string &data) { // if contain crlf, set the label to crlf if (is_crlf_) return; - if (data.find("\r\n") != std::string::npos) { + if (data.contains("\r\n")) { this->ui_->lfLabel->setText("crlf"); is_crlf_ = true; } else { diff --git a/src/ui/widgets/PlainTextEditorPage.h b/src/ui/widgets/PlainTextEditorPage.h index e2188e4e..64724d7c 100644 --- a/src/ui/widgets/PlainTextEditorPage.h +++ b/src/ui/widgets/PlainTextEditorPage.h @@ -126,8 +126,8 @@ class PlainTextEditorPage : public QWidget { bool read_done_ = false; ///< bool binary_mode_ = false; ///< size_t read_bytes_ = 0; ///< - std::string charset_name_; ///< - std::string language_name_; ///< + QString charset_name_; ///< + QString language_name_; ///< int32_t charset_confidence_{}; ///< bool is_crlf_ = false; ///< @@ -136,14 +136,14 @@ class PlainTextEditorPage : public QWidget { * * @param data */ - void detect_encoding(const std::string& data); + void detect_encoding(const QString& data); /** * @brief * * @param data */ - void detect_cr_lf(const std::string& data); + void detect_cr_lf(const QString& data); private slots: diff --git a/src/ui/widgets/TextEdit.cpp b/src/ui/widgets/TextEdit.cpp index e784ec1f..6fd93f7b 100644 --- a/src/ui/widgets/TextEdit.cpp +++ b/src/ui/widgets/TextEdit.cpp @@ -29,8 +29,6 @@ #include "ui/widgets/TextEdit.h" #include <QtPrintSupport> -#include <boost/format.hpp> -#include <string> #include <tuple> #include <vector> @@ -73,16 +71,15 @@ void TextEdit::SlotNewTab() { this, &TextEdit::slot_save_status_to_cache_for_revovery); } -void TextEdit::SlotNewTabWithContent(std::string title, - const std::string& content) { +void TextEdit::SlotNewTabWithContent(QString title, const QString& content) { QString header = _("untitled") + QString::number(++count_page_) + ".txt"; - if (!title.empty()) { + if (!title.isEmpty()) { // modify title - if (!title.empty() && title[0] == '*') { - title.erase(0, 1); + if (!title.isEmpty() && title[0] == '*') { + title.remove(0, 1); } // set title - header = QString::fromStdString(title); + header = title; } auto* page = new PlainTextEditorPage(); @@ -96,8 +93,7 @@ void TextEdit::SlotNewTabWithContent(std::string title, this, &TextEdit::slot_save_status_to_cache_for_revovery); // set content with modified status - page->GetTextPage()->document()->setPlainText( - QString::fromStdString(content)); + page->GetTextPage()->document()->setPlainText(content); } void TextEdit::slotNewHelpTab(const QString& title, const QString& path) const { @@ -144,10 +140,9 @@ void TextEdit::SlotOpenFile(const QString& path) { page->ReadFile(); } else { QMessageBox::warning(this, _("Warning"), - (boost::format(_("Cannot read file %1%:\n%2%.")) % - path.toStdString() % file.errorString().toStdString()) - .str() - .c_str()); + QString(_("Cannot read file %1:\n%2.")) + .arg(path) + .arg(file.errorString())); } file.close(); @@ -168,14 +163,14 @@ void TextEdit::SlotSave() { return; } - QString fileName = SlotCurPageTextEdit()->GetFilePath(); + QString file_name = SlotCurPageTextEdit()->GetFilePath(); - if (fileName.isEmpty()) { + if (file_name.isEmpty()) { // QString docname = tabWidget->tabText(tabWidget->currentIndex()); // docname.remove(0,2); SlotSaveAs(); } else { - save_file(fileName); + save_file(file_name); } } @@ -208,33 +203,30 @@ bool TextEdit::save_file(const QString& fileName) { QFile file(fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { - QTextStream outputStream(&file); + QTextStream output_stream(&file); QApplication::setOverrideCursor(Qt::WaitCursor); - outputStream << page->GetTextPage()->toPlainText(); + output_stream << page->GetTextPage()->toPlainText(); QApplication::restoreOverrideCursor(); QTextDocument* document = page->GetTextPage()->document(); document->setModified(false); - int curIndex = tab_widget_->currentIndex(); - tab_widget_->setTabText(curIndex, stripped_name(fileName)); + int cur_index = tab_widget_->currentIndex(); + tab_widget_->setTabText(cur_index, stripped_name(fileName)); page->SetFilePath(fileName); page->NotifyFileSaved(); file.close(); return true; - } else { - QMessageBox::warning( - this, _("Warning"), - (boost::format(_("Cannot read file %1%:\n%2%.")) % - fileName.toStdString() % file.errorString().toStdString()) - .str() - .c_str()); - return false; } + QMessageBox::warning(this, _("Warning"), + QString(_("Cannot read file %1%:\n%2%.")) + .arg(fileName) + .arg(file.errorString())); + return false; } -bool TextEdit::SlotSaveAs() { +auto TextEdit::SlotSaveAs() -> bool { if (tab_widget_->count() == 0 || SlotCurPageTextEdit() == nullptr) { return true; } @@ -247,8 +239,7 @@ bool TextEdit::SlotSaveAs() { path = tab_widget_->tabText(tab_widget_->currentIndex()).remove(0, 2); } - QString fileName = QFileDialog::getSaveFileName(this, _("Save file"), path); - return save_file(fileName); + return save_file(QFileDialog::getSaveFileName(this, _("Save file"), path)); } void TextEdit::SlotCloseTab() { @@ -324,20 +315,16 @@ bool TextEdit::maybe_save_current_tab(bool askToSave) { // QString docname = tabWidget->tabText(tabWidget->currentIndex()); // docname.remove(0,2); return SlotSaveAs(); - } else { - return save_file(file_path); } - } else if (result == QMessageBox::Discard) { - return true; - } else { - return false; + return save_file(file_path); } + return result == QMessageBox::Discard; } page->deleteLater(); return true; } -bool TextEdit::MaybeSaveAnyTab() { +auto TextEdit::MaybeSaveAnyTab() -> bool { // get a list of all unsaved documents and their tabids QHash<int, QString> unsaved_docs = this->UnsavedDocuments(); @@ -352,8 +339,8 @@ bool TextEdit::MaybeSaveAnyTab() { * and show normal unsaved doc dialog */ if (unsaved_docs.size() == 1) { - int modifiedTab = unsaved_docs.keys().at(0); - tab_widget_->setCurrentIndex(modifiedTab); + int modified_tab = unsaved_docs.keys().at(0); + tab_widget_->setCurrentIndex(modified_tab); return maybe_save_current_tab(true); } @@ -410,14 +397,14 @@ FilePage* TextEdit::CurFilePage() const { int TextEdit::TabCount() const { return tab_widget_->count(); } PlainTextEditorPage* TextEdit::SlotCurPageTextEdit() const { - auto* curPage = + auto* cur_page = qobject_cast<PlainTextEditorPage*>(tab_widget_->currentWidget()); - return curPage; + return cur_page; } FilePage* TextEdit::SlotCurPageFileTreeView() const { - auto* curPage = qobject_cast<FilePage*>(tab_widget_->currentWidget()); - return curPage; + auto* cur_page = qobject_cast<FilePage*>(tab_widget_->currentWidget()); + return cur_page; } void TextEdit::SlotQuote() const { @@ -453,12 +440,10 @@ void TextEdit::SlotFillTextEditWithText(const QString& text) const { void TextEdit::LoadFile(const QString& fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { - QMessageBox::warning( - this, _("Warning"), - (boost::format(_("Cannot read file %1%:\n%2%.")) % - fileName.toStdString() % file.errorString().toStdString()) - .str() - .c_str()); + QMessageBox::warning(this, _("Warning"), + QString(_("Cannot read file %1:\n%2.")) + .arg(fileName) + .arg(file.errorString())); return; } QTextStream in(&file); @@ -540,8 +525,8 @@ void TextEdit::SlotSwitchTabDown() const { * return a hash of tabindexes and title of unsaved tabs */ QHash<int, QString> TextEdit::UnsavedDocuments() const { - QHash<int, QString> unsavedDocs; // this list could be used to implement - // gedit like "unsaved changed"-dialog + QHash<int, QString> unsaved_docs; // this list could be used to implement + // gedit like "unsaved changed"-dialog for (int i = 0; i < tab_widget_->count(); i++) { auto* ep = qobject_cast<PlainTextEditorPage*>(tab_widget_->widget(i)); @@ -552,10 +537,10 @@ QHash<int, QString> TextEdit::UnsavedDocuments() const { // remove * before name of modified doc doc_name.remove(0, 2); - unsavedDocs.insert(i, doc_name); + unsaved_docs.insert(i, doc_name); } } - return unsavedDocs; + return unsaved_docs; } void TextEdit::SlotCut() const { @@ -629,15 +614,15 @@ void TextEdit::SlotSelectAll() const { void TextEdit::slot_file_page_path_changed(const QString& path) const { int index = tab_widget_->currentIndex(); - QString mPath; - QFileInfo fileInfo(path); - QString tPath = fileInfo.absoluteFilePath(); + QString m_path; + QFileInfo file_info(path); + QString t_path = file_info.absoluteFilePath(); if (path.size() > 18) { - mPath = tPath.mid(tPath.size() - 18, 18).prepend("..."); + m_path = t_path.mid(t_path.size() - 18, 18).prepend("..."); } else { - mPath = tPath; + m_path = t_path; } - tab_widget_->setTabText(index, mPath); + tab_widget_->setTabText(index, m_path); } void TextEdit::slot_save_status_to_cache_for_revovery() { @@ -664,7 +649,7 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { "{}", tab_count); - std::vector<std::tuple<int, std::string, std::string>> unsaved_pages; + std::vector<std::tuple<int, QString, QString>> unsaved_pages; for (int i = 0; i < tab_count; i++) { auto* target_page = @@ -676,24 +661,26 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { } auto* document = target_page->GetTextPage()->document(); - auto tab_title = tab_widget_->tabText(i).toStdString(); + auto tab_title = tab_widget_->tabText(i); if (!target_page->ReadDone() || !target_page->isEnabled() || !document->isModified()) { continue; } - auto raw_text = document->toRawText().toStdString(); + auto raw_text = document->toRawText(); GF_UI_LOG_DEBUG("unsaved page index: {}, tab title: {} tab content: {}", i, tab_title, raw_text.size()); - unsaved_pages.push_back({i, tab_title, raw_text}); + unsaved_pages.emplace_back(i, tab_title, raw_text); } nlohmann::json unsaved_page_array = nlohmann::json::array(); for (const auto& page : unsaved_pages) { + const auto [index, title, content] = page; + nlohmann::json page_json; - page_json["index"] = std::get<0>(page); - page_json["title"] = std::get<1>(page); - page_json["content"] = std::get<2>(page); + page_json["index"] = index; + page_json["title"] = title.toStdString(); + page_json["content"] = content.toStdString(); unsaved_page_array.push_back(page_json); } diff --git a/src/ui/widgets/TextEdit.h b/src/ui/widgets/TextEdit.h index 842cb406..cba1c6e4 100644 --- a/src/ui/widgets/TextEdit.h +++ b/src/ui/widgets/TextEdit.h @@ -153,7 +153,7 @@ class TextEdit : public QWidget { * @details * */ - void SlotNewTabWithContent(std::string title, const std::string& content); + void SlotNewTabWithContent(QString title, const QString& content); /** * @details Adds a new tab with opening file by path diff --git a/src/ui/widgets/VerifyKeyDetailBox.cpp b/src/ui/widgets/VerifyKeyDetailBox.cpp index 54f5cf9e..a2c130ad 100644 --- a/src/ui/widgets/VerifyKeyDetailBox.cpp +++ b/src/ui/widgets/VerifyKeyDetailBox.cpp @@ -53,9 +53,9 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, connect(import_button, &QPushButton::clicked, this, &VerifyKeyDetailBox::slot_import_form_key_server); - this->setTitle(QString(_("Key not present with id 0x")) + fpr_.c_str()); + this->setTitle(QString(_("Key not present with id 0x")) + fpr_); - auto grid = new QGridLayout(); + auto* grid = new QGridLayout(); grid->addWidget(new QLabel(QString(_("Status")) + _(":")), 0, 0); // grid->addWidget(new QLabel(_("Fingerprint:")), 1, 0); @@ -68,14 +68,14 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, } case GPG_ERR_NO_ERROR: { this->setTitle(QString(_("A Signature")) + ":"); - auto gird = create_key_info_grid(signature); + auto* gird = create_key_info_grid(signature); if (gird != nullptr) { vbox->addLayout(gird); } else { vbox->addWidget(new QLabel(_("Key Information is NOT Available"))); - if (!signature.GetFingerprint().empty()) { + if (!signature.GetFingerprint().isEmpty()) { vbox->addWidget(new QLabel(QString(_("Fingerprint")) + ": " + - signature.GetFingerprint().c_str())); + signature.GetFingerprint())); } } break; @@ -84,14 +84,14 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, this->setTitle("An Error Signature"); vbox->addWidget( new QLabel(QString(_("Status")) + ":" + _("Cert Revoked"))); - auto gird = create_key_info_grid(signature); + auto* gird = create_key_info_grid(signature); if (gird != nullptr) { vbox->addLayout(gird); } else { vbox->addWidget(new QLabel(_("Key Information is NOT Available"))); - if (!signature.GetFingerprint().empty()) { + if (!signature.GetFingerprint().isEmpty()) { vbox->addWidget(new QLabel(QString(_("Fingerprint")) + ": " + - signature.GetFingerprint().c_str())); + signature.GetFingerprint())); } } break; @@ -100,14 +100,14 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, this->setTitle("An Error Signature"); vbox->addWidget( new QLabel(QString(_("Status")) + ":" + _("Signature Expired"))); - auto gird = create_key_info_grid(signature); + auto* gird = create_key_info_grid(signature); if (gird != nullptr) { vbox->addLayout(gird); } else { vbox->addWidget(new QLabel(_("Key Information is NOT Available"))); - if (!signature.GetFingerprint().empty()) { + if (!signature.GetFingerprint().isEmpty()) { vbox->addWidget(new QLabel(QString(_("Fingerprint")) + ": " + - signature.GetFingerprint().c_str())); + signature.GetFingerprint())); } } break; @@ -118,14 +118,14 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, new QLabel(QString(_("Status")) + ":" + _("Key Expired"))); vbox->addWidget( new QLabel(QString(_("Status")) + ":" + _("Key Expired"))); - auto gird = create_key_info_grid(signature); + auto* gird = create_key_info_grid(signature); if (gird != nullptr) { vbox->addLayout(gird); } else { vbox->addWidget(new QLabel(_("Key Information is NOT Available"))); - if (!signature.GetFingerprint().empty()) { + if (!signature.GetFingerprint().isEmpty()) { vbox->addWidget(new QLabel(QString(_("Fingerprint")) + ": " + - signature.GetFingerprint().c_str())); + signature.GetFingerprint())); } } break; @@ -134,14 +134,14 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, this->setTitle("An Error Signature"); vbox->addWidget( new QLabel(QString(_("Status")) + ":" + _("General Error"))); - auto gird = create_key_info_grid(signature); + auto* gird = create_key_info_grid(signature); if (gird != nullptr) { vbox->addLayout(gird); } else { vbox->addWidget(new QLabel(_("Key Information is NOT Available"))); - if (!signature.GetFingerprint().empty()) { + if (!signature.GetFingerprint().isEmpty()) { vbox->addWidget(new QLabel(QString(_("Fingerprint")) + ": " + - signature.GetFingerprint().c_str())); + signature.GetFingerprint())); } } break; @@ -149,14 +149,14 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, default: { this->setTitle("An Error Signature"); this->setTitle(QString(_("Status")) + ":" + _("Unknown Error ")); - auto gird = create_key_info_grid(signature); + auto* gird = create_key_info_grid(signature); if (gird != nullptr) { vbox->addLayout(gird); } else { vbox->addWidget(new QLabel(_("Key Information is NOT Available"))); - if (!signature.GetFingerprint().empty()) { + if (!signature.GetFingerprint().isEmpty()) { vbox->addWidget(new QLabel(QString(_("Fingerprint")) + ": " + - signature.GetFingerprint().c_str())); + signature.GetFingerprint())); } } break; @@ -166,16 +166,16 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(const GpgSignature& signature, } void VerifyKeyDetailBox::slot_import_form_key_server() { - auto* importDialog = new KeyServerImportDialog(false, this); + auto* import_dialog = new KeyServerImportDialog(this); auto key_ids = std::make_unique<KeyIdArgsList>(); key_ids->push_back(fpr_); - importDialog->SlotImport(key_ids); + import_dialog->SlotImport(key_ids); } -QGridLayout* VerifyKeyDetailBox::create_key_info_grid( - const GpgSignature& signature) { - auto grid = new QGridLayout(); - GpgKey key = GpgKeyGetter::GetInstance().GetKey(fpr_); +auto VerifyKeyDetailBox::create_key_info_grid(const GpgSignature& signature) + -> QGridLayout* { + auto* grid = new QGridLayout(); + auto key = GpgKeyGetter::GetInstance().GetKey(fpr_); if (!key.IsGood()) return nullptr; grid->addWidget(new QLabel(QString(_("Signer Name")) + ":"), 0, 0); @@ -184,41 +184,42 @@ QGridLayout* VerifyKeyDetailBox::create_key_info_grid( grid->addWidget(new QLabel(QString(_("Valid")) + ":"), 3, 0); grid->addWidget(new QLabel(QString(_("Flags")) + ":"), 4, 0); - grid->addWidget(new QLabel(QString::fromStdString(key.GetName())), 0, 1); - grid->addWidget(new QLabel(QString::fromStdString(key.GetEmail())), 1, 1); - grid->addWidget(new QLabel(BeautifyFingerprint(fpr_).c_str()), 2, 1); + grid->addWidget(new QLabel(key.GetName()), 0, 1); + grid->addWidget(new QLabel(key.GetEmail()), 1, 1); + grid->addWidget(new QLabel(BeautifyFingerprint(fpr_)), 2, 1); - if (signature.GetSummary() & GPGME_SIGSUM_VALID) { + if ((signature.GetSummary() & GPGME_SIGSUM_VALID) != 0U) { grid->addWidget(new QLabel(_("Fully Valid")), 3, 1); } else { grid->addWidget(new QLabel(_("NOT Fully Valid")), 3, 1); } - std::stringstream text_stream; + QString buffer; + QTextStream text_stream(&buffer); - if (signature.GetSummary() & GPGME_SIGSUM_GREEN) { + if ((signature.GetSummary() & GPGME_SIGSUM_GREEN) != 0U) { text_stream << _("Good") << " "; } - if (signature.GetSummary() & GPGME_SIGSUM_RED) { + if ((signature.GetSummary() & GPGME_SIGSUM_RED) != 0U) { text_stream << _("Bad") << " "; } - if (signature.GetSummary() & GPGME_SIGSUM_SIG_EXPIRED) { + if ((signature.GetSummary() & GPGME_SIGSUM_SIG_EXPIRED) != 0U) { text_stream << _("Expired") << " "; } - if (signature.GetSummary() & GPGME_SIGSUM_KEY_MISSING) { + if ((signature.GetSummary() & GPGME_SIGSUM_KEY_MISSING) != 0U) { text_stream << _("Missing Key") << " "; } - if (signature.GetSummary() & GPGME_SIGSUM_KEY_REVOKED) { + if ((signature.GetSummary() & GPGME_SIGSUM_KEY_REVOKED) != 0U) { text_stream << _("Revoked Key") << " "; } - if (signature.GetSummary() & GPGME_SIGSUM_KEY_EXPIRED) { + if ((signature.GetSummary() & GPGME_SIGSUM_KEY_EXPIRED) != 0U) { text_stream << _("Expired Key") << " "; } - if (signature.GetSummary() & GPGME_SIGSUM_CRL_MISSING) { + if ((signature.GetSummary() & GPGME_SIGSUM_CRL_MISSING) != 0U) { text_stream << _("Missing CRL") << " "; } - grid->addWidget(new QLabel(text_stream.str().c_str()), 4, 1); + grid->addWidget(new QLabel(text_stream.readAll()), 4, 1); return grid; } diff --git a/src/ui/widgets/VerifyKeyDetailBox.h b/src/ui/widgets/VerifyKeyDetailBox.h index 55c261d8..4885fdda 100644 --- a/src/ui/widgets/VerifyKeyDetailBox.h +++ b/src/ui/widgets/VerifyKeyDetailBox.h @@ -64,7 +64,7 @@ class VerifyKeyDetailBox : public QGroupBox { */ QGridLayout* create_key_info_grid(const GpgSignature& signature); - std::string fpr_; ///< fingerprint of the key + QString fpr_; ///< fingerprint of the key }; } // namespace GpgFrontend::UI |