refactor: start to tidy up code using clang-tidy

This commit is contained in:
saturneric 2023-10-29 02:46:15 +08:00
parent eb406ab4d3
commit fd46d46676
57 changed files with 876 additions and 914 deletions

View File

@ -49,7 +49,7 @@
// build info
#define PROJECT_NAME "@CMAKE_PROJECT_NAME@"
#define OS_PLATFORM @OS_PLATFORM @
#define OS_PLATFORM "@OS_PLATFORM@"
#define LOCALE_DIR "@LOCALE_DIR@"
// macros to find resource files

View File

@ -31,9 +31,9 @@
/**
* Logic Version (*.*.*)
*/
#define VERSION_MAJOR @CMAKE_PROJECT_VERSION_MAJOR@
#define VERSION_MINOR @CMAKE_PROJECT_VERSION_MINOR@
#define VERSION_PATCH @CMAKE_PROJECT_VERSION_PATCH@
#define VERSION_MAJOR "@CMAKE_PROJECT_VERSION_MAJOR@"
#define VERSION_MINOR "@CMAKE_PROJECT_VERSION_MINOR@"
#define VERSION_PATCH "@CMAKE_PROJECT_VERSION_PATCH@"
/**
* Code Version (According to Git)
@ -44,13 +44,12 @@
/**
* Generated Information (According to CMake)
*/
#define PROJECT_NAME "@PROJECT_NAME@"
#define BUILD_VERSION "@BUILD_VERSION@"
#define GIT_VERSION "@GIT_VERSION@"
/**
* Build Information
*/
#define BUILD_FLAG @BUILD_FLAG@
#define BUILD_FLAG "@BUILD_FLAG@"
#define BUILD_TIMESTAMP "@BUILD_TIMESTAMP@"
#define APP_INSTALL_FLAG "@APP_INSTALL_FLAG@"

View File

