diff options
author | saturneric <[email protected]> | 2024-01-15 09:22:32 +0000 |
---|---|---|
committer | saturneric <[email protected]> | 2024-01-15 09:22:32 +0000 |
commit | 6c632d70b391f8b317c68f7db8cfd217f9370995 (patch) | |
tree | 4136eb7164d9f910527c0392d12bd4854a2fdcff /src | |
parent | refactor: remove boost and use QString instead of std::filesystem::path (diff) | |
download | GpgFrontend-6c632d70b391f8b317c68f7db8cfd217f9370995.tar.gz GpgFrontend-6c632d70b391f8b317c68f7db8cfd217f9370995.zip |
feat: use qt json support components in data object and infos gathering module
Diffstat (limited to 'src')
29 files changed, 792 insertions, 631 deletions
diff --git a/src/core/function/CacheManager.cpp b/src/core/function/CacheManager.cpp index 88d3bddd..90396017 100644 --- a/src/core/function/CacheManager.cpp +++ b/src/core/function/CacheManager.cpp @@ -98,25 +98,23 @@ class CacheManager::Impl : public QObject { &Impl::slot_flush_cache_storage); flush_timer_->start(15000); + // load data from storage load_all_cache_storage(); } - void SaveCache(QString key, const nlohmann::json& value, bool flush) { + void SaveCache(QString key, const QJsonDocument& 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.toStdString()) == key_storage_.end()) { + if (!key_storage_.contains(key)) { GF_CORE_LOG_DEBUG("register new key of cache", key); - key_storage_.push_back(key.toStdString()); + key_storage_.push_back(key); } - if (flush) { - slot_flush_cache_storage(); - } + if (flush) slot_flush_cache_storage(); } - auto LoadCache(const QString& key) -> nlohmann::json { + auto LoadCache(const QString& key) -> QJsonDocument { auto data_object_key = get_data_object_key(key); if (!cache_storage_.exists(key)) { @@ -124,14 +122,12 @@ class CacheManager::Impl : public QObject { } auto cache = cache_storage_.get(key); - if (cache) { - return *cache; - } + if (cache.has_value()) return cache.value(); return {}; } - auto LoadCache(const QString& key, nlohmann::json default_value) - -> nlohmann::json { + auto LoadCache(const QString& key, QJsonDocument default_value) + -> QJsonDocument { auto data_object_key = get_data_object_key(key); if (!cache_storage_.exists(key)) { cache_storage_.insert(key, @@ -139,9 +135,7 @@ class CacheManager::Impl : public QObject { } auto cache = cache_storage_.get(key); - if (cache) { - return *cache; - } + if (cache.has_value()) return cache.value(); return {}; } @@ -159,18 +153,17 @@ class CacheManager::Impl : public QObject { void slot_flush_cache_storage() { for (const auto& cache : cache_storage_.mirror()) { auto key = get_data_object_key(cache.first); - GF_CORE_LOG_TRACE("save cache into filesystem, key {}, value size: {}", - key, cache.second.size()); - GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(key, - cache.second); + GF_CORE_LOG_TRACE("save cache into filesystem, key {}", key); + GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj( + key, QJsonDocument(cache.second)); } - GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(drk_key_, - key_storage_); + GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj( + drk_key_, QJsonDocument(key_storage_)); } private: - ThreadSafeMap<QString, nlohmann::json> cache_storage_; - nlohmann::json key_storage_; + ThreadSafeMap<QString, QJsonDocument> cache_storage_; + QJsonArray key_storage_; QTimer* flush_timer_; const QString drk_key_ = "__cache_manage_data_register_key_list"; @@ -189,18 +182,16 @@ class CacheManager::Impl : public QObject { * * @param key * @param default_value - * @return nlohmann::json + * @return QJsonObject */ - static auto load_cache_storage(QString key, nlohmann::json default_value) - -> nlohmann::json { + static auto load_cache_storage(QString key, QJsonDocument default_value) + -> QJsonDocument { auto data_object_key = get_data_object_key(std::move(key)); auto stored_data = GpgFrontend::DataObjectOperator::GetInstance().GetDataObject( data_object_key); - if (stored_data.has_value()) { - return stored_data.value(); - } + if (stored_data.has_value()) return stored_data.value(); return default_value; } @@ -214,20 +205,16 @@ class CacheManager::Impl : public QObject { GpgFrontend::DataObjectOperator::GetInstance().GetDataObject(drk_key_); // get cache data list from file system - nlohmann::json registered_key_list; - if (stored_data.has_value()) { - registered_key_list = std::move(stored_data.value()); - } - - if (!registered_key_list.is_array()) { + QJsonArray registered_key_list; + if (stored_data->isArray()) { + registered_key_list = stored_data->array(); + } else { GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj( - drk_key_, nlohmann::json::array()); - GF_CORE_LOG_ERROR("drk_key_ is not an array, abort."); - return; + drk_key_, QJsonDocument(QJsonArray())); } for (const auto& key : registered_key_list) { - load_cache_storage(QString::fromStdString(key), {}); + load_cache_storage(key.toString(), {}); } key_storage_ = registered_key_list; @@ -247,17 +234,17 @@ CacheManager::CacheManager(int channel) CacheManager::~CacheManager() = default; -void CacheManager::SaveCache(QString key, const nlohmann::json& value, +void CacheManager::SaveCache(QString key, const QJsonDocument& value, bool flush) { p_->SaveCache(std::move(key), value, flush); } -auto CacheManager::LoadCache(QString key) -> nlohmann::json { +auto CacheManager::LoadCache(QString key) -> QJsonDocument { return p_->LoadCache(key); } -auto CacheManager::LoadCache(QString key, nlohmann::json default_value) - -> nlohmann::json { +auto CacheManager::LoadCache(QString key, QJsonDocument default_value) + -> QJsonDocument { return p_->LoadCache(key, std::move(default_value)); } diff --git a/src/core/function/CacheManager.h b/src/core/function/CacheManager.h index 9e95096d..96496648 100644 --- a/src/core/function/CacheManager.h +++ b/src/core/function/CacheManager.h @@ -28,8 +28,6 @@ #pragma once -#include <nlohmann/json.hpp> - #include "core/function/basic/GpgFunctionObject.h" namespace GpgFrontend { @@ -42,11 +40,11 @@ class GPGFRONTEND_CORE_EXPORT CacheManager ~CacheManager() override; - void SaveCache(QString key, const nlohmann::json& value, bool flush = false); + void SaveCache(QString key, const QJsonDocument& value, bool flush = false); - auto LoadCache(QString key) -> nlohmann::json; + auto LoadCache(QString key) -> QJsonDocument; - auto LoadCache(QString key, nlohmann::json default_value) -> nlohmann::json; + auto LoadCache(QString key, QJsonDocument default_value) -> QJsonDocument; auto ResetCache(QString key) -> bool; diff --git a/src/core/function/DataObjectOperator.cpp b/src/core/function/DataObjectOperator.cpp index 3033f23b..1d4d2c4a 100644 --- a/src/core/function/DataObjectOperator.cpp +++ b/src/core/function/DataObjectOperator.cpp @@ -36,7 +36,7 @@ namespace GpgFrontend { void DataObjectOperator::init_app_secure_key() { - GF_CORE_LOG_TRACE("initializing application secure key"); + GF_CORE_LOG_INFO("initializing application secure key..."); WriteFile(app_secure_key_path_, PassphraseGenerator::GetInstance().Generate(256).toUtf8()); QFile::setPermissions(app_secure_key_path_, @@ -46,97 +46,95 @@ void DataObjectOperator::init_app_secure_key() { DataObjectOperator::DataObjectOperator(int channel) : SingletonFunctionObject<DataObjectOperator>(channel) { if (!QDir(app_secure_path_).exists()) QDir(app_secure_path_).mkdir("."); - - if (!QDir(app_secure_key_path_).exists()) { - init_app_secure_key(); - } + if (!QFileInfo(app_secure_key_path_).exists()) init_app_secure_key(); QByteArray key; if (!ReadFile(app_secure_key_path_, key)) { GF_CORE_LOG_ERROR("failed to read app secure key file: {}", app_secure_key_path_); - throw std::runtime_error("failed to read app secure key file"); + // unsafe mode + key = {}; } + hash_key_ = QCryptographicHash::hash(key, QCryptographicHash::Sha256); - GF_CORE_LOG_TRACE("app secure key loaded {} bytes", hash_key_.size()); - if (!QDir(app_data_objs_path_).exists()) QDir(app_data_objs_path_).mkpath("."); + if (!QDir(app_data_objs_path_).exists()) { + QDir(app_data_objs_path_).mkpath("."); + } } -auto DataObjectOperator::SaveDataObj(const QString& _key, - const nlohmann::json& value) -> QString { +auto DataObjectOperator::SaveDataObj(const QString& key, + const QJsonDocument& value) -> QString { QByteArray hash_obj_key = {}; - if (_key.isEmpty()) { + if (key.isEmpty()) { hash_obj_key = QCryptographicHash::hash( - hash_key_ - .append( - PassphraseGenerator::GetInstance().Generate(32).toUtf8()) - .append(QDateTime::currentDateTime().toString().toUtf8()), + hash_key_ + + PassphraseGenerator::GetInstance().Generate(32).toUtf8() + + QDateTime::currentDateTime().toString().toUtf8(), QCryptographicHash::Sha256) .toHex(); } else { - hash_obj_key = QCryptographicHash::hash(hash_key_.append(_key.toUtf8()), + hash_obj_key = QCryptographicHash::hash(hash_key_ + key.toUtf8(), QCryptographicHash::Sha256) .toHex(); } - const auto obj_path = app_data_objs_path_ + "/" + hash_obj_key; - - QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, - QAESEncryption::Padding::ISO); - auto encoded = - encryption.encode(QByteArray::fromStdString(to_string(value)), hash_key_); - GF_CORE_LOG_TRACE("saving data object {} to {} , size: {} bytes", - hash_obj_key, obj_path, encoded.size()); - - WriteFile(obj_path, encoded); + const auto target_obj_path = app_data_objs_path_ + "/" + hash_obj_key; + auto encoded_data = + QAESEncryption(QAESEncryption::AES_256, QAESEncryption::ECB, + QAESEncryption::Padding::ISO) + .encode(value.toJson(), hash_key_); + GF_CORE_LOG_TRACE("saving data object {} to disk {} , size: {} bytes", + hash_obj_key, target_obj_path, encoded_data.size()); + + // recreate if not exists + if (!QDir(app_data_objs_path_).exists()) { + QDir(app_data_objs_path_).mkpath("."); + } - return _key.isEmpty() ? hash_obj_key : QString(); + if (!WriteFile(target_obj_path, encoded_data)) { + GF_CORE_LOG_ERROR("failed to write data object to disk: {}", key); + } + return key.isEmpty() ? hash_obj_key : QString(); } -auto DataObjectOperator::GetDataObject(const QString& _key) - -> std::optional<nlohmann::json> { +auto DataObjectOperator::GetDataObject(const QString& key) + -> std::optional<QJsonDocument> { try { - GF_CORE_LOG_TRACE("get data object from disk {}", _key); - auto hash_obj_key = - QCryptographicHash::hash(hash_key_.append(_key.toUtf8()), - QCryptographicHash::Sha256) - .toHex(); + GF_CORE_LOG_TRACE("try to get data object from disk, key: {}", key); + auto hash_obj_key = QCryptographicHash::hash(hash_key_ + key.toUtf8(), + QCryptographicHash::Sha256) + .toHex(); const auto obj_path = app_data_objs_path_ + "/" + hash_obj_key; - if (!QFileInfo(obj_path).exists()) { - GF_CORE_LOG_WARN("data object not found, key: {}", _key); + GF_CORE_LOG_WARN("data object not found from disk, key: {}", key); return {}; } QByteArray encoded_data; if (!ReadFile(obj_path, encoded_data)) { - GF_CORE_LOG_ERROR("failed to read data object, key: {}", _key); + GF_CORE_LOG_ERROR("failed to read data object from disk, key: {}", key); return {}; } QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); - GF_CORE_LOG_TRACE("decrypting data object {} , hash key size: {}", - encoded_data.size(), hash_key_.size()); - - auto decoded = + auto decoded_data = encryption.removePadding(encryption.decode(encoded_data, hash_key_)); - - GF_CORE_LOG_TRACE("data object decoded: {}", _key); - - return nlohmann::json::parse(decoded.toStdString()); + GF_CORE_LOG_TRACE("data object has been decoded, key: {}, data: {}", key, + decoded_data); + return QJsonDocument::fromJson(decoded_data); } catch (...) { - GF_CORE_LOG_ERROR("failed to get data object, caught exception: {}", _key); + GF_CORE_LOG_ERROR("failed to get data object, caught exception: {}", key); return {}; } } auto DataObjectOperator::GetDataObjectByRef(const QString& _ref) - -> std::optional<nlohmann::json> { + -> std::optional<QJsonDocument> { if (_ref.size() != 64) return {}; try { @@ -151,10 +149,10 @@ auto DataObjectOperator::GetDataObjectByRef(const QString& _ref) QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); - auto decoded = + auto decoded_data = encryption.removePadding(encryption.decode(encoded_data, hash_key_)); - return nlohmann::json::parse(decoded.toStdString()); + return QJsonDocument::fromJson(decoded_data); } catch (...) { return {}; } diff --git a/src/core/function/DataObjectOperator.h b/src/core/function/DataObjectOperator.h index 3d0606d6..992b0c46 100644 --- a/src/core/function/DataObjectOperator.h +++ b/src/core/function/DataObjectOperator.h @@ -28,7 +28,6 @@ #pragma once -#include <nlohmann/json.hpp> #include <optional> #include "core/function/GlobalSettingStation.h" @@ -47,11 +46,11 @@ class GPGFRONTEND_CORE_EXPORT DataObjectOperator explicit DataObjectOperator( int channel = SingletonFunctionObject::GetDefaultChannel()); - auto SaveDataObj(const QString &_key, const nlohmann::json &value) -> QString; + auto SaveDataObj(const QString &_key, const QJsonDocument &value) -> QString; - auto GetDataObject(const QString &_key) -> std::optional<nlohmann::json>; + auto GetDataObject(const QString &_key) -> std::optional<QJsonDocument>; - auto GetDataObjectByRef(const QString &_ref) -> std::optional<nlohmann::json>; + auto GetDataObjectByRef(const QString &_ref) -> std::optional<QJsonDocument>; private: /** @@ -69,9 +68,7 @@ class GPGFRONTEND_CORE_EXPORT DataObjectOperator app_secure_path_ + "/app.key"; ///< Where the key of data object is stored QString app_data_objs_path_ = - global_setting_station_.GetAppDataPath() + "/data_objs"; ///< Where data - ///< object is - ///< stored + global_setting_station_.GetAppDataPath() + "/data_objs"; QByteArray hash_key_; ///< Hash key }; diff --git a/src/core/utils/CacheUtils.cpp b/src/core/utils/CacheUtils.cpp index 575634ae..5e8657fa 100644 --- a/src/core/utils/CacheUtils.cpp +++ b/src/core/utils/CacheUtils.cpp @@ -33,14 +33,17 @@ namespace GpgFrontend { void SetTempCacheValue(const QString& key, const QString& value) { - nlohmann::json cache_json = value.toStdString(); - CacheManager::GetInstance().SaveCache(key, cache_json); + QJsonDocument json; + json.setObject(QJsonObject({{key, value}})); + CacheManager::GetInstance().SaveCache(key, json); } auto GetTempCacheValue(const QString& key) -> QString { - nlohmann::json cache_json = ""; - cache_json = CacheManager::GetInstance().LoadCache(key, cache_json); - return QString::fromStdString(cache_json.template get<std::string>()); + QJsonDocument json = CacheManager::GetInstance().LoadCache(key); + if (!json.isObject()) return {}; + auto json_object = json.object(); + if (!json_object.contains(key) && json_object[key].isString()) return {}; + return json_object[key].toString(); } void ResetTempCacheValue(const QString& key) { diff --git a/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp b/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp index c7b87b5b..0db639f8 100644 --- a/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp +++ b/src/module/integrated/gnupg_info_gathering_module/GnuPGInfoGatheringModule.cpp @@ -28,8 +28,6 @@ #include "GnuPGInfoGatheringModule.h" -#include <nlohmann/json.hpp> -#include <string> #include <vector> #include "GpgInfo.h" @@ -43,8 +41,8 @@ auto CheckBinaryChacksum(QString path) -> std::optional<QString> { // check file info and access rights QFileInfo info(path); if (!info.exists() || !info.isFile() || !info.isReadable()) { - MODULE_LOG_ERROR("get info for file {} error, exists: {}", - info.filePath().toStdString(), info.exists()); + MODULE_LOG_ERROR("get info for file {} error, exists: {}", info.filePath(), + info.exists()); return {}; } @@ -52,7 +50,7 @@ auto CheckBinaryChacksum(QString path) -> std::optional<QString> { QFile f(info.filePath()); if (!f.open(QIODevice::ReadOnly)) { MODULE_LOG_ERROR("open {} to calculate check sum error: {}", path, - f.errorString().toStdString()); + f.errorString()); return {}; } @@ -122,7 +120,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.toStdString(); + c_i_gpgme.version = gpgme_version; c_i_gpgme.path = _("Embedded In"); c_i_gpgme.binary_checksum = "/"; @@ -130,24 +128,22 @@ 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.toStdString(); + c_i_gpgconf.path = gpgconf_path; auto gpgconf_binary_checksum = CheckBinaryChacksum(gpgconf_path); c_i_gpgconf.binary_checksum = (gpgconf_binary_checksum.has_value() ? gpgconf_binary_checksum.value() - : QString("/")) - .toStdString(); + : QString("/")); 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; + auto const jsonlized_gpgme_component_info = c_i_gpgme.Json(); + auto const jsonlized_gpgconf_component_info = c_i_gpgconf.Json(); 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()))); + QJsonDocument(jsonlized_gpgme_component_info).toJson()); + UpsertRTValue( + GetModuleIdentifier(), "gnupg.components.gpgconf", + QJsonDocument(jsonlized_gpgconf_component_info).toJson()); auto line_split_list = p_out.split("\n"); @@ -194,20 +190,18 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { { GpgComponentInfo c_i; - 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.name = component_name; + c_i.desc = component_desc; + c_i.version = version; + c_i.path = component_path; c_i.binary_checksum = (binary_checksum.has_value() ? binary_checksum.value() - : QString("/")) - .toStdString(); + : QString("/")); - nlohmann::json const jsonlized_component_info = c_i; + auto const jsonlized_component_info = c_i.Json(); UpsertRTValue(GetModuleIdentifier(), QString("gnupg.components.%1").arg(component_name), - QString::fromStdString(static_cast<std::string>( - jsonlized_component_info.dump()))); + QJsonDocument(jsonlized_component_info).toJson()); component_infos.push_back(c_i); } @@ -270,11 +264,13 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { for (const auto &component : components) { auto component_info_json = RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - QString("gnupg.components.%1").arg(component), QString{}); + QString("gnupg.components.%1").arg(component), QByteArray{}); auto jsonlized_component_info = - nlohmann::json::parse(component_info_json.toStdString()); - auto component_info = jsonlized_component_info.get<GpgComponentInfo>(); + QJsonDocument::fromJson(component_info_json); + assert(jsonlized_component_info.isObject()); + + auto component_info = GpgComponentInfo(jsonlized_component_info.object()); MODULE_LOG_DEBUG("gpgconf check options ready, component: {}", component_info.name); @@ -284,7 +280,7 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { exec_contexts.emplace_back(GpgCommandExecutor::ExecuteContext{ gpgconf_path, - {"--list-options", component_info.name.c_str()}, + {"--list-options", component_info.name}, [this, component_info](int exit_code, const QString &p_out, const QString &p_err) { MODULE_LOG_DEBUG( @@ -328,24 +324,23 @@ auto GnuPGInfoGatheringModule::Exec(EventRefrernce event) -> int { auto option_value = info_split_list[9].trimmed(); GpgOptionsInfo info; - 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; + 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; + + auto const jsonlized_option_info = info.Json(); UpsertRTValue(GetModuleIdentifier(), QString("gnupg.components.%1.options.%2") - .arg(component_info.name.c_str()) + .arg(component_info.name) .arg(option_name), - QString::fromStdString(static_cast<std::string>( - jsonlized_option_info.dump()))); + QJsonDocument(jsonlized_option_info).toJson()); options_infos.push_back(info); } }, diff --git a/src/module/integrated/gnupg_info_gathering_module/GpgInfo.cpp b/src/module/integrated/gnupg_info_gathering_module/GpgInfo.cpp index 8d6fef74..2015bc0a 100644 --- a/src/module/integrated/gnupg_info_gathering_module/GpgInfo.cpp +++ b/src/module/integrated/gnupg_info_gathering_module/GpgInfo.cpp @@ -28,4 +28,53 @@ #include "module/integrated/gnupg_info_gathering_module/GpgInfo.h" -namespace GpgFrontend::Module::Integrated::GnuPGInfoGatheringModule {} +namespace GpgFrontend::Module::Integrated::GnuPGInfoGatheringModule { + +GpgOptionsInfo::GpgOptionsInfo(const QJsonObject &j) { + if (const auto v = j["name"]; v.isString()) name = v.toString(); + if (const auto v = j["flags"]; v.isString()) flags = v.toString(); + if (const auto v = j["level"]; v.isString()) level = v.toString(); + if (const auto v = j["description"]; v.isString()) description = v.toString(); + if (const auto v = j["type"]; v.isString()) type = v.toString(); + if (const auto v = j["alt_type"]; v.isString()) alt_type = v.toString(); + if (const auto v = j["argname"]; v.isString()) argname = v.toString(); + if (const auto v = j["default_value"]; v.isString()) + default_value = v.toString(); + if (const auto v = j["argdef"]; v.isString()) argdef = v.toString(); + if (const auto v = j["value"]; v.isString()) value = v.toString(); +} + +auto GpgOptionsInfo::Json() const -> QJsonObject { + QJsonObject j; + j["name"] = name; + j["flags"] = flags; + j["level"] = level; + j["description"] = description; + j["type"] = type; + j["alt_type"] = alt_type; + j["argname"] = argname; + j["default_value"] = default_value; + j["argdef"] = argdef; + j["value"] = value; + return j; +} + +auto GpgComponentInfo::Json() const -> QJsonObject { + QJsonObject j; + j["name"] = name; + j["desc"] = desc; + j["version"] = version; + j["path"] = path; + j["binary_checksum"] = binary_checksum; + return j; +} + +GpgComponentInfo::GpgComponentInfo(const QJsonObject &j) { + if (const auto v = j["name"]; v.isString()) name = v.toString(); + if (const auto v = j["desc"]; v.isString()) desc = v.toString(); + if (const auto v = j["version"]; v.isString()) version = v.toString(); + if (const auto v = j["path"]; v.isString()) path = v.toString(); + if (const auto v = j["binary_checksum"]; v.isString()) + binary_checksum = v.toString(); +} +} // namespace GpgFrontend::Module::Integrated::GnuPGInfoGatheringModule diff --git a/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h b/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h index 943832c3..72513bc8 100644 --- a/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h +++ b/src/module/integrated/gnupg_info_gathering_module/GpgInfo.h @@ -50,35 +50,40 @@ class GpgInfo { * */ struct GpgComponentInfo { - std::string name; - std::string desc; - std::string version; - std::string path; - std::string binary_checksum; -}; + QString name; + QString desc; + QString version; + QString path; + QString binary_checksum; + + GpgComponentInfo() = default; -NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(GpgComponentInfo, name, desc, version, path, - binary_checksum); + explicit GpgComponentInfo(const QJsonObject &j); + + [[nodiscard]] auto Json() const -> QJsonObject; +}; /** * The format of each line is: * name:flags:level:description:type:alt-type:argname:default:argdef:value */ struct GpgOptionsInfo { - std::string name; - std::string flags; - std::string level; - std::string description; - std::string type; - std::string alt_type; - std::string argname; - std::string default_value; - std::string argdef; - std::string value; -}; + QString name; + QString flags; + QString level; + QString description; + QString type; + QString alt_type; + QString argname; + QString default_value; + QString argdef; + QString value; + + GpgOptionsInfo() = default; -NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(GpgOptionsInfo, name, flags, level, - description, type, alt_type, argname, - default_value, argdef, value); + explicit GpgOptionsInfo(const QJsonObject &j); + + [[nodiscard]] auto Json() const -> QJsonObject; +}; } // namespace GpgFrontend::Module::Integrated::GnuPGInfoGatheringModule diff --git a/src/ui/UserInterfaceUtils.cpp b/src/ui/UserInterfaceUtils.cpp index 2c353d19..69534ca6 100644 --- a/src/ui/UserInterfaceUtils.cpp +++ b/src/ui/UserInterfaceUtils.cpp @@ -32,8 +32,6 @@ #include <qdialog.h> #include <QtNetwork> -#include <string> -#include <utility> #include <vector> #include "core/GpgConstants.h" @@ -43,7 +41,6 @@ #include "core/model/GpgImportInformation.h" #include "core/module/ModuleManager.h" #include "core/thread/Task.h" -#include "core/thread/TaskRunner.h" #include "core/thread/TaskRunnerGetter.h" #include "core/typedef/GpgTypedef.h" #include "core/utils/CacheUtils.h" @@ -52,7 +49,9 @@ #include "ui/UISignalStation.h" #include "ui/dialog/WaitingDialog.h" #include "ui/dialog/gnupg/GnuPGControllerDialog.h" +#include "ui/struct/CacheObject.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/KeyServerSO.h" #include "ui/widgets/TextEdit.h" namespace GpgFrontend::UI { @@ -400,36 +399,16 @@ void CommonUtils::SlotExecuteGpgCommand( void CommonUtils::SlotImportKeyFromKeyServer( const KeyIdArgsList &key_ids, const ImportCallbackFunctiopn &callback) { - // target key server that we need to import key from it - QString target_keyserver; - - try { - SettingsObject key_server_json("key_server"); - - // get key servers from settings - const auto key_server_list = - key_server_json.Check("server_list", nlohmann::json::array()); - if (key_server_list.empty()) { - throw std::runtime_error("No key server configured"); - } - - const size_t target_key_server_index = - key_server_json.Check("default_server", 0); - if (target_key_server_index >= key_server_list.size()) { - throw std::runtime_error("default_server index out of range"); - } - target_keyserver = - 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); - } catch (...) { - GF_UI_LOG_ERROR(_("Cannot read default_keyserver From Settings")); + auto target_keyserver = + KeyServerSO(SettingsObject("key_server")).GetTargetServer(); + if (target_keyserver.isEmpty()) { QMessageBox::critical(nullptr, _("Default Keyserver Not Found"), _("Cannot read default keyserver from your settings, " "please set a default keyserver first")); return; } + GF_UI_LOG_DEBUG("set target key server to default Key Server: {}", + target_keyserver); auto *thread = QThread::create([target_keyserver, key_ids, callback]() { QUrl target_keyserver_url(target_keyserver); @@ -541,40 +520,37 @@ bool CommonUtils::isApplicationNeedRestart() { bool CommonUtils::KeyExistsinFavouriteList(const GpgKey &key) { // load cache - auto key_array = CacheManager::GetInstance().LoadCache("favourite_key_pair"); - if (!key_array.is_array()) { - CacheManager::GetInstance().SaveCache("favourite_key_pair", - nlohmann::json::array()); - } - return std::find(key_array.begin(), key_array.end(), - key.GetFingerprint().toStdString()) != key_array.end(); + auto json_data = CacheObject("favourite_key_pair"); + if (!json_data.isArray()) json_data.setArray(QJsonArray()); + + auto key_array = json_data.array(); + return std::find(key_array.begin(), key_array.end(), key.GetFingerprint()) != + key_array.end(); } void CommonUtils::AddKey2Favourtie(const GpgKey &key) { - auto key_array = CacheManager::GetInstance().LoadCache("favourite_key_pair"); - if (!key_array.is_array()) { - CacheManager::GetInstance().SaveCache("favourite_key_pair", - nlohmann::json::array()); - } - key_array.push_back(key.GetFingerprint().toStdString()); - CacheManager::GetInstance().SaveCache("favourite_key_pair", key_array, true); + auto json_data = CacheObject("favourite_key_pair"); + QJsonArray key_array; + if (json_data.isArray()) key_array = json_data.array(); + + key_array.push_back(key.GetFingerprint()); + json_data.setArray(key_array); } void CommonUtils::RemoveKeyFromFavourite(const GpgKey &key) { - auto key_array = CacheManager::GetInstance().LoadCache("favourite_key_pair"); - if (!key_array.is_array()) { - CacheManager::GetInstance().SaveCache("favourite_key_pair", - nlohmann::json::array(), true); - return; - } - 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().toStdString()); - key_array.erase(rm_it, key_array.end()); - CacheManager::GetInstance().SaveCache("favourite_key_pair", key_array); + auto json_data = CacheObject("favourite_key_pair"); + QJsonArray key_array; + if (json_data.isArray()) key_array = json_data.array(); + + QString fingerprint = key.GetFingerprint(); + QJsonArray new_key_array; + for (auto &&item : key_array) { + if (item.isString() && item.toString() != fingerprint) { + new_key_array.append(item); + } } + + json_data.setArray(new_key_array); } } // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/dialog/GeneralDialog.cpp b/src/ui/dialog/GeneralDialog.cpp index 498e2941..386573a3 100644 --- a/src/ui/dialog/GeneralDialog.cpp +++ b/src/ui/dialog/GeneralDialog.cpp @@ -29,6 +29,9 @@ #include "GeneralDialog.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/WindowStateSO.h" + +namespace GpgFrontend { GpgFrontend::UI::GeneralDialog::GeneralDialog(QString name, QWidget *parent) : QDialog(parent), name_(std::move(name)) { @@ -43,12 +46,12 @@ void GpgFrontend::UI::GeneralDialog::slot_restore_settings() noexcept { update_rect_cache(); SettingsObject general_windows_state(name_ + "_dialog_state"); - bool window_save = general_windows_state.Check("window_save", false); + auto window_state = WindowStateSO(general_windows_state); // Restore window size & location - if (window_save) { - int x = general_windows_state.Check("window_pos").Check("x", 0); - int y = general_windows_state.Check("window_pos").Check("y", 0); + if (window_state.window_save) { + int x = window_state.x; + int y = window_state.y; GF_UI_LOG_DEBUG("stored dialog pos, x: {}, y: {}", x, y); QPoint relative_pos = {x, y}; @@ -56,9 +59,8 @@ 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); - int height = - general_windows_state.Check("window_size").Check("height", 0); + int width = window_state.width; + int height = window_state.height; GF_UI_LOG_DEBUG("stored dialog size, width: {}, height: {}", width, height); @@ -93,12 +95,14 @@ void GpgFrontend::UI::GeneralDialog::slot_save_settings() noexcept { GF_UI_LOG_DEBUG("store dialog pos, x: {}, y: {}", relative_pos.x(), relative_pos.y()); - general_windows_state["window_pos"]["x"] = relative_pos.x(); - general_windows_state["window_pos"]["y"] = relative_pos.y(); + WindowStateSO window_state; + window_state.x = relative_pos.x(); + window_state.y = relative_pos.y(); + window_state.width = rect_.width(); + window_state.height = rect_.height(); + window_state.window_save = true; - general_windows_state["window_size"]["width"] = rect_.width(); - general_windows_state["window_size"]["height"] = rect_.height(); - general_windows_state["window_save"] = true; + general_windows_state.Store(window_state.Json()); } catch (...) { GF_UI_LOG_ERROR("general dialog: {}, caught exception", name_); @@ -210,4 +214,6 @@ void GpgFrontend::UI::GeneralDialog::showEvent(QShowEvent *event) { if (!isRectRestored()) movePosition2CenterOfParent(); QDialog::showEvent(event); -}
\ No newline at end of file +} + +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/ui/dialog/help/GnupgTab.cpp b/src/ui/dialog/help/GnupgTab.cpp index 9749877f..660732ac 100644 --- a/src/ui/dialog/help/GnupgTab.cpp +++ b/src/ui/dialog/help/GnupgTab.cpp @@ -32,8 +32,6 @@ #include "GnupgTab.h" -#include <nlohmann/json.hpp> - #include "core/module/ModuleManager.h" #include "ui_GnuPGInfo.h" @@ -99,42 +97,45 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { int row = 0; for (auto& component : components) { - auto component_info_json = Module::RetrieveRTValueTypedOrDefault( + auto component_info_json_bytes = Module::RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - QString("gnupg.components.%1").arg(component), QString{}); - GF_UI_LOG_DEBUG("got gnupg component {} info from rt, info: {}", component, - component_info_json); + QString("gnupg.components.%1").arg(component), QByteArray{}); + GF_UI_LOG_DEBUG("got gnupg component {} info from rt", component); - auto component_info = - nlohmann::json::parse(component_info_json.toStdString()); - if (!component_info.contains("name")) { + auto component_info_json = + QJsonDocument::fromJson(component_info_json_bytes); + if (!component_info_json.isObject()) { GF_UI_LOG_WARN("illegal gnupg component info, json: {}", - component_info_json); + QString(component_info_json_bytes)); + continue; + } + + auto component_info = component_info_json.object(); + if (!component_info.contains("name")) { + GF_UI_LOG_WARN( + "illegal gnupg component info. it doesn't have a name, json: {}", + QString(component_info_json_bytes)); continue; } - auto* tmp0 = new QTableWidgetItem( - QString::fromStdString(component_info.value("name", ""))); + auto* tmp0 = new QTableWidgetItem(component_info["name"].toString()); tmp0->setTextAlignment(Qt::AlignCenter); ui_->componentDetailsTable->setItem(row, 0, tmp0); - auto* tmp1 = new QTableWidgetItem( - QString::fromStdString(component_info.value("desc", ""))); + auto* tmp1 = new QTableWidgetItem(component_info["desc"].toString()); tmp1->setTextAlignment(Qt::AlignCenter); ui_->componentDetailsTable->setItem(row, 1, tmp1); - auto* tmp2 = new QTableWidgetItem( - QString::fromStdString(component_info.value("version", ""))); + auto* tmp2 = new QTableWidgetItem(component_info["version"].toString()); tmp2->setTextAlignment(Qt::AlignCenter); ui_->componentDetailsTable->setItem(row, 2, tmp2); - auto* tmp3 = new QTableWidgetItem( - QString::fromStdString(component_info.value("binary_checksum", ""))); + auto* tmp3 = + new QTableWidgetItem(component_info["binary_checksum"].toString()); tmp3->setTextAlignment(Qt::AlignCenter); ui_->componentDetailsTable->setItem(row, 3, tmp3); - auto* tmp4 = new QTableWidgetItem( - QString::fromStdString(component_info.value("path", ""))); + auto* tmp4 = new QTableWidgetItem(component_info["path"].toString()); tmp4->setTextAlignment(Qt::AlignLeft); ui_->componentDetailsTable->setItem(row, 4, tmp4); @@ -150,16 +151,18 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", QString("gnupg.components.%1.options").arg(component)); for (auto& option : options) { - const auto option_info = nlohmann::json::parse( - Module::RetrieveRTValueTypedOrDefault( + const auto option_info_json = + QJsonDocument::fromJson(Module::RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", QString("gnupg.components.%1.options.%2") .arg(component) .arg(option), - QString{}) - .toStdString()); - if (!option_info.contains("name") || - option_info.value("flags", "1") == "1") { + QByteArray{})); + + if (!option_info_json.isObject()) continue; + + auto option_info = option_info_json.object(); + if (!option_info.contains("name") || option_info["flags"] == "1") { continue; } row++; @@ -175,26 +178,31 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { QString("gnupg.components.%1.options").arg(component)); for (auto& option : options) { - auto option_info_json = Module::RetrieveRTValueTypedOrDefault( + auto option_info_json_bytes = Module::RetrieveRTValueTypedOrDefault( "com.bktus.gpgfrontend.module.integrated.gnupg-info-gathering", - QString("gnupg.components.%1.options.%2") - .arg(component) - .arg(option), - QString{}); + QString("gnupg.components.%1.options.%2").arg(component).arg(option), + QByteArray{}); GF_UI_LOG_DEBUG("got gnupg component's option {} info from rt, info: {}", - component, option_info_json); + component, option_info_json_bytes); + + auto option_info_json = QJsonDocument::fromJson(option_info_json_bytes); - auto option_info = nlohmann::json::parse(option_info_json.toStdString()); + if (!option_info_json.isObject()) { + GF_UI_LOG_WARN("illegal gnupg option info, json: {}", + QString(option_info_json_bytes)); + continue; + } + auto option_info = option_info_json.object(); if (!option_info.contains("name")) { - GF_UI_LOG_WARN("illegal gnupg configuation info, json: {}", - option_info_json); + GF_UI_LOG_WARN( + "illegal gnupg configuation info. it doesn't have a name, json: {}", + QString(option_info_json_bytes)); continue; } - if (option_info.value("flags", "1") == "1") { - configuration_group = - QString::fromStdString(option_info.value("name", "")); + if (option_info["flags"] == "1") { + configuration_group = option_info["name"].toString(); continue; } @@ -206,24 +214,21 @@ void GpgFrontend::UI::GnupgTab::process_software_info() { tmp1->setTextAlignment(Qt::AlignCenter); ui_->configurationDetailsTable->setItem(row, 1, tmp1); - auto* tmp2 = new QTableWidgetItem( - QString::fromStdString(option_info.value("name", ""))); + auto* tmp2 = new QTableWidgetItem(option_info["name"].toString()); tmp2->setTextAlignment(Qt::AlignCenter); ui_->configurationDetailsTable->setItem(row, 2, tmp2); - auto* tmp3 = new QTableWidgetItem( - QString::fromStdString(option_info.value("description", ""))); + auto* tmp3 = new QTableWidgetItem(option_info["description"].toString()); tmp3->setTextAlignment(Qt::AlignLeft); ui_->configurationDetailsTable->setItem(row, 3, tmp3); - auto* tmp4 = new QTableWidgetItem( - QString::fromStdString(option_info.value("default_value", ""))); + auto* tmp4 = + new QTableWidgetItem(option_info["default_value"].toString()); tmp4->setTextAlignment(Qt::AlignLeft); ui_->configurationDetailsTable->setItem(row, 4, tmp4); - auto* tmp5 = new QTableWidgetItem( - QString::fromStdString(option_info.value("value", ""))); + auto* tmp5 = new QTableWidgetItem(option_info["value"].toString()); tmp5->setTextAlignment(Qt::AlignLeft); ui_->configurationDetailsTable->setItem(row, 5, tmp5); diff --git a/src/ui/dialog/import_export/KeyServerImportDialog.cpp b/src/ui/dialog/import_export/KeyServerImportDialog.cpp index 313c2ed1..f3213dc0 100644 --- a/src/ui/dialog/import_export/KeyServerImportDialog.cpp +++ b/src/ui/dialog/import_export/KeyServerImportDialog.cpp @@ -37,6 +37,7 @@ #include "core/function/gpg/GpgKeyImportExporter.h" #include "ui/UISignalStation.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/KeyServerSO.h" #include "ui/thread/KeyServerImportTask.h" #include "ui/thread/KeyServerSearchTask.h" @@ -126,25 +127,12 @@ auto KeyServerImportDialog::create_combo_box() -> QComboBox* { combo_box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); try { - SettingsObject key_server_json("key_server"); - - const auto key_server_list = - key_server_json.Check("server_list", nlohmann::json::array()); - + KeyServerSO key_server(SettingsObject("general_settings_state")); + const auto& key_server_list = key_server.server_list; for (const auto& key_server : key_server_list) { - const auto key_server_str = key_server.get<std::string>(); - combo_box->addItem(key_server_str.c_str()); - } - - size_t default_key_server_index = - key_server_json.Check("default_server", 0); - if (default_key_server_index >= key_server_list.size()) { - throw std::runtime_error("default_server index out of range"); + combo_box->addItem(key_server); } - auto default_key_server = - key_server_list[default_key_server_index].get<std::string>(); - - combo_box->setCurrentText(default_key_server.c_str()); + combo_box->setCurrentText(key_server.GetTargetServer()); } catch (...) { GF_UI_LOG_ERROR("setting operation error", "server_list", "default_server"); } @@ -401,29 +389,8 @@ void KeyServerImportDialog::SlotImport(const KeyIdArgsListPtr& keys) { target_keyserver = key_server_combo_box_->currentText(); } if (target_keyserver.isEmpty()) { - try { - SettingsObject key_server_json("key_server"); - const auto key_server_list = - key_server_json.Check("server_list", nlohmann::json::array()); - - size_t default_key_server_index = - key_server_json.Check("default_server", 0); - if (default_key_server_index >= key_server_list.size()) { - throw std::runtime_error("default_server index out of range"); - } - auto default_key_server = - key_server_list[default_key_server_index].get<std::string>(); - - target_keyserver = QString::fromStdString(default_key_server); - } catch (...) { - GF_UI_LOG_ERROR("setting operation error", "server_list", - "default_server"); - QMessageBox::critical( - nullptr, _("Default Keyserver Not Found"), - _("Cannot read default keyserver from your settings, " - "please set a default keyserver first")); - return; - } + KeyServerSO key_server(SettingsObject("general_settings_state")); + target_keyserver = key_server.GetTargetServer(); } std::vector<QString> key_ids; for (const auto& key_id : *keys) { diff --git a/src/ui/dialog/import_export/KeyUploadDialog.cpp b/src/ui/dialog/import_export/KeyUploadDialog.cpp index 4d36654e..3fdbc629 100644 --- a/src/ui/dialog/import_export/KeyUploadDialog.cpp +++ b/src/ui/dialog/import_export/KeyUploadDialog.cpp @@ -37,6 +37,7 @@ #include "core/utils/GpgUtils.h" #include "ui/UserInterfaceUtils.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/KeyServerSO.h" namespace GpgFrontend::UI { @@ -85,33 +86,8 @@ void KeyUploadDialog::SlotUpload() { void KeyUploadDialog::slot_upload_key_to_server( const GpgFrontend::GFBuffer& keys_data) { - QString target_keyserver; - - try { - SettingsObject key_server_json("key_server"); - - const auto key_server_list = - key_server_json.Check("server_list", nlohmann::json::array()); - - size_t default_key_server_index = - key_server_json.Check("default_server", 0); - if (default_key_server_index >= key_server_list.size()) { - throw std::runtime_error("default_server index out of range"); - } - - 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); - - } catch (...) { - GF_UI_LOG_ERROR(_("Cannot read default_keyserver From Settings")); - QMessageBox::critical(nullptr, _("Default Keyserver Not Found"), - _("Cannot read default keyserver from your settings, " - "please set a default keyserver first")); - return; - } + KeyServerSO key_server(SettingsObject("general_settings_state")); + auto target_keyserver = key_server.GetTargetServer(); QUrl req_url(target_keyserver + "/pks/add"); auto* qnam = new QNetworkAccessManager(this); diff --git a/src/ui/dialog/settings/SettingsAppearance.cpp b/src/ui/dialog/settings/SettingsAppearance.cpp index 6ce04f45..b1843388 100644 --- a/src/ui/dialog/settings/SettingsAppearance.cpp +++ b/src/ui/dialog/settings/SettingsAppearance.cpp @@ -28,14 +28,15 @@ #include "SettingsAppearance.h" +#include "core/utils/MemoryUtils.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/AppearanceSO.h" #include "ui_AppearanceSettings.h" namespace GpgFrontend::UI { AppearanceTab::AppearanceTab(QWidget* parent) - : QWidget(parent), - ui_(GpgFrontend::SecureCreateSharedObject<Ui_AppearanceSettings>()) { + : QWidget(parent), ui_(SecureCreateSharedObject<Ui_AppearanceSettings>()) { ui_->setupUi(this); ui_->iconSizeBox->setTitle(_("Icon Size")); @@ -73,14 +74,10 @@ AppearanceTab::AppearanceTab(QWidget* parent) } void AppearanceTab::SetSettings() { - SettingsObject general_settings_state("general_settings_state"); - - int const width = - general_settings_state.Check("icon_size").Check("width", 24); - int const height = - general_settings_state.Check("icon_size").Check("height", 24); + AppearanceSO appearance(SettingsObject("general_settings_state")); - auto icon_size = QSize(width, height); + auto icon_size = + QSize(appearance.tool_bar_icon_width, appearance.tool_bar_icon_height); switch (icon_size.width()) { case 12: @@ -92,14 +89,12 @@ void AppearanceTab::SetSettings() { case 32: ui_->largeRadioButton->setChecked(true); break; + default: + ui_->smallRadioButton->setChecked(true); + break; } - // icon_style - int const s_icon_style = - general_settings_state.Check("icon_style", Qt::ToolButtonTextUnderIcon); - auto icon_style = static_cast<Qt::ToolButtonStyle>(s_icon_style); - - switch (icon_style) { + switch (appearance.tool_bar_button_style) { case Qt::ToolButtonTextOnly: ui_->justTextRadioButton->setChecked(true); break; @@ -113,18 +108,17 @@ void AppearanceTab::SetSettings() { break; } - bool const window_save = general_settings_state.Check("window_save", true); - if (window_save) ui_->windowStateCheckBox->setCheckState(Qt::Checked); + if (appearance.save_window_state) { + ui_->windowStateCheckBox->setCheckState(Qt::Checked); + } - auto info_board_info_font_size = - general_settings_state.Check("info_board").Check("font_size", 10); + auto info_board_info_font_size = appearance.info_board_font_size; if (info_board_info_font_size < 9 || info_board_info_font_size > 18) { info_board_info_font_size = 10; } ui_->fontSizeInformationBoardSpinBox->setValue(info_board_info_font_size); - auto text_editor_info_font_size = - general_settings_state.Check("text_editor").Check("font_size", 10); + auto text_editor_info_font_size = appearance.text_editor_font_size; if (text_editor_info_font_size < 9 || text_editor_info_font_size > 18) { text_editor_info_font_size = 10; } @@ -133,6 +127,7 @@ void AppearanceTab::SetSettings() { void AppearanceTab::ApplySettings() { SettingsObject general_settings_state("general_settings_state"); + AppearanceSO appearance(general_settings_state); int icon_size = 24; switch (icon_size_group_->checkedId()) { @@ -147,8 +142,8 @@ void AppearanceTab::ApplySettings() { break; } - general_settings_state["icon_size"]["width"] = icon_size; - general_settings_state["icon_size"]["height"] = icon_size; + appearance.tool_bar_icon_height = icon_size; + appearance.tool_bar_icon_width = icon_size; auto icon_style = Qt::ToolButtonTextUnderIcon; switch (icon_style_group_->checkedId()) { @@ -161,17 +156,19 @@ void AppearanceTab::ApplySettings() { case 3: icon_style = Qt::ToolButtonTextUnderIcon; break; + default: + icon_style = Qt::ToolButtonTextOnly; + break; } + appearance.tool_bar_button_style = icon_style; - general_settings_state["icon_style"] = icon_style; - - general_settings_state["window_save"] = ui_->windowStateCheckBox->isChecked(); - - general_settings_state["info_board"]["font_size"] = + appearance.save_window_state = ui_->windowStateCheckBox->isChecked(); + appearance.info_board_font_size = ui_->fontSizeInformationBoardSpinBox->value(); - - general_settings_state["text_editor"]["font_size"] = + appearance.text_editor_font_size = ui_->fontSizeTextEditorLabelSpinBox->value(); + + general_settings_state.Store(appearance.ToJson()); } } // namespace GpgFrontend::UI diff --git a/src/ui/dialog/settings/SettingsKeyServer.cpp b/src/ui/dialog/settings/SettingsKeyServer.cpp index 922ca230..83e3758b 100644 --- a/src/ui/dialog/settings/SettingsKeyServer.cpp +++ b/src/ui/dialog/settings/SettingsKeyServer.cpp @@ -34,6 +34,7 @@ #include "core/thread/Task.h" #include "core/thread/TaskRunnerGetter.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/KeyServerSO.h" #include "ui/thread/ListedKeyServerTestTask.h" #include "ui_KeyServerSettings.h" @@ -118,32 +119,18 @@ KeyserverTab::KeyserverTab(QWidget* parent) } void KeyserverTab::SetSettings() { - try { - SettingsObject key_server_json("key_server"); + KeyServerSO key_server(SettingsObject("key_server")); - const auto key_server_list = - key_server_json.Check("server_list", nlohmann::json::array()); - - for (const auto& key_server : key_server_list) { - const auto key_server_str = key_server.get<std::string>(); - this->key_server_str_list_.append(key_server_str.c_str()); - } - - size_t default_key_server_index = - key_server_json.Check("default_server", 0); - if (default_key_server_index >= key_server_list.size()) { - throw std::runtime_error("default_server index out of range"); - } - const auto default_key_server = - key_server_list[default_key_server_index].get<std::string>(); + if (key_server.server_list.empty()) key_server.ResetDefaultServerList(); + for (const auto& key_server : key_server.server_list) { + this->key_server_str_list_.append(key_server); + } - 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()); + const auto default_key_server = key_server.GetTargetServer(); + if (!key_server_str_list_.contains(default_key_server)) { + key_server_str_list_.append(default_key_server); } + default_key_server_ = default_key_server; } void KeyserverTab::slot_add_key_server() { @@ -170,26 +157,26 @@ void KeyserverTab::slot_add_key_server() { "that want to add it into the keyserver list?"), QMessageBox::Ok | QMessageBox::Cancel); - if (ret == QMessageBox::Cancel) - return; - else - key_server_str_list_.append(ui_->addKeyServerEdit->text()); + if (ret == QMessageBox::Cancel) return; + key_server_str_list_.append(ui_->addKeyServerEdit->text()); } slot_refresh_table(); } void KeyserverTab::ApplySettings() { SettingsObject key_server_json("key_server"); - key_server_json["server_list"] = nlohmann::json::array(); - auto& key_server_list = key_server_json["server_list"]; + KeyServerSO key_server; + auto& key_server_list = key_server.server_list; const auto list_size = key_server_str_list_.size(); for (int i = 0; i < list_size; i++) { const auto key_server = key_server_str_list_[i]; - if (default_key_server_ == key_server) + if (default_key_server_ == key_server) { key_server_json["default_server"] = i; - key_server_list.insert(key_server_list.end(), key_server.toStdString()); + } + key_server_list << key_server; } + key_server_json.Store(key_server.ToJson()); } void KeyserverTab::slot_refresh_table() { diff --git a/src/ui/main_window/GeneralMainWindow.cpp b/src/ui/main_window/GeneralMainWindow.cpp index ad2f061a..2eb9f2a4 100644 --- a/src/ui/main_window/GeneralMainWindow.cpp +++ b/src/ui/main_window/GeneralMainWindow.cpp @@ -28,9 +28,13 @@ #include "GeneralMainWindow.h" -#include <utility> - #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/AppearanceSO.h" +#include "ui/struct/settings/WindowStateSO.h" + +namespace GpgFrontend::UI { + +class GeneralWindowState {}; GpgFrontend::UI::GeneralMainWindow::GeneralMainWindow(QString name, QWidget *parent) @@ -50,30 +54,19 @@ void GpgFrontend::UI::GeneralMainWindow::closeEvent(QCloseEvent *event) { void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { try { - SettingsObject general_windows_state(name_ + "_state"); + WindowStateSO window_state(SettingsObject(name_ + "_state")); - QString window_state = QString::fromStdString(general_windows_state.Check( - "window_state", saveState().toBase64().toStdString())); - GF_UI_LOG_DEBUG("restore main window state: {}", window_state); + GF_UI_LOG_DEBUG("restore main window state: {}", + window_state.window_state_data); // state sets pos & size of dock-widgets - 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); - 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); - int height = - general_windows_state.Check("window_size").Check("height", 450); + this->restoreState( + QByteArray::fromBase64(window_state.window_state_data.toUtf8())); - size_ = {width, height}; + // restore window size & location + if (window_state.window_save) { + pos_ = {window_state.x, window_state.y}; + size_ = {window_state.width, window_state.height}; if (this->parent() != nullptr) { GF_UI_LOG_DEBUG("parent address: {}", @@ -114,21 +107,14 @@ void GpgFrontend::UI::GeneralMainWindow::slot_restore_settings() noexcept { } // appearance - SettingsObject general_settings_state("general_settings_state"); + AppearanceSO appearance(SettingsObject("general_settings_state")); - 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}; - font_size_ = general_settings_state.Check("font_size", 10); + icon_size_ = {appearance.tool_bar_icon_width, + appearance.tool_bar_icon_height}; + font_size_ = appearance.info_board_font_size; this->setIconSize(icon_size_); - - // icon_style - int s_icon_style = - general_settings_state.Check("icon_style", Qt::ToolButtonTextUnderIcon); - this->setToolButtonStyle(static_cast<Qt::ToolButtonStyle>(s_icon_style)); + this->setToolButtonStyle(appearance.tool_bar_button_style); icon_style_ = toolButtonStyle(); } catch (...) { @@ -141,32 +127,22 @@ void GpgFrontend::UI::GeneralMainWindow::slot_save_settings() noexcept { GF_UI_LOG_DEBUG("save main window state, name: {}", name_); SettingsObject general_windows_state(name_ + "_state"); - // window position and size - general_windows_state["window_state"] = - saveState().toBase64().toStdString(); - general_windows_state["window_pos"]["x"] = pos().x(); - general_windows_state["window_pos"]["y"] = pos().y(); - - // update size of current dialog + // update geo of current dialog size_ = this->size(); + pos_ = this->pos(); - general_windows_state["window_size"]["width"] = size_.width(); - general_windows_state["window_size"]["height"] = size_.height(); - general_windows_state["window_save"] = true; - - SettingsObject general_settings_state("general_settings_state"); - - // icon size - general_settings_state["icon_size"]["width"] = icon_size_.width(); - general_settings_state["icon_size"]["height"] = icon_size_.height(); - - // font size - general_settings_state["font_size"] = font_size_; - - // tool button style - general_settings_state["icon_style"] = this->toolButtonStyle(); + WindowStateSO window_state; + window_state.x = pos_.x(); + window_state.y = pos_.y(); + window_state.width = size_.width(); + window_state.height = size_.height(); + window_state.window_save = true; + window_state.window_state_data = this->saveState().toBase64(); + general_windows_state.Store(window_state.Json()); } catch (...) { GF_UI_LOG_ERROR("gernal main window: {}, caught exception", name_); } } + +} // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/main_window/MainWindow.cpp b/src/ui/main_window/MainWindow.cpp index e8280e93..0faa7379 100644 --- a/src/ui/main_window/MainWindow.cpp +++ b/src/ui/main_window/MainWindow.cpp @@ -37,6 +37,7 @@ #include "ui/UISignalStation.h" #include "ui/main_window/GeneralMainWindow.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/KeyServerSO.h" #include "ui/widgets/KeyList.h" namespace GpgFrontend::UI { @@ -190,21 +191,17 @@ void MainWindow::restore_settings() { try { GF_UI_LOG_DEBUG("restore settings key_server"); - SettingsObject key_server_json("key_server"); - if (!key_server_json.contains("server_list") || - key_server_json["server_list"].empty()) { - key_server_json["server_list"] = {"https://keyserver.ubuntu.com", - "https://keys.openpgp.org"}; - } - if (!key_server_json.contains("default_server")) { - key_server_json["default_server"] = 0; - } + KeyServerSO key_server(SettingsObject("key_server")); + + if (key_server.server_list.empty()) key_server.ResetDefaultServerList(); + if (key_server.default_server < 0) key_server.default_server = 0; 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"]; @@ -233,25 +230,30 @@ void MainWindow::restore_settings() { } void MainWindow::recover_editor_unsaved_pages_from_cache() { - auto unsaved_page_array = + auto json_data = CacheManager::GetInstance().LoadCache("editor_unsaved_pages"); - if (!unsaved_page_array.is_array() || unsaved_page_array.empty()) { + if (json_data.isEmpty() || !json_data.isArray()) { return; } GF_UI_LOG_DEBUG("plan ot recover unsaved page from cache, page array: {}", - unsaved_page_array.dump()); + json_data.toJson()); bool first = true; - for (auto &unsaved_page_json : unsaved_page_array) { + QJsonArray unsaved_page_array = json_data.array(); + for (const auto &value_ref : unsaved_page_array) { + if (!value_ref.isObject()) continue; + auto unsaved_page_json = value_ref.toObject(); + if (!unsaved_page_json.contains("title") || !unsaved_page_json.contains("content")) { continue; } - QString title = QString::fromStdString(unsaved_page_json["title"]); - QString content = QString::fromStdString(unsaved_page_json["content"]); + + QString title = unsaved_page_json["title"].toString(); + QString content = unsaved_page_json["content"].toString(); GF_UI_LOG_DEBUG( "recovering unsaved page from cache, page title: {}, content size", @@ -294,7 +296,7 @@ void MainWindow::closeEvent(QCloseEvent *event) { if (event->isAccepted()) { // clear cache of unsaved page CacheManager::GetInstance().SaveCache("editor_unsaved_pages", - nlohmann::json::array(), true); + QJsonDocument(QJsonArray()), true); // clear password from memory // GpgContext::GetInstance().clearPasswordCache(); diff --git a/src/ui/main_window/MainWindowSlotUI.cpp b/src/ui/main_window/MainWindowSlotUI.cpp index 772204b1..2c7a6f62 100644 --- a/src/ui/main_window/MainWindowSlotUI.cpp +++ b/src/ui/main_window/MainWindowSlotUI.cpp @@ -34,6 +34,7 @@ #include "ui/function/RaisePinentry.h" #include "ui/main_window/KeyMgmt.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/AppearanceSO.h" namespace GpgFrontend::UI { @@ -100,30 +101,25 @@ void MainWindow::slot_disable_tab_actions(int number) { } void MainWindow::slot_open_settings_dialog() { - auto dialog = new SettingsDialog(this); + auto* dialog = new SettingsDialog(this); connect(dialog, &SettingsDialog::finished, this, [&]() -> void { - SettingsObject general_settings_state("general_settings_state"); + AppearanceSO appearance(SettingsObject("general_settings_state")); + GF_UI_LOG_DEBUG("tool bar icon_size: {}, {}", + appearance.tool_bar_icon_width, + appearance.tool_bar_icon_height); - 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); - - general_settings_state.Check("info_font_size", 10); - - // icon_style - int s_icon_style = - general_settings_state.Check("icon_style", Qt::ToolButtonTextUnderIcon); - auto icon_style = static_cast<Qt::ToolButtonStyle>(s_icon_style); - this->setToolButtonStyle(icon_style); - import_button_->setToolButtonStyle(icon_style); + this->setToolButtonStyle(appearance.tool_bar_button_style); + import_button_->setToolButtonStyle(appearance.tool_bar_button_style); // icons ize - this->setIconSize(QSize(width, height)); - import_button_->setIconSize(QSize(width, height)); + this->setIconSize( + QSize(appearance.tool_bar_icon_width, appearance.tool_bar_icon_height)); + import_button_->setIconSize( + QSize(appearance.tool_bar_icon_width, appearance.tool_bar_icon_height)); // restart mainwindow if necessary - if (get_restart_needed()) { + if (get_restart_needed() != 0) { if (edit_->MaybeSaveAnyTab()) { save_settings(); emit SignalRestartApplication(get_restart_needed()); diff --git a/src/ui/struct/CacheObject.cpp b/src/ui/struct/CacheObject.cpp new file mode 100644 index 00000000..5413a80e --- /dev/null +++ b/src/ui/struct/CacheObject.cpp @@ -0,0 +1,48 @@ +/** + * 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 "CacheObject.h" + +#include <utility> + +#include "core/function/CacheManager.h" + +namespace GpgFrontend::UI { + +CacheObject::CacheObject(QString cache_name) + : cache_name_(std::move(cache_name)) { + GF_UI_LOG_DEBUG("loading cache from: {}", this->cache_name_); + this->QJsonDocument::operator=( + CacheManager::GetInstance().LoadCache(cache_name_)); +} + +CacheObject::~CacheObject() { + CacheManager::GetInstance().SaveCache(cache_name_, *this); +} + +} // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/struct/CacheObject.h b/src/ui/struct/CacheObject.h new file mode 100644 index 00000000..ae8aa056 --- /dev/null +++ b/src/ui/struct/CacheObject.h @@ -0,0 +1,52 @@ +/** + * 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::UI { + +class CacheObject : public QJsonDocument { + public: + /** + * @brief Construct a new Cache Object object + * + * @param cache_name + */ + explicit CacheObject(QString cache_name); + + /** + * @brief Destroy the Cache Object object + * + */ + ~CacheObject(); + + private: + QString cache_name_; ///< +}; + +} // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/struct/SettingsObject.cpp b/src/ui/struct/SettingsObject.cpp index d03a4fe3..cc5e85bf 100644 --- a/src/ui/struct/SettingsObject.cpp +++ b/src/ui/struct/SettingsObject.cpp @@ -28,81 +28,42 @@ #include "SettingsObject.h" -nlohmann::json& GpgFrontend::UI::SettingsObject::Check( - 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"); - this->nlohmann::json::operator=(nlohmann::json::object()); - } +#include "core/function/DataObjectOperator.h" - try { - 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[](s_key) = nlohmann::json::object(); - } else { - this->nlohmann::json::operator[](s_key) = default_value; - } - } - return this->nlohmann::json::at(s_key); - } catch (nlohmann::json::exception& e) { - GF_UI_LOG_ERROR(e.what()); - throw e; - } -} - -GpgFrontend::UI::SettingsObject GpgFrontend::UI::SettingsObject::Check( - 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()); - } +namespace GpgFrontend::UI { - 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[](s_key) = nlohmann::json::object(); - } - return SettingsObject{nlohmann::json::operator[](s_key), false}; -} - -GpgFrontend::UI::SettingsObject::SettingsObject(QString settings_name) +SettingsObject::SettingsObject(QString settings_name) : settings_name_(std::move(settings_name)) { try { GF_UI_LOG_DEBUG("loading settings from: {}", this->settings_name_); - auto _json_optional = - GpgFrontend::DataObjectOperator::GetInstance().GetDataObject( - settings_name_); + auto json_optional = + DataObjectOperator::GetInstance().GetDataObject(settings_name_); - if (_json_optional.has_value()) { + if (json_optional.has_value() && json_optional->isObject()) { GF_UI_LOG_DEBUG("settings object: {} loaded.", settings_name_); - nlohmann::json::operator=(_json_optional.value()); + QJsonObject::operator=(json_optional.value().object()); } else { GF_UI_LOG_DEBUG("settings object: {} not found.", settings_name_); - nlohmann::json::operator=({}); + QJsonObject::operator=({}); } } catch (std::exception& e) { - GF_UI_LOG_ERROR(e.what()); + GF_UI_LOG_ERROR("load setting object error: {}", e.what()); } } -GpgFrontend::UI::SettingsObject::SettingsObject(nlohmann::json _sub_json, bool) - : nlohmann::json(std::move(_sub_json)) {} +SettingsObject::SettingsObject(QJsonObject sub_json) + : QJsonObject(std::move(sub_json)) {} -GpgFrontend::UI::SettingsObject::~SettingsObject() { +SettingsObject::~SettingsObject() { if (!settings_name_.isEmpty()) { - GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(settings_name_, - *this); + DataObjectOperator::GetInstance().SaveDataObj(settings_name_, + QJsonDocument(*this)); } -}
\ No newline at end of file +} + +void SettingsObject::Store(const QJsonObject& json) { + auto* parent = (static_cast<QJsonObject*>(this)); + *parent = json; +} +} // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/struct/SettingsObject.h b/src/ui/struct/SettingsObject.h index 25e459ac..a9e5819f 100644 --- a/src/ui/struct/SettingsObject.h +++ b/src/ui/struct/SettingsObject.h @@ -28,18 +28,14 @@ #pragma once -#include <utility> - -#include "core/function/DataObjectOperator.h" - namespace GpgFrontend::UI { /** * @brief The SettingsObject class - * This class is used to store settings for the application securely. + * This class is used to store data for the application securely. * */ -class SettingsObject : public nlohmann::json { +class SettingsObject : public QJsonObject { public: /** * @brief Construct a new Settings Object object @@ -53,7 +49,7 @@ class SettingsObject : public nlohmann::json { * * @param _sub_json */ - explicit SettingsObject(nlohmann::json _sub_json, bool); + explicit SettingsObject(QJsonObject sub_json); /** * @brief Destroy the Settings Object object @@ -64,20 +60,8 @@ class SettingsObject : public nlohmann::json { /** * @brief * - * @param key - * @param default_value - * @return nlohmann::json& - */ - nlohmann::json& Check(const QString& key, - const nlohmann::json& default_value); - - /** - * @brief - * - * @param key - * @return SettingsObject */ - SettingsObject Check(const QString& key); + void Store(const QJsonObject&); private: QString settings_name_; ///< diff --git a/src/ui/struct/settings/AppearanceSO.h b/src/ui/struct/settings/AppearanceSO.h new file mode 100644 index 00000000..25262f22 --- /dev/null +++ b/src/ui/struct/settings/AppearanceSO.h @@ -0,0 +1,77 @@ +/** + * 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::UI { + +struct AppearanceSO { + int text_editor_font_size = 12; + int info_board_font_size = 12; + int tool_bar_icon_width = 24; + int tool_bar_icon_height = 24; + Qt::ToolButtonStyle tool_bar_button_style = Qt::ToolButtonTextUnderIcon; + + bool save_window_state; + + explicit AppearanceSO(const QJsonObject& j) { + if (const auto v = j["text_editor_font_size"]; v.isDouble()) { + text_editor_font_size = v.toInt(); + } + if (const auto v = j["info_board_font_size"]; v.isDouble()) { + info_board_font_size = v.toInt(); + } + if (const auto v = j["tool_bar_icon_width"]; v.isDouble()) { + tool_bar_icon_width = v.toInt(); + } + if (const auto v = j["tool_bar_icon_height"]; v.isDouble()) { + tool_bar_icon_height = v.toInt(); + } + if (const auto v = j["tool_bar_button_style"]; v.isDouble()) { + tool_bar_button_style = static_cast<Qt::ToolButtonStyle>(v.toInt()); + } + + if (const auto v = j["save_window_state"]; v.isBool()) { + save_window_state = v.toBool(); + } + } + + [[nodiscard]] auto ToJson() const -> QJsonObject { + QJsonObject j; + j["text_editor_font_size"] = text_editor_font_size; + j["info_board_font_size"] = info_board_font_size; + j["tool_bar_icon_width"] = tool_bar_icon_width; + j["tool_bar_icon_height"] = tool_bar_icon_height; + j["tool_bar_button_style"] = tool_bar_button_style; + + j["save_window_state"] = save_window_state; + return j; + } +}; + +} // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/struct/settings/KeyServerSO.h b/src/ui/struct/settings/KeyServerSO.h new file mode 100644 index 00000000..3c9320d2 --- /dev/null +++ b/src/ui/struct/settings/KeyServerSO.h @@ -0,0 +1,79 @@ +/** + * 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::UI { + +struct KeyServerSO { + int default_server = 0; + QStringList server_list; + + KeyServerSO() = default; + + explicit KeyServerSO(const QJsonObject& j) { + if (const auto v = j["default_server"]; v.isDouble()) { + default_server = v.toInt(); + } + + if (const auto v = j["server_list"]; v.isArray()) { + const QJsonArray j_array = v.toArray(); + server_list.reserve(j_array.size()); + for (const auto& server : j_array) { + server_list.append(server.toString()); + } + } + + if (server_list.empty()) ResetDefaultServerList(); + } + + auto ToJson() -> QJsonObject { + QJsonObject j; + j["default_server"] = default_server; + auto j_array = QJsonArray(); + + for (const auto& s : server_list) { + j_array.push_back(s); + } + j["server_list"] = j_array; + return j; + } + + auto GetTargetServer() -> QString { + if (server_list.empty()) this->ResetDefaultServerList(); + if (default_server >= server_list.size()) default_server = 0; + return server_list[default_server]; + } + + void ResetDefaultServerList() { + server_list << "https://keyserver.ubuntu.com" + << "https://keys.openpgp.org"; + } +}; + +} // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/struct/settings/WindowStateSO.h b/src/ui/struct/settings/WindowStateSO.h new file mode 100644 index 00000000..3fa56f3c --- /dev/null +++ b/src/ui/struct/settings/WindowStateSO.h @@ -0,0 +1,65 @@ +/** + * 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::UI { + +struct WindowStateSO { + bool window_save = false; + QString window_state_data; + int x = 100; + int y = 100; + int width = 400; + int height = 200; + + WindowStateSO() = default; + + explicit WindowStateSO(const QJsonObject &j) { + if (const auto v = j["window_save"]; v.isBool()) window_save = v.toBool(); + if (const auto v = j["window_state_data"]; v.isString()) { + window_state_data = v.toString(); + } + if (const auto v = j["x"]; v.isDouble()) x = v.toInt(); + if (const auto v = j["y"]; v.isDouble()) y = v.toInt(); + if (const auto v = j["width"]; v.isDouble()) width = v.toInt(); + if (const auto v = j["height"]; v.isDouble()) height = v.toInt(); + } + + [[nodiscard]] auto Json() const -> QJsonObject { + QJsonObject j; + j["window_save"] = window_save; + j["window_state_data"] = window_state_data; + j["x"] = x; + j["y"] = y; + j["width"] = width; + j["height"] = height; + return j; + } +}; +} // namespace GpgFrontend::UI
\ No newline at end of file diff --git a/src/ui/thread/KeyServerImportTask.cpp b/src/ui/thread/KeyServerImportTask.cpp index 4e8a41db..cf5c6263 100644 --- a/src/ui/thread/KeyServerImportTask.cpp +++ b/src/ui/thread/KeyServerImportTask.cpp @@ -30,6 +30,7 @@ #include "core/function/gpg/GpgKeyImportExporter.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/KeyServerSO.h" GpgFrontend::UI::KeyServerImportTask::KeyServerImportTask( QString keyserver_url, std::vector<QString> keyids) @@ -40,27 +41,8 @@ GpgFrontend::UI::KeyServerImportTask::KeyServerImportTask( HoldOnLifeCycle(true); if (keyserver_url_.isEmpty()) { - try { - SettingsObject key_server_json("key_server"); - const auto key_server_list = - key_server_json.Check("server_list", nlohmann::json::array()); - - size_t const default_key_server_index = - key_server_json.Check("default_server", 0); - if (default_key_server_index >= key_server_list.size()) { - throw std::runtime_error("default_server index out of range"); - } - auto default_key_server = - key_server_list[default_key_server_index].get<std::string>(); - - keyserver_url_ = QString::fromStdString(default_key_server); - } catch (...) { - GF_UI_LOG_ERROR("setting operation error", "server_list", - "default_server"); - keyserver_url_ = "https://keys.openpgp.org"; - return; - } - + KeyServerSO key_server(SettingsObject("general_settings_state")); + keyserver_url_ = key_server.GetTargetServer(); GF_UI_LOG_DEBUG("key server import task sets key server url: {}", keyserver_url_); } diff --git a/src/ui/widgets/InfoBoardWidget.cpp b/src/ui/widgets/InfoBoardWidget.cpp index 26530f8d..bf3dba18 100644 --- a/src/ui/widgets/InfoBoardWidget.cpp +++ b/src/ui/widgets/InfoBoardWidget.cpp @@ -31,6 +31,7 @@ #include "core/GpgModel.h" #include "ui/UISignalStation.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/AppearanceSO.h" #include "ui_InfoBoard.h" namespace GpgFrontend::UI { @@ -81,12 +82,10 @@ void InfoBoardWidget::SetInfoBoard(const QString& text, status.setColor(QPalette::Text, color); ui_->infoBoard->setPalette(status); - SettingsObject general_settings_state("general_settings_state"); + AppearanceSO appearance(SettingsObject("general_settings_state")); // info board font size - auto info_font_size = - general_settings_state.Check("info_board").Check("font_size", 10); - ui_->infoBoard->setFont(QFont("Times", info_font_size)); + ui_->infoBoard->setFont(QFont("Times", appearance.info_board_font_size)); } void InfoBoardWidget::SlotRefresh(const QString& text, InfoBoardStatus status) { diff --git a/src/ui/widgets/PlainTextEditorPage.cpp b/src/ui/widgets/PlainTextEditorPage.cpp index 0a4d9d1a..1a6978fe 100644 --- a/src/ui/widgets/PlainTextEditorPage.cpp +++ b/src/ui/widgets/PlainTextEditorPage.cpp @@ -28,8 +28,6 @@ #include "PlainTextEditorPage.h" -#include <sstream> -#include <string> #include <utility> #include "core/function/CharsetOperator.h" @@ -37,6 +35,7 @@ #include "core/thread/Task.h" #include "core/thread/TaskRunnerGetter.h" #include "ui/struct/SettingsObject.h" +#include "ui/struct/settings/AppearanceSO.h" #include "ui_PlainTextEditor.h" namespace GpgFrontend::UI { @@ -50,13 +49,9 @@ PlainTextEditorPage::PlainTextEditorPage(QString file_path, QWidget *parent) ui_->textPage->setFocus(); ui_->loadingLabel->setHidden(true); - // Front in same width - SettingsObject general_settings_state("general_settings_state"); - // font size - auto editor_font_size = - general_settings_state.Check("text_editor").Check("font_size", 10); - ui_->textPage->setFont(QFont("Courier", editor_font_size)); + AppearanceSO appearance(SettingsObject("general_settings_state")); + ui_->textPage->setFont(QFont("Courier", appearance.text_editor_font_size)); this->setAttribute(Qt::WA_DeleteOnClose); diff --git a/src/ui/widgets/TextEdit.cpp b/src/ui/widgets/TextEdit.cpp index e29184b8..0c5fb631 100644 --- a/src/ui/widgets/TextEdit.cpp +++ b/src/ui/widgets/TextEdit.cpp @@ -35,6 +35,7 @@ #include "core/GpgModel.h" #include "core/function/CacheManager.h" #include "core/function/GlobalSettingStation.h" +#include "ui/struct/CacheObject.h" namespace GpgFrontend::UI { @@ -668,26 +669,24 @@ void TextEdit::slot_save_status_to_cache_for_revovery() { } auto raw_text = document->toRawText(); - GF_UI_LOG_DEBUG("unsaved page index: {}, tab title: {} tab content: {}", i, - tab_title, raw_text.size()); + GF_UI_LOG_DEBUG("unsaved page index: {}, tab title: {}", i, tab_title); unsaved_pages.emplace_back(i, tab_title, raw_text); } - nlohmann::json unsaved_page_array = nlohmann::json::array(); + CacheObject cache("editor_unsaved_pages"); + QJsonArray unsaved_page_array; for (const auto& page : unsaved_pages) { const auto [index, title, content] = page; - nlohmann::json page_json; + QJsonObject page_json; page_json["index"] = index; - page_json["title"] = title.toStdString(); - page_json["content"] = content.toStdString(); + page_json["title"] = title; + page_json["content"] = content; unsaved_page_array.push_back(page_json); } - GF_UI_LOG_DEBUG("unsaved page json array: {}", unsaved_page_array.dump()); - CacheManager::GetInstance().SaveCache("editor_unsaved_pages", - unsaved_page_array); + cache.setArray(unsaved_page_array); } } // namespace GpgFrontend::UI |