BlueGit

timfa posprint

Trial: print checkboxes as UTF-8 ☐ / πŸ—Ή.

Drop ESC & / bit-image paths; emit ballot glyphs as plain text to see if the printer renders them.

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

timfa Tim Falken Β· pushed by timfa

Authored 2026-07-17 Β· 4 months ago

Hash
5ea66901f1ae837c2526d4e2503b822e1f75d8c1
Parent
118ec91a
9 files changed +34 βˆ’784
docs/ARCHITECTURE.md +0 βˆ’1
@@ -27,7 +27,6 @@ src/
27 27 β”œβ”€β”€ dsl/ # Parser and AST
28 28 β”œβ”€β”€ params.rs # Parameter collect / substitute / preview samples
29 29 β”œβ”€β”€ escpos.rs # ESC/POS byte encoder (in-tree)
30 β”œβ”€β”€ bitmap_font.rs # Checkbox glyphs (user-defined chars) + mixed-line wrap
31 30 β”œβ”€β”€ preview.rs # PreviewModel for UI canvas
32 31 β”œβ”€β”€ text_wrap.rs # Shared wrap (preview + print)
33 32 β”œβ”€β”€ datetime.rs # @date / @time formatting
@@ -27,7 +27,6 @@ src/
27β”œβ”€β”€ dsl/ # Parser and AST
27β”œβ”€β”€ dsl/ # Parser and AST
28β”œβ”€β”€ params.rs # Parameter collect / substitute / preview samples
28β”œβ”€β”€ params.rs # Parameter collect / substitute / preview samples
29β”œβ”€β”€ escpos.rs # ESC/POS byte encoder (in-tree)
29β”œβ”€β”€ escpos.rs # ESC/POS byte encoder (in-tree)
30β”œβ”€β”€ bitmap_font.rs # Checkbox glyphs (user-defined chars) + mixed-line wrap
31β”œβ”€β”€ preview.rs # PreviewModel for UI canvas
30β”œβ”€β”€ preview.rs # PreviewModel for UI canvas
32β”œβ”€β”€ text_wrap.rs # Shared wrap (preview + print)
31β”œβ”€β”€ text_wrap.rs # Shared wrap (preview + print)
33β”œβ”€β”€ datetime.rs # @date / @time formatting
32β”œβ”€β”€ datetime.rs # @date / @time formatting
docs/DSL-SPEC.md +4 βˆ’4
@@ -81,10 +81,10 @@ Wrapped lines use a hanging indent:
81 81
82 82 | Syntax | Printed result |
83 83 |--------|----------------|
84 | `[]` or `[ ]` | Empty checkbox (raster) |
85 | `[x]` or `[X]` | Checked checkbox with tick (raster) |
84 | `[]` or `[ ]` | ☐ (U+2610) |
85 | `[x]` or `[X]` | πŸ—Ή (U+1F5F9) |
86 86
87 Lines that contain checkboxes keep the printer’s normal text font; the box/tick is two Font A user-defined characters (ESC `&`). Preview uses Unicode ☐ / β˜‘.
87 Emitted as UTF-8 text (experiment). Many ESC/POS printers only speak CP437 and may show garbage or blanks instead.
88 88
89 89 Parameters work inside any text, and inside barcode/QR/image directives (below).
90 90
@@ -269,7 +269,7 @@ Parse errors include 1-based line and column. Typical causes:
269 269 | `# heading` | Double width/height ON β†’ text β†’ OFF |
270 270 | `## heading` | Bold ON β†’ text β†’ OFF |
271 271 | `- item` | ASCII `* ` bullet + hanging wrap |
272 | `[]` / `[ ]` / `[x]` | User-defined Font A chars (ESC `&`) for checkbox; text stays native |
272 | `[]` / `[ ]` / `[x]` | UTF-8 ☐ / πŸ—Ή (trial; CP437 printers may not render) |
273 273 | `:center:` | Justification center |
274 274 | `@feed n` / blank line | ESC d n |
275 275 | `@cut` | GS V partial cut |
@@ -81,10 +81,10 @@ Wrapped lines use a hanging indent:
81
81
82| Syntax | Printed result |
82| Syntax | Printed result |
83|--------|----------------|
83|--------|----------------|
84| `[]` or `[ ]` | Empty checkbox (raster) |
84| `[]` or `[ ]` | ☐ (U+2610) |
85| `[x]` or `[X]` | Checked checkbox with tick (raster) |
85| `[x]` or `[X]` | πŸ—Ή (U+1F5F9) |
86
86
87Lines that contain checkboxes keep the printer’s normal text font; the box/tick is two Font A user-defined characters (ESC `&`). Preview uses Unicode ☐ / β˜‘.
87Emitted as UTF-8 text (experiment). Many ESC/POS printers only speak CP437 and may show garbage or blanks instead.
88
88
89Parameters work inside any text, and inside barcode/QR/image directives (below).
89Parameters work inside any text, and inside barcode/QR/image directives (below).
90
90
@@ -269,7 +269,7 @@ Parse errors include 1-based line and column. Typical causes:
269| `# heading` | Double width/height ON β†’ text β†’ OFF |
269| `# heading` | Double width/height ON β†’ text β†’ OFF |
270| `## heading` | Bold ON β†’ text β†’ OFF |
270| `## heading` | Bold ON β†’ text β†’ OFF |
271| `- item` | ASCII `* ` bullet + hanging wrap |
271| `- item` | ASCII `* ` bullet + hanging wrap |
272| `[]` / `[ ]` / `[x]` | User-defined Font A chars (ESC `&`) for checkbox; text stays native |
272| `[]` / `[ ]` / `[x]` | UTF-8 ☐ / πŸ—Ή (trial; CP437 printers may not render) |
273| `:center:` | Justification center |
273| `:center:` | Justification center |
274| `@feed n` / blank line | ESC d n |
274| `@feed n` / blank line | ESC d n |
275| `@cut` | GS V partial cut |
275| `@cut` | GS V partial cut |
docs/HELP.md +3 βˆ’3
@@ -82,12 +82,12 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
82 82
83 83 ### Checkboxes
84 84
85 Inline checkboxes print as a real empty box or a box with a checkmark (user-defined printer characters). Surrounding text uses the normal printer font. Preview shows ☐ / β˜‘.
85 Inline checkboxes print as Unicode ☐ / πŸ—Ή (UTF-8 trial on the printer). Preview shows the same glyphs.
86 86
87 87 | Syntax | Result |
88 88 |--------|--------|
89 | `[]` or `[ ]` | Empty checkbox |
90 | `[x]` or `[X]` | Checked checkbox |
89 | `[]` or `[ ]` | ☐ |
90 | `[x]` or `[X]` | πŸ—Ή |
91 91
92 92 ```markdown
93 93 [] Unchecked
@@ -82,12 +82,12 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
82
82
83### Checkboxes
83### Checkboxes
84
84
85Inline checkboxes print as a real empty box or a box with a checkmark (user-defined printer characters). Surrounding text uses the normal printer font. Preview shows ☐ / β˜‘.
85Inline checkboxes print as Unicode ☐ / πŸ—Ή (UTF-8 trial on the printer). Preview shows the same glyphs.
86
86
87| Syntax | Result |
87| Syntax | Result |
88|--------|--------|
88|--------|--------|
89| `[]` or `[ ]` | Empty checkbox |
89| `[]` or `[ ]` | ☐ |
90| `[x]` or `[X]` | Checked checkbox |
90| `[x]` or `[X]` | πŸ—Ή |
91
91
92```markdown
92```markdown
93[] Unchecked
93[] Unchecked
docs/PRINTING.md +1 βˆ’1
@@ -29,7 +29,7 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
29 29 | Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text ends with LF; blank/`@feed` use ESC d |
30 30 | Raster flush | LF after GS v 0 | Ensures spacing after images/barcodes/QR rasters |
31 31 | List bullet | ASCII `*` | `- item` lines in templates |
32 | Inline checkbox | ESC `&` user-defined Font A chars (2 cells) | `[]` / `[ ]` / `[x]`; surrounding text uses native font |
32 | Inline checkbox | UTF-8 ☐ / πŸ—Ή | `[]` / `[ ]` / `[x]` (trial glyphs) |
33 33 | Partial cut | GS V 66 0 | `@cut` in template only |
34 34 | Barcode | GS k | Native symbologies; raster via GS v 0 |
35 35 | QR Code | GS ( k | Model 2; or raster GS v 0 |
@@ -29,7 +29,7 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
29| Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text ends with LF; blank/`@feed` use ESC d |
29| Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text ends with LF; blank/`@feed` use ESC d |
30| Raster flush | LF after GS v 0 | Ensures spacing after images/barcodes/QR rasters |
30| Raster flush | LF after GS v 0 | Ensures spacing after images/barcodes/QR rasters |
31| List bullet | ASCII `*` | `- item` lines in templates |
31| List bullet | ASCII `*` | `- item` lines in templates |
32| Inline checkbox | ESC `&` user-defined Font A chars (2 cells) | `[]` / `[ ]` / `[x]`; surrounding text uses native font |
32| Inline checkbox | UTF-8 ☐ / πŸ—Ή | `[]` / `[ ]` / `[x]` (trial glyphs) |
33| Partial cut | GS V 66 0 | `@cut` in template only |
33| Partial cut | GS V 66 0 | `@cut` in template only |
34| Barcode | GS k | Native symbologies; raster via GS v 0 |
34| Barcode | GS k | Native symbologies; raster via GS v 0 |
35| QR Code | GS ( k | Model 2; or raster GS v 0 |
35| QR Code | GS ( k | Model 2; or raster GS v 0 |
examples/print_checkbox_test.rs +1 βˆ’1
@@ -30,5 +30,5 @@ fn main() {
30 30 println!("Printing checkbox test to: {}", device.display_name);
31 31 let mut transport = open_printer(&device.target).expect("open printer");
32 32 print_bytes(&mut transport, &bytes).expect("print");
33 println!("OK β€” check paper for real checkbox boxes (empty / empty / checked with tick)");
33 println!("OK β€” check paper for Unicode ☐ / ☐ / πŸ—Ή (may be blank/garbage on CP437-only printers)");
34 34 }
@@ -30,5 +30,5 @@ fn main() {
30 println!("Printing checkbox test to: {}", device.display_name);
30 println!("Printing checkbox test to: {}", device.display_name);
31 let mut transport = open_printer(&device.target).expect("open printer");
31 let mut transport = open_printer(&device.target).expect("open printer");
32 print_bytes(&mut transport, &bytes).expect("print");
32 print_bytes(&mut transport, &bytes).expect("print");
33 println!("OK β€” check paper for real checkbox boxes (empty / empty / checked with tick)");
33 println!("OK β€” check paper for Unicode ☐ / ☐ / πŸ—Ή (may be blank/garbage on CP437-only printers)");
34}
34}
src/bitmap_font.rs deleted +0 βˆ’633
@@ -1,633 +0,0 @@
1 //! Minimal 8Γ—8 ASCII font for rasterizing lines that contain checkbox glyphs.
2 //! Glyphs are public-domain style bitmaps (MSB = leftmost pixel).
3
4 use image::{GrayImage, Luma};
5
6 /// Columns reserved for one checkbox when wrapping text (two Font A cells).
7 pub const CHECKBOX_WRAP_COLS: usize = 2;
8
9 /// Render height of a normal text line (matches Font A row height on ESC/POS).
10 pub const LINE_HEIGHT: u32 = 24;
11 /// Font A cell width in dots β€” checkbox spans two cells via user-defined chars.
12 pub const CHAR_WIDTH: u32 = 12;
13 const CHAR_SRC: u32 = 8;
14 /// Checkbox box size (~20% larger than the original 14px).
15 const CHECKBOX_SIDE: u32 = 17;
16
17 /// User-defined character codes (ESC &): empty L/R, checked L/R.
18 pub const CHAR_EMPTY_L: u8 = 0x01;
19 pub const CHAR_EMPTY_R: u8 = 0x02;
20 pub const CHAR_CHECKED_L: u8 = 0x03;
21 pub const CHAR_CHECKED_R: u8 = 0x04;
22
23 #[derive(Debug, Clone, PartialEq, Eq)]
24 pub enum MixedSeg {
25 Text(String),
26 Checkbox { checked: bool },
27 }
28
29 pub fn segments_from_inlines(inlines: &[crate::dsl::Inline]) -> Vec<MixedSeg> {
30 let mut out = Vec::new();
31 for inline in inlines {
32 match inline {
33 crate::dsl::Inline::Text(t) | crate::dsl::Inline::Param(t) => {
34 if t.is_empty() {
35 continue;
36 }
37 if let Some(MixedSeg::Text(existing)) = out.last_mut() {
38 existing.push_str(t);
39 } else {
40 out.push(MixedSeg::Text(t.clone()));
41 }
42 }
43 crate::dsl::Inline::Checkbox { checked } => {
44 out.push(MixedSeg::Checkbox {
45 checked: *checked,
46 });
47 }
48 }
49 }
50 out
51 }
52
53 pub fn inlines_have_checkbox(inlines: &[crate::dsl::Inline]) -> bool {
54 inlines
55 .iter()
56 .any(|i| matches!(i, crate::dsl::Inline::Checkbox { .. }))
57 }
58
59 /// Word-wrap mixed segments to `max_cols` character columns.
60 /// Explicit `\n` inside text segments start a new line (same as [`crate::text_wrap::wrap_text`]).
61 pub fn wrap_segments(segs: &[MixedSeg], max_cols: usize) -> Vec<Vec<MixedSeg>> {
62 wrap_segments_hanging(segs, max_cols, "", "")
63 }
64
65 /// Split segments into hard lines on `\n` inside text (checkboxes never contain newlines).
66 fn split_on_newlines(segs: &[MixedSeg]) -> Vec<Vec<MixedSeg>> {
67 let mut lines: Vec<Vec<MixedSeg>> = vec![Vec::new()];
68 for seg in segs {
69 match seg {
70 MixedSeg::Checkbox { checked } => {
71 lines.last_mut().unwrap().push(MixedSeg::Checkbox {
72 checked: *checked,
73 });
74 }
75 MixedSeg::Text(t) => {
76 let parts: Vec<&str> = t.split('\n').collect();
77 for (i, part) in parts.iter().enumerate() {
78 if i > 0 {
79 lines.push(Vec::new());
80 }
81 if part.is_empty() {
82 continue;
83 }
84 let line = lines.last_mut().unwrap();
85 if let Some(MixedSeg::Text(existing)) = line.last_mut() {
86 existing.push_str(part);
87 } else {
88 line.push(MixedSeg::Text((*part).to_string()));
89 }
90 }
91 }
92 }
93 }
94 lines
95 }
96
97 /// Word-wrap with hanging prefixes (e.g. bullet `* ` / ` `).
98 /// Explicit `\n` inside text start a new hanging-wrapped group.
99 pub fn wrap_segments_hanging(
100 segs: &[MixedSeg],
101 max_cols: usize,
102 first_prefix: &str,
103 next_prefix: &str,
104 ) -> Vec<Vec<MixedSeg>> {
105 let mut out = Vec::new();
106 for paragraph in split_on_newlines(segs) {
107 out.extend(wrap_segments_hanging_one(
108 &paragraph,
109 max_cols,
110 first_prefix,
111 next_prefix,
112 ));
113 }
114 if out.is_empty() {
115 out.push(prefix_line(first_prefix, Vec::new()));
116 }
117 out
118 }
119
120 fn wrap_segments_hanging_one(
121 segs: &[MixedSeg],
122 max_cols: usize,
123 first_prefix: &str,
124 next_prefix: &str,
125 ) -> Vec<Vec<MixedSeg>> {
126 let first_budget = max_cols.saturating_sub(first_prefix.chars().count()).max(1);
127 let next_budget = max_cols.saturating_sub(next_prefix.chars().count()).max(1);
128
129 let atoms = flatten_atoms(segs);
130 if atoms.is_empty() {
131 return vec![prefix_line(first_prefix, Vec::new())];
132 }
133
134 let mut lines: Vec<Vec<MixedSeg>> = Vec::new();
135 let mut current: Vec<Atom> = Vec::new();
136 let mut budget = first_budget;
137 let mut is_first = true;
138
139 for atom in atoms {
140 let atom_w = atom.width();
141 let cur_w = atoms_width(&current);
142 let need = if current.is_empty() {
143 atom_w
144 } else {
145 cur_w + 1 + atom_w // space between atoms
146 };
147
148 if !current.is_empty() && need > budget {
149 let prefix = if is_first { first_prefix } else { next_prefix };
150 lines.push(prefix_line(prefix, atoms_to_segs(&current)));
151 current.clear();
152 budget = next_budget;
153 is_first = false;
154 current.push(atom);
155 } else if current.is_empty() && atom_w > budget {
156 // Split overlong text atoms.
157 match atom {
158 Atom::Word(word) => {
159 let mut rest = word;
160 while !rest.is_empty() {
161 let chunk: String = rest.chars().take(budget).collect();
162 let n = chunk.chars().count();
163 let prefix = if is_first { first_prefix } else { next_prefix };
164 lines.push(prefix_line(prefix, vec![MixedSeg::Text(chunk)]));
165 rest = rest.chars().skip(n).collect();
166 budget = next_budget;
167 is_first = false;
168 }
169 }
170 Atom::Checkbox { checked } => {
171 let prefix = if is_first { first_prefix } else { next_prefix };
172 lines.push(prefix_line(
173 prefix,
174 vec![MixedSeg::Checkbox { checked }],
175 ));
176 budget = next_budget;
177 is_first = false;
178 }
179 }
180 } else {
181 current.push(atom);
182 }
183 }
184
185 if !current.is_empty() || lines.is_empty() {
186 let prefix = if is_first { first_prefix } else { next_prefix };
187 lines.push(prefix_line(prefix, atoms_to_segs(&current)));
188 }
189 lines
190 }
191
192 fn prefix_line(prefix: &str, mut segs: Vec<MixedSeg>) -> Vec<MixedSeg> {
193 if prefix.is_empty() {
194 return segs;
195 }
196 if let Some(MixedSeg::Text(t)) = segs.first_mut() {
197 t.insert_str(0, prefix);
198 segs
199 } else {
200 let mut out = vec![MixedSeg::Text(prefix.to_string())];
201 out.append(&mut segs);
202 out
203 }
204 }
205
206 #[derive(Clone)]
207 enum Atom {
208 Word(String),
209 Checkbox { checked: bool },
210 }
211
212 impl Atom {
213 fn width(&self) -> usize {
214 match self {
215 Atom::Word(w) => w.chars().count(),
216 Atom::Checkbox { .. } => CHECKBOX_WRAP_COLS,
217 }
218 }
219 }
220
221 fn flatten_atoms(segs: &[MixedSeg]) -> Vec<Atom> {
222 let mut atoms = Vec::new();
223 for seg in segs {
224 match seg {
225 MixedSeg::Checkbox { checked } => {
226 atoms.push(Atom::Checkbox {
227 checked: *checked,
228 });
229 }
230 MixedSeg::Text(t) => {
231 for word in t.split_whitespace() {
232 atoms.push(Atom::Word(word.to_string()));
233 }
234 }
235 }
236 }
237 atoms
238 }
239
240 fn atoms_width(atoms: &[Atom]) -> usize {
241 if atoms.is_empty() {
242 return 0;
243 }
244 let words: usize = atoms.iter().map(Atom::width).sum();
245 words + atoms.len().saturating_sub(1)
246 }
247
248 fn atoms_to_segs(atoms: &[Atom]) -> Vec<MixedSeg> {
249 let mut segs = Vec::new();
250 for (i, atom) in atoms.iter().enumerate() {
251 if i > 0 {
252 if let Some(MixedSeg::Text(t)) = segs.last_mut() {
253 t.push(' ');
254 } else {
255 segs.push(MixedSeg::Text(" ".into()));
256 }
257 }
258 match atom {
259 Atom::Word(w) => {
260 if let Some(MixedSeg::Text(t)) = segs.last_mut() {
261 t.push_str(w);
262 } else {
263 segs.push(MixedSeg::Text(w.clone()));
264 }
265 }
266 Atom::Checkbox { checked } => {
267 segs.push(MixedSeg::Checkbox {
268 checked: *checked,
269 });
270 }
271 }
272 }
273 segs
274 }
275
276 /// Rasterize a mixed text/checkbox line to a gray bitmap (black ink on white).
277 pub fn render_mixed_line(segs: &[MixedSeg]) -> GrayImage {
278 let width = line_width_dots(segs).max(1);
279 let mut img = GrayImage::from_pixel(width, LINE_HEIGHT, Luma([255]));
280 let mut x = 0u32;
281 for seg in segs {
282 match seg {
283 MixedSeg::Text(t) => {
284 for ch in t.chars() {
285 draw_char(&mut img, x, 0, ch);
286 x += CHAR_WIDTH;
287 }
288 }
289 MixedSeg::Checkbox { checked } => {
290 let box_img = render_checkbox(*checked);
291 blit(&mut img, x, 0, &box_img);
292 x += checkbox_width_dots();
293 }
294 }
295 }
296 img
297 }
298
299 pub fn checkbox_width_dots() -> u32 {
300 CHAR_WIDTH * CHECKBOX_WRAP_COLS as u32
301 }
302
303 /// Column-format data for Font A user-defined characters (ESC & y=3).
304 /// Returns (left half, right half), each ≀ 12 columns of 3 bytes.
305 pub fn checkbox_font_a_halves(checked: bool) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) {
306 let img = render_checkbox(checked);
307 let cols = gray_to_font_a_columns(&img);
308 let mid = (cols.len() / 2).min(12);
309 let right_len = (cols.len() - mid).min(12);
310 (
311 cols[..mid].to_vec(),
312 cols[mid..mid + right_len].to_vec(),
313 )
314 }
315
316 fn gray_to_font_a_columns(img: &GrayImage) -> Vec<[u8; 3]> {
317 let w = img.width().min(24);
318 let h = img.height().min(24);
319 let mut cols = Vec::with_capacity(w as usize);
320 for x in 0..w {
321 let mut bytes = [0u8; 3];
322 for y in 0..h {
323 if img.get_pixel(x, y).0[0] < 128 {
324 let byte_idx = (y / 8) as usize;
325 let bit = 7 - (y % 8);
326 bytes[byte_idx] |= 1 << bit;
327 }
328 }
329 cols.push(bytes);
330 }
331 cols
332 }
333
334 fn line_width_dots(segs: &[MixedSeg]) -> u32 {
335 let mut w = 0u32;
336 for seg in segs {
337 match seg {
338 MixedSeg::Text(t) => w += t.chars().count() as u32 * CHAR_WIDTH,
339 MixedSeg::Checkbox { .. } => w += checkbox_width_dots(),
340 }
341 }
342 w
343 }
344
345 /// Empty or checked checkbox glyph (box + optional checkmark), vertically centered.
346 pub fn render_checkbox(checked: bool) -> GrayImage {
347 let w = checkbox_width_dots();
348 let mut img = GrayImage::from_pixel(w, LINE_HEIGHT, Luma([255]));
349 let side = CHECKBOX_SIDE;
350 let x0 = (w.saturating_sub(side)) / 2;
351 let y0 = (LINE_HEIGHT.saturating_sub(side)) / 2;
352
353 for i in 0..side {
354 put_black(&mut img, x0 + i, y0);
355 put_black(&mut img, x0 + i, y0 + side - 1);
356 put_black(&mut img, x0, y0 + i);
357 put_black(&mut img, x0 + side - 1, y0 + i);
358 // 2px border
359 if i + 1 < side {
360 put_black(&mut img, x0 + i, y0 + 1);
361 put_black(&mut img, x0 + i, y0 + side - 2);
362 put_black(&mut img, x0 + 1, y0 + i);
363 put_black(&mut img, x0 + side - 2, y0 + i);
364 }
365 }
366
367 if checked {
368 // Checkmark proportions scaled with side (was 14px: 3,7 β†’ 6,10 β†’ 11,3).
369 let x1 = x0 + side * 3 / 14;
370 let y1 = y0 + side * 7 / 14;
371 let x2 = x0 + side * 6 / 14;
372 let y2 = y0 + side * 10 / 14;
373 let x3 = x0 + side * 11 / 14;
374 let y3 = y0 + side * 3 / 14;
375 draw_thick_line(&mut img, x1, y1, x2, y2);
376 draw_thick_line(&mut img, x2, y2, x3, y3);
377 }
378 img
379 }
380
381 fn put_black(img: &mut GrayImage, x: u32, y: u32) {
382 if x < img.width() && y < img.height() {
383 img.put_pixel(x, y, Luma([0]));
384 }
385 }
386
387 fn draw_thick_line(img: &mut GrayImage, x0: u32, y0: u32, x1: u32, y1: u32) {
388 for dx in 0..=1u32 {
389 for dy in 0..=1u32 {
390 draw_line(img, x0 + dx, y0 + dy, x1 + dx, y1 + dy);
391 }
392 }
393 }
394
395 fn draw_line(img: &mut GrayImage, x0: u32, y0: u32, x1: u32, y1: u32) {
396 let x0i = x0 as i32;
397 let y0i = y0 as i32;
398 let x1i = x1 as i32;
399 let y1i = y1 as i32;
400 let dx = (x1i - x0i).abs();
401 let sx = if x0i < x1i { 1 } else { -1 };
402 let dy = -(y1i - y0i).abs();
403 let sy = if y0i < y1i { 1 } else { -1 };
404 let mut err = dx + dy;
405 let mut x = x0i;
406 let mut y = y0i;
407 loop {
408 if x >= 0 && y >= 0 {
409 put_black(img, x as u32, y as u32);
410 }
411 if x == x1i && y == y1i {
412 break;
413 }
414 let e2 = 2 * err;
415 if e2 >= dy {
416 err += dy;
417 x += sx;
418 }
419 if e2 <= dx {
420 err += dx;
421 y += sy;
422 }
423 }
424 }
425
426 fn blit(dst: &mut GrayImage, x0: u32, y0: u32, src: &GrayImage) {
427 for y in 0..src.height() {
428 for x in 0..src.width() {
429 let p = src.get_pixel(x, y).0[0];
430 if p < 128 {
431 put_black(dst, x0 + x, y0 + y);
432 }
433 }
434 }
435 }
436
437 fn draw_char(img: &mut GrayImage, x0: u32, y0: u32, ch: char) {
438 let glyph = glyph_bitmap(ch);
439 // Scale 8Γ—8 β†’ 12Γ—24 with nearest neighbor.
440 for sy in 0..LINE_HEIGHT {
441 for sx in 0..CHAR_WIDTH {
442 let src_x = sx * CHAR_SRC / CHAR_WIDTH;
443 let src_y = sy * CHAR_SRC / LINE_HEIGHT;
444 let row = glyph[src_y as usize];
445 // font8x8_basic: least significant bit is the leftmost pixel.
446 let on = (row >> src_x) & 1 == 1;
447 if on {
448 put_black(img, x0 + sx, y0 + sy);
449 }
450 }
451 }
452 }
453
454 fn glyph_bitmap(ch: char) -> [u8; 8] {
455 let idx = if ch.is_ascii() && (ch as u8) >= 32 {
456 (ch as u8 - 32) as usize
457 } else {
458 // '?' for unsupported
459 (b'?' - 32) as usize
460 };
461 FONT8X8_BASIC.get(idx).copied().unwrap_or(FONT8X8_BASIC[b'?' as usize - 32])
462 }
463
464 // 8Γ—8 font for ASCII 32..126 (95 glyphs). Row-major, MSB = left.
465 // Derived from the common public-domain font8x8_basic set.
466 const FONT8X8_BASIC: [[u8; 8]; 95] = [
467 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], //
468 [0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00], // !
469 [0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // "
470 [0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00], // #
471 [0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00], // $
472 [0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00], // %
473 [0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00], // &
474 [0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00], // '
475 [0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00], // (
476 [0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00], // )
477 [0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00], // *
478 [0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00], // +
479 [0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06], // ,
480 [0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00], // -
481 [0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00], // .
482 [0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00], // /
483 [0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00], // 0
484 [0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00], // 1
485 [0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00], // 2
486 [0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00], // 3
487 [0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00], // 4
488 [0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00], // 5
489 [0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00], // 6
490 [0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00], // 7
491 [0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00], // 8
492 [0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00], // 9
493 [0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00], // :
494 [0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06], // ;
495 [0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00], // <
496 [0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00], // =
497 [0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00], // >
498 [0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00], // ?
499 [0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00], // @
500 [0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00], // A
501 [0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00], // B
502 [0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00], // C
503 [0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00], // D
504 [0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00], // E
505 [0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00], // F
506 [0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00], // G
507 [0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00], // H
508 [0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // I
509 [0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00], // J
510 [0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00], // K
511 [0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00], // L
512 [0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00], // M
513 [0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00], // N
514 [0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00], // O
515 [0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00], // P
516 [0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00], // Q
517 [0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00], // R
518 [0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00], // S
519 [0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // T
520 [0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00], // U
521 [0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00], // V
522 [0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00], // W
523 [0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00], // X
524 [0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00], // Y
525 [0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00], // Z
526 [0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00], // [
527 [0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00], // \
528 [0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00], // ]
529 [0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00], // ^
530 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF], // _
531 [0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00], // `
532 [0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00], // a
533 [0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00], // b
534 [0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00], // c
535 [0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00], // d
536 [0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00], // e
537 [0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00], // f
538 [0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F], // g
539 [0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00], // h
540 [0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // i
541 [0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E], // j
542 [0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00], // k
543 [0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // l
544 [0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00], // m
545 [0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00], // n
546 [0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00], // o
547 [0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F], // p
548 [0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78], // q
549 [0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00], // r
550 [0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00], // s
551 [0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00], // t
552 [0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00], // u
553 [0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00], // v
554 [0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00], // w
555 [0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00], // x
556 [0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F], // y
557 [0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00], // z
558 [0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00], // {
559 [0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00], // |
560 [0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00], // }
561 [0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // ~
562 ];
563
564 #[cfg(test)]
565 mod tests {
566 use super::*;
567 use crate::dsl::parse;
568
569 #[test]
570 fn checkbox_has_ink() {
571 let empty = render_checkbox(false);
572 let checked = render_checkbox(true);
573 assert_eq!(empty.dimensions(), checked.dimensions());
574 let empty_ink: usize = empty.pixels().filter(|p| p.0[0] < 128).count();
575 let checked_ink: usize = checked.pixels().filter(|p| p.0[0] < 128).count();
576 assert!(empty_ink > 40, "empty box should draw a border");
577 assert!(
578 checked_ink > empty_ink,
579 "checked box should have more ink than empty"
580 );
581 }
582
583 #[test]
584 fn wraps_checkbox_segments() {
585 let segs = vec![
586 MixedSeg::Checkbox { checked: false },
587 MixedSeg::Text("hello world".into()),
588 ];
589 let lines = wrap_segments(&segs, 10);
590 assert!(!lines.is_empty());
591 assert!(matches!(lines[0][0], MixedSeg::Checkbox { checked: false }));
592 }
593
594 #[test]
595 fn hard_newlines_keep_checkboxes_on_separate_lines() {
596 let doc = parse("[] empty\n[x] done").unwrap();
597 let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
598 panic!("paragraph");
599 };
600 let segs = segments_from_inlines(inlines);
601 let lines = wrap_segments(&segs, 32);
602 assert_eq!(lines.len(), 2, "expected 2 hard lines, got {lines:?}");
603 assert!(matches!(lines[0][0], MixedSeg::Checkbox { checked: false }));
604 assert!(matches!(lines[1][0], MixedSeg::Checkbox { checked: true }));
605 }
606
607 #[test]
608 fn segments_from_parsed_checkboxes() {
609 let doc = parse("[] hi [x]").unwrap();
610 let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
611 panic!("paragraph");
612 };
613 assert!(inlines_have_checkbox(inlines));
614 let segs = segments_from_inlines(inlines);
615 assert_eq!(
616 segs.iter()
617 .filter(|s| matches!(s, MixedSeg::Checkbox { .. }))
618 .count(),
619 2
620 );
621 }
622
623 #[test]
624 fn render_mixed_line_wider_than_checkbox() {
625 let segs = vec![
626 MixedSeg::Checkbox { checked: true },
627 MixedSeg::Text(" Done".into()),
628 ];
629 let img = render_mixed_line(&segs);
630 assert!(img.width() > checkbox_width_dots());
631 assert_eq!(img.height(), LINE_HEIGHT);
632 }
633 }
@@ -1,633 +0,0 @@
1//! Minimal 8Γ—8 ASCII font for rasterizing lines that contain checkbox glyphs.
2//! Glyphs are public-domain style bitmaps (MSB = leftmost pixel).
3
4use image::{GrayImage, Luma};
5
6/// Columns reserved for one checkbox when wrapping text (two Font A cells).
7pub const CHECKBOX_WRAP_COLS: usize = 2;
8
9/// Render height of a normal text line (matches Font A row height on ESC/POS).
10pub const LINE_HEIGHT: u32 = 24;
11/// Font A cell width in dots β€” checkbox spans two cells via user-defined chars.
12pub const CHAR_WIDTH: u32 = 12;
13const CHAR_SRC: u32 = 8;
14/// Checkbox box size (~20% larger than the original 14px).
15const CHECKBOX_SIDE: u32 = 17;
16
17/// User-defined character codes (ESC &): empty L/R, checked L/R.
18pub const CHAR_EMPTY_L: u8 = 0x01;
19pub const CHAR_EMPTY_R: u8 = 0x02;
20pub const CHAR_CHECKED_L: u8 = 0x03;
21pub const CHAR_CHECKED_R: u8 = 0x04;
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum MixedSeg {
25 Text(String),
26 Checkbox { checked: bool },
27}
28
29pub fn segments_from_inlines(inlines: &[crate::dsl::Inline]) -> Vec<MixedSeg> {
30 let mut out = Vec::new();
31 for inline in inlines {
32 match inline {
33 crate::dsl::Inline::Text(t) | crate::dsl::Inline::Param(t) => {
34 if t.is_empty() {
35 continue;
36 }
37 if let Some(MixedSeg::Text(existing)) = out.last_mut() {
38 existing.push_str(t);
39 } else {
40 out.push(MixedSeg::Text(t.clone()));
41 }
42 }
43 crate::dsl::Inline::Checkbox { checked } => {
44 out.push(MixedSeg::Checkbox {
45 checked: *checked,
46 });
47 }
48 }
49 }
50 out
51}
52
53pub fn inlines_have_checkbox(inlines: &[crate::dsl::Inline]) -> bool {
54 inlines
55 .iter()
56 .any(|i| matches!(i, crate::dsl::Inline::Checkbox { .. }))
57}
58
59/// Word-wrap mixed segments to `max_cols` character columns.
60/// Explicit `\n` inside text segments start a new line (same as [`crate::text_wrap::wrap_text`]).
61pub fn wrap_segments(segs: &[MixedSeg], max_cols: usize) -> Vec<Vec<MixedSeg>> {
62 wrap_segments_hanging(segs, max_cols, "", "")
63}
64
65/// Split segments into hard lines on `\n` inside text (checkboxes never contain newlines).
66fn split_on_newlines(segs: &[MixedSeg]) -> Vec<Vec<MixedSeg>> {
67 let mut lines: Vec<Vec<MixedSeg>> = vec![Vec::new()];
68 for seg in segs {
69 match seg {
70 MixedSeg::Checkbox { checked } => {
71 lines.last_mut().unwrap().push(MixedSeg::Checkbox {
72 checked: *checked,
73 });
74 }
75 MixedSeg::Text(t) => {
76 let parts: Vec<&str> = t.split('\n').collect();
77 for (i, part) in parts.iter().enumerate() {
78 if i > 0 {
79 lines.push(Vec::new());
80 }
81 if part.is_empty() {
82 continue;
83 }
84 let line = lines.last_mut().unwrap();
85 if let Some(MixedSeg::Text(existing)) = line.last_mut() {
86 existing.push_str(part);
87 } else {
88 line.push(MixedSeg::Text((*part).to_string()));
89 }
90 }
91 }
92 }
93 }
94 lines
95}
96
97/// Word-wrap with hanging prefixes (e.g. bullet `* ` / ` `).
98/// Explicit `\n` inside text start a new hanging-wrapped group.
99pub fn wrap_segments_hanging(
100 segs: &[MixedSeg],
101 max_cols: usize,
102 first_prefix: &str,
103 next_prefix: &str,
104) -> Vec<Vec<MixedSeg>> {
105 let mut out = Vec::new();
106 for paragraph in split_on_newlines(segs) {
107 out.extend(wrap_segments_hanging_one(
108 &paragraph,
109 max_cols,
110 first_prefix,
111 next_prefix,
112 ));
113 }
114 if out.is_empty() {
115 out.push(prefix_line(first_prefix, Vec::new()));
116 }
117 out
118}
119
120fn wrap_segments_hanging_one(
121 segs: &[MixedSeg],
122 max_cols: usize,
123 first_prefix: &str,
124 next_prefix: &str,
125) -> Vec<Vec<MixedSeg>> {
126 let first_budget = max_cols.saturating_sub(first_prefix.chars().count()).max(1);
127 let next_budget = max_cols.saturating_sub(next_prefix.chars().count()).max(1);
128
129 let atoms = flatten_atoms(segs);
130 if atoms.is_empty() {
131 return vec![prefix_line(first_prefix, Vec::new())];
132 }
133
134 let mut lines: Vec<Vec<MixedSeg>> = Vec::new();
135 let mut current: Vec<Atom> = Vec::new();
136 let mut budget = first_budget;
137 let mut is_first = true;
138
139 for atom in atoms {
140 let atom_w = atom.width();
141 let cur_w = atoms_width(&current);
142 let need = if current.is_empty() {
143 atom_w
144 } else {
145 cur_w + 1 + atom_w // space between atoms
146 };
147
148 if !current.is_empty() && need > budget {
149 let prefix = if is_first { first_prefix } else { next_prefix };
150 lines.push(prefix_line(prefix, atoms_to_segs(&current)));
151 current.clear();
152 budget = next_budget;
153 is_first = false;
154 current.push(atom);
155 } else if current.is_empty() && atom_w > budget {
156 // Split overlong text atoms.
157 match atom {
158 Atom::Word(word) => {
159 let mut rest = word;
160 while !rest.is_empty() {
161 let chunk: String = rest.chars().take(budget).collect();
162 let n = chunk.chars().count();
163 let prefix = if is_first { first_prefix } else { next_prefix };
164 lines.push(prefix_line(prefix, vec![MixedSeg::Text(chunk)]));
165 rest = rest.chars().skip(n).collect();
166 budget = next_budget;
167 is_first = false;
168 }
169 }
170 Atom::Checkbox { checked } => {
171 let prefix = if is_first { first_prefix } else { next_prefix };
172 lines.push(prefix_line(
173 prefix,
174 vec![MixedSeg::Checkbox { checked }],
175 ));
176 budget = next_budget;
177 is_first = false;
178 }
179 }
180 } else {
181 current.push(atom);
182 }
183 }
184
185 if !current.is_empty() || lines.is_empty() {
186 let prefix = if is_first { first_prefix } else { next_prefix };
187 lines.push(prefix_line(prefix, atoms_to_segs(&current)));
188 }
189 lines
190}
191
192fn prefix_line(prefix: &str, mut segs: Vec<MixedSeg>) -> Vec<MixedSeg> {
193 if prefix.is_empty() {
194 return segs;
195 }
196 if let Some(MixedSeg::Text(t)) = segs.first_mut() {
197 t.insert_str(0, prefix);
198 segs
199 } else {
200 let mut out = vec![MixedSeg::Text(prefix.to_string())];
201 out.append(&mut segs);
202 out
203 }
204}
205
206#[derive(Clone)]
207enum Atom {
208 Word(String),
209 Checkbox { checked: bool },
210}
211
212impl Atom {
213 fn width(&self) -> usize {
214 match self {
215 Atom::Word(w) => w.chars().count(),
216 Atom::Checkbox { .. } => CHECKBOX_WRAP_COLS,
217 }
218 }
219}
220
221fn flatten_atoms(segs: &[MixedSeg]) -> Vec<Atom> {
222 let mut atoms = Vec::new();
223 for seg in segs {
224 match seg {
225 MixedSeg::Checkbox { checked } => {
226 atoms.push(Atom::Checkbox {
227 checked: *checked,
228 });
229 }
230 MixedSeg::Text(t) => {
231 for word in t.split_whitespace() {
232 atoms.push(Atom::Word(word.to_string()));
233 }
234 }
235 }
236 }
237 atoms
238}
239
240fn atoms_width(atoms: &[Atom]) -> usize {
241 if atoms.is_empty() {
242 return 0;
243 }
244 let words: usize = atoms.iter().map(Atom::width).sum();
245 words + atoms.len().saturating_sub(1)
246}
247
248fn atoms_to_segs(atoms: &[Atom]) -> Vec<MixedSeg> {
249 let mut segs = Vec::new();
250 for (i, atom) in atoms.iter().enumerate() {
251 if i > 0 {
252 if let Some(MixedSeg::Text(t)) = segs.last_mut() {
253 t.push(' ');
254 } else {
255 segs.push(MixedSeg::Text(" ".into()));
256 }
257 }
258 match atom {
259 Atom::Word(w) => {
260 if let Some(MixedSeg::Text(t)) = segs.last_mut() {
261 t.push_str(w);
262 } else {
263 segs.push(MixedSeg::Text(w.clone()));
264 }
265 }
266 Atom::Checkbox { checked } => {
267 segs.push(MixedSeg::Checkbox {
268 checked: *checked,
269 });
270 }
271 }
272 }
273 segs
274}
275
276/// Rasterize a mixed text/checkbox line to a gray bitmap (black ink on white).
277pub fn render_mixed_line(segs: &[MixedSeg]) -> GrayImage {
278 let width = line_width_dots(segs).max(1);
279 let mut img = GrayImage::from_pixel(width, LINE_HEIGHT, Luma([255]));
280 let mut x = 0u32;
281 for seg in segs {
282 match seg {
283 MixedSeg::Text(t) => {
284 for ch in t.chars() {
285 draw_char(&mut img, x, 0, ch);
286 x += CHAR_WIDTH;
287 }
288 }
289 MixedSeg::Checkbox { checked } => {
290 let box_img = render_checkbox(*checked);
291 blit(&mut img, x, 0, &box_img);
292 x += checkbox_width_dots();
293 }
294 }
295 }
296 img
297}
298
299pub fn checkbox_width_dots() -> u32 {
300 CHAR_WIDTH * CHECKBOX_WRAP_COLS as u32
301}
302
303/// Column-format data for Font A user-defined characters (ESC & y=3).
304/// Returns (left half, right half), each ≀ 12 columns of 3 bytes.
305pub fn checkbox_font_a_halves(checked: bool) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) {
306 let img = render_checkbox(checked);
307 let cols = gray_to_font_a_columns(&img);
308 let mid = (cols.len() / 2).min(12);
309 let right_len = (cols.len() - mid).min(12);
310 (
311 cols[..mid].to_vec(),
312 cols[mid..mid + right_len].to_vec(),
313 )
314}
315
316fn gray_to_font_a_columns(img: &GrayImage) -> Vec<[u8; 3]> {
317 let w = img.width().min(24);
318 let h = img.height().min(24);
319 let mut cols = Vec::with_capacity(w as usize);
320 for x in 0..w {
321 let mut bytes = [0u8; 3];
322 for y in 0..h {
323 if img.get_pixel(x, y).0[0] < 128 {
324 let byte_idx = (y / 8) as usize;
325 let bit = 7 - (y % 8);
326 bytes[byte_idx] |= 1 << bit;
327 }
328 }
329 cols.push(bytes);
330 }
331 cols
332}
333
334fn line_width_dots(segs: &[MixedSeg]) -> u32 {
335 let mut w = 0u32;
336 for seg in segs {
337 match seg {
338 MixedSeg::Text(t) => w += t.chars().count() as u32 * CHAR_WIDTH,
339 MixedSeg::Checkbox { .. } => w += checkbox_width_dots(),
340 }
341 }
342 w
343}
344
345/// Empty or checked checkbox glyph (box + optional checkmark), vertically centered.
346pub fn render_checkbox(checked: bool) -> GrayImage {
347 let w = checkbox_width_dots();
348 let mut img = GrayImage::from_pixel(w, LINE_HEIGHT, Luma([255]));
349 let side = CHECKBOX_SIDE;
350 let x0 = (w.saturating_sub(side)) / 2;
351 let y0 = (LINE_HEIGHT.saturating_sub(side)) / 2;
352
353 for i in 0..side {
354 put_black(&mut img, x0 + i, y0);
355 put_black(&mut img, x0 + i, y0 + side - 1);
356 put_black(&mut img, x0, y0 + i);
357 put_black(&mut img, x0 + side - 1, y0 + i);
358 // 2px border
359 if i + 1 < side {
360 put_black(&mut img, x0 + i, y0 + 1);
361 put_black(&mut img, x0 + i, y0 + side - 2);
362 put_black(&mut img, x0 + 1, y0 + i);
363 put_black(&mut img, x0 + side - 2, y0 + i);
364 }
365 }
366
367 if checked {
368 // Checkmark proportions scaled with side (was 14px: 3,7 β†’ 6,10 β†’ 11,3).
369 let x1 = x0 + side * 3 / 14;
370 let y1 = y0 + side * 7 / 14;
371 let x2 = x0 + side * 6 / 14;
372 let y2 = y0 + side * 10 / 14;
373 let x3 = x0 + side * 11 / 14;
374 let y3 = y0 + side * 3 / 14;
375 draw_thick_line(&mut img, x1, y1, x2, y2);
376 draw_thick_line(&mut img, x2, y2, x3, y3);
377 }
378 img
379}
380
381fn put_black(img: &mut GrayImage, x: u32, y: u32) {
382 if x < img.width() && y < img.height() {
383 img.put_pixel(x, y, Luma([0]));
384 }
385}
386
387fn draw_thick_line(img: &mut GrayImage, x0: u32, y0: u32, x1: u32, y1: u32) {
388 for dx in 0..=1u32 {
389 for dy in 0..=1u32 {
390 draw_line(img, x0 + dx, y0 + dy, x1 + dx, y1 + dy);
391 }
392 }
393}
394
395fn draw_line(img: &mut GrayImage, x0: u32, y0: u32, x1: u32, y1: u32) {
396 let x0i = x0 as i32;
397 let y0i = y0 as i32;
398 let x1i = x1 as i32;
399 let y1i = y1 as i32;
400 let dx = (x1i - x0i).abs();
401 let sx = if x0i < x1i { 1 } else { -1 };
402 let dy = -(y1i - y0i).abs();
403 let sy = if y0i < y1i { 1 } else { -1 };
404 let mut err = dx + dy;
405 let mut x = x0i;
406 let mut y = y0i;
407 loop {
408 if x >= 0 && y >= 0 {
409 put_black(img, x as u32, y as u32);
410 }
411 if x == x1i && y == y1i {
412 break;
413 }
414 let e2 = 2 * err;
415 if e2 >= dy {
416 err += dy;
417 x += sx;
418 }
419 if e2 <= dx {
420 err += dx;
421 y += sy;
422 }
423 }
424}
425
426fn blit(dst: &mut GrayImage, x0: u32, y0: u32, src: &GrayImage) {
427 for y in 0..src.height() {
428 for x in 0..src.width() {
429 let p = src.get_pixel(x, y).0[0];
430 if p < 128 {
431 put_black(dst, x0 + x, y0 + y);
432 }
433 }
434 }
435}
436
437fn draw_char(img: &mut GrayImage, x0: u32, y0: u32, ch: char) {
438 let glyph = glyph_bitmap(ch);
439 // Scale 8Γ—8 β†’ 12Γ—24 with nearest neighbor.
440 for sy in 0..LINE_HEIGHT {
441 for sx in 0..CHAR_WIDTH {
442 let src_x = sx * CHAR_SRC / CHAR_WIDTH;
443 let src_y = sy * CHAR_SRC / LINE_HEIGHT;
444 let row = glyph[src_y as usize];
445 // font8x8_basic: least significant bit is the leftmost pixel.
446 let on = (row >> src_x) & 1 == 1;
447 if on {
448 put_black(img, x0 + sx, y0 + sy);
449 }
450 }
451 }
452}
453
454fn glyph_bitmap(ch: char) -> [u8; 8] {
455 let idx = if ch.is_ascii() && (ch as u8) >= 32 {
456 (ch as u8 - 32) as usize
457 } else {
458 // '?' for unsupported
459 (b'?' - 32) as usize
460 };
461 FONT8X8_BASIC.get(idx).copied().unwrap_or(FONT8X8_BASIC[b'?' as usize - 32])
462}
463
464// 8Γ—8 font for ASCII 32..126 (95 glyphs). Row-major, MSB = left.
465// Derived from the common public-domain font8x8_basic set.
466const FONT8X8_BASIC: [[u8; 8]; 95] = [
467 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], //
468 [0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00], // !
469 [0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // "
470 [0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00], // #
471 [0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00], // $
472 [0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00], // %
473 [0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00], // &
474 [0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00], // '
475 [0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00], // (
476 [0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00], // )
477 [0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00], // *
478 [0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00], // +
479 [0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06], // ,
480 [0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00], // -
481 [0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00], // .
482 [0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00], // /
483 [0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00], // 0
484 [0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00], // 1
485 [0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00], // 2
486 [0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00], // 3
487 [0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00], // 4
488 [0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00], // 5
489 [0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00], // 6
490 [0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00], // 7
491 [0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00], // 8
492 [0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00], // 9
493 [0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00], // :
494 [0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06], // ;
495 [0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00], // <
496 [0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00], // =
497 [0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00], // >
498 [0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00], // ?
499 [0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00], // @
500 [0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00], // A
501 [0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00], // B
502 [0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00], // C
503 [0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00], // D
504 [0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00], // E
505 [0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00], // F
506 [0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00], // G
507 [0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00], // H
508 [0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // I
509 [0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00], // J
510 [0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00], // K
511 [0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00], // L
512 [0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00], // M
513 [0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00], // N
514 [0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00], // O
515 [0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00], // P
516 [0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00], // Q
517 [0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00], // R
518 [0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00], // S
519 [0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // T
520 [0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00], // U
521 [0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00], // V
522 [0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00], // W
523 [0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00], // X
524 [0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00], // Y
525 [0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00], // Z
526 [0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00], // [
527 [0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00], // \
528 [0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00], // ]
529 [0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00], // ^
530 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF], // _
531 [0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00], // `
532 [0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00], // a
533 [0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00], // b
534 [0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00], // c
535 [0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00], // d
536 [0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00], // e
537 [0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00], // f
538 [0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F], // g
539 [0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00], // h
540 [0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // i
541 [0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E], // j
542 [0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00], // k
543 [0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00], // l
544 [0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00], // m
545 [0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00], // n
546 [0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00], // o
547 [0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F], // p
548 [0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78], // q
549 [0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00], // r
550 [0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00], // s
551 [0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00], // t
552 [0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00], // u
553 [0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00], // v
554 [0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00], // w
555 [0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00], // x
556 [0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F], // y
557 [0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00], // z
558 [0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00], // {
559 [0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00], // |
560 [0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00], // }
561 [0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // ~
562];
563
564#[cfg(test)]
565mod tests {
566 use super::*;
567 use crate::dsl::parse;
568
569 #[test]
570 fn checkbox_has_ink() {
571 let empty = render_checkbox(false);
572 let checked = render_checkbox(true);
573 assert_eq!(empty.dimensions(), checked.dimensions());
574 let empty_ink: usize = empty.pixels().filter(|p| p.0[0] < 128).count();
575 let checked_ink: usize = checked.pixels().filter(|p| p.0[0] < 128).count();
576 assert!(empty_ink > 40, "empty box should draw a border");
577 assert!(
578 checked_ink > empty_ink,
579 "checked box should have more ink than empty"
580 );
581 }
582
583 #[test]
584 fn wraps_checkbox_segments() {
585 let segs = vec![
586 MixedSeg::Checkbox { checked: false },
587 MixedSeg::Text("hello world".into()),
588 ];
589 let lines = wrap_segments(&segs, 10);
590 assert!(!lines.is_empty());
591 assert!(matches!(lines[0][0], MixedSeg::Checkbox { checked: false }));
592 }
593
594 #[test]
595 fn hard_newlines_keep_checkboxes_on_separate_lines() {
596 let doc = parse("[] empty\n[x] done").unwrap();
597 let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
598 panic!("paragraph");
599 };
600 let segs = segments_from_inlines(inlines);
601 let lines = wrap_segments(&segs, 32);
602 assert_eq!(lines.len(), 2, "expected 2 hard lines, got {lines:?}");
603 assert!(matches!(lines[0][0], MixedSeg::Checkbox { checked: false }));
604 assert!(matches!(lines[1][0], MixedSeg::Checkbox { checked: true }));
605 }
606
607 #[test]
608 fn segments_from_parsed_checkboxes() {
609 let doc = parse("[] hi [x]").unwrap();
610 let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
611 panic!("paragraph");
612 };
613 assert!(inlines_have_checkbox(inlines));
614 let segs = segments_from_inlines(inlines);
615 assert_eq!(
616 segs.iter()
617 .filter(|s| matches!(s, MixedSeg::Checkbox { .. }))
618 .count(),
619 2
620 );
621 }
622
623 #[test]
624 fn render_mixed_line_wider_than_checkbox() {
625 let segs = vec![
626 MixedSeg::Checkbox { checked: true },
627 MixedSeg::Text(" Done".into()),
628 ];
629 let img = render_mixed_line(&segs);
630 assert!(img.width() > checkbox_width_dots());
631 assert_eq!(img.height(), LINE_HEIGHT);
632 }
633}
src/dsl/mod.rs +3 βˆ’3
@@ -141,12 +141,12 @@ pub enum Inline {
141 141 },
142 142 }
143 143
144 /// Preview glyphs for checkboxes (Unicode ballot boxes; print uses rasters).
144 /// Checkbox glyphs sent as UTF-8 (trial: ballot box / ballot box with bold check).
145 145 pub fn checkbox_glyph(checked: bool) -> &'static str {
146 146 if checked {
147 "β˜‘"
147 "πŸ—Ή" // U+1F5F9 BALLOT BOX WITH BOLD CHECK
148 148 } else {
149 "☐"
149 "☐" // U+2610 BALLOT BOX
150 150 }
151 151 }
152 152
@@ -141,12 +141,12 @@ pub enum Inline {
141 },
141 },
142}
142}
143
143
144/// Preview glyphs for checkboxes (Unicode ballot boxes; print uses rasters).
144/// Checkbox glyphs sent as UTF-8 (trial: ballot box / ballot box with bold check).
145pub fn checkbox_glyph(checked: bool) -> &'static str {
145pub fn checkbox_glyph(checked: bool) -> &'static str {
146 if checked {
146 if checked {
147 "β˜‘"
147 "πŸ—Ή" // U+1F5F9 BALLOT BOX WITH BOLD CHECK
148 } else {
148 } else {
149 "☐"
149 "☐" // U+2610 BALLOT BOX
150 }
150 }
151}
151}
152
152
src/escpos.rs +22 βˆ’137
@@ -2,7 +2,6 @@ use std::path::Path;
2 2
3 3 use image::GrayImage;
4 4
5 use crate::bitmap_font::{self, MixedSeg};
6 5 use crate::dsl::{
7 6 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc, QrMode,
8 7 };
@@ -54,33 +53,6 @@ impl EscPosEncoder {
54 53 fn init(&mut self) {
55 54 self.buffer.extend_from_slice(&[0x1B, b'@']);
56 55 self.buffer.extend_from_slice(&[0x1B, b't', 0]);
57 // Checkbox glyphs as Font A user-defined characters so they stay inline
58 // with the native text font (ESC * is not buffered on many micro-printers).
59 self.define_checkbox_user_chars();
60 }
61
62 fn define_checkbox_user_chars(&mut self) {
63 let (el, er) = bitmap_font::checkbox_font_a_halves(false);
64 let (cl, cr) = bitmap_font::checkbox_font_a_halves(true);
65 self.define_font_a_char(bitmap_font::CHAR_EMPTY_L, &el);
66 self.define_font_a_char(bitmap_font::CHAR_EMPTY_R, &er);
67 self.define_font_a_char(bitmap_font::CHAR_CHECKED_L, &cl);
68 self.define_font_a_char(bitmap_font::CHAR_CHECKED_R, &cr);
69 // Select user-defined character set; undefined codes use the resident font.
70 self.buffer.extend_from_slice(&[0x1B, b'%', 1]);
71 }
72
73 /// ESC & y=3 β€” define one Font A (12Γ—24) user character from column data.
74 fn define_font_a_char(&mut self, code: u8, columns: &[[u8; 3]]) {
75 let x = columns.len().min(12) as u8;
76 if x == 0 {
77 return;
78 }
79 self.buffer
80 .extend_from_slice(&[0x1B, b'&', 3, code, code, x]);
81 for col in columns.iter().take(x as usize) {
82 self.buffer.extend_from_slice(col);
83 }
84 56 }
85 57
86 58 fn encode_block(&mut self, block: &Block) -> Result<(), EscPosError> {
@@ -88,31 +60,18 @@ impl EscPosEncoder {
88 60 Block::Paragraph { align, inlines } => {
89 61 self.set_align(*align);
90 62 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
91 if bitmap_font::inlines_have_checkbox(inlines) {
92 self.encode_mixed_inlines(inlines, cols, "", "")?;
93 } else {
94 let line = inlines_to_plain(inlines);
95 for part in text_wrap::wrap_text(&line, cols) {
96 self.writeln(&part);
97 }
63 let line = inlines_to_plain(inlines);
64 for part in text_wrap::wrap_text(&line, cols) {
65 self.writeln(&part);
98 66 }
99 67 }
100 68 Block::List { align, items } => {
101 69 self.set_align(*align);
102 70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
103 71 for item in items {
104 if bitmap_font::inlines_have_checkbox(item) {
105 self.encode_mixed_inlines(
106 item,
107 cols,
108 text_wrap::BULLET_FIRST_PREFIX,
109 text_wrap::BULLET_NEXT_PREFIX,
110 )?;
111 } else {
112 let line = inlines_to_plain(item);
113 for part in text_wrap::wrap_bullet_item(&line, cols) {
114 self.writeln(&part);
115 }
72 let line = inlines_to_plain(item);
73 for part in text_wrap::wrap_bullet_item(&line, cols) {
74 self.writeln(&part);
116 75 }
117 76 }
118 77 }
@@ -124,33 +83,19 @@ impl EscPosEncoder {
124 83 TextWrapStyle::Heading2
125 84 };
126 85 let cols = text_wrap::wrap_cols(&self.metadata, wrap_style);
127 if bitmap_font::inlines_have_checkbox(inlines) {
128 if *level == 1 {
129 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
130 } else {
131 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
132 }
133 self.encode_mixed_inlines(inlines, cols, "", "")?;
134 if *level == 1 {
135 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
136 } else {
137 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
138 }
86 let wrapped = text_wrap::wrap_text(&inlines_to_plain(inlines), cols);
87 if *level == 1 {
88 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
139 89 } else {
140 let wrapped = text_wrap::wrap_text(&inlines_to_plain(inlines), cols);
141 if *level == 1 {
142 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
143 } else {
144 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
145 }
146 for part in &wrapped {
147 self.writeln(part);
148 }
149 if *level == 1 {
150 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
151 } else {
152 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
153 }
90 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
91 }
92 for part in &wrapped {
93 self.writeln(part);
94 }
95 if *level == 1 {
96 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
97 } else {
98 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
154 99 }
155 100 }
156 101 Block::Rule => {
@@ -237,50 +182,6 @@ impl EscPosEncoder {
237 182 self.buffer.push(b'\n');
238 183 }
239 184
240 fn encode_mixed_inlines(
241 &mut self,
242 inlines: &[Inline],
243 cols: usize,
244 first_prefix: &str,
245 next_prefix: &str,
246 ) -> Result<(), EscPosError> {
247 let segs = bitmap_font::segments_from_inlines(inlines);
248 let lines = if first_prefix.is_empty() && next_prefix.is_empty() {
249 bitmap_font::wrap_segments(&segs, cols)
250 } else {
251 bitmap_font::wrap_segments_hanging(&segs, cols, first_prefix, next_prefix)
252 };
253 for line in lines {
254 self.encode_mixed_line(&line)?;
255 }
256 Ok(())
257 }
258
259 fn encode_mixed_line(&mut self, segs: &[MixedSeg]) -> Result<(), EscPosError> {
260 for seg in segs {
261 match seg {
262 MixedSeg::Text(t) => self.buffer.extend_from_slice(t.as_bytes()),
263 MixedSeg::Checkbox { checked } => self.write_checkbox_chars(*checked),
264 }
265 }
266 self.buffer.push(b'\n');
267 Ok(())
268 }
269
270 fn write_checkbox_chars(&mut self, checked: bool) {
271 if checked {
272 self.buffer.extend_from_slice(&[
273 bitmap_font::CHAR_CHECKED_L,
274 bitmap_font::CHAR_CHECKED_R,
275 ]);
276 } else {
277 self.buffer.extend_from_slice(&[
278 bitmap_font::CHAR_EMPTY_L,
279 bitmap_font::CHAR_EMPTY_R,
280 ]);
281 }
282 }
283
284 185 fn feed(&mut self, lines: u8) {
285 186 if lines == 0 {
286 187 return;
@@ -498,31 +399,15 @@ mod tests {
498 399 }
499 400
500 401 #[test]
501 fn encodes_inline_checkboxes_as_user_chars() {
402 fn encodes_inline_checkboxes_as_unicode_glyphs() {
502 403 let doc = parse("[] hello [x]").unwrap();
503 404 let mut enc = EscPosEncoder::new(PosMetadata::default());
504 405 let bytes = enc.encode_document(&doc).unwrap();
406 let text = String::from_utf8_lossy(bytes);
505 407 assert!(
506 bytes.windows(2).any(|w| w == [0x1B, b'&']),
507 "should define user-defined checkbox characters with ESC &"
508 );
509 assert!(
510 bytes.windows(2).any(|w| w == [0x1B, b'%']),
511 "should select user-defined character set"
512 );
513 assert!(
514 bytes.windows(5).any(|w| w == b"hello"),
515 "surrounding text should stay as native font bytes"
516 );
517 assert!(
518 !bytes.windows(3).any(|w| w == [0x1B, b'*', 33]),
519 "should not use ESC * bit images for checkboxes"
408 text.contains("☐ hello πŸ—Ή\n"),
409 "expected Unicode ballot glyphs inline, got: {text:?}"
520 410 );
521 // `[] hello` β†’ empty chars, space, then "hello"
522 let hello = bytes.windows(5).position(|w| w == b"hello").unwrap();
523 assert_eq!(bytes[hello - 1], b' ');
524 assert_eq!(bytes[hello - 2], bitmap_font::CHAR_EMPTY_R);
525 assert_eq!(bytes[hello - 3], bitmap_font::CHAR_EMPTY_L);
526 411 }
527 412
528 413 #[test]
@@ -2,7 +2,6 @@ use std::path::Path;
2
2
3use image::GrayImage;
3use image::GrayImage;
4
4
5use crate::bitmap_font::{self, MixedSeg};
6use crate::dsl::{
5use crate::dsl::{
7 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc, QrMode,
6 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc, QrMode,
8};
7};
@@ -54,33 +53,6 @@ impl EscPosEncoder {
54 fn init(&mut self) {
53 fn init(&mut self) {
55 self.buffer.extend_from_slice(&[0x1B, b'@']);
54 self.buffer.extend_from_slice(&[0x1B, b'@']);
56 self.buffer.extend_from_slice(&[0x1B, b't', 0]);
55 self.buffer.extend_from_slice(&[0x1B, b't', 0]);
57 // Checkbox glyphs as Font A user-defined characters so they stay inline
58 // with the native text font (ESC * is not buffered on many micro-printers).
59 self.define_checkbox_user_chars();
60 }
61
62 fn define_checkbox_user_chars(&mut self) {
63 let (el, er) = bitmap_font::checkbox_font_a_halves(false);
64 let (cl, cr) = bitmap_font::checkbox_font_a_halves(true);
65 self.define_font_a_char(bitmap_font::CHAR_EMPTY_L, &el);
66 self.define_font_a_char(bitmap_font::CHAR_EMPTY_R, &er);
67 self.define_font_a_char(bitmap_font::CHAR_CHECKED_L, &cl);
68 self.define_font_a_char(bitmap_font::CHAR_CHECKED_R, &cr);
69 // Select user-defined character set; undefined codes use the resident font.
70 self.buffer.extend_from_slice(&[0x1B, b'%', 1]);
71 }
72
73 /// ESC & y=3 β€” define one Font A (12Γ—24) user character from column data.
74 fn define_font_a_char(&mut self, code: u8, columns: &[[u8; 3]]) {
75 let x = columns.len().min(12) as u8;
76 if x == 0 {
77 return;
78 }
79 self.buffer
80 .extend_from_slice(&[0x1B, b'&', 3, code, code, x]);
81 for col in columns.iter().take(x as usize) {
82 self.buffer.extend_from_slice(col);
83 }
84 }
56 }
85
57
86 fn encode_block(&mut self, block: &Block) -> Result<(), EscPosError> {
58 fn encode_block(&mut self, block: &Block) -> Result<(), EscPosError> {
@@ -88,31 +60,18 @@ impl EscPosEncoder {
88 Block::Paragraph { align, inlines } => {
60 Block::Paragraph { align, inlines } => {
89 self.set_align(*align);
61 self.set_align(*align);
90 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
62 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
91 if bitmap_font::inlines_have_checkbox(inlines) {
63 let line = inlines_to_plain(inlines);
92 self.encode_mixed_inlines(inlines, cols, "", "")?;
64 for part in text_wrap::wrap_text(&line, cols) {
93 } else {
65 self.writeln(&part);
94 let line = inlines_to_plain(inlines);
95 for part in text_wrap::wrap_text(&line, cols) {
96 self.writeln(&part);
97 }
98 }
66 }
99 }
67 }
100 Block::List { align, items } => {
68 Block::List { align, items } => {
101 self.set_align(*align);
69 self.set_align(*align);
102 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
103 for item in items {
71 for item in items {
104 if bitmap_font::inlines_have_checkbox(item) {
72 let line = inlines_to_plain(item);
105 self.encode_mixed_inlines(
73 for part in text_wrap::wrap_bullet_item(&line, cols) {
106 item,
74 self.writeln(&part);
107 cols,
108 text_wrap::BULLET_FIRST_PREFIX,
109 text_wrap::BULLET_NEXT_PREFIX,
110 )?;
111 } else {
112 let line = inlines_to_plain(item);
113 for part in text_wrap::wrap_bullet_item(&line, cols) {
114 self.writeln(&part);
115 }
116 }
75 }
117 }
76 }
118 }
77 }
@@ -124,33 +83,19 @@ impl EscPosEncoder {
124 TextWrapStyle::Heading2
83 TextWrapStyle::Heading2
125 };
84 };
126 let cols = text_wrap::wrap_cols(&self.metadata, wrap_style);
85 let cols = text_wrap::wrap_cols(&self.metadata, wrap_style);
127 if bitmap_font::inlines_have_checkbox(inlines) {
86 let wrapped = text_wrap::wrap_text(&inlines_to_plain(inlines), cols);
128 if *level == 1 {
87 if *level == 1 {
129 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
88 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
130 } else {
131 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
132 }
133 self.encode_mixed_inlines(inlines, cols, "", "")?;
134 if *level == 1 {
135 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
136 } else {
137 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
138 }
139 } else {
89 } else {
140 let wrapped = text_wrap::wrap_text(&inlines_to_plain(inlines), cols);
90 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
141 if *level == 1 {
91 }
142 self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
92 for part in &wrapped {
143 } else {
93 self.writeln(part);
144 self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
94 }
145 }
95 if *level == 1 {
146 for part in &wrapped {
96 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
147 self.writeln(part);
97 } else {
148 }
98 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
149 if *level == 1 {
150 self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
151 } else {
152 self.buffer.extend_from_slice(&[0x1B, b'E', 0]);
153 }
154 }
99 }
155 }
100 }
156 Block::Rule => {
101 Block::Rule => {
@@ -237,50 +182,6 @@ impl EscPosEncoder {
237 self.buffer.push(b'\n');
182 self.buffer.push(b'\n');
238 }
183 }
239
184
240 fn encode_mixed_inlines(
241 &mut self,
242 inlines: &[Inline],
243 cols: usize,
244 first_prefix: &str,
245 next_prefix: &str,
246 ) -> Result<(), EscPosError> {
247 let segs = bitmap_font::segments_from_inlines(inlines);
248 let lines = if first_prefix.is_empty() && next_prefix.is_empty() {
249 bitmap_font::wrap_segments(&segs, cols)
250 } else {
251 bitmap_font::wrap_segments_hanging(&segs, cols, first_prefix, next_prefix)
252 };
253 for line in lines {
254 self.encode_mixed_line(&line)?;
255 }
256 Ok(())
257 }
258
259 fn encode_mixed_line(&mut self, segs: &[MixedSeg]) -> Result<(), EscPosError> {
260 for seg in segs {
261 match seg {
262 MixedSeg::Text(t) => self.buffer.extend_from_slice(t.as_bytes()),
263 MixedSeg::Checkbox { checked } => self.write_checkbox_chars(*checked),
264 }
265 }
266 self.buffer.push(b'\n');
267 Ok(())
268 }
269
270 fn write_checkbox_chars(&mut self, checked: bool) {
271 if checked {
272 self.buffer.extend_from_slice(&[
273 bitmap_font::CHAR_CHECKED_L,
274 bitmap_font::CHAR_CHECKED_R,
275 ]);
276 } else {
277 self.buffer.extend_from_slice(&[
278 bitmap_font::CHAR_EMPTY_L,
279 bitmap_font::CHAR_EMPTY_R,
280 ]);
281 }
282 }
283
284 fn feed(&mut self, lines: u8) {
185 fn feed(&mut self, lines: u8) {
285 if lines == 0 {
186 if lines == 0 {
286 return;
187 return;
@@ -498,31 +399,15 @@ mod tests {
498 }
399 }
499
400
500 #[test]
401 #[test]
501 fn encodes_inline_checkboxes_as_user_chars() {
402 fn encodes_inline_checkboxes_as_unicode_glyphs() {
502 let doc = parse("[] hello [x]").unwrap();
403 let doc = parse("[] hello [x]").unwrap();
503 let mut enc = EscPosEncoder::new(PosMetadata::default());
404 let mut enc = EscPosEncoder::new(PosMetadata::default());
504 let bytes = enc.encode_document(&doc).unwrap();
405 let bytes = enc.encode_document(&doc).unwrap();
406 let text = String::from_utf8_lossy(bytes);
505 assert!(
407 assert!(
506 bytes.windows(2).any(|w| w == [0x1B, b'&']),
408 text.contains("☐ hello πŸ—Ή\n"),
507 "should define user-defined checkbox characters with ESC &"
409 "expected Unicode ballot glyphs inline, got: {text:?}"
508 );
509 assert!(
510 bytes.windows(2).any(|w| w == [0x1B, b'%']),
511 "should select user-defined character set"
512 );
513 assert!(
514 bytes.windows(5).any(|w| w == b"hello"),
515 "surrounding text should stay as native font bytes"
516 );
517 assert!(
518 !bytes.windows(3).any(|w| w == [0x1B, b'*', 33]),
519 "should not use ESC * bit images for checkboxes"
520 );
410 );
521 // `[] hello` β†’ empty chars, space, then "hello"
522 let hello = bytes.windows(5).position(|w| w == b"hello").unwrap();
523 assert_eq!(bytes[hello - 1], b' ');
524 assert_eq!(bytes[hello - 2], bitmap_font::CHAR_EMPTY_R);
525 assert_eq!(bytes[hello - 3], bitmap_font::CHAR_EMPTY_L);
526 }
411 }
527
412
528 #[test]
413 #[test]
src/lib.rs +0 βˆ’1
@@ -1,4 +1,3 @@
1 pub mod bitmap_font;
2 1 pub mod cli;
3 2 pub mod datetime;
4 3 pub mod dsl;
@@ -1,4 +1,3 @@
1pub mod bitmap_font;
2pub mod cli;
1pub mod cli;
3pub mod datetime;
2pub mod datetime;
4pub mod dsl;
3pub mod dsl;