BlueGit

timfa posprint

Show a live preview beside the print-only dialog.

Print-only and posprint:// now use a split layout with receipt preview updating as parameters change.

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

timfa Tim Falken · pushed by timfa

Authored 2026-07-21 · 3 months ago

Hash
e2e43b713baee7863c8627adc67d009ecde68d72
Parent
4ac56a02
7 files changed +253 −170
docs/HELP-CLI-LINUX.md +1 −1
@@ -70,7 +70,7 @@ posprint link --help
70 70 posprint --help
71 71 ```
72 72
73 Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
73 Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) or `posprint --print` starts print-only mode: live preview on the left, parameters and printer on the right.
74 74
75 75 After package install, if `posprint://` links do not open:
76 76
@@ -70,7 +70,7 @@ posprint link --help
70posprint --help
70posprint --help
71```
71```
72
72
73Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
73Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) or `posprint --print` starts print-only mode: live preview on the left, parameters and printer on the right.
74
74
75After package install, if `posprint://` links do not open:
75After package install, if `posprint://` links do not open:
76
76
docs/HELP-CLI-WINDOWS.md +1 −1
@@ -60,4 +60,4 @@ posprint link --help
60 60 posprint --help
61 61 ```
62 62
63 Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
63 Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) or `posprint --print` starts print-only mode: live preview on the left, parameters and printer on the right.
@@ -60,4 +60,4 @@ posprint link --help
60posprint --help
60posprint --help
61```
61```
62
62
63Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
63Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) or `posprint --print` starts print-only mode: live preview on the left, parameters and printer on the right.
docs/HELP.md +2 −0
@@ -23,6 +23,8 @@ Built-in reference for the template editor and POS markup language.
23 23
24 24 While the Print dialog is open, the rest of the UI (including editor autocomplete) is disabled so parameter fields keep focus.
25 25
26 **Print-only mode** (`posprint --print`, Explorer Print, or a `posprint://` link) shows a live preview on the left and parameters / printer controls on the right. The preview updates as you type parameter values.
27
26 28 ## Editor assistance
27 29
28 30 - Type `@` at the start of a line for **directive autocomplete** (`feed`, `cut`, `image`, `barcode`, `qr`, `date`, `time`).
@@ -23,6 +23,8 @@ Built-in reference for the template editor and POS markup language.
23
23
24While the Print dialog is open, the rest of the UI (including editor autocomplete) is disabled so parameter fields keep focus.
24While the Print dialog is open, the rest of the UI (including editor autocomplete) is disabled so parameter fields keep focus.
25
25
26**Print-only mode** (`posprint --print`, Explorer Print, or a `posprint://` link) shows a live preview on the left and parameters / printer controls on the right. The preview updates as you type parameter values.
27
26## Editor assistance
28## Editor assistance
27
29
28- Type `@` at the start of a line for **directive autocomplete** (`feed`, `cut`, `image`, `barcode`, `qr`, `date`, `time`).
30- Type `@` at the start of a line for **directive autocomplete** (`feed`, `cut`, `image`, `barcode`, `qr`, `date`, `time`).
src/app.rs +14 −142
@@ -10,14 +10,10 @@ use posprint::editor_assist::{
10 10 };
11 11 use posprint::help_view;
12 12 use posprint::io::{PosFile, PosMetadata};
13 use posprint::preview::{
14 preview_char_width_px, preview_content_width_px, preview_font_size_px,
15 preview_line_height_estimate, preview_line_spacing_px, preview_text_advance_px,
16 preview_visual_scale, render_preview, PreviewLine, TextStyle,
17 };
18 13 use posprint::undo::TextUndo;
19 14 use posprint::HELP_MARKDOWN;
20 15
16 use crate::preview_panel::show_preview_panel;
21 17 use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
22 18
23 19 #[derive(Clone, Copy, PartialEq, Eq)]
@@ -524,150 +520,26 @@ impl PosPrintApp {
524 520 }
525 521
526 522 fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
527 let Ok(doc) = parse(&self.body) else {
528 ui.label("Fix parse errors to preview.");
529 return;
530 };
531
532 523 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
533 let model = render_preview(
534 &doc,
524 // Prefer live dialog inputs while the print dialog is open.
525 let params = if self.show_print_dialog {
526 &self.print_dialog.param_inputs
527 } else {
528 &self.print_dialog.last_params
529 };
530 show_preview_panel(
531 ui,
532 ctx,
533 &self.body,
535 534 &self.metadata,
536 535 base_dir,
537 &self.print_dialog.last_params,
536 params,
537 self.preview_zoom,
538 "design_preview_",
538 539 );
539 let visual_scale = preview_visual_scale(self.preview_zoom);
540 let content_width = preview_content_width_px(&self.metadata) * visual_scale;
541 let char_width = preview_char_width_px(&self.metadata, self.preview_zoom);
542 let line_spacing = preview_line_spacing_px(self.preview_zoom);
543 // No horizontal padding: wrap columns must match the full paper width.
544 let pad_y = 4.0 * visual_scale;
545
546 egui::ScrollArea::both()
547 .auto_shrink([false; 2])
548 .show(ui, |ui| {
549 egui::Frame::canvas(ui.style()).show(ui, |ui| {
550 let mut total_height = pad_y * 2.0;
551 for line in &model.lines {
552 total_height +=
553 preview_line_height_estimate(line, &self.metadata, self.preview_zoom);
554 }
555 total_height = total_height.max(100.0);
556
557 let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height));
558 let painter = ui.painter_at(rect);
559 painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
560 painter.rect_stroke(
561 rect,
562 4.0,
563 egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
564 egui::StrokeKind::Inside,
565 );
566
567 let mut y = rect.min.y + pad_y;
568 let inner_width = content_width;
569
570 for (idx, line) in model.lines.iter().enumerate() {
571 match line {
572 PreviewLine::Text {
573 content,
574 align,
575 style,
576 } => {
577 let font_id = preview_text_font(*style, char_width);
578 let galley = painter.layout_no_wrap(
579 content.clone(),
580 font_id,
581 egui::Color32::BLACK,
582 );
583 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
584 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
585 y += preview_text_advance_px(*style, self.preview_zoom);
586 }
587 PreviewLine::Rule => {
588 painter.line_segment(
589 [
590 egui::pos2(rect.min.x, y),
591 egui::pos2(rect.max.x, y),
592 ],
593 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
594 );
595 y += preview_line_spacing_px(self.preview_zoom);
596 }
597 PreviewLine::Graphic { image, align } => {
598 let tex = gray_to_texture(
599 ctx,
600 &format!("preview_graphic_{idx}"),
601 image,
602 );
603 let size = egui::vec2(
604 tex.size()[0] as f32 * visual_scale,
605 tex.size()[1] as f32 * visual_scale,
606 );
607 let x = align_x(*align, rect.min.x, inner_width, size.x);
608 painter.image(
609 tex.id(),
610 egui::Rect::from_min_size(egui::pos2(x, y), size),
611 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
612 egui::Color32::WHITE,
613 );
614 y += size.y;
615 }
616 PreviewLine::Error { message, align } => {
617 let galley = painter.layout(
618 message.clone(),
619 egui::FontId::proportional(12.0 * visual_scale),
620 egui::Color32::RED,
621 inner_width,
622 );
623 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
624 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
625 y += preview_line_spacing_px(self.preview_zoom);
626 }
627 PreviewLine::Spacer(n) => {
628 y += line_spacing * (*n as f32);
629 }
630 }
631 }
632 });
633 });
634 540 }
635 541 }
636 542
637 fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
638 let normal = preview_font_size_px(char_width);
639 match style {
640 // GS ! 0x11 — double width and double height
641 TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0),
642 TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal),
643 }
644 }
645
646 fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 {
647 match align {
648 dsl::Align::Left => left,
649 dsl::Align::Center => left + (inner_width - item_width) / 2.0,
650 dsl::Align::Right => left + inner_width - item_width,
651 }
652 }
653
654 fn gray_to_texture(
655 ctx: &egui::Context,
656 id: &str,
657 image: &image::GrayImage,
658 ) -> egui::TextureHandle {
659 let (w, h) = image.dimensions();
660 let pixels: Vec<egui::Color32> = image
661 .pixels()
662 .map(|p| egui::Color32::from_gray(p.0[0]))
663 .collect();
664 let color_image = egui::ColorImage {
665 size: [w as usize, h as usize],
666 pixels,
667 };
668 ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST)
669 }
670
671 543 fn default_template() -> String {
672 544 String::new()
673 545 }
@@ -10,14 +10,10 @@ use posprint::editor_assist::{
10};
10};
11use posprint::help_view;
11use posprint::help_view;
12use posprint::io::{PosFile, PosMetadata};
12use posprint::io::{PosFile, PosMetadata};
13use posprint::preview::{
14 preview_char_width_px, preview_content_width_px, preview_font_size_px,
15 preview_line_height_estimate, preview_line_spacing_px, preview_text_advance_px,
16 preview_visual_scale, render_preview, PreviewLine, TextStyle,
17};
18use posprint::undo::TextUndo;
13use posprint::undo::TextUndo;
19use posprint::HELP_MARKDOWN;
14use posprint::HELP_MARKDOWN;
20
15
16use crate::preview_panel::show_preview_panel;
21use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
17use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
22
18
23#[derive(Clone, Copy, PartialEq, Eq)]
19#[derive(Clone, Copy, PartialEq, Eq)]
@@ -524,150 +520,26 @@ impl PosPrintApp {
524 }
520 }
525
521
526 fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
522 fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
527 let Ok(doc) = parse(&self.body) else {
528 ui.label("Fix parse errors to preview.");
529 return;
530 };
531
532 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
523 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
533 let model = render_preview(
524 // Prefer live dialog inputs while the print dialog is open.
534 &doc,
525 let params = if self.show_print_dialog {
526 &self.print_dialog.param_inputs
527 } else {
528 &self.print_dialog.last_params
529 };
530 show_preview_panel(
531 ui,
532 ctx,
533 &self.body,
535 &self.metadata,
534 &self.metadata,
536 base_dir,
535 base_dir,
537 &self.print_dialog.last_params,
536 params,
537 self.preview_zoom,
538 "design_preview_",
538 );
539 );
539 let visual_scale = preview_visual_scale(self.preview_zoom);
540 let content_width = preview_content_width_px(&self.metadata) * visual_scale;
541 let char_width = preview_char_width_px(&self.metadata, self.preview_zoom);
542 let line_spacing = preview_line_spacing_px(self.preview_zoom);
543 // No horizontal padding: wrap columns must match the full paper width.
544 let pad_y = 4.0 * visual_scale;
545
546 egui::ScrollArea::both()
547 .auto_shrink([false; 2])
548 .show(ui, |ui| {
549 egui::Frame::canvas(ui.style()).show(ui, |ui| {
550 let mut total_height = pad_y * 2.0;
551 for line in &model.lines {
552 total_height +=
553 preview_line_height_estimate(line, &self.metadata, self.preview_zoom);
554 }
555 total_height = total_height.max(100.0);
556
557 let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height));
558 let painter = ui.painter_at(rect);
559 painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
560 painter.rect_stroke(
561 rect,
562 4.0,
563 egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
564 egui::StrokeKind::Inside,
565 );
566
567 let mut y = rect.min.y + pad_y;
568 let inner_width = content_width;
569
570 for (idx, line) in model.lines.iter().enumerate() {
571 match line {
572 PreviewLine::Text {
573 content,
574 align,
575 style,
576 } => {
577 let font_id = preview_text_font(*style, char_width);
578 let galley = painter.layout_no_wrap(
579 content.clone(),
580 font_id,
581 egui::Color32::BLACK,
582 );
583 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
584 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
585 y += preview_text_advance_px(*style, self.preview_zoom);
586 }
587 PreviewLine::Rule => {
588 painter.line_segment(
589 [
590 egui::pos2(rect.min.x, y),
591 egui::pos2(rect.max.x, y),
592 ],
593 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
594 );
595 y += preview_line_spacing_px(self.preview_zoom);
596 }
597 PreviewLine::Graphic { image, align } => {
598 let tex = gray_to_texture(
599 ctx,
600 &format!("preview_graphic_{idx}"),
601 image,
602 );
603 let size = egui::vec2(
604 tex.size()[0] as f32 * visual_scale,
605 tex.size()[1] as f32 * visual_scale,
606 );
607 let x = align_x(*align, rect.min.x, inner_width, size.x);
608 painter.image(
609 tex.id(),
610 egui::Rect::from_min_size(egui::pos2(x, y), size),
611 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
612 egui::Color32::WHITE,
613 );
614 y += size.y;
615 }
616 PreviewLine::Error { message, align } => {
617 let galley = painter.layout(
618 message.clone(),
619 egui::FontId::proportional(12.0 * visual_scale),
620 egui::Color32::RED,
621 inner_width,
622 );
623 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
624 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
625 y += preview_line_spacing_px(self.preview_zoom);
626 }
627 PreviewLine::Spacer(n) => {
628 y += line_spacing * (*n as f32);
629 }
630 }
631 }
632 });
633 });
634 }
540 }
635}
541}
636
542
637fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
638 let normal = preview_font_size_px(char_width);
639 match style {
640 // GS ! 0x11 — double width and double height
641 TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0),
642 TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal),
643 }
644}
645
646fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 {
647 match align {
648 dsl::Align::Left => left,
649 dsl::Align::Center => left + (inner_width - item_width) / 2.0,
650 dsl::Align::Right => left + inner_width - item_width,
651 }
652}
653
654fn gray_to_texture(
655 ctx: &egui::Context,
656 id: &str,
657 image: &image::GrayImage,
658) -> egui::TextureHandle {
659 let (w, h) = image.dimensions();
660 let pixels: Vec<egui::Color32> = image
661 .pixels()
662 .map(|p| egui::Color32::from_gray(p.0[0]))
663 .collect();
664 let color_image = egui::ColorImage {
665 size: [w as usize, h as usize],
666 pixels,
667 };
668 ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST)
669}
670
671fn default_template() -> String {
543fn default_template() -> String {
672 String::new()
544 String::new()
673}
545}
src/main.rs +3 −2
@@ -1,6 +1,7 @@
1 1 #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
2 2
3 3 mod app;
4 mod preview_panel;
4 5 mod print_dialog;
5 6 mod print_only_app;
6 7 mod shell_integration;
@@ -81,8 +82,8 @@ fn run_print_only_error(message: String) -> eframe::Result<()> {
81 82
82 83 fn run_print_only_app(app: print_only_app::PrintOnlyApp) -> eframe::Result<()> {
83 84 let mut viewport = eframe::egui::ViewportBuilder::default()
84 .with_inner_size([440.0, 420.0])
85 .with_min_inner_size([380.0, 320.0]);
85 .with_inner_size([960.0, 620.0])
86 .with_min_inner_size([720.0, 420.0]);
86 87 if let Some(icon) = load_viewport_icon() {
87 88 viewport = viewport.with_icon(icon);
88 89 }
@@ -1,6 +1,7 @@
1#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
1#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
2
2
3mod app;
3mod app;
4mod preview_panel;
4mod print_dialog;
5mod print_dialog;
5mod print_only_app;
6mod print_only_app;
6mod shell_integration;
7mod shell_integration;
@@ -81,8 +82,8 @@ fn run_print_only_error(message: String) -> eframe::Result<()> {
81
82
82fn run_print_only_app(app: print_only_app::PrintOnlyApp) -> eframe::Result<()> {
83fn run_print_only_app(app: print_only_app::PrintOnlyApp) -> eframe::Result<()> {
83 let mut viewport = eframe::egui::ViewportBuilder::default()
84 let mut viewport = eframe::egui::ViewportBuilder::default()
84 .with_inner_size([440.0, 420.0])
85 .with_inner_size([960.0, 620.0])
85 .with_min_inner_size([380.0, 320.0]);
86 .with_min_inner_size([720.0, 420.0]);
86 if let Some(icon) = load_viewport_icon() {
87 if let Some(icon) = load_viewport_icon() {
87 viewport = viewport.with_icon(icon);
88 viewport = viewport.with_icon(icon);
88 }
89 }
src/preview_panel.rs added +153 −0
@@ -0,0 +1,153 @@
1 //! Shared receipt preview canvas for Design and print-only views.
2
3 use std::collections::HashMap;
4 use std::path::Path;
5
6 use eframe::egui;
7
8 use posprint::dsl::{self, parse};
9 use posprint::io::PosMetadata;
10 use posprint::preview::{
11 preview_char_width_px, preview_content_width_px, preview_font_size_px,
12 preview_line_height_estimate, preview_line_spacing_px, preview_text_advance_px,
13 preview_visual_scale, render_preview, PreviewLine, TextStyle,
14 };
15
16 /// Draw a live receipt preview using current parameter values.
17 pub fn show_preview_panel(
18 ui: &mut egui::Ui,
19 ctx: &egui::Context,
20 body: &str,
21 metadata: &PosMetadata,
22 base_dir: Option<&Path>,
23 params: &HashMap<String, String>,
24 preview_zoom: f32,
25 texture_id_prefix: &str,
26 ) {
27 let Ok(doc) = parse(body) else {
28 ui.label("Fix parse errors to preview.");
29 return;
30 };
31
32 let model = render_preview(&doc, metadata, base_dir, params);
33 let visual_scale = preview_visual_scale(preview_zoom);
34 let content_width = preview_content_width_px(metadata) * visual_scale;
35 let char_width = preview_char_width_px(metadata, preview_zoom);
36 let line_spacing = preview_line_spacing_px(preview_zoom);
37 let pad_y = 4.0 * visual_scale;
38
39 egui::ScrollArea::both()
40 .auto_shrink([false; 2])
41 .show(ui, |ui| {
42 egui::Frame::canvas(ui.style()).show(ui, |ui| {
43 let mut total_height = pad_y * 2.0;
44 for line in &model.lines {
45 total_height += preview_line_height_estimate(line, metadata, preview_zoom);
46 }
47 total_height = total_height.max(100.0);
48
49 let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height));
50 let painter = ui.painter_at(rect);
51 painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
52 painter.rect_stroke(
53 rect,
54 4.0,
55 egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
56 egui::StrokeKind::Inside,
57 );
58
59 let mut y = rect.min.y + pad_y;
60 let inner_width = content_width;
61
62 for (idx, line) in model.lines.iter().enumerate() {
63 match line {
64 PreviewLine::Text {
65 content,
66 align,
67 style,
68 } => {
69 let font_id = preview_text_font(*style, char_width);
70 let galley =
71 painter.layout_no_wrap(content.clone(), font_id, egui::Color32::BLACK);
72 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
73 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
74 y += preview_text_advance_px(*style, preview_zoom);
75 }
76 PreviewLine::Rule => {
77 painter.line_segment(
78 [egui::pos2(rect.min.x, y), egui::pos2(rect.max.x, y)],
79 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
80 );
81 y += preview_line_spacing_px(preview_zoom);
82 }
83 PreviewLine::Graphic { image, align } => {
84 let tex = gray_to_texture(
85 ctx,
86 &format!("{texture_id_prefix}{idx}"),
87 image,
88 );
89 let size = egui::vec2(
90 tex.size()[0] as f32 * visual_scale,
91 tex.size()[1] as f32 * visual_scale,
92 );
93 let x = align_x(*align, rect.min.x, inner_width, size.x);
94 painter.image(
95 tex.id(),
96 egui::Rect::from_min_size(egui::pos2(x, y), size),
97 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
98 egui::Color32::WHITE,
99 );
100 y += size.y;
101 }
102 PreviewLine::Error { message, align } => {
103 let galley = painter.layout(
104 message.clone(),
105 egui::FontId::proportional(12.0 * visual_scale),
106 egui::Color32::RED,
107 inner_width,
108 );
109 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
110 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
111 y += preview_line_spacing_px(preview_zoom);
112 }
113 PreviewLine::Spacer(n) => {
114 y += line_spacing * (*n as f32);
115 }
116 }
117 }
118 });
119 });
120 }
121
122 fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
123 let normal = preview_font_size_px(char_width);
124 match style {
125 TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0),
126 TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal),
127 }
128 }
129
130 fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 {
131 match align {
132 dsl::Align::Left => left,
133 dsl::Align::Center => left + (inner_width - item_width) / 2.0,
134 dsl::Align::Right => left + inner_width - item_width,
135 }
136 }
137
138 fn gray_to_texture(
139 ctx: &egui::Context,
140 id: &str,
141 image: &image::GrayImage,
142 ) -> egui::TextureHandle {
143 let (w, h) = image.dimensions();
144 let pixels: Vec<egui::Color32> = image
145 .pixels()
146 .map(|p| egui::Color32::from_gray(p.0[0]))
147 .collect();
148 let color_image = egui::ColorImage {
149 size: [w as usize, h as usize],
150 pixels,
151 };
152 ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST)
153 }
@@ -0,0 +1,153 @@
1//! Shared receipt preview canvas for Design and print-only views.
2
3use std::collections::HashMap;
4use std::path::Path;
5
6use eframe::egui;
7
8use posprint::dsl::{self, parse};
9use posprint::io::PosMetadata;
10use posprint::preview::{
11 preview_char_width_px, preview_content_width_px, preview_font_size_px,
12 preview_line_height_estimate, preview_line_spacing_px, preview_text_advance_px,
13 preview_visual_scale, render_preview, PreviewLine, TextStyle,
14};
15
16/// Draw a live receipt preview using current parameter values.
17pub fn show_preview_panel(
18 ui: &mut egui::Ui,
19 ctx: &egui::Context,
20 body: &str,
21 metadata: &PosMetadata,
22 base_dir: Option<&Path>,
23 params: &HashMap<String, String>,
24 preview_zoom: f32,
25 texture_id_prefix: &str,
26) {
27 let Ok(doc) = parse(body) else {
28 ui.label("Fix parse errors to preview.");
29 return;
30 };
31
32 let model = render_preview(&doc, metadata, base_dir, params);
33 let visual_scale = preview_visual_scale(preview_zoom);
34 let content_width = preview_content_width_px(metadata) * visual_scale;
35 let char_width = preview_char_width_px(metadata, preview_zoom);
36 let line_spacing = preview_line_spacing_px(preview_zoom);
37 let pad_y = 4.0 * visual_scale;
38
39 egui::ScrollArea::both()
40 .auto_shrink([false; 2])
41 .show(ui, |ui| {
42 egui::Frame::canvas(ui.style()).show(ui, |ui| {
43 let mut total_height = pad_y * 2.0;
44 for line in &model.lines {
45 total_height += preview_line_height_estimate(line, metadata, preview_zoom);
46 }
47 total_height = total_height.max(100.0);
48
49 let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height));
50 let painter = ui.painter_at(rect);
51 painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
52 painter.rect_stroke(
53 rect,
54 4.0,
55 egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
56 egui::StrokeKind::Inside,
57 );
58
59 let mut y = rect.min.y + pad_y;
60 let inner_width = content_width;
61
62 for (idx, line) in model.lines.iter().enumerate() {
63 match line {
64 PreviewLine::Text {
65 content,
66 align,
67 style,
68 } => {
69 let font_id = preview_text_font(*style, char_width);
70 let galley =
71 painter.layout_no_wrap(content.clone(), font_id, egui::Color32::BLACK);
72 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
73 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
74 y += preview_text_advance_px(*style, preview_zoom);
75 }
76 PreviewLine::Rule => {
77 painter.line_segment(
78 [egui::pos2(rect.min.x, y), egui::pos2(rect.max.x, y)],
79 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
80 );
81 y += preview_line_spacing_px(preview_zoom);
82 }
83 PreviewLine::Graphic { image, align } => {
84 let tex = gray_to_texture(
85 ctx,
86 &format!("{texture_id_prefix}{idx}"),
87 image,
88 );
89 let size = egui::vec2(
90 tex.size()[0] as f32 * visual_scale,
91 tex.size()[1] as f32 * visual_scale,
92 );
93 let x = align_x(*align, rect.min.x, inner_width, size.x);
94 painter.image(
95 tex.id(),
96 egui::Rect::from_min_size(egui::pos2(x, y), size),
97 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
98 egui::Color32::WHITE,
99 );
100 y += size.y;
101 }
102 PreviewLine::Error { message, align } => {
103 let galley = painter.layout(
104 message.clone(),
105 egui::FontId::proportional(12.0 * visual_scale),
106 egui::Color32::RED,
107 inner_width,
108 );
109 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
110 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
111 y += preview_line_spacing_px(preview_zoom);
112 }
113 PreviewLine::Spacer(n) => {
114 y += line_spacing * (*n as f32);
115 }
116 }
117 }
118 });
119 });
120}
121
122fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
123 let normal = preview_font_size_px(char_width);
124 match style {
125 TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0),
126 TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal),
127 }
128}
129
130fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 {
131 match align {
132 dsl::Align::Left => left,
133 dsl::Align::Center => left + (inner_width - item_width) / 2.0,
134 dsl::Align::Right => left + inner_width - item_width,
135 }
136}
137
138fn gray_to_texture(
139 ctx: &egui::Context,
140 id: &str,
141 image: &image::GrayImage,
142) -> egui::TextureHandle {
143 let (w, h) = image.dimensions();
144 let pixels: Vec<egui::Color32> = image
145 .pixels()
146 .map(|p| egui::Color32::from_gray(p.0[0]))
147 .collect();
148 let color_image = egui::ColorImage {
149 size: [w as usize, h as usize],
150 pixels,
151 };
152 ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST)
153}
src/print_only_app.rs +79 −24
@@ -1,4 +1,4 @@
1 //! Minimal UI: print dialog only, then exit.
1 //! Print dialog + live preview, then exit.
2 2
3 3 use std::path::PathBuf;
4 4
@@ -6,6 +6,7 @@ use eframe::egui;
6 6
7 7 use posprint::io::{PosFile, PosMetadata};
8 8
9 use crate::preview_panel::show_preview_panel;
9 10 use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
10 11
11 12 pub struct PrintOnlyApp {
@@ -15,6 +16,7 @@ pub struct PrintOnlyApp {
15 16 file_path: Option<PathBuf>,
16 17 title_override: Option<String>,
17 18 dialog: PrintDialog,
19 preview_zoom: f32,
18 20 fatal_error: Option<String>,
19 21 exit_requested: bool,
20 22 }
@@ -27,6 +29,7 @@ impl PrintOnlyApp {
27 29 file_path: Some(path.clone()),
28 30 title_override: None,
29 31 dialog: PrintDialog::default(),
32 preview_zoom: 1.0,
30 33 fatal_error: None,
31 34 exit_requested: false,
32 35 };
@@ -52,6 +55,7 @@ impl PrintOnlyApp {
52 55 file_path: None,
53 56 title_override: Some(source_label.into()),
54 57 dialog: PrintDialog::default(),
58 preview_zoom: 1.0,
55 59 fatal_error: None,
56 60 exit_requested: false,
57 61 };
@@ -68,6 +72,7 @@ impl PrintOnlyApp {
68 72 file_path: None,
69 73 title_override: Some("posprint://".into()),
70 74 dialog: PrintDialog::default(),
75 preview_zoom: 1.0,
71 76 fatal_error: Some(message.into()),
72 77 exit_requested: false,
73 78 }
@@ -113,31 +118,81 @@ impl eframe::App for PrintOnlyApp {
113 118 return;
114 119 }
115 120
116 let mut window_open = true;
117 egui::Window::new("Print")
118 .collapsible(false)
119 .resizable(false)
120 .open(&mut window_open)
121 .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
122 .show(ctx, |ui| {
123 match self.dialog.show_ui(ui, "Cancel") {
124 PrintDialogAction::Cancel => self.request_exit(),
125 PrintDialogAction::Print => {
126 if self
127 .dialog
128 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
129 == PrintExecuteResult::Printed
130 {
131 self.request_exit();
132 }
133 }
134 PrintDialogAction::None => {}
135 }
121 let mut action = PrintDialogAction::None;
122
123 egui::CentralPanel::default().show(ctx, |ui| {
124 let available = ui.available_size();
125 // Preview left (~55%), print controls right.
126 let preview_width = (available.x * 0.55).clamp(280.0, available.x - 320.0);
127
128 ui.horizontal(|ui| {
129 ui.allocate_ui_with_layout(
130 egui::vec2(preview_width, available.y),
131 egui::Layout::top_down(egui::Align::Min),
132 |ui| {
133 ui.horizontal(|ui| {
134 ui.heading("Preview");
135 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
136 egui::ComboBox::from_id_salt("print_only_zoom")
137 .selected_text(format!("{:.0}%", self.preview_zoom * 100.0))
138 .show_ui(ui, |ui| {
139 for pct in [50, 75, 100, 125, 150, 200] {
140 let z = pct as f32 / 100.0;
141 ui.selectable_value(
142 &mut self.preview_zoom,
143 z,
144 format!("{pct}%"),
145 );
146 }
147 });
148 });
149 });
150 ui.separator();
151 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
152 show_preview_panel(
153 ui,
154 ctx,
155 &self.body,
156 &self.metadata,
157 base_dir,
158 &self.dialog.param_inputs,
159 self.preview_zoom,
160 "print_only_preview_",
161 );
162 },
163 );
164
165 ui.separator();
166
167 ui.allocate_ui_with_layout(
168 egui::vec2(ui.available_width(), available.y),
169 egui::Layout::top_down(egui::Align::Min),
170 |ui| {
171 egui::ScrollArea::vertical()
172 .auto_shrink([false; 2])
173 .show(ui, |ui| {
174 action = self.dialog.show_ui(ui, "Cancel");
175 });
176 },
177 );
136 178 });
179 });
137 180
138 if !window_open {
139 self.dialog.apply_inputs_to_last_params();
140 self.request_exit();
181 match action {
182 PrintDialogAction::Cancel => {
183 self.dialog.apply_inputs_to_last_params();
184 self.request_exit();
185 }
186 PrintDialogAction::Print => {
187 if self
188 .dialog
189 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
190 == PrintExecuteResult::Printed
191 {
192 self.request_exit();
193 }
194 }
195 PrintDialogAction::None => {}
141 196 }
142 197 }
143 198 }
@@ -1,4 +1,4 @@
1//! Minimal UI: print dialog only, then exit.
1//! Print dialog + live preview, then exit.
2
2
3use std::path::PathBuf;
3use std::path::PathBuf;
4
4
@@ -6,6 +6,7 @@ use eframe::egui;
6
6
7use posprint::io::{PosFile, PosMetadata};
7use posprint::io::{PosFile, PosMetadata};
8
8
9use crate::preview_panel::show_preview_panel;
9use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
10use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
10
11
11pub struct PrintOnlyApp {
12pub struct PrintOnlyApp {
@@ -15,6 +16,7 @@ pub struct PrintOnlyApp {
15 file_path: Option<PathBuf>,
16 file_path: Option<PathBuf>,
16 title_override: Option<String>,
17 title_override: Option<String>,
17 dialog: PrintDialog,
18 dialog: PrintDialog,
19 preview_zoom: f32,
18 fatal_error: Option<String>,
20 fatal_error: Option<String>,
19 exit_requested: bool,
21 exit_requested: bool,
20}
22}
@@ -27,6 +29,7 @@ impl PrintOnlyApp {
27 file_path: Some(path.clone()),
29 file_path: Some(path.clone()),
28 title_override: None,
30 title_override: None,
29 dialog: PrintDialog::default(),
31 dialog: PrintDialog::default(),
32 preview_zoom: 1.0,
30 fatal_error: None,
33 fatal_error: None,
31 exit_requested: false,
34 exit_requested: false,
32 };
35 };
@@ -52,6 +55,7 @@ impl PrintOnlyApp {
52 file_path: None,
55 file_path: None,
53 title_override: Some(source_label.into()),
56 title_override: Some(source_label.into()),
54 dialog: PrintDialog::default(),
57 dialog: PrintDialog::default(),
58 preview_zoom: 1.0,
55 fatal_error: None,
59 fatal_error: None,
56 exit_requested: false,
60 exit_requested: false,
57 };
61 };
@@ -68,6 +72,7 @@ impl PrintOnlyApp {
68 file_path: None,
72 file_path: None,
69 title_override: Some("posprint://".into()),
73 title_override: Some("posprint://".into()),
70 dialog: PrintDialog::default(),
74 dialog: PrintDialog::default(),
75 preview_zoom: 1.0,
71 fatal_error: Some(message.into()),
76 fatal_error: Some(message.into()),
72 exit_requested: false,
77 exit_requested: false,
73 }
78 }
@@ -113,31 +118,81 @@ impl eframe::App for PrintOnlyApp {
113 return;
118 return;
114 }
119 }
115
120
116 let mut window_open = true;
121 let mut action = PrintDialogAction::None;
117 egui::Window::new("Print")
122
118 .collapsible(false)
123 egui::CentralPanel::default().show(ctx, |ui| {
119 .resizable(false)
124 let available = ui.available_size();
120 .open(&mut window_open)
125 // Preview left (~55%), print controls right.
121 .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
126 let preview_width = (available.x * 0.55).clamp(280.0, available.x - 320.0);
122 .show(ctx, |ui| {
127
123 match self.dialog.show_ui(ui, "Cancel") {
128 ui.horizontal(|ui| {
124 PrintDialogAction::Cancel => self.request_exit(),
129 ui.allocate_ui_with_layout(
125 PrintDialogAction::Print => {
130 egui::vec2(preview_width, available.y),
126 if self
131 egui::Layout::top_down(egui::Align::Min),
127 .dialog
132 |ui| {
128 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
133 ui.horizontal(|ui| {
129 == PrintExecuteResult::Printed
134 ui.heading("Preview");
130 {
135 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
131 self.request_exit();
136 egui::ComboBox::from_id_salt("print_only_zoom")
132 }
137 .selected_text(format!("{:.0}%", self.preview_zoom * 100.0))
133 }
138 .show_ui(ui, |ui| {
134 PrintDialogAction::None => {}
139 for pct in [50, 75, 100, 125, 150, 200] {
135 }
140 let z = pct as f32 / 100.0;
141 ui.selectable_value(
142 &mut self.preview_zoom,
143 z,
144 format!("{pct}%"),
145 );
146 }
147 });
148 });
149 });
150 ui.separator();
151 let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
152 show_preview_panel(
153 ui,
154 ctx,
155 &self.body,
156 &self.metadata,
157 base_dir,
158 &self.dialog.param_inputs,
159 self.preview_zoom,
160 "print_only_preview_",
161 );
162 },
163 );
164
165 ui.separator();
166
167 ui.allocate_ui_with_layout(
168 egui::vec2(ui.available_width(), available.y),
169 egui::Layout::top_down(egui::Align::Min),
170 |ui| {
171 egui::ScrollArea::vertical()
172 .auto_shrink([false; 2])
173 .show(ui, |ui| {
174 action = self.dialog.show_ui(ui, "Cancel");
175 });
176 },
177 );
136 });
178 });
179 });
137
180
138 if !window_open {
181 match action {
139 self.dialog.apply_inputs_to_last_params();
182 PrintDialogAction::Cancel => {
140 self.request_exit();
183 self.dialog.apply_inputs_to_last_params();
184 self.request_exit();
185 }
186 PrintDialogAction::Print => {
187 if self
188 .dialog
189 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
190 == PrintExecuteResult::Printed
191 {
192 self.request_exit();
193 }
194 }
195 PrintDialogAction::None => {}
141 }
196 }
142 }
197 }
143}
198}