//! Label formats for TSPL label printers, remembered per printer model in a //! separate file (`label_formats.json` next to `config.json`) so the existing //! config file format does not change. use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "snake_case")] pub enum MediaKind { /// Labels separated by a gap or notch (gap sensor). #[default] Gap, /// Black mark on the back (black-mark sensor). BlackMark, /// Continuous media, no separation. Continuous, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct LabelFormat { pub width_mm: f32, pub height_mm: f32, /// Gap or black-mark height in mm (ignored for continuous media). #[serde(default = "default_gap")] pub gap_mm: f32, #[serde(default)] pub media: MediaKind, /// Print-head resolution (203 or 300 dpi; 600 for 600-dpi models). #[serde(default = "default_dpi")] pub dpi: u16, /// Print rotated 180° (TSPL `DIRECTION 1`). #[serde(default)] pub rotate_180: bool, } fn default_gap() -> f32 { 3.0 } fn default_dpi() -> u16 { 203 } impl Default for LabelFormat { fn default() -> Self { Self { width_mm: 100.0, height_mm: 50.0, gap_mm: default_gap(), media: MediaKind::Gap, dpi: default_dpi(), rotate_180: false, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FormatError { Width, Height, Gap, Dpi, } impl LabelFormat { /// Defaults for a model; the resolution is guessed from the model name /// (e.g. `ATP-300 Pro` → 300 dpi). Shown pre-filled in the print dialog. pub fn suggested_for_model(model: Option<&str>) -> Self { let mut f = Self::default(); if let Some(m) = model { let m = m.to_ascii_lowercase(); if m.contains("-300") || m.contains(" 300") || m.contains("344") || m.contains("346") { f.dpi = 300; } else if m.contains("-600") || m.contains(" 600") { f.dpi = 600; } if m.contains("atp-300") || m.contains("atp-600") { f.width_mm = 100.0; } } f } pub fn validate(&self) -> Result<(), FormatError> { if !(self.width_mm.is_finite() && (10.0..=120.0).contains(&self.width_mm)) { return Err(FormatError::Width); } if !(self.height_mm.is_finite() && (5.0..=1000.0).contains(&self.height_mm)) { return Err(FormatError::Height); } if self.media != MediaKind::Continuous && !(self.gap_mm.is_finite() && (0.0..=25.4).contains(&self.gap_mm)) { return Err(FormatError::Gap); } if ![203u16, 300, 600].contains(&self.dpi) { return Err(FormatError::Dpi); } Ok(()) } /// Dots per mm as used by TSPL (manual: 200 DPI = 8 dots/mm, 300 DPI = 12 dots/mm). pub fn dots_per_mm(&self) -> u32 { match self.dpi { 300 => 12, 600 => 24, _ => 8, } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct LabelFormatStore { #[serde(default)] pub formats: BTreeMap, } impl LabelFormatStore { pub fn load() -> Self { Self::load_from_path(&store_path()) } pub fn load_from_path(path: &Path) -> Self { fs::read_to_string(path) .ok() .and_then(|t| serde_json::from_str::(&t).ok()) .unwrap_or_default() } pub fn save(&self) -> Result<(), String> { self.save_to_path(&store_path()) } pub fn save_to_path(&self, path: &Path) -> Result<(), String> { if let Some(parent) = path.parent() { fs::create_dir_all(parent).map_err(|e| e.to_string())?; } let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; fs::write(path, json).map_err(|e| e.to_string()) } pub fn get(&self, model_key: &str) -> Option<&LabelFormat> { self.formats.get(model_key.trim()) } pub fn set(&mut self, model_key: &str, format: LabelFormat) { let key = model_key.trim(); if !key.is_empty() { self.formats.insert(key.to_string(), format); } } } /// `label_formats.json` next to the app config file. pub fn store_path() -> PathBuf { let cfg = crate::config::config_path(); cfg.parent() .map(|p| p.join("label_formats.json")) .unwrap_or_else(|| PathBuf::from("label_formats.json")) } #[cfg(test)] mod tests { use super::*; #[test] fn roundtrip_per_model() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("posprint").join("label_formats.json"); let mut store = LabelFormatStore::default(); let f = LabelFormat { width_mm: 50.0, height_mm: 30.0, gap_mm: 2.0, media: MediaKind::Gap, dpi: 300, rotate_180: false }; store.set("Altec ATP-300 Pro", f.clone()); store.set(" ", LabelFormat::default()); store.save_to_path(&path).unwrap(); let loaded = LabelFormatStore::load_from_path(&path); assert_eq!(loaded.get("Altec ATP-300 Pro"), Some(&f)); assert_eq!(loaded.formats.len(), 1); assert!(loaded.get("Other").is_none()); } #[test] fn corrupt_or_missing_file_is_empty() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("label_formats.json"); assert!(LabelFormatStore::load_from_path(&path).formats.is_empty()); fs::write(&path, "{not json").unwrap(); assert!(LabelFormatStore::load_from_path(&path).formats.is_empty()); } #[test] fn suggests_300_dpi_for_atp_300() { assert_eq!(LabelFormat::suggested_for_model(Some("Altec ATP-300 Pro")).dpi, 300); assert_eq!(LabelFormat::suggested_for_model(Some("TSC TE200")).dpi, 203); assert_eq!(LabelFormat::suggested_for_model(None).dots_per_mm(), 8); } #[test] fn validation() { assert!(LabelFormat::default().validate().is_ok()); let mut f = LabelFormat::default(); f.width_mm = 0.0; assert_eq!(f.validate(), Err(FormatError::Width)); f = LabelFormat::default(); f.height_mm = f32::NAN; assert_eq!(f.validate(), Err(FormatError::Height)); f = LabelFormat::default(); f.gap_mm = 40.0; assert_eq!(f.validate(), Err(FormatError::Gap)); f.media = MediaKind::Continuous; assert!(f.validate().is_ok()); f.dpi = 150; assert_eq!(f.validate(), Err(FormatError::Dpi)); } #[test] fn store_file_is_separate_from_config() { assert_eq!(store_path().file_name().unwrap(), "label_formats.json"); assert_eq!(store_path().parent(), crate::config::config_path().parent()); } }