use std::collections::HashMap; use std::path::Path; use image::GrayImage; use crate::align_row::{columns_from_parts, layout_aligned_row_or_lines}; use crate::dsl::{ Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode, }; use crate::io::PosMetadata; use crate::datetime; use crate::params::{preview_barcode_sample, substitute_for_preview, substitute_inlines_for_preview}; use crate::raster::{render_barcode, render_qr, scale_gray_to_print_width}; use crate::text_wrap::{self, TextWrapStyle}; #[derive(Debug, Clone, PartialEq)] pub struct PreviewModel { pub lines: Vec, pub width_dots: u32, pub width_mm: f32, } #[derive(Debug, Clone, PartialEq)] pub enum PreviewLine { Text { content: String, align: Align, style: TextStyle, }, Rule, Graphic { image: GrayImage, align: Align, }, Error { message: String, align: Align, }, Spacer(u8), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum TextStyle { #[default] Normal, Heading1, Heading2, } pub fn render_preview( document: &Document, metadata: &PosMetadata, base_dir: Option<&Path>, preview_params: &HashMap, ) -> PreviewModel { let width_dots = metadata.printable_dots() as u32; let mut lines = Vec::new(); for block in &document.blocks { match block { Block::Paragraph { align, inlines } => { let text = substitute_inlines_for_preview(inlines, preview_params); let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal); for line in text_wrap::wrap_text(&text, cols) { lines.push(PreviewLine::Text { content: line, align: *align, style: TextStyle::Normal, }); } } Block::AlignedRow { parts } => { let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal); let plain_parts: Vec<(Align, String)> = parts .iter() .map(|(align, inlines)| { ( *align, substitute_inlines_for_preview(inlines, preview_params), ) }) .collect(); let columns = columns_from_parts(&plain_parts); for (align, line) in layout_aligned_row_or_lines(&columns, cols) { for wrapped in text_wrap::wrap_text(&line, cols) { lines.push(PreviewLine::Text { content: wrapped, align, style: TextStyle::Normal, }); } } } Block::List { align, items } => { let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal); for item in items { let text = substitute_inlines_for_preview(&item.inlines, preview_params); for line in text_wrap::wrap_bullet_item_at_depth(&text, cols, item.depth) { lines.push(PreviewLine::Text { content: line, align: *align, style: TextStyle::Normal, }); } } } Block::Heading { level, align, inlines } => { let style = if *level == 1 { TextStyle::Heading1 } else { TextStyle::Heading2 }; let wrap_style = if *level == 1 { TextWrapStyle::Heading1 } else { TextWrapStyle::Heading2 }; let text = substitute_inlines_for_preview(inlines, preview_params); let cols = text_wrap::wrap_cols(metadata, wrap_style); for line in text_wrap::wrap_text(&text, cols) { lines.push(PreviewLine::Text { content: line, align: *align, style, }); } } Block::Rule => lines.push(PreviewLine::Rule), Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)), Block::Cut => lines.push(PreviewLine::Text { content: "--- cut ---".into(), align: Align::Center, style: TextStyle::Normal, }), Block::Image { path, width, align } => { let path = substitute_for_preview(path, preview_params); lines.push(render_image_preview(&path, *width, *align, metadata, base_dir)); } Block::Barcode { mode, symbology, data, height, align, .. } => { let resolved = substitute_for_preview(data, preview_params); lines.push(render_barcode_preview( *mode, *symbology, data, &resolved, *height, *align, metadata, )); } Block::Qr { mode, data, size, ecc, version, align, } => { let data = substitute_for_preview(data, preview_params); lines.push(render_qr_preview( *mode, &data, *size, *ecc, *version, *align, metadata, )); } Block::Date { format, align } => { let text = datetime::format_date(format.as_deref()); let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal); for line in text_wrap::wrap_text(&text, cols) { lines.push(PreviewLine::Text { content: line, align: *align, style: TextStyle::Normal, }); } } Block::Time { format, align } => { let text = datetime::format_time(*format); let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal); for line in text_wrap::wrap_text(&text, cols) { lines.push(PreviewLine::Text { content: line, align: *align, style: TextStyle::Normal, }); } } } } PreviewModel { lines, width_dots, width_mm: metadata.page_width_mm, } } fn render_barcode_preview( mode: BarcodeMode, symbology: BarcodeSymbology, template_data: &str, resolved_data: &str, height: u8, align: Align, metadata: &PosMetadata, ) -> PreviewLine { let height_px = u32::from(height.max(20)); let resolved_data = resolved_data.trim(); let print_width = metadata.printable_dots() as u32; match mode { BarcodeMode::Raster | BarcodeMode::Native => { match render_barcode(symbology, resolved_data, height_px) { Ok(img) => PreviewLine::Graphic { image: scale_gray_to_print_width(img, print_width), align, }, Err(e) => { if template_data.contains("${") { if let Ok(img) = render_barcode(symbology, preview_barcode_sample(symbology), height_px) { return PreviewLine::Graphic { image: scale_gray_to_print_width(img, print_width), align, }; } } PreviewLine::Error { message: format!( "barcode: {e} ({} supports alphanumeric data; URLs and punctuation often fail)", symbology.as_str() ), align, } } } } } } fn render_qr_preview( mode: QrMode, data: &str, size: u8, ecc: crate::dsl::QrEcc, version: Option, align: Align, metadata: &PosMetadata, ) -> PreviewLine { let module_pixels = u32::from(size.max(2)); match mode { QrMode::Raster | QrMode::Native => match render_qr(data, version, ecc, module_pixels) { Ok(img) => { let max_w = (metadata.printable_dots() as u32).min(img.width()); scale_graphic_to_width(img, max_w, align) } Err(e) => PreviewLine::Error { message: format!("qr: {e}"), align, }, }, } } fn render_image_preview( path: &str, width: ImageWidth, align: Align, metadata: &PosMetadata, base_dir: Option<&Path>, ) -> PreviewLine { match crate::image_load::load_image(path, base_dir) { Ok(img) => { let gray = img.to_luma8(); let target = target_image_width(width, metadata); let scaled = scale_gray_to_width(gray, target); PreviewLine::Graphic { image: scaled, align, } } Err(e) => PreviewLine::Error { message: e.to_string(), align, }, } } fn scale_graphic_to_width(img: GrayImage, target_width: u32, align: Align) -> PreviewLine { PreviewLine::Graphic { image: scale_gray_to_width(img, target_width), align, } } fn scale_gray_to_width(gray: GrayImage, target_width: u32) -> GrayImage { let (w, h) = gray.dimensions(); if w == 0 || h == 0 { return gray; } let new_w = target_width.min(w).max(1); if new_w == w { return gray; } let new_h = ((h as f32) * (new_w as f32 / w as f32)).max(1.0) as u32; image::imageops::resize( &gray, new_w, new_h, image::imageops::FilterType::Nearest, ) } fn target_image_width(width: ImageWidth, metadata: &PosMetadata) -> u32 { match width { ImageWidth::Percent(pct) => { (metadata.printable_dots() as u32 * pct as u32 / 100).max(1) } ImageWidth::Dots(d) => d as u32, ImageWidth::Default => metadata.printable_dots() as u32, } } /// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI). pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0; /// Screen calibration so zoom `1.0` matches a typical receipt width on screen. pub const PREVIEW_SCREEN_CALIBRATION: f32 = 0.52; /// Preview canvas width in printer dots (before screen calibration). pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 { metadata.printable_dots() as f32 } /// User-controlled zoom factor (1.0 = 100%). pub fn preview_zoom_scale(zoom: f32) -> f32 { zoom.clamp(0.25, 4.0) } /// Effective on-screen scale for page width, text, and raster graphics. pub fn preview_visual_scale(zoom: f32) -> f32 { preview_zoom_scale(zoom) * PREVIEW_SCREEN_CALIBRATION } /// Character cell width in preview pixels (matches print column width). pub fn preview_char_width_px(metadata: &PosMetadata, zoom: f32) -> f32 { preview_content_width_px(metadata) * preview_visual_scale(zoom) / metadata.chars_per_line().max(1) as f32 } /// egui monospace sized 1:1 to column width reads smaller than printed Font A. /// Empirically ~60% of print; scale up so preview matches the receipt. pub const PREVIEW_FONT_PRINT_MATCH: f32 = 1.0 / 0.6; /// Font size in preview pixels for normal / `##` text. pub fn preview_font_size_px(char_width: f32) -> f32 { char_width * PREVIEW_FONT_PRINT_MATCH } /// Blank-line / `@feed` vertical space in preview pixels (printer line spacing). pub fn preview_line_spacing_px(zoom: f32) -> f32 { PREVIEW_LINE_SPACING_DOTS * preview_visual_scale(zoom) } /// Vertical advance for a text style (matches printer LF / ESC d line spacing). pub fn preview_text_advance_px(style: TextStyle, zoom: f32) -> f32 { let line_sp = preview_line_spacing_px(zoom); match style { // GS ! 0x11: double height → two line advances TextStyle::Heading1 => line_sp * 2.0, TextStyle::Heading2 | TextStyle::Normal => line_sp, } } /// Estimated line height for layout (text styles use galley at draw time). pub fn preview_line_height_estimate( line: &PreviewLine, _metadata: &PosMetadata, zoom: f32, ) -> f32 { let scale = preview_visual_scale(zoom); match line { PreviewLine::Text { style, .. } => preview_text_advance_px(*style, zoom), PreviewLine::Rule => 4.0 * scale, PreviewLine::Graphic { image, .. } => image.height() as f32 * scale, PreviewLine::Error { .. } => preview_line_spacing_px(zoom), PreviewLine::Spacer(n) => preview_line_spacing_px(zoom) * (*n as f32), } } #[cfg(test)] mod tests { use super::*; use crate::dsl::parse; use std::collections::HashMap; #[test] fn renders_paragraph_lines() { let doc = parse("Line1\nLine2").unwrap(); let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new()); assert!(model.lines.len() >= 2); } #[test] fn uses_placeholder_when_param_not_set() { let doc = parse("${X}").unwrap(); let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new()); let PreviewLine::Text { content, .. } = &model.lines[0] else { panic!(); }; assert_eq!(content, "1234567890"); } #[test] fn uses_dialog_params_in_preview() { let doc = parse("Hello ${Name}").unwrap(); let mut params = HashMap::new(); params.insert("Name".into(), "Ada".into()); let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms); let PreviewLine::Text { content, .. } = &model.lines[0] else { panic!(); }; assert_eq!(content, "Hello Ada"); } #[test] fn renders_barcode_graphic() { let doc = parse("@barcode CODE128 TEST").unwrap(); let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new()); assert!(model .lines .iter() .any(|l| matches!(l, PreviewLine::Graphic { .. }))); } #[test] fn renders_barcode_with_unresolved_params() { let doc = parse("@barcode CODE128 ${DocumentNumber}").unwrap(); let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new()); assert!(model .lines .iter() .any(|l| matches!(l, PreviewLine::Graphic { .. }))); } #[test] fn renders_raster_code128_with_data_param() { let doc = parse( ":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n", ) .unwrap(); let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new()); let graphics = model .lines .iter() .filter(|l| matches!(l, PreviewLine::Graphic { .. })) .count(); let errors: Vec<_> = model .lines .iter() .filter_map(|l| match l { PreviewLine::Error { message, .. } => Some(message.as_str()), _ => None, }) .collect(); assert_eq!(graphics, 2, "expected QR and barcode graphics, errors: {errors:?}"); } #[test] fn empty_param_value_uses_barcode_placeholder() { let doc = parse("@barcode RASTER CODE128 ${Data}\n").unwrap(); let mut params = HashMap::new(); params.insert("Data".into(), String::new()); let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms); assert!(model .lines .iter() .any(|l| matches!(l, PreviewLine::Graphic { .. }))); } #[test] fn shared_data_param_url_still_renders_barcode_preview() { let doc = parse("@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n").unwrap(); let mut params = HashMap::new(); params.insert("Data".into(), "https://example.com".into()); let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms); let graphics = model .lines .iter() .filter(|l| matches!(l, PreviewLine::Graphic { .. })) .count(); assert_eq!(graphics, 2, "QR and barcode preview should both render"); } #[test] fn persistent_center_heading_uses_center_in_preview() { let doc = parse(":center:\n# Hello").unwrap(); let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new()); let PreviewLine::Text { align, content, .. } = &model.lines[0] else { panic!(); }; assert_eq!(content, "Hello"); assert_eq!(*align, Align::Center); } #[test] fn inline_left_right_is_one_preview_line() { let doc = parse(":left:appel:right:10").unwrap(); let meta = PosMetadata { chars_per_line: Some(32), ..Default::default() }; let model = render_preview(&doc, &meta, None, &HashMap::new()); let text_lines: Vec<_> = model .lines .iter() .filter_map(|l| match l { PreviewLine::Text { content, align, .. } => Some((content.as_str(), *align)), _ => None, }) .collect(); assert_eq!(text_lines.len(), 1); assert_eq!(text_lines[0].1, Align::Left); assert_eq!( text_lines[0].0, format!("appel{}10", " ".repeat(25)) ); } #[test] fn heading_wraps_in_preview_on_narrow_paper() { let doc = parse("# Proof of Transfer").unwrap(); let meta = PosMetadata { page_width_mm: 53.0, ..Default::default() }; let model = render_preview(&doc, &meta, None, &HashMap::new()); let text_lines: Vec<_> = model .lines .iter() .filter_map(|l| match l { PreviewLine::Text { content, style, .. } if *style == TextStyle::Heading1 => { Some(content.as_str()) } _ => None, }) .collect(); assert_eq!(text_lines, vec!["Proof of", "Transfer"]); } #[test] fn preview_width_matches_printable_dots() { let meta = PosMetadata { page_width_mm: 53.0, ..Default::default() }; assert_eq!( preview_content_width_px(&meta) as u16, meta.printable_dots() ); } #[test] fn spacer_height_matches_line_spacing() { let meta = PosMetadata::default(); let line = PreviewLine::Spacer(1); let h = preview_line_height_estimate(&line, &meta, 1.0); assert!((h - PREVIEW_LINE_SPACING_DOTS * PREVIEW_SCREEN_CALIBRATION).abs() < 0.01); } #[test] fn zoom_100_percent_uses_screen_calibration() { assert!((preview_visual_scale(1.0) - PREVIEW_SCREEN_CALIBRATION).abs() < 0.001); } #[test] fn font_size_matches_print_calibration() { let char_w = 6.0; assert!((preview_font_size_px(char_w) - char_w / 0.6).abs() < 0.001); } #[test] fn char_width_fits_columns_on_paper() { let meta = PosMetadata::default(); let width = preview_content_width_px(&meta) * preview_visual_scale(1.0); let char_w = preview_char_width_px(&meta, 1.0); assert!((char_w * meta.chars_per_line() as f32 - width).abs() < 0.01); } #[test] fn heading1_is_double_normal_text_height() { let meta = PosMetadata::default(); let normal = preview_line_height_estimate( &PreviewLine::Text { content: "x".into(), align: crate::dsl::Align::Left, style: TextStyle::Normal, }, &meta, 1.0, ); let heading = preview_line_height_estimate( &PreviewLine::Text { content: "x".into(), align: crate::dsl::Align::Left, style: TextStyle::Heading1, }, &meta, 1.0, ); assert!((heading - normal * 2.0).abs() < 0.01); } #[test] fn spacer_matches_normal_text_advance() { let meta = PosMetadata::default(); let spacer = preview_line_height_estimate(&PreviewLine::Spacer(1), &meta, 1.0); let text = preview_text_advance_px(TextStyle::Normal, 1.0); assert!((spacer - text).abs() < 0.01); } #[test] fn renders_bullet_list_with_hanging_indent() { let doc = parse("- this is a long line").unwrap(); let meta = PosMetadata { chars_per_line: Some(15), ..Default::default() }; let model = render_preview(&doc, &meta, None, &HashMap::new()); assert_eq!(model.lines.len(), 2); let PreviewLine::Text { content: first, .. } = &model.lines[0] else { panic!(); }; let PreviewLine::Text { content: second, .. } = &model.lines[1] else { panic!(); }; assert!(first.starts_with("* ")); assert!(second.starts_with(" ")); } }