BlueGit

timfa posprint

Files

posprint / src / io / mod.rs

mod.rs

mod.rs 4.7 KiB Download Raw
1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4pub struct PosFile {
5 pub version: u32,
6 pub metadata: PosMetadata,
7 pub body: String,
8}
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11pub struct PosMetadata {
12 #[serde(skip_serializing_if = "Option::is_none")]
13 pub title: Option<String>,
14 pub page_width_mm: f32,
15 #[serde(skip_serializing_if = "Option::is_none")]
16 pub chars_per_line: Option<u32>,
17 #[serde(skip_serializing_if = "Option::is_none")]
18 pub codepage: Option<String>,
19 #[serde(default = "default_cut_after_print")]
20 pub cut_after_print: bool,
21}
22
23fn default_cut_after_print() -> bool {
24 true
25}
26
27impl Default for PosMetadata {
28 fn default() -> Self {
29 Self {
30 title: None,
31 page_width_mm: 80.0,
32 chars_per_line: None,
33 codepage: Some("CP437".into()),
34 cut_after_print: true,
35 }
36 }
37}
38
39impl PosFile {
40 pub fn new(body: impl Into<String>) -> Self {
41 Self {
42 version: 1,
43 metadata: PosMetadata::default(),
44 body: body.into(),
45 }
46 }
47
48 pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
49 serde_json::to_string_pretty(self)
50 }
51
52 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
53 serde_json::from_str(json)
54 }
55
56 pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), SaveError> {
57 let json = self.to_json_pretty()?;
58 std::fs::write(path, json)?;
59 Ok(())
60 }
61
62 pub fn load_from_path(path: &std::path::Path) -> Result<Self, LoadError> {
63 let json = std::fs::read_to_string(path)?;
64 let file = PosFile::from_json(&json).map_err(LoadError::Json)?;
65 if file.version != 1 {
66 return Err(LoadError::UnsupportedVersion(file.version));
67 }
68 Ok(file)
69 }
70}
71
72impl PosMetadata {
73 pub fn printable_dots(&self) -> u16 {
74 // 203 DPI is common for thermal printers
75 (self.page_width_mm / 25.4 * 203.0).round() as u16
76 }
77
78 pub fn chars_per_line(&self) -> u32 {
79 self.chars_per_line.unwrap_or_else(|| {
80 if self.page_width_mm <= 58.0 {
81 32
82 } else {
83 48
84 }
85 })
86 }
87}
88
89#[derive(Debug)]
90pub enum SaveError {
91 Json(serde_json::Error),
92 Io(std::io::Error),
93}
94
95impl From<serde_json::Error> for SaveError {
96 fn from(value: serde_json::Error) -> Self {
97 Self::Json(value)
98 }
99}
100
101impl From<std::io::Error> for SaveError {
102 fn from(value: std::io::Error) -> Self {
103 Self::Io(value)
104 }
105}
106
107#[derive(Debug)]
108pub enum LoadError {
109 Io(std::io::Error),
110 Json(serde_json::Error),
111 UnsupportedVersion(u32),
112}
113
114impl From<std::io::Error> for LoadError {
115 fn from(value: std::io::Error) -> Self {
116 Self::Io(value)
117 }
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123
124 #[test]
125 fn roundtrip_json() {
126 let file = PosFile::new("# Test");
127 let json = file.to_json_pretty().unwrap();
128 assert!(!json.contains("default_feed_before_cut"));
129 let loaded = PosFile::from_json(&json).unwrap();
130 assert_eq!(loaded, file);
131 }
132
133 #[test]
134 fn chars_per_line_defaults() {
135 let narrow = PosMetadata {
136 page_width_mm: 58.0,
137 ..Default::default()
138 };
139 assert_eq!(narrow.chars_per_line(), 32);
140 let wide = PosMetadata::default();
141 assert_eq!(wide.chars_per_line(), 48);
142 }
143
144 #[test]
145 fn ignores_legacy_preview_mode_field() {
146 let json = r#"{
147 "version": 1,
148 "metadata": {
149 "page_width_mm": 80.0,
150 "preview_mode": "autoscale",
151 "cut_after_print": true,
152 "default_feed_before_cut": 4
153 },
154 "body": "hello"
155 }"#;
156 let loaded = PosFile::from_json(json).unwrap();
157 assert_eq!(loaded.body, "hello");
158 assert!(!loaded.to_json_pretty().unwrap().contains("preview_mode"));
159 assert!(
160 !loaded
161 .to_json_pretty()
162 .unwrap()
163 .contains("default_feed_before_cut")
164 );
165 }
166
167 #[test]
168 fn save_and_load_file() {
169 let dir = tempfile::tempdir().unwrap();
170 let path = dir.path().join("test.pos");
171 let file = PosFile::new("hello");
172 file.save_to_path(&path).unwrap();
173 let loaded = PosFile::load_from_path(&path).unwrap();
174 assert_eq!(loaded.body, "hello");
175 }
176}