diff options
Diffstat (limited to 'src/ui/UserInterfaceUtils.cpp')
-rw-r--r-- | src/ui/UserInterfaceUtils.cpp | 462 |
1 files changed, 248 insertions, 214 deletions
diff --git a/src/ui/UserInterfaceUtils.cpp b/src/ui/UserInterfaceUtils.cpp index 7e236c02..9e1d906f 100644 --- a/src/ui/UserInterfaceUtils.cpp +++ b/src/ui/UserInterfaceUtils.cpp @@ -1,5 +1,5 @@ /** - * Copyright (C) 2021 Saturneric + * Copyright (C) 2021 Saturneric <[email protected]> * * This file is part of GpgFrontend. * @@ -20,7 +20,7 @@ * 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. + * Saturneric <[email protected]> starting on May 12, 2021. * * SPDX-License-Identifier: GPL-3.0-or-later * @@ -28,25 +28,24 @@ #include "UserInterfaceUtils.h" -#include <string> -#include <utility> -#include <vector> - #include "core/GpgConstants.h" -#include "core/common/CoreCommonUtil.h" -#include "core/function/CacheManager.h" #include "core/function/CoreSignalStation.h" -#include "core/function/FileOperator.h" -#include "core/function/GlobalSettingStation.h" #include "core/function/gpg/GpgKeyGetter.h" +#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 "dialog/gnupg/GnuPGControllerDialog.h" -#include "spdlog/spdlog.h" -#include "ui/SignalStation.h" +#include "core/typedef/GpgTypedef.h" +#include "core/utils/GpgUtils.h" +#include "core/utils/IOUtils.h" +#include "thread/KeyServerImportTask.h" +#include "ui/UISignalStation.h" #include "ui/dialog/WaitingDialog.h" +#include "ui/dialog/gnupg/GnuPGControllerDialog.h" +#include "ui/dialog/import_export/KeyServerImportDialog.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 { @@ -58,7 +57,7 @@ void show_verify_details(QWidget *parent, InfoBoardWidget *info_board, GpgError error, const GpgVerifyResult &verify_result) { // take out result info_board->ResetOptionActionsMenu(); - info_board->AddOptionalAction(_("Show Verify Details"), [=]() { + info_board->AddOptionalAction(QObject::tr("Show Verify Details"), [=]() { VerifyDetailsDialog(parent, error, verify_result); }); } @@ -67,17 +66,18 @@ void import_unknown_key_from_keyserver( QWidget *parent, const GpgVerifyResultAnalyse &verify_res) { QMessageBox::StandardButton reply; reply = QMessageBox::question( - parent, _("Public key not found locally"), - _("There is no target public key content in local for GpgFrontend to " - "gather enough information about this Signature. Do you want to " - "import the public key from Keyserver now?"), + parent, QObject::tr("Public key not found locally"), + QObject::tr( + "There is no target public key content in local for GpgFrontend to " + "gather enough information about this Signature. Do you want to " + "import the public key from Keyserver now?"), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { - auto dialog = KeyServerImportDialog(true, parent); + auto dialog = KeyServerImportDialog(parent); auto key_ids = std::make_unique<KeyIdArgsList>(); auto *signature = verify_res.GetSignatures(); while (signature != nullptr) { - SPDLOG_DEBUG("signature fpr: {}", signature->fpr); + GF_UI_LOG_DEBUG("signature fpr: {}", signature->fpr); key_ids->push_back(signature->fpr); signature = signature->next; } @@ -87,15 +87,14 @@ void import_unknown_key_from_keyserver( } void refresh_info_board(InfoBoardWidget *info_board, int status, - const std::string &report_text) { - if (status < 0) - info_board->SlotRefresh(QString::fromStdString(report_text), - INFO_ERROR_CRITICAL); - else if (status > 0) - info_board->SlotRefresh(QString::fromStdString(report_text), INFO_ERROR_OK); - else - info_board->SlotRefresh(QString::fromStdString(report_text), - INFO_ERROR_WARN); + const QString &report_text) { + if (status < 0) { + info_board->SlotRefresh(report_text, INFO_ERROR_CRITICAL); + } else if (status > 0) { + info_board->SlotRefresh(report_text, INFO_ERROR_OK); + } else { + info_board->SlotRefresh(report_text, INFO_ERROR_WARN); + } } void process_result_analyse(TextEdit *edit, InfoBoardWidget *info_board, @@ -116,12 +115,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, - Thread::Task::DataObjectPtr data_object) { - auto *dialog = - new WaitingDialog(QString::fromStdString(waiting_title), parent); + DataObjectPtr data_object) { + auto *dialog = new WaitingDialog(waiting_title, parent); auto *process_task = new Thread::Task(std::move(func), waiting_title, data_object, std::move(callback)); @@ -146,7 +144,7 @@ void process_operation(QWidget *parent, const std::string &waiting_title, looper.exec(); } -CommonUtils *CommonUtils::GetInstance() { +auto CommonUtils::GetInstance() -> CommonUtils * { if (instance_ == nullptr) { instance_ = std::make_unique<CommonUtils>(); } @@ -154,109 +152,154 @@ CommonUtils *CommonUtils::GetInstance() { } CommonUtils::CommonUtils() : QWidget(nullptr) { - connect(CoreCommonUtil::GetInstance(), &CoreCommonUtil::SignalGnupgNotInstall, - this, &CommonUtils::SignalGnupgNotInstall); + connect(CoreSignalStation::GetInstance(), + &CoreSignalStation::SignalBadGnupgEnv, this, + &CommonUtils::SignalBadGnupgEnv); connect(this, &CommonUtils::SignalKeyStatusUpdated, - SignalStation::GetInstance(), - &SignalStation::SignalKeyDatabaseRefresh); + UISignalStation::GetInstance(), + &UISignalStation::SignalKeyDatabaseRefresh); connect(this, &CommonUtils::SignalKeyDatabaseRefreshDone, - SignalStation::GetInstance(), - &SignalStation::SignalKeyDatabaseRefreshDone); - connect(this, &CommonUtils::SignalUserInputPassphraseDone, - CoreSignalStation::GetInstance(), - &CoreSignalStation::SignalUserInputPassphraseDone); + UISignalStation::GetInstance(), + &UISignalStation::SignalKeyDatabaseRefreshDone); // directly connect to SignalKeyStatusUpdated // to avoid the delay of signal emitting // when the key database is refreshed - connect(SignalStation::GetInstance(), - &SignalStation::SignalKeyDatabaseRefresh, this, + connect(UISignalStation::GetInstance(), + &UISignalStation::SignalKeyDatabaseRefresh, this, &CommonUtils::slot_update_key_status); - connect(CoreSignalStation::GetInstance(), - &CoreSignalStation::SignalNeedUserInputPassphrase, this, - &CommonUtils::slot_popup_passphrase_input_dialog); - connect(this, &CommonUtils::SignalRestartApplication, - SignalStation::GetInstance(), - &SignalStation::SignalRestartApplication); + UISignalStation::GetInstance(), + &UISignalStation::SignalRestartApplication); - connect(SignalStation::GetInstance(), - &SignalStation::SignalRestartApplication, this, + connect(UISignalStation::GetInstance(), + &UISignalStation::SignalRestartApplication, this, &CommonUtils::SlotRestartApplication); - connect(this, &CommonUtils::SignalGnupgNotInstall, this, [=]() { - QMessageBox msgBox; - msgBox.setText(_("GnuPG Context Loading Failed")); - msgBox.setInformativeText( - _("Gnupg(gpg) is not installed correctly, please follow " - "<a href='https://www.gpgfrontend.bktus.com/#/" - "faq?id=how-to-deal-with-39env-loading-failed39'>this notes</a>" - " in FAQ to install Gnupg and then open " - "GpgFrontend. Or, you can open GnuPG Controller to set a custom " - "GnuPG " - "which GpgFrontend should use. Then, GpgFrontend will restart.")); - msgBox.setStandardButtons(QMessageBox::Open | QMessageBox::Cancel); - msgBox.setDefaultButton(QMessageBox::Save); - int ret = msgBox.exec(); - - switch (ret) { - case QMessageBox::Open: - (new GnuPGControllerDialog(this))->exec(); - // restart application when loop start - application_need_to_restart_at_once_ = true; - // restart application, core and ui - emit SignalRestartApplication(DEEP_RESTART_CODE); - break; - case QMessageBox::Cancel: - // close application - emit SignalRestartApplication(0); - break; - default: - // close application - emit SignalRestartApplication(0); - break; - } + connect(this, &CommonUtils::SignalBadGnupgEnv, this, + [=](const QString &reason) { + QMessageBox msg_box; + msg_box.setText(tr("GnuPG Context Loading Failed")); + msg_box.setInformativeText( + tr("Gnupg(gpg) is not installed correctly, please follow " + "<a href='https://www.gpgfrontend.bktus.com/#/" + "faq?id=how-to-deal-with-39env-loading-failed39'>this " + "notes</a> in FAQ to install Gnupg and then open " + "GpgFrontend. <br />" + "Or, you can open GnuPG Controller to set a " + "custom GnuPG which GpgFrontend should use. Then, " + "GpgFrontend will restart. <br /><br />" + "Breif Reason: %1") + .arg(reason)); + msg_box.setStandardButtons(QMessageBox::Open | QMessageBox::Cancel); + msg_box.setDefaultButton(QMessageBox::Save); + int ret = msg_box.exec(); + + switch (ret) { + case QMessageBox::Open: + (new GnuPGControllerDialog(this))->exec(); + // restart application when loop start + application_need_to_restart_at_once_ = true; + // restart application, core and ui + emit SignalRestartApplication(kDeepRestartCode); + break; + case QMessageBox::Cancel: + // close application + emit SignalRestartApplication(0); + break; + default: + // close application + emit SignalRestartApplication(0); + break; + } + }); +} + +void CommonUtils::WaitForOpera(QWidget *parent, + const QString &waiting_dialog_title, + const OperaWaitingCb &opera) { + QEventLoop looper; + QPointer<WaitingDialog> const dialog = + new WaitingDialog(waiting_dialog_title, parent); + connect(dialog, &QDialog::finished, &looper, &QEventLoop::quit); + connect(dialog, &QDialog::finished, dialog, &QDialog::deleteLater); + dialog->show(); + + QTimer::singleShot(64, parent, [=]() { + opera([dialog]() { + if (dialog != nullptr) { + GF_UI_LOG_DEBUG("called operating waiting cb, dialog: {}", + static_cast<void *>(dialog)); + dialog->close(); + dialog->accept(); + } + }); }); + + looper.exec(); +} + +void CommonUtils::RaiseMessageBox(QWidget *parent, GpgError err) { + GpgErrorDesc desc = DescribeGpgErrCode(err); + GpgErrorCode err_code = CheckGpgError2ErrCode(err); + + if (err_code == GPG_ERR_NO_ERROR) { + QMessageBox::information(parent, tr("Success"), + tr("Gpg Operation succeed.")); + } else { + RaiseFailureMessageBox(parent, err); + } +} + +void CommonUtils::RaiseFailureMessageBox(QWidget *parent, GpgError err) { + GpgErrorDesc desc = DescribeGpgErrCode(err); + GpgErrorCode err_code = CheckGpgError2ErrCode(err); + + QMessageBox::critical(parent, tr("Failure"), + tr("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) { - GpgImportInformation result = GpgKeyImportExporter::GetInstance().ImportKey( - std::make_unique<ByteArray>(in_buffer)); +void CommonUtils::SlotImportKeys(QWidget *parent, const QString &in_buffer) { + auto info = + GpgKeyImportExporter::GetInstance().ImportKey(GFBuffer(in_buffer)); emit SignalKeyStatusUpdated(); - new KeyImportDetailDialog(result, false, parent); + + (new KeyImportDetailDialog(info, parent)); } void CommonUtils::SlotImportKeyFromFile(QWidget *parent) { - QString file_name = QFileDialog::getOpenFileName( - this, _("Open Key"), QString(), - QString(_("Key Files")) + " (*.asc *.txt);;" + _("Keyring files") + - " (*.gpg);;All Files (*)"); + auto file_name = QFileDialog::getOpenFileName(this, tr("Open Key"), QString(), + tr("Key Files")) + + " (*.asc *.txt);;" + tr("Keyring files") + + " (*.gpg);;All Files (*)"; if (!file_name.isNull()) { QByteArray key_buffer; - if (!FileOperator::ReadFile(file_name, key_buffer)) { - QMessageBox::critical(nullptr, _("File Open Failed"), - _("Failed to open file: ") + file_name); + if (!ReadFile(file_name, key_buffer)) { + QMessageBox::critical(nullptr, tr("File Open Failed"), + tr("Failed to open file: ") + file_name); return; } - SlotImportKeys(parent, key_buffer.toStdString()); + SlotImportKeys(parent, key_buffer); } } void CommonUtils::SlotImportKeyFromKeyServer(QWidget *parent) { - auto dialog = new KeyServerImportDialog(false, parent); + auto *dialog = new KeyServerImportDialog(parent); dialog->show(); } 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); @@ -267,21 +310,21 @@ void CommonUtils::SlotExecuteCommand( &QEventLoop::quit); connect(cmd_process, &QProcess::errorOccurred, &looper, &QEventLoop::quit); connect(cmd_process, &QProcess::started, - []() -> void { SPDLOG_DEBUG("process started"); }); + []() -> void { GF_UI_LOG_DEBUG("process started"); }); connect(cmd_process, &QProcess::readyReadStandardOutput, [interact_func, cmd_process]() { interact_func(cmd_process); }); connect(cmd_process, &QProcess::errorOccurred, this, - [=]() -> void { SPDLOG_ERROR("error in process"); }); + [=]() -> void { GF_UI_LOG_ERROR("error in process"); }); connect(cmd_process, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, [=](int, QProcess::ExitStatus status) { if (status == QProcess::NormalExit) - SPDLOG_DEBUG("succeed in executing command: {}", cmd); + GF_UI_LOG_DEBUG("succeed in executing command: {}", cmd); else - SPDLOG_WARN("error in executing command: {}", cmd); + 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(); @@ -291,7 +334,7 @@ void CommonUtils::SlotExecuteGpgCommand( const QStringList &arguments, const std::function<void(QProcess *)> &interact_func) { QEventLoop looper; - auto dialog = new WaitingDialog(_("Processing"), nullptr); + auto dialog = new WaitingDialog(tr("Processing"), nullptr); dialog->show(); auto *gpg_process = new QProcess(&looper); gpg_process->setProcessChannelMode(QProcess::MergedChannels); @@ -304,29 +347,32 @@ void CommonUtils::SlotExecuteGpgCommand( &WaitingDialog::deleteLater); connect(gpg_process, &QProcess::errorOccurred, &looper, &QEventLoop::quit); connect(gpg_process, &QProcess::started, - []() -> void { SPDLOG_DEBUG("gpg process started"); }); + []() -> void { GF_UI_LOG_DEBUG("gpg process started"); }); connect(gpg_process, &QProcess::readyReadStandardOutput, [interact_func, gpg_process]() { interact_func(gpg_process); }); connect(gpg_process, &QProcess::errorOccurred, this, [=]() -> void { - SPDLOG_ERROR("Error in Process"); + GF_UI_LOG_ERROR("Error in Process"); dialog->close(); - QMessageBox::critical(nullptr, _("Failure"), - _("Failed to execute command.")); + QMessageBox::critical(nullptr, tr("Failure"), + tr("Failed to execute command.")); }); connect(gpg_process, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, [=](int, QProcess::ExitStatus status) { dialog->close(); if (status == QProcess::NormalExit) - QMessageBox::information(nullptr, _("Success"), - _("Succeed in executing command.")); + QMessageBox::information(nullptr, tr("Success"), + tr("Succeed in executing command.")); else - QMessageBox::information(nullptr, _("Warning"), - _("Finished executing command.")); + QMessageBox::information(nullptr, tr("Warning"), + tr("Finished executing command.")); }); - gpg_process->setProgram( - GpgContext::GetInstance().GetInfo(false).AppPath.c_str()); + const auto app_path = Module::RetrieveRTValueTypedOrDefault<>( + "core", "gpgme.ctx.app_path", QString{}); + GF_UI_LOG_DEBUG("got gnupg app path from rt: {}", app_path); + + gpg_process->setProgram(app_path); gpg_process->setArguments(arguments); gpg_process->start(); looper.exec(); @@ -336,51 +382,33 @@ 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; - - try { - auto &settings = GlobalSettingStation::GetInstance().GetUISettings(); - 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 int 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>(); - - SPDLOG_DEBUG("set target key server to default Key Server: {}", - target_keyserver); - } catch (...) { - SPDLOG_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")); + auto target_keyserver = + KeyServerSO(SettingsObject("key_server")).GetTargetServer(); + if (target_keyserver.isEmpty()) { + QMessageBox::critical( + nullptr, tr("Default Keyserver Not Found"), + tr("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.c_str()); + auto *thread = QThread::create([target_keyserver, key_ids, callback]() { + QUrl target_keyserver_url(target_keyserver); auto network_manager = std::make_unique<QNetworkAccessManager>(); // LOOP - decltype(key_ids.size()) current_index = 1, all_index = key_ids.size(); + decltype(key_ids.size()) current_index = 1; + decltype(key_ids.size()) all_index = key_ids.size(); + 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"); - SPDLOG_DEBUG("request url: {}", req_url.toString().toStdString()); + GF_UI_LOG_DEBUG("request url: {}", req_url.toString().toStdString()); // Waiting for reply QNetworkReply *reply = network_manager->get(QNetworkRequest(req_url)); @@ -388,41 +416,35 @@ void CommonUtils::SlotImportKeyFromKeyServer( connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); - // Get Data - auto key_data = reply->readAll(); - auto key_data_ptr = - std::make_unique<ByteArray>(key_data.data(), key_data.size()); - // Detect status - std::string status; + QString status; auto error = reply->error(); if (error != QNetworkReply::NoError) { switch (error) { case QNetworkReply::ContentNotFoundError: - status = _("Key Not Found"); + status = tr("Key Not Found"); break; case QNetworkReply::TimeoutError: - status = _("Timeout"); + status = tr("Timeout"); break; case QNetworkReply::HostNotFoundError: - status = _("Key Server Not Found"); + status = tr("Key Server Not Found"); break; default: - status = _("Connection Error"); + status = tr("Connection Error"); } } reply->deleteLater(); // Try importing - GpgImportInformation result = - GpgKeyImportExporter::GetInstance().ImportKey( - std::move(key_data_ptr)); + auto result = GpgKeyImportExporter::GetInstance().ImportKey( + GFBuffer(reply->readAll())); - if (result.imported == 1) { - status = _("The key has been updated"); + if (result->imported == 1) { + status = tr("The key has been updated"); } else { - status = _("No need to update the key"); + status = tr("No need to update the key"); } callback(key_id, status, current_index, all_index); current_index++; @@ -433,8 +455,8 @@ void CommonUtils::SlotImportKeyFromKeyServer( } void CommonUtils::slot_update_key_status() { - auto refresh_task = new Thread::Task( - [](Thread::Task::DataObjectPtr) -> int { + auto *refresh_task = new Thread::Task( + [](DataObjectPtr) -> int { // flush key cache for all GpgKeyGetter Intances. for (const auto &channel_id : GpgKeyGetter::GetAllChannelId()) { GpgKeyGetter::GetInstance(channel_id).FlushKeyCache(); @@ -443,33 +465,31 @@ void CommonUtils::slot_update_key_status() { }, "update_key_database_task"); connect(refresh_task, &Thread::Task::SignalTaskEnd, this, - &CommonUtils::SignalKeyDatabaseRefreshDone, - Qt::BlockingQueuedConnection); + &CommonUtils::SignalKeyDatabaseRefreshDone); // post the task to the default task runner Thread::TaskRunnerGetter::GetInstance().GetTaskRunner()->PostTask( refresh_task); } -void CommonUtils::slot_popup_passphrase_input_dialog() { - auto *dialog = new QInputDialog(QApplication::activeWindow(), Qt::Dialog); - dialog->setModal(true); - dialog->setWindowTitle(_("Password Input Dialog")); - dialog->setInputMode(QInputDialog::TextInput); - dialog->setTextEchoMode(QLineEdit::Password); - dialog->setLabelText(_("Please Input The Password")); - dialog->resize(500, 80); - dialog->exec(); - - QString password = dialog->textValue(); - dialog->deleteLater(); +void CommonUtils::slot_update_key_from_server_finished( + bool success, QString err_msg, QByteArray buffer, + std::shared_ptr<GpgImportInformation> info) { + if (!success) { + GF_UI_LOG_ERROR("get err from reply: {}", buffer); + QMessageBox::critical(nullptr, tr("Error"), err_msg); + return; + } + + // refresh the key database + emit UISignalStation::GetInstance()->SignalKeyDatabaseRefresh(); - // send signal - emit SignalUserInputPassphraseDone(password); + // show details + (new KeyImportDetailDialog(std::move(info), this))->exec(); } void CommonUtils::SlotRestartApplication(int code) { - SPDLOG_DEBUG("application need restart, code: {}", code); + GF_UI_LOG_DEBUG("application need restart, code: {}", code); if (code == 0) { std::exit(0); @@ -482,41 +502,55 @@ bool CommonUtils::isApplicationNeedRestart() { return application_need_to_restart_at_once_; } -bool CommonUtils::KeyExistsinFavouriteList(const GpgKey &key) { +auto CommonUtils::KeyExistsinFavouriteList(const GpgKey &key) -> bool { // 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()); - } + 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()); - } + 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()); - CacheManager::GetInstance().SaveCache("favourite_key_pair", key_array, true); + 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()); - if (it != key_array.end()) { - auto rm_it = - std::remove(key_array.begin(), key_array.end(), key.GetFingerprint()); - 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); +} + +/** + * @brief + * + */ +void CommonUtils::ImportKeyFromKeyServer(const KeyIdArgsList &key_ids) { + KeyServerSO key_server(SettingsObject("general_settings_state")); + auto target_keyserver = key_server.GetTargetServer(); + + auto *task = new KeyServerImportTask(target_keyserver, key_ids); + connect(task, &KeyServerImportTask::SignalKeyServerImportResult, this, + &CommonUtils::slot_update_key_from_server_finished); + Thread::TaskRunnerGetter::GetInstance() + .GetTaskRunner(Thread::TaskRunnerGetter::kTaskRunnerType_Network) + ->PostTask(task); } } // namespace GpgFrontend::UI
\ No newline at end of file |