Files
EchoionApi/include/echoion/api/ConfigManager.hpp
T
2026-02-01 23:05:41 +03:00

97 lines
2.9 KiB
C++

#pragma once
#include "ConfigTypes.hpp"
#include <filesystem>
#include <mutex>
#include <shared_mutex>
#include <optional>
#include <functional>
namespace Echoion::Api {
/**
* @brief DEPRECATED: Global configuration manager
*
* This singleton pattern does NOT work across shared library boundaries.
* Each shared library (Plugin and Core) gets its own instance.
*
* NEW ARCHITECTURE:
* - Plugin loads config using ConfigLoader
- Plugin passes config to Core via CoreLoader::setConfig() -> Core::initialize()
* - Core stores config locally, updates via Core::updateConfig()
* - Config reload: Core calls plugin->reloadConfig() -> Core::updateConfig()
*
* This header is kept for backward compatibility but should not be used.
*/
class ConfigManager {
public:
using ConfigChangedCallback = std::function<void(const AppConfig&)>;
// Get singleton instance
static ConfigManager& instance();
// Delete copy/move
ConfigManager(const ConfigManager&) = delete;
ConfigManager& operator=(const ConfigManager&) = delete;
// Initialize with config file path (call once at startup)
[[nodiscard]] bool initialize(const std::filesystem::path& configPath);
// Initialize with default path (~/.config/echoion/config.json)
[[nodiscard]] bool initialize();
// Get current config (thread-safe)
[[nodiscard]] AppConfig getConfig() const;
// Get config by reference (faster, but hold lock briefly)
template<typename Func>
auto withConfig(Func&& func) const -> decltype(func(std::declval<const AppConfig&>())) {
std::shared_lock lock(mutex_);
return func(config_);
}
// Reload configuration from file
[[nodiscard]] bool reload();
// Save current configuration to file
[[nodiscard]] bool save();
// Update config (and optionally save)
void updateConfig(const AppConfig& config, bool saveToFile = true);
// Check if initialized
[[nodiscard]] bool isInitialized() const;
// Get config file path
[[nodiscard]] std::filesystem::path getConfigPath() const;
// Get default config path (~/.config/echoion/config.json)
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
// Subscribe to config changes
void onConfigChanged(ConfigChangedCallback callback);
// Create default config file if it doesn't exist
[[nodiscard]] bool createDefaultConfigIfNeeded();
private:
ConfigManager() = default;
~ConfigManager() = default;
mutable std::shared_mutex mutex_;
AppConfig config_;
std::filesystem::path configPath_;
std::atomic<bool> initialized_{false};
std::vector<ConfigChangedCallback> callbacks_;
mutable std::mutex callbackMutex_;
void notifyCallbacks();
[[nodiscard]] bool loadFromFileInternal();
[[nodiscard]] bool saveToFileInternal();
};
} // namespace Echoion::Api
// Convenience macro for accessing config
#define ECHOION_CONFIG (::Echoion::Api::ConfigManager::instance().getConfig())