//! Persisted app preferences (trusted URL origins, default page width, LAN printers). use std::fs; use std::path::PathBuf; use serde::{Deserialize, Serialize}; use crate::print::LanPrinterCacheEntry; const CONFIG_VERSION: u32 = 1; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AppConfig { #[serde(default = "default_config_version")] pub version: u32, /// Default paper width for **New** documents (mm). #[serde(default = "default_page_width_mm")] pub default_page_width_mm: f32, /// Hostnames allowed to use `noconfirm=1` without asking again. #[serde(default)] pub trusted_origins: Vec, /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, `net:…`, or `manual:…`). #[serde(default)] pub last_printer_key: Option, /// When true, the print dialog discovers LAN printers via TCP 9100. #[serde(default)] pub lan_printers_enabled: bool, /// Last known LAN printers (validated first on the next discovery). #[serde(default)] pub lan_printer_cache: Vec, } fn default_config_version() -> u32 { CONFIG_VERSION } fn default_page_width_mm() -> f32 { 80.0 } impl Default for AppConfig { fn default() -> Self { Self { version: CONFIG_VERSION, default_page_width_mm: default_page_width_mm(), trusted_origins: Vec::new(), last_printer_key: None, lan_printers_enabled: false, lan_printer_cache: Vec::new(), } } } impl AppConfig { pub fn load() -> Self { Self::load_from_path(&config_path()) } pub fn load_from_path(path: &std::path::Path) -> Self { match fs::read_to_string(path) { Ok(text) => match serde_json::from_str::(&text) { Ok(mut cfg) => { cfg.normalize(); cfg } Err(_) => Self::default(), }, Err(_) => Self::default(), } } pub fn save(&self) -> Result<(), String> { self.save_to_path(&config_path()) } pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> { if let Some(parent) = path.parent() { fs::create_dir_all(parent).map_err(|e| e.to_string())?; } let mut cfg = self.clone(); cfg.normalize(); let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?; fs::write(path, json).map_err(|e| e.to_string()) } pub fn is_trusted(&self, origin: &str) -> bool { let Some(host) = normalize_origin(origin) else { return false; }; self.trusted_origins.iter().any(|o| o == &host) } pub fn trust_origin(&mut self, origin: &str) -> bool { let Some(host) = normalize_origin(origin) else { return false; }; if !self.trusted_origins.iter().any(|o| o == &host) { self.trusted_origins.push(host); self.trusted_origins.sort(); } true } pub fn revoke_origin(&mut self, origin: &str) { let Some(host) = normalize_origin(origin) else { return; }; self.trusted_origins.retain(|o| o != &host); } pub fn remember_printer(&mut self, key: impl Into) { let key = key.into(); if key.is_empty() { return; } self.last_printer_key = Some(key); } pub fn clear_lan_printer_cache(&mut self) { self.lan_printer_cache.clear(); } fn normalize(&mut self) { self.version = CONFIG_VERSION; if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 { self.default_page_width_mm = 40.0; } else if self.default_page_width_mm > 120.0 { self.default_page_width_mm = 120.0; } let mut hosts: Vec = self .trusted_origins .iter() .filter_map(|o| normalize_origin(o)) .collect(); hosts.sort(); hosts.dedup(); self.trusted_origins = hosts; if let Some(key) = &self.last_printer_key { let trimmed = key.trim(); if trimmed.is_empty() { self.last_printer_key = None; } else if trimmed != key.as_str() { self.last_printer_key = Some(trimmed.to_string()); } } self.lan_printer_cache.retain(|e| !e.host.trim().is_empty() && e.port != 0); for entry in &mut self.lan_printer_cache { entry.host = entry.host.trim().to_string(); if entry.port == 0 { entry.port = crate::print::DEFAULT_PORT; } } self.lan_printer_cache .sort_by(|a, b| (&a.host, a.port).cmp(&(&b.host, b.port))); self.lan_printer_cache .dedup_by(|a, b| a.host == b.host && a.port == b.port); } } /// Config file path: `%APPDATA%/posprint/config.json` (Windows) or /// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix). pub fn config_path() -> PathBuf { #[cfg(windows)] { let base = std::env::var_os("APPDATA") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(".")); base.join("posprint").join("config.json") } #[cfg(not(windows))] { let base = std::env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) .or_else(|| { std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")) }) .unwrap_or_else(|| PathBuf::from(".")); base.join("posprint").join("config.json") } } /// Normalize a caller-supplied origin to a lowercase hostname. /// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`. pub fn normalize_origin(raw: &str) -> Option { let s = raw.trim(); if s.is_empty() { return None; } let without_scheme = s .strip_prefix("https://") .or_else(|| s.strip_prefix("http://")) .or_else(|| s.strip_prefix("HTTPS://")) .or_else(|| s.strip_prefix("HTTP://")) .unwrap_or(s); let host_port = without_scheme.split('/').next()?.trim(); if host_port.is_empty() { return None; } // Drop port for trust matching (example.com:443 → example.com). let host = host_port.split(':').next()?.trim(); if host.is_empty() { return None; } Some(host.to_ascii_lowercase()) } #[cfg(test)] mod tests { use super::*; #[test] fn normalize_strips_scheme_path_and_port() { assert_eq!( normalize_origin("https://Shop.Example.com/checkout").as_deref(), Some("shop.example.com") ); assert_eq!( normalize_origin("http://localhost:5173/").as_deref(), Some("localhost") ); assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com")); assert_eq!(normalize_origin(" ").as_deref(), None); } #[test] fn trust_and_revoke_roundtrip() { let mut cfg = AppConfig::default(); assert!(!cfg.is_trusted("https://a.example")); assert!(cfg.trust_origin("https://a.example/x")); assert!(cfg.is_trusted("a.example")); assert!(cfg.is_trusted("HTTPS://A.Example")); cfg.revoke_origin("a.example"); assert!(!cfg.is_trusted("a.example")); } #[test] fn save_load_roundtrip_in_temp_dir() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("posprint").join("config.json"); let mut cfg = AppConfig::default(); cfg.default_page_width_mm = 58.0; cfg.trust_origin("pos.example"); cfg.remember_printer("winspool:POS-58"); cfg.lan_printers_enabled = true; cfg.lan_printer_cache.push(LanPrinterCacheEntry::new("192.168.1.50", 9100)); cfg.save_to_path(&path).unwrap(); let loaded = AppConfig::load_from_path(&path); assert_eq!(loaded.default_page_width_mm, 58.0); assert!(loaded.is_trusted("pos.example")); assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58")); assert!(loaded.lan_printers_enabled); assert_eq!(loaded.lan_printer_cache.len(), 1); assert_eq!(loaded.lan_printer_cache[0].host, "192.168.1.50"); } #[test] fn lan_disabled_by_default() { assert!(!AppConfig::default().lan_printers_enabled); assert!(AppConfig::default().lan_printer_cache.is_empty()); } }