// Map, wardley map editor for linux // Copyright (C) 2026 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 Affero 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . use std::fs; use std::path::PathBuf; use crate::info; 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(info::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(preferences: &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(preferences).map_err(std::io::Error::other)?; fs::write(path, content) } /// Exports preferences to JSON string (for file export) pub fn export_json(preferences: &UserPreferences) -> Option { let json_preferences = preferences.to_json(); serde_json::to_string_pretty(&json_preferences).ok() } /// Imports preferences from JSON string (partial updates supported) /// Returns true on success, false on parse error pub fn import_json(preferences: &mut UserPreferences, json: &str) -> bool { match serde_json::from_str::(json) { Ok(imported) => { preferences.update_from_json(&imported); true } Err(_) => false, } } /// Saves preferences to a specific file path (for export dialog) pub fn export_to_file(preferences: &UserPreferences, path: &PathBuf) -> Result<(), std::io::Error> { let content = export_json(preferences).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( preferences: &mut UserPreferences, path: &PathBuf, ) -> Result<(), std::io::Error> { let content = fs::read_to_string(path)?; if import_json(preferences, &content) { Ok(()) } else { Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Invalid preferences format", )) } }