| 1 | //! Persisted app preferences (default page width, last printer).
|
| 2 |
|
| 3 | use std::fs;
|
| 4 | use std::path::PathBuf;
|
| 5 |
|
| 6 | use serde::{Deserialize, Serialize};
|
| 7 |
|
| 8 | const CONFIG_VERSION: u32 = 1;
|
| 9 |
|
| 10 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
| 11 | pub struct AppConfig {
|
| 12 | #[serde(default = "default_config_version")]
|
| 13 | pub version: u32,
|
| 14 | /// Default paper width for **New** documents (mm).
|
| 15 | #[serde(default = "default_page_width_mm")]
|
| 16 | pub default_page_width_mm: f32,
|
| 17 | /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
|
| 18 | #[serde(default)]
|
| 19 | pub last_printer_key: Option<String>,
|
| 20 | /// Ignored legacy field from older configs (trusted noconfirm hosts).
|
| 21 | #[serde(default, skip_serializing)]
|
| 22 | trusted_origins: Vec<String>,
|
| 23 | }
|
| 24 |
|
| 25 | fn default_config_version() -> u32 {
|
| 26 | CONFIG_VERSION
|
| 27 | }
|
| 28 |
|
| 29 | fn default_page_width_mm() -> f32 {
|
| 30 | 80.0
|
| 31 | }
|
| 32 |
|
| 33 | impl Default for AppConfig {
|
| 34 | fn default() -> Self {
|
| 35 | Self {
|
| 36 | version: CONFIG_VERSION,
|
| 37 | default_page_width_mm: default_page_width_mm(),
|
| 38 | last_printer_key: None,
|
| 39 | trusted_origins: Vec::new(),
|
| 40 | }
|
| 41 | }
|
| 42 | }
|
| 43 |
|
| 44 | impl AppConfig {
|
| 45 | pub fn load() -> Self {
|
| 46 | Self::load_from_path(&config_path())
|
| 47 | }
|
| 48 |
|
| 49 | pub fn load_from_path(path: &std::path::Path) -> Self {
|
| 50 | match fs::read_to_string(path) {
|
| 51 | Ok(text) => match serde_json::from_str::<AppConfig>(&text) {
|
| 52 | Ok(mut cfg) => {
|
| 53 | cfg.normalize();
|
| 54 | cfg
|
| 55 | }
|
| 56 | Err(_) => Self::default(),
|
| 57 | },
|
| 58 | Err(_) => Self::default(),
|
| 59 | }
|
| 60 | }
|
| 61 |
|
| 62 | pub fn save(&self) -> Result<(), String> {
|
| 63 | self.save_to_path(&config_path())
|
| 64 | }
|
| 65 |
|
| 66 | pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> {
|
| 67 | if let Some(parent) = path.parent() {
|
| 68 | fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
| 69 | }
|
| 70 | let mut cfg = self.clone();
|
| 71 | cfg.normalize();
|
| 72 | let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
|
| 73 | fs::write(path, json).map_err(|e| e.to_string())
|
| 74 | }
|
| 75 |
|
| 76 | pub fn remember_printer(&mut self, key: impl Into<String>) {
|
| 77 | let key = key.into();
|
| 78 | if key.is_empty() {
|
| 79 | return;
|
| 80 | }
|
| 81 | self.last_printer_key = Some(key);
|
| 82 | }
|
| 83 |
|
| 84 | fn normalize(&mut self) {
|
| 85 | self.version = CONFIG_VERSION;
|
| 86 | self.trusted_origins.clear();
|
| 87 | if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
|
| 88 | self.default_page_width_mm = 40.0;
|
| 89 | } else if self.default_page_width_mm > 120.0 {
|
| 90 | self.default_page_width_mm = 120.0;
|
| 91 | }
|
| 92 | if let Some(key) = &self.last_printer_key {
|
| 93 | let trimmed = key.trim();
|
| 94 | if trimmed.is_empty() {
|
| 95 | self.last_printer_key = None;
|
| 96 | } else if trimmed != key.as_str() {
|
| 97 | self.last_printer_key = Some(trimmed.to_string());
|
| 98 | }
|
| 99 | }
|
| 100 | }
|
| 101 | }
|
| 102 |
|
| 103 | /// Config file path: `%APPDATA%/posprint/config.json` (Windows) or
|
| 104 | /// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix).
|
| 105 | pub fn config_path() -> PathBuf {
|
| 106 | #[cfg(windows)]
|
| 107 | {
|
| 108 | let base = std::env::var_os("APPDATA")
|
| 109 | .map(PathBuf::from)
|
| 110 | .unwrap_or_else(|| PathBuf::from("."));
|
| 111 | base.join("posprint").join("config.json")
|
| 112 | }
|
| 113 | #[cfg(not(windows))]
|
| 114 | {
|
| 115 | let base = std::env::var_os("XDG_CONFIG_HOME")
|
| 116 | .map(PathBuf::from)
|
| 117 | .or_else(|| {
|
| 118 | std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))
|
| 119 | })
|
| 120 | .unwrap_or_else(|| PathBuf::from("."));
|
| 121 | base.join("posprint").join("config.json")
|
| 122 | }
|
| 123 | }
|
| 124 |
|
| 125 | #[cfg(test)]
|
| 126 | mod tests {
|
| 127 | use super::*;
|
| 128 |
|
| 129 | #[test]
|
| 130 | fn save_load_roundtrip_in_temp_dir() {
|
| 131 | let dir = tempfile::tempdir().unwrap();
|
| 132 | let path = dir.path().join("posprint").join("config.json");
|
| 133 | let mut cfg = AppConfig::default();
|
| 134 | cfg.default_page_width_mm = 58.0;
|
| 135 | cfg.remember_printer("winspool:POS-58");
|
| 136 | cfg.save_to_path(&path).unwrap();
|
| 137 |
|
| 138 | let loaded = AppConfig::load_from_path(&path);
|
| 139 | assert_eq!(loaded.default_page_width_mm, 58.0);
|
| 140 | assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
|
| 141 | }
|
| 142 |
|
| 143 | #[test]
|
| 144 | fn loads_legacy_trusted_origins_without_keeping_them() {
|
| 145 | let dir = tempfile::tempdir().unwrap();
|
| 146 | let path = dir.path().join("config.json");
|
| 147 | fs::write(
|
| 148 | &path,
|
| 149 | r#"{"version":1,"default_page_width_mm":80.0,"trusted_origins":["shop.example"],"last_printer_key":null}"#,
|
| 150 | )
|
| 151 | .unwrap();
|
| 152 | let loaded = AppConfig::load_from_path(&path);
|
| 153 | assert!(loaded.trusted_origins.is_empty());
|
| 154 | loaded.save_to_path(&path).unwrap();
|
| 155 | let text = fs::read_to_string(&path).unwrap();
|
| 156 | assert!(!text.contains("trusted_origins"));
|
| 157 | }
|
| 158 | }
|