BlueGit

timfa posprint

Files

posprint / src / io / mod.rs

mod.rs

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