@ -198,7 +198,7 @@ GpgContext::GpgContext(const GpgContextInitArgs &args) : args_(args) {
Thread::TaskRunnerGetter::GetInstance()
.GetTaskRunner(Thread::TaskRunnerGetter::kTaskRunnerType_GPG)
->PostTask(new Thread::Task(
[=](Thread::DataObjectPtr) -> int {
[=](DataObjectPtr) -> int {
post_init_ctx();
return 0;
},

View File

@ -210,7 +210,7 @@ void InitGpgFrontendCore() {
Thread::TaskRunnerGetter::GetInstance()
.GetTaskRunner(Thread::TaskRunnerGetter::kTaskRunnerType_GPG)
->PostTask(new Thread::Task(
[=](Thread::DataObjectPtr data_obj) -> int {
[=](DataObjectPtr data_obj) -> int {
// init non-ascii channel
auto& ctx = GpgFrontend::GpgContext::CreateInstance(
GPGFRONTEND_NON_ASCII_CHANNEL,
@ -252,7 +252,7 @@ void InitGpgFrontendCore() {
"gnupginfogathering gnupg.gathering_done changed, restarting gpg "
"components");
// try to restart all components
GpgFrontend::GpgAdvancedOperator::GetInstance().RestartGpgComponents();
GpgFrontend::GpgAdvancedOperator::RestartGpgComponents();
});
Module::TriggerEvent("GPGFRONTEND_CORE_INITLIZED");
}

View File

@ -30,7 +30,6 @@
#include <cassert>
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
@ -38,44 +37,47 @@ void GpgFrontend::ChannelObject::SetChannel(int channel) {
this->channel_ = channel;
}
int GpgFrontend::ChannelObject::GetChannel() const { return channel_; }
auto GpgFrontend::ChannelObject::GetChannel() const -> int { return channel_; }
int GpgFrontend::ChannelObject::GetDefaultChannel() { return _default_channel; }
auto GpgFrontend::ChannelObject::GetDefaultChannel() -> int {
return kGpgFrontendDefaultChannel;
}
void GpgFrontend::SingletonStorage::ReleaseChannel(int channel) {
decltype(instances_map_.end()) _it;
decltype(instances_map_.end()) ins_it;
{
std::shared_lock<std::shared_mutex> lock(instances_mutex_);
_it = instances_map_.find(channel);
ins_it = instances_map_.find(channel);
}
if (_it != instances_map_.end()) instances_map_.erase(_it);
if (ins_it != instances_map_.end()) instances_map_.erase(ins_it);
}
GpgFrontend::ChannelObject* GpgFrontend::SingletonStorage::FindObjectInChannel(
int channel) {
auto GpgFrontend::SingletonStorage::FindObjectInChannel(int channel)
-> GpgFrontend::ChannelObject* {
// read instances_map_
decltype(instances_map_.end()) _it;
decltype(instances_map_.end()) ins_it;
{
std::shared_lock<std::shared_mutex> lock(instances_mutex_);
_it = instances_map_.find(channel);
if (_it == instances_map_.end()) {
ins_it = instances_map_.find(channel);
if (ins_it == instances_map_.end()) {
return nullptr;
} else {
return _it->second.get();
}
return ins_it->second.get();
}
}
std::vector<int> GpgFrontend::SingletonStorage::GetAllChannelId() {
std::vector<int> _channels;
auto GpgFrontend::SingletonStorage::GetAllChannelId() -> std::vector<int> {
std::vector<int> channels;
channels.reserve(instances_map_.size());
for (const auto& [key, value] : instances_map_) {
_channels.push_back(key);
channels.push_back(key);
}
return _channels;
return channels;
}
GpgFrontend::ChannelObject* GpgFrontend::SingletonStorage::SetObjectInChannel(
int channel, std::unique_ptr<ChannelObject> p_obj) {
auto GpgFrontend::SingletonStorage::SetObjectInChannel(
int channel, std::unique_ptr<ChannelObject> p_obj)
-> GpgFrontend::ChannelObject* {
{
SPDLOG_TRACE("set channel: {} instance address: {}", channel,
static_cast<void*>(&instances_map_));
@ -83,7 +85,7 @@ GpgFrontend::ChannelObject* GpgFrontend::SingletonStorage::SetObjectInChannel(
assert(p_obj != nullptr);
if (p_obj == nullptr) return nullptr;
auto raw_obj = p_obj.get();
auto* raw_obj = p_obj.get();
p_obj->SetChannel(channel);
{
std::unique_lock<std::shared_mutex> lock(instances_mutex_);
@ -93,18 +95,17 @@ GpgFrontend::ChannelObject* GpgFrontend::SingletonStorage::SetObjectInChannel(
}
}
GpgFrontend::SingletonStorage*
GpgFrontend::SingletonStorageCollection::GetSingletonStorage(
const std::type_info& type_id) {
auto GpgFrontend::SingletonStorageCollection::GetSingletonStorage(
const std::type_info& type_id) -> GpgFrontend::SingletonStorage* {
const auto hash = type_id.hash_code();
while (true) {
decltype(storages_map_.end()) _it;
decltype(storages_map_.end()) ins_it;
{
std::shared_lock<std::shared_mutex> lock(storages_mutex_);
_it = storages_map_.find(hash);
ins_it = storages_map_.find(hash);
}
if (_it == storages_map_.end()) {
if (ins_it == storages_map_.end()) {
{
std::unique_lock<std::shared_mutex> lock(storages_mutex_);
storages_map_.insert({hash, std::make_unique<SingletonStorage>()});
@ -112,15 +113,13 @@ GpgFrontend::SingletonStorageCollection::GetSingletonStorage(
SPDLOG_TRACE("hash: {} created, storage address: {} type_name: {}", hash,
static_cast<void*>(&storages_map_), type_id.name());
continue;
} else {
return _it->second.get();
}
return ins_it->second.get();
}
}
GpgFrontend::SingletonStorageCollection*
GpgFrontend::SingletonStorageCollection::GetInstance(
bool force_refresh = false) {
auto GpgFrontend::SingletonStorageCollection::GetInstance(
bool force_refresh = false) -> GpgFrontend::SingletonStorageCollection* {
static SingletonStorageCollection* instance = nullptr;
if (force_refresh || instance == nullptr) {

View File

@ -30,10 +30,11 @@
#include <shared_mutex>
#include "core/GpgFrontendCore.h"
namespace GpgFrontend {
static constexpr int kGpgFrontendDefaultChannel =
0; ///< the default channel id
/**
* @brief object which in channel system
*
@ -51,21 +52,21 @@ class GPGFRONTEND_CORE_EXPORT ChannelObject {
*
* @param channel
*/
ChannelObject(int channel);
explicit ChannelObject(int channel);
/**
* @brief Get the Default Channel object
*
* @return int
*/
static int GetDefaultChannel();
static auto GetDefaultChannel() -> int;
/**
* @brief Get the Channel object
*
* @return int
*/
[[nodiscard]] int GetChannel() const;
[[nodiscard]] auto GetChannel() const -> int;
/**
* @brief Set the Channel object
@ -75,8 +76,7 @@ class GPGFRONTEND_CORE_EXPORT ChannelObject {
void SetChannel(int channel);
private:
int channel_ = _default_channel; ///< The channel id
static constexpr int _default_channel = 0; ///< The default channel id
int channel_ = kGpgFrontendDefaultChannel; ///< The channel id
};
class GPGFRONTEND_CORE_EXPORT SingletonStorage {
@ -94,14 +94,14 @@ class GPGFRONTEND_CORE_EXPORT SingletonStorage {
* @param channel
* @return T*
*/
ChannelObject* FindObjectInChannel(int channel);
auto FindObjectInChannel(int channel) -> ChannelObject*;
/**
* @brief Get all the channel ids
*
* @return std::vector<int>
*/
std::vector<int> GetAllChannelId();
auto GetAllChannelId() -> std::vector<int>;
/**
* @brief Set a new object in channel object
@ -110,8 +110,8 @@ class GPGFRONTEND_CORE_EXPORT SingletonStorage {
* @param p_obj
* @return T*
*/
ChannelObject* SetObjectInChannel(int channel,
std::unique_ptr<ChannelObject> p_obj);
auto SetObjectInChannel(int channel, std::unique_ptr<ChannelObject> p_obj)
-> ChannelObject*;
private:
std::shared_mutex instances_mutex_; ///< mutex for _instances_map
@ -126,7 +126,7 @@ class GPGFRONTEND_CORE_EXPORT SingletonStorageCollection {
*
* @return SingletonStorageCollection*
*/
static SingletonStorageCollection* GetInstance(bool force_refresh);
static auto GetInstance(bool force_refresh) -> SingletonStorageCollection*;
/**
* @brief Get the Singleton Storage object
@ -134,7 +134,7 @@ class GPGFRONTEND_CORE_EXPORT SingletonStorageCollection {
* @param singleton_function_object
* @return SingletonStorage*
*/
SingletonStorage* GetSingletonStorage(const std::type_info&);
auto GetSingletonStorage(const std::type_info&) -> SingletonStorage*;
private:
std::shared_mutex storages_mutex_; ///< mutex for storages_map_
@ -159,8 +159,8 @@ class SingletonFunctionObject : public ChannelObject {
*
* @return SingletonFunctionObject&
*/
SingletonFunctionObject& operator=(const SingletonFunctionObject<T>&) =
delete;
auto operator=(const SingletonFunctionObject<T>&)
-> SingletonFunctionObject& = delete;
/**
* @brief Get the Instance object
@ -168,8 +168,8 @@ class SingletonFunctionObject : public ChannelObject {
* @param channel
* @return T&
*/
static T& GetInstance(
int channel = GpgFrontend::GPGFRONTEND_DEFAULT_CHANNEL) {
static auto GetInstance(
int channel = GpgFrontend::GPGFRONTEND_DEFAULT_CHANNEL) -> T& {
static std::mutex g_channel_mutex_map_lock;
static std::map<int, std::mutex> g_channel_mutex_map;
@ -186,22 +186,24 @@ class SingletonFunctionObject : public ChannelObject {
auto* p_storage =
SingletonStorageCollection::GetInstance(false)->GetSingletonStorage(
typeid(T));
auto* _p_pbj = (T*)(p_storage->FindObjectInChannel(channel));
auto* p_pbj = static_cast<T*>(p_storage->FindObjectInChannel(channel));
if (_p_pbj == nullptr) {
if (p_pbj == nullptr) {
// lock this channel
std::lock_guard<std::mutex> guard(g_channel_mutex_map[channel]);
// double check
if ((_p_pbj = (T*)(p_storage->FindObjectInChannel(channel))) != nullptr)
return *_p_pbj;
if (p_pbj = static_cast<T*>(p_storage->FindObjectInChannel(channel));
p_pbj != nullptr) {
return *p_pbj;
}
// do create object of this channel
auto new_obj = std::unique_ptr<ChannelObject>(new T(channel));
return *(T*)(p_storage->SetObjectInChannel(channel, std::move(new_obj)));
} else {
return *_p_pbj;
return *static_cast<T*>(
p_storage->SetObjectInChannel(channel, std::move(new_obj)));
}
return *p_pbj;
}
/**
@ -211,23 +213,24 @@ class SingletonFunctionObject : public ChannelObject {
* @param factory
* @return T&
*/
static T& CreateInstance(
static auto CreateInstance(
int channel,
std::function<std::unique_ptr<ChannelObject>(void)> factory) {
const std::function<std::unique_ptr<ChannelObject>(void)>& factory)
-> T& {
static_assert(std::is_base_of<SingletonFunctionObject<T>, T>::value,
"T not derived from SingletonFunctionObject<T>");
auto p_storage =
auto* p_storage =
SingletonStorageCollection::GetInstance(false)->GetSingletonStorage(
typeid(T));
auto _p_pbj = (T*)(p_storage->FindObjectInChannel(channel));
auto p_pbj = static_cast<T*>(p_storage->FindObjectInChannel(channel));
if (_p_pbj == nullptr) {
return *(
T*)(p_storage->SetObjectInChannel(channel, factory()));
} else
return *_p_pbj;
if (p_pbj == nullptr) {
return *static_cast<T*>(
p_storage->SetObjectInChannel(channel, factory()));
}
return *p_pbj;
}
/**
@ -247,21 +250,25 @@ class SingletonFunctionObject : public ChannelObject {
*
* @return int
*/
static int GetDefaultChannel() { return ChannelObject::GetDefaultChannel(); }
static auto GetDefaultChannel() -> int {
return ChannelObject::GetDefaultChannel();
}
/**
* @brief Get the Channel object
*
* @return int
*/
[[nodiscard]] int GetChannel() const { return ChannelObject::GetChannel(); }
[[nodiscard]] auto GetChannel() const -> int {
return ChannelObject::GetChannel();
}
/**
* @brief Get all the channel ids
*
* @return std::vector<int>
*/
static std::vector<int> GetAllChannelId() {
static auto GetAllChannelId() -> std::vector<int> {
return SingletonStorageCollection::GetInstance(false)
->GetSingletonStorage(typeid(T))
->GetAllChannelId();

View File

@ -33,8 +33,6 @@
#include <boost/date_time/gregorian/greg_duration.hpp>
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <cassert>
#include <string>
#include <vector>
void GpgFrontend::GenKeyInfo::SetAlgo(
const GpgFrontend::GenKeyInfo::KeyGenAlgo &m_algo) {
@ -237,8 +235,8 @@ GpgFrontend::GenKeyInfo::GenKeyInfo(bool m_is_sub_key, bool m_standalone)
SetAlgo(GetSupportedKeyAlgo()[0]);
}
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
&GpgFrontend::GenKeyInfo::GetSupportedKeyAlgo() {
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo> &
GpgFrontend::GenKeyInfo::GetSupportedKeyAlgo() {
static const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
support_key_algo = {
{"RSA", "RSA"},
@ -248,8 +246,8 @@ const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
return support_key_algo;
}
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
&GpgFrontend::GenKeyInfo::GetSupportedSubkeyAlgo() {
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo> &
GpgFrontend::GenKeyInfo::GetSupportedSubkeyAlgo() {
static const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
support_subkey_algo = {
{"RSA", "RSA"},
@ -263,8 +261,8 @@ const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
return support_subkey_algo;
}
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
&GpgFrontend::GenKeyInfo::GetSupportedKeyAlgoStandalone() {
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo> &
GpgFrontend::GenKeyInfo::GetSupportedKeyAlgoStandalone() {
static const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
support_subkey_algo_standalone = {
{"RSA", "RSA"},
@ -273,8 +271,8 @@ const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
return support_subkey_algo_standalone;
}
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
&GpgFrontend::GenKeyInfo::GetSupportedSubkeyAlgoStandalone() {
const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo> &
GpgFrontend::GenKeyInfo::GetSupportedSubkeyAlgoStandalone() {
static const std::vector<GpgFrontend::GenKeyInfo::KeyGenAlgo>
support_subkey_algo_standalone = {
{"RSA", "RSA"},

View File

@ -31,8 +31,6 @@
#include <boost/date_time.hpp>
#include <boost/date_time/gregorian/greg_duration_types.hpp>
#include <boost/format.hpp>
#include <string>
#include <vector>
#include "GpgFrontend.h"

View File

@ -28,8 +28,6 @@
#include "CoreCommonUtil.h"
#include <string>
namespace GpgFrontend {
std::unique_ptr<CoreCommonUtil> CoreCommonUtil::instance_ = nullptr; ///<

View File

@ -28,8 +28,6 @@
#pragma once
#include <string>
#include "core/GpgFrontendCore.h"
namespace GpgFrontend {

View File

@ -30,7 +30,6 @@
#include <algorithm>
#include <boost/format.hpp>
#include <string>
#include "function/DataObjectOperator.h"

View File

@ -31,7 +31,6 @@
#include <nlohmann/json.hpp>
#include <optional>
#include <shared_mutex>
#include <string>
#include "core/GpgFunctionObject.h"

View File

@ -34,8 +34,6 @@
#include <unicode/utypes.h>
#include <cstddef>
#include <memory>
#include <string>
GpgFrontend::CharsetOperator::CharsetInfo GpgFrontend::CharsetOperator::Detect(
const std::string &buffer) {

View File

@ -34,12 +34,8 @@
#include "core/function/gpg/GpgCommandExecutor.h"
#include "core/module/ModuleManager.h"
#include "spdlog/spdlog.h"
GpgFrontend::GpgAdvancedOperator::GpgAdvancedOperator(int channel)
: SingletonFunctionObject(channel) {}
bool GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() {
auto GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() -> bool {
bool success = false;
const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>(
@ -51,10 +47,11 @@ bool GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() {
return false;
}
GpgFrontend::GpgCommandExecutor::GetInstance().ExecuteSync(
GpgFrontend::GpgCommandExecutor::ExecuteSync(
{gpgconf_path,
{"--reload", "gpg-agent"},
[&](int exit_code, const std::string &p_out, const std::string &p_err) {
[&](int exit_code, const std::string & /*p_out*/,
const std::string & /*p_err*/) {
if (exit_code == 0) {
SPDLOG_DEBUG("gpgconf reload exit code: {}", exit_code);
success = true;
@ -63,7 +60,7 @@ bool GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache() {
return success;
}
bool GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() {
auto GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() -> bool {
bool success = false;
const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>(
@ -75,7 +72,7 @@ bool GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents() {
return false;
}
GpgFrontend::GpgCommandExecutor::GetInstance().ExecuteSync(
GpgFrontend::GpgCommandExecutor::ExecuteSync(
{gpgconf_path,
{"--reload"},
[&](int exit_code, const std::string &p_out, const std::string &p_err) {
@ -101,7 +98,7 @@ void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() {
return;
}
GpgFrontend::GpgCommandExecutor::GetInstance().ExecuteSync(
GpgFrontend::GpgCommandExecutor::ExecuteSync(
{gpgconf_path,
{"--verbose", "--kill", "all"},
[&](int exit_code, const std::string &p_out, const std::string &p_err) {
@ -146,7 +143,7 @@ void GpgFrontend::GpgAdvancedOperator::RestartGpgComponents() {
}});
}
bool GpgFrontend::GpgAdvancedOperator::ResetConfigures() {
auto GpgFrontend::GpgAdvancedOperator::ResetConfigures() -> bool {
bool success = false;
const auto gpgconf_path = Module::RetrieveRTValueTypedOrDefault<>(
@ -158,7 +155,7 @@ bool GpgFrontend::GpgAdvancedOperator::ResetConfigures() {
return false;
}
GpgFrontend::GpgCommandExecutor::GetInstance().ExecuteSync(
GpgFrontend::GpgCommandExecutor::ExecuteSync(
{gpgconf_path,
{"--apply-defaults"},
[&](int exit_code, const std::string &p_out, const std::string &p_err) {
@ -175,7 +172,7 @@ bool GpgFrontend::GpgAdvancedOperator::ResetConfigures() {
return success;
}
bool GpgFrontend::GpgAdvancedOperator::StartGpgAgent() {
auto GpgFrontend::GpgAdvancedOperator::StartGpgAgent() -> bool {
bool success = false;
const auto gpg_agent_path = Module::RetrieveRTValueTypedOrDefault<>(
@ -195,7 +192,7 @@ bool GpgFrontend::GpgAdvancedOperator::StartGpgAgent() {
return false;
}
GpgFrontend::GpgCommandExecutor::GetInstance().ExecuteSync(
GpgFrontend::GpgCommandExecutor::ExecuteSync(
{gpg_agent_path,
{"--homedir", home_path, "--daemon"},
[&](int exit_code, const std::string &p_out, const std::string &p_err) {
@ -217,7 +214,7 @@ bool GpgFrontend::GpgAdvancedOperator::StartGpgAgent() {
return success;
}
bool GpgFrontend::GpgAdvancedOperator::StartDirmngr() {
auto GpgFrontend::GpgAdvancedOperator::StartDirmngr() -> bool {
bool success = false;
const auto dirmngr_path = Module::RetrieveRTValueTypedOrDefault<>(
@ -237,7 +234,7 @@ bool GpgFrontend::GpgAdvancedOperator::StartDirmngr() {
return false;
}
GpgFrontend::GpgCommandExecutor::GetInstance().ExecuteSync(
GpgFrontend::GpgCommandExecutor::ExecuteSync(
{dirmngr_path,
{"--homedir", home_path, "--daemon"},
[&](int exit_code, const std::string &p_out, const std::string &p_err) {
@ -258,7 +255,7 @@ bool GpgFrontend::GpgAdvancedOperator::StartDirmngr() {
return success;
}
bool GpgFrontend::GpgAdvancedOperator::StartKeyBoxd() {
auto GpgFrontend::GpgAdvancedOperator::StartKeyBoxd() -> bool {
bool success = false;
const auto keyboxd_path = Module::RetrieveRTValueTypedOrDefault<>(
@ -278,7 +275,7 @@ bool GpgFrontend::GpgAdvancedOperator::StartKeyBoxd() {
return false;
}
GpgFrontend::GpgCommandExecutor::GetInstance().ExecuteSync(
GpgFrontend::GpgCommandExecutor::ExecuteSync(
{keyboxd_path,
{"--homedir", home_path, "--daemon"},
[&](int exit_code, const std::string &p_out, const std::string &p_err) {

View File

@ -32,22 +32,17 @@
#pragma once
#include "core/GpgConstants.h"
#include "core/GpgContext.h"
#include "core/GpgFunctionObject.h"
namespace GpgFrontend {
class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator
: public SingletonFunctionObject<GpgAdvancedOperator> {
class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator {
public:
/**
* @brief Construct a new Basic Operator object
* @brief
*
* @param channel Channel corresponding to the context
* @return true
* @return false
*/
explicit GpgAdvancedOperator(
int channel = SingletonFunctionObject::GetDefaultChannel());
static auto ClearGpgPasswordCache() -> bool;
/**
* @brief
@ -55,7 +50,7 @@ class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator
* @return true
* @return false
*/
bool ClearGpgPasswordCache();
static auto ReloadGpgComponents() -> bool;
/**
* @brief
@ -63,7 +58,7 @@ class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator
* @return true
* @return false
*/
bool ReloadGpgComponents();
static void RestartGpgComponents();
/**
* @brief
@ -71,7 +66,7 @@ class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator
* @return true
* @return false
*/
void RestartGpgComponents();
static auto ResetConfigures() -> bool;
/**
* @brief
@ -79,7 +74,7 @@ class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator
* @return true
* @return false
*/
bool ResetConfigures();
static auto StartGpgAgent() -> bool;
/**
* @brief
@ -87,7 +82,7 @@ class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator
* @return true
* @return false
*/
bool StartGpgAgent();
static auto StartDirmngr() -> bool;
/**
* @brief
@ -95,19 +90,7 @@ class GPGFRONTEND_CORE_EXPORT GpgAdvancedOperator
* @return true
* @return false
*/
bool StartDirmngr();
/**
* @brief
*
* @return true
* @return false
*/
bool StartKeyBoxd();
private:
GpgContext& ctx_ = GpgContext::GetInstance(
SingletonFunctionObject::GetChannel()); ///< Corresponding context
static auto StartKeyBoxd() -> bool;
};
} // namespace GpgFrontend

View File

@ -28,26 +28,26 @@
#include "GpgBasicOperator.h"
#include <vector>
#include "GpgKeyGetter.h"
GpgFrontend::GpgBasicOperator::GpgBasicOperator(int channel)
: SingletonFunctionObject<GpgBasicOperator>(channel) {}
GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Encrypt(
auto GpgFrontend::GpgBasicOperator::Encrypt(
KeyListPtr keys, GpgFrontend::BypeArrayRef in_buffer,
GpgFrontend::ByteArrayPtr& out_buffer, GpgFrontend::GpgEncrResult& result) {
GpgFrontend::ByteArrayPtr& out_buffer, GpgFrontend::GpgEncrResult& result)
-> GpgFrontend::GpgError {
// gpgme_encrypt_result_t e_result;
gpgme_key_t recipients[keys->size() + 1];
int index = 0;
for (const auto& key : *keys) recipients[index++] = gpgme_key_t(key);
for (const auto& key : *keys) {
recipients[index++] = static_cast<gpgme_key_t>(key);
}
// Last entry data_in array has to be nullptr
recipients[keys->size()] = nullptr;
GpgData data_in(in_buffer.data(), in_buffer.size()), data_out;
GpgData data_in(in_buffer.data(), in_buffer.size());
GpgData data_out;
gpgme_error_t err = check_gpg_error(gpgme_op_encrypt(
ctx_, recipients, GPGME_ENCRYPT_ALWAYS_TRUST, data_in, data_out));
@ -61,12 +61,13 @@ GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Encrypt(
return err;
}
GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Decrypt(
auto GpgFrontend::GpgBasicOperator::Decrypt(
BypeArrayRef in_buffer, GpgFrontend::ByteArrayPtr& out_buffer,
GpgFrontend::GpgDecrResult& result) {
GpgFrontend::GpgDecrResult& result) -> GpgFrontend::GpgError {
gpgme_error_t err;
GpgData data_in(in_buffer.data(), in_buffer.size()), data_out;
GpgData data_in(in_buffer.data(), in_buffer.size());
GpgData data_out;
err = check_gpg_error(gpgme_op_decrypt(ctx_, data_in, data_out));
auto temp_data_out = data_out.Read2Buffer();
@ -78,19 +79,21 @@ GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Decrypt(
return err;
}
GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Verify(
BypeArrayRef& in_buffer, ByteArrayPtr& sig_buffer,
GpgVerifyResult& result) const {
auto GpgFrontend::GpgBasicOperator::Verify(BypeArrayRef& in_buffer,
ByteArrayPtr& sig_buffer,
GpgVerifyResult& result) const
-> GpgFrontend::GpgError {
gpgme_error_t err;
GpgData data_in(in_buffer.data(), in_buffer.size());
GpgData data_out;
if (sig_buffer != nullptr && sig_buffer->size() > 0) {
if (sig_buffer != nullptr && !sig_buffer->empty()) {
GpgData sig_data(sig_buffer->data(), sig_buffer->size());
err = check_gpg_error(gpgme_op_verify(ctx_, sig_data, data_in, nullptr));
} else
} else {
err = check_gpg_error(gpgme_op_verify(ctx_, data_in, nullptr, data_out));
}
auto temp_result = _new_result(gpgme_op_verify_result(ctx_));
std::swap(result, temp_result);
@ -98,15 +101,16 @@ GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Verify(
return err;
}
GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Sign(
auto GpgFrontend::GpgBasicOperator::Sign(
KeyListPtr signers, BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
gpgme_sig_mode_t mode, GpgSignResult& result) {
gpgme_sig_mode_t mode, GpgSignResult& result) -> GpgFrontend::GpgError {
gpgme_error_t err;
// Set Singers of this opera
SetSigners(*signers);
GpgData data_in(in_buffer.data(), in_buffer.size()), data_out;
GpgData data_in(in_buffer.data(), in_buffer.size());
GpgData data_out;
err = check_gpg_error(gpgme_op_sign(ctx_, data_in, data_out, mode));
@ -120,12 +124,14 @@ GpgFrontend::GpgError GpgFrontend::GpgBasicOperator::Sign(
return err;
}
gpgme_error_t GpgFrontend::GpgBasicOperator::DecryptVerify(
auto GpgFrontend::GpgBasicOperator::DecryptVerify(
BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgDecrResult& decrypt_result, GpgVerifyResult& verify_result) {
GpgDecrResult& decrypt_result, GpgVerifyResult& verify_result)
-> gpgme_error_t {
gpgme_error_t err;
GpgData data_in(in_buffer.data(), in_buffer.size()), data_out;
GpgData data_in(in_buffer.data(), in_buffer.size());
GpgData data_out;
err = check_gpg_error(gpgme_op_decrypt_verify(ctx_, data_in, data_out));
@ -141,10 +147,10 @@ gpgme_error_t GpgFrontend::GpgBasicOperator::DecryptVerify(
return err;
}
gpgme_error_t GpgFrontend::GpgBasicOperator::EncryptSign(
auto GpgFrontend::GpgBasicOperator::EncryptSign(
KeyListPtr keys, KeyListPtr signers, BypeArrayRef in_buffer,
ByteArrayPtr& out_buffer, GpgEncrResult& encr_result,
GpgSignResult& sign_result) {
GpgSignResult& sign_result) -> gpgme_error_t {
gpgme_error_t err;
SetSigners(*signers);
@ -153,12 +159,15 @@ gpgme_error_t GpgFrontend::GpgBasicOperator::EncryptSign(
// set key for user
int index = 0;
for (const auto& key : *keys) recipients[index++] = gpgme_key_t(key);
for (const auto& key : *keys) {
recipients[index++] = static_cast<gpgme_key_t>(key);
}
// Last entry dataIn array has to be nullptr
recipients[keys->size()] = nullptr;
GpgData data_in(in_buffer.data(), in_buffer.size()), data_out;
GpgData data_in(in_buffer.data(), in_buffer.size());
GpgData data_out;
// If the last parameter isnt 0, a private copy of data is made
err = check_gpg_error(gpgme_op_encrypt_sign(
@ -189,22 +198,23 @@ void GpgFrontend::GpgBasicOperator::SetSigners(KeyArgsList& signers) {
SPDLOG_DEBUG("not all signers added");
}
std::unique_ptr<GpgFrontend::KeyArgsList>
GpgFrontend::GpgBasicOperator::GetSigners() {
auto GpgFrontend::GpgBasicOperator::GetSigners()
-> std::unique_ptr<GpgFrontend::KeyArgsList> {
auto count = gpgme_signers_count(ctx_);
auto signers = std::make_unique<std::vector<GpgKey>>();
for (auto i = 0u; i < count; i++) {
for (auto i = 0U; i < count; i++) {
auto key = GpgKey(gpgme_signers_enum(ctx_, i));
signers->push_back(GpgKey(std::move(key)));
}
return signers;
}
gpg_error_t GpgFrontend::GpgBasicOperator::EncryptSymmetric(
auto GpgFrontend::GpgBasicOperator::EncryptSymmetric(
GpgFrontend::ByteArray& in_buffer, GpgFrontend::ByteArrayPtr& out_buffer,
GpgFrontend::GpgEncrResult& result) {
GpgFrontend::GpgEncrResult& result) -> gpg_error_t {
// deepcopy from ByteArray to GpgData
GpgData data_in(in_buffer.data(), in_buffer.size()), data_out;
GpgData data_in(in_buffer.data(), in_buffer.size());
GpgData data_out;
gpgme_error_t err = check_gpg_error(gpgme_op_encrypt(
ctx_, nullptr, GPGME_ENCRYPT_SYMMETRIC, data_in, data_out));

View File

@ -62,8 +62,8 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
* @param result the result of the operation
* @return error code
*/
gpg_error_t Encrypt(KeyListPtr keys, BypeArrayRef in_buffer,
ByteArrayPtr& out_buffer, GpgEncrResult& result);
auto Encrypt(KeyListPtr keys, BypeArrayRef in_buffer,
ByteArrayPtr& out_buffer, GpgEncrResult& result) -> gpg_error_t;
/**
* @brief Call the interface provided by GPGME to symmetrical encryption
@ -73,8 +73,8 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
* @param result Encrypted results
* @return gpg_error_t
*/
gpg_error_t EncryptSymmetric(BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgEncrResult& result);
auto EncryptSymmetric(BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgEncrResult& result) -> gpg_error_t;
/**
*
@ -89,10 +89,9 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
* @param sign_result Signature result
* @return
*/
gpgme_error_t EncryptSign(KeyListPtr keys, KeyListPtr signers,
BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgEncrResult& encr_result,
GpgSignResult& sign_result);
auto EncryptSign(KeyListPtr keys, KeyListPtr signers, BypeArrayRef in_buffer,
ByteArrayPtr& out_buffer, GpgEncrResult& encr_result,
GpgSignResult& sign_result) -> gpgme_error_t;
/**
* @brief Call the interface provided by gpgme for decryption operation
@ -102,8 +101,8 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
* @param result the result of the operation
* @return error code
*/
gpgme_error_t Decrypt(BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgDecrResult& result);
auto Decrypt(BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgDecrResult& result) -> gpgme_error_t;
/**
* @brief Call the interface provided by gpgme to perform decryption and
@ -115,9 +114,9 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
* @param verify_result the result of the verifying operation
* @return error code
*/
gpgme_error_t DecryptVerify(BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgDecrResult& decrypt_result,
GpgVerifyResult& verify_result);
auto DecryptVerify(BypeArrayRef in_buffer, ByteArrayPtr& out_buffer,
GpgDecrResult& decrypt_result,
GpgVerifyResult& verify_result) -> gpgme_error_t;
/**
* @brief Call the interface provided by gpgme for verification operation
@ -127,8 +126,8 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
* @param result the result of the operation
* @return error code
*/
gpgme_error_t Verify(BypeArrayRef in_buffer, ByteArrayPtr& sig_buffer,
GpgVerifyResult& result) const;
auto Verify(BypeArrayRef in_buffer, ByteArrayPtr& sig_buffer,
GpgVerifyResult& result) const -> gpgme_error_t;
/**
* @brief Call the interface provided by gpgme for signing operation
@ -150,9 +149,9 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
* @param result the result of the operation
* @return error code
*/
gpg_error_t Sign(KeyListPtr signers, BypeArrayRef in_buffer,
ByteArrayPtr& out_buffer, gpgme_sig_mode_t mode,
GpgSignResult& result);
auto Sign(KeyListPtr signers, BypeArrayRef in_buffer,
ByteArrayPtr& out_buffer, gpgme_sig_mode_t mode,
GpgSignResult& result) -> gpg_error_t;
/**
* @brief Set the private key for signatures, this operation is a global
@ -167,7 +166,7 @@ class GPGFRONTEND_CORE_EXPORT GpgBasicOperator
*
* @return Intelligent pointer pointing to the private key list
*/
std::unique_ptr<KeyArgsList> GetSigners();
auto GetSigners() -> std::unique_ptr<KeyArgsList>;
private:
GpgContext& ctx_ = GpgContext::GetInstance(

View File

@ -28,32 +28,161 @@
#include "GpgCommandExecutor.h"
#include <boost/format.hpp>
#include <string>
#include <utility>
#include "GpgFunctionObject.h"
#include "core/thread/DataObject.h"
#include "core/model/DataObject.h"
#include "core/module/Module.h"
#include "core/thread/Task.h"
#include "core/thread/TaskRunnerGetter.h"
#include "module/Module.h"
#include "spdlog/spdlog.h"
#include "thread/Task.h"
namespace GpgFrontend {
auto BuildTaskFromExecCtx(const GpgCommandExecutor::ExecuteContext &context)
-> Thread::Task * {
const auto &cmd = context.cmd;
const auto &arguments = context.arguments;
const auto &interact_function = context.int_func;
const auto &cmd_executor_callback = context.cb_func;
const std::string joined_argument = std::accumulate(
std::begin(arguments), std::end(arguments), std::string(),
[](const std::string &a, const std::string &b) -> std::string {
return a + (a.length() > 0 ? " " : "") + b;
});
SPDLOG_DEBUG("building task: called cmd {} arguments size: {}", cmd,
arguments.size());
Thread::Task::TaskCallback result_callback =
[cmd, joined_argument](int /*rtn*/, const DataObjectPtr &data_object) {
SPDLOG_DEBUG(
"data object args count of cmd executor result callback: {}",
data_object->GetObjectSize());
if (!data_object->Check<int, std::string, std::string,
GpgCommandExecutorCallback>()) {
throw std::runtime_error("invalid data object size");
}
auto exit_code = ExtractParams<int>(data_object, 0);
auto process_stdout = ExtractParams<std::string>(data_object, 1);
auto process_stderr = ExtractParams<std::string>(data_object, 2);
auto callback =
ExtractParams<GpgCommandExecutorCallback>(data_object, 3);
// call callback
SPDLOG_DEBUG(
"calling custom callback from caller of cmd {} {}, "
"exit_code: {}",
cmd, joined_argument, exit_code);
callback(exit_code, process_stdout, process_stderr);
};
Thread::Task::TaskRunnable runner =
[joined_argument](const DataObjectPtr &data_object) -> int {
SPDLOG_DEBUG("process runner called, data object size: {}",
data_object->GetObjectSize());
if (!data_object->Check<std::string, std::vector<std::string>,
GpgCommandExecutorInteractor,
GpgCommandExecutorCallback>()) {
throw std::runtime_error("invalid data object size");
}
// get arguments
auto cmd = ExtractParams<std::string>(data_object, 0);
auto arguments = ExtractParams<std::vector<std::string>>(data_object, 1);
auto interact_func =
ExtractParams<GpgCommandExecutorInteractor>(data_object, 2);
auto callback = ExtractParams<GpgCommandExecutorCallback>(data_object, 3);
// create process
auto *cmd_process = new QProcess();
// move to current thread
//
cmd_process->moveToThread(QThread::currentThread());
// set process channel mode
// this is to make sure we can get all output from stdout and stderr
cmd_process->setProcessChannelMode(QProcess::MergedChannels);
cmd_process->setProgram(QString::fromStdString(cmd));
// set arguments
QStringList q_arguments;
for (const auto &argument : arguments) {
q_arguments.append(QString::fromStdString(argument));
}
cmd_process->setArguments(q_arguments);
QObject::connect(
cmd_process, &QProcess::started, [cmd, joined_argument]() -> void {
SPDLOG_DEBUG(
"\n== Process Execute Started ==\nCommand: {}\nArguments: "
"{}\n========================",
cmd, joined_argument);
});
QObject::connect(
cmd_process, &QProcess::readyReadStandardOutput,
[interact_func, cmd_process]() { interact_func(cmd_process); });
QObject::connect(
cmd_process, &QProcess::errorOccurred,
[=](QProcess::ProcessError error) {
SPDLOG_ERROR("caught error while executing command: {} {}, error: {}",
cmd, joined_argument, error);
});
SPDLOG_DEBUG(
"\n== Process Execute Ready ==\nCommand: {}\nArguments: "
"{}\n========================",
cmd, joined_argument);
cmd_process->start();
cmd_process->waitForFinished();
std::string process_stdout =
cmd_process->readAllStandardOutput().toStdString();
std::string process_stderr =
cmd_process->readAllStandardError().toStdString();
int exit_code = cmd_process->exitCode();
SPDLOG_DEBUG(
"\n==== Process Execution Summary ====\n"
"Command: {}\n"
"Arguments: {}\n"
"Exit Code: {}\n"
"---- Standard Output ----\n"
"{}\n"
"---- Standard Error ----\n"
"{}\n"
"===============================",
cmd, joined_argument, exit_code, process_stdout, process_stderr);
cmd_process->close();
cmd_process->deleteLater();
data_object->Swap({exit_code, process_stdout, process_stderr, callback});
return 0;
};
return new Thread::Task(
std::move(runner),
(boost::format("GpgCommamdExecutor(%1%){%2%}") % cmd % joined_argument)
.str(),
TransferParams(cmd, arguments, interact_function, cmd_executor_callback),
std::move(result_callback));
}
GpgCommandExecutor::ExecuteContext::ExecuteContext(
std::string cmd, std::vector<std::string> arguments,
GpgCommandExecutorCallback callback, Module::TaskRunnerPtr task_runner,
GpgCommandExecutorInteractor int_func)
: cmd(cmd),
arguments(arguments),
cb_func(callback),
int_func(int_func),
task_runner(task_runner) {}
GpgCommandExecutor::GpgCommandExecutor(int channel)
: SingletonFunctionObject<GpgCommandExecutor>(channel) {}
: cmd(std::move(cmd)),
arguments(std::move(arguments)),
cb_func(std::move(callback)),
int_func(std::move(int_func)),
task_runner(std::move(task_runner)) {}
void GpgCommandExecutor::ExecuteSync(ExecuteContext context) {
Thread::Task *task = build_task_from_exec_ctx(context);
Thread::Task *task = BuildTaskFromExecCtx(context);
QEventLoop looper;
QObject::connect(task, &Thread::Task::SignalTaskEnd, &looper,
@ -83,177 +212,50 @@ void GpgCommandExecutor::ExecuteSync(ExecuteContext context) {
void GpgCommandExecutor::ExecuteConcurrentlyAsync(ExecuteContexts contexts) {
for (auto &context : contexts) {
auto &cmd = context.cmd;
const auto &cmd = context.cmd;
SPDLOG_INFO("gpg concurrently called cmd {}", cmd);
Thread::Task *task = build_task_from_exec_ctx(context);
Thread::Task *task = BuildTaskFromExecCtx(context);
if (context.task_runner != nullptr)
if (context.task_runner != nullptr) {
context.task_runner->PostTask(task);
else
} else {
GpgFrontend::Thread::TaskRunnerGetter::GetInstance()
.GetTaskRunner(
Thread::TaskRunnerGetter::kTaskRunnerType_External_Process)
->PostTask(task);
}
}
}
void GpgCommandExecutor::ExecuteConcurrentlySync(
const ExecuteContexts contexts) {
void GpgCommandExecutor::ExecuteConcurrentlySync(ExecuteContexts contexts) {
QEventLoop looper;
int remainingTasks = contexts.size();
auto remaining_tasks = contexts.size();
for (auto &context : contexts) {
auto &cmd = context.cmd;
const auto &cmd = context.cmd;
SPDLOG_INFO("gpg concurrently called cmd {}", cmd);
Thread::Task *task = build_task_from_exec_ctx(context);
Thread::Task *task = BuildTaskFromExecCtx(context);
QObject::connect(task, &Thread::Task::SignalTaskEnd, [&]() {
--remainingTasks;
if (remainingTasks <= 0) {
--remaining_tasks;
if (remaining_tasks <= 0) {
looper.quit();
}
});
if (context.task_runner != nullptr)
if (context.task_runner != nullptr) {
context.task_runner->PostTask(task);
else
} else {
GpgFrontend::Thread::TaskRunnerGetter::GetInstance()
.GetTaskRunner(
Thread::TaskRunnerGetter::kTaskRunnerType_External_Process)
->PostTask(task);
}
}
looper.exec();
}
Thread::Task *GpgCommandExecutor::build_task_from_exec_ctx(
const ExecuteContext &context) {
auto &cmd = context.cmd;
auto &arguments = context.arguments;
auto &interact_function = context.int_func;
auto &cmd_executor_callback = context.cb_func;
const std::string joined_argument = std::accumulate(
std::begin(arguments), std::end(arguments), std::string(),
[](const std::string &a, const std::string &b) -> std::string {
return a + (a.length() > 0 ? " " : "") + b;
});
SPDLOG_DEBUG("building task: called cmd {} arguments size: {}", cmd,
arguments.size());
Thread::Task::TaskCallback result_callback =
[cmd, joined_argument](int rtn, Thread::DataObjectPtr data_object) {
SPDLOG_DEBUG(
"data object args count of cmd executor result callback: {}",
data_object->GetObjectSize());
if (!data_object->Check<int, std::string, std::string,
GpgCommandExecutorCallback>())
throw std::runtime_error("invalid data object size");
auto exit_code = Thread::ExtractParams<int>(data_object, 0);
auto process_stdout =
Thread::ExtractParams<std::string>(data_object, 1);
auto process_stderr =
Thread::ExtractParams<std::string>(data_object, 2);
auto callback =
Thread::ExtractParams<GpgCommandExecutorCallback>(data_object, 3);
// call callback
SPDLOG_DEBUG(
"calling custom callback from caller of cmd {} {}, "
"exit_code: {}",
cmd, joined_argument, exit_code);
callback(exit_code, process_stdout, process_stderr);
};
Thread::Task::TaskRunnable runner =
[joined_argument](Thread::DataObjectPtr data_object) -> int {
SPDLOG_DEBUG("process runner called, data object size: {}",
data_object->GetObjectSize());
if (!data_object->Check<std::string, std::vector<std::string>,
GpgCommandExecutorInteractor,
GpgCommandExecutorCallback>())
throw std::runtime_error("invalid data object size");
// get arguments
auto cmd = Thread::ExtractParams<std::string>(data_object, 0);
auto arguments =
Thread::ExtractParams<std::vector<std::string>>(data_object, 1);
auto interact_func =
Thread::ExtractParams<GpgCommandExecutorInteractor>(data_object, 2);
auto callback =
Thread::ExtractParams<GpgCommandExecutorCallback>(data_object, 3);
auto *cmd_process = new QProcess();
cmd_process->moveToThread(QThread::currentThread());
cmd_process->setProcessChannelMode(QProcess::MergedChannels);
cmd_process->setProgram(QString::fromStdString(cmd));
QStringList q_arguments;
for (const auto &argument : arguments)
q_arguments.append(QString::fromStdString(argument));
cmd_process->setArguments(q_arguments);
QObject::connect(
cmd_process, &QProcess::started, [cmd, joined_argument]() -> void {
SPDLOG_DEBUG(
"\n== Process Execute Started ==\nCommand: {}\nArguments: "
"{}\n========================",
cmd, joined_argument);
});
QObject::connect(
cmd_process, &QProcess::readyReadStandardOutput,
[interact_func, cmd_process]() { interact_func(cmd_process); });
QObject::connect(
cmd_process, &QProcess::errorOccurred,
[=](QProcess::ProcessError error) {
SPDLOG_ERROR("caught error while executing command: {} {}, error: {}",
cmd, joined_argument, error);
});
SPDLOG_DEBUG(
"\n== Process Execute Ready ==\nCommand: {}\nArguments: "
"{}\n========================",
cmd, joined_argument);
cmd_process->start();
cmd_process->waitForFinished();
std::string process_stdout =
cmd_process->readAllStandardOutput().toStdString(),
process_stderr =
cmd_process->readAllStandardError().toStdString();
int exit_code = cmd_process->exitCode();
SPDLOG_DEBUG(
"\n==== Process Execution Summary ====\n"
"Command: {}\n"
"Arguments: {}\n"
"Exit Code: {}\n"
"---- Standard Output ----\n"
"{}\n"
"---- Standard Error ----\n"
"{}\n"
"===============================",
cmd, joined_argument, exit_code, process_stdout, process_stderr);
cmd_process->close();
cmd_process->deleteLater();
data_object->Swap({exit_code, process_stdout, process_stderr, callback});
return 0;
};
return new Thread::Task(
std::move(runner),
(boost::format("GpgCommamdExecutor(%1%){%2%}") % cmd % joined_argument)
.str(),
Thread::TransferParams(cmd, arguments, interact_function,
cmd_executor_callback),
std::move(result_callback));
}
} // namespace GpgFrontend

View File

@ -28,17 +28,7 @@
#pragma once
#include <initializer_list>
#include "core/module/Module.h"
#include "core/thread/TaskRunner.h"
#ifndef WINDOWS
#include <boost/process.hpp>
#endif
#include "core/GpgContext.h"
#include "core/GpgFunctionObject.h"
#include "core/thread/Task.h"
namespace GpgFrontend {
@ -50,8 +40,7 @@ using GpgCommandExecutorInteractor = std::function<void(QProcess *)>;
* @brief Extra commands related to GPG
*
*/
class GPGFRONTEND_CORE_EXPORT GpgCommandExecutor
: public SingletonFunctionObject<GpgCommandExecutor> {
class GPGFRONTEND_CORE_EXPORT GpgCommandExecutor {
public:
struct ExecuteContext {
const std::string cmd;
@ -70,31 +59,17 @@ class GPGFRONTEND_CORE_EXPORT GpgCommandExecutor
using ExecuteContexts = std::vector<ExecuteContext>;
/**
* @brief Construct a new Gpg Command Executor object
*
* @param channel Corresponding context
*/
explicit GpgCommandExecutor(
int channel = SingletonFunctionObject::GetDefaultChannel());
/**
* @brief Excuting a command
*
* @param arguments Command parameters
* @param interact_func Command answering function
*/
void ExecuteSync(ExecuteContext);
static void ExecuteSync(ExecuteContext);
void ExecuteConcurrentlyAsync(ExecuteContexts);
static void ExecuteConcurrentlyAsync(ExecuteContexts);
void ExecuteConcurrentlySync(ExecuteContexts);
private:
GpgContext &ctx_ = GpgContext::GetInstance(
SingletonFunctionObject::GetChannel()); ///< Corresponding context
Thread::Task *build_task_from_exec_ctx(const ExecuteContext &);
static void ExecuteConcurrentlySync(ExecuteContexts);
};
} // namespace GpgFrontend

View File

@ -27,19 +27,15 @@
*/
#include "GpgFileOpera.h"
#include <memory>
#include <string>
#include "core/GpgConstants.h"
#include "core/function/FileOperator.h"
#include "core/function/gpg/GpgBasicOperator.h"
#include "GpgBasicOperator.h"
#include "GpgConstants.h"
#include "function/FileOperator.h"
GpgFrontend::GpgFileOpera::GpgFileOpera(int channel)
: SingletonFunctionObject<GpgFileOpera>(channel) {}
GpgFrontend::GpgError GpgFrontend::GpgFileOpera::EncryptFile(
KeyListPtr keys, const std::string& in_path, const std::string& out_path,
GpgEncrResult& result, int _channel) {
auto GpgFrontend::GpgFileOpera::EncryptFile(KeyListPtr keys,
const std::string& in_path,
const std::string& out_path,
GpgEncrResult& result, int _channel)
-> GpgFrontend::GpgError {
#ifdef WINDOWS
auto in_path_std =
std::filesystem::path(QString::fromStdString(in_path).toStdU16String());
@ -68,9 +64,10 @@ GpgFrontend::GpgError GpgFrontend::GpgFileOpera::EncryptFile(
return err;
}
GpgFrontend::GpgError GpgFrontend::GpgFileOpera::DecryptFile(
const std::string& in_path, const std::string& out_path,
GpgDecrResult& result) {
auto GpgFrontend::GpgFileOpera::DecryptFile(const std::string& in_path,
const std::string& out_path,
GpgDecrResult& result)
-> GpgFrontend::GpgError {
#ifdef WINDOWS
auto in_path_std =
std::filesystem::path(QString::fromStdString(in_path).toStdU16String());
@ -100,11 +97,11 @@ GpgFrontend::GpgError GpgFrontend::GpgFileOpera::DecryptFile(
return err;
}
gpgme_error_t GpgFrontend::GpgFileOpera::SignFile(KeyListPtr keys,
const std::string& in_path,
const std::string& out_path,
GpgSignResult& result,
int _channel) {
auto GpgFrontend::GpgFileOpera::SignFile(KeyListPtr keys,
const std::string& in_path,
const std::string& out_path,
GpgSignResult& result, int _channel)
-> gpgme_error_t {
#ifdef WINDOWS
auto in_path_std =
std::filesystem::path(QString::fromStdString(in_path).toStdU16String());
@ -132,9 +129,10 @@ gpgme_error_t GpgFrontend::GpgFileOpera::SignFile(KeyListPtr keys,
return err;
}
gpgme_error_t GpgFrontend::GpgFileOpera::VerifyFile(
const std::string& data_path, const std::string& sign_path,
GpgVerifyResult& result, int _channel) {
auto GpgFrontend::GpgFileOpera::VerifyFile(const std::string& data_path,
const std::string& sign_path,
GpgVerifyResult& result,
int _channel) -> gpgme_error_t {
#ifdef WINDOWS
auto data_path_std =
std::filesystem::path(QString::fromStdString(data_path).toStdU16String());
@ -162,10 +160,10 @@ gpgme_error_t GpgFrontend::GpgFileOpera::VerifyFile(
return err;
}
gpg_error_t GpgFrontend::GpgFileOpera::EncryptSignFile(
auto GpgFrontend::GpgFileOpera::EncryptSignFile(
KeyListPtr keys, KeyListPtr signer_keys, const std::string& in_path,
const std::string& out_path, GpgEncrResult& encr_res,
GpgSignResult& sign_res, int _channel) {
GpgSignResult& sign_res, int _channel) -> gpg_error_t {
#ifdef WINDOWS
auto in_path_std =
std::filesystem::path(QString::fromStdString(in_path).toStdU16String());
@ -194,9 +192,11 @@ gpg_error_t GpgFrontend::GpgFileOpera::EncryptSignFile(
return err;
}
gpg_error_t GpgFrontend::GpgFileOpera::DecryptVerifyFile(
const std::string& in_path, const std::string& out_path,
GpgDecrResult& decr_res, GpgVerifyResult& verify_res) {
auto GpgFrontend::GpgFileOpera::DecryptVerifyFile(const std::string& in_path,
const std::string& out_path,
GpgDecrResult& decr_res,
GpgVerifyResult& verify_res)
-> gpg_error_t {
#ifdef WINDOWS
auto in_path_std =
std::filesystem::path(QString::fromStdString(in_path).toStdU16String());
@ -223,9 +223,9 @@ gpg_error_t GpgFrontend::GpgFileOpera::DecryptVerifyFile(
return err;
}
unsigned int GpgFrontend::GpgFileOpera::EncryptFileSymmetric(
auto GpgFrontend::GpgFileOpera::EncryptFileSymmetric(
const std::string& in_path, const std::string& out_path,
GpgFrontend::GpgEncrResult& result, int _channel) {
GpgFrontend::GpgEncrResult& result, int _channel) -> unsigned int {
#ifdef WINDOWS
auto in_path_std =
std::filesystem::path(QString::fromStdString(in_path).toStdU16String());

View File

@ -29,49 +29,46 @@
#pragma once
#include "core/GpgConstants.h"
#include "core/GpgContext.h"
#include "core/GpgModel.h"
namespace GpgFrontend {
/**
* @brief Executive files related to the basic operations that are provided by
* GpgBasicOperator
* @brief Executive files related to the basic operations of GPG
*
* @class class: GpgBasicOperator
*/
class GPGFRONTEND_CORE_EXPORT GpgFileOpera
: public SingletonFunctionObject<GpgFileOpera> {
class GPGFRONTEND_CORE_EXPORT GpgFileOpera {
public:
explicit GpgFileOpera(
int channel = SingletonFunctionObject::GetDefaultChannel());
/**
* @brief Encrypted file
* @brief Encrypted file with public key
*
* @param keys Used public key
* @param in_path The path where the enter file is located
* @param out_path The path where the output file is located
* @param result Encrypted results
* @param _channel Channel in context
* @param channel Channel in context
* @return unsigned int error code
*/
static unsigned int EncryptFile(KeyListPtr keys, const std::string& in_path,
const std::string& out_path,
GpgEncrResult& result,
int _channel = GPGFRONTEND_DEFAULT_CHANNEL);
static auto EncryptFile(KeyListPtr keys, const std::string& in_path,
const std::string& out_path, GpgEncrResult& result,
int channel = GPGFRONTEND_DEFAULT_CHANNEL)
-> unsigned int;
/**
* @brief
* @brief Encrypted file symmetrically (with password)
*
* @param in_path
* @param out_path
* @param result
* @param _channel
* @param channel
* @return unsigned int
*/
static unsigned int EncryptFileSymmetric(
const std::string& in_path, const std::string& out_path,
GpgEncrResult& result, int _channel = GPGFRONTEND_DEFAULT_CHANNEL);
static auto EncryptFileSymmetric(const std::string& in_path,
const std::string& out_path,
GpgEncrResult& result,
int channel = GPGFRONTEND_DEFAULT_CHANNEL)
-> unsigned int;
/**
* @brief
@ -81,40 +78,39 @@ class GPGFRONTEND_CORE_EXPORT GpgFileOpera
* @param result
* @return GpgError
*/
static GpgError DecryptFile(const std::string& in_path,
const std::string& out_path,
GpgDecrResult& result);
static auto DecryptFile(const std::string& in_path,
const std::string& out_path, GpgDecrResult& result)
-> GpgError;
/**
* @brief
* @brief Sign file with private key
*
* @param keys
* @param in_path
* @param out_path
* @param result
* @param _channel
* @param channel
* @return GpgError
*/
static GpgError SignFile(KeyListPtr keys, const std::string& in_path,
const std::string& out_path, GpgSignResult& result,
int _channel = GPGFRONTEND_DEFAULT_CHANNEL);
static auto SignFile(KeyListPtr keys, const std::string& in_path,
const std::string& out_path, GpgSignResult& result,
int channel = GPGFRONTEND_DEFAULT_CHANNEL) -> GpgError;
/**
* @brief
* @brief Verify file with public key
*
* @param data_path
* @param sign_path
* @param result
* @param _channel
* @param data_path The path where the enter file is located
* @param sign_path The path where the signature file is located
* @param result Verify results
* @param channel Channel in context
* @return GpgError
*/
static GpgError VerifyFile(const std::string& data_path,
const std::string& sign_path,
GpgVerifyResult& result,
int _channel = GPGFRONTEND_DEFAULT_CHANNEL);
static auto VerifyFile(const std::string& data_path,
const std::string& sign_path, GpgVerifyResult& result,
int channel = GPGFRONTEND_DEFAULT_CHANNEL) -> GpgError;
/**
* @brief
* @brief Encrypt and sign file with public key and private key
*
* @param keys
* @param signer_keys
@ -122,15 +118,15 @@ class GPGFRONTEND_CORE_EXPORT GpgFileOpera
* @param out_path
* @param encr_res
* @param sign_res
* @param _channel
* @param channel
* @return GpgError
*/
static GpgError EncryptSignFile(KeyListPtr keys, KeyListPtr signer_keys,
const std::string& in_path,
const std::string& out_path,
GpgEncrResult& encr_res,
GpgSignResult& sign_res,
int _channel = GPGFRONTEND_DEFAULT_CHANNEL);
static auto EncryptSignFile(KeyListPtr keys, KeyListPtr signer_keys,
const std::string& in_path,
const std::string& out_path,
GpgEncrResult& encr_res, GpgSignResult& sign_res,
int channel = GPGFRONTEND_DEFAULT_CHANNEL)
-> GpgError;
/**
* @brief
@ -141,10 +137,10 @@ class GPGFRONTEND_CORE_EXPORT GpgFileOpera
* @param verify_res
* @return GpgError
*/
static GpgError DecryptVerifyFile(const std::string& in_path,
const std::string& out_path,
GpgDecrResult& decr_res,
GpgVerifyResult& verify_res);
static auto DecryptVerifyFile(const std::string& in_path,
const std::string& out_path,
GpgDecrResult& decr_res,
GpgVerifyResult& verify_res) -> GpgError;
};
} // namespace GpgFrontend

View File

@ -32,136 +32,199 @@
#include <mutex>
#include <shared_mutex>
#include <utility>
#include "GpgConstants.h"
#include "model/GpgKey.h"
#include "core/GpgConstants.h"
#include "core/GpgContext.h"
GpgFrontend::GpgKeyGetter::GpgKeyGetter(int channel)
: SingletonFunctionObject<GpgKeyGetter>(channel) {
namespace GpgFrontend {
class GpgKeyGetter::Impl : public SingletonFunctionObject<GpgKeyGetter::Impl> {
public:
explicit Impl(int channel)
: SingletonFunctionObject<GpgKeyGetter::Impl>(channel) {
SPDLOG_DEBUG("called channel: {}", channel);
}
auto GetKey(const std::string& fpr, bool use_cache) -> GpgKey {
// find in cache first
if (use_cache) {
auto key = get_key_in_cache(fpr);
if (key.IsGood()) return key;
}
gpgme_key_t p_key = nullptr;
gpgme_get_key(ctx_, fpr.c_str(), &p_key, 1);
if (p_key == nullptr) {
SPDLOG_WARN("GpgKeyGetter GetKey Private _p_key Null fpr", fpr);
return GetPubkey(fpr, true);
}
return GpgKey(std::move(p_key));
}
auto GetPubkey(const std::string& fpr, bool use_cache) -> GpgKey {
// find in cache first
if (use_cache) {
auto key = get_key_in_cache(fpr);
if (key.IsGood()) return key;
}
gpgme_key_t p_key = nullptr;
gpgme_get_key(ctx_, fpr.c_str(), &p_key, 0);
if (p_key == nullptr) SPDLOG_WARN("GpgKeyGetter GetKey _p_key Null", fpr);
return GpgKey(std::move(p_key));
}
auto FetchKey() -> KeyLinkListPtr {
// get the lock
std::lock_guard<std::mutex> lock(keys_cache_mutex_);
auto keys_list = std::make_unique<GpgKeyLinkList>();
for (const auto& [key, value] : keys_cache_) {
keys_list->push_back(value.Copy());
}
return keys_list;
}
void FlushKeyCache() {
SPDLOG_DEBUG("called channel id: {}", GetChannel());
// clear the keys cache
keys_cache_.clear();
// init
GpgError err = gpgme_op_keylist_start(ctx_, nullptr, 0);
// for debug
assert(check_gpg_error_2_err_code(err) == GPG_ERR_NO_ERROR);
// return when error
if (check_gpg_error_2_err_code(err) != GPG_ERR_NO_ERROR) return;
{
// get the lock
std::lock_guard<std::mutex> lock(keys_cache_mutex_);
gpgme_key_t key;
while ((err = gpgme_op_keylist_next(ctx_, &key)) == GPG_ERR_NO_ERROR) {
auto gpg_key = GpgKey(std::move(key));
// detect if the key is in a smartcard
// if so, try to get full information using gpgme_get_key()
// this maybe a bug in gpgme
if (gpg_key.IsHasCardKey()) {
gpg_key = GetKey(gpg_key.GetId(), false);
}
keys_cache_.insert({gpg_key.GetId(), std::move(gpg_key)});
}
}
SPDLOG_DEBUG("cache address: {} object address: {}",
static_cast<void*>(&keys_cache_), static_cast<void*>(this));
// for debug
assert(check_gpg_error_2_err_code(err, GPG_ERR_EOF) == GPG_ERR_EOF);
err = gpgme_op_keylist_end(ctx_);
assert(check_gpg_error_2_err_code(err, GPG_ERR_EOF) == GPG_ERR_NO_ERROR);
}
auto GetKeys(const KeyIdArgsListPtr& ids) -> KeyListPtr {
auto keys = std::make_unique<KeyArgsList>();
for (const auto& key_id : *ids) keys->emplace_back(GetKey(key_id, true));
return keys;
}
auto GetKeysCopy(const KeyLinkListPtr& keys) -> KeyLinkListPtr {
// get the lock
std::lock_guard<std::mutex> lock(ctx_mutex_);
auto keys_copy = std::make_unique<GpgKeyLinkList>();
for (const auto& key : *keys) keys_copy->emplace_back(key.Copy());
return keys_copy;
}
auto GetKeysCopy(const KeyListPtr& keys) -> KeyListPtr {
// get the lock
std::lock_guard<std::mutex> lock(ctx_mutex_);
auto keys_copy = std::make_unique<KeyArgsList>();
for (const auto& key : *keys) keys_copy->emplace_back(key.Copy());
return keys_copy;
}
private:
/**
* @brief Get the gpgme context object
*
*/
GpgContext& ctx_ =
GpgContext::GetInstance(SingletonFunctionObject::GetChannel());
/**
* @brief shared mutex for the keys cache
*
*/
mutable std::mutex ctx_mutex_;
/**
* @brief cache the keys with key id
*
*/
std::map<std::string, GpgKey> keys_cache_;
/**
* @brief shared mutex for the keys cache
*
*/
mutable std::mutex keys_cache_mutex_;
/**
* @brief Get the Key object
*
* @param id
* @return GpgKey
*/
auto get_key_in_cache(const std::string& key_id) -> GpgKey {
std::lock_guard<std::mutex> lock(keys_cache_mutex_);
if (keys_cache_.find(key_id) != keys_cache_.end()) {
std::lock_guard<std::mutex> lock(ctx_mutex_);
// return a copy of the key in cache
return keys_cache_[key_id].Copy();
}
// return a bad key
return {};
}
};
GpgKeyGetter::GpgKeyGetter(int channel)
: SingletonFunctionObject<GpgKeyGetter>(channel),
p_(std::make_unique<Impl>(channel)) {
SPDLOG_DEBUG("called channel: {}", channel);
}
GpgFrontend::GpgKey GpgFrontend::GpgKeyGetter::GetKey(const std::string& fpr,
bool use_cache) {
// find in cache first
if (use_cache) {
auto key = get_key_in_cache(fpr);
if (key.IsGood()) return key;
}
gpgme_key_t _p_key = nullptr;
gpgme_get_key(ctx_, fpr.c_str(), &_p_key, 1);
if (_p_key == nullptr) {
SPDLOG_WARN("GpgKeyGetter GetKey Private _p_key Null fpr", fpr);
return GetPubkey(fpr);
} else {
return GpgKey(std::move(_p_key));
}
auto GpgKeyGetter::GetKey(const std::string& key_id, bool use_cache) -> GpgKey {
return p_->GetKey(key_id, use_cache);
}
GpgFrontend::GpgKey GpgFrontend::GpgKeyGetter::GetPubkey(const std::string& fpr,
bool use_cache) {
// find in cache first
if (use_cache) {
auto key = get_key_in_cache(fpr);
if (key.IsGood()) return key;
}
gpgme_key_t _p_key = nullptr;
gpgme_get_key(ctx_, fpr.c_str(), &_p_key, 0);
if (_p_key == nullptr) SPDLOG_WARN("GpgKeyGetter GetKey _p_key Null", fpr);
return GpgKey(std::move(_p_key));
auto GpgKeyGetter::GetPubkey(const std::string& key_id, bool use_cache)
-> GpgKey {
return p_->GetPubkey(key_id, use_cache);
}
GpgFrontend::KeyLinkListPtr GpgFrontend::GpgKeyGetter::FetchKey() {
// get the lock
std::lock_guard<std::mutex> lock(keys_cache_mutex_);
void GpgKeyGetter::FlushKeyCache() { p_->FlushKeyCache(); }
auto keys_list = std::make_unique<GpgKeyLinkList>();
for (const auto& [key, value] : keys_cache_) {
keys_list->push_back(value.Copy());
}
return keys_list;
auto GpgKeyGetter::GetKeys(const KeyIdArgsListPtr& ids) -> KeyListPtr {
return p_->GetKeys(ids);
}
void GpgFrontend::GpgKeyGetter::FlushKeyCache() {
SPDLOG_DEBUG("called channel id: {}", GetChannel());
// clear the keys cache
keys_cache_.clear();
// init
GpgError err = gpgme_op_keylist_start(ctx_, nullptr, 0);
// for debug
assert(check_gpg_error_2_err_code(err) == GPG_ERR_NO_ERROR);
// return when error
if (check_gpg_error_2_err_code(err) != GPG_ERR_NO_ERROR) return;
{
// get the lock
std::lock_guard<std::mutex> lock(keys_cache_mutex_);
gpgme_key_t key;
while ((err = gpgme_op_keylist_next(ctx_, &key)) == GPG_ERR_NO_ERROR) {
auto gpg_key = GpgKey(std::move(key));
// detect if the key is in a smartcard
// if so, try to get full information using gpgme_get_key()
// this maybe a bug in gpgme
if (gpg_key.IsHasCardKey()) {
gpg_key = GetKey(gpg_key.GetId(), false);
}
keys_cache_.insert({gpg_key.GetId(), std::move(gpg_key)});
}
}
SPDLOG_DEBUG("cache address: {} object address: {}",
static_cast<void*>(&keys_cache_), static_cast<void*>(this));
// for debug
assert(check_gpg_error_2_err_code(err, GPG_ERR_EOF) == GPG_ERR_EOF);
err = gpgme_op_keylist_end(ctx_);
assert(check_gpg_error_2_err_code(err, GPG_ERR_EOF) == GPG_ERR_NO_ERROR);
auto GpgKeyGetter::GetKeysCopy(const KeyLinkListPtr& keys) -> KeyLinkListPtr {
return p_->GetKeysCopy(keys);
}
GpgFrontend::KeyListPtr GpgFrontend::GpgKeyGetter::GetKeys(
const KeyIdArgsListPtr& ids) {
auto keys = std::make_unique<KeyArgsList>();
for (const auto& id : *ids) keys->emplace_back(GetKey(id));
return keys;
auto GpgKeyGetter::GetKeysCopy(const KeyListPtr& keys) -> KeyListPtr {
return p_->GetKeysCopy(keys);
}
GpgFrontend::KeyLinkListPtr GpgFrontend::GpgKeyGetter::GetKeysCopy(
const GpgFrontend::KeyLinkListPtr& keys) {
// get the lock
std::lock_guard<std::mutex> lock(ctx_mutex_);
auto keys_copy = std::make_unique<GpgKeyLinkList>();
for (const auto& key : *keys) keys_copy->emplace_back(key.Copy());
return keys_copy;
}
auto GpgKeyGetter::FetchKey() -> KeyLinkListPtr { return p_->FetchKey(); }
GpgFrontend::KeyListPtr GpgFrontend::GpgKeyGetter::GetKeysCopy(
const GpgFrontend::KeyListPtr& keys) {
// get the lock
std::lock_guard<std::mutex> lock(ctx_mutex_);
auto keys_copy = std::make_unique<KeyArgsList>();
for (const auto& key : *keys) keys_copy->emplace_back(key.Copy());
return keys_copy;
}
GpgFrontend::GpgKey GpgFrontend::GpgKeyGetter::get_key_in_cache(
const std::string& id) {
std::lock_guard<std::mutex> lock(keys_cache_mutex_);
if (keys_cache_.find(id) != keys_cache_.end()) {
std::lock_guard<std::mutex> lock(ctx_mutex_);
// return a copy of the key in cache
return keys_cache_[id].Copy();
}
// return a bad key
return GpgKey();
}
} // namespace GpgFrontend

View File

@ -28,10 +28,6 @@
#pragma once
#include <mutex>
#include <vector>
#include "core/GpgContext.h"
#include "core/GpgFunctionObject.h"
#include "core/GpgModel.h"
@ -49,8 +45,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter
*
* @param channel
*/
explicit GpgKeyGetter(
int channel = SingletonFunctionObject::GetDefaultChannel());
explicit GpgKeyGetter(int channel = kGpgFrontendDefaultChannel);
/**
* @brief Get the Key object
@ -58,7 +53,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter
* @param fpr
* @return GpgKey
*/
GpgKey GetKey(const std::string& id, bool use_cache = true);
auto GetKey(const std::string& key_id, bool use_cache = true) -> GpgKey;
/**
* @brief Get the Keys object
@ -66,7 +61,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter
* @param ids
* @return KeyListPtr
*/
KeyListPtr GetKeys(const KeyIdArgsListPtr& ids);
auto GetKeys(const KeyIdArgsListPtr& key_ids) -> KeyListPtr;
/**
* @brief Get the Pubkey object
@ -74,14 +69,14 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter
* @param fpr
* @return GpgKey
*/
GpgKey GetPubkey(const std::string& id, bool use_cache = true);
auto GetPubkey(const std::string& key_id, bool use_cache = true) -> GpgKey;
/**
* @brief Get all the keys by receiving a linked list
*
* @return KeyLinkListPtr
*/
KeyLinkListPtr FetchKey();
auto FetchKey() -> KeyLinkListPtr;
/**
* @brief flush the keys in the cache
@ -95,7 +90,7 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter
* @param keys
* @return KeyListPtr
*/
KeyListPtr GetKeysCopy(const KeyListPtr& keys);
auto GetKeysCopy(const KeyListPtr& keys) -> KeyListPtr;
/**
* @brief Get the Keys Copy object
@ -103,40 +98,10 @@ class GPGFRONTEND_CORE_EXPORT GpgKeyGetter
* @param keys
* @return KeyLinkListPtr
*/
KeyLinkListPtr GetKeysCopy(const KeyLinkListPtr& keys);
auto GetKeysCopy(const KeyLinkListPtr& keys) -> KeyLinkListPtr;
private:
/**
* @brief Get the gpgme context object
*
*/
GpgContext& ctx_ =
GpgContext::GetInstance(SingletonFunctionObject::GetChannel());
/**
* @brief shared mutex for the keys cache
*
*/
mutable std::mutex ctx_mutex_;
/**
* @brief cache the keys with key id
*
*/
std::map<std::string, GpgKey> keys_cache_;
/**
* @brief shared mutex for the keys cache
*
*/
mutable std::mutex keys_cache_mutex_;
/**
* @brief Get the Key object
*
* @param id
* @return GpgKey
*/
GpgKey get_key_in_cache(const std::string& id);
class Impl;
std::unique_ptr<Impl> p_;
};
} // namespace GpgFrontend

View File

@ -28,8 +28,6 @@
#include "GpgKeyImportExporter.h"
#include <memory>
#include "GpgConstants.h"
#include "GpgKeyGetter.h"

View File

@ -28,8 +28,6 @@
#pragma once
#include <string>
#include "core/GpgConstants.h"
#include "core/GpgContext.h"
#include "core/GpgFunctionObject.h"

View File

@ -30,8 +30,6 @@
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/conversion.hpp>
#include <memory>
#include <string>
#include "GpgBasicOperator.h"
#include "GpgKeyGetter.h"

View File

@ -29,7 +29,6 @@
#pragma once
#include <functional>
#include <string>
#include "core/GpgContext.h"
#include "core/GpgFunctionObject.h"

View File

@ -107,7 +107,7 @@ void GpgKeyOpera::GenerateRevokeCert(const GpgKey& key,
const auto app_path = Module::RetrieveRTValueTypedOrDefault<>(
"core", "gpgme.ctx.app_path", std::string{});
// get all components
GpgCommandExecutor::GetInstance().ExecuteSync(
GpgCommandExecutor::ExecuteSync(
{app_path,
{"--command-fd", "0", "--status-fd", "1", "--no-tty", "-o",
output_file_path, "--gen-revoke", key.GetFingerprint().c_str()},

View File

@ -28,7 +28,6 @@
#pragma once
#include <sstream>
#include <string>
#include "core/GpgConstants.h"
namespace GpgFrontend {

View File

@ -28,12 +28,9 @@
#include "DataObject.h"
#include <memory>
#include <stack>
#include "function/DataObjectOperator.h"
namespace GpgFrontend::Thread {
namespace GpgFrontend {
class DataObject::Impl {
public:
@ -63,7 +60,7 @@ DataObject::DataObject(std::initializer_list<std::any> i)
DataObject::~DataObject() = default;
DataObject::DataObject(GpgFrontend::Thread::DataObject&&) noexcept = default;
DataObject::DataObject(DataObject&&) noexcept = default;
std::any DataObject::operator[](size_t index) const {
return p_->GetParameter(index);
@ -83,4 +80,4 @@ void DataObject::Swap(DataObject&& other) noexcept { p_ = std::move(other.p_); }
void swap(DataObject& a, DataObject& b) noexcept { a.Swap(b); }
} // namespace GpgFrontend::Thread
} // namespace GpgFrontend

View File

@ -32,7 +32,7 @@
#include "core/GpgFrontendCoreExport.h"
namespace GpgFrontend::Thread {
namespace GpgFrontend {
class DataObject;
using DataObjectPtr = std::shared_ptr<DataObject>; ///<
@ -45,7 +45,7 @@ class GPGFRONTEND_CORE_EXPORT DataObject {
~DataObject();
DataObject(GpgFrontend::Thread::DataObject&&) noexcept;
DataObject(DataObject&&) noexcept;
std::any operator[](size_t index) const;
@ -90,4 +90,4 @@ T ExtractParams(const std::shared_ptr<DataObject>& d_o, int index) {
void swap(DataObject& a, DataObject& b) noexcept;
} // namespace GpgFrontend::Thread
} // namespace GpgFrontend

View File

@ -29,7 +29,6 @@
#pragma once
#include <boost/date_time.hpp>
#include <string>
#include "core/GpgConstants.h"

View File

@ -29,7 +29,6 @@
#pragma once
#include <boost/date_time.hpp>
#include <string>
#include "core/GpgConstants.h"

View File

@ -28,70 +28,75 @@
#include "Event.h"
#include <memory>
#include <utility>
namespace GpgFrontend::Module {
class Event::Impl {
public:
Impl(const std::string& event_dientifier,
std::initializer_list<ParameterInitializer> params_init_list = {})
: event_identifier_(event_dientifier) {
for (const auto& param : params_init_list) {
Impl(std::string event_id, std::initializer_list<ParameterInitializer> params,
EventCallback callback)
: event_identifier_(std::move(event_id)), callback_(std::move(callback)) {
for (const auto& param : params) {
AddParameter(param);
}
}
std::optional<ParameterValue> operator[](const std::string& key) const {
auto it = data_.find(key);
if (it != data_.end()) {
return it->second;
auto operator[](const std::string& key) const
-> std::optional<ParameterValue> {
auto it_data = data_.find(key);
if (it_data != data_.end()) {
return it_data->second;
}
return std::nullopt;
}
bool operator==(const Event& other) const {
auto operator==(const Event& other) const -> bool {
return event_identifier_ == other.p_->event_identifier_;
}
bool operator!=(const Event& other) const { return !(*this == other); }
auto operator!=(const Event& other) const -> bool {
return !(*this == other);
}
bool operator<(const Event& other) const {
auto operator<(const Event& other) const -> bool {
return this->event_identifier_ < other.p_->event_identifier_;
}
operator std::string() const { return event_identifier_; }
explicit operator std::string() const { return event_identifier_; }
EventIdentifier GetIdentifier() { return event_identifier_; }
auto GetIdentifier() -> EventIdentifier { return event_identifier_; }
void AddParameter(const std::string& key, const ParameterValue& value) {
data_[key] = value;
}
void AddParameter(ParameterInitializer param) {
void AddParameter(const ParameterInitializer& param) {
AddParameter(param.key, param.value);
}
private:
EventIdentifier event_identifier_;
std::map<std::string, ParameterValue> data_;
EventCallback callback_;
};
Event::Event(const std::string& event_dientifier,
std::initializer_list<ParameterInitializer> params_init_list)
: p_(std::make_unique<Impl>(event_dientifier, params_init_list)) {}
Event::Event(const std::string& event_id,
std::initializer_list<ParameterInitializer> params,
EventCallback callback)
: p_(std::make_unique<Impl>(event_id, params, std::move(callback))) {}
Event::~Event() = default;
bool Event::Event::operator==(const Event& other) const {
auto Event::Event::operator==(const Event& other) const -> bool {
return this->p_ == other.p_;
}
bool Event::Event::operator!=(const Event& other) const {
auto Event::Event::operator!=(const Event& other) const -> bool {
return this->p_ != other.p_;
}
bool Event::Event::operator<(const Event& other) const {
auto Event::Event::operator<(const Event& other) const -> bool {
return this->p_ < other.p_;
}
@ -99,7 +104,9 @@ Event::Event::operator std::string() const {
return static_cast<std::string>(*p_);
}
EventIdentifier Event::Event::GetIdentifier() { return p_->GetIdentifier(); }
auto Event::Event::GetIdentifier() -> EventIdentifier {
return p_->GetIdentifier();
}
void Event::AddParameter(const std::string& key, const ParameterValue& value) {
p_->AddParameter(key, value);

View File

@ -29,9 +29,11 @@
#pragma once
#include <any>
#include <functional>
#include <optional>
#include "core/GpgFrontendCore.h"
#include "core/model/DataObject.h"
namespace GpgFrontend::Module {
@ -45,29 +47,34 @@ class GPGFRONTEND_CORE_EXPORT Event {
public:
using ParameterValue = std::any;
using EventIdentifier = std::string;
using ListenerIdentifier = std::string;
using EventCallback =
std::function<void(EventIdentifier, ListenerIdentifier, DataObject)>;
struct ParameterInitializer {
std::string key;
ParameterValue value;
};
Event(const std::string& event_dientifier,
std::initializer_list<ParameterInitializer> params_init_list = {});
explicit Event(const std::string&,
std::initializer_list<ParameterInitializer> = {},
EventCallback = nullptr);
~Event();
std::optional<ParameterValue> operator[](const std::string& key) const;
auto operator[](const std::string& key) const
-> std::optional<ParameterValue>;
bool operator==(const Event& other) const;
auto operator==(const Event& other) const -> bool;
bool operator!=(const Event& other) const;
auto operator!=(const Event& other) const -> bool;
bool operator<(const Event& other) const;
auto operator<(const Event& other) const -> bool;
bool operator<=(const Event& other) const;
auto operator<=(const Event& other) const -> bool;
operator std::string() const;
explicit operator std::string() const;
EventIdentifier GetIdentifier();
auto GetIdentifier() -> EventIdentifier;
void AddParameter(const std::string& key, const ParameterValue& value);
@ -77,7 +84,8 @@ class GPGFRONTEND_CORE_EXPORT Event {
};
template <typename... Args>
EventRefrernce MakeEvent(const EventIdentifier& event_id, Args&&... args) {
auto MakeEvent(const EventIdentifier& event_id, Args&&... args)
-> EventRefrernce {
std::initializer_list<Event::ParameterInitializer> params = {
Event::ParameterInitializer{std::forward<Args>(args)}...};
return std::make_shared<Event>(event_id, params);

View File

@ -34,28 +34,29 @@
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include "core/module/Event.h"
#include "core/module/Module.h"
#include "core/thread/Task.h"
#include "thread/DataObject.h"
#include "model/DataObject.h"
namespace GpgFrontend::Module {
class GlobalModuleContext::Impl {
public:
Impl(TaskRunnerPtr task_runner)
explicit Impl(TaskRunnerPtr task_runner)
: random_gen_(
(boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
.total_milliseconds()),
default_task_runner_(task_runner) {
default_task_runner_(std::move(task_runner)) {
// Initialize acquired channels with default values.
acquired_channel_.insert(GPGFRONTEND_DEFAULT_CHANNEL);
acquired_channel_.insert(GPGFRONTEND_NON_ASCII_CHANNEL);
}
int GetChannel(ModuleRawPtr module) {
auto GetChannel(ModuleRawPtr module) -> int {
// Search for the module in the register table.
auto module_info_opt =
search_module_register_table(module->GetModuleIdentifier());
@ -72,9 +73,11 @@ class GlobalModuleContext::Impl {
return module_info->channel;
}
int GetDefaultChannel(ModuleRawPtr) { return GPGFRONTEND_DEFAULT_CHANNEL; }
static auto GetDefaultChannel(ModuleRawPtr) -> int {
return GPGFRONTEND_DEFAULT_CHANNEL;
}
std::optional<TaskRunnerPtr> GetTaskRunner(ModuleRawPtr module) {
auto GetTaskRunner(ModuleRawPtr module) -> std::optional<TaskRunnerPtr> {
auto opt = search_module_register_table(module->GetModuleIdentifier());
if (!opt.has_value()) {
return std::nullopt;
@ -82,7 +85,8 @@ class GlobalModuleContext::Impl {
return opt.value()->task_runner;
}
std::optional<TaskRunnerPtr> GetTaskRunner(ModuleIdentifier module_id) {
auto GetTaskRunner(ModuleIdentifier module_id)
-> std::optional<TaskRunnerPtr> {
// Search for the module in the register table.
auto module_info_opt = search_module_register_table(module_id);
if (!module_info_opt.has_value()) {
@ -92,11 +96,11 @@ class GlobalModuleContext::Impl {
return module_info_opt.value()->task_runner;
}
std::optional<TaskRunnerPtr> GetGlobalTaskRunner() {
auto GetGlobalTaskRunner() -> std::optional<TaskRunnerPtr> {
return default_task_runner_;
}
bool RegisterModule(ModulePtr module) {
auto RegisterModule(const ModulePtr& module) -> bool {
SPDLOG_DEBUG("attempting to register module: {}",
module->GetModuleIdentifier());
// Check if the module is null or already registered.
@ -131,7 +135,7 @@ class GlobalModuleContext::Impl {
return true;
}
bool ActiveModule(ModuleIdentifier module_id) {
auto ActiveModule(ModuleIdentifier module_id) -> bool {
SPDLOG_DEBUG("attempting to activate module: {}", module_id);
// Search for the module in the register table.
@ -151,28 +155,27 @@ class GlobalModuleContext::Impl {
return module_info->activate;
}
bool ListenEvent(ModuleIdentifier module_id, EventIdentifier event) {
auto ListenEvent(ModuleIdentifier module_id, EventIdentifier event) -> bool {
SPDLOG_DEBUG("module: {} is attempting to listen to event {}", module_id,
event);
// Check if the event exists, if not, create it.
auto it = module_events_table_.find(event);
if (it == module_events_table_.end()) {
auto met_it = module_events_table_.find(event);
if (met_it == module_events_table_.end()) {
module_events_table_[event] = std::unordered_set<ModuleIdentifier>();
it = module_events_table_.find(event);
met_it = module_events_table_.find(event);
SPDLOG_INFO("new event {} of module system created", event);
}
auto& listeners_set = it->second;
auto& listeners_set = met_it->second;
// Add the listener (module) to the event.
auto listener_it =
std::find(listeners_set.begin(), listeners_set.end(), module_id);
auto listener_it = listeners_set.find(module_id);
if (listener_it == listeners_set.end()) {
listeners_set.insert(module_id);
}
return true;
}
bool DeactivateModule(ModuleIdentifier module_id) {
auto DeactivateModule(ModuleIdentifier module_id) -> bool {
// Search for the module in the register table.
auto module_info_opt = search_module_register_table(module_id);
if (!module_info_opt.has_value()) {
@ -189,13 +192,13 @@ class GlobalModuleContext::Impl {
return !module_info->activate;
}
bool TriggerEvent(EventRefrernce event) {
auto TriggerEvent(const EventRefrernce& event) -> bool {
auto event_id = event->GetIdentifier();
SPDLOG_DEBUG("attempting to trigger event: {}", event_id);
// Find the set of listeners associated with the given event in the table
auto it = module_events_table_.find(event_id);
if (it == module_events_table_.end()) {
auto met_it = module_events_table_.find(event_id);
if (met_it == module_events_table_.end()) {
// Log a warning if the event is not registered and nobody is listening
SPDLOG_WARN(
"event {} is not listening by anyone and not registered as well",
@ -204,7 +207,7 @@ class GlobalModuleContext::Impl {
}
// Retrieve the set of listeners for this event
auto& listeners_set = it->second;
auto& listeners_set = met_it->second;
// Check if the set of listeners is empty
if (listeners_set.empty()) {
@ -219,7 +222,7 @@ class GlobalModuleContext::Impl {
event->GetIdentifier(), listeners_set.size());
// Iterate through each listener and execute the corresponding module
for (auto& listener_module_id : listeners_set) {
for (const auto& listener_module_id : listeners_set) {
// Search for the module's information in the registration table
auto module_info_opt = search_module_register_table(listener_module_id);
@ -227,6 +230,7 @@ class GlobalModuleContext::Impl {
if (!module_info_opt.has_value()) {
SPDLOG_ERROR("cannot find module id {} at register table",
listener_module_id);
continue;
}
// Retrieve the module's information
@ -243,19 +247,17 @@ class GlobalModuleContext::Impl {
if (!module_info->activate) continue;
Thread::Task::TaskRunnable exec_runnerable =
[module, event](Thread::DataObjectPtr) -> int {
return module->Exec(event);
};
[module, event](DataObjectPtr) -> int { return module->Exec(event); };
Thread::Task::TaskCallback exec_callback =
[listener_module_id, event_id](int code, Thread::DataObjectPtr) {
if (code < 0) {
// Log an error if the module execution fails
SPDLOG_ERROR(
"module {} execution failed of event {}: exec return code {}",
listener_module_id, event_id, code);
}
};
Thread::Task::TaskCallback exec_callback = [listener_module_id, event_id](
int code, DataObjectPtr) {
if (code < 0) {
// Log an error if the module execution fails
SPDLOG_ERROR(
"module {} execution failed of event {}: exec return code {}",
listener_module_id, event_id, code);
}
};
module_info->task_runner->PostTask(
new Thread::Task(exec_runnerable,
@ -269,8 +271,8 @@ class GlobalModuleContext::Impl {
return true;
}
bool IsModuleExists(ModuleIdentifier id) const {
return search_module_register_table(id).has_value();
auto IsModuleExists(const ModuleIdentifier& m_id) const -> bool {
return search_module_register_table(m_id).has_value();
}
private:
@ -292,7 +294,7 @@ class GlobalModuleContext::Impl {
boost::random::mt19937 random_gen_;
TaskRunnerPtr default_task_runner_;
int acquire_new_unique_channel() {
auto acquire_new_unique_channel() -> int {
boost::random::uniform_int_distribution<> dist(1, 65535);
int random_channel = dist(random_gen_);
@ -307,70 +309,71 @@ class GlobalModuleContext::Impl {
}
// Function to search for a module in the register table.
std::optional<ModuleRegisterInfoPtr> search_module_register_table(
ModuleIdentifier identifier) const {
auto it = module_register_table_.find(identifier);
if (it == module_register_table_.end()) {
auto search_module_register_table(const ModuleIdentifier& identifier) const
-> std::optional<ModuleRegisterInfoPtr> {
auto mrt_it = module_register_table_.find(identifier);
if (mrt_it == module_register_table_.end()) {
return std::nullopt;
}
return it->second;
return mrt_it->second;
}
};
// Constructor for GlobalModuleContext, takes a TaskRunnerPtr as an argument.
GlobalModuleContext::GlobalModuleContext(TaskRunnerPtr task_runner)
: p_(std::make_unique<Impl>(task_runner)) {}
: p_(std::make_unique<Impl>(std::move(task_runner))) {}
GlobalModuleContext::~GlobalModuleContext() = default;
// Function to get the task runner associated with a module.
std::optional<TaskRunnerPtr> GlobalModuleContext::GetTaskRunner(
ModuleRawPtr module) {
auto GlobalModuleContext::GetTaskRunner(ModuleRawPtr module)
-> std::optional<TaskRunnerPtr> {
return p_->GetTaskRunner(module);
}
// Function to get the task runner associated with a module.
std::optional<TaskRunnerPtr> GlobalModuleContext::GetTaskRunner(
ModuleIdentifier module_id) {
return p_->GetTaskRunner(module_id);
auto GlobalModuleContext::GetTaskRunner(ModuleIdentifier module_id)
-> std::optional<TaskRunnerPtr> {
return p_->GetTaskRunner(std::move(module_id));
}
// Function to get the global task runner.
std::optional<TaskRunnerPtr> GlobalModuleContext::GetGlobalTaskRunner() {
auto GlobalModuleContext::GetGlobalTaskRunner()
-> std::optional<TaskRunnerPtr> {
return p_->GetGlobalTaskRunner();
}
bool GlobalModuleContext::RegisterModule(ModulePtr module) {
return p_->RegisterModule(module);
auto GlobalModuleContext::RegisterModule(ModulePtr module) -> bool {
return p_->RegisterModule(std::move(module));
}
bool GlobalModuleContext::ActiveModule(ModuleIdentifier module_id) {
return p_->ActiveModule(module_id);
auto GlobalModuleContext::ActiveModule(ModuleIdentifier module_id) -> bool {
return p_->ActiveModule(std::move(module_id));
}
bool GlobalModuleContext::ListenEvent(ModuleIdentifier module_id,
EventIdentifier event) {
return p_->ListenEvent(module_id, event);
auto GlobalModuleContext::ListenEvent(ModuleIdentifier module_id,
EventIdentifier event) -> bool {
return p_->ListenEvent(std::move(module_id), std::move(event));
}
bool GlobalModuleContext::DeactivateModule(ModuleIdentifier module_id) {
return p_->DeactivateModule(module_id);
auto GlobalModuleContext::DeactivateModule(ModuleIdentifier module_id) -> bool {
return p_->DeactivateModule(std::move(module_id));
}
bool GlobalModuleContext::TriggerEvent(EventRefrernce event) {
return p_->TriggerEvent(event);
auto GlobalModuleContext::TriggerEvent(EventRefrernce event) -> bool {
return p_->TriggerEvent(std::move(event));
}
int GlobalModuleContext::GetChannel(ModuleRawPtr module) {
auto GlobalModuleContext::GetChannel(ModuleRawPtr module) -> int {
return p_->GetChannel(module);
}
int GlobalModuleContext::GetDefaultChannel(ModuleRawPtr _) {
return p_->GetDefaultChannel(_);
auto GlobalModuleContext::GetDefaultChannel(ModuleRawPtr channel) -> int {
return GlobalModuleContext::Impl::GetDefaultChannel(channel);
}
bool GlobalModuleContext::IsModuleExists(ModuleIdentifier id) {
return p_->IsModuleExists(id);
auto GlobalModuleContext::IsModuleExists(ModuleIdentifier m_id) -> bool {
return p_->IsModuleExists(std::move(m_id));
}
} // namespace GpgFrontend::Module

View File

@ -53,31 +53,31 @@ using TaskRunnerPtr = std::shared_ptr<Thread::TaskRunner>;
class GPGFRONTEND_CORE_EXPORT GlobalModuleContext : public QObject {
Q_OBJECT
public:
GlobalModuleContext(TaskRunnerPtr);
explicit GlobalModuleContext(TaskRunnerPtr);
~GlobalModuleContext();
~GlobalModuleContext() override;
int GetChannel(ModuleRawPtr);
auto GetChannel(ModuleRawPtr) -> int;
int GetDefaultChannel(ModuleRawPtr);
static auto GetDefaultChannel(ModuleRawPtr) -> int;
std::optional<TaskRunnerPtr> GetTaskRunner(ModuleRawPtr);
auto GetTaskRunner(ModuleRawPtr) -> std::optional<TaskRunnerPtr>;
std::optional<TaskRunnerPtr> GetTaskRunner(ModuleIdentifier);
auto GetTaskRunner(ModuleIdentifier) -> std::optional<TaskRunnerPtr>;
std::optional<TaskRunnerPtr> GetGlobalTaskRunner();
auto GetGlobalTaskRunner() -> std::optional<TaskRunnerPtr>;
bool RegisterModule(ModulePtr);
auto RegisterModule(ModulePtr) -> bool;
bool ActiveModule(ModuleIdentifier);
auto ActiveModule(ModuleIdentifier) -> bool;
bool DeactivateModule(ModuleIdentifier);
auto DeactivateModule(ModuleIdentifier) -> bool;
bool ListenEvent(ModuleIdentifier, EventIdentifier);
auto ListenEvent(ModuleIdentifier, EventIdentifier) -> bool;
bool TriggerEvent(EventRefrernce);
auto TriggerEvent(EventRefrernce) -> bool;
bool IsModuleExists(ModuleIdentifier);
auto IsModuleExists(ModuleIdentifier) -> bool;
private:
class Impl;

View File

@ -29,13 +29,10 @@
#include "GlobalRegisterTable.h"
#include <any>
#include <memory>
#include <optional>
#include <shared_mutex>
#include <unordered_map>
#include "spdlog/spdlog.h"
namespace GpgFrontend::Module {
class GlobalRegisterTable::Impl {
@ -44,7 +41,7 @@ class GlobalRegisterTable::Impl {
std::optional<std::any> value = std::nullopt;
std::unordered_map<std::string, std::unique_ptr<RTNode>> children;
int version = 0;
const std::type_info* type = nullptr; // 保存类型信息
const std::type_info* type = nullptr;
};
Impl(GlobalRegisterTable* parent)
@ -103,7 +100,7 @@ class GlobalRegisterTable::Impl {
return rtn;
}
bool ListenPublish(QObject* o, Namespace n, Key k, LPCallback c, bool c_o) {
bool ListenPublish(QObject* o, Namespace n, Key k, LPCallback c) {
if (o == nullptr) return false;
return QObject::connect(
parent_, &GlobalRegisterTable::SignalPublish, o,
@ -135,8 +132,8 @@ std::optional<std::any> GlobalRegisterTable::LookupKV(Namespace n, Key v) {
}
bool GlobalRegisterTable::ListenPublish(QObject* o, Namespace n, Key k,
LPCallback c, bool c_o) {
return p_->ListenPublish(o, n, k, c, c_o);
LPCallback c) {
return p_->ListenPublish(o, n, k, c);
}
} // namespace GpgFrontend::Module

View File

@ -49,7 +49,7 @@ class GlobalRegisterTable : public QObject {
std::optional<std::any> LookupKV(Namespace, Key);
bool ListenPublish(QObject *, Namespace, Key, LPCallback, bool);
bool ListenPublish(QObject *, Namespace, Key, LPCallback);
signals:
void SignalPublish(Namespace, Key, int, std::any);

View File

@ -29,7 +29,6 @@
#include "Module.h"
#include <boost/format.hpp>
#include <string>
#include "core/module/GlobalModuleContext.h"

View File

@ -51,7 +51,7 @@ class ModuleManager::Impl {
void RegisterModule(ModulePtr module) {
task_runner_->PostTask(new Thread::Task(
[=](GpgFrontend::Thread::DataObjectPtr) -> int {
[=](GpgFrontend::DataObjectPtr) -> int {
module->SetGPC(gmc_);
gmc_->RegisterModule(module);
return 0;
@ -61,7 +61,7 @@ class ModuleManager::Impl {
void TriggerEvent(EventRefrernce event) {
task_runner_->PostTask(new Thread::Task(
[=](GpgFrontend::Thread::DataObjectPtr) -> int {
[=](GpgFrontend::DataObjectPtr) -> int {
gmc_->TriggerEvent(event);
return 0;
},
@ -70,7 +70,7 @@ class ModuleManager::Impl {
void ActiveModule(ModuleIdentifier identifier) {
task_runner_->PostTask(new Thread::Task(
[=](GpgFrontend::Thread::DataObjectPtr) -> int {
[=](GpgFrontend::DataObjectPtr) -> int {
gmc_->ActiveModule(identifier);
return 0;
},
@ -89,8 +89,8 @@ class ModuleManager::Impl {
return grt_->LookupKV(n, k);
}
bool ListenPublish(QObject* o, Namespace n, Key k, LPCallback c, bool c_o) {
return grt_->ListenPublish(o, n, k, c, c_o);
bool ListenPublish(QObject* o, Namespace n, Key k, LPCallback c) {
return grt_->ListenPublish(o, n, k, c);
}
private:
@ -107,9 +107,8 @@ bool UpsertRTValue(const std::string& namespace_, const std::string& key,
}
bool GPGFRONTEND_CORE_EXPORT ListenRTPublishEvent(QObject* o, Namespace n,
Key k, LPCallback c,
bool c_o) {
return ModuleManager::GetInstance()->ListenRTPublish(o, n, k, c, c_o);
Key k, LPCallback c) {
return ModuleManager::GetInstance()->ListenRTPublish(o, n, k, c);
}
ModuleManager::ModuleManager() : p_(std::make_unique<Impl>()) {}
@ -147,8 +146,8 @@ std::optional<std::any> ModuleManager::RetrieveRTValue(Namespace n, Key k) {
}
bool ModuleManager::ListenRTPublish(QObject* o, Namespace n, Key k,
LPCallback c, bool c_o) {
return p_->ListenPublish(o, n, k, c, c_o);
LPCallback c) {
return p_->ListenPublish(o, n, k, c);
}
ModuleIdentifier GetRealModuleIdentifier(const ModuleIdentifier& id) {

View File

@ -76,7 +76,7 @@ class GPGFRONTEND_CORE_EXPORT ModuleManager : public QObject {
std::optional<std::any> RetrieveRTValue(Namespace, Key);
bool ListenRTPublish(QObject*, Namespace, Key, LPCallback, bool);
bool ListenRTPublish(QObject*, Namespace, Key, LPCallback);
private:
class Impl;
@ -111,8 +111,7 @@ bool GPGFRONTEND_CORE_EXPORT UpsertRTValue(const std::string& namespace_,
const std::any& value);
bool GPGFRONTEND_CORE_EXPORT ListenRTPublishEvent(QObject*, Namespace, Key,
LPCallback,
bool callback_once = true);
LPCallback);
template <typename T>
std::optional<T> RetrieveRTValueTyped(const std::string& namespace_,

View File

@ -28,16 +28,11 @@
#include "core/thread/Task.h"
#include <qobjectdefs.h>
#include <qtmetamacros.h>
#include <boost/stacktrace.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <memory>
#include "spdlog/spdlog.h"
#include <utility>
namespace GpgFrontend::Thread {
@ -56,11 +51,11 @@ class Task::Impl : public QObject {
: QObject(parent),
parent_(parent),
uuid_(generate_uuid()),
name_(name),
runnable_(runnable),
name_(std::move(name)),
runnable_(std::move(runnable)),
callback_([](int, const DataObjectPtr &) {}),
callback_thread_(QThread::currentThread()),
data_object_(data_object) {
data_object_(std::move(data_object)) {
SPDLOG_TRACE("task {} created with runnable, callback_thread_: {}",
GetFullID(), static_cast<void *>(callback_thread_));
init();
@ -71,11 +66,11 @@ class Task::Impl : public QObject {
: QObject(parent),
parent_(parent),
uuid_(generate_uuid()),
name_(name),
runnable_(runnable),
callback_(callback),
name_(std::move(name)),
runnable_(std::move(runnable)),
callback_(std::move(callback)),
callback_thread_(QThread::currentThread()),
data_object_(data_object) {
data_object_(std::move(data_object)) {
SPDLOG_TRACE(
"task {} created with runnable and callback, callback_thread_: {}",
GetFullID(), static_cast<void *>(callback_thread_));

View File

@ -29,15 +29,12 @@
#pragma once
#include "core/GpgFrontendCore.h"
#include "core/thread/DataObject.h"
#include "core/model/DataObject.h"
namespace GpgFrontend::Thread {
class TaskRunner;
class DataObject;
using DataObjectPtr = std::shared_ptr<DataObject>; ///<
class GPGFRONTEND_CORE_EXPORT Task : public QObject, public QRunnable {
Q_OBJECT
public:
@ -50,7 +47,7 @@ class GPGFRONTEND_CORE_EXPORT Task : public QObject, public QRunnable {
* @brief Construct a new Task object
*
*/
Task(std::string name);
explicit Task(std::string name);
/**
* @brief Construct a new Task object
@ -68,11 +65,11 @@ class GPGFRONTEND_CORE_EXPORT Task : public QObject, public QRunnable {
explicit Task(TaskRunnable runnable, std::string name, DataObjectPtr data,
TaskCallback callback);
virtual ~Task() override;
~Task() override;
std::string GetUUID() const;
[[nodiscard]] auto GetUUID() const -> std::string;
std::string GetFullID() const;
[[nodiscard]] auto GetFullID() const -> std::string;
void HoldOnLifeCycle(bool hold_on);
@ -95,6 +92,6 @@ class GPGFRONTEND_CORE_EXPORT Task : public QObject, public QRunnable {
class Impl;
Impl* p_;
virtual void run() override;
void run() override;
};
} // namespace GpgFrontend::Thread

View File

@ -33,8 +33,6 @@
#include <qthread.h>
#include <qthreadpool.h>
#include <memory>
#include "core/thread/Task.h"
namespace GpgFrontend::Thread {

View File

@ -28,8 +28,6 @@
#pragma once
#include <vector>
#include "core/GpgFrontendCore.h"
namespace GpgFrontend::Thread {

View File

@ -28,8 +28,6 @@
#include "core/thread/TaskRunnerGetter.h"
#include <memory>
#include "thread/TaskRunner.h"
namespace GpgFrontend::Thread {

View File

@ -106,7 +106,7 @@ int GnuPGInfoGatheringModule::Exec(EventRefrernce event) {
MODULE_LOG_DEBUG("start to load extra info at module gnupginfogathering...");
// get all components
GpgCommandExecutor::GetInstance().ExecuteSync(
GpgCommandExecutor::ExecuteSync(
{gpgconf_path,
{"--list-components"},
[this, gpgme_version, gpgconf_path](
@ -411,7 +411,7 @@ int GnuPGInfoGatheringModule::Exec(EventRefrernce event) {
getTaskRunner()});
}
GpgCommandExecutor::GetInstance().ExecuteConcurrentlySync(exec_contexts);
GpgCommandExecutor::ExecuteConcurrentlySync(exec_contexts);
UpsertRTValue(GetModuleIdentifier(), "gnupg.gathering_done", true);
return 0;

View File

@ -40,9 +40,8 @@ namespace GpgFrontend::Module::Integrated::VersionCheckingModule {
VersionCheckTask::VersionCheckTask()
: Task("version_check_task"),
network_manager_(new QNetworkAccessManager(this)),
current_version_(std::string("v") + std::to_string(VERSION_MAJOR) + "." +
std::to_string(VERSION_MINOR) + "." +
std::to_string(VERSION_PATCH)) {
current_version_(std::string("v") + VERSION_MAJOR + "." + VERSION_MINOR +
"." + VERSION_PATCH) {
HoldOnLifeCycle(true);
qRegisterMetaType<SoftwareVersion>("SoftwareVersion");
version_.current_version = current_version_;

View File

@ -120,7 +120,7 @@ void process_result_analyse(TextEdit *edit, InfoBoardWidget *info_board,
void process_operation(QWidget *parent, const std::string &waiting_title,
const Thread::Task::TaskRunnable func,
const Thread::Task::TaskCallback callback,
Thread::DataObjectPtr data_object) {
DataObjectPtr data_object) {
auto *dialog =
new WaitingDialog(QString::fromStdString(waiting_title), parent);
@ -437,7 +437,7 @@ void CommonUtils::SlotImportKeyFromKeyServer(
void CommonUtils::slot_update_key_status() {
auto refresh_task = new Thread::Task(
[](Thread::DataObjectPtr) -> int {
[](DataObjectPtr) -> int {
// flush key cache for all GpgKeyGetter Intances.
for (const auto &channel_id : GpgKeyGetter::GetAllChannelId()) {
GpgKeyGetter::GetInstance(channel_id).FlushKeyCache();

View File

@ -106,7 +106,7 @@ void process_operation(
QWidget* parent, const std::string& waiting_title,
GpgFrontend::Thread::Task::TaskRunnable func,
GpgFrontend::Thread::Task::TaskCallback callback = nullptr,
Thread::DataObjectPtr data_object = nullptr);
DataObjectPtr data_object = nullptr);
/**
* @brief

View File

@ -31,7 +31,6 @@
#include "SignalStation.h"
#include "core/function/GlobalSettingStation.h"
#include "core/module/ModuleManager.h"
#include "spdlog/spdlog.h"
#include "ui/dialog/GeneralDialog.h"
#include "ui_GnuPGControllerDialog.h"

View File

@ -160,9 +160,8 @@ UpdateTab::UpdateTab(QWidget* parent) : QWidget(parent) {
pixmap_label->setPixmap(*pixmap);
layout->addWidget(pixmap_label, 0, 0, 1, -1, Qt::AlignCenter);
current_version_ = "v" + QString::number(VERSION_MAJOR) + "." +
QString::number(VERSION_MINOR) + "." +
QString::number(VERSION_PATCH);
current_version_ =
QString("v") + VERSION_MAJOR + "." + VERSION_MINOR + "." + VERSION_PATCH;
auto tips_label = new QLabel();
tips_label->setText(

View File

@ -123,8 +123,7 @@ void MainWindow::Init() noexcept {
if (GlobalSettingStation::GetInstance().LookupSettings(
"general.clear_gpg_password_cache", false)) {
if (GpgFrontend::GpgAdvancedOperator::GetInstance()
.ClearGpgPasswordCache()) {
if (GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache()) {
SPDLOG_DEBUG("clear gpg password cache done");
} else {
SPDLOG_ERROR("clear gpg password cache error");

View File

@ -92,7 +92,7 @@ bool process_tarball_into_directory(QWidget* parent,
bool if_error = false;
process_operation(parent, _("Extracting Tarball"),
[&](Thread::DataObjectPtr) -> int {
[&](DataObjectPtr) -> int {
try {
GpgFrontend::ArchiveFileOperator::ExtractArchive(
target_path, base_path);
@ -136,16 +136,15 @@ bool process_directory_into_tarball(QWidget* parent, QString& path) {
selected_dir_path.u8string());
bool if_error = false;
process_operation(parent, _("Making Tarball"),
[&](Thread::DataObjectPtr) -> int {
try {
GpgFrontend::ArchiveFileOperator::CreateArchive(
base_path, target_path, 0, {selected_dir_path});
} catch (const std::runtime_error& e) {
if_error = true;
}
return 0;
});
process_operation(parent, _("Making Tarball"), [&](DataObjectPtr) -> int {
try {
GpgFrontend::ArchiveFileOperator::CreateArchive(base_path, target_path,
0, {selected_dir_path});
} catch (const std::runtime_error& e) {
if_error = true;
}
return 0;
});
if (if_error || !exists(target_path)) {
throw std::runtime_error("Compress Failed");
@ -229,7 +228,7 @@ void MainWindow::SlotFileEncrypt() {
if (ret == QMessageBox::Cancel) return;
process_operation(
this, _("Symmetrically Encrypting"), [&](Thread::DataObjectPtr) -> int {
this, _("Symmetrically Encrypting"), [&](DataObjectPtr) -> int {
try {
error = GpgFrontend::GpgFileOpera::EncryptFileSymmetric(
path.toStdString(), out_path.toStdString(), result, _channel);
@ -255,7 +254,7 @@ void MainWindow::SlotFileEncrypt() {
}
}
process_operation(this, _("Encrypting"), [&](Thread::DataObjectPtr) -> int {
process_operation(this, _("Encrypting"), [&](DataObjectPtr) -> int {
try {
error =
GpgFileOpera::EncryptFile(std::move(p_keys), path.toStdString(),
@ -318,7 +317,7 @@ void MainWindow::SlotFileDecrypt() {
GpgDecrResult result = nullptr;
gpgme_error_t error;
bool if_error = false;
process_operation(this, _("Decrypting"), [&](Thread::DataObjectPtr) -> int {
process_operation(this, _("Decrypting"), [&](DataObjectPtr) -> int {
try {
error = GpgFileOpera::DecryptFile(path.toStdString(), out_path.u8string(),
result);
@ -422,7 +421,7 @@ void MainWindow::SlotFileSign() {
gpgme_error_t error;
bool if_error = false;
process_operation(this, _("Signing"), [&](Thread::DataObjectPtr) -> int {
process_operation(this, _("Signing"), [&](DataObjectPtr) -> int {
try {
error =
GpgFileOpera::SignFile(std::move(keys), in_path.u8string(),
@ -506,7 +505,7 @@ void MainWindow::SlotFileVerify() {
GpgVerifyResult result = nullptr;
gpgme_error_t error;
bool if_error = false;
process_operation(this, _("Verifying"), [&](Thread::DataObjectPtr) -> int {
process_operation(this, _("Verifying"), [&](DataObjectPtr) -> int {
try {
error =
GpgFileOpera::VerifyFile(data_file_path.u8string(),
@ -522,11 +521,13 @@ void MainWindow::SlotFileVerify() {
result_analyse.Analyse();
process_result_analyse(edit_, info_board_, result_analyse);
if (result_analyse.GetStatus() == -2)
if (result_analyse.GetStatus() == -2) {
import_unknown_key_from_keyserver(this, result_analyse);
}
if (result_analyse.GetStatus() >= 0)
if (result_analyse.GetStatus() >= 0) {
show_verify_details(this, info_board_, error, result);
}
fileTreeView->update();
} else {
@ -537,8 +538,8 @@ void MainWindow::SlotFileVerify() {
}
void MainWindow::SlotFileEncryptSign() {
auto fileTreeView = edit_->SlotCurPageFileTreeView();
auto path = fileTreeView->GetSelected();
auto* file_tree_view = edit_->SlotCurPageFileTreeView();
auto path = file_tree_view->GetSelected();
if (!path_pre_check(this, path)) return;
@ -578,14 +579,14 @@ void MainWindow::SlotFileEncryptSign() {
path = path + (file_info.isDir() ? ".tar" : "");
}
auto _channel = GPGFRONTEND_DEFAULT_CHANNEL;
auto _extension = ".asc";
auto channel = GPGFRONTEND_DEFAULT_CHANNEL;
const auto* extension = ".asc";
if (non_ascii_when_export || file_info.isDir()) {
_channel = GPGFRONTEND_NON_ASCII_CHANNEL;
_extension = ".gpg";
channel = GPGFRONTEND_NON_ASCII_CHANNEL;
extension = ".gpg";
}
auto out_path = path + _extension;
auto out_path = path + extension;
if (QFile::exists(out_path)) {
auto ret = QMessageBox::warning(
@ -596,15 +597,15 @@ void MainWindow::SlotFileEncryptSign() {
if (ret == QMessageBox::Cancel) return;
}
auto signersPicker = new SignersPicker(this);
auto* signers_picker = new SignersPicker(this);
QEventLoop loop;
connect(signersPicker, &SignersPicker::finished, &loop, &QEventLoop::quit);
connect(signers_picker, &SignersPicker::finished, &loop, &QEventLoop::quit);
loop.exec();
// return when canceled
if (!signersPicker->GetStatus()) return;
if (!signers_picker->GetStatus()) return;
auto signer_key_ids = signersPicker->GetCheckedSigners();
auto signer_key_ids = signers_picker->GetCheckedSigners();
auto p_signer_keys = GpgKeyGetter::GetInstance().GetKeys(signer_key_ids);
// convert directory into tarball
@ -624,11 +625,11 @@ void MainWindow::SlotFileEncryptSign() {
bool if_error = false;
process_operation(
this, _("Encrypting and Signing"), [&](Thread::DataObjectPtr) -> int {
this, _("Encrypting and Signing"), [&](DataObjectPtr) -> int {
try {
error = GpgFileOpera::EncryptSignFile(
std::move(p_keys), std::move(p_signer_keys), path.toStdString(),
out_path.toStdString(), encr_result, sign_result, _channel);
out_path.toStdString(), encr_result, sign_result, channel);
} catch (const std::runtime_error& e) {
if_error = true;
}
@ -643,7 +644,7 @@ void MainWindow::SlotFileEncryptSign() {
sign_res.Analyse();
process_result_analyse(edit_, info_board_, encrypt_result, sign_res);
fileTreeView->update();
file_tree_view->update();
} else {
QMessageBox::critical(this, _("Error"),
@ -662,8 +663,8 @@ void MainWindow::SlotFileEncryptSign() {
}
void MainWindow::SlotFileDecryptVerify() {
auto fileTreeView = edit_->SlotCurPageFileTreeView();
auto path = fileTreeView->GetSelected();
auto* file_tree_view = edit_->SlotCurPageFileTreeView();
auto path = file_tree_view->GetSelected();
if (!path_pre_check(this, path)) return;
@ -697,7 +698,7 @@ void MainWindow::SlotFileDecryptVerify() {
gpgme_error_t error;
bool if_error = false;
process_operation(
this, _("Decrypting and Verifying"), [&](Thread::DataObjectPtr) -> int {
this, _("Decrypting and Verifying"), [&](DataObjectPtr) -> int {
try {
error = GpgFileOpera::DecryptVerifyFile(
path.toStdString(), out_path.u8string(), d_result, v_result);
@ -714,13 +715,15 @@ void MainWindow::SlotFileDecryptVerify() {
verify_res.Analyse();
process_result_analyse(edit_, info_board_, decrypt_res, verify_res);
if (verify_res.GetStatus() == -2)
if (verify_res.GetStatus() == -2) {
import_unknown_key_from_keyserver(this, verify_res);
}
if (verify_res.GetStatus() >= 0)
if (verify_res.GetStatus() >= 0) {
show_verify_details(this, info_board_, error, v_result);
}
fileTreeView->update();
file_tree_view->update();
} else {
QMessageBox::critical(this, _("Error"),
_("An error occurred during operation."));
@ -729,10 +732,11 @@ void MainWindow::SlotFileDecryptVerify() {
// extract the tarball
if (out_path.extension() == ".tar" && exists(out_path)) {
bool ret = QMessageBox::information(
this, _("Decrypting"),
_("Do you want to extract and delete the decrypted tarball?"),
QMessageBox::Ok | QMessageBox::Cancel);
bool ret =
QMessageBox::information(
this, _("Decrypting"),
_("Do you want to extract and delete the decrypted tarball?"),
QMessageBox::Ok | QMessageBox::Cancel) != 0;
if (ret) {
if (process_tarball_into_directory(this, out_path)) {
QMessageBox::information(this, _("Decrypting"),

View File

@ -40,8 +40,8 @@
#include "core/function/result_analyse/GpgEncryptResultAnalyse.h"
#include "core/function/result_analyse/GpgSignResultAnalyse.h"
#include "core/function/result_analyse/GpgVerifyResultAnalyse.h"
#include "core/model/DataObject.h"
#include "core/module/ModuleManager.h"
#include "core/thread/DataObject.h"
#include "ui/UserInterfaceUtils.h"
#include "ui/dialog/SignersPicker.h"
#include "ui/dialog/help/AboutDialog.h"
@ -62,17 +62,17 @@ void MainWindow::slot_encrypt() {
auto key_ids = m_key_list_->GetChecked();
// data to transfer into task
auto data_object = Thread::TransferParams(
auto data_object = TransferParams(
edit_->CurTextPage()->GetTextPage()->toPlainText().toStdString());
// the callback function
auto result_callback = [this](int rtn, Thread::DataObjectPtr data_object) {
if (!rtn) {
auto result_callback = [this](int rtn, const DataObjectPtr& data_object) {
if (rtn == 0) {
if (!data_object->Check<GpgError, GpgEncrResult, ByteArrayPtr>())
throw std::runtime_error("data object doesn't pass checking");
auto error = Thread::ExtractParams<GpgError>(data_object, 0);
auto result = Thread::ExtractParams<GpgEncrResult>(data_object, 1);
auto tmp = Thread::ExtractParams<ByteArrayPtr>(data_object, 2);
auto error = ExtractParams<GpgError>(data_object, 0);
auto result = ExtractParams<GpgEncrResult>(data_object, 1);
auto tmp = ExtractParams<ByteArrayPtr>(data_object, 2);
auto resultAnalyse = GpgEncryptResultAnalyse(error, std::move(result));
resultAnalyse.Analyse();
@ -90,7 +90,7 @@ void MainWindow::slot_encrypt() {
Thread::Task::TaskRunnable encrypt_runner = nullptr;
std::string encrypt_type = "";
std::string encrypt_type;
if (key_ids->empty()) {
// Symmetric Encrypt
@ -103,10 +103,10 @@ void MainWindow::slot_encrypt() {
if (ret == QMessageBox::Cancel) return;
encrypt_type = _("Symmetrically Encrypting");
encrypt_runner = [](Thread::DataObjectPtr data_object) -> int {
encrypt_runner = [](const DataObjectPtr& data_object) -> int {
if (data_object == nullptr || !data_object->Check<std::string>())
throw std::runtime_error("data object doesn't pass checking");
auto buffer = Thread::ExtractParams<std::string>(data_object, 0);
auto buffer = ExtractParams<std::string>(data_object, 0);
try {
GpgEncrResult result = nullptr;
auto tmp = std::make_shared<ByteArray>();
@ -114,8 +114,7 @@ void MainWindow::slot_encrypt() {
GpgFrontend::GpgBasicOperator::GetInstance().EncryptSymmetric(
buffer, tmp, result);
data_object->Swap(Thread::DataObject{
std::move(error), std::move(result), std::move(tmp)});
data_object->Swap(DataObject{error, std::move(result), std::move(tmp)});
} catch (const std::runtime_error& e) {
return -1;
}
@ -142,14 +141,14 @@ void MainWindow::slot_encrypt() {
// Asymmetric Encrypt
encrypt_type = _("Encrypting");
encrypt_runner = [](Thread::DataObjectPtr data_object) -> int {
encrypt_runner = [](DataObjectPtr data_object) -> int {
// check the size of the data object
if (data_object == nullptr ||
!data_object->Check<std::string, KeyListPtr>())
throw std::runtime_error("data object doesn't pass checking");
auto buffer = Thread::ExtractParams<std::string>(data_object, 0);
auto keys = Thread::ExtractParams<KeyListPtr>(data_object, 1);
auto buffer = ExtractParams<std::string>(data_object, 0);
auto keys = ExtractParams<KeyListPtr>(data_object, 1);
try {
GpgEncrResult result = nullptr;
auto tmp = std::make_shared<ByteArray>();
@ -198,7 +197,7 @@ void MainWindow::slot_sign() {
}
// data to transfer into task
auto data_object = Thread::TransferParams();
auto data_object = TransferParams();
// set input buffer
auto buffer =
@ -208,13 +207,13 @@ void MainWindow::slot_sign() {
// push the keys into data object
data_object->AppendObject(std::move(keys));
auto sign_ruunner = [](Thread::DataObjectPtr data_object) -> int {
auto sign_ruunner = [](DataObjectPtr data_object) -> int {
// check the size of the data object
if (data_object == nullptr || data_object->GetObjectSize() != 2)
throw std::runtime_error("data object doesn't pass checking");
auto buffer = Thread::ExtractParams<std::string>(data_object, 0);
auto keys = Thread::ExtractParams<KeyListPtr>(data_object, 1);
auto buffer = ExtractParams<std::string>(data_object, 0);
auto keys = ExtractParams<KeyListPtr>(data_object, 1);
try {
GpgSignResult result = nullptr;
@ -229,13 +228,13 @@ void MainWindow::slot_sign() {
return 0;
};
auto result_callback = [this](int rtn, Thread::DataObjectPtr data_object) {
auto result_callback = [this](int rtn, DataObjectPtr data_object) {
if (!rtn) {
if (data_object == nullptr || data_object->GetObjectSize() != 3)
throw std::runtime_error("data object doesn't pass checking");
auto error = Thread::ExtractParams<GpgError>(data_object, 0);
auto result = Thread::ExtractParams<GpgSignResult>(data_object, 1);
auto tmp = Thread::ExtractParams<ByteArrayPtr>(data_object, 2);
auto error = ExtractParams<GpgError>(data_object, 0);
auto result = ExtractParams<GpgSignResult>(data_object, 1);
auto tmp = ExtractParams<ByteArrayPtr>(data_object, 2);
auto resultAnalyse = GpgSignResultAnalyse(error, std::move(result));
resultAnalyse.Analyse();
process_result_analyse(edit_, info_board_, resultAnalyse);
@ -269,15 +268,15 @@ void MainWindow::slot_decrypt() {
}
// data to transfer into task
auto data_object = Thread::TransferParams(
auto data_object = TransferParams(
edit_->CurTextPage()->GetTextPage()->toPlainText().toStdString());
auto decrypt_runner = [](Thread::DataObjectPtr data_object) -> int {
auto decrypt_runner = [](DataObjectPtr data_object) -> int {
// check the size of the data object
if (data_object == nullptr || data_object->GetObjectSize() != 1)
throw std::runtime_error("data object doesn't pass checking");
auto buffer = Thread::ExtractParams<std::string>(data_object, 0);
auto buffer = ExtractParams<std::string>(data_object, 0);
try {
GpgDecrResult result = nullptr;
auto decrypted = std::make_shared<ByteArray>();
@ -291,14 +290,14 @@ void MainWindow::slot_decrypt() {
return 0;
};
auto result_callback = [this](int rtn, Thread::DataObjectPtr data_object) {
auto result_callback = [this](int rtn, DataObjectPtr data_object) {
if (!rtn) {
if (data_object == nullptr ||
!data_object->Check<GpgError, GpgDecrResult, ByteArrayPtr>())
throw std::runtime_error("data object doesn't pass checking");
auto error = Thread::ExtractParams<GpgError>(data_object, 0);
auto result = Thread::ExtractParams<GpgDecrResult>(data_object, 1);
auto decrypted = Thread::ExtractParams<ByteArrayPtr>(data_object, 2);
auto error = ExtractParams<GpgError>(data_object, 0);
auto result = ExtractParams<GpgDecrResult>(data_object, 1);
auto decrypted = ExtractParams<ByteArrayPtr>(data_object, 2);
auto resultAnalyse = GpgDecryptResultAnalyse(error, std::move(result));
resultAnalyse.Analyse();
process_result_analyse(edit_, info_board_, resultAnalyse);
@ -323,19 +322,19 @@ void MainWindow::slot_verify() {
}
// data to transfer into task
auto data_object = Thread::TransferParams();
auto data_object = TransferParams();
// set input buffer
auto buffer =
edit_->CurTextPage()->GetTextPage()->toPlainText().toStdString();
data_object->AppendObject(std::move(buffer));
auto verify_runner = [](Thread::DataObjectPtr data_object) -> int {
auto verify_runner = [](DataObjectPtr data_object) -> int {
// check the size of the data object
if (data_object == nullptr || !data_object->Check<std::string>())
throw std::runtime_error("data object doesn't pass checking");
auto buffer = Thread::ExtractParams<std::string>(data_object, 0);
auto buffer = ExtractParams<std::string>(data_object, 0);
SPDLOG_DEBUG("verify buffer size: {}", buffer.size());
@ -352,14 +351,13 @@ void MainWindow::slot_verify() {
return 0;
};
auto result_callback = [this](int rtn, Thread::DataObjectPtr data_object) {
auto result_callback = [this](int rtn, DataObjectPtr data_object) {
if (!rtn) {
if (data_object == nullptr ||
!data_object->Check<GpgError, GpgVerifyResult>())
throw std::runtime_error("data object doesn't pass checking");
auto error = Thread::ExtractParams<GpgError>(data_object, 0);
auto verify_result =
Thread::ExtractParams<GpgVerifyResult>(data_object, 1);
auto error = ExtractParams<GpgError>(data_object, 0);
auto verify_result = ExtractParams<GpgVerifyResult>(data_object, 1);
auto result_analyse = GpgVerifyResultAnalyse(error, verify_result);
result_analyse.Analyse();
@ -434,19 +432,19 @@ void MainWindow::slot_encrypt_sign() {
}
// data to transfer into task
auto data_object = Thread::TransferParams(
auto data_object = TransferParams(
std::move(signer_keys), std::move(keys),
edit_->CurTextPage()->GetTextPage()->toPlainText().toStdString());
auto encrypt_sign_runner = [](Thread::DataObjectPtr data_object) -> int {
auto encrypt_sign_runner = [](DataObjectPtr data_object) -> int {
// check the size of the data object
if (data_object == nullptr ||
!data_object->Check<KeyListPtr, KeyListPtr, std::string>())
throw std::runtime_error("data object doesn't pass checking");
auto signer_keys = Thread::ExtractParams<KeyListPtr>(data_object, 0);
auto keys = Thread::ExtractParams<KeyListPtr>(data_object, 1);
auto buffer = Thread::ExtractParams<std::string>(data_object, 2);
auto signer_keys = ExtractParams<KeyListPtr>(data_object, 0);
auto keys = ExtractParams<KeyListPtr>(data_object, 1);
auto buffer = ExtractParams<std::string>(data_object, 2);
try {
GpgEncrResult encr_result = nullptr;
GpgSignResult sign_result = nullptr;
@ -463,17 +461,16 @@ void MainWindow::slot_encrypt_sign() {
return 0;
};
auto result_callback = [this](int rtn, Thread::DataObjectPtr data_object) {
auto result_callback = [this](int rtn, DataObjectPtr data_object) {
if (!rtn) {
if (data_object == nullptr ||
!data_object
->Check<GpgError, GpgEncrResult, GpgSignResult, ByteArrayPtr>())
throw std::runtime_error("data object doesn't pass checking");
auto error = Thread::ExtractParams<GpgError>(data_object, 0);
auto encrypt_result =
Thread::ExtractParams<GpgEncrResult>(data_object, 1);
auto sign_result = Thread::ExtractParams<GpgSignResult>(data_object, 2);
auto tmp = Thread::ExtractParams<ByteArrayPtr>(data_object, 3);
auto error = ExtractParams<GpgError>(data_object, 0);
auto encrypt_result = ExtractParams<GpgEncrResult>(data_object, 1);
auto sign_result = ExtractParams<GpgSignResult>(data_object, 2);
auto tmp = ExtractParams<ByteArrayPtr>(data_object, 3);
auto encrypt_result_analyse =
GpgEncryptResultAnalyse(error, std::move(encrypt_result));
@ -506,15 +503,15 @@ void MainWindow::slot_decrypt_verify() {
}
// data to transfer into task
auto data_object = Thread::TransferParams(
auto data_object = TransferParams(
edit_->CurTextPage()->GetTextPage()->toPlainText().toStdString());
auto decrypt_verify_runner = [](Thread::DataObjectPtr data_object) -> int {
auto decrypt_verify_runner = [](DataObjectPtr data_object) -> int {
// check the size of the data object
if (data_object == nullptr || !data_object->Check<std::string>())
throw std::runtime_error("data object doesn't pass checking");
auto buffer = Thread::ExtractParams<std::string>(data_object, 0);
auto buffer = ExtractParams<std::string>(data_object, 0);
try {
GpgDecrResult decrypt_result = nullptr;
GpgVerifyResult verify_result = nullptr;
@ -531,19 +528,17 @@ void MainWindow::slot_decrypt_verify() {
return 0;
};
auto result_callback = [this](int rtn, Thread::DataObjectPtr data_object) {
auto result_callback = [this](int rtn, DataObjectPtr data_object) {
if (!rtn) {
if (data_object == nullptr ||
!data_object->Check<GpgError, GpgDecrResult, GpgVerifyResult,
ByteArrayPtr>())
throw std::runtime_error("data object doesn't pass checking");
auto error = Thread::ExtractParams<GpgError>(data_object, 0);
auto decrypt_result =
Thread::ExtractParams<GpgDecrResult>(data_object, 1);
auto verify_result =
Thread::ExtractParams<GpgVerifyResult>(data_object, 2);
auto decrypted = Thread::ExtractParams<ByteArrayPtr>(data_object, 3);
auto error = ExtractParams<GpgError>(data_object, 0);
auto decrypt_result = ExtractParams<GpgDecrResult>(data_object, 1);
auto verify_result = ExtractParams<GpgVerifyResult>(data_object, 2);
auto decrypted = ExtractParams<ByteArrayPtr>(data_object, 3);
auto decrypt_result_analyse =
GpgDecryptResultAnalyse(error, std::move(decrypt_result));

View File

@ -287,8 +287,7 @@ void MainWindow::create_actions() {
clean_gpg_password_cache_act_->setIcon(QIcon(":configure.png"));
clean_gpg_password_cache_act_->setToolTip(_("Clear Password Cache of GnuPG"));
connect(clean_gpg_password_cache_act_, &QAction::triggered, this, [=]() {
if (GpgFrontend::GpgAdvancedOperator::GetInstance()
.ClearGpgPasswordCache()) {
if (GpgFrontend::GpgAdvancedOperator::ClearGpgPasswordCache()) {
QMessageBox::information(this, _("Successful Operation"),
_("Clear password cache successfully"));
} else {
@ -301,7 +300,7 @@ void MainWindow::create_actions() {
reload_components_act_->setIcon(QIcon(":configure.png"));
reload_components_act_->setToolTip(_("Reload All GnuPG's Components"));
connect(reload_components_act_, &QAction::triggered, this, [=]() {
if (GpgFrontend::GpgAdvancedOperator::GetInstance().ReloadGpgComponents()) {
if (GpgFrontend::GpgAdvancedOperator::ReloadGpgComponents()) {
QMessageBox::information(
this, _("Successful Operation"),
_("Reload all the GnuPG's components successfully"));
@ -316,7 +315,7 @@ void MainWindow::create_actions() {
restart_components_act_->setIcon(QIcon(":configure.png"));
restart_components_act_->setToolTip(_("Restart All GnuPG's Components"));
connect(restart_components_act_, &QAction::triggered, this, [=]() {
GpgFrontend::GpgAdvancedOperator::GetInstance().RestartGpgComponents();
GpgFrontend::GpgAdvancedOperator::RestartGpgComponents();
Module::ListenRTPublishEvent(
this, "core", "gpg_advanced_operator.restart_gpg_components",
[=](Module::Namespace, Module::Key, int, std::any value) {