BlueGit

timfa posprint

Files

posprint / src / label_format.rs

label_format.rs

label_format.rs 6.9 KiB Download Raw
1//! Label formats for TSPL label printers, remembered per printer model in a
2//! separate file (`label_formats.json` next to `config.json`) so the existing
3//! config file format does not change.
4
5use std::collections::BTreeMap;
6use std::fs;
7use std::path::{Path, PathBuf};
8
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
12#[serde(rename_all = "snake_case")]
13pub enum MediaKind {
14 /// Labels separated by a gap or notch (gap sensor).
15 #[default]
16 Gap,
17 /// Black mark on the back (black-mark sensor).
18 BlackMark,
19 /// Continuous media, no separation.
20 Continuous,
21}
22
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct LabelFormat {
25 pub width_mm: f32,
26 pub height_mm: f32,
27 /// Gap or black-mark height in mm (ignored for continuous media).
28 #[serde(default = "default_gap")]
29 pub gap_mm: f32,
30 #[serde(default)]
31 pub media: MediaKind,
32 /// Print-head resolution (203 or 300 dpi; 600 for 600-dpi models).
33 #[serde(default = "default_dpi")]
34 pub dpi: u16,
35 /// Print rotated 180° (TSPL `DIRECTION 1`).
36 #[serde(default)]
37 pub rotate_180: bool,
38}
39
40fn default_gap() -> f32 {
41 3.0
42}
43fn default_dpi() -> u16 {
44 203
45}
46
47impl Default for LabelFormat {
48 fn default() -> Self {
49 Self {
50 width_mm: 100.0,
51 height_mm: 50.0,
52 gap_mm: default_gap(),
53 media: MediaKind::Gap,
54 dpi: default_dpi(),
55 rotate_180: false,
56 }
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum FormatError {
62 Width,
63 Height,
64 Gap,
65 Dpi,
66}
67
68impl LabelFormat {
69 /// Defaults for a model; the resolution is guessed from the model name
70 /// (e.g. `ATP-300 Pro` → 300 dpi). Shown pre-filled in the print dialog.
71 pub fn suggested_for_model(model: Option<&str>) -> Self {
72 let mut f = Self::default();
73 if let Some(m) = model {
74 let m = m.to_ascii_lowercase();
75 if m.contains("-300") || m.contains(" 300") || m.contains("344") || m.contains("346") {
76 f.dpi = 300;
77 } else if m.contains("-600") || m.contains(" 600") {
78 f.dpi = 600;
79 }
80 if m.contains("atp-300") || m.contains("atp-600") {
81 f.width_mm = 100.0;
82 }
83 }
84 f
85 }
86
87 pub fn validate(&self) -> Result<(), FormatError> {
88 if !(self.width_mm.is_finite() && (10.0..=120.0).contains(&self.width_mm)) {
89 return Err(FormatError::Width);
90 }
91 if !(self.height_mm.is_finite() && (5.0..=1000.0).contains(&self.height_mm)) {
92 return Err(FormatError::Height);
93 }
94 if self.media != MediaKind::Continuous
95 && !(self.gap_mm.is_finite() && (0.0..=25.4).contains(&self.gap_mm))
96 {
97 return Err(FormatError::Gap);
98 }
99 if ![203u16, 300, 600].contains(&self.dpi) {
100 return Err(FormatError::Dpi);
101 }
102 Ok(())
103 }
104
105 /// Dots per mm as used by TSPL (manual: 200 DPI = 8 dots/mm, 300 DPI = 12 dots/mm).
106 pub fn dots_per_mm(&self) -> u32 {
107 match self.dpi {
108 300 => 12,
109 600 => 24,
110 _ => 8,
111 }
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
116pub struct LabelFormatStore {
117 #[serde(default)]
118 pub formats: BTreeMap<String, LabelFormat>,
119}
120
121impl LabelFormatStore {
122 pub fn load() -> Self {
123 Self::load_from_path(&store_path())
124 }
125
126 pub fn load_from_path(path: &Path) -> Self {
127 fs::read_to_string(path)
128 .ok()
129 .and_then(|t| serde_json::from_str::<Self>(&t).ok())
130 .unwrap_or_default()
131 }
132
133 pub fn save(&self) -> Result<(), String> {
134 self.save_to_path(&store_path())
135 }
136
137 pub fn save_to_path(&self, path: &Path) -> Result<(), String> {
138 if let Some(parent) = path.parent() {
139 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
140 }
141 let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
142 fs::write(path, json).map_err(|e| e.to_string())
143 }
144
145 pub fn get(&self, model_key: &str) -> Option<&LabelFormat> {
146 self.formats.get(model_key.trim())
147 }
148
149 pub fn set(&mut self, model_key: &str, format: LabelFormat) {
150 let key = model_key.trim();
151 if !key.is_empty() {
152 self.formats.insert(key.to_string(), format);
153 }
154 }
155}
156
157/// `label_formats.json` next to the app config file.
158pub fn store_path() -> PathBuf {
159 let cfg = crate::config::config_path();
160 cfg.parent()
161 .map(|p| p.join("label_formats.json"))
162 .unwrap_or_else(|| PathBuf::from("label_formats.json"))
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn roundtrip_per_model() {
171 let dir = tempfile::tempdir().unwrap();
172 let path = dir.path().join("posprint").join("label_formats.json");
173 let mut store = LabelFormatStore::default();
174 let f = LabelFormat { width_mm: 50.0, height_mm: 30.0, gap_mm: 2.0, media: MediaKind::Gap, dpi: 300, rotate_180: false };
175 store.set("Altec ATP-300 Pro", f.clone());
176 store.set(" ", LabelFormat::default());
177 store.save_to_path(&path).unwrap();
178 let loaded = LabelFormatStore::load_from_path(&path);
179 assert_eq!(loaded.get("Altec ATP-300 Pro"), Some(&f));
180 assert_eq!(loaded.formats.len(), 1);
181 assert!(loaded.get("Other").is_none());
182 }
183
184 #[test]
185 fn corrupt_or_missing_file_is_empty() {
186 let dir = tempfile::tempdir().unwrap();
187 let path = dir.path().join("label_formats.json");
188 assert!(LabelFormatStore::load_from_path(&path).formats.is_empty());
189 fs::write(&path, "{not json").unwrap();
190 assert!(LabelFormatStore::load_from_path(&path).formats.is_empty());
191 }
192
193 #[test]
194 fn suggests_300_dpi_for_atp_300() {
195 assert_eq!(LabelFormat::suggested_for_model(Some("Altec ATP-300 Pro")).dpi, 300);
196 assert_eq!(LabelFormat::suggested_for_model(Some("TSC TE200")).dpi, 203);
197 assert_eq!(LabelFormat::suggested_for_model(None).dots_per_mm(), 8);
198 }
199
200 #[test]
201 fn validation() {
202 assert!(LabelFormat::default().validate().is_ok());
203 let mut f = LabelFormat::default();
204 f.width_mm = 0.0;
205 assert_eq!(f.validate(), Err(FormatError::Width));
206 f = LabelFormat::default();
207 f.height_mm = f32::NAN;
208 assert_eq!(f.validate(), Err(FormatError::Height));
209 f = LabelFormat::default();
210 f.gap_mm = 40.0;
211 assert_eq!(f.validate(), Err(FormatError::Gap));
212 f.media = MediaKind::Continuous;
213 assert!(f.validate().is_ok());
214 f.dpi = 150;
215 assert_eq!(f.validate(), Err(FormatError::Dpi));
216 }
217
218 #[test]
219 fn store_file_is_separate_from_config() {
220 assert_eq!(store_path().file_name().unwrap(), "label_formats.json");
221 assert_eq!(store_path().parent(), crate::config::config_path().parent());
222 }
223}