// Copyright (C) 2024 Rubén Beltrán del Río // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see https://map.tranquil.systems. use std::fs; use std::path::PathBuf; use crate::constants; use super::models::{UserPreferences, UserPreferencesJson}; /// Returns the XDG config directory path for preferences pub fn config_dir() -> PathBuf { dirs::config_dir() .unwrap_or_else(|| PathBuf::from(".")) .join(constants::APP_ID) } /// Returns the preferences file path pub fn preferences_path() -> PathBuf { config_dir().join("preferences.json") } /// Loads preferences from disk, returning defaults if not found pub fn load() -> UserPreferences { let path = preferences_path(); if path.exists() { match fs::read_to_string(&path) { Ok(content) => serde_json::from_str(&content).unwrap_or_default(), Err(_) => UserPreferences::default(), } } else { UserPreferences::default() } } /// Saves preferences to disk pub fn save(prefs: &UserPreferences) -> Result<(), std::io::Error> { let path = preferences_path(); if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } let content = serde_json::to_string_pretty(prefs).map_err(std::io::Error::other)?; fs::write(path, content) } /// Exports preferences to JSON string (for file export) pub fn export_json(prefs: &UserPreferences) -> Option { let json_prefs = prefs.to_json(); serde_json::to_string_pretty(&json_prefs).ok() } /// Imports preferences from JSON string (partial updates supported) /// Returns true on success, false on parse error pub fn import_json(prefs: &mut UserPreferences, json: &str) -> bool { match serde_json::from_str::(json) { Ok(imported) => { prefs.update_from_json(&imported); true } Err(_) => false, } } /// Saves preferences to a specific file path (for export dialog) pub fn export_to_file(prefs: &UserPreferences, path: &PathBuf) -> Result<(), std::io::Error> { let content = export_json(prefs).ok_or_else(|| std::io::Error::other("Serialization failed"))?; fs::write(path, content) } /// Loads preferences from a specific file path (for import dialog) pub fn import_from_file(prefs: &mut UserPreferences, path: &PathBuf) -> Result<(), std::io::Error> { let content = fs::read_to_string(path)?; if import_json(prefs, &content) { Ok(()) } else { Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Invalid preferences format", )) } }