| 1 | use std::collections::HashMap;
|
| 2 | use std::path::{Path, PathBuf};
|
| 3 |
|
| 4 | use image::GrayImage;
|
| 5 |
|
| 6 | use crate::dsl::{
|
| 7 | Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode,
|
| 8 | };
|
| 9 | use crate::io::PosMetadata;
|
| 10 | use crate::datetime;
|
| 11 | use crate::params::{preview_barcode_sample, substitute_for_preview, substitute_inlines_for_preview};
|
| 12 | use crate::raster::{render_barcode, render_qr, scale_gray_to_print_width};
|
| 13 | use crate::text_wrap::{self, TextWrapStyle};
|
| 14 |
|
| 15 | #[derive(Debug, Clone, PartialEq)]
|
| 16 | pub struct PreviewModel {
|
| 17 | pub lines: Vec<PreviewLine>,
|
| 18 | pub width_dots: u32,
|
| 19 | pub width_mm: f32,
|
| 20 | }
|
| 21 |
|
| 22 | #[derive(Debug, Clone, PartialEq)]
|
| 23 | pub 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)]
|
| 42 | pub enum TextStyle {
|
| 43 | #[default]
|
| 44 | Normal,
|
| 45 | Heading1,
|
| 46 | Heading2,
|
| 47 | Bold,
|
| 48 | Italic,
|
| 49 | Code,
|
| 50 | }
|
| 51 |
|
| 52 | pub fn render_preview(
|
| 53 | document: &Document,
|
| 54 | metadata: &PosMetadata,
|
| 55 | base_dir: Option<&Path>,
|
| 56 | preview_params: &HashMap<String, String>,
|
| 57 | ) -> PreviewModel {
|
| 58 | let width_dots = metadata.printable_dots() as u32;
|
| 59 | let mut lines = Vec::new();
|
| 60 |
|
| 61 | for block in &document.blocks {
|
| 62 | match block {
|
| 63 | Block::Paragraph { align, inlines } => {
|
| 64 | let text = substitute_inlines_for_preview(inlines, preview_params);
|
| 65 | let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
|
| 66 | for line in text_wrap::wrap_text(&text, cols) {
|
| 67 | lines.push(PreviewLine::Text {
|
| 68 | content: line,
|
| 69 | align: *align,
|
| 70 | style: TextStyle::Normal,
|
| 71 | });
|
| 72 | }
|
| 73 | }
|
| 74 | Block::Heading { level, align, inlines } => {
|
| 75 | let style = if *level == 1 {
|
| 76 | TextStyle::Heading1
|
| 77 | } else {
|
| 78 | TextStyle::Heading2
|
| 79 | };
|
| 80 | let wrap_style = if *level == 1 {
|
| 81 | TextWrapStyle::Heading1
|
| 82 | } else {
|
| 83 | TextWrapStyle::Heading2
|
| 84 | };
|
| 85 | let text = substitute_inlines_for_preview(inlines, preview_params);
|
| 86 | let cols = text_wrap::wrap_cols(metadata, wrap_style);
|
| 87 | for line in text_wrap::wrap_text(&text, cols) {
|
| 88 | lines.push(PreviewLine::Text {
|
| 89 | content: line,
|
| 90 | align: *align,
|
| 91 | style,
|
| 92 | });
|
| 93 | }
|
| 94 | }
|
| 95 | Block::Rule => lines.push(PreviewLine::Rule),
|
| 96 | Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)),
|
| 97 | Block::Cut => lines.push(PreviewLine::Text {
|
| 98 | content: "--- cut ---".into(),
|
| 99 | align: Align::Center,
|
| 100 | style: TextStyle::Code,
|
| 101 | }),
|
| 102 | Block::Image { path, width, align } => {
|
| 103 | let path = substitute_for_preview(path, preview_params);
|
| 104 | lines.push(render_image_preview(&path, *width, *align, metadata, base_dir));
|
| 105 | }
|
| 106 | Block::Barcode {
|
| 107 | mode,
|
| 108 | symbology,
|
| 109 | data,
|
| 110 | height,
|
| 111 | align,
|
| 112 | ..
|
| 113 | } => {
|
| 114 | let resolved = substitute_for_preview(data, preview_params);
|
| 115 | lines.push(render_barcode_preview(
|
| 116 | *mode,
|
| 117 | *symbology,
|
| 118 | data,
|
| 119 | &resolved,
|
| 120 | *height,
|
| 121 | *align,
|
| 122 | metadata,
|
| 123 | ));
|
| 124 | }
|
| 125 | Block::Qr {
|
| 126 | mode,
|
| 127 | data,
|
| 128 | size,
|
| 129 | ecc,
|
| 130 | version,
|
| 131 | align,
|
| 132 | } => {
|
| 133 | let data = substitute_for_preview(data, preview_params);
|
| 134 | lines.push(render_qr_preview(
|
| 135 | *mode, &data, *size, *ecc, *version, *align, metadata,
|
| 136 | ));
|
| 137 | }
|
| 138 | Block::Date { format, align } => {
|
| 139 | let text = datetime::format_date(format.as_deref());
|
| 140 | let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
|
| 141 | for line in text_wrap::wrap_text(&text, cols) {
|
| 142 | lines.push(PreviewLine::Text {
|
| 143 | content: line,
|
| 144 | align: *align,
|
| 145 | style: TextStyle::Normal,
|
| 146 | });
|
| 147 | }
|
| 148 | }
|
| 149 | Block::Time { format, align } => {
|
| 150 | let text = datetime::format_time(*format);
|
| 151 | let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
|
| 152 | for line in text_wrap::wrap_text(&text, cols) {
|
| 153 | lines.push(PreviewLine::Text {
|
| 154 | content: line,
|
| 155 | align: *align,
|
| 156 | style: TextStyle::Normal,
|
| 157 | });
|
| 158 | }
|
| 159 | }
|
| 160 | }
|
| 161 | }
|
| 162 |
|
| 163 | PreviewModel {
|
| 164 | lines,
|
| 165 | width_dots,
|
| 166 | width_mm: metadata.page_width_mm,
|
| 167 | }
|
| 168 | }
|
| 169 |
|
| 170 | fn render_barcode_preview(
|
| 171 | mode: BarcodeMode,
|
| 172 | symbology: BarcodeSymbology,
|
| 173 | template_data: &str,
|
| 174 | resolved_data: &str,
|
| 175 | height: u8,
|
| 176 | align: Align,
|
| 177 | metadata: &PosMetadata,
|
| 178 | ) -> PreviewLine {
|
| 179 | let height_px = u32::from(height.max(20));
|
| 180 | let resolved_data = resolved_data.trim();
|
| 181 | let print_width = metadata.printable_dots() as u32;
|
| 182 | match mode {
|
| 183 | BarcodeMode::Raster | BarcodeMode::Native => {
|
| 184 | match render_barcode(symbology, resolved_data, height_px) {
|
| 185 | Ok(img) => PreviewLine::Graphic {
|
| 186 | image: scale_gray_to_print_width(img, print_width),
|
| 187 | align,
|
| 188 | },
|
| 189 | Err(e) => {
|
| 190 | if template_data.contains("${") {
|
| 191 | if let Ok(img) =
|
| 192 | render_barcode(symbology, preview_barcode_sample(symbology), height_px)
|
| 193 | {
|
| 194 | return PreviewLine::Graphic {
|
| 195 | image: scale_gray_to_print_width(img, print_width),
|
| 196 | align,
|
| 197 | };
|
| 198 | }
|
| 199 | }
|
| 200 | PreviewLine::Error {
|
| 201 | message: format!(
|
| 202 | "barcode: {e} ({} supports alphanumeric data; URLs and punctuation often fail)",
|
| 203 | symbology.as_str()
|
| 204 | ),
|
| 205 | align,
|
| 206 | }
|
| 207 | }
|
| 208 | }
|
| 209 | }
|
| 210 | }
|
| 211 | }
|
| 212 |
|
| 213 | fn render_qr_preview(
|
| 214 | mode: QrMode,
|
| 215 | data: &str,
|
| 216 | size: u8,
|
| 217 | ecc: crate::dsl::QrEcc,
|
| 218 | version: Option<u8>,
|
| 219 | align: Align,
|
| 220 | metadata: &PosMetadata,
|
| 221 | ) -> PreviewLine {
|
| 222 | let module_pixels = u32::from(size.max(2));
|
| 223 | match mode {
|
| 224 | QrMode::Raster | QrMode::Native => match render_qr(data, version, ecc, module_pixels) {
|
| 225 | Ok(img) => {
|
| 226 | let max_w = (metadata.printable_dots() as u32).min(img.width());
|
| 227 | scale_graphic_to_width(img, max_w, align)
|
| 228 | }
|
| 229 | Err(e) => PreviewLine::Error {
|
| 230 | message: format!("qr: {e}"),
|
| 231 | align,
|
| 232 | },
|
| 233 | },
|
| 234 | }
|
| 235 | }
|
| 236 |
|
| 237 | fn render_image_preview(
|
| 238 | path: &str,
|
| 239 | width: ImageWidth,
|
| 240 | align: Align,
|
| 241 | metadata: &PosMetadata,
|
| 242 | base_dir: Option<&Path>,
|
| 243 | ) -> PreviewLine {
|
| 244 | let resolved = resolve_image_path(path, base_dir);
|
| 245 | match image::open(&resolved) {
|
| 246 | Ok(img) => {
|
| 247 | let gray = img.to_luma8();
|
| 248 | let target = target_image_width(width, metadata);
|
| 249 | let scaled = scale_gray_to_width(gray, target);
|
| 250 | PreviewLine::Graphic {
|
| 251 | image: scaled,
|
| 252 | align,
|
| 253 | }
|
| 254 | }
|
| 255 | Err(e) => PreviewLine::Error {
|
| 256 | message: format!("image {path}: {e}"),
|
| 257 | align,
|
| 258 | },
|
| 259 | }
|
| 260 | }
|
| 261 |
|
| 262 | fn scale_graphic_to_width(img: GrayImage, target_width: u32, align: Align) -> PreviewLine {
|
| 263 | PreviewLine::Graphic {
|
| 264 | image: scale_gray_to_width(img, target_width),
|
| 265 | align,
|
| 266 | }
|
| 267 | }
|
| 268 |
|
| 269 | fn scale_gray_to_width(gray: GrayImage, target_width: u32) -> GrayImage {
|
| 270 | let (w, h) = gray.dimensions();
|
| 271 | if w == 0 || h == 0 {
|
| 272 | return gray;
|
| 273 | }
|
| 274 | let new_w = target_width.min(w).max(1);
|
| 275 | if new_w == w {
|
| 276 | return gray;
|
| 277 | }
|
| 278 | let new_h = ((h as f32) * (new_w as f32 / w as f32)).max(1.0) as u32;
|
| 279 | image::imageops::resize(
|
| 280 | &gray,
|
| 281 | new_w,
|
| 282 | new_h,
|
| 283 | image::imageops::FilterType::Nearest,
|
| 284 | )
|
| 285 | }
|
| 286 |
|
| 287 | fn target_image_width(width: ImageWidth, metadata: &PosMetadata) -> u32 {
|
| 288 | match width {
|
| 289 | ImageWidth::Percent(pct) => {
|
| 290 | (metadata.printable_dots() as u32 * pct as u32 / 100).max(1)
|
| 291 | }
|
| 292 | ImageWidth::Dots(d) => d as u32,
|
| 293 | ImageWidth::Default => metadata.printable_dots() as u32,
|
| 294 | }
|
| 295 | }
|
| 296 |
|
| 297 | fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
|
| 298 | let p = Path::new(path);
|
| 299 | if p.is_absolute() {
|
| 300 | p.to_path_buf()
|
| 301 | } else if let Some(base) = base_dir {
|
| 302 | base.join(p)
|
| 303 | } else {
|
| 304 | p.to_path_buf()
|
| 305 | }
|
| 306 | }
|
| 307 |
|
| 308 | /// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
|
| 309 | pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
|
| 310 |
|
| 311 | /// Preview canvas width: one screen pixel per printer dot at zoom 1.0.
|
| 312 | pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 {
|
| 313 | metadata.printable_dots() as f32
|
| 314 | }
|
| 315 |
|
| 316 | /// Character cell width in preview pixels (matches print column width).
|
| 317 | pub fn preview_char_width_px(metadata: &PosMetadata, zoom: f32) -> f32 {
|
| 318 | preview_content_width_px(metadata) * preview_zoom_scale(zoom)
|
| 319 | / metadata.chars_per_line().max(1) as f32
|
| 320 | }
|
| 321 |
|
| 322 | /// Blank-line / `@feed` vertical space in preview pixels.
|
| 323 | pub fn preview_line_spacing_px(zoom: f32) -> f32 {
|
| 324 | PREVIEW_LINE_SPACING_DOTS * preview_zoom_scale(zoom)
|
| 325 | }
|
| 326 |
|
| 327 | /// User-controlled zoom factor applied on top of the dot-based layout.
|
| 328 | pub fn preview_zoom_scale(zoom: f32) -> f32 {
|
| 329 | zoom.clamp(0.25, 4.0)
|
| 330 | }
|
| 331 |
|
| 332 | /// Estimated line height for layout (text styles use galley at draw time).
|
| 333 | pub fn preview_line_height_estimate(
|
| 334 | line: &PreviewLine,
|
| 335 | metadata: &PosMetadata,
|
| 336 | zoom: f32,
|
| 337 | ) -> f32 {
|
| 338 | let scale = preview_zoom_scale(zoom);
|
| 339 | let char_w = preview_char_width_px(metadata, zoom);
|
| 340 | let line_sp = preview_line_spacing_px(zoom);
|
| 341 | match line {
|
| 342 | PreviewLine::Text { style, .. } => match style {
|
| 343 | TextStyle::Heading1 => char_w * 2.2,
|
| 344 | TextStyle::Heading2 => char_w * 1.8,
|
| 345 | _ => line_sp,
|
| 346 | },
|
| 347 | PreviewLine::Rule => 4.0 * scale,
|
| 348 | PreviewLine::Graphic { image, .. } => image.height() as f32 * scale,
|
| 349 | PreviewLine::Error { .. } => line_sp,
|
| 350 | PreviewLine::Spacer(n) => line_sp * (*n as f32),
|
| 351 | }
|
| 352 | }
|
| 353 |
|
| 354 | #[cfg(test)]
|
| 355 | mod tests {
|
| 356 | use super::*;
|
| 357 | use crate::dsl::parse;
|
| 358 | use std::collections::HashMap;
|
| 359 |
|
| 360 | #[test]
|
| 361 | fn renders_paragraph_lines() {
|
| 362 | let doc = parse("Line1\nLine2").unwrap();
|
| 363 | let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
|
| 364 | assert!(model.lines.len() >= 2);
|
| 365 | }
|
| 366 |
|
| 367 | #[test]
|
| 368 | fn uses_placeholder_when_param_not_set() {
|
| 369 | let doc = parse("${X}").unwrap();
|
| 370 | let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
|
| 371 | let PreviewLine::Text { content, .. } = &model.lines[0] else {
|
| 372 | panic!();
|
| 373 | };
|
| 374 | assert_eq!(content, "1234567890");
|
| 375 | }
|
| 376 |
|
| 377 | #[test]
|
| 378 | fn uses_dialog_params_in_preview() {
|
| 379 | let doc = parse("Hello ${Name}").unwrap();
|
| 380 | let mut params = HashMap::new();
|
| 381 | params.insert("Name".into(), "Ada".into());
|
| 382 | let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
|
| 383 | let PreviewLine::Text { content, .. } = &model.lines[0] else {
|
| 384 | panic!();
|
| 385 | };
|
| 386 | assert_eq!(content, "Hello Ada");
|
| 387 | }
|
| 388 |
|
| 389 | #[test]
|
| 390 | fn renders_barcode_graphic() {
|
| 391 | let doc = parse("@barcode CODE128 TEST").unwrap();
|
| 392 | let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
|
| 393 | assert!(model
|
| 394 | .lines
|
| 395 | .iter()
|
| 396 | .any(|l| matches!(l, PreviewLine::Graphic { .. })));
|
| 397 | }
|
| 398 |
|
| 399 | #[test]
|
| 400 | fn renders_barcode_with_unresolved_params() {
|
| 401 | let doc = parse("@barcode CODE128 ${DocumentNumber}").unwrap();
|
| 402 | let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
|
| 403 | assert!(model
|
| 404 | .lines
|
| 405 | .iter()
|
| 406 | .any(|l| matches!(l, PreviewLine::Graphic { .. })));
|
| 407 | }
|
| 408 |
|
| 409 | #[test]
|
| 410 | fn renders_raster_code128_with_data_param() {
|
| 411 | let doc = parse(
|
| 412 | ":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n",
|
| 413 | )
|
| 414 | .unwrap();
|
| 415 | let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
|
| 416 | let graphics = model
|
| 417 | .lines
|
| 418 | .iter()
|
| 419 | .filter(|l| matches!(l, PreviewLine::Graphic { .. }))
|
| 420 | .count();
|
| 421 | let errors: Vec<_> = model
|
| 422 | .lines
|
| 423 | .iter()
|
| 424 | .filter_map(|l| match l {
|
| 425 | PreviewLine::Error { message, .. } => Some(message.as_str()),
|
| 426 | _ => None,
|
| 427 | })
|
| 428 | .collect();
|
| 429 | assert_eq!(graphics, 2, "expected QR and barcode graphics, errors: {errors:?}");
|
| 430 | }
|
| 431 |
|
| 432 | #[test]
|
| 433 | fn empty_param_value_uses_barcode_placeholder() {
|
| 434 | let doc = parse("@barcode RASTER CODE128 ${Data}\n").unwrap();
|
| 435 | let mut params = HashMap::new();
|
| 436 | params.insert("Data".into(), String::new());
|
| 437 | let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
|
| 438 | assert!(model
|
| 439 | .lines
|
| 440 | .iter()
|
| 441 | .any(|l| matches!(l, PreviewLine::Graphic { .. })));
|
| 442 | }
|
| 443 |
|
| 444 | #[test]
|
| 445 | fn shared_data_param_url_still_renders_barcode_preview() {
|
| 446 | let doc = parse("@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n").unwrap();
|
| 447 | let mut params = HashMap::new();
|
| 448 | params.insert("Data".into(), "https://example.com".into());
|
| 449 | let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
|
| 450 | let graphics = model
|
| 451 | .lines
|
| 452 | .iter()
|
| 453 | .filter(|l| matches!(l, PreviewLine::Graphic { .. }))
|
| 454 | .count();
|
| 455 | assert_eq!(graphics, 2, "QR and barcode preview should both render");
|
| 456 | }
|
| 457 |
|
| 458 | #[test]
|
| 459 | fn persistent_center_heading_uses_center_in_preview() {
|
| 460 | let doc = parse(":center:\n# Hello").unwrap();
|
| 461 | let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
|
| 462 | let PreviewLine::Text { align, content, .. } = &model.lines[0] else {
|
| 463 | panic!();
|
| 464 | };
|
| 465 | assert_eq!(content, "Hello");
|
| 466 | assert_eq!(*align, Align::Center);
|
| 467 | }
|
| 468 |
|
| 469 | #[test]
|
| 470 | fn heading_wraps_in_preview_on_narrow_paper() {
|
| 471 | let doc = parse("# Proof of Transfer").unwrap();
|
| 472 | let meta = PosMetadata {
|
| 473 | page_width_mm: 53.0,
|
| 474 | ..Default::default()
|
| 475 | };
|
| 476 | let model = render_preview(&doc, &meta, None, &HashMap::new());
|
| 477 | let text_lines: Vec<_> = model
|
| 478 | .lines
|
| 479 | .iter()
|
| 480 | .filter_map(|l| match l {
|
| 481 | PreviewLine::Text { content, style, .. } if *style == TextStyle::Heading1 => {
|
| 482 | Some(content.as_str())
|
| 483 | }
|
| 484 | _ => None,
|
| 485 | })
|
| 486 | .collect();
|
| 487 | assert_eq!(text_lines, vec!["Proof of", "Transfer"]);
|
| 488 | }
|
| 489 |
|
| 490 | #[test]
|
| 491 | fn preview_width_matches_printable_dots() {
|
| 492 | let meta = PosMetadata {
|
| 493 | page_width_mm: 53.0,
|
| 494 | ..Default::default()
|
| 495 | };
|
| 496 | assert_eq!(
|
| 497 | preview_content_width_px(&meta) as u16,
|
| 498 | meta.printable_dots()
|
| 499 | );
|
| 500 | }
|
| 501 |
|
| 502 | #[test]
|
| 503 | fn spacer_height_matches_line_spacing() {
|
| 504 | let meta = PosMetadata::default();
|
| 505 | let line = PreviewLine::Spacer(1);
|
| 506 | let h = preview_line_height_estimate(&line, &meta, 1.0);
|
| 507 | assert!((h - PREVIEW_LINE_SPACING_DOTS).abs() < 0.01);
|
| 508 | }
|
| 509 | }
|