From 2feba4447a482840e21fa2d3b33f1a5da12d09b7 Mon Sep 17 00:00:00 2001 From: Fabien Proriol Date: Thu, 22 May 2025 17:10:35 +0200 Subject: qt: Add Qt Wrapper library and QML module --- .gitignore | 3 + CMakeLists.txt | 115 +++++++++++++++---- cmake/CPack.cmake | 4 +- cmake/Config.cmake.in | 6 +- cmd/ksettings.cpp | 44 ------- cmd/kzsettings.cpp | 44 +++++++ python/bindings.cpp | 38 +++---- qt/cmake/Config.cmake.in | 9 ++ qt/kzqproperty.cpp | 64 +++++++++++ qt/kzqproperty.h | 38 +++++++ qt/kzqsettings.cpp | 246 +++++++++++++++++++++++++++++++++++++++ qt/kzqsettings.h | 34 ++++++ qt/kzqsettings_plugin.cpp | 12 ++ qt/kzqsettings_plugin.h | 15 +++ qt/qml/qmldir | 2 + src/changewatcher.cpp | 1 - src/kzsettings.cpp | 285 ++++++++++++++++++++++++++++++++++++++++++++++ src/kzsettings.h | 180 +++++++++++++++++++++++++++++ src/settings.cpp | 285 ---------------------------------------------- src/settings.h | 180 ----------------------------- 20 files changed, 1046 insertions(+), 559 deletions(-) create mode 100644 .gitignore delete mode 100644 cmd/ksettings.cpp create mode 100644 cmd/kzsettings.cpp create mode 100644 qt/cmake/Config.cmake.in create mode 100644 qt/kzqproperty.cpp create mode 100644 qt/kzqproperty.h create mode 100644 qt/kzqsettings.cpp create mode 100644 qt/kzqsettings.h create mode 100644 qt/kzqsettings_plugin.cpp create mode 100644 qt/kzqsettings_plugin.h create mode 100644 qt/qml/qmldir create mode 100644 src/kzsettings.cpp create mode 100644 src/kzsettings.h delete mode 100644 src/settings.cpp delete mode 100644 src/settings.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c3897b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +build* +CMakeLists.txt.user* + diff --git a/CMakeLists.txt b/CMakeLists.txt index acb7c5d..9d06877 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,34 +1,38 @@ cmake_minimum_required(VERSION 3.14) -project(KaZoe-Settings VERSION 1.0.0 LANGUAGES CXX) +project(KzSettings VERSION 1.0.0 LANGUAGES CXX) -option(WITH_PYTHON "Create python binding" ON) +option(WITH_PYTHON "Create python binding" ON) +option(WITH_QT "Create Qt6 library and QML Module" ON) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) +include(GNUInstallDirs) find_package (Threads REQUIRED) -add_library(KaZoeSettings SHARED - src/settings.h src/settings.cpp +add_library(KzSettings SHARED + src/kzsettings.h src/kzsettings.cpp src/changewatcher.h src/changewatcher.cpp + cmake/Config.cmake.in + cmake/CPack.cmake ) -set_target_properties(KaZoeSettings PROPERTIES VERSION ${CMAKE_PROJECT_VERSION} SOVERSION 1) -set_target_properties(KaZoeSettings PROPERTIES PUBLIC_HEADER "src/settings.h") -target_link_libraries(KaZoeSettings PRIVATE Threads::Threads) +set_target_properties(KzSettings PROPERTIES VERSION ${CMAKE_PROJECT_VERSION} SOVERSION 1) +set_target_properties(KzSettings PROPERTIES PUBLIC_HEADER "src/kzsettings.h") +target_link_libraries(KzSettings PRIVATE Threads::Threads) -add_executable(ksettings cmd/ksettings.cpp) -target_include_directories(ksettings PRIVATE src) -target_link_libraries(ksettings KaZoeSettings) +add_executable(kzsettings cmd/kzsettings.cpp) +target_include_directories(kzsettings PRIVATE src) +target_link_libraries(kzsettings KzSettings) -install(TARGETS KaZoeSettings - EXPORT "KaZoeSettingsTargets" +install(TARGETS KzSettings + EXPORT "KzSettingsTargets" LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_PREFIX}/include/KaZoe/" ) -install(TARGETS ksettings +install(TARGETS kzsettings LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) @@ -39,33 +43,94 @@ if(WITH_PYTHON) set(PYTHON_MODULE_EXTENSION ".so" CACHE INTERNAL "Cross python lib extension") find_package(pybind11 REQUIRED) include_directories(${Python3_INCLUDE_DIRS}) - pybind11_add_module(PyKaZoeSettings python/bindings.cpp) - set_target_properties(PyKaZoeSettings PROPERTIES OUTPUT_NAME "KaZoeSettings") - target_link_libraries(PyKaZoeSettings PUBLIC KaZoeSettings ${PYTHON_LIBRARY}) - install(TARGETS PyKaZoeSettings LIBRARY DESTINATION ${Python3_SITEARCH}) + pybind11_add_module(PyKzSettings python/bindings.cpp) + set_target_properties(PyKzSettings PROPERTIES OUTPUT_NAME "KzSettings") + target_link_libraries(PyKzSettings PUBLIC KzSettings ${PYTHON_LIBRARY}) + if(NOT PYTHONPATH) + set(PYTHONPATH ${Python3_SITEARCH}) + endif(NOT PYTHONPATH) + install(TARGETS PyKzSettings LIBRARY DESTINATION ${PYTHONPATH}) endif(WITH_PYTHON) -# CMake Module include(CMakePackageConfigHelpers) + +if(WITH_QT) + if(NOT DEFINED QML_MODULE_INSTALL_PATH) + if(DEFINED OE_QMAKE_PATH_QML) + set(QML_MODULE_INSTALL_PATH ${OE_QMAKE_PATH_QML} ) + else() + set(QML_MODULE_INSTALL_PATH ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/qml ) + endif() + endif() + message(STATUS "Build with Qt module in ${QML_MODULE_INSTALL_PATH}") + + find_package(Qt6 COMPONENTS Core Qml REQUIRED) + add_library(KzQSettings SHARED + qt/kzqsettings.h qt/kzqsettings.cpp + qt/kzqproperty.h qt/kzqproperty.cpp + qt/cmake/Config.cmake.in + ) + target_link_libraries(KzQSettings PUBLIC Qt6::Core KzSettings) + set_target_properties(KzQSettings PROPERTIES VERSION ${CMAKE_PROJECT_VERSION} SOVERSION 1) + set(KzQSettingsPublicHeader qt/kzqsettings.h qt/kzqproperty.h) + set_target_properties(KzQSettings PROPERTIES PUBLIC_HEADER "${KzQSettingsPublicHeader}") + install(TARGETS KzQSettings + EXPORT "KzQSettingsTargets" + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_PREFIX}/include/KaZoe/" + ) + write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/generated/KzQSettingsConfigVersion.cmake" COMPATIBILITY SameMajorVersion + ) + + configure_package_config_file( + "qt/cmake/Config.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/generated/KzQSettingsConfig.cmake" + INSTALL_DESTINATION "lib/cmake/KzQSettings" + ) + + install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/generated/KzQSettingsConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/generated/KzQSettingsConfigVersion.cmake" + DESTINATION "lib/cmake/KzQSettings" + ) + + install( + EXPORT "KzQSettingsTargets" + DESTINATION "lib/cmake/KzQSettings" + ) + + set(PLUGIN_SOURCES + qt/kzqsettings_plugin.h qt/kzqsettings_plugin.cpp + qt/qml/qmldir + ) + + add_library(KzQSettingsPlugin SHARED ${PLUGIN_SOURCES}) + target_link_libraries(KzQSettingsPlugin PRIVATE Qt6::Qml KzQSettings) + install(TARGETS KzQSettingsPlugin DESTINATION ${QML_MODULE_INSTALL_PATH}/org/kazoe/settings) + install(FILES qt/qml/qmldir DESTINATION ${QML_MODULE_INSTALL_PATH}/org/kazoe/settings) +endif(WITH_QT) + + write_basic_package_version_file( - "${CMAKE_CURRENT_BINARY_DIR}/generated/KaZoeSettingsConfigVersion.cmake" COMPATIBILITY SameMajorVersion + "${CMAKE_CURRENT_BINARY_DIR}/generated/KzSettingsConfigVersion.cmake" COMPATIBILITY SameMajorVersion ) configure_package_config_file( "cmake/Config.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/generated/KaZoeSettingsConfig.cmake" - INSTALL_DESTINATION "lib/cmake/${PROJECT_NAME}" + "${CMAKE_CURRENT_BINARY_DIR}/generated/KzSettingsConfig.cmake" + INSTALL_DESTINATION "lib/cmake/KzSettings" ) install( - FILES "${CMAKE_CURRENT_BINARY_DIR}/generated/KaZoeSettingsConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/generated/KaZoeSettingsConfigVersion.cmake" - DESTINATION "lib/cmake/${PROJECT_NAME}" + FILES "${CMAKE_CURRENT_BINARY_DIR}/generated/KzSettingsConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/generated/KzSettingsConfigVersion.cmake" + DESTINATION "lib/cmake/KzSettings" ) install( - EXPORT "KaZoeSettingsTargets" - DESTINATION "lib/cmake/${PROJECT_NAME}" + EXPORT "KzSettingsTargets" + DESTINATION "lib/cmake/KzSettings" ) include(cmake/CPack.cmake) diff --git a/cmake/CPack.cmake b/cmake/CPack.cmake index 33169b1..b8b9f75 100644 --- a/cmake/CPack.cmake +++ b/cmake/CPack.cmake @@ -1,8 +1,8 @@ set(CPACK_GENERATOR "DEB") -set(CPACK_PACKAGE_NAME "KaZoe-Settings") +set(CPACK_PACKAGE_NAME "KzSettings") set(CPACK_DEBIAN_PACKAGE_DEPENDS "python3") set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) set(CPACK_PACKAGE_VERSION_PATCH "${CMAKE_PROJECT_VERSION_PATCH}") -set(CPACK_PACKAGE_DESCRIPTION "KaZoe library") +set(CPACK_PACKAGE_DESCRIPTION "KaZoe Settings library") set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Fabien Proriol ") include(CPack) diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in index efbb7cc..cc295f1 100644 --- a/cmake/Config.cmake.in +++ b/cmake/Config.cmake.in @@ -1,7 +1,7 @@ @PACKAGE_INIT@ -include("${CMAKE_CURRENT_LIST_DIR}/KaZoeSettingsTargets.cmake") -set(LIBKAZOESETTINGS_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/include/@PROJECT_NAME@") -set(LIBKAZOESETTINGS_LIBRARIES "KaZoeSettings" ) +include("${CMAKE_CURRENT_LIST_DIR}/KzSettingsTargets.cmake") +set(LIBKZSETTINGS_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/include/KaZoe") +set(LIBKZSETTINGS_LIBRARIES "KzSettings" ) check_required_components("@PROJECT_NAME@") diff --git a/cmd/ksettings.cpp b/cmd/ksettings.cpp deleted file mode 100644 index 0d29dab..0000000 --- a/cmd/ksettings.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include -#include - -using namespace std; - -int main(int argc, char *argv[]) -{ - KaZoe::Settings settings; - - if(argc < 2) - { - std::cout << "Current settings:" << std::endl; - - settings.forEach([](const SettingKey& key, const SettingValue& value) { - std::string head; - if(!key.first.empty()) - { - head = "[" + key.first + "]"; - } - std::cout << "> " << head << key.second << " = " << KaZoe::valueToStr(value) << std::endl; - }); - } - else - { - std::string category; - std::string gkey = argv[1]; - if(gkey.starts_with("[")) - { - category = gkey.substr(1, gkey.find(']') - 1); - gkey = gkey.substr(gkey.find(']') + 1); - } - if(argc == 2) - { - std::cout << KaZoe::valueToStr(settings.get(gkey, category)) << std::endl; - } - else if(argc == 3) - { - std::string value = argv[2]; - settings.set(gkey, KaZoe::makeValue(value), category); - } - } - - return 0; -} diff --git a/cmd/kzsettings.cpp b/cmd/kzsettings.cpp new file mode 100644 index 0000000..2484e1d --- /dev/null +++ b/cmd/kzsettings.cpp @@ -0,0 +1,44 @@ +#include +#include + +using namespace std; + +int main(int argc, char *argv[]) +{ + KaZoe::KzSettings settings; + + if(argc < 2) + { + std::cout << "Current settings:" << std::endl; + + settings.forEach([](const KzSettingKey& key, const KzSettingValue& value) { + std::string head; + if(!key.first.empty()) + { + head = "[" + key.first + "]"; + } + std::cout << "> " << head << key.second << " = " << KaZoe::valueToStr(value) << std::endl; + }); + } + else + { + std::string category; + std::string gkey = argv[1]; + if(gkey.starts_with("[")) + { + category = gkey.substr(1, gkey.find(']') - 1); + gkey = gkey.substr(gkey.find(']') + 1); + } + if(argc == 2) + { + std::cout << KaZoe::valueToStr(settings.get(gkey, category)) << std::endl; + } + else if(argc == 3) + { + std::string value = argv[2]; + settings.set(gkey, KaZoe::makeValue(value), category); + } + } + + return 0; +} diff --git a/python/bindings.cpp b/python/bindings.cpp index 5c816f6..acce65b 100644 --- a/python/bindings.cpp +++ b/python/bindings.cpp @@ -1,65 +1,65 @@ #include #include -#include "../src/settings.h" +#include "../src/kzsettings.h" namespace py = pybind11; using namespace pybind11::literals; -class PyKaZoeSettings { - KaZoe::Settings m_settings; +class KzPySettings { + KaZoe::KzSettings m_settings; public: - PyKaZoeSettings(); + KzPySettings(); std::string __repr__(); static void add_python_binding(pybind11::module &m); - SettingValue get(std::string key, std::string category, SettingValue def); - SettingValue set(std::string key, SettingValue value, std::string category); + KzSettingValue get(std::string key, std::string category, KzSettingValue def); + KzSettingValue set(std::string key, KzSettingValue value, std::string category); }; -PyKaZoeSettings::PyKaZoeSettings() { +KzPySettings::KzPySettings() { py::module sys = py::module::import("sys"); py::list argv = sys.attr("argv"); m_settings.setId(argv[0].cast()); } -SettingValue PyKaZoeSettings::get(std::string key, std::string category, SettingValue def) { +KzSettingValue KzPySettings::get(std::string key, std::string category, KzSettingValue def) { return m_settings.get(key, category, def); } -SettingValue PyKaZoeSettings::set(std::string key, SettingValue value, std::string category) { +KzSettingValue KzPySettings::set(std::string key, KzSettingValue value, std::string category) { return m_settings.set(key, value, category); } -std::string PyKaZoeSettings::__repr__() { +std::string KzPySettings::__repr__() { std::string result = "KaZoeSettings"; return result; } -void PyKaZoeSettings::add_python_binding(pybind11::module &m) +void KzPySettings::add_python_binding(pybind11::module &m) { - py::class_(m, "KaZoeSettings") + py::class_(m, "KzSettings") .def(py::init<>()) - .def("get", [] (PyKaZoeSettings &m, std::string key, std::string category = "", SettingValue def = SettingValue()) { + .def("get", [] (KzPySettings &m, std::string key, std::string category = "", KzSettingValue def = KzSettingValue()) { return m.get(key, category, def); }, py::arg("key"), py::arg("category") = "", - py::arg("default") = SettingValue()) - .def("set", [] (PyKaZoeSettings &m, std::string key, SettingValue value, std::string category = "") { + py::arg("default") = KzSettingValue()) + .def("set", [] (KzPySettings &m, std::string key, KzSettingValue value, std::string category = "") { return m.set(key, value, category); }, py::arg("key"), py::arg("value"), py::arg("category") = "") - .def("__repr__", &PyKaZoeSettings::__repr__); + .def("__repr__", &KzPySettings::__repr__); } -PYBIND11_MODULE(KaZoeSettings, m) { +PYBIND11_MODULE(KzSettings, m) { m.doc() = R"pbdoc( - Python bindings for KaZoeSettings + Python bindings for KzSettings )pbdoc"; - PyKaZoeSettings::add_python_binding(m); + KzPySettings::add_python_binding(m); } diff --git a/qt/cmake/Config.cmake.in b/qt/cmake/Config.cmake.in new file mode 100644 index 0000000..a0d89fc --- /dev/null +++ b/qt/cmake/Config.cmake.in @@ -0,0 +1,9 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") +set(LIBKZQSETTINGS_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/KaZoe") +find_package(Qt6 COMPONENTS Core REQUIRED) +find_package(KzSettings REQUIRED) +set(LIBKZQSETTINGS_LIBRARIES "KzQSettings" "Qt6::Core" "${LIBKZSETTINGS_LIBRARIES}") + +check_required_components("@PROJECT_NAME@") diff --git a/qt/kzqproperty.cpp b/qt/kzqproperty.cpp new file mode 100644 index 0000000..4290e8c --- /dev/null +++ b/qt/kzqproperty.cpp @@ -0,0 +1,64 @@ +#include "kzqproperty.h" +#include "kzqsettings.h" + +namespace KaZoe { +class KzQPropertyPrivate +{ + Q_DISABLE_COPY(KzQPropertyPrivate) + Q_DECLARE_PUBLIC(KaZoe::KzQProperty) + + KaZoe::KzQProperty * const q_ptr; + QString m_key; + QVariant m_value; + KaZoe::KzQSettings m_settings; + + KzQPropertyPrivate(KaZoe::KzQProperty* systemprop): q_ptr(systemprop){} +}; +}; + +KaZoe::KzQProperty::KzQProperty(QObject *parent) + : QObject{parent} + , d_ptr(new KaZoe::KzQPropertyPrivate(this)) +{ + Q_D(KzQProperty); + QObject::connect(&d->m_settings, &KaZoe::KzQSettings::valueChanged, [this](QString id, QVariant value){ + Q_D(KzQProperty); + if(id == d->m_key) + { + setValue(value); + } + }); +} + +KaZoe::KzQProperty::~KzQProperty() = default; + +QString KaZoe::KzQProperty::key() const +{ + Q_D(const KzQProperty); + return d->m_key; +} + +void KaZoe::KzQProperty::setKey(const QString &newKey) +{ + Q_D(KzQProperty); + if (d->m_key == newKey) + return; + d->m_key = newKey; + setValue(d->m_settings.get(d->m_key)); + emit keyChanged(); +} + +QVariant KaZoe::KzQProperty::value() const +{ + Q_D(const KzQProperty); + return d->m_value; +} + +void KaZoe::KzQProperty::setValue(const QVariant &newValue) +{ + Q_D(KzQProperty); + if (d->m_value == newValue) + return; + d->m_value = newValue; + emit valueChanged(); +} diff --git a/qt/kzqproperty.h b/qt/kzqproperty.h new file mode 100644 index 0000000..8bd1b08 --- /dev/null +++ b/qt/kzqproperty.h @@ -0,0 +1,38 @@ +#ifndef KZQPROPERTY_H +#define KZQPROPERTY_H + +#include +#include +#include + +namespace KaZoe { + +class KzQPropertyPrivate; +class KzQProperty : public QObject +{ + Q_OBJECT + Q_PROPERTY(QString key READ key WRITE setKey NOTIFY keyChanged) + Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) + +public: + explicit KzQProperty(QObject *parent = nullptr); + ~KzQProperty(); + + QString key() const; + void setKey(const QString &newKey); + + QVariant value() const; + void setValue(const QVariant &newValue); + +signals: + void keyChanged(); + void valueChanged(); + +private: + Q_DISABLE_COPY(KzQProperty) + Q_DECLARE_PRIVATE(KzQProperty) + QScopedPointer d_ptr; +}; +}; + +#endif // KZQPROPERTY_H diff --git a/qt/kzqsettings.cpp b/qt/kzqsettings.cpp new file mode 100644 index 0000000..9ad4674 --- /dev/null +++ b/qt/kzqsettings.cpp @@ -0,0 +1,246 @@ +#include "kzqsettings.h" +#include "../src/kzsettings.h" +#include + +class QFileSystemWatcher; + + +QVariant toQVariant(const KzSettingValue &value, QVariant defvalue = QVariant()) +{ + if(std::holds_alternative(value)) + { + return QString::fromStdString(std::get(value)); + } + if(std::holds_alternative(value)) + { + return std::get(value); + } + if(std::holds_alternative(value)) + { + return std::get(value); + } + if(std::holds_alternative(value)) + { + return std::get(value); + } + return QVariant(defvalue); +} + +KzSettingValue fromQVariant(const QVariant &value) +{ + if(value.isNull()) + return KzSettingValue(); + + switch (value.userType()) + { + case QMetaType::Int: + return value.value(); + + case QMetaType::QString: + return value.toString().toStdString(); + + case QMetaType::Bool: + return value.value(); + + case QMetaType::Double: + return value.value(); + + default: + return false; + } +} + +QString toKeyCombined(const std::string& category, const std::string& key) +{ + QString keysig; + if(category.size()) + { + keysig.append("["); + keysig.append(QString::fromStdString(category)); + keysig.append("]"); + } + keysig.append(QString::fromStdString(key)); + return keysig; +} + +KaZoe::KzQSettings::KzQSettings(QObject *parent) + : QObject(parent) + , m_settings(new KaZoe::KzSettings()) +{ + m_settings->setNotifier([this](const std::string& category, const std::string& key, KzSettingValue value) { + emit valueChanged(toKeyCombined(category, key), toQVariant(value)); + }); +} + +KaZoe::KzQSettings::~KzQSettings() +{ +} + +QVariant KaZoe::KzQSettings::getValue(const QString &id, QVariant defvalue) +{ + KaZoe::KzSettings settings; + + QString category; + QString key = id; + if(id.contains("/")) + { + qWarning() << "OLD Syntax used for " << id; + QStringList tab = id.split("/"); + category = tab[0]; + tab.removeFirst(); + key = tab.join("/"); + } + + KzSettingValue value = settings.get(key.toStdString(), category.toStdString(), fromQVariant(defvalue)); + return toQVariant(value); +} + +bool KaZoe::KzQSettings::setValue(const QString &id, const QVariant &value) +{ + KaZoe::KzSettings settings; + bool ret; + QString key = id; + QString category; + + if(id.contains("/")) + { + qWarning() << "OLD Syntax used for " << id; + QStringList tab = id.split("/"); + category = tab[0]; + tab.removeFirst(); + key = tab.join("/"); + } + + switch (value.userType()) + { + case QMetaType::Int: + ret = settings.set(key.toStdString(), value.value(), category.toStdString()); + break; + + case QMetaType::QString: + ret = settings.set(key.toStdString(), value.toString().toStdString(), category.toStdString()); + break; + + case QMetaType::Bool: + ret = settings.set(key.toStdString(), value.value(), category.toStdString()); + break; + + case QMetaType::Double: + ret = settings.set(key.toStdString(), value.value(), category.toStdString()); + break; + default: + ret = false; + break; + } + + if(!ret) + { + qWarning() << "Settings ERROR: Write access not permitted for" << id << " with " << QString::fromStdString(settings.id()); + return false; + } + return true; +} + + +int KaZoe::KzQSettings::count() const +{ + if(m_settings) return m_settings->size(); + qWarning() << "Invalid object state for count"; + return -1; +} + +QVariant KaZoe::KzQSettings::get(const QString &id, const QVariant defvalue) const +{ + if(!m_settings) + { + qWarning() << "Invalid object state for get"; + return QVariant(); + } + + QString category; + QString key = id; + if(id.contains("/")) + { + qWarning() << "OLD Syntax used for " << id; + QStringList tab = id.split("/"); + category = tab[0]; + tab.removeFirst(); + key = tab.join("/"); + } + + KzSettingValue value = m_settings->get(key.toStdString(), category.toStdString(), fromQVariant(defvalue)); + return toQVariant(value); +} + +bool KaZoe::KzQSettings::set(const QString &id, const QVariant &value) +{ + if(!m_settings) + { + qWarning() << "Invalid object state for set"; + return false; + } + bool ret; + QString key = id; + QString category; + + if(id.contains("/")) + { + qWarning() << "OLD Syntax used for " << id; + QStringList tab = id.split("/"); + category = tab[0]; + tab.removeFirst(); + key = tab.join("/"); + } + + switch (value.userType()) + { + case QMetaType::Int: + ret = m_settings->set(key.toStdString(), value.value(), category.toStdString()); + break; + + case QMetaType::QString: + ret = m_settings->set(key.toStdString(), value.toString().toStdString(), category.toStdString()); + break; + + case QMetaType::Bool: + ret = m_settings->set(key.toStdString(), value.value(), category.toStdString()); + break; + + case QMetaType::Double: + ret = m_settings->set(key.toStdString(), value.value(), category.toStdString()); + break; + default: + ret = false; + break; + } + + if(!ret) + { + qWarning() << "Settings ERROR: Write access not permitted for" << id << " with " << QString::fromStdString(m_settings->id()); + return false; + } + + emit valueChanged(toKeyCombined(category.toStdString(), key.toStdString()), value); + return true; +} + +QStringList KaZoe::KzQSettings::keys() const +{ + if(!m_settings) + { + qWarning() << "Invalid object state for keys"; + return QStringList(); + } + + QStringList keys; + m_settings->forEach([&keys](const KzSettingKey& key, const KzSettingValue& value) { + std::string combined; + if(!key.first.empty()) + { + combined = "[" + key.first + "]"; + } + combined.append(key.second); + keys.append(QString::fromStdString(combined)); + }); + return keys; +} diff --git a/qt/kzqsettings.h b/qt/kzqsettings.h new file mode 100644 index 0000000..6ab48a0 --- /dev/null +++ b/qt/kzqsettings.h @@ -0,0 +1,34 @@ +#ifndef KZQSETTINGS_H +#define KZQSETTINGS_H + +#include +#include + +namespace KaZoe { + +class KzSettings; + +class KzQSettings : public QObject +{ + Q_OBJECT + QScopedPointer m_settings; + +public: + explicit KzQSettings(QObject *parent = nullptr); + virtual ~KzQSettings(); + + static QVariant getValue(const QString &id, QVariant defvalue = QVariant()); + static bool setValue(const QString &id, const QVariant &value); + +public slots: + int count() const; + QVariant get(const QString &id, const QVariant defvalue = QVariant()) const; + bool set(const QString &id, const QVariant &value); + QStringList keys() const; + +signals: + void valueChanged(QString id, QVariant value); +}; +}; + +#endif // KZQSETTINGS_H diff --git a/qt/kzqsettings_plugin.cpp b/qt/kzqsettings_plugin.cpp new file mode 100644 index 0000000..170324e --- /dev/null +++ b/qt/kzqsettings_plugin.cpp @@ -0,0 +1,12 @@ +#include "kzqsettings_plugin.h" +#include "kzqsettings.h" +#include "kzqproperty.h" + +#include + +void KzSettingsPlugin::registerTypes(const char *uri) +{ + // @uri kazoe + qmlRegisterType(uri, 1, 0, "KzSettings"); + qmlRegisterType(uri, 1, 0, "KzProperty"); +} diff --git a/qt/kzqsettings_plugin.h b/qt/kzqsettings_plugin.h new file mode 100644 index 0000000..dcaf808 --- /dev/null +++ b/qt/kzqsettings_plugin.h @@ -0,0 +1,15 @@ +#ifndef KZSETTINGS_PLUGIN_H +#define KZSETTINGS_PLUGIN_H + +#include + +class KzSettingsPlugin : public QQmlExtensionPlugin +{ + Q_OBJECT + Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid) + +public: + void registerTypes(const char *uri) override; +}; + +#endif // SYSTEMSETTINGS_PLUGIN_H diff --git a/qt/qml/qmldir b/qt/qml/qmldir new file mode 100644 index 0000000..d15e7a3 --- /dev/null +++ b/qt/qml/qmldir @@ -0,0 +1,2 @@ +module org.kazoe.settings +plugin KzQSettingsPlugin diff --git a/src/changewatcher.cpp b/src/changewatcher.cpp index 4762ebb..ef54019 100644 --- a/src/changewatcher.cpp +++ b/src/changewatcher.cpp @@ -1,5 +1,4 @@ #include "changewatcher.h" -#include #include #include #include diff --git a/src/kzsettings.cpp b/src/kzsettings.cpp new file mode 100644 index 0000000..5580a80 --- /dev/null +++ b/src/kzsettings.cpp @@ -0,0 +1,285 @@ +#include "kzsettings.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "changewatcher.h" + +using namespace KaZoe; + +static inline void trim(std::string & str) +{ + str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](const unsigned char ch){return !std::isspace(ch);})); + str.erase(std::find_if(str.rbegin(), str.rend(), [](const unsigned char ch){return !std::isspace(ch);}).base(), str.end()); +} + +static inline bool list_contains(std::vector list, const std::string & str) +{ + return (std::find(list.begin(), list.end(), str) != list.end()); +} + +namespace KaZoe { +class KzSettingsPrivate { + friend class KzSettings; + KzSettings *m_parent; + std::map m_data; + ChangeWatcher m_watcher; + std::map m_owner; + std::string m_id; + std::mutex m_mutex_data; + std::mutex m_mutex_notifier; + bool m_bypass {false}; + std::vector> m_notifier; + +public: + KzSettingsPrivate(KzSettings *parent) + : m_parent(parent) { + char result[PATH_MAX]; + ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); + std::string binary = std::string(result, (count > 0) ? count : 0); + std::filesystem::path bin = binary; + m_id = bin.filename(); + if(m_id == "kzsettings") + { + // Only "kzsettings cli tools can bypass the owner protection" + m_bypass = true; + } + + m_watcher.setFileAdded([this](const std::string path){ refreshDirectory(path); }); + m_watcher.setFileRemoved([this](const std::string path){ refreshAll(); }); + m_watcher.setFileWrited([this](const std::string path){ refreshFile(path); }); + } + + void parseFile(const std::string &filename, std::map &data, bool watch = false) + { + if(!std::filesystem::exists(filename)) + { + return; + } + std::filesystem::path pfile = filename; + if(pfile.filename().string().starts_with(".")) return; + if(pfile.extension() != ".conf") return; + + if(watch) + { + m_watcher.watch(filename); + } + + std::ifstream file(filename); + std::string line; + std::string category = ""; + + while (std::getline(file, line)) { + trim(line); + + if(line.empty() || line.starts_with("#") || line.ends_with(";")) { + continue; + } + if(line.starts_with("[") && line.ends_with("]")) { + category = line.substr(1, line.length() - 2); + if(category == "General") category.clear(); + continue; + } + size_t pos = line.find("="); + std::string key = line.substr(0, pos); + trim(key); + std::string value = line.substr(pos + 1); + trim(value); + + if(key.starts_with("@")) + { + m_owner[KzSettingKey(category, key.substr(1))] = value; + continue; + } + if(key.ends_with("/owner")) + { + std::cerr << "WARNING: Legacy usage for owner: " << key << " should be @" << key.substr(0, key.size() - 6) << std::endl; + m_owner[KzSettingKey(category, key.substr(0, key.size() - 6))] = value; + continue; + } + + data[KzSettingKey(category, key)] = makeValue(value); + } + } + + void parseDir(const std::string &dconf, std::map &data, bool watch) + { + if(std::filesystem::exists(dconf) && std::filesystem::is_directory(dconf)) + { + for (const auto& entry : std::filesystem::directory_iterator(dconf)) + { + if(entry.is_directory()) continue; + parseFile(std::filesystem::absolute(entry.path()), data, watch); + } + } + } + + void parseConf(const std::string &fconf, std::map &data, bool watch) + { + if(std::filesystem::exists(fconf)) + { + parseFile(fconf, data, watch); + } + std::string dconf = fconf + ".d"; + parseDir(dconf, data, watch); + if(watch) + { + m_watcher.watch(dconf); + } + } + + void refreshData(const std::map &cust_data) + { + std::lock_guard lock(m_mutex_data); + std::lock_guard lock_notifier(m_mutex_notifier); + for(const auto& [key, value] : cust_data) { + if(!m_data.contains(key) || m_data[key] != value) + { + // New ITEM OR Data changed + m_data[key] = value; + for(auto ¬ifier: m_notifier) + { + notifier(key.first, key.second, value); + } + continue; + } + } + } + + void refreshFile(const std::string &file) + { + std::map cust_data; + parseFile(file, cust_data); + refreshData(cust_data); + } + + void refreshDirectory(const std::string &dirname) + { + std::map cust_data; + parseDir(dirname, cust_data, true); + refreshData(cust_data); + } + + void refreshAll() + { + std::map cust_data; + parseConf("/etc/kazoe.conf", cust_data, false); + parseConf("/var/kazoe.conf", cust_data, true); + refreshData(cust_data); + } +}; +}; + +KzSettings::KzSettings() + : m_ptr(std::make_unique(this)) +{ + m_ptr->parseConf("/etc/kazoe.conf", m_ptr->m_data, false); + m_ptr->parseConf("/var/kazoe.conf", m_ptr->m_data, true); +} + +KzSettingValue KzSettings::get(const std::string &key, const std::string &category, KzSettingValue def) const +{ + std::lock_guard lock(m_ptr->m_mutex_data); + std::string gkey = key; + std::string gcategory = category; + if(gcategory.empty() && gkey.starts_with("[")) + { + gcategory = gkey.substr(1, gkey.find(']') - 1); + gkey = gkey.substr(gkey.find(']') + 1); + } + + KzSettingKey pkey(gcategory, gkey); + + if(m_ptr->m_data.count(pkey)) + { + return m_ptr->m_data[pkey]; + } + return def; +} + +bool KzSettings::set(const std::string &key, KzSettingValue value, const std::string &category) +{ + // Check if variable is writable + std::lock_guard lock(m_ptr->m_mutex_data); + KzSettingKey pkey(category, key); + std::string id; + + if(!m_ptr->m_owner.count(pkey)) + { + std::cerr << "Variable " << category << ">" << key << " is not writable" << std::endl; + return false; + } + + if(m_ptr->m_bypass) + { + id = m_ptr->m_owner[pkey]; + } + else + { + id = m_ptr->m_id; + if(m_ptr->m_owner[pkey] != id) + { + std::cerr << "Variable " << category << ">" << key << " is not own by " << m_ptr->m_id << std::endl; + return false; + } + } + + // Permission is OK, get old custom variable + std::map cust_data; + m_ptr->parseFile("/var/kazoe.conf.d/"+id+".conf", cust_data); + cust_data[pkey] = value; + std::string last_category = ""; + std::ofstream file("/var/kazoe.conf.d/"+id+".conf"); + + for(const auto& [key, value] : cust_data) { + if(key.first != last_category) + { + last_category = key.first.empty() ? "General" : key.first; + file << "[" << last_category << "]\n"; + } + file << key.second << " = " << KaZoe::valueToStr(value) << "\n"; + } + + m_ptr->m_data[pkey] = value; + return true; +} + +std::string KzSettings::id() const +{ + return m_ptr->m_id; +} + +void KzSettings::setId(const std::string &newid) +{ + m_ptr->m_id = newid; +} + +void KzSettings::setNotifier(const std::function &callback) +{ + std::lock_guard lock(m_ptr->m_mutex_notifier); + m_ptr->m_notifier.push_back(callback); + m_ptr->m_watcher.setEnable(true); +} + +std::size_t KzSettings::size() const +{ + std::lock_guard lock(m_ptr->m_mutex_data); + return m_ptr->m_data.size(); +} + +void KzSettings::forEach(const std::function &callback) const +{ + std::lock_guard lock(m_ptr->m_mutex_data); + for (const auto& [key, value] : m_ptr->m_data) { + callback(key, value); + } +} + +KzSettings::~KzSettings() +{ + m_ptr->m_watcher.setEnable(false); +} diff --git a/src/kzsettings.h b/src/kzsettings.h new file mode 100644 index 0000000..9f8d35b --- /dev/null +++ b/src/kzsettings.h @@ -0,0 +1,180 @@ +#ifndef KZSETTINGS_H +#define KZSETTINGS_H + +#include +#include +#include +#include +#include + +/** @brief Key type for settings, composed of category and name */ +using KzSettingKey = std::pair; + +/** @brief Value type that can hold string, int, double or boolean */ +using KzSettingValue = std::variant; + + +namespace KaZoe { + +class KzSettingsPrivate; + +/** + * @brief Main class for managing KaZoe settings + * + * This class provides a thread-safe interface for storing and retrieving + * configuration settings with support for different value types. + */ +class KzSettings +{ +public: + /** @brief Constructs a new Settings instance */ + explicit KzSettings(); + + /** @brief Virtual destructor */ + virtual ~KzSettings(); + + /** + * @brief Retrieves a setting value + * @param key The setting key + * @param category The setting category (optional) + * @param def Default value if setting not found (optional) + * @return The setting value or default if not found + */ + KzSettingValue get(const std::string &key, const std::string &category = "", KzSettingValue def = KzSettingValue()) const; + + /** + * @brief Sets a setting value + * @param key The setting key + * @param value The value to set + * @param category The setting category (optional) + * @return true if successful, false otherwise + */ + bool set(const std::string &key, KzSettingValue value, const std::string &category = ""); + + /** + * @brief Gets the current instance identifier + * @return The instance ID string, by default, this is the excecutable filename + */ + std::string id() const; + + /** + * @brief Sets the instance identifier + * @param newid The new ID to set + */ + void setId(const std::string &newid); + + /** + * @brief Sets a callback for setting changes notification + * @param callback Function to call when settings change + */ + void setNotifier(const std::function& callback); + + /** + * @brief Gets the number of settings + * @return The total count of settings + */ + std::size_t size() const; + + /** + * @brief Iterates over all settings in a thread-safe manner + * @param callback Function called for each key-value pair + */ + void forEach(const std::function& callback) const; + +private: + std::unique_ptr m_ptr; ///< Private implementation pointer +}; + + +/** + * @brief Functor to convert SettingValue variants to string + * + * Provides string conversion for all supported setting value types + */ +struct settingValueFunctor { + std::string operator()(const std::string &x) const { return x; } + std::string operator()(int x) const { return std::to_string(x); } + std::string operator()(double x) const { return std::to_string(x); } + std::string operator()(bool x) const { return x ? "true" : "false"; } +}; + +/** + * @brief Convert a SettingValue into a string for display + * @param value Input SettingValue to convert + * @return std::string containing the converted value + */ +static inline std::string valueToStr(const KzSettingValue &value) +{ + return std::visit(settingValueFunctor(), value); +} + +/** + * @brief Check if a string represents a valid numeric value + * @param str String to check + * @return true if string is numeric, false otherwise + */ +static inline bool is_numeric(const std::string& str) { + return !str.empty() && + str.find_first_not_of("0123456789.-") == std::string::npos && + (std::count(str.begin(), str.end(), '.') <= 1) && + (std::count(str.begin(), str.end(), '-') <= 1) && + (str[0] == '-' || std::isdigit(str[0])); +} + +/** + * @brief Convert a string to appropriate SettingValue type + * @param value Input string to convert + * @return SettingValue containing the converted value + * + * Conversion rules: + * - Quoted strings -> string without quotes + * - Numeric values -> int or double + * - "true"/"on" -> boolean true + * - "false"/"off" -> boolean false + * - Other -> string + */ +static inline KzSettingValue makeValue(const std::string &value) +{ + if(value.starts_with('"') || value.starts_with('\'')) + { + return value.substr(1, value.length() - 2); + } + + if(is_numeric(value)) + { + // double + if(value.find('.') != value.npos) + { + return std::stod(value); + } + else + { + return std::stoi(value); + } + } + + // To Lower case + std::string lvalue = value; + std::transform(lvalue.begin(), lvalue.end(), lvalue.begin(), + [](unsigned char c){ return std::tolower(c); }); + + + // bool true + if(lvalue == "true" || lvalue == "on") + { + return true; + } + + // bool false + if(lvalue == "false" || lvalue == "off") + { + return false; + } + + // else, string without quote + return value; +} + +}; + +#endif // KZSETTINGS_H diff --git a/src/settings.cpp b/src/settings.cpp deleted file mode 100644 index addaa32..0000000 --- a/src/settings.cpp +++ /dev/null @@ -1,285 +0,0 @@ -#include "settings.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include "changewatcher.h" - -using namespace KaZoe; - -static inline void trim(std::string & str) -{ - str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](const unsigned char ch){return !std::isspace(ch);})); - str.erase(std::find_if(str.rbegin(), str.rend(), [](const unsigned char ch){return !std::isspace(ch);}).base(), str.end()); -} - -static inline bool list_contains(std::vector list, const std::string & str) -{ - return (std::find(list.begin(), list.end(), str) != list.end()); -} - -namespace KaZoe { -class SettingsPrivate { - friend class Settings; - Settings *m_parent; - std::map m_data; - ChangeWatcher m_watcher; - std::map m_owner; - std::string m_id; - std::mutex m_mutex_data; - std::mutex m_mutex_notifier; - bool m_bypass {false}; - std::vector> m_notifier; - -public: - SettingsPrivate(Settings *parent) - : m_parent(parent) { - char result[PATH_MAX]; - ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); - std::string binary = std::string(result, (count > 0) ? count : 0); - std::filesystem::path bin = binary; - m_id = bin.filename(); - if(m_id == "settings") - { - // Only "settings cli tools can bypass the owner protection" - m_bypass = true; - } - - m_watcher.setFileAdded([this](const std::string path){ refreshDirectory(path); }); - m_watcher.setFileRemoved([this](const std::string path){ refreshAll(); }); - m_watcher.setFileWrited([this](const std::string path){ refreshFile(path); }); - } - - void parseFile(const std::string &filename, std::map &data, bool watch = false) - { - if(!std::filesystem::exists(filename)) - { - return; - } - std::filesystem::path pfile = filename; - if(pfile.filename().string().starts_with(".")) return; - if(pfile.extension() != ".conf") return; - - if(watch) - { - m_watcher.watch(filename); - } - - std::ifstream file(filename); - std::string line; - std::string category = ""; - - while (std::getline(file, line)) { - trim(line); - - if(line.empty() || line.starts_with("#") || line.ends_with(";")) { - continue; - } - if(line.starts_with("[") && line.ends_with("]")) { - category = line.substr(1, line.length() - 2); - if(category == "General") category.clear(); - continue; - } - size_t pos = line.find("="); - std::string key = line.substr(0, pos); - trim(key); - std::string value = line.substr(pos + 1); - trim(value); - - if(key.starts_with("@")) - { - m_owner[SettingKey(category, key.substr(1))] = value; - continue; - } - if(key.ends_with("/owner")) - { - std::cerr << "WARNING: Legacy usage for owner: " << key << " should be @" << key.substr(0, key.size() - 6) << std::endl; - m_owner[SettingKey(category, key.substr(0, key.size() - 6))] = value; - continue; - } - - data[SettingKey(category, key)] = makeValue(value); - } - } - - void parseDir(const std::string &dconf, std::map &data, bool watch) - { - if(std::filesystem::exists(dconf) && std::filesystem::is_directory(dconf)) - { - for (const auto& entry : std::filesystem::directory_iterator(dconf)) - { - if(entry.is_directory()) continue; - parseFile(std::filesystem::absolute(entry.path()), data, watch); - } - } - } - - void parseConf(const std::string &fconf, std::map &data, bool watch) - { - if(std::filesystem::exists(fconf)) - { - parseFile(fconf, data, watch); - } - std::string dconf = fconf + ".d"; - parseDir(dconf, data, watch); - if(watch) - { - m_watcher.watch(dconf); - } - } - - void refreshData(const std::map &cust_data) - { - std::lock_guard lock(m_mutex_data); - std::lock_guard lock_notifier(m_mutex_notifier); - for(const auto& [key, value] : cust_data) { - if(!m_data.contains(key) || m_data[key] != value) - { - // New ITEM OR Data changed - m_data[key] = value; - for(auto ¬ifier: m_notifier) - { - notifier(key.first, key.second, value); - } - continue; - } - } - } - - void refreshFile(const std::string &file) - { - std::map cust_data; - parseFile(file, cust_data); - refreshData(cust_data); - } - - void refreshDirectory(const std::string &dirname) - { - std::map cust_data; - parseDir(dirname, cust_data, true); - refreshData(cust_data); - } - - void refreshAll() - { - std::map cust_data; - parseConf("/etc/kazoe.conf", cust_data, false); - parseConf("/var/kazoe.conf", cust_data, true); - refreshData(cust_data); - } -}; -}; - -Settings::Settings() - : m_ptr(std::make_unique(this)) -{ - m_ptr->parseConf("/etc/kazoe.conf", m_ptr->m_data, false); - m_ptr->parseConf("/var/kazoe.conf", m_ptr->m_data, true); -} - -SettingValue Settings::get(const std::string &key, const std::string &category, SettingValue def) const -{ - std::lock_guard lock(m_ptr->m_mutex_data); - std::string gkey = key; - std::string gcategory = category; - if(gcategory.empty() && gkey.starts_with("[")) - { - gcategory = gkey.substr(1, gkey.find(']') - 1); - gkey = gkey.substr(gkey.find(']') + 1); - } - - SettingKey pkey(gcategory, gkey); - - if(m_ptr->m_data.count(pkey)) - { - return m_ptr->m_data[pkey]; - } - return def; -} - -bool Settings::set(const std::string &key, SettingValue value, const std::string &category) -{ - // Check if variable is writable - std::lock_guard lock(m_ptr->m_mutex_data); - SettingKey pkey(category, key); - std::string id; - - if(!m_ptr->m_owner.count(pkey)) - { - std::cerr << "Variable " << category << ">" << key << " is not writable" << std::endl; - return false; - } - - if(m_ptr->m_bypass) - { - id = m_ptr->m_owner[pkey]; - } - else - { - id = m_ptr->m_id; - if(m_ptr->m_owner[pkey] != id) - { - std::cerr << "Variable " << category << ">" << key << " is not own by " << m_ptr->m_id << std::endl; - return false; - } - } - - // Permission is OK, get old custom variable - std::map cust_data; - m_ptr->parseFile("/var/kazoe.conf.d/"+id+".conf", cust_data); - cust_data[pkey] = value; - std::string last_category = ""; - std::ofstream file("/var/kazoe.conf.d/"+id+".conf"); - - for(const auto& [key, value] : cust_data) { - if(key.first != last_category) - { - last_category = key.first.empty() ? "General" : key.first; - file << "[" << last_category << "]\n"; - } - file << key.second << " = " << KaZoe::valueToStr(value) << "\n"; - } - - m_ptr->m_data[pkey] = value; - return true; -} - -std::string Settings::id() const -{ - return m_ptr->m_id; -} - -void Settings::setId(const std::string &newid) -{ - m_ptr->m_id = newid; -} - -void Settings::setNotifier(const std::function &callback) -{ - std::lock_guard lock(m_ptr->m_mutex_notifier); - m_ptr->m_notifier.push_back(callback); - m_ptr->m_watcher.setEnable(true); -} - -std::size_t Settings::size() const -{ - std::lock_guard lock(m_ptr->m_mutex_data); - return m_ptr->m_data.size(); -} - -void Settings::forEach(const std::function &callback) const -{ - std::lock_guard lock(m_ptr->m_mutex_data); - for (const auto& [key, value] : m_ptr->m_data) { - callback(key, value); - } -} - -Settings::~Settings() -{ - m_ptr->m_watcher.setEnable(false); -} diff --git a/src/settings.h b/src/settings.h deleted file mode 100644 index 5dfe90b..0000000 --- a/src/settings.h +++ /dev/null @@ -1,180 +0,0 @@ -#ifndef KAZOESETTINGS_H -#define KAZOESETTINGS_H - -#include -#include -#include -#include -#include - -/** @brief Key type for settings, composed of category and name */ -using SettingKey = std::pair; - -/** @brief Value type that can hold string, int, double or boolean */ -using SettingValue = std::variant; - - -namespace KaZoe { - -class SettingsPrivate; - -/** - * @brief Main class for managing KaZoe settings - * - * This class provides a thread-safe interface for storing and retrieving - * configuration settings with support for different value types. - */ -class Settings -{ -public: - /** @brief Constructs a new Settings instance */ - explicit Settings(); - - /** @brief Virtual destructor */ - virtual ~Settings(); - - /** - * @brief Retrieves a setting value - * @param key The setting key - * @param category The setting category (optional) - * @param def Default value if setting not found (optional) - * @return The setting value or default if not found - */ - SettingValue get(const std::string &key, const std::string &category = "", SettingValue def = SettingValue()) const; - - /** - * @brief Sets a setting value - * @param key The setting key - * @param value The value to set - * @param category The setting category (optional) - * @return true if successful, false otherwise - */ - bool set(const std::string &key, SettingValue value, const std::string &category = ""); - - /** - * @brief Gets the current instance identifier - * @return The instance ID string, by default, this is the excecutable filename - */ - std::string id() const; - - /** - * @brief Sets the instance identifier - * @param newid The new ID to set - */ - void setId(const std::string &newid); - - /** - * @brief Sets a callback for setting changes notification - * @param callback Function to call when settings change - */ - void setNotifier(const std::function& callback); - - /** - * @brief Gets the number of settings - * @return The total count of settings - */ - std::size_t size() const; - - /** - * @brief Iterates over all settings in a thread-safe manner - * @param callback Function called for each key-value pair - */ - void forEach(const std::function& callback) const; - -private: - std::unique_ptr m_ptr; ///< Private implementation pointer -}; - - -/** - * @brief Functor to convert SettingValue variants to string - * - * Provides string conversion for all supported setting value types - */ -struct settingValueFunctor { - std::string operator()(const std::string &x) const { return x; } - std::string operator()(int x) const { return std::to_string(x); } - std::string operator()(double x) const { return std::to_string(x); } - std::string operator()(bool x) const { return x ? "true" : "false"; } -}; - -/** - * @brief Convert a SettingValue into a string for display - * @param value Input SettingValue to convert - * @return std::string containing the converted value - */ -static inline std::string valueToStr(const SettingValue &value) -{ - return std::visit(settingValueFunctor(), value); -} - -/** - * @brief Check if a string represents a valid numeric value - * @param str String to check - * @return true if string is numeric, false otherwise - */ -static inline bool is_numeric(const std::string& str) { - return !str.empty() && - str.find_first_not_of("0123456789.-") == std::string::npos && - (std::count(str.begin(), str.end(), '.') <= 1) && - (std::count(str.begin(), str.end(), '-') <= 1) && - (str[0] == '-' || std::isdigit(str[0])); -} - -/** - * @brief Convert a string to appropriate SettingValue type - * @param value Input string to convert - * @return SettingValue containing the converted value - * - * Conversion rules: - * - Quoted strings -> string without quotes - * - Numeric values -> int or double - * - "true"/"on" -> boolean true - * - "false"/"off" -> boolean false - * - Other -> string - */ -static inline SettingValue makeValue(const std::string &value) -{ - if(value.starts_with('"') || value.starts_with('\'')) - { - return value.substr(1, value.length() - 2); - } - - if(is_numeric(value)) - { - // double - if(value.find('.') != value.npos) - { - return std::stod(value); - } - else - { - return std::stoi(value); - } - } - - // To Lower case - std::string lvalue = value; - std::transform(lvalue.begin(), lvalue.end(), lvalue.begin(), - [](unsigned char c){ return std::tolower(c); }); - - - // bool true - if(lvalue == "true" || lvalue == "on") - { - return true; - } - - // bool false - if(lvalue == "false" || lvalue == "off") - { - return false; - } - - // else, string without quote - return value; -} - -}; - -#endif // KAZOESETTINGS_H -- cgit v1.2.3