BlueGit

timfa posprint

Scaling and parsing for bulletpoint lists

timfa Tim Falken · pushed by timfa

Authored 2026-07-16 · 4 months ago

Hash
cfe7435b592bc16139f2d477bd3d4aab6592b4b0
Parent
aca7836e
11 files changed +442 −144
docs/ARCHITECTURE.md +1 −0
@@ -96,6 +96,7 @@ struct Document { blocks: Vec<Block> }
96 96
97 97 enum Block {
98 98 Paragraph { align, inlines },
99 List { align, items },
99 100 Heading { level, inlines },
100 101 Rule,
101 102 Feed(u8),
@@ -96,6 +96,7 @@ struct Document { blocks: Vec<Block> }
96
96
97enum Block {
97enum Block {
98 Paragraph { align, inlines },
98 Paragraph { align, inlines },
99 List { align, items },
99 Heading { level, inlines },
100 Heading { level, inlines },
100 Rule,
101 Rule,
101 Feed(u8),
102 Feed(u8),
docs/DSL-SPEC.md +21 −7
@@ -54,13 +54,27 @@ Total: ${Amount}
54 54 | `:center:` | Centered |
55 55 | `:right:` | Right-aligned |
56 56
57 ### Inline markup
57 ### Bullet lists
58
59 ```markdown
60 - Milk
61 - Bread
62 - Eggs
63 ```
64
65 Each line must start with `- ` (dash + space). Consecutive list lines form one list block. A blank line ends the list.
66
67 Wrapped lines use a hanging indent:
68
69 ```text
70 * this is a
71 long line
72 ```
73
74 ### Parameters
58 75
59 76 | Syntax | Effect |
60 77 |--------|--------|
61 | `**text**` | Bold |
62 | `*text*` | Italic / emphasized (printer secondary font if available) |
63 | `` `text` `` | Monospace / condensed |
64 78 | `${Name}` | Parameter placeholder (see Parameters) |
65 79
66 80 Parameters work inside any text, and inside barcode/QR/image directives (below).
@@ -71,7 +85,7 @@ Parameters work inside any text, and inside barcode/QR/image directives (below).
71 85 Receipt #${DocumentNumber}
72 86 Date: ${Date}
73 87
74 Item: ${ItemName} **${LineTotal}**
88 Item: ${ItemName} ${LineTotal}
75 89 ```
76 90
77 91 ### Horizontal rule
@@ -233,7 +247,6 @@ The parser reports:
233 247
234 248 - Unknown directive
235 249 - Invalid barcode symbology
236 - Unclosed `**` or `` ` ``
237 250 - Invalid `${}` name
238 251 - Missing required directive argument
239 252
@@ -246,7 +259,8 @@ Errors include 1-based line and column for editor highlighting.
246 259 | DSL | ESC/POS |
247 260 |-----|---------|
248 261 | `# heading` | Double width/height ON → text → OFF |
249 | `**bold**` | Bold ON/OFF |
262 | `## heading` | Bold ON → text → OFF |
263 | `- item` | ASCII `* ` bullet + hanging wrap |
250 264 | `:center:` | Justification center |
251 265 | `@feed n` | Print and feed n lines |
252 266 | `@cut` | GS V partial cut |
@@ -54,13 +54,27 @@ Total: ${Amount}
54| `:center:` | Centered |
54| `:center:` | Centered |
55| `:right:` | Right-aligned |
55| `:right:` | Right-aligned |
56
56
57### Inline markup
57### Bullet lists
58
59```markdown
60- Milk
61- Bread
62- Eggs
63```
64
65Each line must start with `- ` (dash + space). Consecutive list lines form one list block. A blank line ends the list.
66
67Wrapped lines use a hanging indent:
68
69```text
70* this is a
71 long line
72```
73
74### Parameters
58
75
59| Syntax | Effect |
76| Syntax | Effect |
60|--------|--------|
77|--------|--------|
61| `**text**` | Bold |
62| `*text*` | Italic / emphasized (printer secondary font if available) |
63| `` `text` `` | Monospace / condensed |
64| `${Name}` | Parameter placeholder (see Parameters) |
78| `${Name}` | Parameter placeholder (see Parameters) |
65
79
66Parameters work inside any text, and inside barcode/QR/image directives (below).
80Parameters work inside any text, and inside barcode/QR/image directives (below).
@@ -71,7 +85,7 @@ Parameters work inside any text, and inside barcode/QR/image directives (below).
71Receipt #${DocumentNumber}
85Receipt #${DocumentNumber}
72Date: ${Date}
86Date: ${Date}
73
87
74Item: ${ItemName} **${LineTotal}**
88Item: ${ItemName} ${LineTotal}
75```
89```
76
90
77### Horizontal rule
91### Horizontal rule
@@ -233,7 +247,6 @@ The parser reports:
233
247
234- Unknown directive
248- Unknown directive
235- Invalid barcode symbology
249- Invalid barcode symbology
236- Unclosed `**` or `` ` ``
237- Invalid `${}` name
250- Invalid `${}` name
238- Missing required directive argument
251- Missing required directive argument
239
252
@@ -246,7 +259,8 @@ Errors include 1-based line and column for editor highlighting.
246| DSL | ESC/POS |
259| DSL | ESC/POS |
247|-----|---------|
260|-----|---------|
248| `# heading` | Double width/height ON → text → OFF |
261| `# heading` | Double width/height ON → text → OFF |
249| `**bold**` | Bold ON/OFF |
262| `## heading` | Bold ON → text → OFF |
263| `- item` | ASCII `* ` bullet + hanging wrap |
250| `:center:` | Justification center |
264| `:center:` | Justification center |
251| `@feed n` | Print and feed n lines |
265| `@feed n` | Print and feed n lines |
252| `@cut` | GS V partial cut |
266| `@cut` | GS V partial cut |
docs/HELP.md +17 −6
@@ -32,9 +32,9 @@ Built-in reference for the template editor and POS markup language.
32 32 | Setting | Description |
33 33 |---------|-------------|
34 34 | **Page width (mm)** | Paper width — set this to match your physical roll (e.g. `53`, `58`, `80`) |
35 | **Preview zoom** | Screen zoom only; layout uses printer dots at 100% |
35 | **Preview zoom** | Screen zoom; `100%` is calibrated to typical receipt width on screen |
36 36
37 Preview width matches printable dots (203 DPI). Blank lines in the editor feed paper the same as `@feed 1`.
37 Preview width and text both use the same calibrated screen scale. Preview font size is bumped to match printed Font A (~same visual size as the receipt). Blank lines / `@feed` use the same line spacing as printed text. Heading `#` uses double width/height like GS `!` on the printer; `##` uses bold only.
38 38
39 39 If the document does not end with `@cut` (ignoring blank lines after it), a red warning appears next to **Help**.
40 40
@@ -59,13 +59,24 @@ Consecutive non-empty lines form one paragraph.
59 59
60 60 `:left:`, `:center:`, or `:right:` before a paragraph.
61 61
62 ### Inline markup
62 ### Bullet lists
63
64 ```markdown
65 - first item
66 - second item
67 ```
68
69 Long items wrap with a hanging indent:
70
71 ```text
72 * this is a
73 long line
74 ```
75
76 ### Parameters
63 77
64 78 | Syntax | Effect |
65 79 |--------|--------|
66 | `**text**` | Bold |
67 | `*text*` | Italic |
68 | `` `text` `` | Monospace |
69 80 | `${Name}` | Parameter (filled at print time) |
70 81
71 82 ### Horizontal rule
@@ -32,9 +32,9 @@ Built-in reference for the template editor and POS markup language.
32| Setting | Description |
32| Setting | Description |
33|---------|-------------|
33|---------|-------------|
34| **Page width (mm)** | Paper width — set this to match your physical roll (e.g. `53`, `58`, `80`) |
34| **Page width (mm)** | Paper width — set this to match your physical roll (e.g. `53`, `58`, `80`) |
35| **Preview zoom** | Screen zoom only; layout uses printer dots at 100% |
35| **Preview zoom** | Screen zoom; `100%` is calibrated to typical receipt width on screen |
36
36
37Preview width matches printable dots (203 DPI). Blank lines in the editor feed paper the same as `@feed 1`.
37Preview width and text both use the same calibrated screen scale. Preview font size is bumped to match printed Font A (~same visual size as the receipt). Blank lines / `@feed` use the same line spacing as printed text. Heading `#` uses double width/height like GS `!` on the printer; `##` uses bold only.
38
38
39If the document does not end with `@cut` (ignoring blank lines after it), a red warning appears next to **Help**.
39If the document does not end with `@cut` (ignoring blank lines after it), a red warning appears next to **Help**.
40
40
@@ -59,13 +59,24 @@ Consecutive non-empty lines form one paragraph.
59
59
60`:left:`, `:center:`, or `:right:` before a paragraph.
60`:left:`, `:center:`, or `:right:` before a paragraph.
61
61
62### Inline markup
62### Bullet lists
63
64```markdown
65- first item
66- second item
67```
68
69Long items wrap with a hanging indent:
70
71```text
72* this is a
73 long line
74```
75
76### Parameters
63
77
64| Syntax | Effect |
78| Syntax | Effect |
65|--------|--------|
79|--------|--------|
66| `**text**` | Bold |
67| `*text*` | Italic |
68| `` `text` `` | Monospace |
69| `${Name}` | Parameter (filled at print time) |
80| `${Name}` | Parameter (filled at print time) |
70
81
71### Horizontal rule
82### Horizontal rule
docs/PRINTING.md +3 −2
@@ -25,10 +25,11 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
25 25 |---------|---------|--------|
26 26 | Initialize | ESC @ | `escpos.rs` |
27 27 | Code page | ESC t 0 (CP437) | Always CP437 today; metadata field reserved |
28 | Bold | ESC E | Headings level 2, `**text**` flattened at encode |
28 | Bold | ESC E | Headings level 2 only |
29 29 | Double size | GS ! | Heading level 1 |
30 30 | Alignment | ESC a | Paragraphs, images, barcodes, QR |
31 | Line feed | LF, ESC d | Text lines, `@feed` |
31 | Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text lines end with LF; explicit feeds use ESC d |
32 | List bullet | ASCII `*` | `- item` lines in templates |
32 33 | Partial cut | GS V 66 0 | `@cut` in template |
33 34 | Barcode | GS k | CODE128, EAN13, EAN8, CODE39 |
34 35 | QR Code | GS ( k | Model 2 |
@@ -25,10 +25,11 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
25|---------|---------|--------|
25|---------|---------|--------|
26| Initialize | ESC @ | `escpos.rs` |
26| Initialize | ESC @ | `escpos.rs` |
27| Code page | ESC t 0 (CP437) | Always CP437 today; metadata field reserved |
27| Code page | ESC t 0 (CP437) | Always CP437 today; metadata field reserved |
28| Bold | ESC E | Headings level 2, `**text**` flattened at encode |
28| Bold | ESC E | Headings level 2 only |
29| Double size | GS ! | Heading level 1 |
29| Double size | GS ! | Heading level 1 |
30| Alignment | ESC a | Paragraphs, images, barcodes, QR |
30| Alignment | ESC a | Paragraphs, images, barcodes, QR |
31| Line feed | LF, ESC d | Text lines, `@feed` |
31| Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text lines end with LF; explicit feeds use ESC d |
32| List bullet | ASCII `*` | `- item` lines in templates |
32| Partial cut | GS V 66 0 | `@cut` in template |
33| Partial cut | GS V 66 0 | `@cut` in template |
33| Barcode | GS k | CODE128, EAN13, EAN8, CODE39 |
34| Barcode | GS k | CODE128, EAN13, EAN8, CODE39 |
34| QR Code | GS ( k | Model 2 |
35| QR Code | GS ( k | Model 2 |
src/app.rs +23 −27
@@ -11,8 +11,9 @@ use posprint::editor_assist::{
11 11 use posprint::help_view;
12 12 use posprint::io::{PosFile, PosMetadata};
13 13 use posprint::preview::{
14 preview_char_width_px, preview_content_width_px, preview_line_height_estimate,
15 preview_line_spacing_px, preview_zoom_scale, render_preview, PreviewLine, TextStyle,
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,
16 17 };
17 18 use posprint::undo::TextUndo;
18 19 use posprint::HELP_MARKDOWN;
@@ -514,21 +515,21 @@ impl PosPrintApp {
514 515 base_dir,
515 516 &self.print_dialog.last_params,
516 517 );
517 let visual_scale = preview_zoom_scale(self.preview_zoom);
518 let visual_scale = preview_visual_scale(self.preview_zoom);
518 519 let content_width = preview_content_width_px(&self.metadata) * visual_scale;
519 520 let char_width = preview_char_width_px(&self.metadata, self.preview_zoom);
520 521 let line_spacing = preview_line_spacing_px(self.preview_zoom);
521 let padding = 8.0 * visual_scale;
522 // No horizontal padding: wrap columns must match the full paper width.
523 let pad_y = 4.0 * visual_scale;
522 524
523 525 egui::ScrollArea::both()
524 526 .auto_shrink([false; 2])
525 527 .show(ui, |ui| {
526 528 egui::Frame::canvas(ui.style()).show(ui, |ui| {
527 let mut total_height = padding * 2.0;
529 let mut total_height = pad_y * 2.0;
528 530 for line in &model.lines {
529 531 total_height +=
530 preview_line_height_estimate(line, &self.metadata, self.preview_zoom)
531 + 2.0;
532 preview_line_height_estimate(line, &self.metadata, self.preview_zoom);
532 533 }
533 534 total_height = total_height.max(100.0);
534 535
@@ -542,8 +543,8 @@ impl PosPrintApp {
542 543 egui::StrokeKind::Inside,
543 544 );
544 545
545 let mut y = rect.min.y + padding;
546 let inner_width = content_width - padding * 2.0;
546 let mut y = rect.min.y + pad_y;
547 let inner_width = content_width;
547 548
548 549 for (idx, line) in model.lines.iter().enumerate() {
549 550 match line {
@@ -558,20 +559,19 @@ impl PosPrintApp {
558 559 font_id,
559 560 egui::Color32::BLACK,
560 561 );
561 let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
562 let line_h = galley.size().y;
562 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
563 563 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
564 y += line_h + 2.0 * visual_scale;
564 y += preview_text_advance_px(*style, self.preview_zoom);
565 565 }
566 566 PreviewLine::Rule => {
567 567 painter.line_segment(
568 568 [
569 egui::pos2(rect.min.x + padding, y),
570 egui::pos2(rect.max.x - padding, y),
569 egui::pos2(rect.min.x, y),
570 egui::pos2(rect.max.x, y),
571 571 ],
572 572 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
573 573 );
574 y += 12.0 * visual_scale;
574 y += preview_line_spacing_px(self.preview_zoom);
575 575 }
576 576 PreviewLine::Graphic { image, align } => {
577 577 let tex = gray_to_texture(
@@ -583,14 +583,14 @@ impl PosPrintApp {
583 583 tex.size()[0] as f32 * visual_scale,
584 584 tex.size()[1] as f32 * visual_scale,
585 585 );
586 let x = align_x(*align, rect.min.x + padding, inner_width, size.x);
586 let x = align_x(*align, rect.min.x, inner_width, size.x);
587 587 painter.image(
588 588 tex.id(),
589 589 egui::Rect::from_min_size(egui::pos2(x, y), size),
590 590 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
591 591 egui::Color32::WHITE,
592 592 );
593 y += size.y + 2.0 * visual_scale;
593 y += size.y;
594 594 }
595 595 PreviewLine::Error { message, align } => {
596 596 let galley = painter.layout(
@@ -599,10 +599,9 @@ impl PosPrintApp {
599 599 egui::Color32::RED,
600 600 inner_width,
601 601 );
602 let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
603 let line_h = galley.size().y;
602 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
604 603 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
605 y += line_h + 4.0 * visual_scale;
604 y += preview_line_spacing_px(self.preview_zoom);
606 605 }
607 606 PreviewLine::Spacer(n) => {
608 607 y += line_spacing * (*n as f32);
@@ -615,14 +614,11 @@ impl PosPrintApp {
615 614 }
616 615
617 616 fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
618 let base = char_width * 0.9;
617 let normal = preview_font_size_px(char_width);
619 618 match style {
620 TextStyle::Heading1 => egui::FontId::monospace(base * 2.0),
621 TextStyle::Heading2 => egui::FontId::monospace(base * 1.5),
622 TextStyle::Bold => egui::FontId::monospace(base * 1.05),
623 TextStyle::Italic => egui::FontId::monospace(base),
624 TextStyle::Code => egui::FontId::monospace(base),
625 TextStyle::Normal => egui::FontId::monospace(base),
619 // GS ! 0x11 — double width and double height
620 TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0),
621 TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal),
626 622 }
627 623 }
628 624
@@ -11,8 +11,9 @@ use posprint::editor_assist::{
11use posprint::help_view;
11use posprint::help_view;
12use posprint::io::{PosFile, PosMetadata};
12use posprint::io::{PosFile, PosMetadata};
13use posprint::preview::{
13use posprint::preview::{
14 preview_char_width_px, preview_content_width_px, preview_line_height_estimate,
14 preview_char_width_px, preview_content_width_px, preview_font_size_px,
15 preview_line_spacing_px, preview_zoom_scale, render_preview, PreviewLine, TextStyle,
15 preview_line_height_estimate, preview_line_spacing_px, preview_text_advance_px,
16 preview_visual_scale, render_preview, PreviewLine, TextStyle,
16};
17};
17use posprint::undo::TextUndo;
18use posprint::undo::TextUndo;
18use posprint::HELP_MARKDOWN;
19use posprint::HELP_MARKDOWN;
@@ -514,21 +515,21 @@ impl PosPrintApp {
514 base_dir,
515 base_dir,
515 &self.print_dialog.last_params,
516 &self.print_dialog.last_params,
516 );
517 );
517 let visual_scale = preview_zoom_scale(self.preview_zoom);
518 let visual_scale = preview_visual_scale(self.preview_zoom);
518 let content_width = preview_content_width_px(&self.metadata) * visual_scale;
519 let content_width = preview_content_width_px(&self.metadata) * visual_scale;
519 let char_width = preview_char_width_px(&self.metadata, self.preview_zoom);
520 let char_width = preview_char_width_px(&self.metadata, self.preview_zoom);
520 let line_spacing = preview_line_spacing_px(self.preview_zoom);
521 let line_spacing = preview_line_spacing_px(self.preview_zoom);
521 let padding = 8.0 * visual_scale;
522 // No horizontal padding: wrap columns must match the full paper width.
523 let pad_y = 4.0 * visual_scale;
522
524
523 egui::ScrollArea::both()
525 egui::ScrollArea::both()
524 .auto_shrink([false; 2])
526 .auto_shrink([false; 2])
525 .show(ui, |ui| {
527 .show(ui, |ui| {
526 egui::Frame::canvas(ui.style()).show(ui, |ui| {
528 egui::Frame::canvas(ui.style()).show(ui, |ui| {
527 let mut total_height = padding * 2.0;
529 let mut total_height = pad_y * 2.0;
528 for line in &model.lines {
530 for line in &model.lines {
529 total_height +=
531 total_height +=
530 preview_line_height_estimate(line, &self.metadata, self.preview_zoom)
532 preview_line_height_estimate(line, &self.metadata, self.preview_zoom);
531 + 2.0;
532 }
533 }
533 total_height = total_height.max(100.0);
534 total_height = total_height.max(100.0);
534
535
@@ -542,8 +543,8 @@ impl PosPrintApp {
542 egui::StrokeKind::Inside,
543 egui::StrokeKind::Inside,
543 );
544 );
544
545
545 let mut y = rect.min.y + padding;
546 let mut y = rect.min.y + pad_y;
546 let inner_width = content_width - padding * 2.0;
547 let inner_width = content_width;
547
548
548 for (idx, line) in model.lines.iter().enumerate() {
549 for (idx, line) in model.lines.iter().enumerate() {
549 match line {
550 match line {
@@ -558,20 +559,19 @@ impl PosPrintApp {
558 font_id,
559 font_id,
559 egui::Color32::BLACK,
560 egui::Color32::BLACK,
560 );
561 );
561 let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
562 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
562 let line_h = galley.size().y;
563 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
563 painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
564 y += line_h + 2.0 * visual_scale;
564 y += preview_text_advance_px(*style, self.preview_zoom);
565 }
565 }
566 PreviewLine::Rule => {
566 PreviewLine::Rule => {
567 painter.line_segment(
567 painter.line_segment(
568 [
568 [
569 egui::pos2(rect.min.x + padding, y),
569 egui::pos2(rect.min.x, y),
570 egui::pos2(rect.max.x - padding, y),
570 egui::pos2(rect.max.x, y),
571 ],
571 ],
572 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
572 egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
573 );
573 );
574 y += 12.0 * visual_scale;
574 y += preview_line_spacing_px(self.preview_zoom);
575 }
575 }
576 PreviewLine::Graphic { image, align } => {
576 PreviewLine::Graphic { image, align } => {
577 let tex = gray_to_texture(
577 let tex = gray_to_texture(
@@ -583,14 +583,14 @@ impl PosPrintApp {
583 tex.size()[0] as f32 * visual_scale,
583 tex.size()[0] as f32 * visual_scale,
584 tex.size()[1] as f32 * visual_scale,
584 tex.size()[1] as f32 * visual_scale,
585 );
585 );
586 let x = align_x(*align, rect.min.x + padding, inner_width, size.x);
586 let x = align_x(*align, rect.min.x, inner_width, size.x);
587 painter.image(
587 painter.image(
588 tex.id(),
588 tex.id(),
589 egui::Rect::from_min_size(egui::pos2(x, y), size),
589 egui::Rect::from_min_size(egui::pos2(x, y), size),
590 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
590 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
591 egui::Color32::WHITE,
591 egui::Color32::WHITE,
592 );
592 );
593 y += size.y + 2.0 * visual_scale;
593 y += size.y;
594 }
594 }
595 PreviewLine::Error { message, align } => {
595 PreviewLine::Error { message, align } => {
596 let galley = painter.layout(
596 let galley = painter.layout(
@@ -599,10 +599,9 @@ impl PosPrintApp {
599 egui::Color32::RED,
599 egui::Color32::RED,
600 inner_width,
600 inner_width,
601 );
601 );
602 let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
602 let x = align_x(*align, rect.min.x, inner_width, galley.size().x);
603 let line_h = galley.size().y;
604 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
603 painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
605 y += line_h + 4.0 * visual_scale;
604 y += preview_line_spacing_px(self.preview_zoom);
606 }
605 }
607 PreviewLine::Spacer(n) => {
606 PreviewLine::Spacer(n) => {
608 y += line_spacing * (*n as f32);
607 y += line_spacing * (*n as f32);
@@ -615,14 +614,11 @@ impl PosPrintApp {
615}
614}
616
615
617fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
616fn preview_text_font(style: TextStyle, char_width: f32) -> egui::FontId {
618 let base = char_width * 0.9;
617 let normal = preview_font_size_px(char_width);
619 match style {
618 match style {
620 TextStyle::Heading1 => egui::FontId::monospace(base * 2.0),
619 // GS ! 0x11 — double width and double height
621 TextStyle::Heading2 => egui::FontId::monospace(base * 1.5),
620 TextStyle::Heading1 => egui::FontId::monospace(normal * 2.0),
622 TextStyle::Bold => egui::FontId::monospace(base * 1.05),
621 TextStyle::Heading2 | TextStyle::Normal => egui::FontId::monospace(normal),
623 TextStyle::Italic => egui::FontId::monospace(base),
624 TextStyle::Code => egui::FontId::monospace(base),
625 TextStyle::Normal => egui::FontId::monospace(base),
626 }
622 }
627}
623}
628
624
src/dsl/mod.rs +4 −3
@@ -30,6 +30,10 @@ pub enum Block {
30 30 align: Align,
31 31 inlines: Vec<Inline>,
32 32 },
33 List {
34 align: Align,
35 items: Vec<Vec<Inline>>,
36 },
33 37 Heading {
34 38 level: u8,
35 39 align: Align,
@@ -130,9 +134,6 @@ pub enum QrEcc {
130 134 #[derive(Debug, Clone, PartialEq, Eq)]
131 135 pub enum Inline {
132 136 Text(String),
133 Bold(Vec<Inline>),
134 Italic(Vec<Inline>),
135 Code(String),
136 137 Param(String),
137 138 }
138 139
@@ -30,6 +30,10 @@ pub enum Block {
30 align: Align,
30 align: Align,
31 inlines: Vec<Inline>,
31 inlines: Vec<Inline>,
32 },
32 },
33 List {
34 align: Align,
35 items: Vec<Vec<Inline>>,
36 },
33 Heading {
37 Heading {
34 level: u8,
38 level: u8,
35 align: Align,
39 align: Align,
@@ -130,9 +134,6 @@ pub enum QrEcc {
130#[derive(Debug, Clone, PartialEq, Eq)]
134#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum Inline {
135pub enum Inline {
132 Text(String),
136 Text(String),
133 Bold(Vec<Inline>),
134 Italic(Vec<Inline>),
135 Code(String),
136 Param(String),
137 Param(String),
137}
138}
138
139
src/dsl/parser.rs +73 −56
@@ -55,11 +55,34 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
55 55 continue;
56 56 }
57 57
58 if seg_text.trim_start().starts_with('@') {
58 if seg_text.trim_start().starts_with("@") {
59 59 blocks.push(parse_directive(seg_text.trim(), line_no, *seg_align)?);
60 60 continue;
61 61 }
62 62
63 if is_list_item_line(seg_text) {
64 let mut items = vec![parse_list_item_inlines(seg_text, line_no)?];
65 while let Some(&next) = lines.peek() {
66 if is_blank_feed_line(next)
67 || next.starts_with('#')
68 || next.trim() == "---"
69 || next.trim_start().starts_with('@')
70 || parse_align_line(next).is_some()
71 || !is_list_item_line(next.trim_end())
72 {
73 break;
74 }
75 line_no += 1;
76 let next_line = lines.next().unwrap().trim_end();
77 items.push(parse_list_item_inlines(next_line, line_no)?);
78 }
79 blocks.push(Block::List {
80 align: *seg_align,
81 items,
82 });
83 continue;
84 }
85
63 86 if allow_multiline_paragraph {
64 87 let mut paragraph_lines = vec![seg_text.clone()];
65 88 while let Some(&next) = lines.peek() {
@@ -68,6 +91,7 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
68 91 || next.trim() == "---"
69 92 || next.trim_start().starts_with('@')
70 93 || parse_align_line(next).is_some()
94 || is_list_item_line(next.trim_end())
71 95 {
72 96 break;
73 97 }
@@ -498,6 +522,21 @@ fn parse_align_value(value: &str, line_no: usize) -> Result<Align, ParseError> {
498 522 }
499 523 }
500 524
525 fn is_list_item_line(line: &str) -> bool {
526 line.trim_start().starts_with("- ")
527 }
528
529 fn list_item_text(line: &str) -> &str {
530 line.trim_start()
531 .strip_prefix("- ")
532 .map(str::trim_end)
533 .unwrap_or(line.trim_end())
534 }
535
536 fn parse_list_item_inlines(line: &str, line_no: usize) -> Result<Vec<Inline>, ParseError> {
537 parse_inlines(list_item_text(line), line_no, 1)
538 }
539
501 540 fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
502 541 let mut out = Vec::new();
503 542 let mut i = 0usize;
@@ -524,35 +563,8 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
524 563 i = j + 1;
525 564 continue;
526 565 }
527 if chars[i] == '*' && i + 1 < chars.len() && chars[i + 1] == '*' {
528 let (inner, next) = parse_delimited(&chars, i + 2, "**", line, col)?;
529 out.push(Inline::Bold(parse_inlines(&inner, line, col + i + 2)?));
530 i = next;
531 continue;
532 }
533 if chars[i] == '*' {
534 let (inner, next) = parse_delimited(&chars, i + 1, "*", line, col)?;
535 out.push(Inline::Italic(parse_inlines(&inner, line, col + i + 1)?));
536 i = next;
537 continue;
538 }
539 if chars[i] == '`' {
540 let (inner, next) = parse_delimited(&chars, i + 1, "`", line, col)?;
541 out.push(Inline::Code(inner));
542 i = next;
543 continue;
544 }
545 566 let start = i;
546 while i < chars.len()
547 && !matches!(chars[i], '$' | '*' | '`')
548 && !(chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{')
549 {
550 if chars[i] == '$' {
551 break;
552 }
553 if chars[i] == '*' || chars[i] == '`' {
554 break;
555 }
567 while i < chars.len() && chars[i] != '$' {
556 568 i += 1;
557 569 }
558 570 if i == start {
@@ -564,29 +576,6 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
564 576 Ok(out)
565 577 }
566 578
567 fn parse_delimited(
568 chars: &[char],
569 start: usize,
570 marker: &str,
571 line: usize,
572 col: usize,
573 ) -> Result<(String, usize), ParseError> {
574 let mlen = marker.chars().count();
575 let mut i = start;
576 while i < chars.len() {
577 if chars[i..].iter().collect::<String>().starts_with(marker) {
578 let inner: String = chars[start..i].iter().collect();
579 return Ok((inner, i + mlen));
580 }
581 i += 1;
582 }
583 Err(err(
584 line,
585 col + start,
586 format!("unclosed delimiter '{marker}'"),
587 ))
588 }
589
590 579 fn is_valid_param_name(name: &str) -> bool {
591 580 let mut chars = name.chars();
592 581 match chars.next() {
@@ -613,8 +602,7 @@ mod tests {
613 602 let mut out = String::new();
614 603 for inline in inlines {
615 604 match inline {
616 Inline::Text(t) | Inline::Code(t) | Inline::Param(t) => out.push_str(t),
617 Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_text(inner)),
605 Inline::Text(t) | Inline::Param(t) => out.push_str(t),
618 606 }
619 607 }
620 608 out
@@ -622,12 +610,34 @@ mod tests {
622 610
623 611 #[test]
624 612 fn parses_heading_and_paragraph() {
625 let doc = parse("# Store\nHello **world**").unwrap();
613 let doc = parse("# Store\nHello world").unwrap();
626 614 assert_eq!(doc.blocks.len(), 2);
627 615 assert!(matches!(doc.blocks[0], Block::Heading { level: 1, .. }));
628 616 assert!(matches!(doc.blocks[1], Block::Paragraph { .. }));
629 617 }
630 618
619 #[test]
620 fn parses_bullet_list() {
621 let doc = parse("- this\n- is then\n- a list").unwrap();
622 assert_eq!(doc.blocks.len(), 1);
623 let Block::List { items, .. } = &doc.blocks[0] else {
624 panic!("expected list");
625 };
626 assert_eq!(items.len(), 3);
627 assert_eq!(inlines_to_text(&items[0]), "this");
628 assert_eq!(inlines_to_text(&items[1]), "is then");
629 assert_eq!(inlines_to_text(&items[2]), "a list");
630 }
631
632 #[test]
633 fn blank_line_breaks_bullet_list() {
634 let doc = parse("- one\n\n- two").unwrap();
635 assert_eq!(doc.blocks.len(), 3);
636 assert!(matches!(doc.blocks[0], Block::List { .. }));
637 assert!(matches!(doc.blocks[1], Block::Feed(1)));
638 assert!(matches!(doc.blocks[2], Block::List { .. }));
639 }
640
631 641 #[test]
632 642 fn parses_parameters() {
633 643 let doc = parse("Order ${OrderId}").unwrap();
@@ -829,7 +839,14 @@ mod tests {
829 839 #[test]
830 840 fn blank_line_between_barcode_and_qr_is_feed() {
831 841 let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
832 assert!(doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))));
842 assert!(matches!(
843 doc.blocks.as_slice(),
844 [
845 Block::Barcode { .. },
846 Block::Feed(1),
847 Block::Qr { .. },
848 ]
849 ));
833 850 }
834 851
835 852 #[test]
@@ -55,11 +55,34 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
55 continue;
55 continue;
56 }
56 }
57
57
58 if seg_text.trim_start().starts_with('@') {
58 if seg_text.trim_start().starts_with("@") {
59 blocks.push(parse_directive(seg_text.trim(), line_no, *seg_align)?);
59 blocks.push(parse_directive(seg_text.trim(), line_no, *seg_align)?);
60 continue;
60 continue;
61 }
61 }
62
62
63 if is_list_item_line(seg_text) {
64 let mut items = vec![parse_list_item_inlines(seg_text, line_no)?];
65 while let Some(&next) = lines.peek() {
66 if is_blank_feed_line(next)
67 || next.starts_with('#')
68 || next.trim() == "---"
69 || next.trim_start().starts_with('@')
70 || parse_align_line(next).is_some()
71 || !is_list_item_line(next.trim_end())
72 {
73 break;
74 }
75 line_no += 1;
76 let next_line = lines.next().unwrap().trim_end();
77 items.push(parse_list_item_inlines(next_line, line_no)?);
78 }
79 blocks.push(Block::List {
80 align: *seg_align,
81 items,
82 });
83 continue;
84 }
85
63 if allow_multiline_paragraph {
86 if allow_multiline_paragraph {
64 let mut paragraph_lines = vec![seg_text.clone()];
87 let mut paragraph_lines = vec![seg_text.clone()];
65 while let Some(&next) = lines.peek() {
88 while let Some(&next) = lines.peek() {
@@ -68,6 +91,7 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
68 || next.trim() == "---"
91 || next.trim() == "---"
69 || next.trim_start().starts_with('@')
92 || next.trim_start().starts_with('@')
70 || parse_align_line(next).is_some()
93 || parse_align_line(next).is_some()
94 || is_list_item_line(next.trim_end())
71 {
95 {
72 break;
96 break;
73 }
97 }
@@ -498,6 +522,21 @@ fn parse_align_value(value: &str, line_no: usize) -> Result<Align, ParseError> {
498 }
522 }
499}
523}
500
524
525fn is_list_item_line(line: &str) -> bool {
526 line.trim_start().starts_with("- ")
527}
528
529fn list_item_text(line: &str) -> &str {
530 line.trim_start()
531 .strip_prefix("- ")
532 .map(str::trim_end)
533 .unwrap_or(line.trim_end())
534}
535
536fn parse_list_item_inlines(line: &str, line_no: usize) -> Result<Vec<Inline>, ParseError> {
537 parse_inlines(list_item_text(line), line_no, 1)
538}
539
501fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
540fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
502 let mut out = Vec::new();
541 let mut out = Vec::new();
503 let mut i = 0usize;
542 let mut i = 0usize;
@@ -524,35 +563,8 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
524 i = j + 1;
563 i = j + 1;
525 continue;
564 continue;
526 }
565 }
527 if chars[i] == '*' && i + 1 < chars.len() && chars[i + 1] == '*' {
528 let (inner, next) = parse_delimited(&chars, i + 2, "**", line, col)?;
529 out.push(Inline::Bold(parse_inlines(&inner, line, col + i + 2)?));
530 i = next;
531 continue;
532 }
533 if chars[i] == '*' {
534 let (inner, next) = parse_delimited(&chars, i + 1, "*", line, col)?;
535 out.push(Inline::Italic(parse_inlines(&inner, line, col + i + 1)?));
536 i = next;
537 continue;
538 }
539 if chars[i] == '`' {
540 let (inner, next) = parse_delimited(&chars, i + 1, "`", line, col)?;
541 out.push(Inline::Code(inner));
542 i = next;
543 continue;
544 }
545 let start = i;
566 let start = i;
546 while i < chars.len()
567 while i < chars.len() && chars[i] != '$' {
547 && !matches!(chars[i], '$' | '*' | '`')
548 && !(chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{')
549 {
550 if chars[i] == '$' {
551 break;
552 }
553 if chars[i] == '*' || chars[i] == '`' {
554 break;
555 }
556 i += 1;
568 i += 1;
557 }
569 }
558 if i == start {
570 if i == start {
@@ -564,29 +576,6 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
564 Ok(out)
576 Ok(out)
565}
577}
566
578
567fn parse_delimited(
568 chars: &[char],
569 start: usize,
570 marker: &str,
571 line: usize,
572 col: usize,
573) -> Result<(String, usize), ParseError> {
574 let mlen = marker.chars().count();
575 let mut i = start;
576 while i < chars.len() {
577 if chars[i..].iter().collect::<String>().starts_with(marker) {
578 let inner: String = chars[start..i].iter().collect();
579 return Ok((inner, i + mlen));
580 }
581 i += 1;
582 }
583 Err(err(
584 line,
585 col + start,
586 format!("unclosed delimiter '{marker}'"),
587 ))
588}
589
590fn is_valid_param_name(name: &str) -> bool {
579fn is_valid_param_name(name: &str) -> bool {
591 let mut chars = name.chars();
580 let mut chars = name.chars();
592 match chars.next() {
581 match chars.next() {
@@ -613,8 +602,7 @@ mod tests {
613 let mut out = String::new();
602 let mut out = String::new();
614 for inline in inlines {
603 for inline in inlines {
615 match inline {
604 match inline {
616 Inline::Text(t) | Inline::Code(t) | Inline::Param(t) => out.push_str(t),
605 Inline::Text(t) | Inline::Param(t) => out.push_str(t),
617 Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_text(inner)),
618 }
606 }
619 }
607 }
620 out
608 out
@@ -622,12 +610,34 @@ mod tests {
622
610
623 #[test]
611 #[test]
624 fn parses_heading_and_paragraph() {
612 fn parses_heading_and_paragraph() {
625 let doc = parse("# Store\nHello **world**").unwrap();
613 let doc = parse("# Store\nHello world").unwrap();
626 assert_eq!(doc.blocks.len(), 2);
614 assert_eq!(doc.blocks.len(), 2);
627 assert!(matches!(doc.blocks[0], Block::Heading { level: 1, .. }));
615 assert!(matches!(doc.blocks[0], Block::Heading { level: 1, .. }));
628 assert!(matches!(doc.blocks[1], Block::Paragraph { .. }));
616 assert!(matches!(doc.blocks[1], Block::Paragraph { .. }));
629 }
617 }
630
618
619 #[test]
620 fn parses_bullet_list() {
621 let doc = parse("- this\n- is then\n- a list").unwrap();
622 assert_eq!(doc.blocks.len(), 1);
623 let Block::List { items, .. } = &doc.blocks[0] else {
624 panic!("expected list");
625 };
626 assert_eq!(items.len(), 3);
627 assert_eq!(inlines_to_text(&items[0]), "this");
628 assert_eq!(inlines_to_text(&items[1]), "is then");
629 assert_eq!(inlines_to_text(&items[2]), "a list");
630 }
631
632 #[test]
633 fn blank_line_breaks_bullet_list() {
634 let doc = parse("- one\n\n- two").unwrap();
635 assert_eq!(doc.blocks.len(), 3);
636 assert!(matches!(doc.blocks[0], Block::List { .. }));
637 assert!(matches!(doc.blocks[1], Block::Feed(1)));
638 assert!(matches!(doc.blocks[2], Block::List { .. }));
639 }
640
631 #[test]
641 #[test]
632 fn parses_parameters() {
642 fn parses_parameters() {
633 let doc = parse("Order ${OrderId}").unwrap();
643 let doc = parse("Order ${OrderId}").unwrap();
@@ -829,7 +839,14 @@ mod tests {
829 #[test]
839 #[test]
830 fn blank_line_between_barcode_and_qr_is_feed() {
840 fn blank_line_between_barcode_and_qr_is_feed() {
831 let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
841 let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
832 assert!(doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))));
842 assert!(matches!(
843 doc.blocks.as_slice(),
844 [
845 Block::Barcode { .. },
846 Block::Feed(1),
847 Block::Qr { .. },
848 ]
849 ));
833 }
850 }
834
851
835 #[test]
852 #[test]
src/escpos.rs +65 −12
@@ -65,6 +65,16 @@ impl EscPosEncoder {
65 65 self.writeln(&part);
66 66 }
67 67 }
68 Block::List { align, items } => {
69 self.set_align(*align);
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
71 for item in items {
72 let line = inlines_to_plain(item);
73 for part in text_wrap::wrap_bullet_item(&line, cols) {
74 self.writeln(&part);
75 }
76 }
77 }
68 78 Block::Heading { level, align, inlines } => {
69 79 self.set_align(*align);
70 80 let wrap_style = if *level == 1 {
@@ -173,10 +183,11 @@ impl EscPosEncoder {
173 183 }
174 184
175 185 fn feed(&mut self, lines: u8) {
176 // LF feeds match print-bridge / node-escpos; ESC d is unreliable after raster graphics.
177 for _ in 0..lines {
178 self.buffer.push(b'\n');
186 if lines == 0 {
187 return;
179 188 }
189 // ESC d — reliable paper feed after raster graphics (print-bridge uses this too).
190 self.buffer.extend_from_slice(&[0x1B, b'd', lines]);
180 191 }
181 192
182 193 fn cut(&mut self) {
@@ -320,6 +331,8 @@ impl EscPosEncoder {
320 331 self.buffer
321 332 .extend_from_slice(&[0x1D, b'v', 0x30, 0x00, x_l, x_h, y_l, y_h]);
322 333 self.buffer.extend_from_slice(&raster);
334 // LF prints/flushes the raster; without it the next graphic can butt against this one.
335 self.buffer.push(b'\n');
323 336 Ok(())
324 337 }
325 338 }
@@ -339,9 +352,8 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
339 352 let mut out = String::new();
340 353 for inline in inlines {
341 354 match inline {
342 Inline::Text(t) | Inline::Code(t) => out.push_str(t),
355 Inline::Text(t) => out.push_str(t),
343 356 Inline::Param(t) => out.push_str(t),
344 Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_plain(inner)),
345 357 }
346 358 }
347 359 out
@@ -350,7 +362,7 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
350 362 #[cfg(test)]
351 363 mod tests {
352 364 use super::*;
353 use crate::dsl::parse;
365 use crate::dsl::{parse, Block};
354 366
355 367 #[test]
356 368 fn heading_wraps_like_preview_on_narrow_paper() {
@@ -371,6 +383,20 @@ mod tests {
371 383 );
372 384 }
373 385
386 #[test]
387 fn encodes_bullet_list_with_hanging_indent() {
388 let doc = parse("- this is a long line").unwrap();
389 let meta = PosMetadata {
390 chars_per_line: Some(15),
391 ..Default::default()
392 };
393 let mut enc = EscPosEncoder::new(meta);
394 let bytes = enc.encode_document(&doc).unwrap();
395 let text = String::from_utf8_lossy(bytes);
396 assert!(text.contains("* this is a\n"));
397 assert!(text.contains(" long line\n"));
398 }
399
374 400 #[test]
375 401 fn encodes_init_and_text() {
376 402 let doc = parse("Hello").unwrap();
@@ -442,18 +468,29 @@ mod tests {
442 468 }
443 469
444 470 #[test]
445 fn feed_uses_line_feed_not_esc_d() {
471 fn feed_uses_esc_d_for_blank_lines() {
446 472 let doc = parse("A\n\nB").unwrap();
447 473 let mut enc = EscPosEncoder::new(PosMetadata::default());
448 474 let bytes = enc.encode_document(&doc).unwrap();
449 assert!(bytes.contains(&b'\n'));
450 assert!(!bytes.windows(2).any(|w| w == [0x1B, b'd']));
475 assert!(bytes.windows(3).any(|w| w == [0x1B, b'd', 1]));
476 }
477
478 #[test]
479 fn blank_line_between_barcode_and_qr_is_ordered_feed() {
480 let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
481 assert!(matches!(
482 doc.blocks.as_slice(),
483 [
484 Block::Barcode { .. },
485 Block::Feed(1),
486 Block::Qr { .. },
487 ]
488 ));
451 489 }
452 490
453 491 #[test]
454 492 fn blank_line_between_graphics_feeds_on_print() {
455 493 let doc = parse("@barcode RASTER CODE128 X\n\n@qr RASTER Y scale=4").unwrap();
456 assert!(doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))));
457 494 let mut enc = EscPosEncoder::new(PosMetadata {
458 495 page_width_mm: 53.0,
459 496 ..Default::default()
@@ -468,8 +505,24 @@ mod tests {
468 505 assert_eq!(raster_positions.len(), 2);
469 506 let between = &bytes[raster_positions[0]..raster_positions[1]];
470 507 assert!(
471 between.contains(&b'\n'),
472 "expected line feed between raster graphics"
508 between.windows(3).any(|w| w == [0x1B, b'd', 1]),
509 "expected ESC d feed between raster graphics, got {} bytes",
510 between.len()
511 );
512 }
513
514 #[test]
515 fn raster_graphic_ends_with_line_feed() {
516 let doc = parse("@barcode RASTER CODE128 X").unwrap();
517 let mut enc = EscPosEncoder::new(PosMetadata::default());
518 let bytes = enc.encode_document(&doc).unwrap();
519 let raster_start = bytes
520 .windows(4)
521 .position(|w| w == [0x1D, b'v', 0x30, 0x00])
522 .expect("raster header");
523 assert!(
524 bytes[raster_start..].contains(&b'\n'),
525 "expected LF after raster data"
473 526 );
474 527 }
475 528
@@ -65,6 +65,16 @@ impl EscPosEncoder {
65 self.writeln(&part);
65 self.writeln(&part);
66 }
66 }
67 }
67 }
68 Block::List { align, items } => {
69 self.set_align(*align);
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
71 for item in items {
72 let line = inlines_to_plain(item);
73 for part in text_wrap::wrap_bullet_item(&line, cols) {
74 self.writeln(&part);
75 }
76 }
77 }
68 Block::Heading { level, align, inlines } => {
78 Block::Heading { level, align, inlines } => {
69 self.set_align(*align);
79 self.set_align(*align);
70 let wrap_style = if *level == 1 {
80 let wrap_style = if *level == 1 {
@@ -173,10 +183,11 @@ impl EscPosEncoder {
173 }
183 }
174
184
175 fn feed(&mut self, lines: u8) {
185 fn feed(&mut self, lines: u8) {
176 // LF feeds match print-bridge / node-escpos; ESC d is unreliable after raster graphics.
186 if lines == 0 {
177 for _ in 0..lines {
187 return;
178 self.buffer.push(b'\n');
179 }
188 }
189 // ESC d — reliable paper feed after raster graphics (print-bridge uses this too).
190 self.buffer.extend_from_slice(&[0x1B, b'd', lines]);
180 }
191 }
181
192
182 fn cut(&mut self) {
193 fn cut(&mut self) {
@@ -320,6 +331,8 @@ impl EscPosEncoder {
320 self.buffer
331 self.buffer
321 .extend_from_slice(&[0x1D, b'v', 0x30, 0x00, x_l, x_h, y_l, y_h]);
332 .extend_from_slice(&[0x1D, b'v', 0x30, 0x00, x_l, x_h, y_l, y_h]);
322 self.buffer.extend_from_slice(&raster);
333 self.buffer.extend_from_slice(&raster);
334 // LF prints/flushes the raster; without it the next graphic can butt against this one.
335 self.buffer.push(b'\n');
323 Ok(())
336 Ok(())
324 }
337 }
325}
338}
@@ -339,9 +352,8 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
339 let mut out = String::new();
352 let mut out = String::new();
340 for inline in inlines {
353 for inline in inlines {
341 match inline {
354 match inline {
342 Inline::Text(t) | Inline::Code(t) => out.push_str(t),
355 Inline::Text(t) => out.push_str(t),
343 Inline::Param(t) => out.push_str(t),
356 Inline::Param(t) => out.push_str(t),
344 Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_plain(inner)),
345 }
357 }
346 }
358 }
347 out
359 out
@@ -350,7 +362,7 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
350#[cfg(test)]
362#[cfg(test)]
351mod tests {
363mod tests {
352 use super::*;
364 use super::*;
353 use crate::dsl::parse;
365 use crate::dsl::{parse, Block};
354
366
355 #[test]
367 #[test]
356 fn heading_wraps_like_preview_on_narrow_paper() {
368 fn heading_wraps_like_preview_on_narrow_paper() {
@@ -371,6 +383,20 @@ mod tests {
371 );
383 );
372 }
384 }
373
385
386 #[test]
387 fn encodes_bullet_list_with_hanging_indent() {
388 let doc = parse("- this is a long line").unwrap();
389 let meta = PosMetadata {
390 chars_per_line: Some(15),
391 ..Default::default()
392 };
393 let mut enc = EscPosEncoder::new(meta);
394 let bytes = enc.encode_document(&doc).unwrap();
395 let text = String::from_utf8_lossy(bytes);
396 assert!(text.contains("* this is a\n"));
397 assert!(text.contains(" long line\n"));
398 }
399
374 #[test]
400 #[test]
375 fn encodes_init_and_text() {
401 fn encodes_init_and_text() {
376 let doc = parse("Hello").unwrap();
402 let doc = parse("Hello").unwrap();
@@ -442,18 +468,29 @@ mod tests {
442 }
468 }
443
469
444 #[test]
470 #[test]
445 fn feed_uses_line_feed_not_esc_d() {
471 fn feed_uses_esc_d_for_blank_lines() {
446 let doc = parse("A\n\nB").unwrap();
472 let doc = parse("A\n\nB").unwrap();
447 let mut enc = EscPosEncoder::new(PosMetadata::default());
473 let mut enc = EscPosEncoder::new(PosMetadata::default());
448 let bytes = enc.encode_document(&doc).unwrap();
474 let bytes = enc.encode_document(&doc).unwrap();
449 assert!(bytes.contains(&b'\n'));
475 assert!(bytes.windows(3).any(|w| w == [0x1B, b'd', 1]));
450 assert!(!bytes.windows(2).any(|w| w == [0x1B, b'd']));
476 }
477
478 #[test]
479 fn blank_line_between_barcode_and_qr_is_ordered_feed() {
480 let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap();
481 assert!(matches!(
482 doc.blocks.as_slice(),
483 [
484 Block::Barcode { .. },
485 Block::Feed(1),
486 Block::Qr { .. },
487 ]
488 ));
451 }
489 }
452
490
453 #[test]
491 #[test]
454 fn blank_line_between_graphics_feeds_on_print() {
492 fn blank_line_between_graphics_feeds_on_print() {
455 let doc = parse("@barcode RASTER CODE128 X\n\n@qr RASTER Y scale=4").unwrap();
493 let doc = parse("@barcode RASTER CODE128 X\n\n@qr RASTER Y scale=4").unwrap();
456 assert!(doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))));
457 let mut enc = EscPosEncoder::new(PosMetadata {
494 let mut enc = EscPosEncoder::new(PosMetadata {
458 page_width_mm: 53.0,
495 page_width_mm: 53.0,
459 ..Default::default()
496 ..Default::default()
@@ -468,8 +505,24 @@ mod tests {
468 assert_eq!(raster_positions.len(), 2);
505 assert_eq!(raster_positions.len(), 2);
469 let between = &bytes[raster_positions[0]..raster_positions[1]];
506 let between = &bytes[raster_positions[0]..raster_positions[1]];
470 assert!(
507 assert!(
471 between.contains(&b'\n'),
508 between.windows(3).any(|w| w == [0x1B, b'd', 1]),
472 "expected line feed between raster graphics"
509 "expected ESC d feed between raster graphics, got {} bytes",
510 between.len()
511 );
512 }
513
514 #[test]
515 fn raster_graphic_ends_with_line_feed() {
516 let doc = parse("@barcode RASTER CODE128 X").unwrap();
517 let mut enc = EscPosEncoder::new(PosMetadata::default());
518 let bytes = enc.encode_document(&doc).unwrap();
519 let raster_start = bytes
520 .windows(4)
521 .position(|w| w == [0x1D, b'v', 0x30, 0x00])
522 .expect("raster header");
523 assert!(
524 bytes[raster_start..].contains(&b'\n'),
525 "expected LF after raster data"
473 );
526 );
474 }
527 }
475
528
src/params.rs +13 −8
@@ -20,10 +20,7 @@ pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap
20 20 .iter()
21 21 .map(|inline| match inline {
22 22 Inline::Text(t) => Inline::Text(t.clone()),
23 Inline::Code(t) => Inline::Code(t.clone()),
24 23 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
25 Inline::Bold(inner) => Inline::Bold(substitute_inlines(inner, values)),
26 Inline::Italic(inner) => Inline::Italic(substitute_inlines(inner, values)),
27 24 })
28 25 .collect()
29 26 }
@@ -125,6 +122,13 @@ pub fn substitute_document(
125 122 align: *align,
126 123 inlines: substitute_inlines(inlines, values),
127 124 },
125 Block::List { align, items } => Block::List {
126 align: *align,
127 items: items
128 .iter()
129 .map(|item| substitute_inlines(item, values))
130 .collect(),
131 },
128 132 Block::Rule => Block::Rule,
129 133 Block::Feed(n) => Block::Feed(*n),
130 134 Block::Cut => Block::Cut,
@@ -183,6 +187,11 @@ fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
183 187 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
184 188 collect_from_inlines(inlines, names);
185 189 }
190 Block::List { items, .. } => {
191 for item in items {
192 collect_from_inlines(item, names);
193 }
194 }
186 195 Block::Image { path, .. } => collect_from_raw(path, names),
187 196 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
188 197 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
@@ -195,8 +204,7 @@ fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
195 204 Inline::Param(name) => {
196 205 names.insert(name.clone());
197 206 }
198 Inline::Bold(inner) | Inline::Italic(inner) => collect_from_inlines(inner, names),
199 Inline::Text(_) | Inline::Code(_) => {}
207 Inline::Text(_) => {}
200 208 }
201 209 }
202 210 }
@@ -230,12 +238,9 @@ pub fn substitute_inlines_for_preview(
230 238 for inline in inlines {
231 239 match inline {
232 240 Inline::Text(t) => out.push_str(t),
233 Inline::Code(t) => out.push_str(t),
234 241 Inline::Param(name) => {
235 242 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
236 243 }
237 Inline::Bold(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
238 Inline::Italic(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
239 244 }
240 245 }
241 246 out
@@ -20,10 +20,7 @@ pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap
20 .iter()
20 .iter()
21 .map(|inline| match inline {
21 .map(|inline| match inline {
22 Inline::Text(t) => Inline::Text(t.clone()),
22 Inline::Text(t) => Inline::Text(t.clone()),
23 Inline::Code(t) => Inline::Code(t.clone()),
24 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
23 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
25 Inline::Bold(inner) => Inline::Bold(substitute_inlines(inner, values)),
26 Inline::Italic(inner) => Inline::Italic(substitute_inlines(inner, values)),
27 })
24 })
28 .collect()
25 .collect()
29}
26}
@@ -125,6 +122,13 @@ pub fn substitute_document(
125 align: *align,
122 align: *align,
126 inlines: substitute_inlines(inlines, values),
123 inlines: substitute_inlines(inlines, values),
127 },
124 },
125 Block::List { align, items } => Block::List {
126 align: *align,
127 items: items
128 .iter()
129 .map(|item| substitute_inlines(item, values))
130 .collect(),
131 },
128 Block::Rule => Block::Rule,
132 Block::Rule => Block::Rule,
129 Block::Feed(n) => Block::Feed(*n),
133 Block::Feed(n) => Block::Feed(*n),
130 Block::Cut => Block::Cut,
134 Block::Cut => Block::Cut,
@@ -183,6 +187,11 @@ fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
183 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
187 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
184 collect_from_inlines(inlines, names);
188 collect_from_inlines(inlines, names);
185 }
189 }
190 Block::List { items, .. } => {
191 for item in items {
192 collect_from_inlines(item, names);
193 }
194 }
186 Block::Image { path, .. } => collect_from_raw(path, names),
195 Block::Image { path, .. } => collect_from_raw(path, names),
187 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
196 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
188 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
197 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
@@ -195,8 +204,7 @@ fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
195 Inline::Param(name) => {
204 Inline::Param(name) => {
196 names.insert(name.clone());
205 names.insert(name.clone());
197 }
206 }
198 Inline::Bold(inner) | Inline::Italic(inner) => collect_from_inlines(inner, names),
207 Inline::Text(_) => {}
199 Inline::Text(_) | Inline::Code(_) => {}
200 }
208 }
201 }
209 }
202}
210}
@@ -230,12 +238,9 @@ pub fn substitute_inlines_for_preview(
230 for inline in inlines {
238 for inline in inlines {
231 match inline {
239 match inline {
232 Inline::Text(t) => out.push_str(t),
240 Inline::Text(t) => out.push_str(t),
233 Inline::Code(t) => out.push_str(t),
234 Inline::Param(name) => {
241 Inline::Param(name) => {
235 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
242 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
236 }
243 }
237 Inline::Bold(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
238 Inline::Italic(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
239 }
244 }
240 }
245 }
241 out
246 out
src/preview.rs +116 −23
@@ -44,9 +44,6 @@ pub enum TextStyle {
44 44 Normal,
45 45 Heading1,
46 46 Heading2,
47 Bold,
48 Italic,
49 Code,
50 47 }
51 48
52 49 pub fn render_preview(
@@ -71,6 +68,19 @@ pub fn render_preview(
71 68 });
72 69 }
73 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, preview_params);
75 for line in text_wrap::wrap_bullet_item(&text, cols) {
76 lines.push(PreviewLine::Text {
77 content: line,
78 align: *align,
79 style: TextStyle::Normal,
80 });
81 }
82 }
83 }
74 84 Block::Heading { level, align, inlines } => {
75 85 let style = if *level == 1 {
76 86 TextStyle::Heading1
@@ -97,7 +107,7 @@ pub fn render_preview(
97 107 Block::Cut => lines.push(PreviewLine::Text {
98 108 content: "--- cut ---".into(),
99 109 align: Align::Center,
100 style: TextStyle::Code,
110 style: TextStyle::Normal,
101 111 }),
102 112 Block::Image { path, width, align } => {
103 113 let path = substitute_for_preview(path, preview_params);
@@ -308,46 +318,67 @@ fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
308 318 /// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
309 319 pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
310 320
311 /// Preview canvas width: one screen pixel per printer dot at zoom 1.0.
321 /// Screen calibration so zoom `1.0` matches a typical receipt width on screen.
322 pub const PREVIEW_SCREEN_CALIBRATION: f32 = 0.52;
323
324 /// Preview canvas width in printer dots (before screen calibration).
312 325 pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 {
313 326 metadata.printable_dots() as f32
314 327 }
315 328
329 /// User-controlled zoom factor (1.0 = 100%).
330 pub fn preview_zoom_scale(zoom: f32) -> f32 {
331 zoom.clamp(0.25, 4.0)
332 }
333
334 /// Effective on-screen scale for page width, text, and raster graphics.
335 pub fn preview_visual_scale(zoom: f32) -> f32 {
336 preview_zoom_scale(zoom) * PREVIEW_SCREEN_CALIBRATION
337 }
338
316 339 /// Character cell width in preview pixels (matches print column width).
317 340 pub fn preview_char_width_px(metadata: &PosMetadata, zoom: f32) -> f32 {
318 preview_content_width_px(metadata) * preview_zoom_scale(zoom)
341 preview_content_width_px(metadata) * preview_visual_scale(zoom)
319 342 / metadata.chars_per_line().max(1) as f32
320 343 }
321 344
322 /// Blank-line / `@feed` vertical space in preview pixels.
345 /// egui monospace sized 1:1 to column width reads smaller than printed Font A.
346 /// Empirically ~60% of print; scale up so preview matches the receipt.
347 pub const PREVIEW_FONT_PRINT_MATCH: f32 = 1.0 / 0.6;
348
349 /// Font size in preview pixels for normal / `##` text.
350 pub fn preview_font_size_px(char_width: f32) -> f32 {
351 char_width * PREVIEW_FONT_PRINT_MATCH
352 }
353
354 /// Blank-line / `@feed` vertical space in preview pixels (printer line spacing).
323 355 pub fn preview_line_spacing_px(zoom: f32) -> f32 {
324 PREVIEW_LINE_SPACING_DOTS * preview_zoom_scale(zoom)
356 PREVIEW_LINE_SPACING_DOTS * preview_visual_scale(zoom)
325 357 }
326 358
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)
359 /// Vertical advance for a text style (matches printer LF / ESC d line spacing).
360 pub fn preview_text_advance_px(style: TextStyle, zoom: f32) -> f32 {
361 let line_sp = preview_line_spacing_px(zoom);
362 match style {
363 // GS ! 0x11: double height → two line advances
364 TextStyle::Heading1 => line_sp * 2.0,
365 TextStyle::Heading2 | TextStyle::Normal => line_sp,
366 }
330 367 }
331 368
332 369 /// Estimated line height for layout (text styles use galley at draw time).
333 370 pub fn preview_line_height_estimate(
334 371 line: &PreviewLine,
335 metadata: &PosMetadata,
372 _metadata: &PosMetadata,
336 373 zoom: f32,
337 374 ) -> 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);
375 let scale = preview_visual_scale(zoom);
341 376 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 },
377 PreviewLine::Text { style, .. } => preview_text_advance_px(*style, zoom),
347 378 PreviewLine::Rule => 4.0 * scale,
348 379 PreviewLine::Graphic { image, .. } => image.height() as f32 * scale,
349 PreviewLine::Error { .. } => line_sp,
350 PreviewLine::Spacer(n) => line_sp * (*n as f32),
380 PreviewLine::Error { .. } => preview_line_spacing_px(zoom),
381 PreviewLine::Spacer(n) => preview_line_spacing_px(zoom) * (*n as f32),
351 382 }
352 383 }
353 384
@@ -504,6 +535,68 @@ mod tests {
504 535 let meta = PosMetadata::default();
505 536 let line = PreviewLine::Spacer(1);
506 537 let h = preview_line_height_estimate(&line, &meta, 1.0);
507 assert!((h - PREVIEW_LINE_SPACING_DOTS).abs() < 0.01);
538 assert!((h - PREVIEW_LINE_SPACING_DOTS * PREVIEW_SCREEN_CALIBRATION).abs() < 0.01);
539 }
540
541 #[test]
542 fn zoom_100_percent_uses_screen_calibration() {
543 assert!((preview_visual_scale(1.0) - PREVIEW_SCREEN_CALIBRATION).abs() < 0.001);
544 }
545
546 #[test]
547 fn font_size_matches_print_calibration() {
548 let char_w = 6.0;
549 assert!((preview_font_size_px(char_w) - char_w / 0.6).abs() < 0.001);
550 }
551
552 #[test]
553 fn heading1_is_double_normal_text_height() {
554 let meta = PosMetadata::default();
555 let normal = preview_line_height_estimate(
556 &PreviewLine::Text {
557 content: "x".into(),
558 align: crate::dsl::Align::Left,
559 style: TextStyle::Normal,
560 },
561 &meta,
562 1.0,
563 );
564 let heading = preview_line_height_estimate(
565 &PreviewLine::Text {
566 content: "x".into(),
567 align: crate::dsl::Align::Left,
568 style: TextStyle::Heading1,
569 },
570 &meta,
571 1.0,
572 );
573 assert!((heading - normal * 2.0).abs() < 0.01);
574 }
575
576 #[test]
577 fn spacer_matches_normal_text_advance() {
578 let meta = PosMetadata::default();
579 let spacer = preview_line_height_estimate(&PreviewLine::Spacer(1), &meta, 1.0);
580 let text = preview_text_advance_px(TextStyle::Normal, 1.0);
581 assert!((spacer - text).abs() < 0.01);
582 }
583
584 #[test]
585 fn renders_bullet_list_with_hanging_indent() {
586 let doc = parse("- this is a long line").unwrap();
587 let meta = PosMetadata {
588 chars_per_line: Some(15),
589 ..Default::default()
590 };
591 let model = render_preview(&doc, &meta, None, &HashMap::new());
592 assert_eq!(model.lines.len(), 2);
593 let PreviewLine::Text { content: first, .. } = &model.lines[0] else {
594 panic!();
595 };
596 let PreviewLine::Text { content: second, .. } = &model.lines[1] else {
597 panic!();
598 };
599 assert!(first.starts_with("* "));
600 assert!(second.starts_with(" "));
508 601 }
509 602 }
@@ -44,9 +44,6 @@ pub enum TextStyle {
44 Normal,
44 Normal,
45 Heading1,
45 Heading1,
46 Heading2,
46 Heading2,
47 Bold,
48 Italic,
49 Code,
50}
47}
51
48
52pub fn render_preview(
49pub fn render_preview(
@@ -71,6 +68,19 @@ pub fn render_preview(
71 });
68 });
72 }
69 }
73 }
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, preview_params);
75 for line in text_wrap::wrap_bullet_item(&text, cols) {
76 lines.push(PreviewLine::Text {
77 content: line,
78 align: *align,
79 style: TextStyle::Normal,
80 });
81 }
82 }
83 }
74 Block::Heading { level, align, inlines } => {
84 Block::Heading { level, align, inlines } => {
75 let style = if *level == 1 {
85 let style = if *level == 1 {
76 TextStyle::Heading1
86 TextStyle::Heading1
@@ -97,7 +107,7 @@ pub fn render_preview(
97 Block::Cut => lines.push(PreviewLine::Text {
107 Block::Cut => lines.push(PreviewLine::Text {
98 content: "--- cut ---".into(),
108 content: "--- cut ---".into(),
99 align: Align::Center,
109 align: Align::Center,
100 style: TextStyle::Code,
110 style: TextStyle::Normal,
101 }),
111 }),
102 Block::Image { path, width, align } => {
112 Block::Image { path, width, align } => {
103 let path = substitute_for_preview(path, preview_params);
113 let path = substitute_for_preview(path, preview_params);
@@ -308,46 +318,67 @@ fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
308/// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
318/// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
309pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
319pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
310
320
311/// Preview canvas width: one screen pixel per printer dot at zoom 1.0.
321/// Screen calibration so zoom `1.0` matches a typical receipt width on screen.
322pub const PREVIEW_SCREEN_CALIBRATION: f32 = 0.52;
323
324/// Preview canvas width in printer dots (before screen calibration).
312pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 {
325pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 {
313 metadata.printable_dots() as f32
326 metadata.printable_dots() as f32
314}
327}
315
328
329/// User-controlled zoom factor (1.0 = 100%).
330pub fn preview_zoom_scale(zoom: f32) -> f32 {
331 zoom.clamp(0.25, 4.0)
332}
333
334/// Effective on-screen scale for page width, text, and raster graphics.
335pub fn preview_visual_scale(zoom: f32) -> f32 {
336 preview_zoom_scale(zoom) * PREVIEW_SCREEN_CALIBRATION
337}
338
316/// Character cell width in preview pixels (matches print column width).
339/// Character cell width in preview pixels (matches print column width).
317pub fn preview_char_width_px(metadata: &PosMetadata, zoom: f32) -> f32 {
340pub fn preview_char_width_px(metadata: &PosMetadata, zoom: f32) -> f32 {
318 preview_content_width_px(metadata) * preview_zoom_scale(zoom)
341 preview_content_width_px(metadata) * preview_visual_scale(zoom)
319 / metadata.chars_per_line().max(1) as f32
342 / metadata.chars_per_line().max(1) as f32
320}
343}
321
344
322/// Blank-line / `@feed` vertical space in preview pixels.
345/// egui monospace sized 1:1 to column width reads smaller than printed Font A.
346/// Empirically ~60% of print; scale up so preview matches the receipt.
347pub const PREVIEW_FONT_PRINT_MATCH: f32 = 1.0 / 0.6;
348
349/// Font size in preview pixels for normal / `##` text.
350pub fn preview_font_size_px(char_width: f32) -> f32 {
351 char_width * PREVIEW_FONT_PRINT_MATCH
352}
353
354/// Blank-line / `@feed` vertical space in preview pixels (printer line spacing).
323pub fn preview_line_spacing_px(zoom: f32) -> f32 {
355pub fn preview_line_spacing_px(zoom: f32) -> f32 {
324 PREVIEW_LINE_SPACING_DOTS * preview_zoom_scale(zoom)
356 PREVIEW_LINE_SPACING_DOTS * preview_visual_scale(zoom)
325}
357}
326
358
327/// User-controlled zoom factor applied on top of the dot-based layout.
359/// Vertical advance for a text style (matches printer LF / ESC d line spacing).
328pub fn preview_zoom_scale(zoom: f32) -> f32 {
360pub fn preview_text_advance_px(style: TextStyle, zoom: f32) -> f32 {
329 zoom.clamp(0.25, 4.0)
361 let line_sp = preview_line_spacing_px(zoom);
362 match style {
363 // GS ! 0x11: double height → two line advances
364 TextStyle::Heading1 => line_sp * 2.0,
365 TextStyle::Heading2 | TextStyle::Normal => line_sp,
366 }
330}
367}
331
368
332/// Estimated line height for layout (text styles use galley at draw time).
369/// Estimated line height for layout (text styles use galley at draw time).
333pub fn preview_line_height_estimate(
370pub fn preview_line_height_estimate(
334 line: &PreviewLine,
371 line: &PreviewLine,
335 metadata: &PosMetadata,
372 _metadata: &PosMetadata,
336 zoom: f32,
373 zoom: f32,
337) -> f32 {
374) -> f32 {
338 let scale = preview_zoom_scale(zoom);
375 let scale = preview_visual_scale(zoom);
339 let char_w = preview_char_width_px(metadata, zoom);
340 let line_sp = preview_line_spacing_px(zoom);
341 match line {
376 match line {
342 PreviewLine::Text { style, .. } => match style {
377 PreviewLine::Text { style, .. } => preview_text_advance_px(*style, zoom),
343 TextStyle::Heading1 => char_w * 2.2,
344 TextStyle::Heading2 => char_w * 1.8,
345 _ => line_sp,
346 },
347 PreviewLine::Rule => 4.0 * scale,
378 PreviewLine::Rule => 4.0 * scale,
348 PreviewLine::Graphic { image, .. } => image.height() as f32 * scale,
379 PreviewLine::Graphic { image, .. } => image.height() as f32 * scale,
349 PreviewLine::Error { .. } => line_sp,
380 PreviewLine::Error { .. } => preview_line_spacing_px(zoom),
350 PreviewLine::Spacer(n) => line_sp * (*n as f32),
381 PreviewLine::Spacer(n) => preview_line_spacing_px(zoom) * (*n as f32),
351 }
382 }
352}
383}
353
384
@@ -504,6 +535,68 @@ mod tests {
504 let meta = PosMetadata::default();
535 let meta = PosMetadata::default();
505 let line = PreviewLine::Spacer(1);
536 let line = PreviewLine::Spacer(1);
506 let h = preview_line_height_estimate(&line, &meta, 1.0);
537 let h = preview_line_height_estimate(&line, &meta, 1.0);
507 assert!((h - PREVIEW_LINE_SPACING_DOTS).abs() < 0.01);
538 assert!((h - PREVIEW_LINE_SPACING_DOTS * PREVIEW_SCREEN_CALIBRATION).abs() < 0.01);
539 }
540
541 #[test]
542 fn zoom_100_percent_uses_screen_calibration() {
543 assert!((preview_visual_scale(1.0) - PREVIEW_SCREEN_CALIBRATION).abs() < 0.001);
544 }
545
546 #[test]
547 fn font_size_matches_print_calibration() {
548 let char_w = 6.0;
549 assert!((preview_font_size_px(char_w) - char_w / 0.6).abs() < 0.001);
550 }
551
552 #[test]
553 fn heading1_is_double_normal_text_height() {
554 let meta = PosMetadata::default();
555 let normal = preview_line_height_estimate(
556 &PreviewLine::Text {
557 content: "x".into(),
558 align: crate::dsl::Align::Left,
559 style: TextStyle::Normal,
560 },
561 &meta,
562 1.0,
563 );
564 let heading = preview_line_height_estimate(
565 &PreviewLine::Text {
566 content: "x".into(),
567 align: crate::dsl::Align::Left,
568 style: TextStyle::Heading1,
569 },
570 &meta,
571 1.0,
572 );
573 assert!((heading - normal * 2.0).abs() < 0.01);
574 }
575
576 #[test]
577 fn spacer_matches_normal_text_advance() {
578 let meta = PosMetadata::default();
579 let spacer = preview_line_height_estimate(&PreviewLine::Spacer(1), &meta, 1.0);
580 let text = preview_text_advance_px(TextStyle::Normal, 1.0);
581 assert!((spacer - text).abs() < 0.01);
582 }
583
584 #[test]
585 fn renders_bullet_list_with_hanging_indent() {
586 let doc = parse("- this is a long line").unwrap();
587 let meta = PosMetadata {
588 chars_per_line: Some(15),
589 ..Default::default()
590 };
591 let model = render_preview(&doc, &meta, None, &HashMap::new());
592 assert_eq!(model.lines.len(), 2);
593 let PreviewLine::Text { content: first, .. } = &model.lines[0] else {
594 panic!();
595 };
596 let PreviewLine::Text { content: second, .. } = &model.lines[1] else {
597 panic!();
598 };
599 assert!(first.starts_with("* "));
600 assert!(second.starts_with(" "));
508 }
601 }
509}
602}
src/text_wrap.rs +106 −0
@@ -16,6 +16,106 @@ pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize {
16 16 }
17 17 }
18 18
19 /// ASCII bullet prefix — universally supported on ESC/POS printers.
20 pub const BULLET_FIRST_PREFIX: &str = "* ";
21 /// Indent for wrapped continuation lines (same width as [`BULLET_FIRST_PREFIX`]).
22 pub const BULLET_NEXT_PREFIX: &str = " ";
23
24 /// Word-wrap a bullet list item with hanging indentation.
25 pub fn wrap_bullet_item(text: &str, max_cols: usize) -> Vec<String> {
26 wrap_hanging(text, max_cols, BULLET_FIRST_PREFIX, BULLET_NEXT_PREFIX)
27 }
28
29 /// Word-wrap `text` with different budgets for the first and subsequent lines.
30 pub fn wrap_hanging(
31 text: &str,
32 max_cols: usize,
33 first_prefix: &str,
34 next_prefix: &str,
35 ) -> Vec<String> {
36 let first_budget = max_cols.saturating_sub(first_prefix.chars().count());
37 let next_budget = max_cols.saturating_sub(next_prefix.chars().count());
38 let content_lines = wrap_content_var_budget(text, first_budget, next_budget);
39
40 content_lines
41 .into_iter()
42 .enumerate()
43 .map(|(idx, line)| {
44 if idx == 0 {
45 format!("{first_prefix}{line}")
46 } else {
47 format!("{next_prefix}{line}")
48 }
49 })
50 .collect()
51 }
52
53 fn wrap_content_var_budget(text: &str, first_budget: usize, next_budget: usize) -> Vec<String> {
54 if first_budget == 0 && next_budget == 0 {
55 return vec![text.to_string()];
56 }
57
58 let words: Vec<&str> = text.split_whitespace().collect();
59 if words.is_empty() {
60 return vec![String::new()];
61 }
62
63 let mut lines = Vec::new();
64 let mut current = String::new();
65 let mut budget = first_budget.max(1);
66 let mut word_idx = 0usize;
67
68 while word_idx < words.len() {
69 let word = words[word_idx];
70 let word_len = word.chars().count();
71
72 if current.is_empty() {
73 if word_len <= budget {
74 current.push_str(word);
75 word_idx += 1;
76 } else {
77 let mut remaining = word;
78 while !remaining.is_empty() {
79 let chunk = take_char_prefix(remaining, budget);
80 let consumed = chunk.chars().count();
81 if chunk.is_empty() {
82 break;
83 }
84 lines.push(chunk);
85 remaining = &remaining[remaining
86 .char_indices()
87 .nth(consumed)
88 .map(|(idx, _)| idx)
89 .unwrap_or(remaining.len())..];
90 budget = next_budget.max(1);
91 }
92 }
93 } else {
94 let current_len = current.chars().count();
95 if current_len + 1 + word_len <= budget {
96 current.push(' ');
97 current.push_str(word);
98 word_idx += 1;
99 } else {
100 lines.push(std::mem::take(&mut current));
101 budget = next_budget.max(1);
102 }
103 }
104 }
105
106 if !current.is_empty() {
107 lines.push(current);
108 }
109 if lines.is_empty() {
110 lines.push(String::new());
111 }
112 lines
113 }
114
115 fn take_char_prefix(text: &str, max_chars: usize) -> String {
116 text.chars().take(max_chars).collect()
117 }
118
19 119 /// Word-wrap `text` to at most `max_cols` characters per line.
20 120 /// Explicit newlines in `text` start a new wrapped paragraph.
21 121 pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
@@ -120,4 +220,10 @@ mod tests {
120 220 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
121 221 assert_eq!(cols, 32);
122 222 }
223
224 #[test]
225 fn bullet_wrap_uses_hanging_indent() {
226 let lines = wrap_bullet_item("this is a long line", 15);
227 assert_eq!(lines, vec!["* this is a", " long line"]);
228 }
123 229 }
@@ -16,6 +16,106 @@ pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize {
16 }
16 }
17}
17}
18
18
19/// ASCII bullet prefix — universally supported on ESC/POS printers.
20pub const BULLET_FIRST_PREFIX: &str = "* ";
21/// Indent for wrapped continuation lines (same width as [`BULLET_FIRST_PREFIX`]).
22pub const BULLET_NEXT_PREFIX: &str = " ";
23
24/// Word-wrap a bullet list item with hanging indentation.
25pub fn wrap_bullet_item(text: &str, max_cols: usize) -> Vec<String> {
26 wrap_hanging(text, max_cols, BULLET_FIRST_PREFIX, BULLET_NEXT_PREFIX)
27}
28
29/// Word-wrap `text` with different budgets for the first and subsequent lines.
30pub fn wrap_hanging(
31 text: &str,
32 max_cols: usize,
33 first_prefix: &str,
34 next_prefix: &str,
35) -> Vec<String> {
36 let first_budget = max_cols.saturating_sub(first_prefix.chars().count());
37 let next_budget = max_cols.saturating_sub(next_prefix.chars().count());
38 let content_lines = wrap_content_var_budget(text, first_budget, next_budget);
39
40 content_lines
41 .into_iter()
42 .enumerate()
43 .map(|(idx, line)| {
44 if idx == 0 {
45 format!("{first_prefix}{line}")
46 } else {
47 format!("{next_prefix}{line}")
48 }
49 })
50 .collect()
51}
52
53fn wrap_content_var_budget(text: &str, first_budget: usize, next_budget: usize) -> Vec<String> {
54 if first_budget == 0 && next_budget == 0 {
55 return vec![text.to_string()];
56 }
57
58 let words: Vec<&str> = text.split_whitespace().collect();
59 if words.is_empty() {
60 return vec![String::new()];
61 }
62
63 let mut lines = Vec::new();
64 let mut current = String::new();
65 let mut budget = first_budget.max(1);
66 let mut word_idx = 0usize;
67
68 while word_idx < words.len() {
69 let word = words[word_idx];
70 let word_len = word.chars().count();
71
72 if current.is_empty() {
73 if word_len <= budget {
74 current.push_str(word);
75 word_idx += 1;
76 } else {
77 let mut remaining = word;
78 while !remaining.is_empty() {
79 let chunk = take_char_prefix(remaining, budget);
80 let consumed = chunk.chars().count();
81 if chunk.is_empty() {
82 break;
83 }
84 lines.push(chunk);
85 remaining = &remaining[remaining
86 .char_indices()
87 .nth(consumed)
88 .map(|(idx, _)| idx)
89 .unwrap_or(remaining.len())..];
90 budget = next_budget.max(1);
91 }
92 }
93 } else {
94 let current_len = current.chars().count();
95 if current_len + 1 + word_len <= budget {
96 current.push(' ');
97 current.push_str(word);
98 word_idx += 1;
99 } else {
100 lines.push(std::mem::take(&mut current));
101 budget = next_budget.max(1);
102 }
103 }
104 }
105
106 if !current.is_empty() {
107 lines.push(current);
108 }
109 if lines.is_empty() {
110 lines.push(String::new());
111 }
112 lines
113}
114
115fn take_char_prefix(text: &str, max_chars: usize) -> String {
116 text.chars().take(max_chars).collect()
117}
118
19/// Word-wrap `text` to at most `max_cols` characters per line.
119/// Word-wrap `text` to at most `max_cols` characters per line.
20/// Explicit newlines in `text` start a new wrapped paragraph.
120/// Explicit newlines in `text` start a new wrapped paragraph.
21pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
121pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
@@ -120,4 +220,10 @@ mod tests {
120 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
220 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
121 assert_eq!(cols, 32);
221 assert_eq!(cols, 32);
122 }
222 }
223
224 #[test]
225 fn bullet_wrap_uses_hanging_indent() {
226 let lines = wrap_bullet_item("this is a long line", 15);
227 assert_eq!(lines, vec!["* this is a", " long line"]);
228 }
123}
229}