BlueGit

timfa posprint

Add project design docs and development rules.

Document feasibility, architecture, DSL, printing, and in-app help reference.
Establish conventions for testing, branching, and minimal dependencies.

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

timfa Tim Falken · pushed by timfa

Authored 2026-07-15 · 4 months ago

Hash
d154765f9ed841c7609f9ff36d38963d4483820a
9 files changed +1487 −0
.cursor/rules/development.mdc added +35 −0
@@ -0,0 +1,35 @@
1 ---
2 description: posprint development conventions
3 globs: **/*
4 alwaysApply: true
5 ---
6
7 # posprint development rules
8
9 ## Language and dependencies
10
11 - Single language: **Rust** with **egui** (eframe) for the UI.
12 - Prefer std library and in-house code. Add a crate only when reimplementing would be unreasonable (e.g. `serialport`, `serde`, `image`, UI framework).
13 - Printing: **USB-serial only** in v1. No Bluetooth until explicitly requested.
14
15 ## Testing
16
17 - **Every module must have unit tests** in `#[cfg(test)] mod tests` (or `tests/` for integration).
18 - New behavior requires new tests in the same commit.
19 - Run `cargo test` before merging; all tests must pass.
20 - Use mock transports for printer I/O in tests; never require hardware in CI.
21
22 ## Branches and commits
23
24 - Default branch: `master`.
25 - Use `feature/` or `fix/` branches for changes after initial setup.
26 - Commit frequently with focused messages; avoid one large commit at the end.
27
28 ## Documentation
29
30 - Keep `docs/HELP.md` in sync with supported DSL and UI features.
31 - The in-app Help tab must mirror `docs/HELP.md` (via `include_str!`).
32
33 ## Releases
34
35 - GitLab CI builds Windows (`.exe`/`.msi`) and Linux (`.deb` for apt) artifacts.
@@ -0,0 +1,35 @@
1---
2description: posprint development conventions
3globs: **/*
4alwaysApply: true
5---
6
7# posprint development rules
8
9## Language and dependencies
10
11- Single language: **Rust** with **egui** (eframe) for the UI.
12- Prefer std library and in-house code. Add a crate only when reimplementing would be unreasonable (e.g. `serialport`, `serde`, `image`, UI framework).
13- Printing: **USB-serial only** in v1. No Bluetooth until explicitly requested.
14
15## Testing
16
17- **Every module must have unit tests** in `#[cfg(test)] mod tests` (or `tests/` for integration).
18- New behavior requires new tests in the same commit.
19- Run `cargo test` before merging; all tests must pass.
20- Use mock transports for printer I/O in tests; never require hardware in CI.
21
22## Branches and commits
23
24- Default branch: `master`.
25- Use `feature/` or `fix/` branches for changes after initial setup.
26- Commit frequently with focused messages; avoid one large commit at the end.
27
28## Documentation
29
30- Keep `docs/HELP.md` in sync with supported DSL and UI features.
31- The in-app Help tab must mirror `docs/HELP.md` (via `include_str!`).
32
33## Releases
34
35- GitLab CI builds Windows (`.exe`/`.msi`) and Linux (`.deb` for apt) artifacts.
README.md added +44 −0
@@ -0,0 +1,44 @@
1 # posprint
2
3 Cross-platform designer for POS (point-of-sale) receipt documents. Edit templates in a markdown-like syntax, preview output live, substitute runtime parameters, and print directly to USB or Bluetooth thermal printers via raw ESC/POS bytes.
4
5 **Target platforms:** Windows and Linux (x64).
6
7 ## Status
8
9 Pre-implementation — design phase. See [docs/](docs/) for specifications.
10
11 ## Design documents
12
13 | Document | Description |
14 |----------|-------------|
15 | [FEASIBILITY.md](docs/FEASIBILITY.md) | Feasibility assessment, complexity estimate, risks |
16 | [LANGUAGE-CHOICE.md](docs/LANGUAGE-CHOICE.md) | Language and framework recommendation |
17 | [ARCHITECTURE.md](docs/ARCHITECTURE.md) | System architecture and module breakdown |
18 | [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
19 | [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
20 | [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
21
22 ## Planned features
23
24 - Markdown-like template editor with live preview
25 - Page width: auto-scale to window or fixed width (mm)
26 - Save and load `.pos` files
27 - Parameter tokens (`${DocumentNumber}`) with print-time popup and value reuse
28 - Barcodes, QR codes, and images (including parameterized content)
29 - Print to USB / Bluetooth POS printers via raw byte streams
30
31 ## Quick feasibility summary
32
33 **Verdict: feasible** for a small team or solo developer, with the printing layer as the main engineering risk.
34
35 | Area | Complexity | Notes |
36 |------|------------|-------|
37 | Editor + preview UI | Medium | Well-trodden path |
38 | DSL parser + renderer | Medium | Custom grammar, bounded scope |
39 | Parameters | Low | Straightforward substitution |
40 | Barcodes / QR / images | Low–Medium | Mature libraries exist |
41 | USB / BT printer I/O | **High** | OS differences, device quirks |
42 | **Overall (MVP)** | **Medium–High** | ~6–10 weeks for one experienced dev |
43
44 Stack: **Rust + egui** (single language, minimal dependencies). USB-serial printing only in v1. See [LANGUAGE-CHOICE.md](docs/LANGUAGE-CHOICE.md) and [docs/HELP.md](docs/HELP.md).
@@ -0,0 +1,44 @@
1# posprint
2
3Cross-platform designer for POS (point-of-sale) receipt documents. Edit templates in a markdown-like syntax, preview output live, substitute runtime parameters, and print directly to USB or Bluetooth thermal printers via raw ESC/POS bytes.
4
5**Target platforms:** Windows and Linux (x64).
6
7## Status
8
9Pre-implementation — design phase. See [docs/](docs/) for specifications.
10
11## Design documents
12
13| Document | Description |
14|----------|-------------|
15| [FEASIBILITY.md](docs/FEASIBILITY.md) | Feasibility assessment, complexity estimate, risks |
16| [LANGUAGE-CHOICE.md](docs/LANGUAGE-CHOICE.md) | Language and framework recommendation |
17| [ARCHITECTURE.md](docs/ARCHITECTURE.md) | System architecture and module breakdown |
18| [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
19| [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
20| [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
21
22## Planned features
23
24- Markdown-like template editor with live preview
25- Page width: auto-scale to window or fixed width (mm)
26- Save and load `.pos` files
27- Parameter tokens (`${DocumentNumber}`) with print-time popup and value reuse
28- Barcodes, QR codes, and images (including parameterized content)
29- Print to USB / Bluetooth POS printers via raw byte streams
30
31## Quick feasibility summary
32
33**Verdict: feasible** for a small team or solo developer, with the printing layer as the main engineering risk.
34
35| Area | Complexity | Notes |
36|------|------------|-------|
37| Editor + preview UI | Medium | Well-trodden path |
38| DSL parser + renderer | Medium | Custom grammar, bounded scope |
39| Parameters | Low | Straightforward substitution |
40| Barcodes / QR / images | Low–Medium | Mature libraries exist |
41| USB / BT printer I/O | **High** | OS differences, device quirks |
42| **Overall (MVP)** | **Medium–High** | ~6–10 weeks for one experienced dev |
43
44Stack: **Rust + egui** (single language, minimal dependencies). USB-serial printing only in v1. See [LANGUAGE-CHOICE.md](docs/LANGUAGE-CHOICE.md) and [docs/HELP.md](docs/HELP.md).
docs/ARCHITECTURE.md added +201 −0
@@ -0,0 +1,201 @@
1 # System architecture
2
3 ## Overview
4
5 posprint is a desktop application with a **web-based UI** (Tauri) and a **Rust backend** that owns parsing, rendering, file I/O, and printer communication.
6
7 ```
8 ┌──────────────────────────────────────────────────────────────────┐
9 │ Application │
10 ├────────────────────────────┬─────────────────────────────────────┤
11 │ UI Layer │ Core Layer (Rust) │
12 │ (TypeScript / Tauri WebView) │
13 │ │ │
14 │ DocumentEditor ───────────┼──► parse_dsl() → Document AST │
15 │ PreviewPane ◄─────────────┼─── render_preview(ast, width) │
16 │ SettingsPanel │ │
17 │ ParameterDialog │ │
18 │ PrinterPicker │ │
19 │ │ │
20 │ File menu ────────────────┼──► load_pos() / save_pos() │
21 │ Print button ─────────────┼──► list_printers() │
22 │ │ print_document(ast, params, dev) │
23 └────────────────────────────┴─────────────────────────────────────┘
24 │
25 ┌─────────────────┼─────────────────┐
26 ▼ ▼ ▼
27 Preview bitmap ESC/POS bytes .pos JSON file
28 ```
29
30 ---
31
32 ## Modules (Rust crate layout)
33
34 ```
35 posprint-core/ # Library — no UI, unit-testable
36 ├── dsl/
37 │ ├── lexer.rs # Tokenize source
38 │ ├── parser.rs # Build AST
39 │ └── ast.rs # Document, Block, Inline, Directive nodes
40 ├── render/
41 │ ├── preview.rs # Layout for UI (lines, images, barcode placeholders)
42 │ └── escpos.rs # AST → ESC/POS byte buffer
43 ├── params/
44 │ ├── collect.rs # Find unique ${Name} tokens
45 │ └── substitute.rs # Apply user values before render/print
46 ├── io/
47 │ └── pos_file.rs # Serde types, load/save
48 └── print/
49 ├── discover.rs # Enumerate serial / USB / BT devices
50 ├── transport.rs # Trait: write(bytes), read optional status
51 └── pipeline.rs # substitute → escpos → transport
52
53 posprint-app/ # Tauri binary
54 ├── commands/ # #[tauri::command] wrappers
55 ├── state.rs # App state (last params, recent files)
56 └── main.rs
57 ```
58
59 Frontend (`src/`):
60
61 ```
62 src/
63 ├── components/
64 │ ├── Editor.tsx
65 │ ├── Preview.tsx
66 │ ├── Toolbar.tsx
67 │ ├── ParameterModal.tsx
68 │ └── PrinterDialog.tsx
69 ├── hooks/
70 │ ├── useDocument.ts
71 │ └── usePreview.ts
72 └── lib/
73 └── tauri.ts # Typed invoke wrappers
74 ```
75
76 ---
77
78 ## Data flow
79
80 ### Edit loop (live preview)
81
82 1. User types in editor → debounced (e.g. 150 ms) invoke `preview_document(source, settings)`.
83 2. Core parses DSL → AST (or returns parse errors with line/col).
84 3. Core renders preview model: text lines, image refs, barcode/QR placeholders sized to page width.
85 4. UI displays preview scaled to panel width (auto) or fixed mm width.
86
87 ### Save / load
88
89 1. **Save:** UI sends `{ metadata, body }` → `save_pos(path)` → JSON on disk.
90 2. **Load:** `load_pos(path)` → populate editor and settings.
91
92 ### Print
93
94 1. User clicks Print → `collect_parameters(ast)` → unique sorted names.
95 2. UI shows modal; pre-fill from `last_print_params` in app state.
96 3. On confirm → `print_document(ast, params, printer_id)`.
97 4. Core: substitute → build ESC/POS → open transport → write bytes → cut (if configured).
98
99 ---
100
101 ## Key types (conceptual)
102
103 ```rust
104 struct Document {
105 blocks: Vec<Block>,
106 }
107
108 enum Block {
109 Paragraph { inlines: Vec<Inline>, align: Align },
110 Heading { level: u8, text: String },
111 Rule,
112 Image { src: String, width: ImageWidth }, // src may be ${Param}
113 Barcode { symbology: BarcodeKind, data: String, height: u8 },
114 Qr { data: String, size: QrSize },
115 Feed { lines: u8 },
116 Cut,
117 }
118
119 struct PosFile {
120 version: u32,
121 metadata: Metadata,
122 body: String,
123 }
124
125 struct Metadata {
126 title: Option<String>,
127 page_width_mm: f32, // 58, 80, etc.
128 preview_mode: PreviewMode, // AutoScale | Fixed
129 codepage: Option<String>,
130 cut_after_print: bool,
131 }
132
133 struct PrinterDevice {
134 id: String, // stable key for session
135 name: String,
136 transport: TransportKind,
137 // ...
138 }
139 ```
140
141 ---
142
143 ## Tauri commands (IPC surface)
144
145 | Command | Input | Output |
146 |---------|-------|--------|
147 | `parse_document` | `body: string` | `{ ast \| errors }` |
148 | `preview_document` | `body, metadata` | `PreviewModel` |
149 | `collect_parameters` | `body` | `string[]` (unique, sorted) |
150 | `save_pos` | `path, PosFile` | `Result<()>` |
151 | `load_pos` | `path` | `PosFile` |
152 | `list_printers` | — | `PrinterDevice[]` |
153 | `print_document` | `body, metadata, params, printer_id` | `Result<()>` |
154
155 ---
156
157 ## Preview vs print fidelity
158
159 | Aspect | Preview | Print |
160 |--------|---------|-------|
161 | Text font | UI monospace, scaled | Printer built-in font |
162 | Line width | Computed from `page_width_mm` | ESC/POS dot width |
163 | Images | Resized bitmap in canvas | Raster ESC/POS |
164 | Barcodes | SVG/canvas placeholder | Native printer barcode commands |
165 | Alignment | CSS / canvas | ESC/POS justify commands |
166
167 Both paths share the **same AST and substitution**; preview and print each have their own backend (preview renderer vs `escpos` encoder).
168
169 ---
170
171 ## State persistence
172
173 | Data | Storage |
174 |------|---------|
175 | Recent files | App config (Tauri `app_data_dir`) |
176 | Last parameter values | `params.json` keyed by template path or global |
177 | Window layout | Optional, Tauri store |
178 | Selected printer | Per-machine preference |
179
180 ---
181
182 ## Testing strategy
183
184 | Layer | Approach |
185 |-------|----------|
186 | DSL parser | Unit tests + snapshot fixtures |
187 | Parameter collect/substitute | Unit tests |
188 | ESC/POS encoder | Byte snapshot tests |
189 | Preview layout | Snapshot images (optional) |
190 | Printer I/O | Manual hardware matrix; mock `Transport` trait in CI |
191 | UI | Component tests; E2E with mocked Tauri commands |
192
193 ---
194
195 ## Build and release
196
197 - **CI:** GitHub Actions — `cargo test`, `cargo clippy`, frontend lint, build Windows + Linux artifacts.
198 - **Artifacts:** `.msi` or `.exe` (Windows), `.deb` / AppImage (Linux).
199 - **Versioning:** Semver; `.pos` `version` field for file format migrations.
200
201 See [PRINTING.md](PRINTING.md) for the device layer and [DSL-SPEC.md](DSL-SPEC.md) for language details.
@@ -0,0 +1,201 @@
1# System architecture
2
3## Overview
4
5posprint is a desktop application with a **web-based UI** (Tauri) and a **Rust backend** that owns parsing, rendering, file I/O, and printer communication.
6
7```
8┌──────────────────────────────────────────────────────────────────┐
9│ Application │
10├────────────────────────────┬─────────────────────────────────────┤
11│ UI Layer │ Core Layer (Rust) │
12│ (TypeScript / Tauri WebView) │
13│ │ │
14│ DocumentEditor ───────────┼──► parse_dsl() → Document AST │
15│ PreviewPane ◄─────────────┼─── render_preview(ast, width) │
16│ SettingsPanel │ │
17│ ParameterDialog │ │
18│ PrinterPicker │ │
19│ │ │
20│ File menu ────────────────┼──► load_pos() / save_pos() │
21│ Print button ─────────────┼──► list_printers() │
22│ │ print_document(ast, params, dev) │
23└────────────────────────────┴─────────────────────────────────────┘
24 │
25 ┌─────────────────┼─────────────────┐
26 ▼ ▼ ▼
27 Preview bitmap ESC/POS bytes .pos JSON file
28```
29
30---
31
32## Modules (Rust crate layout)
33
34```
35posprint-core/ # Library — no UI, unit-testable
36├── dsl/
37│ ├── lexer.rs # Tokenize source
38│ ├── parser.rs # Build AST
39│ └── ast.rs # Document, Block, Inline, Directive nodes
40├── render/
41│ ├── preview.rs # Layout for UI (lines, images, barcode placeholders)
42│ └── escpos.rs # AST → ESC/POS byte buffer
43├── params/
44│ ├── collect.rs # Find unique ${Name} tokens
45│ └── substitute.rs # Apply user values before render/print
46├── io/
47│ └── pos_file.rs # Serde types, load/save
48└── print/
49 ├── discover.rs # Enumerate serial / USB / BT devices
50 ├── transport.rs # Trait: write(bytes), read optional status
51 └── pipeline.rs # substitute → escpos → transport
52
53posprint-app/ # Tauri binary
54├── commands/ # #[tauri::command] wrappers
55├── state.rs # App state (last params, recent files)
56└── main.rs
57```
58
59Frontend (`src/`):
60
61```
62src/
63├── components/
64│ ├── Editor.tsx
65│ ├── Preview.tsx
66│ ├── Toolbar.tsx
67│ ├── ParameterModal.tsx
68│ └── PrinterDialog.tsx
69├── hooks/
70│ ├── useDocument.ts
71│ └── usePreview.ts
72└── lib/
73 └── tauri.ts # Typed invoke wrappers
74```
75
76---
77
78## Data flow
79
80### Edit loop (live preview)
81
821. User types in editor → debounced (e.g. 150 ms) invoke `preview_document(source, settings)`.
832. Core parses DSL → AST (or returns parse errors with line/col).
843. Core renders preview model: text lines, image refs, barcode/QR placeholders sized to page width.
854. UI displays preview scaled to panel width (auto) or fixed mm width.
86
87### Save / load
88
891. **Save:** UI sends `{ metadata, body }` → `save_pos(path)` → JSON on disk.
902. **Load:** `load_pos(path)` → populate editor and settings.
91
92### Print
93
941. User clicks Print → `collect_parameters(ast)` → unique sorted names.
952. UI shows modal; pre-fill from `last_print_params` in app state.
963. On confirm → `print_document(ast, params, printer_id)`.
974. Core: substitute → build ESC/POS → open transport → write bytes → cut (if configured).
98
99---
100
101## Key types (conceptual)
102
103```rust
104struct Document {
105 blocks: Vec<Block>,
106}
107
108enum Block {
109 Paragraph { inlines: Vec<Inline>, align: Align },
110 Heading { level: u8, text: String },
111 Rule,
112 Image { src: String, width: ImageWidth }, // src may be ${Param}
113 Barcode { symbology: BarcodeKind, data: String, height: u8 },
114 Qr { data: String, size: QrSize },
115 Feed { lines: u8 },
116 Cut,
117}
118
119struct PosFile {
120 version: u32,
121 metadata: Metadata,
122 body: String,
123}
124
125struct Metadata {
126 title: Option<String>,
127 page_width_mm: f32, // 58, 80, etc.
128 preview_mode: PreviewMode, // AutoScale | Fixed
129 codepage: Option<String>,
130 cut_after_print: bool,
131}
132
133struct PrinterDevice {
134 id: String, // stable key for session
135 name: String,
136 transport: TransportKind,
137 // ...
138}
139```
140
141---
142
143## Tauri commands (IPC surface)
144
145| Command | Input | Output |
146|---------|-------|--------|
147| `parse_document` | `body: string` | `{ ast \| errors }` |
148| `preview_document` | `body, metadata` | `PreviewModel` |
149| `collect_parameters` | `body` | `string[]` (unique, sorted) |
150| `save_pos` | `path, PosFile` | `Result<()>` |
151| `load_pos` | `path` | `PosFile` |
152| `list_printers` | — | `PrinterDevice[]` |
153| `print_document` | `body, metadata, params, printer_id` | `Result<()>` |
154
155---
156
157## Preview vs print fidelity
158
159| Aspect | Preview | Print |
160|--------|---------|-------|
161| Text font | UI monospace, scaled | Printer built-in font |
162| Line width | Computed from `page_width_mm` | ESC/POS dot width |
163| Images | Resized bitmap in canvas | Raster ESC/POS |
164| Barcodes | SVG/canvas placeholder | Native printer barcode commands |
165| Alignment | CSS / canvas | ESC/POS justify commands |
166
167Both paths share the **same AST and substitution**; preview and print each have their own backend (preview renderer vs `escpos` encoder).
168
169---
170
171## State persistence
172
173| Data | Storage |
174|------|---------|
175| Recent files | App config (Tauri `app_data_dir`) |
176| Last parameter values | `params.json` keyed by template path or global |
177| Window layout | Optional, Tauri store |
178| Selected printer | Per-machine preference |
179
180---
181
182## Testing strategy
183
184| Layer | Approach |
185|-------|----------|
186| DSL parser | Unit tests + snapshot fixtures |
187| Parameter collect/substitute | Unit tests |
188| ESC/POS encoder | Byte snapshot tests |
189| Preview layout | Snapshot images (optional) |
190| Printer I/O | Manual hardware matrix; mock `Transport` trait in CI |
191| UI | Component tests; E2E with mocked Tauri commands |
192
193---
194
195## Build and release
196
197- **CI:** GitHub Actions — `cargo test`, `cargo clippy`, frontend lint, build Windows + Linux artifacts.
198- **Artifacts:** `.msi` or `.exe` (Windows), `.deb` / AppImage (Linux).
199- **Versioning:** Semver; `.pos` `version` field for file format migrations.
200
201See [PRINTING.md](PRINTING.md) for the device layer and [DSL-SPEC.md](DSL-SPEC.md) for language details.
docs/DSL-SPEC.md added +265 −0
@@ -0,0 +1,265 @@
1 # Document DSL specification
2
3 A lightweight, markdown-inspired syntax for POS receipt templates. The DSL compiles to an AST and then to ESC/POS bytes or a screen preview.
4
5 **Design goals:** easy to author, line-oriented, explicit about POS-specific features (barcodes, cut, feed), parameter-friendly.
6
7 ---
8
9 ## Document structure
10
11 A document is a sequence of **blocks** separated by blank lines. Blocks cannot be nested except for inline markup within text blocks.
12
13 ---
14
15 ## Text blocks
16
17 ### Paragraphs
18
19 Plain text with optional inline markup. One or more consecutive non-empty lines form a paragraph.
20
21 ```markdown
22 Thank you for your purchase!
23 Visit us again soon.
24 ```
25
26 ### Headings
27
28 ```markdown
29 # Store Name
30 ## Receipt
31 ```
32
33 - `#` → large / double-height text (ESC/POS emphasis)
34 - `##` → bold emphasis
35 - Maximum two levels in v1
36
37 ### Alignment
38
39 Prefix a paragraph with alignment markers:
40
41 ```markdown
42 :center:
43 Your Store Name
44
45 :right:
46 Total: ${Amount}
47 ```
48
49 | Marker | Effect |
50 |--------|--------|
51 | `:left:` | Left (default) |
52 | `:center:` | Centered |
53 | `:right:` | Right-aligned |
54
55 ### Inline markup
56
57 | Syntax | Effect |
58 |--------|--------|
59 | `**text**` | Bold |
60 | `*text*` | Italic / emphasized (printer secondary font if available) |
61 | `` `text` `` | Monospace / condensed |
62 | `${Name}` | Parameter placeholder (see Parameters) |
63
64 Parameters work inside any text, and inside barcode/QR/image directives (below).
65
66 **Example:**
67
68 ```markdown
69 Receipt #${DocumentNumber}
70 Date: ${Date}
71
72 Item: ${ItemName} **${LineTotal}**
73 ```
74
75 ### Horizontal rule
76
77 ```markdown
78 ---
79 ```
80
81 Renders a dashed or solid separator line across the print width.
82
83 ---
84
85 ## Directives (block-level)
86
87 Directives start with `@` at the beginning of a line.
88
89 ### Feed (blank lines)
90
91 ```markdown
92 @feed 3
93 ```
94
95 Advances paper by *n* lines.
96
97 ### Cut
98
99 ```markdown
100 @cut
101 ```
102
103 Partial cut after content (if printer supports). Often placed at document end.
104
105 ### Image
106
107 ```markdown
108 @image path/to/logo.png
109 @image ${LogoPath} width=50%
110 @image assets/qr-promo.png width=384
111 ```
112
113 | Attribute | Description |
114 |-----------|-------------|
115 | `path` (positional) | File path relative to `.pos` file or absolute; may be `${Param}` |
116 | `width` | `NN%` of printable width, or absolute dots (e.g. `384`) |
117 | `align` | `left` (default), `center`, `right` |
118
119 Images are converted to monochrome raster data, dithered, and scaled to width.
120
121 ### Barcode
122
123 ```markdown
124 @barcode CODE128 ${Sku}
125 @barcode EAN13 ${EanCode} height=80
126 ```
127
128 | Field | Values |
129 |-------|--------|
130 | Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A` (v1 subset) |
131 | Data | Literal or `${Param}` |
132 | `height` | Module height in dots (default: 64) |
133 | `align` | `left`, `center`, `right` |
134 | `show_text` | `true` / `false` — HRI below barcode (default: true) |
135
136 ### QR code
137
138 ```markdown
139 @qr https://example.com/receipt/${DocumentNumber}
140 @qr ${PaymentUrl} size=6
141 ```
142
143 | Attribute | Description |
144 |-----------|-------------|
145 | Data (positional) | URL or text; may include `${Param}` |
146 | `size` | Module size 1–16 (default: 4) |
147 | `ecc` | Error correction: `L`, `M`, `Q`, `H` (default: `M`) |
148 | `align` | `left`, `center`, `right` |
149
150 ---
151
152 ## Parameters
153
154 ### Syntax
155
156 ```
157 ${ParameterName}
158 ```
159
160 - **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
161 - **Case-sensitive:** `${DocNo}` and `${docno}` are different
162 - **Uniqueness at input:** all occurrences of the same name share one value entered at print time
163
164 ### Where parameters are allowed
165
166 | Location | Example |
167 |----------|---------|
168 | Text | `Order ${OrderId}` |
169 | Barcode data | `@barcode CODE128 ${OrderId}` |
170 | QR data | `@qr ${VerifyUrl}` |
171 | Image path | `@image ${LogoPath}` |
172
173 ### Print-time behavior
174
175 1. Before print, scan AST for all `${...}` tokens.
176 2. Deduplicate by name.
177 3. Show dialog with one field per unique name.
178 4. Pre-fill from last print session (global or per-file — implementation choice).
179 5. Substitute into AST, then render/print.
180
181 Missing parameter at print time: block print and highlight unresolved names in UI.
182
183 ---
184
185 ## Comments
186
187 ```markdown
188 <!-- This is a comment, not printed -->
189 ```
190
191 HTML-style comments are stripped at parse time.
192
193 ---
194
195 ## Example document
196
197 ```markdown
198 # ${StoreName}
199 :center:
200
201 123 Main Street
202 Tel: ${StorePhone}
203
204 ---
205 Date: ${Date} Time: ${Time}
206 Receipt: ${DocumentNumber}
207
208 Item Total
209 ${LineItems}
210
211 ---
212 :right:
213 **TOTAL: ${GrandTotal}**
214
215 @barcode CODE128 ${DocumentNumber}
216 @feed 2
217 @qr https://shop.example.com/r/${DocumentNumber}
218
219 Thank you!
220 @feed 4
221 @cut
222 ```
223
224 `${LineItems}` might be pre-formatted multi-line text passed as a single parameter (v1); structured line items are a future extension.
225
226 ---
227
228 ## Parse errors
229
230 The parser reports:
231
232 - Unknown directive
233 - Invalid barcode symbology
234 - Unclosed `**` or `` ` ``
235 - Invalid `${}` name
236 - Missing required directive argument
237
238 Errors include 1-based line and column for editor highlighting.
239
240 ---
241
242 ## ESC/POS mapping (summary)
243
244 | DSL | ESC/POS |
245 |-----|---------|
246 | `# heading` | Double width/height ON → text → OFF |
247 | `**bold**` | Bold ON/OFF |
248 | `:center:` | Justification center |
249 | `@feed n` | Print and feed n lines |
250 | `@cut` | GS V partial cut |
251 | `@barcode` | GS k / CODE128 native |
252 | `@qr` | GS ( k QR model 2 |
253 | `@image` | GS v 0 raster bit image |
254
255 Full command details live in the print encoder module; see [PRINTING.md](PRINTING.md).
256
257 ---
258
259 ## Future extensions (not v1)
260
261 - `@table` for columnar line items
262 - Conditionals: `@if ${HasDiscount} ... @endif`
263 - Loops / repeating sections
264 - `@signature` for custom ESC/POS hex escape
265 - Multiple code pages / Unicode subset
@@ -0,0 +1,265 @@
1# Document DSL specification
2
3A lightweight, markdown-inspired syntax for POS receipt templates. The DSL compiles to an AST and then to ESC/POS bytes or a screen preview.
4
5**Design goals:** easy to author, line-oriented, explicit about POS-specific features (barcodes, cut, feed), parameter-friendly.
6
7---
8
9## Document structure
10
11A document is a sequence of **blocks** separated by blank lines. Blocks cannot be nested except for inline markup within text blocks.
12
13---
14
15## Text blocks
16
17### Paragraphs
18
19Plain text with optional inline markup. One or more consecutive non-empty lines form a paragraph.
20
21```markdown
22Thank you for your purchase!
23Visit us again soon.
24```
25
26### Headings
27
28```markdown
29# Store Name
30## Receipt
31```
32
33- `#` → large / double-height text (ESC/POS emphasis)
34- `##` → bold emphasis
35- Maximum two levels in v1
36
37### Alignment
38
39Prefix a paragraph with alignment markers:
40
41```markdown
42:center:
43Your Store Name
44
45:right:
46Total: ${Amount}
47```
48
49| Marker | Effect |
50|--------|--------|
51| `:left:` | Left (default) |
52| `:center:` | Centered |
53| `:right:` | Right-aligned |
54
55### Inline markup
56
57| Syntax | Effect |
58|--------|--------|
59| `**text**` | Bold |
60| `*text*` | Italic / emphasized (printer secondary font if available) |
61| `` `text` `` | Monospace / condensed |
62| `${Name}` | Parameter placeholder (see Parameters) |
63
64Parameters work inside any text, and inside barcode/QR/image directives (below).
65
66**Example:**
67
68```markdown
69Receipt #${DocumentNumber}
70Date: ${Date}
71
72Item: ${ItemName} **${LineTotal}**
73```
74
75### Horizontal rule
76
77```markdown
78---
79```
80
81Renders a dashed or solid separator line across the print width.
82
83---
84
85## Directives (block-level)
86
87Directives start with `@` at the beginning of a line.
88
89### Feed (blank lines)
90
91```markdown
92@feed 3
93```
94
95Advances paper by *n* lines.
96
97### Cut
98
99```markdown
100@cut
101```
102
103Partial cut after content (if printer supports). Often placed at document end.
104
105### Image
106
107```markdown
108@image path/to/logo.png
109@image ${LogoPath} width=50%
110@image assets/qr-promo.png width=384
111```
112
113| Attribute | Description |
114|-----------|-------------|
115| `path` (positional) | File path relative to `.pos` file or absolute; may be `${Param}` |
116| `width` | `NN%` of printable width, or absolute dots (e.g. `384`) |
117| `align` | `left` (default), `center`, `right` |
118
119Images are converted to monochrome raster data, dithered, and scaled to width.
120
121### Barcode
122
123```markdown
124@barcode CODE128 ${Sku}
125@barcode EAN13 ${EanCode} height=80
126```
127
128| Field | Values |
129|-------|--------|
130| Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A` (v1 subset) |
131| Data | Literal or `${Param}` |
132| `height` | Module height in dots (default: 64) |
133| `align` | `left`, `center`, `right` |
134| `show_text` | `true` / `false` — HRI below barcode (default: true) |
135
136### QR code
137
138```markdown
139@qr https://example.com/receipt/${DocumentNumber}
140@qr ${PaymentUrl} size=6
141```
142
143| Attribute | Description |
144|-----------|-------------|
145| Data (positional) | URL or text; may include `${Param}` |
146| `size` | Module size 1–16 (default: 4) |
147| `ecc` | Error correction: `L`, `M`, `Q`, `H` (default: `M`) |
148| `align` | `left`, `center`, `right` |
149
150---
151
152## Parameters
153
154### Syntax
155
156```
157${ParameterName}
158```
159
160- **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
161- **Case-sensitive:** `${DocNo}` and `${docno}` are different
162- **Uniqueness at input:** all occurrences of the same name share one value entered at print time
163
164### Where parameters are allowed
165
166| Location | Example |
167|----------|---------|
168| Text | `Order ${OrderId}` |
169| Barcode data | `@barcode CODE128 ${OrderId}` |
170| QR data | `@qr ${VerifyUrl}` |
171| Image path | `@image ${LogoPath}` |
172
173### Print-time behavior
174
1751. Before print, scan AST for all `${...}` tokens.
1762. Deduplicate by name.
1773. Show dialog with one field per unique name.
1784. Pre-fill from last print session (global or per-file — implementation choice).
1795. Substitute into AST, then render/print.
180
181Missing parameter at print time: block print and highlight unresolved names in UI.
182
183---
184
185## Comments
186
187```markdown
188<!-- This is a comment, not printed -->
189```
190
191HTML-style comments are stripped at parse time.
192
193---
194
195## Example document
196
197```markdown
198# ${StoreName}
199:center:
200
201123 Main Street
202Tel: ${StorePhone}
203
204---
205Date: ${Date} Time: ${Time}
206Receipt: ${DocumentNumber}
207
208Item Total
209${LineItems}
210
211---
212:right:
213**TOTAL: ${GrandTotal}**
214
215@barcode CODE128 ${DocumentNumber}
216@feed 2
217@qr https://shop.example.com/r/${DocumentNumber}
218
219Thank you!
220@feed 4
221@cut
222```
223
224`${LineItems}` might be pre-formatted multi-line text passed as a single parameter (v1); structured line items are a future extension.
225
226---
227
228## Parse errors
229
230The parser reports:
231
232- Unknown directive
233- Invalid barcode symbology
234- Unclosed `**` or `` ` ``
235- Invalid `${}` name
236- Missing required directive argument
237
238Errors include 1-based line and column for editor highlighting.
239
240---
241
242## ESC/POS mapping (summary)
243
244| DSL | ESC/POS |
245|-----|---------|
246| `# heading` | Double width/height ON → text → OFF |
247| `**bold**` | Bold ON/OFF |
248| `:center:` | Justification center |
249| `@feed n` | Print and feed n lines |
250| `@cut` | GS V partial cut |
251| `@barcode` | GS k / CODE128 native |
252| `@qr` | GS ( k QR model 2 |
253| `@image` | GS v 0 raster bit image |
254
255Full command details live in the print encoder module; see [PRINTING.md](PRINTING.md).
256
257---
258
259## Future extensions (not v1)
260
261- `@table` for columnar line items
262- Conditionals: `@if ${HasDiscount} ... @endif`
263- Loops / repeating sections
264- `@signature` for custom ESC/POS hex escape
265- Multiple code pages / Unicode subset
docs/FEASIBILITY.md added +163 −0
@@ -0,0 +1,163 @@
1 # Feasibility and complexity assessment
2
3 ## Executive summary
4
5 | Question | Answer |
6 |----------|--------|
7 | Is it feasible? | **Yes** — all required capabilities exist in mature libraries or documented protocols |
8 | Overall complexity | **Medium–high** for a complete v1; **medium** if Bluetooth is deferred |
9 | Biggest risk | Cross-platform raw printer I/O (USB class, serial, Bluetooth SPP) |
10 | Recommended MVP scope | USB-serial printers first; add USB-printer-class and Bluetooth in v1.1 |
11
12 A focused MVP is realistic for one developer in roughly **6–10 weeks**. A polished v1 with broad printer compatibility is closer to **3–4 months**.
13
14 ---
15
16 ## Requirements breakdown
17
18 ### 1. Cross-platform desktop app (Windows + Linux)
19
20 | Aspect | Feasibility | Complexity |
21 |--------|-------------|------------|
22 | Single codebase, native binaries | High | Low–medium |
23 | Packaged installers (.msi/.exe, .deb/AppImage) | High | Medium |
24
25 Modern cross-platform desktop frameworks (Tauri, egui, Avalonia, Qt) all support Windows and Linux. Packaging is routine but needs CI and per-OS testing.
26
27 ### 2. Markdown-like document syntax + live preview
28
29 | Aspect | Feasibility | Complexity |
30 |--------|-------------|------------|
31 | Custom lightweight DSL | High | Medium |
32 | Live preview pane | High | Medium |
33 | Width modes (auto-scale / fixed mm) | High | Low–medium |
34
35 The DSL does not need full CommonMark — a small, POS-oriented grammar keeps the parser simple. Preview renders to a monospace layout matching printer dot width (e.g. 384 dots @ 58 mm, 576 dots @ 80 mm). Matching exact printer fonts is approximate in preview; exact fidelity is only guaranteed at print time.
36
37 ### 3. Save / load `.pos` files
38
39 | Aspect | Feasibility | Complexity |
40 |--------|-------------|------------|
41 | JSON or TOML envelope + body text | High | Low |
42
43 Trivial with serde (Rust) or equivalent. Version field supports forward-compatible evolution.
44
45 ### 4. Parameter tokens (`${Name}`)
46
47 | Aspect | Feasibility | Complexity |
48 |--------|-------------|------------|
49 | Parse and collect unique names | High | Low |
50 | Print-time modal with last-used values | High | Low |
51 | Deduplicate same name across document | High | Low |
52 | Use in text, barcodes, QR, images | High | Low–medium |
53
54 Straightforward string substitution after validation. Image parameters might reference file paths or base64 — define clearly in DSL spec.
55
56 ### 5. Barcodes, QR codes, images
57
58 | Aspect | Feasibility | Complexity |
59 |--------|-------------|------------|
60 | Generate ESC/POS barcode commands | High | Low |
61 | Generate ESC/POS QR commands | High | Low |
62 | Rasterize images to printer width | High | Medium |
63
64 The [`escpos`](https://crates.io/crates/escpos) Rust crate (and similar libraries in other languages) already implements barcodes, QR, and raster graphics. Preview can use the same generation path and render bitmaps in the UI.
65
66 ### 6. Direct USB / Bluetooth printing (raw bytes, no spooler)
67
68 | Aspect | Feasibility | Complexity |
69 |--------|-------------|------------|
70 | USB serial (CDC-ACM, CH340, FTDI) | **High** | Medium |
71 | USB printer class (bulk OUT) | Medium | **High** |
72 | Bluetooth Classic SPP | Medium | **High** |
73 | Enumerate devices in UI | Medium | Medium |
74 | Printer-specific quirks | Ongoing | **High** |
75
76 This is the **primary technical risk**.
77
78 #### How POS printers actually connect
79
80 Most consumer thermal printers expose one of:
81
82 1. **Virtual COM port (USB-serial)** — very common; appears as `COM3` (Windows) or `/dev/ttyUSB0` / `/dev/ttyACM0` (Linux). Raw ESC/POS bytes are written to the serial port. **Easiest path.**
83
84 2. **USB printer class (interface 7)** — bulk transfers to endpoint; needs `libusb`/`nusb` on Linux and either WinUSB/Zadig or Windows `usbprint.sys` on Windows. The `escpos` crate’s `usbprint` feature uses the Windows kernel driver without replacing it.
85
86 3. **Bluetooth Classic SPP** — serial profile; paired device appears as a COM port (Windows) or `/dev/rfcomm*` (Linux). Requires platform Bluetooth APIs for discovery; connection is then serial I/O.
87
88 4. **Network (TCP 9100)** — common in production but **out of scope** unless added later.
89
90 “No drivers” in practice means **no Windows print spooler / CUPS job** — the app opens the device directly and writes bytes. USB-serial devices often need only the generic CDC driver already present. USB-printer-class devices on Windows may still use `usbprint.sys`, which is a kernel driver but not a vendor-specific print driver.
91
92 #### Compatibility reality
93
94 - **MVP:** Target Epson-compatible ESC/POS over USB-serial. Covers a large share of cheap 58/80 mm printers.
95 - **v1:** Add USB printer class via `nusb` / `usbprint`.
96 - **v1.1:** Add Bluetooth SPP discovery and pairing UX.
97
98 Expect **per-printer testing**; some devices need init sequences, code pages, or cut commands that differ slightly.
99
100 ---
101
102 ## Complexity by subsystem
103
104 ```
105 Effort (relative)
106 Editor UI ████████░░ Medium
107 Preview renderer ███████░░░ Medium
108 DSL parser ██████░░░░ Medium
109 File I/O ██░░░░░░░░ Low
110 Parameters ███░░░░░░░ Low
111 Barcode/QR/image █████░░░░░ Low–medium
112 Printer discovery ███████░░░ Medium
113 Raw print I/O █████████░ High
114 Integration/polish ██████░░░░ Medium
115 ```
116
117 ---
118
119 ## Effort estimate (one experienced developer)
120
121 | Phase | Scope | Duration |
122 |-------|-------|----------|
123 | **0 — Design** | Specs, DSL, file format | 1 week |
124 | **1 — Core** | Parser, ESC/POS builder, preview, `.pos` I/O | 2–3 weeks |
125 | **2 — UI** | Editor, preview split, settings, parameters dialog | 2 weeks |
126 | **3 — Print MVP** | USB-serial enumeration + print | 1–2 weeks |
127 | **4 — Hardening** | USB class, BT, edge cases, packaging | 2–4 weeks |
128
129 **MVP (serial USB only):** ~6–8 weeks
130 **Full v1 (USB + BT, packaged):** ~10–14 weeks
131
132 Add 30–50% if the developer is new to Rust or ESC/POS.
133
134 ---
135
136 ## Risks and mitigations
137
138 | Risk | Impact | Mitigation |
139 |------|--------|------------|
140 | Printer hardware diversity | Prints garbled or not at all | ESC/POS subset doc; test matrix; user-selectable code page |
141 | Linux permissions (`dialout`) | Cannot open serial port | Document group membership; clear error UI |
142 | Windows USB access | Admin / driver conflicts | Prefer serial-first; use `usbprint` where applicable |
143 | Bluetooth pairing UX | Users cannot find printer | Defer BT; link to OS pairing instructions |
144 | Preview ≠ print | User confusion | Label preview as approximate; same backend for print |
145 | Image size on narrow paper | Slow print or clipped | Auto-scale to page width; warn in UI |
146
147 ---
148
149 ## Out of scope (v1)
150
151 - Network printers (TCP 9100)
152 - Non-ESC/POS protocols (Star Line, ZPL)
153 - Multi-column layout engines
154 - Collaborative editing / cloud sync
155 - macOS (feasible later with same stack)
156
157 ---
158
159 ## Recommendation
160
161 **Proceed.** Start with a **serial-USB MVP** on **Rust + Tauri 2**, prove the DSL and preview loop, then expand transport layers. Defer Bluetooth until USB paths are stable.
162
163 See [LANGUAGE-CHOICE.md](LANGUAGE-CHOICE.md) for stack details and [ARCHITECTURE.md](ARCHITECTURE.md) for module layout.
@@ -0,0 +1,163 @@
1# Feasibility and complexity assessment
2
3## Executive summary
4
5| Question | Answer |
6|----------|--------|
7| Is it feasible? | **Yes** — all required capabilities exist in mature libraries or documented protocols |
8| Overall complexity | **Medium–high** for a complete v1; **medium** if Bluetooth is deferred |
9| Biggest risk | Cross-platform raw printer I/O (USB class, serial, Bluetooth SPP) |
10| Recommended MVP scope | USB-serial printers first; add USB-printer-class and Bluetooth in v1.1 |
11
12A focused MVP is realistic for one developer in roughly **6–10 weeks**. A polished v1 with broad printer compatibility is closer to **3–4 months**.
13
14---
15
16## Requirements breakdown
17
18### 1. Cross-platform desktop app (Windows + Linux)
19
20| Aspect | Feasibility | Complexity |
21|--------|-------------|------------|
22| Single codebase, native binaries | High | Low–medium |
23| Packaged installers (.msi/.exe, .deb/AppImage) | High | Medium |
24
25Modern cross-platform desktop frameworks (Tauri, egui, Avalonia, Qt) all support Windows and Linux. Packaging is routine but needs CI and per-OS testing.
26
27### 2. Markdown-like document syntax + live preview
28
29| Aspect | Feasibility | Complexity |
30|--------|-------------|------------|
31| Custom lightweight DSL | High | Medium |
32| Live preview pane | High | Medium |
33| Width modes (auto-scale / fixed mm) | High | Low–medium |
34
35The DSL does not need full CommonMark — a small, POS-oriented grammar keeps the parser simple. Preview renders to a monospace layout matching printer dot width (e.g. 384 dots @ 58 mm, 576 dots @ 80 mm). Matching exact printer fonts is approximate in preview; exact fidelity is only guaranteed at print time.
36
37### 3. Save / load `.pos` files
38
39| Aspect | Feasibility | Complexity |
40|--------|-------------|------------|
41| JSON or TOML envelope + body text | High | Low |
42
43Trivial with serde (Rust) or equivalent. Version field supports forward-compatible evolution.
44
45### 4. Parameter tokens (`${Name}`)
46
47| Aspect | Feasibility | Complexity |
48|--------|-------------|------------|
49| Parse and collect unique names | High | Low |
50| Print-time modal with last-used values | High | Low |
51| Deduplicate same name across document | High | Low |
52| Use in text, barcodes, QR, images | High | Low–medium |
53
54Straightforward string substitution after validation. Image parameters might reference file paths or base64 — define clearly in DSL spec.
55
56### 5. Barcodes, QR codes, images
57
58| Aspect | Feasibility | Complexity |
59|--------|-------------|------------|
60| Generate ESC/POS barcode commands | High | Low |
61| Generate ESC/POS QR commands | High | Low |
62| Rasterize images to printer width | High | Medium |
63
64The [`escpos`](https://crates.io/crates/escpos) Rust crate (and similar libraries in other languages) already implements barcodes, QR, and raster graphics. Preview can use the same generation path and render bitmaps in the UI.
65
66### 6. Direct USB / Bluetooth printing (raw bytes, no spooler)
67
68| Aspect | Feasibility | Complexity |
69|--------|-------------|------------|
70| USB serial (CDC-ACM, CH340, FTDI) | **High** | Medium |
71| USB printer class (bulk OUT) | Medium | **High** |
72| Bluetooth Classic SPP | Medium | **High** |
73| Enumerate devices in UI | Medium | Medium |
74| Printer-specific quirks | Ongoing | **High** |
75
76This is the **primary technical risk**.
77
78#### How POS printers actually connect
79
80Most consumer thermal printers expose one of:
81
821. **Virtual COM port (USB-serial)** — very common; appears as `COM3` (Windows) or `/dev/ttyUSB0` / `/dev/ttyACM0` (Linux). Raw ESC/POS bytes are written to the serial port. **Easiest path.**
83
842. **USB printer class (interface 7)** — bulk transfers to endpoint; needs `libusb`/`nusb` on Linux and either WinUSB/Zadig or Windows `usbprint.sys` on Windows. The `escpos` crate’s `usbprint` feature uses the Windows kernel driver without replacing it.
85
863. **Bluetooth Classic SPP** — serial profile; paired device appears as a COM port (Windows) or `/dev/rfcomm*` (Linux). Requires platform Bluetooth APIs for discovery; connection is then serial I/O.
87
884. **Network (TCP 9100)** — common in production but **out of scope** unless added later.
89
90“No drivers” in practice means **no Windows print spooler / CUPS job** — the app opens the device directly and writes bytes. USB-serial devices often need only the generic CDC driver already present. USB-printer-class devices on Windows may still use `usbprint.sys`, which is a kernel driver but not a vendor-specific print driver.
91
92#### Compatibility reality
93
94- **MVP:** Target Epson-compatible ESC/POS over USB-serial. Covers a large share of cheap 58/80 mm printers.
95- **v1:** Add USB printer class via `nusb` / `usbprint`.
96- **v1.1:** Add Bluetooth SPP discovery and pairing UX.
97
98Expect **per-printer testing**; some devices need init sequences, code pages, or cut commands that differ slightly.
99
100---
101
102## Complexity by subsystem
103
104```
105 Effort (relative)
106Editor UI ████████░░ Medium
107Preview renderer ███████░░░ Medium
108DSL parser ██████░░░░ Medium
109File I/O ██░░░░░░░░ Low
110Parameters ███░░░░░░░ Low
111Barcode/QR/image █████░░░░░ Low–medium
112Printer discovery ███████░░░ Medium
113Raw print I/O █████████░ High
114Integration/polish ██████░░░░ Medium
115```
116
117---
118
119## Effort estimate (one experienced developer)
120
121| Phase | Scope | Duration |
122|-------|-------|----------|
123| **0 — Design** | Specs, DSL, file format | 1 week |
124| **1 — Core** | Parser, ESC/POS builder, preview, `.pos` I/O | 2–3 weeks |
125| **2 — UI** | Editor, preview split, settings, parameters dialog | 2 weeks |
126| **3 — Print MVP** | USB-serial enumeration + print | 1–2 weeks |
127| **4 — Hardening** | USB class, BT, edge cases, packaging | 2–4 weeks |
128
129**MVP (serial USB only):** ~6–8 weeks
130**Full v1 (USB + BT, packaged):** ~10–14 weeks
131
132Add 30–50% if the developer is new to Rust or ESC/POS.
133
134---
135
136## Risks and mitigations
137
138| Risk | Impact | Mitigation |
139|------|--------|------------|
140| Printer hardware diversity | Prints garbled or not at all | ESC/POS subset doc; test matrix; user-selectable code page |
141| Linux permissions (`dialout`) | Cannot open serial port | Document group membership; clear error UI |
142| Windows USB access | Admin / driver conflicts | Prefer serial-first; use `usbprint` where applicable |
143| Bluetooth pairing UX | Users cannot find printer | Defer BT; link to OS pairing instructions |
144| Preview ≠ print | User confusion | Label preview as approximate; same backend for print |
145| Image size on narrow paper | Slow print or clipped | Auto-scale to page width; warn in UI |
146
147---
148
149## Out of scope (v1)
150
151- Network printers (TCP 9100)
152- Non-ESC/POS protocols (Star Line, ZPL)
153- Multi-column layout engines
154- Collaborative editing / cloud sync
155- macOS (feasible later with same stack)
156
157---
158
159## Recommendation
160
161**Proceed.** Start with a **serial-USB MVP** on **Rust + Tauri 2**, prove the DSL and preview loop, then expand transport layers. Defer Bluetooth until USB paths are stable.
162
163See [LANGUAGE-CHOICE.md](LANGUAGE-CHOICE.md) for stack details and [ARCHITECTURE.md](ARCHITECTURE.md) for module layout.
docs/FILE-FORMAT.md added +145 −0
@@ -0,0 +1,145 @@
1 # `.pos` file format
2
3 A `.pos` file stores a POS print template: metadata (page settings, title) plus the DSL document body as plain text.
4
5 **Format:** JSON envelope with a `.pos` extension (human-readable, git-friendly).
6 **MIME type (suggested):** `application/vnd.posprint+json`
7
8 ---
9
10 ## Top-level schema
11
12 ```json
13 {
14 "version": 1,
15 "metadata": { ... },
16 "body": "..."
17 }
18 ```
19
20 | Field | Type | Required | Description |
21 |-------|------|----------|-------------|
22 | `version` | `number` | yes | File format version (currently `1`) |
23 | `metadata` | `object` | yes | Document settings |
24 | `body` | `string` | yes | DSL source (UTF-8, `\n` line endings normalized on load) |
25
26 ---
27
28 ## Metadata schema (version 1)
29
30 ```json
31 {
32 "title": "Sales Receipt",
33 "page_width_mm": 80,
34 "preview_mode": "autoscale",
35 "chars_per_line": 48,
36 "codepage": "CP437",
37 "cut_after_print": true,
38 "default_feed_before_cut": 4
39 }
40 ```
41
42 | Field | Type | Default | Description |
43 |-------|------|---------|-------------|
44 | `title` | `string?` | `null` | Display name in app title / recent files |
45 | `page_width_mm` | `number` | `80` | Physical paper width: `58` or `80` (others allowed) |
46 | `preview_mode` | `"autoscale"` \| `"fixed"` | `"autoscale"` | How preview panel sizes content |
47 | `chars_per_line` | `number?` | derived | Override character width for preview; derived from mm if omitted |
48 | `codepage` | `string?` | `"CP437"` | Character encoding for ESC/POS text |
49 | `cut_after_print` | `boolean` | `true` | Append cut command when printing if doc has no `@cut` |
50 | `default_feed_before_cut` | `number` | `4` | Feed lines before auto-cut |
51
52 ### Page width derivation
53
54 | `page_width_mm` | Typical dots (203 DPI) | Default `chars_per_line` (Font A) |
55 |-----------------|------------------------|-----------------------------------|
56 | 58 | 384 | 32 |
57 | 80 | 576 | 48 |
58
59 ---
60
61 ## Example file
62
63 **`receipt.pos`:**
64
65 ```json
66 {
67 "version": 1,
68 "metadata": {
69 "title": "Standard Receipt",
70 "page_width_mm": 80,
71 "preview_mode": "autoscale",
72 "codepage": "CP437",
73 "cut_after_print": true
74 },
75 "body": "# ${StoreName}\n:center:\n\nReceipt: ${DocumentNumber}\n\n---\n\n:right:\n**TOTAL: ${GrandTotal}**\n\n@barcode CODE128 ${DocumentNumber}\n@feed 4\n@cut\n"
76 }
77 ```
78
79 For readability, the app may save `body` with literal newlines (pretty-printed JSON) when the user chooses “formatted save”; both pretty and escaped forms are valid.
80
81 ---
82
83 ## Asset resolution
84
85 - Paths in `@image` directives are resolved relative to the **directory containing the `.pos` file** unless absolute.
86 - Bundled assets: optional `assets/` subfolder next to the template.
87 - Parameterized image paths (`${LogoPath}`) resolve after substitution; relative paths still anchor to the `.pos` file directory.
88
89 ---
90
91 ## Version migration
92
93 | From | To | Migration |
94 |------|-----|-----------|
95 | — | 1 | Initial release |
96
97 On load, if `version` is newer than app supports → error with upgrade message.
98 If older → run migration chain (none yet).
99
100 ---
101
102 ## Alternative considered: two-file bundle
103
104 Rejected for v1: `.pos` + sidecar `.pos.json` adds friction. Single JSON file keeps save/load atomic.
105
106 A future `.poszip` could bundle images for portable templates.
107
108 ---
109
110 ## Validation rules
111
112 On save:
113
114 - `version` must equal supported version
115 - `page_width_mm` > 0
116 - `body` must be valid UTF-8
117
118 On load:
119
120 - Parse JSON; validate schema
121 - Parse `body` with DSL parser; warnings shown in UI but file still loads
122
123 ---
124
125 ## TypeScript / Rust types (reference)
126
127 ```typescript
128 interface PosFile {
129 version: number;
130 metadata: PosMetadata;
131 body: string;
132 }
133
134 interface PosMetadata {
135 title?: string;
136 page_width_mm: number;
137 preview_mode: "autoscale" | "fixed";
138 chars_per_line?: number;
139 codepage?: string;
140 cut_after_print?: boolean;
141 default_feed_before_cut?: number;
142 }
143 ```
144
145 Rust mirrors these with `serde` derive for 1:1 IPC across Tauri.
@@ -0,0 +1,145 @@
1# `.pos` file format
2
3A `.pos` file stores a POS print template: metadata (page settings, title) plus the DSL document body as plain text.
4
5**Format:** JSON envelope with a `.pos` extension (human-readable, git-friendly).
6**MIME type (suggested):** `application/vnd.posprint+json`
7
8---
9
10## Top-level schema
11
12```json
13{
14 "version": 1,
15 "metadata": { ... },
16 "body": "..."
17}
18```
19
20| Field | Type | Required | Description |
21|-------|------|----------|-------------|
22| `version` | `number` | yes | File format version (currently `1`) |
23| `metadata` | `object` | yes | Document settings |
24| `body` | `string` | yes | DSL source (UTF-8, `\n` line endings normalized on load) |
25
26---
27
28## Metadata schema (version 1)
29
30```json
31{
32 "title": "Sales Receipt",
33 "page_width_mm": 80,
34 "preview_mode": "autoscale",
35 "chars_per_line": 48,
36 "codepage": "CP437",
37 "cut_after_print": true,
38 "default_feed_before_cut": 4
39}
40```
41
42| Field | Type | Default | Description |
43|-------|------|---------|-------------|
44| `title` | `string?` | `null` | Display name in app title / recent files |
45| `page_width_mm` | `number` | `80` | Physical paper width: `58` or `80` (others allowed) |
46| `preview_mode` | `"autoscale"` \| `"fixed"` | `"autoscale"` | How preview panel sizes content |
47| `chars_per_line` | `number?` | derived | Override character width for preview; derived from mm if omitted |
48| `codepage` | `string?` | `"CP437"` | Character encoding for ESC/POS text |
49| `cut_after_print` | `boolean` | `true` | Append cut command when printing if doc has no `@cut` |
50| `default_feed_before_cut` | `number` | `4` | Feed lines before auto-cut |
51
52### Page width derivation
53
54| `page_width_mm` | Typical dots (203 DPI) | Default `chars_per_line` (Font A) |
55|-----------------|------------------------|-----------------------------------|
56| 58 | 384 | 32 |
57| 80 | 576 | 48 |
58
59---
60
61## Example file
62
63**`receipt.pos`:**
64
65```json
66{
67 "version": 1,
68 "metadata": {
69 "title": "Standard Receipt",
70 "page_width_mm": 80,
71 "preview_mode": "autoscale",
72 "codepage": "CP437",
73 "cut_after_print": true
74 },
75 "body": "# ${StoreName}\n:center:\n\nReceipt: ${DocumentNumber}\n\n---\n\n:right:\n**TOTAL: ${GrandTotal}**\n\n@barcode CODE128 ${DocumentNumber}\n@feed 4\n@cut\n"
76}
77```
78
79For readability, the app may save `body` with literal newlines (pretty-printed JSON) when the user chooses “formatted save”; both pretty and escaped forms are valid.
80
81---
82
83## Asset resolution
84
85- Paths in `@image` directives are resolved relative to the **directory containing the `.pos` file** unless absolute.
86- Bundled assets: optional `assets/` subfolder next to the template.
87- Parameterized image paths (`${LogoPath}`) resolve after substitution; relative paths still anchor to the `.pos` file directory.
88
89---
90
91## Version migration
92
93| From | To | Migration |
94|------|-----|-----------|
95| — | 1 | Initial release |
96
97On load, if `version` is newer than app supports → error with upgrade message.
98If older → run migration chain (none yet).
99
100---
101
102## Alternative considered: two-file bundle
103
104Rejected for v1: `.pos` + sidecar `.pos.json` adds friction. Single JSON file keeps save/load atomic.
105
106A future `.poszip` could bundle images for portable templates.
107
108---
109
110## Validation rules
111
112On save:
113
114- `version` must equal supported version
115- `page_width_mm` > 0
116- `body` must be valid UTF-8
117
118On load:
119
120- Parse JSON; validate schema
121- Parse `body` with DSL parser; warnings shown in UI but file still loads
122
123---
124
125## TypeScript / Rust types (reference)
126
127```typescript
128interface PosFile {
129 version: number;
130 metadata: PosMetadata;
131 body: string;
132}
133
134interface PosMetadata {
135 title?: string;
136 page_width_mm: number;
137 preview_mode: "autoscale" | "fixed";
138 chars_per_line?: number;
139 codepage?: string;
140 cut_after_print?: boolean;
141 default_feed_before_cut?: number;
142}
143```
144
145Rust mirrors these with `serde` derive for 1:1 IPC across Tauri.
docs/HELP.md added +210 −0
@@ -0,0 +1,210 @@
1 # posprint Help
2
3 Built-in reference for the template editor and POS markup language.
4
5 ---
6
7 ## Application tabs
8
9 | Tab | Purpose |
10 |-----|---------|
11 | **Editor** | Write and edit template source |
12 | **Preview** | Live preview of rendered output |
13 | **Help** | This documentation |
14
15 ## Toolbar actions
16
17 | Action | Description |
18 |--------|-------------|
19 | **New** | Empty template with defaults |
20 | **Open** | Load a `.pos` file |
21 | **Save / Save As** | Write JSON `.pos` file (metadata + body) |
22 | **Print** | Substitute parameters, pick USB printer, send ESC/POS bytes |
23
24 ## Page settings
25
26 | Setting | Description |
27 |---------|-------------|
28 | **Page width (mm)** | Paper width, typically `58` or `80` |
29 | **Preview mode** | `Auto-scale` fits preview to panel; `Fixed` uses exact mm width |
30 | **Code page** | Character encoding sent to printer (default `CP437`) |
31 | **Cut after print** | Append paper feed + cut if template has no `@cut` |
32
33 ---
34
35 ## Template language
36
37 A template is plain text: paragraphs, headings, directives, and inline markup.
38
39 ### Paragraphs
40
41 Consecutive non-empty lines form one paragraph.
42
43 ```markdown
44 Thank you for your visit!
45 Please come again.
46 ```
47
48 ### Headings
49
50 ```markdown
51 # Large heading (store name)
52 ## Bold heading (section title)
53 ```
54
55 ### Alignment
56
57 Prefix a paragraph with `:left:`, `:center:`, or `:right:` (default is left).
58
59 ```markdown
60 :center:
61 Your Store Name
62 ```
63
64 ### Inline markup
65
66 | Syntax | Effect |
67 |--------|--------|
68 | `**text**` | Bold |
69 | `*text*` | Italic |
70 | `` `text` `` | Monospace |
71 | `${Name}` | Parameter (filled at print time) |
72
73 ### Horizontal rule
74
75 ```markdown
76 ---
77 ```
78
79 ### Comments (not printed)
80
81 ```markdown
82 <!-- note to designer only -->
83 ```
84
85 ---
86
87 ## Directives
88
89 Directives start with `@` at the beginning of a line.
90
91 ### Paper feed
92
93 ```markdown
94 @feed 3
95 ```
96
97 Feeds three blank lines.
98
99 ### Cut paper
100
101 ```markdown
102 @cut
103 ```
104
105 Partial cut (if the printer supports it).
106
107 ### Image
108
109 ```markdown
110 @image logo.png
111 @image ${LogoPath} width=50%
112 @image promo.png width=384 align=center
113 ```
114
115 | Attribute | Description |
116 |-----------|-------------|
117 | Path | File relative to the `.pos` file, or `${Parameter}` |
118 | `width` | `NN%` of printable width or dots (e.g. `384`) |
119 | `align` | `left`, `center`, `right` |
120
121 ### Barcode
122
123 ```markdown
124 @barcode CODE128 ${OrderId}
125 @barcode EAN13 5901234123457 height=80 show_text=true
126 ```
127
128 | Field | Values |
129 |-------|--------|
130 | Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39` |
131 | Data | Literal text or `${Parameter}` |
132 | `height` | Height in dots (default `64`) |
133 | `align` | `left`, `center`, `right` |
134 | `show_text` | `true` / `false` — human-readable text under barcode |
135
136 ### QR code
137
138 ```markdown
139 @qr https://example.com/receipt/${DocumentNumber}
140 @qr ${PaymentUrl} size=6 ecc=M align=center
141 ```
142
143 | Attribute | Description |
144 |-----------|-------------|
145 | Data | URL or text; may include `${Parameter}` |
146 | `size` | Module size 1–16 (default `4`) |
147 | `ecc` | Error correction: `L`, `M`, `Q`, `H` |
148 | `align` | `left`, `center`, `right` |
149
150 ---
151
152 ## Parameters
153
154 Write `${ParameterName}` anywhere in text, barcode data, QR data, or image paths.
155
156 - Names: letters, digits, underscore; must start with a letter or `_`.
157 - **Same name → one input** at print time; all occurrences receive the same value.
158 - The print dialog pre-fills values from the last print session.
159
160 ---
161
162 ## Example receipt
163
164 ```markdown
165 # ${StoreName}
166 :center:
167
168 123 Main Street
169
170 ---
171 Receipt: ${DocumentNumber}
172 Date: ${Date}
173
174 ${LineItems}
175
176 ---
177 :right:
178 **TOTAL: ${GrandTotal}**
179
180 @barcode CODE128 ${DocumentNumber}
181 @feed 2
182 @qr https://shop.example.com/r/${DocumentNumber}
183
184 Thank you!
185 @feed 4
186 @cut
187 ```
188
189 ---
190
191 ## Printing (USB)
192
193 1. Click **Print**.
194 2. Enter parameter values in the dialog.
195 3. Choose a USB serial printer from the list (refresh if needed).
196 4. The app sends raw ESC/POS bytes directly to the port (no system print spooler).
197
198 **Linux:** your user must be in the `dialout` group to access serial devices.
199
200 **Windows:** the printer usually appears as `COM3`, `COM4`, etc.
201
202 ---
203
204 ## `.pos` file format
205
206 JSON file with extension `.pos`:
207
208 - `version` — format version (currently `1`)
209 - `metadata` — page width, preview mode, code page, etc.
210 - `body` — template source string
@@ -0,0 +1,210 @@
1# posprint Help
2
3Built-in reference for the template editor and POS markup language.
4
5---
6
7## Application tabs
8
9| Tab | Purpose |
10|-----|---------|
11| **Editor** | Write and edit template source |
12| **Preview** | Live preview of rendered output |
13| **Help** | This documentation |
14
15## Toolbar actions
16
17| Action | Description |
18|--------|-------------|
19| **New** | Empty template with defaults |
20| **Open** | Load a `.pos` file |
21| **Save / Save As** | Write JSON `.pos` file (metadata + body) |
22| **Print** | Substitute parameters, pick USB printer, send ESC/POS bytes |
23
24## Page settings
25
26| Setting | Description |
27|---------|-------------|
28| **Page width (mm)** | Paper width, typically `58` or `80` |
29| **Preview mode** | `Auto-scale` fits preview to panel; `Fixed` uses exact mm width |
30| **Code page** | Character encoding sent to printer (default `CP437`) |
31| **Cut after print** | Append paper feed + cut if template has no `@cut` |
32
33---
34
35## Template language
36
37A template is plain text: paragraphs, headings, directives, and inline markup.
38
39### Paragraphs
40
41Consecutive non-empty lines form one paragraph.
42
43```markdown
44Thank you for your visit!
45Please come again.
46```
47
48### Headings
49
50```markdown
51# Large heading (store name)
52## Bold heading (section title)
53```
54
55### Alignment
56
57Prefix a paragraph with `:left:`, `:center:`, or `:right:` (default is left).
58
59```markdown
60:center:
61Your Store Name
62```
63
64### Inline markup
65
66| Syntax | Effect |
67|--------|--------|
68| `**text**` | Bold |
69| `*text*` | Italic |
70| `` `text` `` | Monospace |
71| `${Name}` | Parameter (filled at print time) |
72
73### Horizontal rule
74
75```markdown
76---
77```
78
79### Comments (not printed)
80
81```markdown
82<!-- note to designer only -->
83```
84
85---
86
87## Directives
88
89Directives start with `@` at the beginning of a line.
90
91### Paper feed
92
93```markdown
94@feed 3
95```
96
97Feeds three blank lines.
98
99### Cut paper
100
101```markdown
102@cut
103```
104
105Partial cut (if the printer supports it).
106
107### Image
108
109```markdown
110@image logo.png
111@image ${LogoPath} width=50%
112@image promo.png width=384 align=center
113```
114
115| Attribute | Description |
116|-----------|-------------|
117| Path | File relative to the `.pos` file, or `${Parameter}` |
118| `width` | `NN%` of printable width or dots (e.g. `384`) |
119| `align` | `left`, `center`, `right` |
120
121### Barcode
122
123```markdown
124@barcode CODE128 ${OrderId}
125@barcode EAN13 5901234123457 height=80 show_text=true
126```
127
128| Field | Values |
129|-------|--------|
130| Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39` |
131| Data | Literal text or `${Parameter}` |
132| `height` | Height in dots (default `64`) |
133| `align` | `left`, `center`, `right` |
134| `show_text` | `true` / `false` — human-readable text under barcode |
135
136### QR code
137
138```markdown
139@qr https://example.com/receipt/${DocumentNumber}
140@qr ${PaymentUrl} size=6 ecc=M align=center
141```
142
143| Attribute | Description |
144|-----------|-------------|
145| Data | URL or text; may include `${Parameter}` |
146| `size` | Module size 1–16 (default `4`) |
147| `ecc` | Error correction: `L`, `M`, `Q`, `H` |
148| `align` | `left`, `center`, `right` |
149
150---
151
152## Parameters
153
154Write `${ParameterName}` anywhere in text, barcode data, QR data, or image paths.
155
156- Names: letters, digits, underscore; must start with a letter or `_`.
157- **Same name → one input** at print time; all occurrences receive the same value.
158- The print dialog pre-fills values from the last print session.
159
160---
161
162## Example receipt
163
164```markdown
165# ${StoreName}
166:center:
167
168123 Main Street
169
170---
171Receipt: ${DocumentNumber}
172Date: ${Date}
173
174${LineItems}
175
176---
177:right:
178**TOTAL: ${GrandTotal}**
179
180@barcode CODE128 ${DocumentNumber}
181@feed 2
182@qr https://shop.example.com/r/${DocumentNumber}
183
184Thank you!
185@feed 4
186@cut
187```
188
189---
190
191## Printing (USB)
192
1931. Click **Print**.
1942. Enter parameter values in the dialog.
1953. Choose a USB serial printer from the list (refresh if needed).
1964. The app sends raw ESC/POS bytes directly to the port (no system print spooler).
197
198**Linux:** your user must be in the `dialout` group to access serial devices.
199
200**Windows:** the printer usually appears as `COM3`, `COM4`, etc.
201
202---
203
204## `.pos` file format
205
206JSON file with extension `.pos`:
207
208- `version` — format version (currently `1`)
209- `metadata` — page width, preview mode, code page, etc.
210- `body` — template source string
docs/LANGUAGE-CHOICE.md added +166 −0
@@ -0,0 +1,166 @@
1 # Language and platform choice
2
3 ## Requirements driving the decision
4
5 | Requirement | Technical implication |
6 |-------------|----------------------|
7 | Windows + Linux binaries | Cross-compile friendly toolchain, native I/O |
8 | Raw USB / serial / Bluetooth | Low-level device access, not browser-only |
9 | ESC/POS byte generation | Binary buffers, barcode/image encoding |
10 | Live preview UI | Responsive editor + rendered preview |
11 | Small distributable | Avoid heavy runtime (no full JVM, prefer no Chromium if possible) |
12 | Long-term maintainability | Strong typing, good deps for hardware |
13
14 ---
15
16 ## Candidates evaluated
17
18 ### Rust + Tauri 2 (recommended)
19
20 | Pros | Cons |
21 |------|------|
22 | Excellent ESC/POS ecosystem (`escpos`, `nusb`, `serialport`) | Rust learning curve |
23 | Tauri 2: small binaries, web UI for editor | Two languages (Rust + TS) |
24 | Proven pattern for serial/USB desktop tools | WebView rendering for preview |
25 | First-class Windows + Linux support | |
26 | `serde` for `.pos` files | |
27
28 **Verdict:** Best fit. Hardware logic stays in Rust; React/Svelte/Vue handles editor UX.
29
30 ### Rust + egui / iced (native UI)
31
32 | Pros | Cons |
33 |------|------|
34 | Single language, single binary | Editor UX more work (no Monaco/CodeMirror out of the box) |
35 | No WebView dependency | Syntax highlighting needs extra crates |
36 | Fast iteration for tools | Less familiar to web developers |
37
38 **Verdict:** Strong alternative if minimizing dependencies matters more than rich editor UX.
39
40 ### C# + Avalonia
41
42 | Pros | Cons |
43 |------|------|
44 | Good desktop UI | USB/BT raw I/O less ergonomic than Rust |
45 | Cross-platform .NET | Larger runtime |
46 | Familiar if team is .NET | ESC/POS libs thinner than Rust |
47
48 **Verdict:** Viable if the team is already .NET-heavy.
49
50 ### Go + Fyne / Wails
51
52 | Pros | Cons |
53 |------|------|
54 | Simple deployment | Weaker ESC/POS and USB ecosystem |
55 | Fast compile | Fyne UI less polished for split editor/preview |
56
57 **Verdict:** Possible but fighting the ecosystem for printer I/O.
58
59 ### Python + PyQt / PySide
60
61 | Pros | Cons |
62 |------|------|
63 | Rapid prototyping | Packaging on Windows/Linux painful |
64 | `python-escpos`, `pyserial` exist | GIL, dependency hell in frozen binaries |
65
66 **Verdict:** Good for a throwaway prototype, poor for a shipped product.
67
68 ### Electron + native Node addon
69
70 | Pros | Cons |
71 |------|------|
72 | Best editor UX (Monaco) | Large bundle (~150 MB+) |
73 | `serialport` npm package | Native addon build complexity per platform |
74
75 **Verdict:** Overkill footprint unless team is JS-only.
76
77 ### C++ + Qt
78
79 | Pros | Cons |
80 |------|------|
81 | Mature, fast | Slowest development velocity |
82 | Qt Serial Port | ESC/POS mostly roll-your-own |
83
84 **Verdict:** Over-engineered for a *small* application.
85
86 ---
87
88 ## Decision (updated)
89
90 ### Selected: **Rust + egui (eframe)** — single-language, minimal dependencies
91
92 See [ARCHITECTURE.md](ARCHITECTURE.md) for the current layout.
93
94 ### Previously considered: **Rust (core) + Tauri 2 + TypeScript (UI)**
95
96 ```
97 ┌─────────────────────────────────────────┐
98 │ Frontend (TypeScript + React/Svelte) │
99 │ - CodeMirror/Monaco editor │
100 │ - Preview canvas (width-scaled) │
101 │ - Parameter modal, printer picker │
102 └─────────────────┬───────────────────────┘
103 │ Tauri commands / events
104 ┌─────────────────▼───────────────────────┐
105 │ Rust backend │
106 │ - DSL parse → AST │
107 │ - Preview layout + ESC/POS encode │
108 │ - Printer discovery (serial, USB, BT) │
109 │ - `.pos` serde │
110 └─────────────────────────────────────────┘
111 ```
112
113 #### Rust crates (planned)
114
115 | Crate | Role |
116 |-------|------|
117 | `escpos` | ESC/POS commands, barcodes, QR, raster |
118 | `serialport` | USB-serial / COM ports |
119 | `nusb` or `rusb` | USB printer class (bulk) |
120 | `serde` + `serde_json` | `.pos` file format |
121 | `image` | Decode/resize images for raster print |
122 | `tauri` 2.x | App shell, IPC |
123
124 #### Frontend (planned)
125
126 | Library | Role |
127 |---------|------|
128 | CodeMirror 6 or Monaco | Syntax-aware editor |
129 | Vite + React (or Svelte) | UI framework |
130 | Tailwind or similar | Layout |
131
132 ### Fallback: **Rust + egui**
133
134 Choose this if you want a single-language codebase and can accept a simpler text editor (egui text edit + optional syntect highlighting).
135
136 ---
137
138 ## Platform-specific notes
139
140 ### Windows
141
142 - USB-serial: `COMx` via `serialport` crate
143 - USB printer class: `escpos` `usbprint` feature (uses `usbprint.sys`, no Zadig)
144 - Bluetooth SPP: paired devices as COM ports; discovery via Windows APIs (later phase)
145 - Build: MSVC toolchain, WiX or NSIS for installer
146
147 ### Linux
148
149 - USB-serial: `/dev/ttyUSB*`, `/dev/ttyACM*` — user must be in `dialout` group
150 - USB printer class: `nusb` + udev rules optional for non-root
151 - Bluetooth: BlueZ, `/dev/rfcomm*` after binding
152 - Build: `cargo deb` / AppImage via Tauri bundler
153
154 ---
155
156 ## Decision record
157
158 | Decision | Choice | Rationale |
159 |----------|--------|-----------|
160 | Core language | **Rust** | ESC/POS + USB/serial ecosystem |
161 | UI shell | **Tauri 2** | Small binary, modern editor UX |
162 | UI language | **TypeScript** | Editor component ecosystem |
163 | Print protocol | **ESC/POS** | De facto POS standard |
164 | MVP transport | **USB-serial** | Highest compatibility, lowest risk |
165
166 This decision should be revisited only if the implementing team has strong expertise elsewhere (e.g. Avalonia) *and* accepts additional printer I/O work.
@@ -0,0 +1,166 @@
1# Language and platform choice
2
3## Requirements driving the decision
4
5| Requirement | Technical implication |
6|-------------|----------------------|
7| Windows + Linux binaries | Cross-compile friendly toolchain, native I/O |
8| Raw USB / serial / Bluetooth | Low-level device access, not browser-only |
9| ESC/POS byte generation | Binary buffers, barcode/image encoding |
10| Live preview UI | Responsive editor + rendered preview |
11| Small distributable | Avoid heavy runtime (no full JVM, prefer no Chromium if possible) |
12| Long-term maintainability | Strong typing, good deps for hardware |
13
14---
15
16## Candidates evaluated
17
18### Rust + Tauri 2 (recommended)
19
20| Pros | Cons |
21|------|------|
22| Excellent ESC/POS ecosystem (`escpos`, `nusb`, `serialport`) | Rust learning curve |
23| Tauri 2: small binaries, web UI for editor | Two languages (Rust + TS) |
24| Proven pattern for serial/USB desktop tools | WebView rendering for preview |
25| First-class Windows + Linux support | |
26| `serde` for `.pos` files | |
27
28**Verdict:** Best fit. Hardware logic stays in Rust; React/Svelte/Vue handles editor UX.
29
30### Rust + egui / iced (native UI)
31
32| Pros | Cons |
33|------|------|
34| Single language, single binary | Editor UX more work (no Monaco/CodeMirror out of the box) |
35| No WebView dependency | Syntax highlighting needs extra crates |
36| Fast iteration for tools | Less familiar to web developers |
37
38**Verdict:** Strong alternative if minimizing dependencies matters more than rich editor UX.
39
40### C# + Avalonia
41
42| Pros | Cons |
43|------|------|
44| Good desktop UI | USB/BT raw I/O less ergonomic than Rust |
45| Cross-platform .NET | Larger runtime |
46| Familiar if team is .NET | ESC/POS libs thinner than Rust |
47
48**Verdict:** Viable if the team is already .NET-heavy.
49
50### Go + Fyne / Wails
51
52| Pros | Cons |
53|------|------|
54| Simple deployment | Weaker ESC/POS and USB ecosystem |
55| Fast compile | Fyne UI less polished for split editor/preview |
56
57**Verdict:** Possible but fighting the ecosystem for printer I/O.
58
59### Python + PyQt / PySide
60
61| Pros | Cons |
62|------|------|
63| Rapid prototyping | Packaging on Windows/Linux painful |
64| `python-escpos`, `pyserial` exist | GIL, dependency hell in frozen binaries |
65
66**Verdict:** Good for a throwaway prototype, poor for a shipped product.
67
68### Electron + native Node addon
69
70| Pros | Cons |
71|------|------|
72| Best editor UX (Monaco) | Large bundle (~150 MB+) |
73| `serialport` npm package | Native addon build complexity per platform |
74
75**Verdict:** Overkill footprint unless team is JS-only.
76
77### C++ + Qt
78
79| Pros | Cons |
80|------|------|
81| Mature, fast | Slowest development velocity |
82| Qt Serial Port | ESC/POS mostly roll-your-own |
83
84**Verdict:** Over-engineered for a *small* application.
85
86---
87
88## Decision (updated)
89
90### Selected: **Rust + egui (eframe)** — single-language, minimal dependencies
91
92See [ARCHITECTURE.md](ARCHITECTURE.md) for the current layout.
93
94### Previously considered: **Rust (core) + Tauri 2 + TypeScript (UI)**
95
96```
97┌─────────────────────────────────────────┐
98│ Frontend (TypeScript + React/Svelte) │
99│ - CodeMirror/Monaco editor │
100│ - Preview canvas (width-scaled) │
101│ - Parameter modal, printer picker │
102└─────────────────┬───────────────────────┘
103 │ Tauri commands / events
104┌─────────────────▼───────────────────────┐
105│ Rust backend │
106│ - DSL parse → AST │
107│ - Preview layout + ESC/POS encode │
108│ - Printer discovery (serial, USB, BT) │
109│ - `.pos` serde │
110└─────────────────────────────────────────┘
111```
112
113#### Rust crates (planned)
114
115| Crate | Role |
116|-------|------|
117| `escpos` | ESC/POS commands, barcodes, QR, raster |
118| `serialport` | USB-serial / COM ports |
119| `nusb` or `rusb` | USB printer class (bulk) |
120| `serde` + `serde_json` | `.pos` file format |
121| `image` | Decode/resize images for raster print |
122| `tauri` 2.x | App shell, IPC |
123
124#### Frontend (planned)
125
126| Library | Role |
127|---------|------|
128| CodeMirror 6 or Monaco | Syntax-aware editor |
129| Vite + React (or Svelte) | UI framework |
130| Tailwind or similar | Layout |
131
132### Fallback: **Rust + egui**
133
134Choose this if you want a single-language codebase and can accept a simpler text editor (egui text edit + optional syntect highlighting).
135
136---
137
138## Platform-specific notes
139
140### Windows
141
142- USB-serial: `COMx` via `serialport` crate
143- USB printer class: `escpos` `usbprint` feature (uses `usbprint.sys`, no Zadig)
144- Bluetooth SPP: paired devices as COM ports; discovery via Windows APIs (later phase)
145- Build: MSVC toolchain, WiX or NSIS for installer
146
147### Linux
148
149- USB-serial: `/dev/ttyUSB*`, `/dev/ttyACM*` — user must be in `dialout` group
150- USB printer class: `nusb` + udev rules optional for non-root
151- Bluetooth: BlueZ, `/dev/rfcomm*` after binding
152- Build: `cargo deb` / AppImage via Tauri bundler
153
154---
155
156## Decision record
157
158| Decision | Choice | Rationale |
159|----------|--------|-----------|
160| Core language | **Rust** | ESC/POS + USB/serial ecosystem |
161| UI shell | **Tauri 2** | Small binary, modern editor UX |
162| UI language | **TypeScript** | Editor component ecosystem |
163| Print protocol | **ESC/POS** | De facto POS standard |
164| MVP transport | **USB-serial** | Highest compatibility, lowest risk |
165
166This decision should be revisited only if the implementing team has strong expertise elsewhere (e.g. Avalonia) *and* accepts additional printer I/O work.
docs/PRINTING.md added +258 −0
@@ -0,0 +1,258 @@
1 # Printing subsystem
2
3 Direct raw-byte printing to POS thermal printers over USB-serial, USB printer class, and Bluetooth SPP — without submitting jobs through the OS print spooler (Windows) or CUPS (Linux).
4
5 ---
6
7 ## Goals
8
9 1. Discover connected POS-capable devices
10 2. Let the user pick a printer in a dialog
11 3. Generate ESC/POS bytes from the document AST (after parameter substitution)
12 4. Write bytes to the device and confirm completion (best-effort)
13
14 ---
15
16 ## Protocol: ESC/POS
17
18 Target **Epson ESC/POS** compatible printers (majority of 58 mm / 80 mm thermal printers).
19
20 ### Supported in v1
21
22 | Feature | Command family |
23 |---------|----------------|
24 | Text, bold, size | ESC !, ESC E, GS ! |
25 | Alignment | ESC a |
26 | Line feed | LF, ESC d |
27 | Partial cut | GS V |
28 | Barcode | GS k, GS h, GS H |
29 | QR Code | GS ( k |
30 | Raster image | GS v 0 |
31 | Initialize | ESC @ |
32
33 ### Printer initialization sequence
34
35 Every print job starts with:
36
37 ```
38 ESC @ ; reset printer
39 ESC t n ; select code page (from metadata.codepage)
40 ; ... document bytes ...
41 [optional feed + cut]
42 ```
43
44 ---
45
46 ## Transport layers
47
48 ```
49 ┌─────────────────┐
50 │ PrintPipeline │
51 └────────┬────────┘
52 │
53 ┌──────────────┼──────────────┐
54 ▼ ▼ ▼
55 SerialTransport UsbTransport BtTransport
56 │ │ │
57 serialport nusb / serialport
58 usbprint (RFCOMM port)
59 ```
60
61 ### Transport trait
62
63 ```rust
64 trait PrinterTransport {
65 fn open(&mut self) -> Result<()>;
66 fn write(&mut self, data: &[u8]) -> Result<()>;
67 fn flush(&mut self) -> Result<()>;
68 fn close(&mut self) -> Result<()>;
69 }
70 ```
71
72 ### Phase rollout
73
74 | Phase | Transport | Discovery |
75 |-------|-----------|-----------|
76 | **MVP** | USB-serial (CDC, CH340, FTDI, Prolific) | `serialport::available_ports()` |
77 | **v1** | USB printer class (bulk OUT) | USB VID/PID filter + interface scan |
78 | **v1.1** | Bluetooth Classic SPP | Paired COM / rfcomm ports |
79
80 ---
81
82 ## Device discovery
83
84 ### USB-serial (MVP)
85
86 Use `serialport` crate:
87
88 ```rust
89 // Pseudocode
90 for port in serialport::available_ports()? {
91 match port.port_type {
92 SerialPortType::UsbPort(info) => {
93 // Filter: known POS vendor IDs optional
94 // Include all USB-serial for user selection
95 }
96 _ => {}
97 }
98 }
99 ```
100
101 **Linux:** User must be in `dialout` group. Show actionable error if permission denied.
102
103 **Windows:** COM ports appear after driver install (usually automatic for CDC).
104
105 ### USB printer class (v1)
106
107 - **Linux:** `nusb` — find interface class 7 (printer), bulk OUT endpoint
108 - **Windows:** `escpos` `usbprint` feature — open via `\\.\USBPRINT\...` without replacing system driver
109
110 Filter candidates by:
111
112 - Interface class 7
113 - Optional known VID list (Epson `0x04b8`, Star, Bixolon, etc.)
114
115 ### Bluetooth SPP (v1.1)
116
117 - **Windows:** Enumerate COM ports associated with paired Bluetooth devices
118 - **Linux:** `/dev/rfcomm*` or bind via BlueZ; may require `bluetooth` group
119
120 Discovery is harder than USB; show paired devices and let user refresh after OS pairing.
121
122 ---
123
124 ## Printer picker UI
125
126 ```
127 ┌─────────────────────────────────────────┐
128 │ Select printer │
129 ├─────────────────────────────────────────┤
130 │ ○ COM3 — USB Serial (VID:04b8 PID:0e15)│
131 │ ○ /dev/ttyUSB0 — CH340 │
132 │ ○ \\.\USBPRINT\epson-tm-t20 │
133 │ │
134 │ [ Refresh ] [ Print ] │
135 └─────────────────────────────────────────┘
136 ```
137
138 Each `PrinterDevice` has:
139
140 | Field | Example |
141 |-------|---------|
142 | `id` | `serial:COM3` or `usb:04b8:0e15:iface0` |
143 | `display_name` | `Epson TM-T20 (COM3)` |
144 | `transport` | `Serial { port: "COM3", baud: 9600 }` |
145 | `last_used` | timestamp for default selection |
146
147 **Default baud:** 9600 or 115200 — probe common rates or expose advanced setting if open fails.
148
149 ---
150
151 ## Print pipeline
152
153 ```
154 Document body (DSL)
155 │
156 ▼
157 Parse → AST
158 │
159 ▼
160 Collect parameters (UI dialog)
161 │
162 ▼
163 Substitute params
164 │
165 ▼
166 ESC/POS encoder (escpos crate)
167 │
168 ▼
169 Transport.write(all bytes)
170 │
171 ▼
172 Optional: read status (paper out, cover open)
173 ```
174
175 ### Error handling
176
177 | Error | User message |
178 |-------|--------------|
179 | Port busy | “Printer in use by another application” |
180 | Permission denied | “Add user to dialout group” (Linux) |
181 | Write timeout | “Printer not responding — check power and cable” |
182 | Paper out (if status read) | “Paper out” |
183
184 ---
185
186 ## Parameter integration at print
187
188 1. `collect_parameters(body)` → `["DocumentNumber", "GrandTotal", ...]`
189 2. Modal collects values; same name used once
190 3. Store in `last_print_params` for next run
191 4. `substitute(body, params)` then encode
192
193 Barcode/QR validation:
194
195 - EAN13 must be 12–13 digits after substitution
196 - Show validation errors before opening printer
197
198 ---
199
200 ## Images on printer
201
202 1. Load image from path (or fail if param path invalid)
203 2. Convert to grayscale → threshold/dither
204 3. Scale to target width (dots), respecting `page_width_mm`
205 4. Emit GS v 0 raster command
206
207 Large images slow printing; warn if > 50% of paper width × tall.
208
209 ---
210
211 ## Preview width vs print width
212
213 | Setting | Preview | Print |
214 |---------|---------|-------|
215 | `autoscale` | Scale preview to panel width | Always full paper width |
216 | `fixed` | Render at exact mm width | Full paper width |
217
218 Print always uses physical paper width from metadata; preview is a visual aid.
219
220 ---
221
222 ## Security considerations
223
224 - **Raw USB access:** only write to user-selected device; no automatic writes
225 - **Path traversal:** image paths must resolve under `.pos` directory or explicit absolute paths user provided
226 - **Bluetooth:** only paired devices user selects
227
228 ---
229
230 ## Testing without hardware
231
232 | Method | Use |
233 |--------|-----|
234 | `FileTransport` | Write `.bin` ESC/POS to disk for hex inspection |
235 | ESC/POS emulator | [escpos-printer-emulator](https://github.com) / serial port loopback |
236 | Snapshot tests | Compare generated bytes to golden files |
237
238 ---
239
240 ## Dependencies (Rust)
241
242 ```toml
243 escpos = { version = "...", features = ["barcodes", "codes_2d", "graphics", "serial_port", "native_usb", "usbprint"] }
244 serialport = "4"
245 nusb = "0.2" # optional USB class
246 image = "0.25"
247 ```
248
249 Platform-specific features enabled per target in `build.rs` or Cargo features.
250
251 ---
252
253 ## Open questions (resolve during implementation)
254
255 1. **Baud rate autodetect** — try 9600, 19200, 115200 on failure?
256 2. **Status polling** — DLE EOT real-time status vs fire-and-forget?
257 3. **Concurrent prints** — mutex per printer ID
258 4. **Network printers** — add TCP 9100 in v2?
@@ -0,0 +1,258 @@
1# Printing subsystem
2
3Direct raw-byte printing to POS thermal printers over USB-serial, USB printer class, and Bluetooth SPP — without submitting jobs through the OS print spooler (Windows) or CUPS (Linux).
4
5---
6
7## Goals
8
91. Discover connected POS-capable devices
102. Let the user pick a printer in a dialog
113. Generate ESC/POS bytes from the document AST (after parameter substitution)
124. Write bytes to the device and confirm completion (best-effort)
13
14---
15
16## Protocol: ESC/POS
17
18Target **Epson ESC/POS** compatible printers (majority of 58 mm / 80 mm thermal printers).
19
20### Supported in v1
21
22| Feature | Command family |
23|---------|----------------|
24| Text, bold, size | ESC !, ESC E, GS ! |
25| Alignment | ESC a |
26| Line feed | LF, ESC d |
27| Partial cut | GS V |
28| Barcode | GS k, GS h, GS H |
29| QR Code | GS ( k |
30| Raster image | GS v 0 |
31| Initialize | ESC @ |
32
33### Printer initialization sequence
34
35Every print job starts with:
36
37```
38ESC @ ; reset printer
39ESC t n ; select code page (from metadata.codepage)
40; ... document bytes ...
41[optional feed + cut]
42```
43
44---
45
46## Transport layers
47
48```
49 ┌─────────────────┐
50 │ PrintPipeline │
51 └────────┬────────┘
52 │
53 ┌──────────────┼──────────────┐
54 ▼ ▼ ▼
55 SerialTransport UsbTransport BtTransport
56 │ │ │
57 serialport nusb / serialport
58 usbprint (RFCOMM port)
59```
60
61### Transport trait
62
63```rust
64trait PrinterTransport {
65 fn open(&mut self) -> Result<()>;
66 fn write(&mut self, data: &[u8]) -> Result<()>;
67 fn flush(&mut self) -> Result<()>;
68 fn close(&mut self) -> Result<()>;
69}
70```
71
72### Phase rollout
73
74| Phase | Transport | Discovery |
75|-------|-----------|-----------|
76| **MVP** | USB-serial (CDC, CH340, FTDI, Prolific) | `serialport::available_ports()` |
77| **v1** | USB printer class (bulk OUT) | USB VID/PID filter + interface scan |
78| **v1.1** | Bluetooth Classic SPP | Paired COM / rfcomm ports |
79
80---
81
82## Device discovery
83
84### USB-serial (MVP)
85
86Use `serialport` crate:
87
88```rust
89// Pseudocode
90for port in serialport::available_ports()? {
91 match port.port_type {
92 SerialPortType::UsbPort(info) => {
93 // Filter: known POS vendor IDs optional
94 // Include all USB-serial for user selection
95 }
96 _ => {}
97 }
98}
99```
100
101**Linux:** User must be in `dialout` group. Show actionable error if permission denied.
102
103**Windows:** COM ports appear after driver install (usually automatic for CDC).
104
105### USB printer class (v1)
106
107- **Linux:** `nusb` — find interface class 7 (printer), bulk OUT endpoint
108- **Windows:** `escpos` `usbprint` feature — open via `\\.\USBPRINT\...` without replacing system driver
109
110Filter candidates by:
111
112- Interface class 7
113- Optional known VID list (Epson `0x04b8`, Star, Bixolon, etc.)
114
115### Bluetooth SPP (v1.1)
116
117- **Windows:** Enumerate COM ports associated with paired Bluetooth devices
118- **Linux:** `/dev/rfcomm*` or bind via BlueZ; may require `bluetooth` group
119
120Discovery is harder than USB; show paired devices and let user refresh after OS pairing.
121
122---
123
124## Printer picker UI
125
126```
127┌─────────────────────────────────────────┐
128│ Select printer │
129├─────────────────────────────────────────┤
130│ ○ COM3 — USB Serial (VID:04b8 PID:0e15)│
131│ ○ /dev/ttyUSB0 — CH340 │
132│ ○ \\.\USBPRINT\epson-tm-t20 │
133│ │
134│ [ Refresh ] [ Print ] │
135└─────────────────────────────────────────┘
136```
137
138Each `PrinterDevice` has:
139
140| Field | Example |
141|-------|---------|
142| `id` | `serial:COM3` or `usb:04b8:0e15:iface0` |
143| `display_name` | `Epson TM-T20 (COM3)` |
144| `transport` | `Serial { port: "COM3", baud: 9600 }` |
145| `last_used` | timestamp for default selection |
146
147**Default baud:** 9600 or 115200 — probe common rates or expose advanced setting if open fails.
148
149---
150
151## Print pipeline
152
153```
154Document body (DSL)
155 │
156 ▼
157 Parse → AST
158 │
159 ▼
160 Collect parameters (UI dialog)
161 │
162 ▼
163 Substitute params
164 │
165 ▼
166 ESC/POS encoder (escpos crate)
167 │
168 ▼
169 Transport.write(all bytes)
170 │
171 ▼
172 Optional: read status (paper out, cover open)
173```
174
175### Error handling
176
177| Error | User message |
178|-------|--------------|
179| Port busy | “Printer in use by another application” |
180| Permission denied | “Add user to dialout group” (Linux) |
181| Write timeout | “Printer not responding — check power and cable” |
182| Paper out (if status read) | “Paper out” |
183
184---
185
186## Parameter integration at print
187
1881. `collect_parameters(body)` → `["DocumentNumber", "GrandTotal", ...]`
1892. Modal collects values; same name used once
1903. Store in `last_print_params` for next run
1914. `substitute(body, params)` then encode
192
193Barcode/QR validation:
194
195- EAN13 must be 12–13 digits after substitution
196- Show validation errors before opening printer
197
198---
199
200## Images on printer
201
2021. Load image from path (or fail if param path invalid)
2032. Convert to grayscale → threshold/dither
2043. Scale to target width (dots), respecting `page_width_mm`
2054. Emit GS v 0 raster command
206
207Large images slow printing; warn if > 50% of paper width × tall.
208
209---
210
211## Preview width vs print width
212
213| Setting | Preview | Print |
214|---------|---------|-------|
215| `autoscale` | Scale preview to panel width | Always full paper width |
216| `fixed` | Render at exact mm width | Full paper width |
217
218Print always uses physical paper width from metadata; preview is a visual aid.
219
220---
221
222## Security considerations
223
224- **Raw USB access:** only write to user-selected device; no automatic writes
225- **Path traversal:** image paths must resolve under `.pos` directory or explicit absolute paths user provided
226- **Bluetooth:** only paired devices user selects
227
228---
229
230## Testing without hardware
231
232| Method | Use |
233|--------|-----|
234| `FileTransport` | Write `.bin` ESC/POS to disk for hex inspection |
235| ESC/POS emulator | [escpos-printer-emulator](https://github.com) / serial port loopback |
236| Snapshot tests | Compare generated bytes to golden files |
237
238---
239
240## Dependencies (Rust)
241
242```toml
243escpos = { version = "...", features = ["barcodes", "codes_2d", "graphics", "serial_port", "native_usb", "usbprint"] }
244serialport = "4"
245nusb = "0.2" # optional USB class
246image = "0.25"
247```
248
249Platform-specific features enabled per target in `build.rs` or Cargo features.
250
251---
252
253## Open questions (resolve during implementation)
254
2551. **Baud rate autodetect** — try 9600, 19200, 115200 on failure?
2562. **Status polling** — DLE EOT real-time status vs fire-and-forget?
2573. **Concurrent prints** — mutex per printer ID
2584. **Network printers** — add TCP 9100 in v2?