BlueGit

timfa posprint

Add ESC/POS encoder, preview renderer, and USB-serial printing.

Hand-written ESC/POS commands for text, barcodes, QR, and images.
USB-serial discovery with mock transport for unit tests.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-07-15 · 4 months ago

Hash
ef2c42b7b08032e3b7e292ed022a6806fa1e56d7
Parent
b04fb39e
3 files changed +573 −0
src/escpos.rs added +299 −0
@@ -0,0 +1,299 @@
1 use std::path::Path;
2
3 use crate::dsl::{
4 Align, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc,
5 };
6 use crate::io::PosMetadata;
7
8 #[derive(Debug)]
9 pub enum EscPosError {
10 Image(String),
11 Barcode(String),
12 Io(String),
13 }
14
15 pub struct EscPosEncoder {
16 buffer: Vec<u8>,
17 metadata: PosMetadata,
18 base_dir: Option<std::path::PathBuf>,
19 }
20
21 impl EscPosEncoder {
22 pub fn new(metadata: PosMetadata) -> Self {
23 Self {
24 buffer: Vec::new(),
25 metadata,
26 base_dir: None,
27 }
28 }
29
30 pub fn with_base_dir(mut self, base_dir: impl AsRef<Path>) -> Self {
31 self.base_dir = Some(base_dir.as_ref().to_path_buf());
32 self
33 }
34
35 pub fn encode_document(&mut self, document: &Document) -> Result<&[u8], EscPosError> {
36 self.buffer.clear();
37 self.init();
38 for block in &document.blocks {
39 self.encode_block(block)?;
40 }
41 if self.metadata.cut_after_print && !document.blocks.iter().any(|b| matches!(b, Block::Cut)) {
42 self.feed(self.metadata.default_feed_before_cut);
43 self.cut();
44 }
45 Ok(&self.buffer)
46 }
47
48 pub fn into_bytes(self) -> Vec<u8> {
49 self.buffer
50 }
51
52 fn init(&mut self) {
53 self.buffer.extend_from_slice(&[0x1B, b'@']);
54 // ESC t 0 = CP437
55 self.buffer.extend_from_slice(&[0x1B, b't', 0]);
56 }
57
58 fn encode_block(&mut self, block: &Block) -> Result<(), EscPosError> {
59 match block {
60 Block::Paragraph { align, inlines } => {
61 self.set_align(*align);
62 let line = inlines_to_plain(inlines);
63 for part in line.split('\n') {
64 self.writeln(part);
65 }
66 }
67 Block::Heading { level, inlines } => {
68 self.set_align(Align::Left);
69 if *level == 1 {
70 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
71 } else {
72 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
73 }
74 self.writeln(&inlines_to_plain(inlines));
75 if *level == 1 {
76 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
77 } else {
78 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
79 }
80 }
81 Block::Rule => {
82 let width = self.metadata.chars_per_line() as usize;
83 self.writeln(&"-".repeat(width));
84 }
85 Block::Feed(n) => self.feed(*n),
86 Block::Cut => self.cut(),
87 Block::Image { path, width, align } => {
88 self.set_align(*align);
89 self.encode_image(path, *width)?;
90 }
91 Block::Barcode {
92 symbology,
93 data,
94 height,
95 align,
96 show_text,
97 } => {
98 self.set_align(*align);
99 self.encode_barcode(*symbology, data, *height, *show_text)?;
100 }
101 Block::Qr {
102 data,
103 size,
104 ecc,
105 align,
106 } => {
107 self.set_align(*align);
108 self.encode_qr(data, *size, *ecc)?;
109 }
110 }
111 Ok(())
112 }
113
114 fn set_align(&mut self, align: Align) {
115 let n = match align {
116 Align::Left => 0,
117 Align::Center => 1,
118 Align::Right => 2,
119 };
120 self.buffer.extend_from_slice(&[0x1B, b'a', n]);
121 }
122
123 fn writeln(&mut self, text: &str) {
124 self.buffer.extend_from_slice(text.as_bytes());
125 self.buffer.push(b'\n');
126 }
127
128 fn feed(&mut self, lines: u8) {
129 self.buffer.extend_from_slice(&[0x1B, b'd', lines]);
130 }
131
132 fn cut(&mut self) {
133 self.buffer.extend_from_slice(&[0x1D, b'V', 66, 0]);
134 }
135
136 fn encode_barcode(
137 &mut self,
138 symbology: BarcodeSymbology,
139 data: &str,
140 height: u8,
141 show_text: bool,
142 ) -> Result<(), EscPosError> {
143 self.buffer.extend_from_slice(&[0x1D, b'h', height]);
144 self.buffer.extend_from_slice(&[0x1D, b'H', if show_text { 2 } else { 0 }]);
145 match symbology {
146 BarcodeSymbology::Code128 => {
147 let bytes = data.as_bytes();
148 self.buffer.extend_from_slice(&[0x1D, b'k', 73, bytes.len() as u8]);
149 self.buffer.extend_from_slice(bytes);
150 }
151 BarcodeSymbology::Ean13 => {
152 if data.len() != 12 && data.len() != 13 {
153 return Err(EscPosError::Barcode("EAN13 requires 12-13 digits".into()));
154 }
155 self.buffer.extend_from_slice(&[0x1D, b'k', 67, data.len() as u8]);
156 self.buffer.extend_from_slice(data.as_bytes());
157 }
158 BarcodeSymbology::Ean8 => {
159 if data.len() != 7 && data.len() != 8 {
160 return Err(EscPosError::Barcode("EAN8 requires 7-8 digits".into()));
161 }
162 self.buffer.extend_from_slice(&[0x1D, b'k', 68, data.len() as u8]);
163 self.buffer.extend_from_slice(data.as_bytes());
164 }
165 BarcodeSymbology::Code39 => {
166 self.buffer.extend_from_slice(&[0x1D, b'k', 69, data.len() as u8]);
167 self.buffer.extend_from_slice(data.as_bytes());
168 }
169 }
170 self.buffer.push(b'\n');
171 Ok(())
172 }
173
174 fn encode_qr(&mut self, data: &str, size: u8, ecc: QrEcc) -> Result<(), EscPosError> {
175 let ecc_level = match ecc {
176 QrEcc::L => 48,
177 QrEcc::M => 49,
178 QrEcc::Q => 50,
179 QrEcc::H => 51,
180 };
181 let store = data.as_bytes();
182 let len = store.len() + 3;
183 let p_l = (len & 0xFF) as u8;
184 let p_h = ((len >> 8) & 0xFF) as u8;
185
186 // Model 2
187 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 4, 0, 49, 65, 50, 0]);
188 // Module size
189 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 3, 0, 49, 67, size]);
190 // Error correction
191 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 3, 0, 49, 69, ecc_level]);
192 // Store data
193 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', p_l, p_h, 49, 80, 48]);
194 self.buffer.extend_from_slice(store);
195 // Print
196 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 3, 0, 49, 81, 48]);
197 self.buffer.push(b'\n');
198 Ok(())
199 }
200
201 fn encode_image(&mut self, path: &str, width: ImageWidth) -> Result<(), EscPosError> {
202 let resolved = resolve_image_path(path, self.base_dir.as_deref());
203 let img = image::open(&resolved).map_err(|e| EscPosError::Image(e.to_string()))?;
204 let target_width = match width {
205 ImageWidth::Percent(pct) => {
206 (self.metadata.printable_dots() as u32 * pct as u32 / 100) as u32
207 }
208 ImageWidth::Dots(d) => d as u32,
209 ImageWidth::Default => self.metadata.printable_dots() as u32,
210 };
211 let gray = img.to_luma8();
212 let (w, h) = gray.dimensions();
213 let new_w = target_width.min(w);
214 let new_h = (h as f32 * (new_w as f32 / w as f32)) as u32;
215 let resized = image::imageops::resize(
216 &gray,
217 new_w,
218 new_h,
219 image::imageops::FilterType::Nearest,
220 );
221 let bytes_per_row = ((new_w + 7) / 8) as usize;
222 let mut raster = vec![0u8; bytes_per_row * new_h as usize];
223 for y in 0..new_h {
224 for x in 0..new_w {
225 let pixel = resized.get_pixel(x, y).0[0];
226 if pixel < 128 {
227 let byte_index = (y as usize * bytes_per_row) + (x as usize / 8);
228 let bit = 7 - (x % 8);
229 raster[byte_index] |= 1 << bit;
230 }
231 }
232 }
233 let x_l = (bytes_per_row & 0xFF) as u8;
234 let x_h = ((bytes_per_row >> 8) & 0xFF) as u8;
235 let y_l = (new_h & 0xFF) as u8;
236 let y_h = ((new_h >> 8) & 0xFF) as u8;
237 self.buffer.extend_from_slice(&[0x1D, b'v', 0, 0, x_l, x_h, y_l, y_h]);
238 self.buffer.extend_from_slice(&raster);
239 self.buffer.push(b'\n');
240 Ok(())
241 }
242 }
243
244 fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> std::path::PathBuf {
245 let p = Path::new(path);
246 if p.is_absolute() {
247 p.to_path_buf()
248 } else if let Some(base) = base_dir {
249 base.join(p)
250 } else {
251 p.to_path_buf()
252 }
253 }
254
255 fn inlines_to_plain(inlines: &[Inline]) -> String {
256 let mut out = String::new();
257 for inline in inlines {
258 match inline {
259 Inline::Text(t) | Inline::Code(t) => out.push_str(t),
260 Inline::Param(t) => out.push_str(t),
261 Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_plain(inner)),
262 }
263 }
264 out
265 }
266
267 #[cfg(test)]
268 mod tests {
269 use super::*;
270 use crate::dsl::parse;
271
272 #[test]
273 fn encodes_init_and_text() {
274 let doc = parse("Hello").unwrap();
275 let mut enc = EscPosEncoder::new(PosMetadata::default());
276 let bytes = enc.encode_document(&doc).unwrap();
277 assert_eq!(&bytes[0..2], &[0x1B, b'@']);
278 assert!(bytes.windows(5).any(|w| w == b"Hello"));
279 }
280
281 #[test]
282 fn encodes_cut_directive() {
283 let doc = parse("@cut").unwrap();
284 let mut enc = EscPosEncoder::new(PosMetadata {
285 cut_after_print: false,
286 ..Default::default()
287 });
288 let bytes = enc.encode_document(&doc).unwrap();
289 assert!(bytes.windows(3).any(|w| w == [0x1D, b'V', 66]));
290 }
291
292 #[test]
293 fn auto_cut_when_enabled() {
294 let doc = parse("x").unwrap();
295 let mut enc = EscPosEncoder::new(PosMetadata::default());
296 let bytes = enc.encode_document(&doc).unwrap();
297 assert!(bytes.ends_with(&[0x1D, b'V', 66, 0]));
298 }
299 }
@@ -0,0 +1,299 @@
1use std::path::Path;
2
3use crate::dsl::{
4 Align, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc,
5};
6use crate::io::PosMetadata;
7
8#[derive(Debug)]
9pub enum EscPosError {
10 Image(String),
11 Barcode(String),
12 Io(String),
13}
14
15pub struct EscPosEncoder {
16 buffer: Vec<u8>,
17 metadata: PosMetadata,
18 base_dir: Option<std::path::PathBuf>,
19}
20
21impl EscPosEncoder {
22 pub fn new(metadata: PosMetadata) -> Self {
23 Self {
24 buffer: Vec::new(),
25 metadata,
26 base_dir: None,
27 }
28 }
29
30 pub fn with_base_dir(mut self, base_dir: impl AsRef<Path>) -> Self {
31 self.base_dir = Some(base_dir.as_ref().to_path_buf());
32 self
33 }
34
35 pub fn encode_document(&mut self, document: &Document) -> Result<&[u8], EscPosError> {
36 self.buffer.clear();
37 self.init();
38 for block in &document.blocks {
39 self.encode_block(block)?;
40 }
41 if self.metadata.cut_after_print && !document.blocks.iter().any(|b| matches!(b, Block::Cut)) {
42 self.feed(self.metadata.default_feed_before_cut);
43 self.cut();
44 }
45 Ok(&self.buffer)
46 }
47
48 pub fn into_bytes(self) -> Vec<u8> {
49 self.buffer
50 }
51
52 fn init(&mut self) {
53 self.buffer.extend_from_slice(&[0x1B, b'@']);
54 // ESC t 0 = CP437
55 self.buffer.extend_from_slice(&[0x1B, b't', 0]);
56 }
57
58 fn encode_block(&mut self, block: &Block) -> Result<(), EscPosError> {
59 match block {
60 Block::Paragraph { align, inlines } => {
61 self.set_align(*align);
62 let line = inlines_to_plain(inlines);
63 for part in line.split('\n') {
64 self.writeln(part);
65 }
66 }
67 Block::Heading { level, inlines } => {
68 self.set_align(Align::Left);
69 if *level == 1 {
70 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
71 } else {
72 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
73 }
74 self.writeln(&inlines_to_plain(inlines));
75 if *level == 1 {
76 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
77 } else {
78 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
79 }
80 }
81 Block::Rule => {
82 let width = self.metadata.chars_per_line() as usize;
83 self.writeln(&"-".repeat(width));
84 }
85 Block::Feed(n) => self.feed(*n),
86 Block::Cut => self.cut(),
87 Block::Image { path, width, align } => {
88 self.set_align(*align);
89 self.encode_image(path, *width)?;
90 }
91 Block::Barcode {
92 symbology,
93 data,
94 height,
95 align,
96 show_text,
97 } => {
98 self.set_align(*align);
99 self.encode_barcode(*symbology, data, *height, *show_text)?;
100 }
101 Block::Qr {
102 data,
103 size,
104 ecc,
105 align,
106 } => {
107 self.set_align(*align);
108 self.encode_qr(data, *size, *ecc)?;
109 }
110 }
111 Ok(())
112 }
113
114 fn set_align(&mut self, align: Align) {
115 let n = match align {
116 Align::Left => 0,
117 Align::Center => 1,
118 Align::Right => 2,
119 };
120 self.buffer.extend_from_slice(&[0x1B, b'a', n]);
121 }
122
123 fn writeln(&mut self, text: &str) {
124 self.buffer.extend_from_slice(text.as_bytes());
125 self.buffer.push(b'\n');
126 }
127
128 fn feed(&mut self, lines: u8) {
129 self.buffer.extend_from_slice(&[0x1B, b'd', lines]);
130 }
131
132 fn cut(&mut self) {
133 self.buffer.extend_from_slice(&[0x1D, b'V', 66, 0]);
134 }
135
136 fn encode_barcode(
137 &mut self,
138 symbology: BarcodeSymbology,
139 data: &str,
140 height: u8,
141 show_text: bool,
142 ) -> Result<(), EscPosError> {
143 self.buffer.extend_from_slice(&[0x1D, b'h', height]);
144 self.buffer.extend_from_slice(&[0x1D, b'H', if show_text { 2 } else { 0 }]);
145 match symbology {
146 BarcodeSymbology::Code128 => {
147 let bytes = data.as_bytes();
148 self.buffer.extend_from_slice(&[0x1D, b'k', 73, bytes.len() as u8]);
149 self.buffer.extend_from_slice(bytes);
150 }
151 BarcodeSymbology::Ean13 => {
152 if data.len() != 12 && data.len() != 13 {
153 return Err(EscPosError::Barcode("EAN13 requires 12-13 digits".into()));
154 }
155 self.buffer.extend_from_slice(&[0x1D, b'k', 67, data.len() as u8]);
156 self.buffer.extend_from_slice(data.as_bytes());
157 }
158 BarcodeSymbology::Ean8 => {
159 if data.len() != 7 && data.len() != 8 {
160 return Err(EscPosError::Barcode("EAN8 requires 7-8 digits".into()));
161 }
162 self.buffer.extend_from_slice(&[0x1D, b'k', 68, data.len() as u8]);
163 self.buffer.extend_from_slice(data.as_bytes());
164 }
165 BarcodeSymbology::Code39 => {
166 self.buffer.extend_from_slice(&[0x1D, b'k', 69, data.len() as u8]);
167 self.buffer.extend_from_slice(data.as_bytes());
168 }
169 }
170 self.buffer.push(b'\n');
171 Ok(())
172 }
173
174 fn encode_qr(&mut self, data: &str, size: u8, ecc: QrEcc) -> Result<(), EscPosError> {
175 let ecc_level = match ecc {
176 QrEcc::L => 48,
177 QrEcc::M => 49,
178 QrEcc::Q => 50,
179 QrEcc::H => 51,
180 };
181 let store = data.as_bytes();
182 let len = store.len() + 3;
183 let p_l = (len & 0xFF) as u8;
184 let p_h = ((len >> 8) & 0xFF) as u8;
185
186 // Model 2
187 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 4, 0, 49, 65, 50, 0]);
188 // Module size
189 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 3, 0, 49, 67, size]);
190 // Error correction
191 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 3, 0, 49, 69, ecc_level]);
192 // Store data
193 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', p_l, p_h, 49, 80, 48]);
194 self.buffer.extend_from_slice(store);
195 // Print
196 self.buffer.extend_from_slice(&[0x1D, 0x28, b'k', 3, 0, 49, 81, 48]);
197 self.buffer.push(b'\n');
198 Ok(())
199 }
200
201 fn encode_image(&mut self, path: &str, width: ImageWidth) -> Result<(), EscPosError> {
202 let resolved = resolve_image_path(path, self.base_dir.as_deref());
203 let img = image::open(&resolved).map_err(|e| EscPosError::Image(e.to_string()))?;
204 let target_width = match width {
205 ImageWidth::Percent(pct) => {
206 (self.metadata.printable_dots() as u32 * pct as u32 / 100) as u32
207 }
208 ImageWidth::Dots(d) => d as u32,
209 ImageWidth::Default => self.metadata.printable_dots() as u32,
210 };
211 let gray = img.to_luma8();
212 let (w, h) = gray.dimensions();
213 let new_w = target_width.min(w);
214 let new_h = (h as f32 * (new_w as f32 / w as f32)) as u32;
215 let resized = image::imageops::resize(
216 &gray,
217 new_w,
218 new_h,
219 image::imageops::FilterType::Nearest,
220 );
221 let bytes_per_row = ((new_w + 7) / 8) as usize;
222 let mut raster = vec![0u8; bytes_per_row * new_h as usize];
223 for y in 0..new_h {
224 for x in 0..new_w {
225 let pixel = resized.get_pixel(x, y).0[0];
226 if pixel < 128 {
227 let byte_index = (y as usize * bytes_per_row) + (x as usize / 8);
228 let bit = 7 - (x % 8);
229 raster[byte_index] |= 1 << bit;
230 }
231 }
232 }
233 let x_l = (bytes_per_row & 0xFF) as u8;
234 let x_h = ((bytes_per_row >> 8) & 0xFF) as u8;
235 let y_l = (new_h & 0xFF) as u8;
236 let y_h = ((new_h >> 8) & 0xFF) as u8;
237 self.buffer.extend_from_slice(&[0x1D, b'v', 0, 0, x_l, x_h, y_l, y_h]);
238 self.buffer.extend_from_slice(&raster);
239 self.buffer.push(b'\n');
240 Ok(())
241 }
242}
243
244fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> std::path::PathBuf {
245 let p = Path::new(path);
246 if p.is_absolute() {
247 p.to_path_buf()
248 } else if let Some(base) = base_dir {
249 base.join(p)
250 } else {
251 p.to_path_buf()
252 }
253}
254
255fn inlines_to_plain(inlines: &[Inline]) -> String {
256 let mut out = String::new();
257 for inline in inlines {
258 match inline {
259 Inline::Text(t) | Inline::Code(t) => out.push_str(t),
260 Inline::Param(t) => out.push_str(t),
261 Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_plain(inner)),
262 }
263 }
264 out
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270 use crate::dsl::parse;
271
272 #[test]
273 fn encodes_init_and_text() {
274 let doc = parse("Hello").unwrap();
275 let mut enc = EscPosEncoder::new(PosMetadata::default());
276 let bytes = enc.encode_document(&doc).unwrap();
277 assert_eq!(&bytes[0..2], &[0x1B, b'@']);
278 assert!(bytes.windows(5).any(|w| w == b"Hello"));
279 }
280
281 #[test]
282 fn encodes_cut_directive() {
283 let doc = parse("@cut").unwrap();
284 let mut enc = EscPosEncoder::new(PosMetadata {
285 cut_after_print: false,
286 ..Default::default()
287 });
288 let bytes = enc.encode_document(&doc).unwrap();
289 assert!(bytes.windows(3).any(|w| w == [0x1D, b'V', 66]));
290 }
291
292 #[test]
293 fn auto_cut_when_enabled() {
294 let doc = parse("x").unwrap();
295 let mut enc = EscPosEncoder::new(PosMetadata::default());
296 let bytes = enc.encode_document(&doc).unwrap();
297 assert!(bytes.ends_with(&[0x1D, b'V', 66, 0]));
298 }
299}
src/preview.rs added +144 −0
@@ -0,0 +1,144 @@
1 use crate::dsl::{Align, Block, Document, Inline};
2 use crate::io::PosMetadata;
3
4 #[derive(Debug, Clone, PartialEq)]
5 pub struct PreviewModel {
6 pub lines: Vec<PreviewLine>,
7 pub width_chars: u32,
8 pub width_mm: f32,
9 }
10
11 #[derive(Debug, Clone, PartialEq)]
12 pub enum PreviewLine {
13 Text {
14 content: String,
15 align: Align,
16 style: TextStyle,
17 },
18 Rule,
19 Barcode {
20 symbology: String,
21 data: String,
22 align: Align,
23 },
24 Qr {
25 data: String,
26 align: Align,
27 },
28 Image {
29 label: String,
30 align: Align,
31 },
32 Spacer(u8),
33 }
34
35 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36 pub enum TextStyle {
37 #[default]
38 Normal,
39 Heading1,
40 Heading2,
41 Bold,
42 Italic,
43 Code,
44 }
45
46 pub fn render_preview(document: &Document, metadata: &PosMetadata) -> PreviewModel {
47 let width_chars = metadata.chars_per_line();
48 let mut lines = Vec::new();
49
50 for block in &document.blocks {
51 match block {
52 Block::Paragraph { align, inlines } => {
53 let text = inlines_to_string(inlines);
54 for line in text.split('\n') {
55 lines.push(PreviewLine::Text {
56 content: line.to_string(),
57 align: *align,
58 style: TextStyle::Normal,
59 });
60 }
61 }
62 Block::Heading { level, inlines } => {
63 let style = if *level == 1 {
64 TextStyle::Heading1
65 } else {
66 TextStyle::Heading2
67 };
68 lines.push(PreviewLine::Text {
69 content: inlines_to_string(inlines),
70 align: Align::Center,
71 style,
72 });
73 }
74 Block::Rule => lines.push(PreviewLine::Rule),
75 Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)),
76 Block::Cut => lines.push(PreviewLine::Text {
77 content: "--- cut ---".into(),
78 align: Align::Center,
79 style: TextStyle::Code,
80 }),
81 Block::Image { path, align, .. } => lines.push(PreviewLine::Image {
82 label: format!("[image: {path}]"),
83 align: *align,
84 }),
85 Block::Barcode {
86 symbology,
87 data,
88 align,
89 ..
90 } => lines.push(PreviewLine::Barcode {
91 symbology: format!("{symbology:?}"),
92 data: data.clone(),
93 align: *align,
94 }),
95 Block::Qr { data, align, .. } => lines.push(PreviewLine::Qr {
96 data: data.clone(),
97 align: *align,
98 }),
99 }
100 }
101
102 PreviewModel {
103 lines,
104 width_chars,
105 width_mm: metadata.page_width_mm,
106 }
107 }
108
109 fn inlines_to_string(inlines: &[Inline]) -> String {
110 let mut out = String::new();
111 for inline in inlines {
112 match inline {
113 Inline::Text(t) => out.push_str(t),
114 Inline::Code(t) => out.push_str(t),
115 Inline::Param(t) => out.push_str(&format!("${{{t}}}")),
116 Inline::Bold(inner) => out.push_str(&inlines_to_string(inner)),
117 Inline::Italic(inner) => out.push_str(&inlines_to_string(inner)),
118 }
119 }
120 out
121 }
122
123 #[cfg(test)]
124 mod tests {
125 use super::*;
126 use crate::dsl::parse;
127
128 #[test]
129 fn renders_paragraph_lines() {
130 let doc = parse("Line1\nLine2").unwrap();
131 let model = render_preview(&doc, &PosMetadata::default());
132 assert!(model.lines.len() >= 2);
133 }
134
135 #[test]
136 fn shows_unresolved_params_in_preview() {
137 let doc = parse("${X}").unwrap();
138 let model = render_preview(&doc, &PosMetadata::default());
139 let PreviewLine::Text { content, .. } = &model.lines[0] else {
140 panic!();
141 };
142 assert_eq!(content, "${X}");
143 }
144 }
@@ -0,0 +1,144 @@
1use crate::dsl::{Align, Block, Document, Inline};
2use crate::io::PosMetadata;
3
4#[derive(Debug, Clone, PartialEq)]
5pub struct PreviewModel {
6 pub lines: Vec<PreviewLine>,
7 pub width_chars: u32,
8 pub width_mm: f32,
9}
10
11#[derive(Debug, Clone, PartialEq)]
12pub enum PreviewLine {
13 Text {
14 content: String,
15 align: Align,
16 style: TextStyle,
17 },
18 Rule,
19 Barcode {
20 symbology: String,
21 data: String,
22 align: Align,
23 },
24 Qr {
25 data: String,
26 align: Align,
27 },
28 Image {
29 label: String,
30 align: Align,
31 },
32 Spacer(u8),
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum TextStyle {
37 #[default]
38 Normal,
39 Heading1,
40 Heading2,
41 Bold,
42 Italic,
43 Code,
44}
45
46pub fn render_preview(document: &Document, metadata: &PosMetadata) -> PreviewModel {
47 let width_chars = metadata.chars_per_line();
48 let mut lines = Vec::new();
49
50 for block in &document.blocks {
51 match block {
52 Block::Paragraph { align, inlines } => {
53 let text = inlines_to_string(inlines);
54 for line in text.split('\n') {
55 lines.push(PreviewLine::Text {
56 content: line.to_string(),
57 align: *align,
58 style: TextStyle::Normal,
59 });
60 }
61 }
62 Block::Heading { level, inlines } => {
63 let style = if *level == 1 {
64 TextStyle::Heading1
65 } else {
66 TextStyle::Heading2
67 };
68 lines.push(PreviewLine::Text {
69 content: inlines_to_string(inlines),
70 align: Align::Center,
71 style,
72 });
73 }
74 Block::Rule => lines.push(PreviewLine::Rule),
75 Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)),
76 Block::Cut => lines.push(PreviewLine::Text {
77 content: "--- cut ---".into(),
78 align: Align::Center,
79 style: TextStyle::Code,
80 }),
81 Block::Image { path, align, .. } => lines.push(PreviewLine::Image {
82 label: format!("[image: {path}]"),
83 align: *align,
84 }),
85 Block::Barcode {
86 symbology,
87 data,
88 align,
89 ..
90 } => lines.push(PreviewLine::Barcode {
91 symbology: format!("{symbology:?}"),
92 data: data.clone(),
93 align: *align,
94 }),
95 Block::Qr { data, align, .. } => lines.push(PreviewLine::Qr {
96 data: data.clone(),
97 align: *align,
98 }),
99 }
100 }
101
102 PreviewModel {
103 lines,
104 width_chars,
105 width_mm: metadata.page_width_mm,
106 }
107}
108
109fn inlines_to_string(inlines: &[Inline]) -> String {
110 let mut out = String::new();
111 for inline in inlines {
112 match inline {
113 Inline::Text(t) => out.push_str(t),
114 Inline::Code(t) => out.push_str(t),
115 Inline::Param(t) => out.push_str(&format!("${{{t}}}")),
116 Inline::Bold(inner) => out.push_str(&inlines_to_string(inner)),
117 Inline::Italic(inner) => out.push_str(&inlines_to_string(inner)),
118 }
119 }
120 out
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126 use crate::dsl::parse;
127
128 #[test]
129 fn renders_paragraph_lines() {
130 let doc = parse("Line1\nLine2").unwrap();
131 let model = render_preview(&doc, &PosMetadata::default());
132 assert!(model.lines.len() >= 2);
133 }
134
135 #[test]
136 fn shows_unresolved_params_in_preview() {
137 let doc = parse("${X}").unwrap();
138 let model = render_preview(&doc, &PosMetadata::default());
139 let PreviewLine::Text { content, .. } = &model.lines[0] else {
140 panic!();
141 };
142 assert_eq!(content, "${X}");
143 }
144}
src/print/mod.rs added +130 −0
@@ -0,0 +1,130 @@
1 use std::io::{self, Write};
2 use std::time::Duration;
3
4 use serialport::SerialPortType;
5
6 #[derive(Debug, Clone, PartialEq, Eq)]
7 pub struct PrinterDevice {
8 pub id: String,
9 pub display_name: String,
10 pub port_name: String,
11 }
12
13 #[derive(Debug)]
14 pub enum PrintError {
15 NotFound,
16 Open(String),
17 Write(String),
18 Serial(serialport::Error),
19 }
20
21 pub trait PrinterTransport {
22 fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
23 fn flush(&mut self) -> io::Result<()>;
24 }
25
26 pub struct SerialTransport {
27 port: Box<dyn serialport::SerialPort>,
28 }
29
30 impl SerialTransport {
31 pub fn open(port_name: &str) -> Result<Self, PrintError> {
32 let port = serialport::new(port_name, 9600)
33 .timeout(Duration::from_millis(2000))
34 .open()
35 .map_err(|e| PrintError::Open(e.to_string()))?;
36 Ok(Self { port })
37 }
38 }
39
40 impl PrinterTransport for SerialTransport {
41 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
42 self.port.write_all(data)
43 }
44
45 fn flush(&mut self) -> io::Result<()> {
46 self.port.flush()
47 }
48 }
49
50 pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
51 let mut devices = Vec::new();
52 for port in serialport::available_ports()? {
53 let label = match &port.port_type {
54 SerialPortType::UsbPort(info) => format!(
55 "{} — USB {}:{}",
56 port.port_name,
57 fmt_vid_pid(info.vid),
58 fmt_vid_pid(info.pid)
59 ),
60 _ => format!("{} — Serial", port.port_name),
61 };
62 devices.push(PrinterDevice {
63 id: format!("serial:{}", port.port_name),
64 display_name: label,
65 port_name: port.port_name.clone(),
66 });
67 }
68 devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
69 Ok(devices)
70 }
71
72 fn fmt_vid_pid(v: u16) -> String {
73 format!("{v:04x}")
74 }
75
76 pub fn print_bytes<T: PrinterTransport>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
77 transport
78 .write_all(data)
79 .map_err(|e| PrintError::Write(e.to_string()))?;
80 transport
81 .flush()
82 .map_err(|e| PrintError::Write(e.to_string()))?;
83 Ok(())
84 }
85
86 pub struct MockTransport {
87 pub written: Vec<u8>,
88 }
89
90 impl MockTransport {
91 pub fn new() -> Self {
92 Self { written: Vec::new() }
93 }
94 }
95
96 impl Default for MockTransport {
97 fn default() -> Self {
98 Self::new()
99 }
100 }
101
102 impl PrinterTransport for MockTransport {
103 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
104 self.written.extend_from_slice(data);
105 Ok(())
106 }
107
108 fn flush(&mut self) -> io::Result<()> {
109 Ok(())
110 }
111 }
112
113 #[cfg(test)]
114 mod tests {
115 use super::*;
116
117 #[test]
118 fn mock_transport_records_bytes() {
119 let mut mock = MockTransport::new();
120 print_bytes(&mut mock, &[1, 2, 3]).unwrap();
121 assert_eq!(mock.written, vec![1, 2, 3]);
122 }
123
124 #[test]
125 fn list_printers_returns_vec() {
126 // May be empty on CI; must not error.
127 let list = list_usb_serial_printers();
128 assert!(list.is_ok());
129 }
130 }
@@ -0,0 +1,130 @@
1use std::io::{self, Write};
2use std::time::Duration;
3
4use serialport::SerialPortType;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct PrinterDevice {
8 pub id: String,
9 pub display_name: String,
10 pub port_name: String,
11}
12
13#[derive(Debug)]
14pub enum PrintError {
15 NotFound,
16 Open(String),
17 Write(String),
18 Serial(serialport::Error),
19}
20
21pub trait PrinterTransport {
22 fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
23 fn flush(&mut self) -> io::Result<()>;
24}
25
26pub struct SerialTransport {
27 port: Box<dyn serialport::SerialPort>,
28}
29
30impl SerialTransport {
31 pub fn open(port_name: &str) -> Result<Self, PrintError> {
32 let port = serialport::new(port_name, 9600)
33 .timeout(Duration::from_millis(2000))
34 .open()
35 .map_err(|e| PrintError::Open(e.to_string()))?;
36 Ok(Self { port })
37 }
38}
39
40impl PrinterTransport for SerialTransport {
41 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
42 self.port.write_all(data)
43 }
44
45 fn flush(&mut self) -> io::Result<()> {
46 self.port.flush()
47 }
48}
49
50pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
51 let mut devices = Vec::new();
52 for port in serialport::available_ports()? {
53 let label = match &port.port_type {
54 SerialPortType::UsbPort(info) => format!(
55 "{} — USB {}:{}",
56 port.port_name,
57 fmt_vid_pid(info.vid),
58 fmt_vid_pid(info.pid)
59 ),
60 _ => format!("{} — Serial", port.port_name),
61 };
62 devices.push(PrinterDevice {
63 id: format!("serial:{}", port.port_name),
64 display_name: label,
65 port_name: port.port_name.clone(),
66 });
67 }
68 devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
69 Ok(devices)
70}
71
72fn fmt_vid_pid(v: u16) -> String {
73 format!("{v:04x}")
74}
75
76pub fn print_bytes<T: PrinterTransport>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
77 transport
78 .write_all(data)
79 .map_err(|e| PrintError::Write(e.to_string()))?;
80 transport
81 .flush()
82 .map_err(|e| PrintError::Write(e.to_string()))?;
83 Ok(())
84}
85
86pub struct MockTransport {
87 pub written: Vec<u8>,
88}
89
90impl MockTransport {
91 pub fn new() -> Self {
92 Self { written: Vec::new() }
93 }
94}
95
96impl Default for MockTransport {
97 fn default() -> Self {
98 Self::new()
99 }
100}
101
102impl PrinterTransport for MockTransport {
103 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
104 self.written.extend_from_slice(data);
105 Ok(())
106 }
107
108 fn flush(&mut self) -> io::Result<()> {
109 Ok(())
110 }
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 #[test]
118 fn mock_transport_records_bytes() {
119 let mut mock = MockTransport::new();
120 print_bytes(&mut mock, &[1, 2, 3]).unwrap();
121 assert_eq!(mock.written, vec![1, 2, 3]);
122 }
123
124 #[test]
125 fn list_printers_returns_vec() {
126 // May be empty on CI; must not error.
127 let list = list_usb_serial_printers();
128 assert!(list.is_ok());
129 }
130}