BlueGit

timfa posprint

Add CP437 [√] checkboxes and $[Name] bool parameters.

Checked boxes use CP437 sqrt; $[Name] is a print-dialog/CLI checkbox distinct from  text params.

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

timfa Tim Falken · pushed by timfa

Authored 2026-07-17 · 4 months ago

Hash
f0465192d630e21f1337760b05b7c8129a279e8b
Parent
d1066061
15 files changed +495 −116
docs/DSL-SPEC.md +20 −13
@@ -75,16 +75,20 @@ Wrapped lines use a hanging indent:
75 75
76 76 | Syntax | Effect |
77 77 |--------|--------|
78 | `${Name}` | Parameter placeholder (see Parameters) |
78 | `${Name}` | Text parameter placeholder (see Parameters) |
79 | `$[Name]` | Bool checkbox parameter → `[ ]` / `[√]` |
80
81 `${Name}` and `$[Name]` must not share the same name.
79 82
80 83 ### Checkboxes
81 84
82 85 | Syntax | Printed result |
83 86 |--------|----------------|
84 87 | `[]` or `[ ]` | `[ ]` |
85 | `[x]` or `[X]` | `[x]` |
88 | `[x]` / `[X]` / `[√]` | `[√]` (CP437 byte `0xFB`) |
89 | `$[Name]` | `[ ]` or `[√]` from a bool parameter |
86 90
87 ASCII only — stays inline in the native CP437 font. Unicode ☐/🗹 and ESC `*`/`&` graphics were tried and rejected for this stack (CJK mojibake / not inline).
91 ASCII brackets + CP437 `√` stay inline in the native font. `${Name}` and `$[Name]` cannot share a name.
88 92
89 93 Parameters work inside any text, and inside barcode/QR/image directives (below).
90 94
@@ -94,7 +98,7 @@ Parameters work inside any text, and inside barcode/QR/image directives (below).
94 98 Receipt #${DocumentNumber}
95 99 Date: ${Date}
96 100
97 [x] Paid
101 $[Paid] Paid
98 102 [] Pending
99 103
100 104 Item: ${ItemName} ${LineTotal}
@@ -207,27 +211,30 @@ Raster barcodes stretch horizontally to full printable width.
207 211 ### Syntax
208 212
209 213 ```
210 ${ParameterName}
214 ${ParameterName} # text
215 $[ParameterName] # boolean checkbox → [ ] / [√]
211 216 ```
212 217
213 218 - **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
214 219 - **Case-sensitive:** `${DocNo}` and `${docno}` are different
220 - **No mixed types:** the same name must not appear as both `${…}` and `$[…]`
215 221 - **Uniqueness at input:** all occurrences of the same name share one value entered at print time
216 222
217 223 ### Where parameters are allowed
218 224
219 225 | Location | Example |
220 226 |----------|---------|
221 | Text | `Order ${OrderId}` |
222 | Barcode data | `@barcode CODE128 ${OrderId}` |
223 | QR data | `@qr ${VerifyUrl}` |
224 | Image path | `@image ${LogoPath}` |
227 | Text | `Order ${OrderId}` / `$[Paid] Paid` |
228 | Barcode data | `@barcode CODE128 ${OrderId}` (`${…}` only) |
229 | QR data | `@qr ${VerifyUrl}` (`${…}` only) |
230 | Image path | `@image ${LogoPath}` (`${…}` only) |
225 231
226 232 ### Print-time behavior
227 233
228 1. Before print, scan AST for all `${...}` tokens.
229 2. Deduplicate by name.
230 3. Show dialog with one field per unique name (or require CLI `--set`).
234 1. Before print, scan AST for all `${…}` and `$[…]` tokens.
235 2. Deduplicate by name (kinds must not conflict — enforced at parse).
236 3. Show dialog: text field per `${…}`, checkbox per `$[…]` (or require CLI `--set`).
237 4. Bool values: `true`/`false` (also `1`/`0`, `yes`/`no`).
231 238 4. Pre-fill from last print session (in-memory).
232 239 5. Substitute into AST, then encode/print.
233 240
@@ -269,7 +276,7 @@ Parse errors include 1-based line and column. Typical causes:
269 276 | `# heading` | Double width/height ON → text → OFF |
270 277 | `## heading` | Bold ON → text → OFF |
271 278 | `- item` | ASCII `* ` bullet + hanging wrap |
272 | `[]` / `[ ]` / `[x]` | ASCII `[ ]` / `[x]` (CP437-safe, inline) |
279 | `[]` / `[ ]` / `[x]` / `$[Name]` | ASCII `[ ]` / `[√]` (CP437-safe, inline) |
273 280 | `:center:` | Justification center |
274 281 | `@feed n` / blank line | ESC d n |
275 282 | `@cut` | GS V partial cut |
@@ -75,16 +75,20 @@ Wrapped lines use a hanging indent:
75
75
76| Syntax | Effect |
76| Syntax | Effect |
77|--------|--------|
77|--------|--------|
78| `${Name}` | Parameter placeholder (see Parameters) |
78| `${Name}` | Text parameter placeholder (see Parameters) |
79| `$[Name]` | Bool checkbox parameter → `[ ]` / `[√]` |
80
81`${Name}` and `$[Name]` must not share the same name.
79
82
80### Checkboxes
83### Checkboxes
81
84
82| Syntax | Printed result |
85| Syntax | Printed result |
83|--------|----------------|
86|--------|----------------|
84| `[]` or `[ ]` | `[ ]` |
87| `[]` or `[ ]` | `[ ]` |
85| `[x]` or `[X]` | `[x]` |
88| `[x]` / `[X]` / `[√]` | `[√]` (CP437 byte `0xFB`) |
89| `$[Name]` | `[ ]` or `[√]` from a bool parameter |
86
90
87ASCII only — stays inline in the native CP437 font. Unicode ☐/🗹 and ESC `*`/`&` graphics were tried and rejected for this stack (CJK mojibake / not inline).
91ASCII brackets + CP437 `√` stay inline in the native font. `${Name}` and `$[Name]` cannot share a name.
88
92
89Parameters work inside any text, and inside barcode/QR/image directives (below).
93Parameters work inside any text, and inside barcode/QR/image directives (below).
90
94
@@ -94,7 +98,7 @@ Parameters work inside any text, and inside barcode/QR/image directives (below).
94Receipt #${DocumentNumber}
98Receipt #${DocumentNumber}
95Date: ${Date}
99Date: ${Date}
96
100
97[x] Paid
101$[Paid] Paid
98[] Pending
102[] Pending
99
103
100Item: ${ItemName} ${LineTotal}
104Item: ${ItemName} ${LineTotal}
@@ -207,27 +211,30 @@ Raster barcodes stretch horizontally to full printable width.
207### Syntax
211### Syntax
208
212
209```
213```
210${ParameterName}
214${ParameterName} # text
215$[ParameterName] # boolean checkbox → [ ] / [√]
211```
216```
212
217
213- **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
218- **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
214- **Case-sensitive:** `${DocNo}` and `${docno}` are different
219- **Case-sensitive:** `${DocNo}` and `${docno}` are different
220- **No mixed types:** the same name must not appear as both `${…}` and `$[…]`
215- **Uniqueness at input:** all occurrences of the same name share one value entered at print time
221- **Uniqueness at input:** all occurrences of the same name share one value entered at print time
216
222
217### Where parameters are allowed
223### Where parameters are allowed
218
224
219| Location | Example |
225| Location | Example |
220|----------|---------|
226|----------|---------|
221| Text | `Order ${OrderId}` |
227| Text | `Order ${OrderId}` / `$[Paid] Paid` |
222| Barcode data | `@barcode CODE128 ${OrderId}` |
228| Barcode data | `@barcode CODE128 ${OrderId}` (`${…}` only) |
223| QR data | `@qr ${VerifyUrl}` |
229| QR data | `@qr ${VerifyUrl}` (`${…}` only) |
224| Image path | `@image ${LogoPath}` |
230| Image path | `@image ${LogoPath}` (`${…}` only) |
225
231
226### Print-time behavior
232### Print-time behavior
227
233
2281. Before print, scan AST for all `${...}` tokens.
2341. Before print, scan AST for all `${…}` and `$[…]` tokens.
2292. Deduplicate by name.
2352. Deduplicate by name (kinds must not conflict — enforced at parse).
2303. Show dialog with one field per unique name (or require CLI `--set`).
2363. Show dialog: text field per `${…}`, checkbox per `$[…]` (or require CLI `--set`).
2374. Bool values: `true`/`false` (also `1`/`0`, `yes`/`no`).
2314. Pre-fill from last print session (in-memory).
2384. Pre-fill from last print session (in-memory).
2325. Substitute into AST, then encode/print.
2395. Substitute into AST, then encode/print.
233
240
@@ -269,7 +276,7 @@ Parse errors include 1-based line and column. Typical causes:
269| `# heading` | Double width/height ON → text → OFF |
276| `# heading` | Double width/height ON → text → OFF |
270| `## heading` | Bold ON → text → OFF |
277| `## heading` | Bold ON → text → OFF |
271| `- item` | ASCII `* ` bullet + hanging wrap |
278| `- item` | ASCII `* ` bullet + hanging wrap |
272| `[]` / `[ ]` / `[x]` | ASCII `[ ]` / `[x]` (CP437-safe, inline) |
279| `[]` / `[ ]` / `[x]` / `$[Name]` | ASCII `[ ]` / `[√]` (CP437-safe, inline) |
273| `:center:` | Justification center |
280| `:center:` | Justification center |
274| `@feed n` / blank line | ESC d n |
281| `@feed n` / blank line | ESC d n |
275| `@cut` | GS V partial cut |
282| `@cut` | GS V partial cut |
docs/HELP-CLI-LINUX.md +3 −2
@@ -19,8 +19,9 @@ posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set Docum
19 19 ## Rules
20 20
21 21 - **`--printer` / `-p`** (required): serial device path (e.g. `/dev/ttyUSB0`, `/dev/ttyACM0`), or another printer id accepted by discovery.
22 - **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` in the template.
23 - If any `${Name}` is missing or empty, the command **fails** and lists missing parameters.
22 - **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
23 - Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24 - If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
24 25 - The GUI is not started when using the `print` subcommand.
25 26
26 27 ## Permissions
@@ -19,8 +19,9 @@ posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set Docum
19## Rules
19## Rules
20
20
21- **`--printer` / `-p`** (required): serial device path (e.g. `/dev/ttyUSB0`, `/dev/ttyACM0`), or another printer id accepted by discovery.
21- **`--printer` / `-p`** (required): serial device path (e.g. `/dev/ttyUSB0`, `/dev/ttyACM0`), or another printer id accepted by discovery.
22- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` in the template.
22- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
23- If any `${Name}` is missing or empty, the command **fails** and lists missing parameters.
23- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
24- The GUI is not started when using the `print` subcommand.
25- The GUI is not started when using the `print` subcommand.
25
26
26## Permissions
27## Permissions
docs/HELP-CLI-WINDOWS.md +3 −2
@@ -19,8 +19,9 @@ posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumbe
19 19 ## Rules
20 20
21 21 - **`--printer` / `-p`** (required): serial port (`COM3`), or a Windows printer queue name for spooler printing.
22 - **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` in the template.
23 - If any `${Name}` is missing or empty, the command **fails** and lists missing parameters.
22 - **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
23 - Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24 - If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
24 25 - The GUI is not started when using the `print` subcommand.
25 26
26 27 ## Examples
@@ -19,8 +19,9 @@ posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumbe
19## Rules
19## Rules
20
20
21- **`--printer` / `-p`** (required): serial port (`COM3`), or a Windows printer queue name for spooler printing.
21- **`--printer` / `-p`** (required): serial port (`COM3`), or a Windows printer queue name for spooler printing.
22- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` in the template.
22- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
23- If any `${Name}` is missing or empty, the command **fails** and lists missing parameters.
23- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
24- The GUI is not started when using the `print` subcommand.
25- The GUI is not started when using the `print` subcommand.
25
26
26## Examples
27## Examples
docs/HELP.md +27 −8
@@ -43,7 +43,7 @@ If the document does not end with `@cut` (ignoring blank lines after it), a red
43 43
44 44 ## Template language
45 45
46 A template is plain text: paragraphs, headings, lists, checkboxes, directives, and `${parameters}`. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
46 A template is plain text: paragraphs, headings, lists, checkboxes, `${text}` / `$[bool]` parameters, and directives. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
47 47
48 48 ### Paragraphs
49 49
@@ -78,24 +78,30 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
78 78
79 79 | Syntax | Effect |
80 80 |--------|--------|
81 | `${Name}` | Parameter (filled at print time) |
81 | `${Name}` | Text parameter (filled at print time) |
82 | `$[Name]` | Checkbox parameter → `[ ]` or `[√]` |
83
84 `${Name}` and `$[Name]` must not share the same name.
82 85
83 86 ### Checkboxes
84 87
85 Inline checkboxes use ASCII so they print correctly on CP437 ESC/POS printers (same font as surrounding text):
88 Inline checkboxes use ASCII brackets plus a CP437 check mark so they print in the native font:
86 89
87 90 | Syntax | Result |
88 91 |--------|--------|
89 92 | `[]` or `[ ]` | `[ ]` |
90 | `[x]` or `[X]` | `[x]` |
93 | `[x]`, `[X]`, or `[√]` | `[√]` (CP437 `√`) |
91 94
92 95 ```markdown
93 96 [] Unchecked
94 97 [ ] Also unchecked
95 98 [x] Done
99 $[Paid]
96 100 ```
97 101
98 Unicode ballot boxes and custom bit-images are not used: UTF-8 becomes garbage/CJK on CP437 printers, and ESC `*` / ESC `&` graphics often leave the text line on micro-printers.
102 `$[Paid]` is a **parameter**: in the Print dialog it is a true/false checkbox; on the receipt it becomes `[ ]` or `[√]`. CLI: `--set Paid=true`.
103
104 Unicode ballot boxes are not used (they become CJK garbage on CP437 printers).
99 105
100 106 ### Horizontal rule
101 107
@@ -209,10 +215,23 @@ Blank lines in the editor also feed one line (same as `@feed 1`).
209 215
210 216 ## Parameters
211 217
212 `${ParameterName}` in text, barcode data, QR data, or image paths.
218 | Form | Type | Print dialog | CLI |
219 |------|------|--------------|-----|
220 | `${Name}` | text | text field | `--set Name=Value` |
221 | `$[Name]` | bool | checkbox | `--set Name=true` / `false` (also `1`/`0`, `yes`/`no`) |
222
223 - Same name must not appear as both `${…}` and `$[…]`.
224 - GUI and CLI require **every** parameter; bools default to unchecked (`false`) in the dialog.
225 - Usable in text; `${…}` also in barcode/QR/image paths (`$[…]` is text-inline only).
213 226
214 - Same name → **one input** at print time (GUI or CLI).
215 - CLI requires **every** parameter via `--set Name=Value`.
227 ```markdown
228 # ${StoreName}
229
230 $[Paid] Paid in full
231 [] Pending review
232
233 Receipt: ${DocumentNumber}
234 ```
216 235
217 236 ---
218 237
@@ -43,7 +43,7 @@ If the document does not end with `@cut` (ignoring blank lines after it), a red
43
43
44## Template language
44## Template language
45
45
46A template is plain text: paragraphs, headings, lists, checkboxes, directives, and `${parameters}`. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
46A template is plain text: paragraphs, headings, lists, checkboxes, `${text}` / `$[bool]` parameters, and directives. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
47
47
48### Paragraphs
48### Paragraphs
49
49
@@ -78,24 +78,30 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
78
78
79| Syntax | Effect |
79| Syntax | Effect |
80|--------|--------|
80|--------|--------|
81| `${Name}` | Parameter (filled at print time) |
81| `${Name}` | Text parameter (filled at print time) |
82| `$[Name]` | Checkbox parameter → `[ ]` or `[√]` |
83
84`${Name}` and `$[Name]` must not share the same name.
82
85
83### Checkboxes
86### Checkboxes
84
87
85Inline checkboxes use ASCII so they print correctly on CP437 ESC/POS printers (same font as surrounding text):
88Inline checkboxes use ASCII brackets plus a CP437 check mark so they print in the native font:
86
89
87| Syntax | Result |
90| Syntax | Result |
88|--------|--------|
91|--------|--------|
89| `[]` or `[ ]` | `[ ]` |
92| `[]` or `[ ]` | `[ ]` |
90| `[x]` or `[X]` | `[x]` |
93| `[x]`, `[X]`, or `[√]` | `[√]` (CP437 `√`) |
91
94
92```markdown
95```markdown
93[] Unchecked
96[] Unchecked
94[ ] Also unchecked
97[ ] Also unchecked
95[x] Done
98[x] Done
99$[Paid]
96```
100```
97
101
98Unicode ballot boxes and custom bit-images are not used: UTF-8 becomes garbage/CJK on CP437 printers, and ESC `*` / ESC `&` graphics often leave the text line on micro-printers.
102`$[Paid]` is a **parameter**: in the Print dialog it is a true/false checkbox; on the receipt it becomes `[ ]` or `[√]`. CLI: `--set Paid=true`.
103
104Unicode ballot boxes are not used (they become CJK garbage on CP437 printers).
99
105
100### Horizontal rule
106### Horizontal rule
101
107
@@ -209,10 +215,23 @@ Blank lines in the editor also feed one line (same as `@feed 1`).
209
215
210## Parameters
216## Parameters
211
217
212`${ParameterName}` in text, barcode data, QR data, or image paths.
218| Form | Type | Print dialog | CLI |
219|------|------|--------------|-----|
220| `${Name}` | text | text field | `--set Name=Value` |
221| `$[Name]` | bool | checkbox | `--set Name=true` / `false` (also `1`/`0`, `yes`/`no`) |
222
223- Same name must not appear as both `${…}` and `$[…]`.
224- GUI and CLI require **every** parameter; bools default to unchecked (`false`) in the dialog.
225- Usable in text; `${…}` also in barcode/QR/image paths (`$[…]` is text-inline only).
213
226
214- Same name → **one input** at print time (GUI or CLI).
227```markdown
215- CLI requires **every** parameter via `--set Name=Value`.
228# ${StoreName}
229
230$[Paid] Paid in full
231[] Pending review
232
233Receipt: ${DocumentNumber}
234```
216
235
217---
236---
218
237
docs/PRINTING.md +3 −2
@@ -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 | ASCII `[ ]` / `[x]` | `[]` / `[ ]` / `[x]` — CP437-safe, same font as text |
32 | Inline checkbox | ASCII `[ ]` / `[√]` (CP437 `0xFB`) | `[]` / `[x]` / `$[Name]` — same font as text |
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 |
@@ -116,7 +116,8 @@ Document body (DSL)
116 116 parse() → Document
117 117 │
118 118 ▼
119 collect_parameter_names() → UI dialog / CLI --set
119 collect_parameters() → UI dialog / CLI --set
120 │ (${Name} text fields, $[Name] checkboxes)
120 121 │
121 122 ▼
122 123 substitute_document()
@@ -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 | ASCII `[ ]` / `[x]` | `[]` / `[ ]` / `[x]` — CP437-safe, same font as text |
32| Inline checkbox | ASCII `[ ]` / `[√]` (CP437 `0xFB`) | `[]` / `[x]` / `$[Name]` — same font as text |
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 |
@@ -116,7 +116,8 @@ Document body (DSL)
116 parse() → Document
116 parse() → Document
117 │
117 │
118 ▼
118 ▼
119 collect_parameter_names() → UI dialog / CLI --set
119 collect_parameters() → UI dialog / CLI --set
120 │ (${Name} text fields, $[Name] checkboxes)
120 │
121 │
121 ▼
122 ▼
122 substitute_document()
123 substitute_document()
examples/checkbox-test.pos +1 −1
@@ -4,5 +4,5 @@
4 4 "title": "Checkbox glyph test",
5 5 "page_width_mm": 58
6 6 },
7 "body": "# Checkbox test\n\n[] empty brackets\n[ ] space brackets\n[x] checked lowercase\n\n@feed 2\n@cut\n"
7 "body": "# Checkbox test\n\n[] empty brackets\n[ ] space brackets\n[x] checked lowercase\n$[Paid] from parameter\n\n@feed 2\n@cut\n"
8 8 }
@@ -4,5 +4,5 @@
4 "title": "Checkbox glyph test",
4 "title": "Checkbox glyph test",
5 "page_width_mm": 58
5 "page_width_mm": 58
6 },
6 },
7 "body": "# Checkbox test\n\n[] empty brackets\n[ ] space brackets\n[x] checked lowercase\n\n@feed 2\n@cut\n"
7 "body": "# Checkbox test\n\n[] empty brackets\n[ ] space brackets\n[x] checked lowercase\n$[Paid] from parameter\n\n@feed 2\n@cut\n"
8}
8}
examples/print_checkbox_test.rs +4 −2
@@ -19,7 +19,9 @@ fn main() {
19 19
20 20 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/checkbox-test.pos");
21 21 let file = PosFile::load_from_path(&path).expect("load checkbox-test.pos");
22 let bytes = encode_pos_file(&file, path.parent(), &HashMap::new()).expect("encode");
22 let mut params = HashMap::new();
23 params.insert("Paid".into(), "true".into());
24 let bytes = encode_pos_file(&file, path.parent(), &params).expect("encode");
23 25
24 26 // Prefer a non-spooler device if present (closer to ESC/POS raw), else first entry.
25 27 let device = printers
@@ -30,5 +32,5 @@ fn main() {
30 32 println!("Printing checkbox test to: {}", device.display_name);
31 33 let mut transport = open_printer(&device.target).expect("open printer");
32 34 print_bytes(&mut transport, &bytes).expect("print");
33 println!("OK — check paper for ASCII [ ] / [ ] / [x] inline with normal text");
35 println!("OK — check paper for [ ] / [ ] / [√] / [√] (last from $[Paid]=true)");
34 36 }
@@ -19,7 +19,9 @@ fn main() {
19
19
20 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/checkbox-test.pos");
20 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/checkbox-test.pos");
21 let file = PosFile::load_from_path(&path).expect("load checkbox-test.pos");
21 let file = PosFile::load_from_path(&path).expect("load checkbox-test.pos");
22 let bytes = encode_pos_file(&file, path.parent(), &HashMap::new()).expect("encode");
22 let mut params = HashMap::new();
23 params.insert("Paid".into(), "true".into());
24 let bytes = encode_pos_file(&file, path.parent(), &params).expect("encode");
23
25
24 // Prefer a non-spooler device if present (closer to ESC/POS raw), else first entry.
26 // Prefer a non-spooler device if present (closer to ESC/POS raw), else first entry.
25 let device = printers
27 let device = printers
@@ -30,5 +32,5 @@ fn main() {
30 println!("Printing checkbox test to: {}", device.display_name);
32 println!("Printing checkbox test to: {}", device.display_name);
31 let mut transport = open_printer(&device.target).expect("open printer");
33 let mut transport = open_printer(&device.target).expect("open printer");
32 print_bytes(&mut transport, &bytes).expect("print");
34 print_bytes(&mut transport, &bytes).expect("print");
33 println!("OK — check paper for ASCII [ ] / [ ] / [x] inline with normal text");
35 println!("OK — check paper for [ ] / [ ] / [√] / [√] (last from $[Paid]=true)");
34}
36}
src/cli.rs +2 −1
@@ -36,7 +36,8 @@ pub enum Commands {
36 36 /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux)
37 37 #[arg(short, long)]
38 38 printer: String,
39 /// Template parameter as NAME=VALUE (repeat for each ${Name} in the template)
39 /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`;
40 /// checkbox params accept true/false)
40 41 #[arg(long = "set", value_name = "NAME=VALUE")]
41 42 set: Vec<String>,
42 43 },
@@ -36,7 +36,8 @@ pub enum Commands {
36 /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux)
36 /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux)
37 #[arg(short, long)]
37 #[arg(short, long)]
38 printer: String,
38 printer: String,
39 /// Template parameter as NAME=VALUE (repeat for each ${Name} in the template)
39 /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`;
40 /// checkbox params accept true/false)
40 #[arg(long = "set", value_name = "NAME=VALUE")]
41 #[arg(long = "set", value_name = "NAME=VALUE")]
41 set: Vec<String>,
42 set: Vec<String>,
42 },
43 },
src/dsl/mod.rs +6 −6
@@ -134,20 +134,20 @@ pub enum QrEcc {
134 134 #[derive(Debug, Clone, PartialEq, Eq)]
135 135 pub enum Inline {
136 136 Text(String),
137 /// Text parameter: `${Name}`.
137 138 Param(String),
138 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` (checked).
139 /// Boolean checkbox parameter: `$[Name]` → `[ ]` or `[√]` at print time.
140 CheckboxParam(String),
141 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` / `[√]` (checked).
139 142 Checkbox {
140 143 checked: bool,
141 144 },
142 145 }
143 146
144 /// ASCII checkbox glyphs — CP437-safe so they stay inline with the native font.
145 ///
146 /// True ballot-box Unicode (☐/🗹) is misread as multi-byte CJK on this printer;
147 /// ESC `*` / ESC `&` graphics do not stay in the text line on many micro-printers.
147 /// Checkbox glyphs for preview / wrap width. Print maps `√` (U+221A) to CP437 `0xFB`.
148 148 pub fn checkbox_glyph(checked: bool) -> &'static str {
149 149 if checked {
150 "[x]"
150 "[\u{221A}]" // √ — CP437 byte 0xFB when encoded for the printer
151 151 } else {
152 152 "[ ]"
153 153 }
@@ -134,20 +134,20 @@ pub enum QrEcc {
134#[derive(Debug, Clone, PartialEq, Eq)]
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub enum Inline {
135pub enum Inline {
136 Text(String),
136 Text(String),
137 /// Text parameter: `${Name}`.
137 Param(String),
138 Param(String),
138 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` (checked).
139 /// Boolean checkbox parameter: `$[Name]` → `[ ]` or `[√]` at print time.
140 CheckboxParam(String),
141 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` / `[√]` (checked).
139 Checkbox {
142 Checkbox {
140 checked: bool,
143 checked: bool,
141 },
144 },
142}
145}
143
146
144/// ASCII checkbox glyphs — CP437-safe so they stay inline with the native font.
147/// Checkbox glyphs for preview / wrap width. Print maps `√` (U+221A) to CP437 `0xFB`.
145///
146/// True ballot-box Unicode (☐/🗹) is misread as multi-byte CJK on this printer;
147/// ESC `*` / ESC `&` graphics do not stay in the text line on many micro-printers.
148pub fn checkbox_glyph(checked: bool) -> &'static str {
148pub fn checkbox_glyph(checked: bool) -> &'static str {
149 if checked {
149 if checked {
150 "[x]"
150 "[\u{221A}]" // √ — CP437 byte 0xFB when encoded for the printer
151 } else {
151 } else {
152 "[ ]"
152 "[ ]"
153 }
153 }
src/dsl/parser.rs +155 −23
@@ -113,7 +113,91 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
113 113 }
114 114 }
115 115
116 Ok(Document { blocks })
116 let document = Document { blocks };
117 validate_param_kinds(&document)?;
118 Ok(document)
119 }
120
121 fn validate_param_kinds(document: &Document) -> Result<(), ParseError> {
122 use std::collections::BTreeSet;
123
124 let mut text_names = BTreeSet::new();
125 let mut bool_names = BTreeSet::new();
126 for block in &document.blocks {
127 collect_param_kinds_from_block(block, &mut text_names, &mut bool_names);
128 }
129 for name in text_names.intersection(&bool_names) {
130 return Err(err(
131 1,
132 1,
133 format!(
134 "parameter '{name}' cannot be both ${{{name}}} (text) and $[{name}] (checkbox)"
135 ),
136 ));
137 }
138 Ok(())
139 }
140
141 fn collect_param_kinds_from_block(
142 block: &Block,
143 text_names: &mut std::collections::BTreeSet<String>,
144 bool_names: &mut std::collections::BTreeSet<String>,
145 ) {
146 match block {
147 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
148 for inline in inlines {
149 match inline {
150 Inline::Param(name) => {
151 text_names.insert(name.clone());
152 }
153 Inline::CheckboxParam(name) => {
154 bool_names.insert(name.clone());
155 }
156 _ => {}
157 }
158 }
159 }
160 Block::List { items, .. } => {
161 for item in items {
162 for inline in item {
163 match inline {
164 Inline::Param(name) => {
165 text_names.insert(name.clone());
166 }
167 Inline::CheckboxParam(name) => {
168 bool_names.insert(name.clone());
169 }
170 _ => {}
171 }
172 }
173 }
174 }
175 Block::Image { path, .. } => collect_text_params_from_raw(path, text_names),
176 Block::Barcode { data, .. } | Block::Qr { data, .. } => {
177 collect_text_params_from_raw(data, text_names);
178 }
179 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
180 }
181 }
182
183 fn collect_text_params_from_raw(text: &str, text_names: &mut std::collections::BTreeSet<String>) {
184 let chars: Vec<char> = text.chars().collect();
185 let mut i = 0;
186 while i < chars.len() {
187 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
188 let start = i + 2;
189 let mut j = start;
190 while j < chars.len() && chars[j] != '}' {
191 j += 1;
192 }
193 if j < chars.len() {
194 text_names.insert(chars[start..j].iter().collect());
195 i = j + 1;
196 continue;
197 }
198 }
199 i += 1;
200 }
117 201 }
118 202
119 203 /// True when the last substantive block is `@cut` (trailing blank-line feeds are ignored).
@@ -542,26 +626,52 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
542 626 let mut i = 0usize;
543 627 let chars: Vec<char> = input.chars().collect();
544 628 while i < chars.len() {
545 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
546 let start = i + 2;
547 let mut j = start;
548 while j < chars.len() && chars[j] != '}' {
549 j += 1;
550 }
551 if j >= chars.len() {
552 return Err(err(line, col + i, "unclosed parameter ${...}"));
553 }
554 let name: String = chars[start..j].iter().collect();
555 if !is_valid_param_name(&name) {
556 return Err(err(
557 line,
558 col + i,
559 format!("invalid parameter name '{name}'"),
560 ));
629 if chars[i] == '$' && i + 1 < chars.len() {
630 match chars[i + 1] {
631 '{' => {
632 let start = i + 2;
633 let mut j = start;
634 while j < chars.len() && chars[j] != '}' {
635 j += 1;
636 }
637 if j >= chars.len() {
638 return Err(err(line, col + i, "unclosed parameter ${...}"));
639 }
640 let name: String = chars[start..j].iter().collect();
641 if !is_valid_param_name(&name) {
642 return Err(err(
643 line,
644 col + i,
645 format!("invalid parameter name '{name}'"),
646 ));
647 }
648 out.push(Inline::Param(name));
649 i = j + 1;
650 continue;
651 }
652 '[' => {
653 let start = i + 2;
654 let mut j = start;
655 while j < chars.len() && chars[j] != ']' {
656 j += 1;
657 }
658 if j >= chars.len() {
659 return Err(err(line, col + i, "unclosed parameter $[...]"));
660 }
661 let name: String = chars[start..j].iter().collect();
662 if !is_valid_param_name(&name) {
663 return Err(err(
664 line,
665 col + i,
666 format!("invalid checkbox parameter name '{name}'"),
667 ));
668 }
669 out.push(Inline::CheckboxParam(name));
670 i = j + 1;
671 continue;
672 }
673 _ => {}
561 674 }
562 out.push(Inline::Param(name));
563 i = j + 1;
564 continue;
565 675 }
566 676 if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
567 677 out.push(Inline::Checkbox { checked });
@@ -585,7 +695,7 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
585 695 Ok(out)
586 696 }
587 697
588 /// Parse `[]`, `[ ]`, `[x]`, or `[X]` at the start of `chars`.
698 /// Parse `[]`, `[ ]`, `[x]`, `[X]`, or `[√]` at the start of `chars`.
589 699 /// Returns `(checked, chars_consumed)`.
590 700 fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
591 701 if chars.first() != Some(&'[') {
@@ -594,7 +704,7 @@ fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
594 704 match chars.get(1) {
595 705 Some(']') => Some((false, 2)),
596 706 Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
597 Some('x' | 'X') if chars.get(2) == Some(&']') => Some((true, 3)),
707 Some('x' | 'X' | '\u{221A}') if chars.get(2) == Some(&']') => Some((true, 3)),
598 708 _ => None,
599 709 }
600 710 }
@@ -625,7 +735,7 @@ mod tests {
625 735 let mut out = String::new();
626 736 for inline in inlines {
627 737 match inline {
628 Inline::Text(t) | Inline::Param(t) => out.push_str(t),
738 Inline::Text(t) | Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t),
629 739 Inline::Checkbox { checked } => {
630 740 out.push_str(crate::dsl::checkbox_glyph(*checked));
631 741 }
@@ -651,6 +761,28 @@ mod tests {
651 761 assert_eq!(glyphs, vec![false, false, true, true]);
652 762 }
653 763
764 #[test]
765 fn parses_checkbox_param() {
766 let doc = parse("$[Paid] ok").unwrap();
767 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
768 panic!("expected paragraph");
769 };
770 assert!(matches!(
771 &inlines[0],
772 Inline::CheckboxParam(name) if name == "Paid"
773 ));
774 }
775
776 #[test]
777 fn rejects_same_name_as_text_and_checkbox_param() {
778 let err = parse("${Paid}\n$[Paid]").unwrap_err();
779 assert!(
780 err.message.contains("cannot be both"),
781 "unexpected error: {}",
782 err.message
783 );
784 }
785
654 786 #[test]
655 787 fn parses_heading_and_paragraph() {
656 788 let doc = parse("# Store\nHello world").unwrap();
@@ -113,7 +113,91 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
113 }
113 }
114 }
114 }
115
115
116 Ok(Document { blocks })
116 let document = Document { blocks };
117 validate_param_kinds(&document)?;
118 Ok(document)
119}
120
121fn validate_param_kinds(document: &Document) -> Result<(), ParseError> {
122 use std::collections::BTreeSet;
123
124 let mut text_names = BTreeSet::new();
125 let mut bool_names = BTreeSet::new();
126 for block in &document.blocks {
127 collect_param_kinds_from_block(block, &mut text_names, &mut bool_names);
128 }
129 for name in text_names.intersection(&bool_names) {
130 return Err(err(
131 1,
132 1,
133 format!(
134 "parameter '{name}' cannot be both ${{{name}}} (text) and $[{name}] (checkbox)"
135 ),
136 ));
137 }
138 Ok(())
139}
140
141fn collect_param_kinds_from_block(
142 block: &Block,
143 text_names: &mut std::collections::BTreeSet<String>,
144 bool_names: &mut std::collections::BTreeSet<String>,
145) {
146 match block {
147 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
148 for inline in inlines {
149 match inline {
150 Inline::Param(name) => {
151 text_names.insert(name.clone());
152 }
153 Inline::CheckboxParam(name) => {
154 bool_names.insert(name.clone());
155 }
156 _ => {}
157 }
158 }
159 }
160 Block::List { items, .. } => {
161 for item in items {
162 for inline in item {
163 match inline {
164 Inline::Param(name) => {
165 text_names.insert(name.clone());
166 }
167 Inline::CheckboxParam(name) => {
168 bool_names.insert(name.clone());
169 }
170 _ => {}
171 }
172 }
173 }
174 }
175 Block::Image { path, .. } => collect_text_params_from_raw(path, text_names),
176 Block::Barcode { data, .. } | Block::Qr { data, .. } => {
177 collect_text_params_from_raw(data, text_names);
178 }
179 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
180 }
181}
182
183fn collect_text_params_from_raw(text: &str, text_names: &mut std::collections::BTreeSet<String>) {
184 let chars: Vec<char> = text.chars().collect();
185 let mut i = 0;
186 while i < chars.len() {
187 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
188 let start = i + 2;
189 let mut j = start;
190 while j < chars.len() && chars[j] != '}' {
191 j += 1;
192 }
193 if j < chars.len() {
194 text_names.insert(chars[start..j].iter().collect());
195 i = j + 1;
196 continue;
197 }
198 }
199 i += 1;
200 }
117}
201}
118
202
119/// True when the last substantive block is `@cut` (trailing blank-line feeds are ignored).
203/// True when the last substantive block is `@cut` (trailing blank-line feeds are ignored).
@@ -542,26 +626,52 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
542 let mut i = 0usize;
626 let mut i = 0usize;
543 let chars: Vec<char> = input.chars().collect();
627 let chars: Vec<char> = input.chars().collect();
544 while i < chars.len() {
628 while i < chars.len() {
545 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
629 if chars[i] == '$' && i + 1 < chars.len() {
546 let start = i + 2;
630 match chars[i + 1] {
547 let mut j = start;
631 '{' => {
548 while j < chars.len() && chars[j] != '}' {
632 let start = i + 2;
549 j += 1;
633 let mut j = start;
550 }
634 while j < chars.len() && chars[j] != '}' {
551 if j >= chars.len() {
635 j += 1;
552 return Err(err(line, col + i, "unclosed parameter ${...}"));
636 }
553 }
637 if j >= chars.len() {
554 let name: String = chars[start..j].iter().collect();
638 return Err(err(line, col + i, "unclosed parameter ${...}"));
555 if !is_valid_param_name(&name) {
639 }
556 return Err(err(
640 let name: String = chars[start..j].iter().collect();
557 line,
641 if !is_valid_param_name(&name) {
558 col + i,
642 return Err(err(
559 format!("invalid parameter name '{name}'"),
643 line,
560 ));
644 col + i,
645 format!("invalid parameter name '{name}'"),
646 ));
647 }
648 out.push(Inline::Param(name));
649 i = j + 1;
650 continue;
651 }
652 '[' => {
653 let start = i + 2;
654 let mut j = start;
655 while j < chars.len() && chars[j] != ']' {
656 j += 1;
657 }
658 if j >= chars.len() {
659 return Err(err(line, col + i, "unclosed parameter $[...]"));
660 }
661 let name: String = chars[start..j].iter().collect();
662 if !is_valid_param_name(&name) {
663 return Err(err(
664 line,
665 col + i,
666 format!("invalid checkbox parameter name '{name}'"),
667 ));
668 }
669 out.push(Inline::CheckboxParam(name));
670 i = j + 1;
671 continue;
672 }
673 _ => {}
561 }
674 }
562 out.push(Inline::Param(name));
563 i = j + 1;
564 continue;
565 }
675 }
566 if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
676 if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
567 out.push(Inline::Checkbox { checked });
677 out.push(Inline::Checkbox { checked });
@@ -585,7 +695,7 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
585 Ok(out)
695 Ok(out)
586}
696}
587
697
588/// Parse `[]`, `[ ]`, `[x]`, or `[X]` at the start of `chars`.
698/// Parse `[]`, `[ ]`, `[x]`, `[X]`, or `[√]` at the start of `chars`.
589/// Returns `(checked, chars_consumed)`.
699/// Returns `(checked, chars_consumed)`.
590fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
700fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
591 if chars.first() != Some(&'[') {
701 if chars.first() != Some(&'[') {
@@ -594,7 +704,7 @@ fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
594 match chars.get(1) {
704 match chars.get(1) {
595 Some(']') => Some((false, 2)),
705 Some(']') => Some((false, 2)),
596 Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
706 Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
597 Some('x' | 'X') if chars.get(2) == Some(&']') => Some((true, 3)),
707 Some('x' | 'X' | '\u{221A}') if chars.get(2) == Some(&']') => Some((true, 3)),
598 _ => None,
708 _ => None,
599 }
709 }
600}
710}
@@ -625,7 +735,7 @@ mod tests {
625 let mut out = String::new();
735 let mut out = String::new();
626 for inline in inlines {
736 for inline in inlines {
627 match inline {
737 match inline {
628 Inline::Text(t) | Inline::Param(t) => out.push_str(t),
738 Inline::Text(t) | Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t),
629 Inline::Checkbox { checked } => {
739 Inline::Checkbox { checked } => {
630 out.push_str(crate::dsl::checkbox_glyph(*checked));
740 out.push_str(crate::dsl::checkbox_glyph(*checked));
631 }
741 }
@@ -651,6 +761,28 @@ mod tests {
651 assert_eq!(glyphs, vec![false, false, true, true]);
761 assert_eq!(glyphs, vec![false, false, true, true]);
652 }
762 }
653
763
764 #[test]
765 fn parses_checkbox_param() {
766 let doc = parse("$[Paid] ok").unwrap();
767 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
768 panic!("expected paragraph");
769 };
770 assert!(matches!(
771 &inlines[0],
772 Inline::CheckboxParam(name) if name == "Paid"
773 ));
774 }
775
776 #[test]
777 fn rejects_same_name_as_text_and_checkbox_param() {
778 let err = parse("${Paid}\n$[Paid]").unwrap_err();
779 assert!(
780 err.message.contains("cannot be both"),
781 "unexpected error: {}",
782 err.message
783 );
784 }
785
654 #[test]
786 #[test]
655 fn parses_heading_and_paragraph() {
787 fn parses_heading_and_paragraph() {
656 let doc = parse("# Store\nHello world").unwrap();
788 let doc = parse("# Store\nHello world").unwrap();
src/editor_assist.rs +27 −9
@@ -158,10 +158,18 @@ pub fn date_time_insert_options() -> Vec<InsertOption> {
158 158 pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
159 159 use std::collections::BTreeSet;
160 160
161 let mut names = BTreeSet::new();
161 let mut text_names = BTreeSet::new();
162 let mut bool_names = BTreeSet::new();
162 163 if let Ok(doc) = crate::dsl::parse(source) {
163 for name in crate::params::collect_parameter_names(&doc) {
164 names.insert(name);
164 for spec in crate::params::collect_parameters(&doc) {
165 match spec.kind {
166 crate::params::ParamKind::Text => {
167 text_names.insert(spec.name);
168 }
169 crate::params::ParamKind::Bool => {
170 bool_names.insert(spec.name);
171 }
172 }
165 173 }
166 174 }
167 175 for preset in [
@@ -174,16 +182,26 @@ pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
174 182 "Date",
175 183 "Time",
176 184 ] {
177 names.insert(preset.to_string());
185 text_names.insert(preset.to_string());
186 }
187 for preset in ["Paid", "Done", "Checked"] {
188 bool_names.insert(preset.to_string());
178 189 }
179 190
180 names
181 .into_iter()
182 .map(|name| InsertOption {
191 let mut out = Vec::new();
192 for name in text_names {
193 out.push(InsertOption {
183 194 label: format!("${{{name}}}"),
184 195 snippet: format!("${{{name}}}"),
185 })
186 .collect()
196 });
197 }
198 for name in bool_names {
199 out.push(InsertOption {
200 label: format!("$[{name}]"),
201 snippet: format!("$[{name}]"),
202 });
203 }
204 out
187 205 }
188 206
189 207 /// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
@@ -158,10 +158,18 @@ pub fn date_time_insert_options() -> Vec<InsertOption> {
158pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
158pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
159 use std::collections::BTreeSet;
159 use std::collections::BTreeSet;
160
160
161 let mut names = BTreeSet::new();
161 let mut text_names = BTreeSet::new();
162 let mut bool_names = BTreeSet::new();
162 if let Ok(doc) = crate::dsl::parse(source) {
163 if let Ok(doc) = crate::dsl::parse(source) {
163 for name in crate::params::collect_parameter_names(&doc) {
164 for spec in crate::params::collect_parameters(&doc) {
164 names.insert(name);
165 match spec.kind {
166 crate::params::ParamKind::Text => {
167 text_names.insert(spec.name);
168 }
169 crate::params::ParamKind::Bool => {
170 bool_names.insert(spec.name);
171 }
172 }
165 }
173 }
166 }
174 }
167 for preset in [
175 for preset in [
@@ -174,16 +182,26 @@ pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
174 "Date",
182 "Date",
175 "Time",
183 "Time",
176 ] {
184 ] {
177 names.insert(preset.to_string());
185 text_names.insert(preset.to_string());
186 }
187 for preset in ["Paid", "Done", "Checked"] {
188 bool_names.insert(preset.to_string());
178 }
189 }
179
190
180 names
191 let mut out = Vec::new();
181 .into_iter()
192 for name in text_names {
182 .map(|name| InsertOption {
193 out.push(InsertOption {
183 label: format!("${{{name}}}"),
194 label: format!("${{{name}}}"),
184 snippet: format!("${{{name}}}"),
195 snippet: format!("${{{name}}}"),
185 })
196 });
186 .collect()
197 }
198 for name in bool_names {
199 out.push(InsertOption {
200 label: format!("$[{name}]"),
201 snippet: format!("$[{name}]"),
202 });
203 }
204 out
187}
205}
188
206
189/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
207/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
src/escpos.rs +22 −6
@@ -178,10 +178,21 @@ impl EscPosEncoder {
178 178 }
179 179
180 180 fn writeln(&mut self, text: &str) {
181 self.buffer.extend_from_slice(text.as_bytes());
181 self.push_cp437(text);
182 182 self.buffer.push(b'\n');
183 183 }
184 184
185 /// Map text to CP437 bytes. ASCII passes through; `√` (U+221A) → `0xFB`.
186 fn push_cp437(&mut self, text: &str) {
187 for ch in text.chars() {
188 match ch {
189 '\u{221A}' => self.buffer.push(0xFB),
190 c if c.is_ascii() => self.buffer.push(c as u8),
191 _ => self.buffer.push(b'?'),
192 }
193 }
194 }
195
185 196 fn feed(&mut self, lines: u8) {
186 197 if lines == 0 {
187 198 return;
@@ -353,7 +364,7 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
353 364 for inline in inlines {
354 365 match inline {
355 366 Inline::Text(t) => out.push_str(t),
356 Inline::Param(t) => out.push_str(t),
367 Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t),
357 368 Inline::Checkbox { checked } => out.push_str(crate::dsl::checkbox_glyph(*checked)),
358 369 }
359 370 }
@@ -399,14 +410,19 @@ mod tests {
399 410 }
400 411
401 412 #[test]
402 fn encodes_inline_checkboxes_as_ascii() {
413 fn encodes_inline_checkboxes_as_ascii_with_cp437_check() {
403 414 let doc = parse("[] hello [x]").unwrap();
404 415 let mut enc = EscPosEncoder::new(PosMetadata::default());
405 416 let bytes = enc.encode_document(&doc).unwrap();
406 let text = String::from_utf8_lossy(bytes);
417 // Empty: "[ ] hello " then checked "[√]" as '[' 0xFB ']'
418 assert!(bytes.windows(9).any(|w| w == b"[ ] hello"));
419 assert!(
420 bytes.windows(3).any(|w| w == [b'[', 0xFB, b']']),
421 "checked glyph should use CP437 sqrt byte 0xFB"
422 );
407 423 assert!(
408 text.contains("[ ] hello [x]\n"),
409 "expected ASCII checkbox glyphs inline, got: {text:?}"
424 !bytes.windows(3).any(|w| w == b"[x]"),
425 "should not emit ASCII x for checked boxes"
410 426 );
411 427 }
412 428
@@ -178,10 +178,21 @@ impl EscPosEncoder {
178 }
178 }
179
179
180 fn writeln(&mut self, text: &str) {
180 fn writeln(&mut self, text: &str) {
181 self.buffer.extend_from_slice(text.as_bytes());
181 self.push_cp437(text);
182 self.buffer.push(b'\n');
182 self.buffer.push(b'\n');
183 }
183 }
184
184
185 /// Map text to CP437 bytes. ASCII passes through; `√` (U+221A) → `0xFB`.
186 fn push_cp437(&mut self, text: &str) {
187 for ch in text.chars() {
188 match ch {
189 '\u{221A}' => self.buffer.push(0xFB),
190 c if c.is_ascii() => self.buffer.push(c as u8),
191 _ => self.buffer.push(b'?'),
192 }
193 }
194 }
195
185 fn feed(&mut self, lines: u8) {
196 fn feed(&mut self, lines: u8) {
186 if lines == 0 {
197 if lines == 0 {
187 return;
198 return;
@@ -353,7 +364,7 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
353 for inline in inlines {
364 for inline in inlines {
354 match inline {
365 match inline {
355 Inline::Text(t) => out.push_str(t),
366 Inline::Text(t) => out.push_str(t),
356 Inline::Param(t) => out.push_str(t),
367 Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t),
357 Inline::Checkbox { checked } => out.push_str(crate::dsl::checkbox_glyph(*checked)),
368 Inline::Checkbox { checked } => out.push_str(crate::dsl::checkbox_glyph(*checked)),
358 }
369 }
359 }
370 }
@@ -399,14 +410,19 @@ mod tests {
399 }
410 }
400
411
401 #[test]
412 #[test]
402 fn encodes_inline_checkboxes_as_ascii() {
413 fn encodes_inline_checkboxes_as_ascii_with_cp437_check() {
403 let doc = parse("[] hello [x]").unwrap();
414 let doc = parse("[] hello [x]").unwrap();
404 let mut enc = EscPosEncoder::new(PosMetadata::default());
415 let mut enc = EscPosEncoder::new(PosMetadata::default());
405 let bytes = enc.encode_document(&doc).unwrap();
416 let bytes = enc.encode_document(&doc).unwrap();
406 let text = String::from_utf8_lossy(bytes);
417 // Empty: "[ ] hello " then checked "[√]" as '[' 0xFB ']'
418 assert!(bytes.windows(9).any(|w| w == b"[ ] hello"));
419 assert!(
420 bytes.windows(3).any(|w| w == [b'[', 0xFB, b']']),
421 "checked glyph should use CP437 sqrt byte 0xFB"
422 );
407 assert!(
423 assert!(
408 text.contains("[ ] hello [x]\n"),
424 !bytes.windows(3).any(|w| w == b"[x]"),
409 "expected ASCII checkbox glyphs inline, got: {text:?}"
425 "should not emit ASCII x for checked boxes"
410 );
426 );
411 }
427 }
412
428
src/params.rs +145 −16
@@ -1,26 +1,71 @@
1 use std::collections::BTreeSet;
1 use std::collections::BTreeMap;
2 2
3 3 use crate::dsl::{Document, Inline};
4 4
5 pub fn collect_parameter_names(document: &Document) -> Vec<String> {
6 let mut names = BTreeSet::new();
5 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6 pub enum ParamKind {
7 /// `${Name}` — free text
8 Text,
9 /// `$[Name]` — boolean checkbox
10 Bool,
11 }
12
13 #[derive(Debug, Clone, PartialEq, Eq)]
14 pub struct ParamSpec {
15 pub name: String,
16 pub kind: ParamKind,
17 }
18
19 pub fn collect_parameters(document: &Document) -> Vec<ParamSpec> {
20 let mut kinds: BTreeMap<String, ParamKind> = BTreeMap::new();
7 21 for block in &document.blocks {
8 collect_from_block(block, &mut names);
22 collect_kinds_from_block(block, &mut kinds);
9 23 }
10 names.into_iter().collect()
24 kinds
25 .into_iter()
26 .map(|(name, kind)| ParamSpec { name, kind })
27 .collect()
11 28 }
12 29
13 pub fn collect_parameter_names_from_source(source: &str) -> Result<Vec<String>, crate::dsl::ParseError> {
30 pub fn collect_parameter_names(document: &Document) -> Vec<String> {
31 collect_parameters(document)
32 .into_iter()
33 .map(|p| p.name)
34 .collect()
35 }
36
37 pub fn collect_parameter_names_from_source(
38 source: &str,
39 ) -> Result<Vec<String>, crate::dsl::ParseError> {
14 40 let doc = crate::dsl::parse(source)?;
15 41 Ok(collect_parameter_names(&doc))
16 42 }
17 43
18 pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap<String, String>) -> Vec<Inline> {
44 /// Parse a checkbox-parameter value from CLI / dialog (`true`/`false`, `1`/`0`, …).
45 pub fn parse_bool_value(raw: &str) -> Option<bool> {
46 match raw.trim().to_ascii_lowercase().as_str() {
47 "true" | "1" | "yes" | "y" | "on" => Some(true),
48 "false" | "0" | "no" | "n" | "off" | "" => Some(false),
49 _ => None,
50 }
51 }
52
53 pub fn substitute_inlines(
54 inlines: &[Inline],
55 values: &std::collections::HashMap<String, String>,
56 ) -> Vec<Inline> {
19 57 inlines
20 58 .iter()
21 59 .map(|inline| match inline {
22 60 Inline::Text(t) => Inline::Text(t.clone()),
23 61 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
62 Inline::CheckboxParam(name) => {
63 let checked = values
64 .get(name)
65 .and_then(|v| parse_bool_value(v))
66 .unwrap_or(false);
67 Inline::Checkbox { checked }
68 }
24 69 Inline::Checkbox { checked } => Inline::Checkbox {
25 70 checked: *checked,
26 71 },
@@ -183,36 +228,42 @@ pub fn substitute_document(
183 228 Document { blocks }
184 229 }
185 230
186 fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
231 fn collect_kinds_from_block(
232 block: &crate::dsl::Block,
233 kinds: &mut BTreeMap<String, ParamKind>,
234 ) {
187 235 use crate::dsl::Block;
188 236
189 237 match block {
190 238 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
191 collect_from_inlines(inlines, names);
239 collect_kinds_from_inlines(inlines, kinds);
192 240 }
193 241 Block::List { items, .. } => {
194 242 for item in items {
195 collect_from_inlines(item, names);
243 collect_kinds_from_inlines(item, kinds);
196 244 }
197 245 }
198 Block::Image { path, .. } => collect_from_raw(path, names),
199 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
246 Block::Image { path, .. } => collect_text_from_raw(path, kinds),
247 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_text_from_raw(data, kinds),
200 248 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
201 249 }
202 250 }
203 251
204 fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
252 fn collect_kinds_from_inlines(inlines: &[Inline], kinds: &mut BTreeMap<String, ParamKind>) {
205 253 for inline in inlines {
206 254 match inline {
207 255 Inline::Param(name) => {
208 names.insert(name.clone());
256 kinds.insert(name.clone(), ParamKind::Text);
257 }
258 Inline::CheckboxParam(name) => {
259 kinds.insert(name.clone(), ParamKind::Bool);
209 260 }
210 261 Inline::Text(_) | Inline::Checkbox { .. } => {}
211 262 }
212 263 }
213 264 }
214 265
215 fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
266 fn collect_text_from_raw(text: &str, kinds: &mut BTreeMap<String, ParamKind>) {
216 267 let chars: Vec<char> = text.chars().collect();
217 268 let mut i = 0;
218 269 while i < chars.len() {
@@ -224,7 +275,7 @@ fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
224 275 }
225 276 if j < chars.len() {
226 277 let name: String = chars[start..j].iter().collect();
227 names.insert(name);
278 kinds.insert(name, ParamKind::Text);
228 279 i = j + 1;
229 280 continue;
230 281 }
@@ -244,6 +295,13 @@ pub fn substitute_inlines_for_preview(
244 295 Inline::Param(name) => {
245 296 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
246 297 }
298 Inline::CheckboxParam(name) => {
299 let checked = values
300 .get(name)
301 .and_then(|v| parse_bool_value(v))
302 .unwrap_or(false);
303 out.push_str(crate::dsl::checkbox_glyph(checked));
304 }
247 305 Inline::Checkbox { checked } => {
248 306 out.push_str(crate::dsl::checkbox_glyph(*checked));
249 307 }
@@ -252,6 +310,27 @@ pub fn substitute_inlines_for_preview(
252 310 out
253 311 }
254 312
313 /// Validate that bool parameters have parseable values when present.
314 pub fn invalid_bool_parameters(
315 document: &Document,
316 values: &std::collections::HashMap<String, String>,
317 ) -> Vec<String> {
318 collect_parameters(document)
319 .into_iter()
320 .filter(|p| p.kind == ParamKind::Bool)
321 .filter_map(|p| {
322 let Some(raw) = values.get(&p.name) else {
323 return None;
324 };
325 if parse_bool_value(raw).is_some() {
326 None
327 } else {
328 Some(p.name)
329 }
330 })
331 .collect()
332 }
333
255 334 #[cfg(test)]
256 335 mod tests {
257 336 use super::*;
@@ -263,6 +342,25 @@ mod tests {
263 342 assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
264 343 }
265 344
345 #[test]
346 fn collects_checkbox_params_as_bool() {
347 let doc = crate::dsl::parse("$[Paid]\n${Name}").unwrap();
348 let params = collect_parameters(&doc);
349 assert_eq!(
350 params,
351 vec![
352 ParamSpec {
353 name: "Name".into(),
354 kind: ParamKind::Text,
355 },
356 ParamSpec {
357 name: "Paid".into(),
358 kind: ParamKind::Bool,
359 },
360 ]
361 );
362 }
363
266 364 #[test]
267 365 fn preview_substitutes_inlines() {
268 366 let doc = crate::dsl::parse("Hello ${Name}").unwrap();
@@ -277,6 +375,28 @@ mod tests {
277 375 );
278 376 }
279 377
378 #[test]
379 fn substitutes_checkbox_param_to_glyph() {
380 let doc = crate::dsl::parse("$[Paid] done").unwrap();
381 let mut values = HashMap::new();
382 values.insert("Paid".into(), "true".into());
383 let sub = substitute_document(&doc, &values);
384 let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
385 panic!();
386 };
387 assert!(matches!(
388 &inlines[0],
389 Inline::Checkbox { checked: true }
390 ));
391 assert_eq!(
392 substitute_inlines_for_preview(
393 &[Inline::CheckboxParam("Paid".into())],
394 &values
395 ),
396 "[\u{221A}]"
397 );
398 }
399
280 400 #[test]
281 401 fn preview_substitutes_placeholders_for_barcodes() {
282 402 let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
@@ -302,4 +422,13 @@ mod tests {
302 422 ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
303 423 ));
304 424 }
425
426 #[test]
427 fn parse_bool_value_accepts_common_forms() {
428 assert_eq!(parse_bool_value("true"), Some(true));
429 assert_eq!(parse_bool_value("FALSE"), Some(false));
430 assert_eq!(parse_bool_value("1"), Some(true));
431 assert_eq!(parse_bool_value("0"), Some(false));
432 assert_eq!(parse_bool_value("maybe"), None);
433 }
305 434 }
@@ -1,26 +1,71 @@
1use std::collections::BTreeSet;
1use std::collections::BTreeMap;
2
2
3use crate::dsl::{Document, Inline};
3use crate::dsl::{Document, Inline};
4
4
5pub fn collect_parameter_names(document: &Document) -> Vec<String> {
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6 let mut names = BTreeSet::new();
6pub enum ParamKind {
7 /// `${Name}` — free text
8 Text,
9 /// `$[Name]` — boolean checkbox
10 Bool,
11}
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct ParamSpec {
15 pub name: String,
16 pub kind: ParamKind,
17}
18
19pub fn collect_parameters(document: &Document) -> Vec<ParamSpec> {
20 let mut kinds: BTreeMap<String, ParamKind> = BTreeMap::new();
7 for block in &document.blocks {
21 for block in &document.blocks {
8 collect_from_block(block, &mut names);
22 collect_kinds_from_block(block, &mut kinds);
9 }
23 }
10 names.into_iter().collect()
24 kinds
25 .into_iter()
26 .map(|(name, kind)| ParamSpec { name, kind })
27 .collect()
11}
28}
12
29
13pub fn collect_parameter_names_from_source(source: &str) -> Result<Vec<String>, crate::dsl::ParseError> {
30pub fn collect_parameter_names(document: &Document) -> Vec<String> {
31 collect_parameters(document)
32 .into_iter()
33 .map(|p| p.name)
34 .collect()
35}
36
37pub fn collect_parameter_names_from_source(
38 source: &str,
39) -> Result<Vec<String>, crate::dsl::ParseError> {
14 let doc = crate::dsl::parse(source)?;
40 let doc = crate::dsl::parse(source)?;
15 Ok(collect_parameter_names(&doc))
41 Ok(collect_parameter_names(&doc))
16}
42}
17
43
18pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap<String, String>) -> Vec<Inline> {
44/// Parse a checkbox-parameter value from CLI / dialog (`true`/`false`, `1`/`0`, …).
45pub fn parse_bool_value(raw: &str) -> Option<bool> {
46 match raw.trim().to_ascii_lowercase().as_str() {
47 "true" | "1" | "yes" | "y" | "on" => Some(true),
48 "false" | "0" | "no" | "n" | "off" | "" => Some(false),
49 _ => None,
50 }
51}
52
53pub fn substitute_inlines(
54 inlines: &[Inline],
55 values: &std::collections::HashMap<String, String>,
56) -> Vec<Inline> {
19 inlines
57 inlines
20 .iter()
58 .iter()
21 .map(|inline| match inline {
59 .map(|inline| match inline {
22 Inline::Text(t) => Inline::Text(t.clone()),
60 Inline::Text(t) => Inline::Text(t.clone()),
23 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
61 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
62 Inline::CheckboxParam(name) => {
63 let checked = values
64 .get(name)
65 .and_then(|v| parse_bool_value(v))
66 .unwrap_or(false);
67 Inline::Checkbox { checked }
68 }
24 Inline::Checkbox { checked } => Inline::Checkbox {
69 Inline::Checkbox { checked } => Inline::Checkbox {
25 checked: *checked,
70 checked: *checked,
26 },
71 },
@@ -183,36 +228,42 @@ pub fn substitute_document(
183 Document { blocks }
228 Document { blocks }
184}
229}
185
230
186fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
231fn collect_kinds_from_block(
232 block: &crate::dsl::Block,
233 kinds: &mut BTreeMap<String, ParamKind>,
234) {
187 use crate::dsl::Block;
235 use crate::dsl::Block;
188
236
189 match block {
237 match block {
190 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
238 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
191 collect_from_inlines(inlines, names);
239 collect_kinds_from_inlines(inlines, kinds);
192 }
240 }
193 Block::List { items, .. } => {
241 Block::List { items, .. } => {
194 for item in items {
242 for item in items {
195 collect_from_inlines(item, names);
243 collect_kinds_from_inlines(item, kinds);
196 }
244 }
197 }
245 }
198 Block::Image { path, .. } => collect_from_raw(path, names),
246 Block::Image { path, .. } => collect_text_from_raw(path, kinds),
199 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
247 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_text_from_raw(data, kinds),
200 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
248 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
201 }
249 }
202}
250}
203
251
204fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
252fn collect_kinds_from_inlines(inlines: &[Inline], kinds: &mut BTreeMap<String, ParamKind>) {
205 for inline in inlines {
253 for inline in inlines {
206 match inline {
254 match inline {
207 Inline::Param(name) => {
255 Inline::Param(name) => {
208 names.insert(name.clone());
256 kinds.insert(name.clone(), ParamKind::Text);
257 }
258 Inline::CheckboxParam(name) => {
259 kinds.insert(name.clone(), ParamKind::Bool);
209 }
260 }
210 Inline::Text(_) | Inline::Checkbox { .. } => {}
261 Inline::Text(_) | Inline::Checkbox { .. } => {}
211 }
262 }
212 }
263 }
213}
264}
214
265
215fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
266fn collect_text_from_raw(text: &str, kinds: &mut BTreeMap<String, ParamKind>) {
216 let chars: Vec<char> = text.chars().collect();
267 let chars: Vec<char> = text.chars().collect();
217 let mut i = 0;
268 let mut i = 0;
218 while i < chars.len() {
269 while i < chars.len() {
@@ -224,7 +275,7 @@ fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
224 }
275 }
225 if j < chars.len() {
276 if j < chars.len() {
226 let name: String = chars[start..j].iter().collect();
277 let name: String = chars[start..j].iter().collect();
227 names.insert(name);
278 kinds.insert(name, ParamKind::Text);
228 i = j + 1;
279 i = j + 1;
229 continue;
280 continue;
230 }
281 }
@@ -244,6 +295,13 @@ pub fn substitute_inlines_for_preview(
244 Inline::Param(name) => {
295 Inline::Param(name) => {
245 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
296 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
246 }
297 }
298 Inline::CheckboxParam(name) => {
299 let checked = values
300 .get(name)
301 .and_then(|v| parse_bool_value(v))
302 .unwrap_or(false);
303 out.push_str(crate::dsl::checkbox_glyph(checked));
304 }
247 Inline::Checkbox { checked } => {
305 Inline::Checkbox { checked } => {
248 out.push_str(crate::dsl::checkbox_glyph(*checked));
306 out.push_str(crate::dsl::checkbox_glyph(*checked));
249 }
307 }
@@ -252,6 +310,27 @@ pub fn substitute_inlines_for_preview(
252 out
310 out
253}
311}
254
312
313/// Validate that bool parameters have parseable values when present.
314pub fn invalid_bool_parameters(
315 document: &Document,
316 values: &std::collections::HashMap<String, String>,
317) -> Vec<String> {
318 collect_parameters(document)
319 .into_iter()
320 .filter(|p| p.kind == ParamKind::Bool)
321 .filter_map(|p| {
322 let Some(raw) = values.get(&p.name) else {
323 return None;
324 };
325 if parse_bool_value(raw).is_some() {
326 None
327 } else {
328 Some(p.name)
329 }
330 })
331 .collect()
332}
333
255#[cfg(test)]
334#[cfg(test)]
256mod tests {
335mod tests {
257 use super::*;
336 use super::*;
@@ -263,6 +342,25 @@ mod tests {
263 assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
342 assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
264 }
343 }
265
344
345 #[test]
346 fn collects_checkbox_params_as_bool() {
347 let doc = crate::dsl::parse("$[Paid]\n${Name}").unwrap();
348 let params = collect_parameters(&doc);
349 assert_eq!(
350 params,
351 vec![
352 ParamSpec {
353 name: "Name".into(),
354 kind: ParamKind::Text,
355 },
356 ParamSpec {
357 name: "Paid".into(),
358 kind: ParamKind::Bool,
359 },
360 ]
361 );
362 }
363
266 #[test]
364 #[test]
267 fn preview_substitutes_inlines() {
365 fn preview_substitutes_inlines() {
268 let doc = crate::dsl::parse("Hello ${Name}").unwrap();
366 let doc = crate::dsl::parse("Hello ${Name}").unwrap();
@@ -277,6 +375,28 @@ mod tests {
277 );
375 );
278 }
376 }
279
377
378 #[test]
379 fn substitutes_checkbox_param_to_glyph() {
380 let doc = crate::dsl::parse("$[Paid] done").unwrap();
381 let mut values = HashMap::new();
382 values.insert("Paid".into(), "true".into());
383 let sub = substitute_document(&doc, &values);
384 let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
385 panic!();
386 };
387 assert!(matches!(
388 &inlines[0],
389 Inline::Checkbox { checked: true }
390 ));
391 assert_eq!(
392 substitute_inlines_for_preview(
393 &[Inline::CheckboxParam("Paid".into())],
394 &values
395 ),
396 "[\u{221A}]"
397 );
398 }
399
280 #[test]
400 #[test]
281 fn preview_substitutes_placeholders_for_barcodes() {
401 fn preview_substitutes_placeholders_for_barcodes() {
282 let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
402 let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
@@ -302,4 +422,13 @@ mod tests {
302 ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
422 ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
303 ));
423 ));
304 }
424 }
425
426 #[test]
427 fn parse_bool_value_accepts_common_forms() {
428 assert_eq!(parse_bool_value("true"), Some(true));
429 assert_eq!(parse_bool_value("FALSE"), Some(false));
430 assert_eq!(parse_bool_value("1"), Some(true));
431 assert_eq!(parse_bool_value("0"), Some(false));
432 assert_eq!(parse_bool_value("maybe"), None);
433 }
305}
434}
src/pipeline.rs +20 −6
@@ -4,7 +4,9 @@ use std::path::Path;
4 4 use crate::dsl::{parse, Document};
5 5 use crate::escpos::{EscPosEncoder, EscPosError};
6 6 use crate::io::{LoadError, PosFile};
7 use crate::params::{collect_parameter_names, substitute_document};
7 use crate::params::{
8 collect_parameters, invalid_bool_parameters, substitute_document, ParamKind,
9 };
8 10 use crate::print::{open_printer_by_name, print_bytes, PrintError};
9 11
10 12 #[derive(Debug)]
@@ -12,6 +14,7 @@ pub enum PipelineError {
12 14 Load(LoadError),
13 15 Parse(crate::dsl::ParseError),
14 16 MissingParams(Vec<String>),
17 InvalidBoolParams(Vec<String>),
15 18 Encode(EscPosError),
16 19 Print(PrintError),
17 20 }
@@ -24,6 +27,11 @@ impl std::fmt::Display for PipelineError {
24 27 Self::MissingParams(names) => {
25 28 write!(f, "missing parameters: {}", names.join(", "))
26 29 }
30 Self::InvalidBoolParams(names) => write!(
31 f,
32 "invalid boolean for {}: use true/false (or 1/0, yes/no)",
33 names.join(", ")
34 ),
27 35 Self::Encode(e) => write!(f, "{e:?}"),
28 36 Self::Print(e) => write!(f, "{e:?}"),
29 37 }
@@ -33,14 +41,16 @@ impl std::fmt::Display for PipelineError {
33 41 impl std::error::Error for PipelineError {}
34 42
35 43 pub fn missing_parameters(document: &Document, params: &HashMap<String, String>) -> Vec<String> {
36 collect_parameter_names(document)
44 collect_parameters(document)
37 45 .into_iter()
38 .filter(|name| {
39 params
40 .get(name)
46 .filter(|p| match p.kind {
47 ParamKind::Text => params
48 .get(&p.name)
41 49 .map(|v| v.is_empty())
42 .unwrap_or(true)
50 .unwrap_or(true),
51 ParamKind::Bool => !params.contains_key(&p.name),
43 52 })
53 .map(|p| p.name)
44 54 .collect()
45 55 }
46 56
@@ -54,6 +64,10 @@ pub fn encode_pos_file(
54 64 if !missing.is_empty() {
55 65 return Err(PipelineError::MissingParams(missing));
56 66 }
67 let invalid_bool = invalid_bool_parameters(&doc, params);
68 if !invalid_bool.is_empty() {
69 return Err(PipelineError::InvalidBoolParams(invalid_bool));
70 }
57 71 let sub = substitute_document(&doc, params);
58 72 let mut encoder = EscPosEncoder::new(file.metadata.clone());
59 73 if let Some(dir) = base_dir {
@@ -4,7 +4,9 @@ use std::path::Path;
4use crate::dsl::{parse, Document};
4use crate::dsl::{parse, Document};
5use crate::escpos::{EscPosEncoder, EscPosError};
5use crate::escpos::{EscPosEncoder, EscPosError};
6use crate::io::{LoadError, PosFile};
6use crate::io::{LoadError, PosFile};
7use crate::params::{collect_parameter_names, substitute_document};
7use crate::params::{
8 collect_parameters, invalid_bool_parameters, substitute_document, ParamKind,
9};
8use crate::print::{open_printer_by_name, print_bytes, PrintError};
10use crate::print::{open_printer_by_name, print_bytes, PrintError};
9
11
10#[derive(Debug)]
12#[derive(Debug)]
@@ -12,6 +14,7 @@ pub enum PipelineError {
12 Load(LoadError),
14 Load(LoadError),
13 Parse(crate::dsl::ParseError),
15 Parse(crate::dsl::ParseError),
14 MissingParams(Vec<String>),
16 MissingParams(Vec<String>),
17 InvalidBoolParams(Vec<String>),
15 Encode(EscPosError),
18 Encode(EscPosError),
16 Print(PrintError),
19 Print(PrintError),
17}
20}
@@ -24,6 +27,11 @@ impl std::fmt::Display for PipelineError {
24 Self::MissingParams(names) => {
27 Self::MissingParams(names) => {
25 write!(f, "missing parameters: {}", names.join(", "))
28 write!(f, "missing parameters: {}", names.join(", "))
26 }
29 }
30 Self::InvalidBoolParams(names) => write!(
31 f,
32 "invalid boolean for {}: use true/false (or 1/0, yes/no)",
33 names.join(", ")
34 ),
27 Self::Encode(e) => write!(f, "{e:?}"),
35 Self::Encode(e) => write!(f, "{e:?}"),
28 Self::Print(e) => write!(f, "{e:?}"),
36 Self::Print(e) => write!(f, "{e:?}"),
29 }
37 }
@@ -33,14 +41,16 @@ impl std::fmt::Display for PipelineError {
33impl std::error::Error for PipelineError {}
41impl std::error::Error for PipelineError {}
34
42
35pub fn missing_parameters(document: &Document, params: &HashMap<String, String>) -> Vec<String> {
43pub fn missing_parameters(document: &Document, params: &HashMap<String, String>) -> Vec<String> {
36 collect_parameter_names(document)
44 collect_parameters(document)
37 .into_iter()
45 .into_iter()
38 .filter(|name| {
46 .filter(|p| match p.kind {
39 params
47 ParamKind::Text => params
40 .get(name)
48 .get(&p.name)
41 .map(|v| v.is_empty())
49 .map(|v| v.is_empty())
42 .unwrap_or(true)
50 .unwrap_or(true),
51 ParamKind::Bool => !params.contains_key(&p.name),
43 })
52 })
53 .map(|p| p.name)
44 .collect()
54 .collect()
45}
55}
46
56
@@ -54,6 +64,10 @@ pub fn encode_pos_file(
54 if !missing.is_empty() {
64 if !missing.is_empty() {
55 return Err(PipelineError::MissingParams(missing));
65 return Err(PipelineError::MissingParams(missing));
56 }
66 }
67 let invalid_bool = invalid_bool_parameters(&doc, params);
68 if !invalid_bool.is_empty() {
69 return Err(PipelineError::InvalidBoolParams(invalid_bool));
70 }
57 let sub = substitute_document(&doc, params);
71 let sub = substitute_document(&doc, params);
58 let mut encoder = EscPosEncoder::new(file.metadata.clone());
72 let mut encoder = EscPosEncoder::new(file.metadata.clone());
59 if let Some(dir) = base_dir {
73 if let Some(dir) = base_dir {
src/print_dialog.rs +57 −19
@@ -8,7 +8,7 @@ use eframe::egui;
8 8
9 9 use posprint::dsl::parse;
10 10 use posprint::io::{PosFile, PosMetadata};
11 use posprint::params::collect_parameter_names;
11 use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12 12 use posprint::pipeline;
13 13 use posprint::print::{
14 14 list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
@@ -22,7 +22,7 @@ pub enum PrintExecuteResult {
22 22
23 23 pub struct PrintDialog {
24 24 pub param_inputs: HashMap<String, String>,
25 pub param_names: Vec<String>,
25 pub param_specs: Vec<ParamSpec>,
26 26 pub last_params: HashMap<String, String>,
27 27 pub printers: Vec<PrinterDevice>,
28 28 pub printers_loading: bool,
@@ -37,7 +37,7 @@ impl Default for PrintDialog {
37 37 fn default() -> Self {
38 38 Self {
39 39 param_inputs: HashMap::new(),
40 param_names: Vec::new(),
40 param_specs: Vec::new(),
41 41 last_params: HashMap::new(),
42 42 printers: Vec::new(),
43 43 printers_loading: false,
@@ -54,15 +54,23 @@ impl PrintDialog {
54 54 pub fn prepare(&mut self, body: &str) -> Result<(), String> {
55 55 self.error = None;
56 56 let doc = parse(body).map_err(|e| e.to_string())?;
57 self.param_names = collect_parameter_names(&doc);
57 self.param_specs = collect_parameters(&doc);
58 58 self.param_inputs.clear();
59 for name in &self.param_names {
60 let value = self
61 .last_params
62 .get(name)
63 .cloned()
64 .unwrap_or_default();
65 self.param_inputs.insert(name.clone(), value);
59 for spec in &self.param_specs {
60 let value = match spec.kind {
61 ParamKind::Bool => self
62 .last_params
63 .get(&spec.name)
64 .cloned()
65 .filter(|v| parse_bool_value(v).is_some())
66 .unwrap_or_else(|| "false".into()),
67 ParamKind::Text => self
68 .last_params
69 .get(&spec.name)
70 .cloned()
71 .unwrap_or_default(),
72 };
73 self.param_inputs.insert(spec.name.clone(), value);
66 74 }
67 75 self.start_printer_discovery();
68 76 Ok(())
@@ -127,11 +135,21 @@ impl PrintDialog {
127 135 return PrintExecuteResult::StillOpen;
128 136 }
129 137
130 for name in &self.param_names {
131 if !self.param_inputs.contains_key(name) {
132 self.error = Some(format!("Missing value for parameter {name}"));
138 for spec in &self.param_specs {
139 if !self.param_inputs.contains_key(&spec.name) {
140 self.error = Some(format!("Missing value for parameter {}", spec.name));
133 141 return PrintExecuteResult::StillOpen;
134 142 }
143 if spec.kind == ParamKind::Bool {
144 let raw = self.param_inputs.get(&spec.name).map(String::as_str).unwrap_or("");
145 if parse_bool_value(raw).is_none() {
146 self.error = Some(format!(
147 "Invalid boolean for {}: use true/false",
148 spec.name
149 ));
150 return PrintExecuteResult::StillOpen;
151 }
152 }
135 153 }
136 154
137 155 self.last_params = self.param_inputs.clone();
@@ -190,14 +208,34 @@ impl PrintDialog {
190 208
191 209 pub fn show_ui(&mut self, ui: &mut egui::Ui, cancel_label: &str) -> PrintDialogAction {
192 210 ui.heading("Parameters");
193 if self.param_names.is_empty() {
211 if self.param_specs.is_empty() {
194 212 ui.label("No parameters in this template.");
195 213 } else {
196 for name in self.param_names.clone() {
214 for spec in self.param_specs.clone() {
197 215 ui.horizontal(|ui| {
198 ui.label(format!("{name}:"));
199 let entry = self.param_inputs.entry(name).or_insert_with(String::new);
200 ui.text_edit_singleline(entry);
216 match spec.kind {
217 ParamKind::Text => {
218 ui.label(format!("{}:", spec.name));
219 let entry = self
220 .param_inputs
221 .entry(spec.name.clone())
222 .or_insert_with(String::new);
223 ui.text_edit_singleline(entry);
224 }
225 ParamKind::Bool => {
226 let mut checked = self
227 .param_inputs
228 .get(&spec.name)
229 .and_then(|v| parse_bool_value(v))
230 .unwrap_or(false);
231 if ui.checkbox(&mut checked, &spec.name).changed() {
232 self.param_inputs.insert(
233 spec.name.clone(),
234 if checked { "true" } else { "false" }.into(),
235 );
236 }
237 }
238 }
201 239 });
202 240 }
203 241 }
@@ -8,7 +8,7 @@ use eframe::egui;
8
8
9use posprint::dsl::parse;
9use posprint::dsl::parse;
10use posprint::io::{PosFile, PosMetadata};
10use posprint::io::{PosFile, PosMetadata};
11use posprint::params::collect_parameter_names;
11use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12use posprint::pipeline;
12use posprint::pipeline;
13use posprint::print::{
13use posprint::print::{
14 list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
14 list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
@@ -22,7 +22,7 @@ pub enum PrintExecuteResult {
22
22
23pub struct PrintDialog {
23pub struct PrintDialog {
24 pub param_inputs: HashMap<String, String>,
24 pub param_inputs: HashMap<String, String>,
25 pub param_names: Vec<String>,
25 pub param_specs: Vec<ParamSpec>,
26 pub last_params: HashMap<String, String>,
26 pub last_params: HashMap<String, String>,
27 pub printers: Vec<PrinterDevice>,
27 pub printers: Vec<PrinterDevice>,
28 pub printers_loading: bool,
28 pub printers_loading: bool,
@@ -37,7 +37,7 @@ impl Default for PrintDialog {
37 fn default() -> Self {
37 fn default() -> Self {
38 Self {
38 Self {
39 param_inputs: HashMap::new(),
39 param_inputs: HashMap::new(),
40 param_names: Vec::new(),
40 param_specs: Vec::new(),
41 last_params: HashMap::new(),
41 last_params: HashMap::new(),
42 printers: Vec::new(),
42 printers: Vec::new(),
43 printers_loading: false,
43 printers_loading: false,
@@ -54,15 +54,23 @@ impl PrintDialog {
54 pub fn prepare(&mut self, body: &str) -> Result<(), String> {
54 pub fn prepare(&mut self, body: &str) -> Result<(), String> {
55 self.error = None;
55 self.error = None;
56 let doc = parse(body).map_err(|e| e.to_string())?;
56 let doc = parse(body).map_err(|e| e.to_string())?;
57 self.param_names = collect_parameter_names(&doc);
57 self.param_specs = collect_parameters(&doc);
58 self.param_inputs.clear();
58 self.param_inputs.clear();
59 for name in &self.param_names {
59 for spec in &self.param_specs {
60 let value = self
60 let value = match spec.kind {
61 .last_params
61 ParamKind::Bool => self
62 .get(name)
62 .last_params
63 .cloned()
63 .get(&spec.name)
64 .unwrap_or_default();
64 .cloned()
65 self.param_inputs.insert(name.clone(), value);
65 .filter(|v| parse_bool_value(v).is_some())
66 .unwrap_or_else(|| "false".into()),
67 ParamKind::Text => self
68 .last_params
69 .get(&spec.name)
70 .cloned()
71 .unwrap_or_default(),
72 };
73 self.param_inputs.insert(spec.name.clone(), value);
66 }
74 }
67 self.start_printer_discovery();
75 self.start_printer_discovery();
68 Ok(())
76 Ok(())
@@ -127,11 +135,21 @@ impl PrintDialog {
127 return PrintExecuteResult::StillOpen;
135 return PrintExecuteResult::StillOpen;
128 }
136 }
129
137
130 for name in &self.param_names {
138 for spec in &self.param_specs {
131 if !self.param_inputs.contains_key(name) {
139 if !self.param_inputs.contains_key(&spec.name) {
132 self.error = Some(format!("Missing value for parameter {name}"));
140 self.error = Some(format!("Missing value for parameter {}", spec.name));
133 return PrintExecuteResult::StillOpen;
141 return PrintExecuteResult::StillOpen;
134 }
142 }
143 if spec.kind == ParamKind::Bool {
144 let raw = self.param_inputs.get(&spec.name).map(String::as_str).unwrap_or("");
145 if parse_bool_value(raw).is_none() {
146 self.error = Some(format!(
147 "Invalid boolean for {}: use true/false",
148 spec.name
149 ));
150 return PrintExecuteResult::StillOpen;
151 }
152 }
135 }
153 }
136
154
137 self.last_params = self.param_inputs.clone();
155 self.last_params = self.param_inputs.clone();
@@ -190,14 +208,34 @@ impl PrintDialog {
190
208
191 pub fn show_ui(&mut self, ui: &mut egui::Ui, cancel_label: &str) -> PrintDialogAction {
209 pub fn show_ui(&mut self, ui: &mut egui::Ui, cancel_label: &str) -> PrintDialogAction {
192 ui.heading("Parameters");
210 ui.heading("Parameters");
193 if self.param_names.is_empty() {
211 if self.param_specs.is_empty() {
194 ui.label("No parameters in this template.");
212 ui.label("No parameters in this template.");
195 } else {
213 } else {
196 for name in self.param_names.clone() {
214 for spec in self.param_specs.clone() {
197 ui.horizontal(|ui| {
215 ui.horizontal(|ui| {
198 ui.label(format!("{name}:"));
216 match spec.kind {
199 let entry = self.param_inputs.entry(name).or_insert_with(String::new);
217 ParamKind::Text => {
200 ui.text_edit_singleline(entry);
218 ui.label(format!("{}:", spec.name));
219 let entry = self
220 .param_inputs
221 .entry(spec.name.clone())
222 .or_insert_with(String::new);
223 ui.text_edit_singleline(entry);
224 }
225 ParamKind::Bool => {
226 let mut checked = self
227 .param_inputs
228 .get(&spec.name)
229 .and_then(|v| parse_bool_value(v))
230 .unwrap_or(false);
231 if ui.checkbox(&mut checked, &spec.name).changed() {
232 self.param_inputs.insert(
233 spec.name.clone(),
234 if checked { "true" } else { "false" }.into(),
235 );
236 }
237 }
238 }
201 });
239 });
202 }
240 }
203 }
241 }