BlueGit

timfa posprint

Files

posprint / src / preview.rs

preview.rs

preview.rs 20.2 KiB Download Raw
1use std::collections::HashMap;
2use std::path::Path;
3
4use image::GrayImage;
5
6use crate::dsl::{
7 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode,
8};
9use crate::io::PosMetadata;
10use crate::datetime;
11use crate::params::{preview_barcode_sample, substitute_for_preview, substitute_inlines_for_preview};
12use crate::raster::{render_barcode, render_qr, scale_gray_to_print_width};
13use crate::text_wrap::{self, TextWrapStyle};
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct PreviewModel {
17 pub lines: Vec<PreviewLine>,
18 pub width_dots: u32,
19 pub width_mm: f32,
20}
21
22#[derive(Debug, Clone, PartialEq)]
23pub enum PreviewLine {
24 Text {
25 content: String,
26 align: Align,
27 style: TextStyle,
28 },
29 Rule,
30 Graphic {
31 image: GrayImage,
32 align: Align,
33 },
34 Error {
35 message: String,
36 align: Align,
37 },
38 Spacer(u8),
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum TextStyle {
43 #[default]
44 Normal,
45 Heading1,
46 Heading2,
47}
48
49pub fn render_preview(
50 document: &Document,
51 metadata: &PosMetadata,
52 base_dir: Option<&Path>,
53 preview_params: &HashMap<String, String>,
54) -> PreviewModel {
55 let width_dots = metadata.printable_dots() as u32;
56 let mut lines = Vec::new();
57
58 for block in &document.blocks {
59 match block {
60 Block::Paragraph { align, inlines } => {
61 let text = substitute_inlines_for_preview(inlines, preview_params);
62 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
63 for line in text_wrap::wrap_text(&text, cols) {
64 lines.push(PreviewLine::Text {
65 content: line,
66 align: *align,
67 style: TextStyle::Normal,
68 });
69 }
70 }
71 Block::List { align, items } => {
72 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
73 for item in items {
74 let text = substitute_inlines_for_preview(&item.inlines, preview_params);
75 for line in text_wrap::wrap_bullet_item_at_depth(&text, cols, item.depth) {
76 lines.push(PreviewLine::Text {
77 content: line,
78 align: *align,
79 style: TextStyle::Normal,
80 });
81 }
82 }
83 }
84 Block::Heading { level, align, inlines } => {
85 let style = if *level == 1 {
86 TextStyle::Heading1
87 } else {
88 TextStyle::Heading2
89 };
90 let wrap_style = if *level == 1 {
91 TextWrapStyle::Heading1
92 } else {
93 TextWrapStyle::Heading2
94 };
95 let text = substitute_inlines_for_preview(inlines, preview_params);
96 let cols = text_wrap::wrap_cols(metadata, wrap_style);
97 for line in text_wrap::wrap_text(&text, cols) {
98 lines.push(PreviewLine::Text {
99 content: line,
100 align: *align,
101 style,
102 });
103 }
104 }
105 Block::Rule => lines.push(PreviewLine::Rule),
106 Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)),
107 Block::Cut => lines.push(PreviewLine::Text {
108 content: "--- cut ---".into(),
109 align: Align::Center,
110 style: TextStyle::Normal,
111 }),
112 Block::Image { path, width, align } => {
113 let path = substitute_for_preview(path, preview_params);
114 lines.push(render_image_preview(&path, *width, *align, metadata, base_dir));
115 }
116 Block::Barcode {
117 mode,
118 symbology,
119 data,
120 height,
121 align,
122 ..
123 } => {
124 let resolved = substitute_for_preview(data, preview_params);
125 lines.push(render_barcode_preview(
126 *mode,
127 *symbology,
128 data,
129 &resolved,
130 *height,
131 *align,
132 metadata,
133 ));
134 }
135 Block::Qr {
136 mode,
137 data,
138 size,
139 ecc,
140 version,
141 align,
142 } => {
143 let data = substitute_for_preview(data, preview_params);
144 lines.push(render_qr_preview(
145 *mode, &data, *size, *ecc, *version, *align, metadata,
146 ));
147 }
148 Block::Date { format, align } => {
149 let text = datetime::format_date(format.as_deref());
150 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
151 for line in text_wrap::wrap_text(&text, cols) {
152 lines.push(PreviewLine::Text {
153 content: line,
154 align: *align,
155 style: TextStyle::Normal,
156 });
157 }
158 }
159 Block::Time { format, align } => {
160 let text = datetime::format_time(*format);
161 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
162 for line in text_wrap::wrap_text(&text, cols) {
163 lines.push(PreviewLine::Text {
164 content: line,
165 align: *align,
166 style: TextStyle::Normal,
167 });
168 }
169 }
170 }
171 }
172
173 PreviewModel {
174 lines,
175 width_dots,
176 width_mm: metadata.page_width_mm,
177 }
178}
179
180fn render_barcode_preview(
181 mode: BarcodeMode,
182 symbology: BarcodeSymbology,
183 template_data: &str,
184 resolved_data: &str,
185 height: u8,
186 align: Align,
187 metadata: &PosMetadata,
188) -> PreviewLine {
189 let height_px = u32::from(height.max(20));
190 let resolved_data = resolved_data.trim();
191 let print_width = metadata.printable_dots() as u32;
192 match mode {
193 BarcodeMode::Raster | BarcodeMode::Native => {
194 match render_barcode(symbology, resolved_data, height_px) {
195 Ok(img) => PreviewLine::Graphic {
196 image: scale_gray_to_print_width(img, print_width),
197 align,
198 },
199 Err(e) => {
200 if template_data.contains("${") {
201 if let Ok(img) =
202 render_barcode(symbology, preview_barcode_sample(symbology), height_px)
203 {
204 return PreviewLine::Graphic {
205 image: scale_gray_to_print_width(img, print_width),
206 align,
207 };
208 }
209 }
210 PreviewLine::Error {
211 message: format!(
212 "barcode: {e} ({} supports alphanumeric data; URLs and punctuation often fail)",
213 symbology.as_str()
214 ),
215 align,
216 }
217 }
218 }
219 }
220 }
221}
222
223fn render_qr_preview(
224 mode: QrMode,
225 data: &str,
226 size: u8,
227 ecc: crate::dsl::QrEcc,
228 version: Option<u8>,
229 align: Align,
230 metadata: &PosMetadata,
231) -> PreviewLine {
232 let module_pixels = u32::from(size.max(2));
233 match mode {
234 QrMode::Raster | QrMode::Native => match render_qr(data, version, ecc, module_pixels) {
235 Ok(img) => {
236 let max_w = (metadata.printable_dots() as u32).min(img.width());
237 scale_graphic_to_width(img, max_w, align)
238 }
239 Err(e) => PreviewLine::Error {
240 message: format!("qr: {e}"),
241 align,
242 },
243 },
244 }
245}
246
247fn render_image_preview(
248 path: &str,
249 width: ImageWidth,
250 align: Align,
251 metadata: &PosMetadata,
252 base_dir: Option<&Path>,
253) -> PreviewLine {
254 match crate::image_load::load_image(path, base_dir) {
255 Ok(img) => {
256 let gray = img.to_luma8();
257 let target = target_image_width(width, metadata);
258 let scaled = scale_gray_to_width(gray, target);
259 PreviewLine::Graphic {
260 image: scaled,
261 align,
262 }
263 }
264 Err(e) => PreviewLine::Error {
265 message: e.to_string(),
266 align,
267 },
268 }
269}
270
271fn scale_graphic_to_width(img: GrayImage, target_width: u32, align: Align) -> PreviewLine {
272 PreviewLine::Graphic {
273 image: scale_gray_to_width(img, target_width),
274 align,
275 }
276}
277
278fn scale_gray_to_width(gray: GrayImage, target_width: u32) -> GrayImage {
279 let (w, h) = gray.dimensions();
280 if w == 0 || h == 0 {
281 return gray;
282 }
283 let new_w = target_width.min(w).max(1);
284 if new_w == w {
285 return gray;
286 }
287 let new_h = ((h as f32) * (new_w as f32 / w as f32)).max(1.0) as u32;
288 image::imageops::resize(
289 &gray,
290 new_w,
291 new_h,
292 image::imageops::FilterType::Nearest,
293 )
294}
295
296fn target_image_width(width: ImageWidth, metadata: &PosMetadata) -> u32 {
297 match width {
298 ImageWidth::Percent(pct) => {
299 (metadata.printable_dots() as u32 * pct as u32 / 100).max(1)
300 }
301 ImageWidth::Dots(d) => d as u32,
302 ImageWidth::Default => metadata.printable_dots() as u32,
303 }
304}
305
306/// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
307pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
308
309/// Screen calibration so zoom `1.0` matches a typical receipt width on screen.
310pub const PREVIEW_SCREEN_CALIBRATION: f32 = 0.52;
311
312/// Preview canvas width in printer dots (before screen calibration).
313pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 {
314 metadata.printable_dots() as f32
315}
316
317/// User-controlled zoom factor (1.0 = 100%).
318pub fn preview_zoom_scale(zoom: f32) -> f32 {
319 zoom.clamp(0.25, 4.0)
320}
321
322/// Effective on-screen scale for page width, text, and raster graphics.
323pub fn preview_visual_scale(zoom: f32) -> f32 {
324 preview_zoom_scale(zoom) * PREVIEW_SCREEN_CALIBRATION
325}
326
327/// Character cell width in preview pixels (matches print column width).
328pub fn preview_char_width_px(metadata: &PosMetadata, zoom: f32) -> f32 {
329 preview_content_width_px(metadata) * preview_visual_scale(zoom)
330 / metadata.chars_per_line().max(1) as f32
331}
332
333/// egui monospace sized 1:1 to column width reads smaller than printed Font A.
334/// Empirically ~60% of print; scale up so preview matches the receipt.
335pub const PREVIEW_FONT_PRINT_MATCH: f32 = 1.0 / 0.6;
336
337/// Font size in preview pixels for normal / `##` text.
338pub fn preview_font_size_px(char_width: f32) -> f32 {
339 char_width * PREVIEW_FONT_PRINT_MATCH
340}
341
342/// Blank-line / `@feed` vertical space in preview pixels (printer line spacing).
343pub fn preview_line_spacing_px(zoom: f32) -> f32 {
344 PREVIEW_LINE_SPACING_DOTS * preview_visual_scale(zoom)
345}
346
347/// Vertical advance for a text style (matches printer LF / ESC d line spacing).
348pub fn preview_text_advance_px(style: TextStyle, zoom: f32) -> f32 {
349 let line_sp = preview_line_spacing_px(zoom);
350 match style {
351 // GS ! 0x11: double height → two line advances
352 TextStyle::Heading1 => line_sp * 2.0,
353 TextStyle::Heading2 | TextStyle::Normal => line_sp,
354 }
355}
356
357/// Estimated line height for layout (text styles use galley at draw time).
358pub fn preview_line_height_estimate(
359 line: &PreviewLine,
360 _metadata: &PosMetadata,
361 zoom: f32,
362) -> f32 {
363 let scale = preview_visual_scale(zoom);
364 match line {
365 PreviewLine::Text { style, .. } => preview_text_advance_px(*style, zoom),
366 PreviewLine::Rule => 4.0 * scale,
367 PreviewLine::Graphic { image, .. } => image.height() as f32 * scale,
368 PreviewLine::Error { .. } => preview_line_spacing_px(zoom),
369 PreviewLine::Spacer(n) => preview_line_spacing_px(zoom) * (*n as f32),
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376 use crate::dsl::parse;
377 use std::collections::HashMap;
378
379 #[test]
380 fn renders_paragraph_lines() {
381 let doc = parse("Line1\nLine2").unwrap();
382 let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
383 assert!(model.lines.len() >= 2);
384 }
385
386 #[test]
387 fn uses_placeholder_when_param_not_set() {
388 let doc = parse("${X}").unwrap();
389 let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
390 let PreviewLine::Text { content, .. } = &model.lines[0] else {
391 panic!();
392 };
393 assert_eq!(content, "1234567890");
394 }
395
396 #[test]
397 fn uses_dialog_params_in_preview() {
398 let doc = parse("Hello ${Name}").unwrap();
399 let mut params = HashMap::new();
400 params.insert("Name".into(), "Ada".into());
401 let model = render_preview(&doc, &PosMetadata::default(), None, &params);
402 let PreviewLine::Text { content, .. } = &model.lines[0] else {
403 panic!();
404 };
405 assert_eq!(content, "Hello Ada");
406 }
407
408 #[test]
409 fn renders_barcode_graphic() {
410 let doc = parse("@barcode CODE128 TEST").unwrap();
411 let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
412 assert!(model
413 .lines
414 .iter()
415 .any(|l| matches!(l, PreviewLine::Graphic { .. })));
416 }
417
418 #[test]
419 fn renders_barcode_with_unresolved_params() {
420 let doc = parse("@barcode CODE128 ${DocumentNumber}").unwrap();
421 let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
422 assert!(model
423 .lines
424 .iter()
425 .any(|l| matches!(l, PreviewLine::Graphic { .. })));
426 }
427
428 #[test]
429 fn renders_raster_code128_with_data_param() {
430 let doc = parse(
431 ":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n",
432 )
433 .unwrap();
434 let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
435 let graphics = model
436 .lines
437 .iter()
438 .filter(|l| matches!(l, PreviewLine::Graphic { .. }))
439 .count();
440 let errors: Vec<_> = model
441 .lines
442 .iter()
443 .filter_map(|l| match l {
444 PreviewLine::Error { message, .. } => Some(message.as_str()),
445 _ => None,
446 })
447 .collect();
448 assert_eq!(graphics, 2, "expected QR and barcode graphics, errors: {errors:?}");
449 }
450
451 #[test]
452 fn empty_param_value_uses_barcode_placeholder() {
453 let doc = parse("@barcode RASTER CODE128 ${Data}\n").unwrap();
454 let mut params = HashMap::new();
455 params.insert("Data".into(), String::new());
456 let model = render_preview(&doc, &PosMetadata::default(), None, &params);
457 assert!(model
458 .lines
459 .iter()
460 .any(|l| matches!(l, PreviewLine::Graphic { .. })));
461 }
462
463 #[test]
464 fn shared_data_param_url_still_renders_barcode_preview() {
465 let doc = parse("@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n").unwrap();
466 let mut params = HashMap::new();
467 params.insert("Data".into(), "https://example.com".into());
468 let model = render_preview(&doc, &PosMetadata::default(), None, &params);
469 let graphics = model
470 .lines
471 .iter()
472 .filter(|l| matches!(l, PreviewLine::Graphic { .. }))
473 .count();
474 assert_eq!(graphics, 2, "QR and barcode preview should both render");
475 }
476
477 #[test]
478 fn persistent_center_heading_uses_center_in_preview() {
479 let doc = parse(":center:\n# Hello").unwrap();
480 let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
481 let PreviewLine::Text { align, content, .. } = &model.lines[0] else {
482 panic!();
483 };
484 assert_eq!(content, "Hello");
485 assert_eq!(*align, Align::Center);
486 }
487
488 #[test]
489 fn heading_wraps_in_preview_on_narrow_paper() {
490 let doc = parse("# Proof of Transfer").unwrap();
491 let meta = PosMetadata {
492 page_width_mm: 53.0,
493 ..Default::default()
494 };
495 let model = render_preview(&doc, &meta, None, &HashMap::new());
496 let text_lines: Vec<_> = model
497 .lines
498 .iter()
499 .filter_map(|l| match l {
500 PreviewLine::Text { content, style, .. } if *style == TextStyle::Heading1 => {
501 Some(content.as_str())
502 }
503 _ => None,
504 })
505 .collect();
506 assert_eq!(text_lines, vec!["Proof of", "Transfer"]);
507 }
508
509 #[test]
510 fn preview_width_matches_printable_dots() {
511 let meta = PosMetadata {
512 page_width_mm: 53.0,
513 ..Default::default()
514 };
515 assert_eq!(
516 preview_content_width_px(&meta) as u16,
517 meta.printable_dots()
518 );
519 }
520
521 #[test]
522 fn spacer_height_matches_line_spacing() {
523 let meta = PosMetadata::default();
524 let line = PreviewLine::Spacer(1);
525 let h = preview_line_height_estimate(&line, &meta, 1.0);
526 assert!((h - PREVIEW_LINE_SPACING_DOTS * PREVIEW_SCREEN_CALIBRATION).abs() < 0.01);
527 }
528
529 #[test]
530 fn zoom_100_percent_uses_screen_calibration() {
531 assert!((preview_visual_scale(1.0) - PREVIEW_SCREEN_CALIBRATION).abs() < 0.001);
532 }
533
534 #[test]
535 fn font_size_matches_print_calibration() {
536 let char_w = 6.0;
537 assert!((preview_font_size_px(char_w) - char_w / 0.6).abs() < 0.001);
538 }
539
540 #[test]
541 fn char_width_fits_columns_on_paper() {
542 let meta = PosMetadata::default();
543 let width = preview_content_width_px(&meta) * preview_visual_scale(1.0);
544 let char_w = preview_char_width_px(&meta, 1.0);
545 assert!((char_w * meta.chars_per_line() as f32 - width).abs() < 0.01);
546 }
547
548 #[test]
549 fn heading1_is_double_normal_text_height() {
550 let meta = PosMetadata::default();
551 let normal = preview_line_height_estimate(
552 &PreviewLine::Text {
553 content: "x".into(),
554 align: crate::dsl::Align::Left,
555 style: TextStyle::Normal,
556 },
557 &meta,
558 1.0,
559 );
560 let heading = preview_line_height_estimate(
561 &PreviewLine::Text {
562 content: "x".into(),
563 align: crate::dsl::Align::Left,
564 style: TextStyle::Heading1,
565 },
566 &meta,
567 1.0,
568 );
569 assert!((heading - normal * 2.0).abs() < 0.01);
570 }
571
572 #[test]
573 fn spacer_matches_normal_text_advance() {
574 let meta = PosMetadata::default();
575 let spacer = preview_line_height_estimate(&PreviewLine::Spacer(1), &meta, 1.0);
576 let text = preview_text_advance_px(TextStyle::Normal, 1.0);
577 assert!((spacer - text).abs() < 0.01);
578 }
579
580 #[test]
581 fn renders_bullet_list_with_hanging_indent() {
582 let doc = parse("- this is a long line").unwrap();
583 let meta = PosMetadata {
584 chars_per_line: Some(15),
585 ..Default::default()
586 };
587 let model = render_preview(&doc, &meta, None, &HashMap::new());
588 assert_eq!(model.lines.len(), 2);
589 let PreviewLine::Text { content: first, .. } = &model.lines[0] else {
590 panic!();
591 };
592 let PreviewLine::Text { content: second, .. } = &model.lines[1] else {
593 panic!();
594 };
595 assert!(first.starts_with("* "));
596 assert!(second.starts_with(" "));
597 }
598}