| use std::path::{Path, PathBuf}; |
| use serde::{Deserialize, Serialize}; |
| use serde_json::Value; |
|
|
| use crate::error::{Result, ZdbError}; |
|
|
| |
| #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] |
| pub enum AppearanceMode { |
| Auto, |
| Light, |
| Dark, |
| } |
|
|
| pub enum Language { |
| Auto, |
| English, |
| Chinese, |
| } |
|
|
| |
| #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] |
| pub enum ConfigKey { |
| |
| AppOwner, |
| AudioLibPath, |
| ExtraLibSearchPath, |
| CustomFontPath, |
| AutoLookupClipboard, |
| MonitorClipboard, |
| AutoLookupSelection, |
| HotkeyLetter, |
| HotkeyModifier, |
| UsePopoverForLookup, |
| LastMainProfileId, |
| |
| |
| GuiLanguage, |
| AppearanceMode, |
| FontFace, |
| FontColor, |
| BackgroundColor, |
| AutoResizeImage, |
| } |
|
|
| impl ConfigKey { |
| |
| pub fn as_str(&self) -> &'static str { |
| match self { |
| |
| ConfigKey::AppOwner => "app_owner", |
| ConfigKey::AudioLibPath => "audio_lib_path", |
| ConfigKey::CustomFontPath => "custom_font_path", |
| ConfigKey::ExtraLibSearchPath => "extra_lib_search_path", |
| ConfigKey::GuiLanguage => "gui_language", |
| ConfigKey::AutoLookupClipboard => "auto_lookup_clipboard", |
| ConfigKey::MonitorClipboard => "monitor_clipboard", |
| ConfigKey::AutoLookupSelection => "auto_lookup_selection", |
| ConfigKey::HotkeyLetter => "hotkey_letter", |
| ConfigKey::HotkeyModifier => "hotkey_modifier", |
| ConfigKey::UsePopoverForLookup => "use_popover_for_lookup", |
| ConfigKey::LastMainProfileId => "last_main_profile_id", |
| |
| |
| ConfigKey::AppearanceMode => "appearance_mode", |
| ConfigKey::FontFace => "font_face", |
| ConfigKey::FontColor => "font_color", |
| ConfigKey::BackgroundColor => "background_color", |
| ConfigKey::AutoResizeImage => "auto_resize_image", |
| } |
| } |
| |
| |
| pub fn from_str(s: &str) -> Option<Self> { |
| match s { |
| |
| "app_owner" => Some(ConfigKey::AppOwner), |
| "audio_lib_path" => Some(ConfigKey::AudioLibPath), |
| "custom_font_path" => Some(ConfigKey::CustomFontPath), |
| "extra_lib_search_path" => Some(ConfigKey::ExtraLibSearchPath), |
| "gui_language" => Some(ConfigKey::GuiLanguage), |
| "auto_lookup_clipboard" => Some(ConfigKey::AutoLookupClipboard), |
| "monitor_clipboard" => Some(ConfigKey::MonitorClipboard), |
| "auto_lookup_selection" => Some(ConfigKey::AutoLookupSelection), |
| "hotkey_letter" => Some(ConfigKey::HotkeyLetter), |
| "hotkey_modifier" => Some(ConfigKey::HotkeyModifier), |
| "use_popover_for_lookup" => Some(ConfigKey::UsePopoverForLookup), |
| "last_main_profile_id" => Some(ConfigKey::LastMainProfileId), |
| |
| |
| "appearance_mode" => Some(ConfigKey::AppearanceMode), |
| "font_face" => Some(ConfigKey::FontFace), |
| "font_color" => Some(ConfigKey::FontColor), |
| "background_color" => Some(ConfigKey::BackgroundColor), |
| "auto_resize_image" => Some(ConfigKey::AutoResizeImage), |
| |
| _ => None, |
| } |
| } |
| } |
|
|
| |
| #[derive(Debug, Clone, Copy, PartialEq)] |
| pub enum ConfigSection { |
| Global, |
| View, |
| } |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct AppConfig { |
| |
| pub global_settings: Value, |
| |
| pub view_settings: Value, |
| |
| #[serde(skip)] |
| pub config_path: Option<PathBuf>, |
| } |
|
|
| impl Default for AppConfig { |
| fn default() -> Self { |
| |
| |
| |
| let global_settings_json = r#"{ |
| "config_version": "1.0", |
| "app_owner": "", |
| "audio_lib_path": "", |
| "gui_language": "", |
| "auto_sip": true, |
| "auto_lookup_clipboard": true, |
| "monitor_clipboard": true, |
| "auto_lookup_selection": false, |
| "hotkey_letter": "", |
| "hotkey_modifier": "", |
| "use_popover_for_lookup": true, |
| "use_tts": true, |
| "tts_engine_id": "", |
| "extra_lib_search_path": "" |
| }"#; |
|
|
| |
| let view_settings_json = r#"{ |
| "font_size": "", |
| "appearance_mode": "Auto", |
| "font_face": "", |
| "font_color": "", |
| "background_color": "", |
| "auto_resize_image": false, |
| "background_image": "", |
| "custom_font_path": "", |
| }"#; |
|
|
| let global_settings = serde_json::from_str(global_settings_json) |
| .unwrap_or(Value::Object(serde_json::Map::new())); |
| let view_settings = serde_json::from_str(view_settings_json) |
| .unwrap_or(Value::Object(serde_json::Map::new())); |
| |
| Self { |
| global_settings, |
| view_settings, |
| config_path: None, |
| } |
| } |
| } |
|
|
| impl AppConfig { |
| |
| pub fn new<P: AsRef<Path>>(config_path: P) -> Result<Self> { |
| let config_path = config_path.as_ref().to_path_buf(); |
| |
| |
| let mut config = if config_path.exists() { |
| Self::from_file(&config_path)? |
| } else { |
| |
| let default_config = Self::default(); |
| default_config.to_file(&config_path)?; |
| default_config |
| }; |
|
|
| |
| config.config_path = Some(config_path); |
| Ok(config) |
| } |
|
|
| |
| pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> { |
| let path_buf = path.as_ref().to_path_buf(); |
| let content = std::fs::read_to_string(&path_buf)?; |
| |
| let mut config: AppConfig = serde_json::from_str(&content)?; |
| |
| |
| config.config_path = Some(path_buf); |
| |
| Ok(config) |
| } |
|
|
| |
| pub fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> { |
| let content = serde_json::to_string_pretty(self)?; |
| |
| std::fs::write(path, content)?; |
| |
| Ok(()) |
| } |
|
|
| |
| pub fn save(&self) -> Result<()> { |
| if let Some(config_path) = &self.config_path { |
| self.to_file(config_path) |
| } else { |
| Err(ZdbError::invalid_parameter("配置文件路径未设置".to_string())) |
| } |
| } |
|
|
| |
| pub fn reload(&mut self) -> Result<()> { |
| if let Some(config_path) = &self.config_path { |
| let new_config = Self::from_file(config_path)?; |
| self.global_settings = new_config.global_settings; |
| self.view_settings = new_config.view_settings; |
| Ok(()) |
| } else { |
| Err(ZdbError::invalid_parameter("配置文件路径未设置".to_string())) |
| } |
| } |
| |
| |
| pub fn get_config<T>(&self, section: ConfigSection, config_key: ConfigKey) -> Result<T> |
| where |
| T: serde::de::DeserializeOwned, |
| { |
| let settings = match section { |
| ConfigSection::Global => &self.global_settings, |
| ConfigSection::View => &self.view_settings, |
| }; |
| |
| let key_str = config_key.as_str(); |
| if let Some(value) = settings.get(key_str) { |
| Ok(serde_json::from_value(value.clone())?) |
| } else { |
| Err(ZdbError::invalid_parameter(format!("配置项 {}.{} 不存在", |
| match section { ConfigSection::Global => "global", ConfigSection::View => "view" }, |
| key_str))) |
| } |
| } |
|
|
| |
| pub fn get_config_with_default<T>(&self, section: ConfigSection, config_key: ConfigKey, default: T) -> T |
| where |
| T: serde::de::DeserializeOwned + Default, |
| { |
| self.get_config(section, config_key).unwrap_or(default) |
| } |
|
|
| |
| pub fn set_config<T>(&mut self, section: ConfigSection, config_key: ConfigKey, value: T) -> Result<()> |
| where |
| T: serde::Serialize, |
| { |
| let key_str = config_key.as_str(); |
| let json_value = serde_json::to_value(value)?; |
| |
| let settings = match section { |
| ConfigSection::Global => &mut self.global_settings, |
| ConfigSection::View => &mut self.view_settings, |
| }; |
| |
| if let Some(obj) = settings.as_object_mut() { |
| obj.insert(key_str.to_string(), json_value); |
| Ok(()) |
| } else { |
| Err(ZdbError::invalid_parameter(format!("配置分组 {:?} 不是有效的对象", section))) |
| } |
| } |
|
|
| } |
|
|
|
|
| #[cfg(test)] |
| mod tests { |
| use super::*; |
| use std::env; |
|
|
| #[test] |
| fn test_default_config() { |
| let config = AppConfig::default(); |
| let appearance_mode: AppearanceMode = config.get_config(ConfigSection::View, ConfigKey::AppearanceMode).unwrap(); |
| |
| assert_eq!(appearance_mode, AppearanceMode::Auto); |
| } |
|
|
| #[test] |
| fn test_config_serialization() { |
| let config = AppConfig::default(); |
| let json = serde_json::to_string(&config).unwrap(); |
| let deserialized: AppConfig = serde_json::from_str(&json).unwrap(); |
| |
| let original_clipboard: bool = config.get_config(ConfigSection::Global, ConfigKey::MonitorClipboard).unwrap(); |
| let deserialized_clipboard: bool = deserialized.get_config(ConfigSection::Global, ConfigKey::MonitorClipboard).unwrap(); |
| |
| assert_eq!(original_clipboard, deserialized_clipboard); |
| } |
|
|
| #[test] |
| fn test_config_new_and_save() { |
| let temp_dir = env::temp_dir(); |
| let config_path = temp_dir.join("test_app_config.json"); |
| |
| |
| if config_path.exists() { |
| std::fs::remove_file(&config_path).unwrap(); |
| } |
|
|
| |
| let mut config = AppConfig::new(&config_path).unwrap(); |
| |
| |
| let lib_path: String = config.get_config(ConfigSection::Global, ConfigKey::ExtraLibSearchPath).unwrap(); |
| assert_eq!(lib_path, ""); |
| |
| |
| config.set_config(ConfigSection::Global, ConfigKey::ExtraLibSearchPath, "/test/path".to_string()).unwrap(); |
| config.set_config(ConfigSection::Global, ConfigKey::MonitorClipboard, false).unwrap(); |
| config.save().unwrap(); |
| |
| |
| assert!(config_path.exists()); |
| |
| |
| let loaded_config = AppConfig::from_file(&config_path).unwrap(); |
| let loaded_lib_path: String = loaded_config.get_config(ConfigSection::Global, ConfigKey::ExtraLibSearchPath).unwrap(); |
| let loaded_clipboard: bool = loaded_config.get_config(ConfigSection::Global, ConfigKey::MonitorClipboard).unwrap(); |
| assert_eq!(loaded_lib_path, "/test/path"); |
| assert_eq!(loaded_clipboard, false); |
| |
| |
| std::fs::remove_file(&config_path).unwrap(); |
| } |
|
|
| |
| #[test] |
| fn test_generic_config_methods() { |
| let mut config = AppConfig::default(); |
| |
| |
| let monitor_clipboard: bool = config.get_config(ConfigSection::Global, ConfigKey::MonitorClipboard).unwrap(); |
| assert_eq!(monitor_clipboard, true); |
| |
| |
| config.set_config(ConfigSection::Global, ConfigKey::MonitorClipboard, false).unwrap(); |
| let updated_clipboard: bool = config.get_config(ConfigSection::Global, ConfigKey::MonitorClipboard).unwrap(); |
| assert_eq!(updated_clipboard, false); |
| |
| |
| let default_lib_path: String = config.get_config_with_default(ConfigSection::Global, ConfigKey::ExtraLibSearchPath, "default_path".to_string()); |
| assert_eq!(default_lib_path, ""); |
| |
| |
| config.set_config(ConfigSection::Global, ConfigKey::GuiLanguage, "zh-CN".to_string()).unwrap(); |
| let language: String = config.get_config(ConfigSection::Global, ConfigKey::GuiLanguage).unwrap(); |
| assert_eq!(language, "zh-CN"); |
| |
| |
| config.set_config(ConfigSection::View, ConfigKey::AppearanceMode, AppearanceMode::Auto).unwrap(); |
| let appearance_mode: AppearanceMode = config.get_config(ConfigSection::View, ConfigKey::AppearanceMode).unwrap(); |
| assert_eq!(appearance_mode, AppearanceMode::Auto); |
| |
| |
| config.set_config(ConfigSection::Global, ConfigKey::MonitorClipboard, true).unwrap(); |
| let clipboard_enabled: bool = config.get_config_with_default(ConfigSection::Global, ConfigKey::MonitorClipboard, false); |
| assert!(clipboard_enabled); |
| } |
| } |