Sync design docs with implemented Rust+egui MVP.
Remove stale Tauri, escpos crate, and Bluetooth-as-v1 references. Document actual modules, USB-serial-only printing, GitLab CI, and planned work. Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -0,0 +1,44 @@
1
---
2
description: posprint architecture and stack conventions
3
globs: src/**/*
4
alwaysApply: true
5
---
6
7
# Architecture rules
8
9
## Stack (do not change without updating docs)
10
11
- **Rust only** — no TypeScript/JavaScript frontend.
12
- **egui / eframe** for UI (`src/app.rs`, `src/main.rs`).
13
- **USB-serial printing only** — `src/print/mod.rs` via `serialport`. No Bluetooth or USB printer-class code until explicitly requested.
14
15
## Module responsibilities
16
17
| Module | Responsibility |
18
|--------|----------------|
19
| `dsl/` | Parse template text → `Document` AST |
20
| `params.rs` | Collect `${Name}` tokens; substitute at print time |
21
| `escpos.rs` | AST → ESC/POS bytes (in-tree; no `escpos` crate) |
22
| `preview.rs` | AST → `PreviewModel` for UI canvas |
23
| `io/` | `PosFile` JSON load/save |
24
| `print/` | Port enumeration, `SerialTransport`, `MockTransport` |
25
| `app.rs` | All egui UI: editor, preview, help, print dialog |
26
27
Keep business logic out of `app.rs` where possible — UI should call `lib` modules.
28
29
## Dependencies
30
31
Add a crate only when hand-rolling is unreasonable. Current allowed set:
32
33
- `eframe`, `serde`, `serde_json`, `serialport`, `image`, `rfd`
34
35
Do **not** add `escpos`, `nusb`, `tauri`, or a JS toolchain without a deliberate stack change and doc update.
36
37
## Preview vs print
38
39
- **Preview:** approximate layout; placeholders for barcode/QR/image; unresolved `${Param}` shown literally.
40
- **Print:** substitute parameters first, then encode ESC/POS, then write to serial port at **9600 baud**.
41
42
## Planned features (not in codebase yet)
43
44
USB printer class, Bluetooth, baud autodetect, persisted recent files/parameters, syntax highlighting. Document these only under "Planned" sections — do not implement stubs without a task.
@@ -0,0 +1,44 @@1
---
2
description: posprint architecture and stack conventions
3
globs: src/**/*
4
alwaysApply: true
5
---
6
7
# Architecture rules
8
9
## Stack (do not change without updating docs)
10
11
- **Rust only** — no TypeScript/JavaScript frontend.
12
- **egui / eframe** for UI (`src/app.rs`, `src/main.rs`).
13
- **USB-serial printing only** — `src/print/mod.rs` via `serialport`. No Bluetooth or USB printer-class code until explicitly requested.
14
15
## Module responsibilities
16
17
| Module | Responsibility |
18
|--------|----------------|
19
| `dsl/` | Parse template text → `Document` AST |
20
| `params.rs` | Collect `${Name}` tokens; substitute at print time |
21
| `escpos.rs` | AST → ESC/POS bytes (in-tree; no `escpos` crate) |
22
| `preview.rs` | AST → `PreviewModel` for UI canvas |
23
| `io/` | `PosFile` JSON load/save |
24
| `print/` | Port enumeration, `SerialTransport`, `MockTransport` |
25
| `app.rs` | All egui UI: editor, preview, help, print dialog |
26
27
Keep business logic out of `app.rs` where possible — UI should call `lib` modules.
28
29
## Dependencies
30
31
Add a crate only when hand-rolling is unreasonable. Current allowed set:
32
33
- `eframe`, `serde`, `serde_json`, `serialport`, `image`, `rfd`
34
35
Do **not** add `escpos`, `nusb`, `tauri`, or a JS toolchain without a deliberate stack change and doc update.
36
37
## Preview vs print
38
39
- **Preview:** approximate layout; placeholders for barcode/QR/image; unresolved `${Param}` shown literally.
40
- **Print:** substitute parameters first, then encode ESC/POS, then write to serial port at **9600 baud**.
41
42
## Planned features (not in codebase yet)
43
44
USB printer class, Bluetooth, baud autodetect, persisted recent files/parameters, syntax highlighting. Document these only under "Planned" sections — do not implement stubs without a task.
@@ -10,26 +10,32 @@ alwaysApply: true
10
10
11
11
- Single language: **Rust** with **egui** (eframe) for the UI.
12
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.
13
- ESC/POS encoding lives in `src/escpos.rs` — do not add the `escpos` crates.io package.
14
- Printing: **USB-serial only** in v0.1.x. No Bluetooth or USB printer-class until explicitly requested.
14
15
15
16
## Testing
16
17
17
18
- **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
- New behaviour requires new tests in the same commit.
19
20
- 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
- Use `MockTransport` for printer I/O in tests; never require hardware in CI.
21
22
22
23
## Branches and commits
23
24
24
25
- Default branch: `master`.
25
- Use `feature/` or `fix/` branches for changes after initial setup.
26
- Use `feature/` or `fix/` branches for changes.
26
27
- Commit frequently with focused messages; avoid one large commit at the end.
28
- Merge to `master` only after `cargo test` is green.
27
29
28
30
## Documentation
29
31
32
- See `.cursor/rules/documentation.mdc` for full doc-sync rules.
30
33
- 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!`).
34
- The in-app Help tab must mirror `docs/HELP.md` (via `include_str!` in `src/lib.rs`).
35
- Update `docs/ARCHITECTURE.md`, `docs/PRINTING.md`, etc. when implementation diverges from design.
32
36
33
37
## Releases
34
38
35
- GitLab CI builds Windows (`.exe`/`.msi`) and Linux (`.deb` for apt) artifacts.
39
- GitLab CI (`.gitlab-ci.yml`) runs tests on push.
40
- Tagged releases produce Linux `.deb` (apt) and Windows `posprint.exe`.
41
- Linux release uses `cargo-deb` and `[package.metadata.deb]` in `Cargo.toml`.
@@ -10,26 +10,32 @@ alwaysApply: true10
10
11
- Single language: **Rust** with **egui** (eframe) for the UI.
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).
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.
13
- ESC/POS encoding lives in `src/escpos.rs` — do not add the `escpos` crates.io package.
14
- Printing: **USB-serial only** in v0.1.x. No Bluetooth or USB printer-class until explicitly requested.
14
15
15
## Testing
16
## Testing
16
17
17
- **Every module must have unit tests** in `#[cfg(test)] mod tests` (or `tests/` for integration).
18
- **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
- New behaviour requires new tests in the same commit.
19
- Run `cargo test` before merging; all tests must pass.
20
- 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
- Use `MockTransport` for printer I/O in tests; never require hardware in CI.
21
22
22
## Branches and commits
23
## Branches and commits
23
24
24
- Default branch: `master`.
25
- Default branch: `master`.
25
- Use `feature/` or `fix/` branches for changes after initial setup.
26
- Use `feature/` or `fix/` branches for changes.
26
- Commit frequently with focused messages; avoid one large commit at the end.
27
- Commit frequently with focused messages; avoid one large commit at the end.
28
- Merge to `master` only after `cargo test` is green.
27
29
28
## Documentation
30
## Documentation
29
31
32
- See `.cursor/rules/documentation.mdc` for full doc-sync rules.
30
- Keep `docs/HELP.md` in sync with supported DSL and UI features.
33
- 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!`).
34
- The in-app Help tab must mirror `docs/HELP.md` (via `include_str!` in `src/lib.rs`).
35
- Update `docs/ARCHITECTURE.md`, `docs/PRINTING.md`, etc. when implementation diverges from design.
32
36
33
## Releases
37
## Releases
34
38
35
- GitLab CI builds Windows (`.exe`/`.msi`) and Linux (`.deb` for apt) artifacts.
39
- GitLab CI (`.gitlab-ci.yml`) runs tests on push.
40
- Tagged releases produce Linux `.deb` (apt) and Windows `posprint.exe`.
41
- Linux release uses `cargo-deb` and `[package.metadata.deb]` in `Cargo.toml`.
@@ -0,0 +1,49 @@
1
---
2
description: Keep project documentation aligned with the codebase
3
globs: docs/**/*
4
alwaysApply: true
5
---
6
7
# Documentation rules
8
9
## Single source of truth
10
11
| Topic | Canonical doc | Also surfaced in |
12
|-------|---------------|------------------|
13
| User-facing features / DSL / UI | `docs/HELP.md` | In-app Help tab (`include_str!` in `src/lib.rs`) |
14
| System design | `docs/ARCHITECTURE.md` | — |
15
| DSL grammar | `docs/DSL-SPEC.md` | `docs/HELP.md` (user subset) |
16
| `.pos` file schema | `docs/FILE-FORMAT.md` | — |
17
| Printing / ESC/POS | `docs/PRINTING.md` | `docs/HELP.md` (USB section) |
18
| Stack choice | `docs/LANGUAGE-CHOICE.md` | `README.md` summary |
19
20
## When to update docs
21
22
Update documentation **in the same commit** (or immediately before merge) when you change:
23
24
- Supported DSL syntax or directives
25
- UI tabs, toolbar actions, or dialogs
26
- `.pos` file schema or metadata fields
27
- Print transport, baud rate, or discovery behaviour
28
- Dependencies or CI/release artifacts
29
- Anything described in the in-app Help tab
30
31
## Implementation status markers
32
33
Design docs written before implementation may describe planned features. When editing:
34
35
- Mark **implemented** vs **planned** clearly (as in `PRINTING.md` and `ARCHITECTURE.md`).
36
- Remove references to rejected choices (e.g. Tauri, `escpos` crate) unless in a historical "considered" section.
37
- Do not document features that are not in code unless under a "Planned" or "Future" heading.
38
39
## HELP.md sync
40
41
If you add or change user-visible behaviour:
42
43
1. Edit `docs/HELP.md`.
44
2. Confirm `pub const HELP_MARKDOWN` in `src/lib.rs` still uses `include_str!("../docs/HELP.md")`.
45
3. No duplicate help text elsewhere.
46
47
## README
48
49
Keep `README.md` as the entry point: status, build/run, release artifacts, link to `docs/`.
@@ -0,0 +1,49 @@1
---
2
description: Keep project documentation aligned with the codebase
3
globs: docs/**/*
4
alwaysApply: true
5
---
6
7
# Documentation rules
8
9
## Single source of truth
10
11
| Topic | Canonical doc | Also surfaced in |
12
|-------|---------------|------------------|
13
| User-facing features / DSL / UI | `docs/HELP.md` | In-app Help tab (`include_str!` in `src/lib.rs`) |
14
| System design | `docs/ARCHITECTURE.md` | — |
15
| DSL grammar | `docs/DSL-SPEC.md` | `docs/HELP.md` (user subset) |
16
| `.pos` file schema | `docs/FILE-FORMAT.md` | — |
17
| Printing / ESC/POS | `docs/PRINTING.md` | `docs/HELP.md` (USB section) |
18
| Stack choice | `docs/LANGUAGE-CHOICE.md` | `README.md` summary |
19
20
## When to update docs
21
22
Update documentation **in the same commit** (or immediately before merge) when you change:
23
24
- Supported DSL syntax or directives
25
- UI tabs, toolbar actions, or dialogs
26
- `.pos` file schema or metadata fields
27
- Print transport, baud rate, or discovery behaviour
28
- Dependencies or CI/release artifacts
29
- Anything described in the in-app Help tab
30
31
## Implementation status markers
32
33
Design docs written before implementation may describe planned features. When editing:
34
35
- Mark **implemented** vs **planned** clearly (as in `PRINTING.md` and `ARCHITECTURE.md`).
36
- Remove references to rejected choices (e.g. Tauri, `escpos` crate) unless in a historical "considered" section.
37
- Do not document features that are not in code unless under a "Planned" or "Future" heading.
38
39
## HELP.md sync
40
41
If you add or change user-visible behaviour:
42
43
1. Edit `docs/HELP.md`.
44
2. Confirm `pub const HELP_MARKDOWN` in `src/lib.rs` still uses `include_str!("../docs/HELP.md")`.
45
3. No duplicate help text elsewhere.
46
47
## README
48
49
Keep `README.md` as the entry point: status, build/run, release artifacts, link to `docs/`.
@@ -55,11 +55,14 @@ ESC/POS encoding is implemented in-tree.
55
55
|----------|-------------|
56
56
| [FEASIBILITY.md](docs/FEASIBILITY.md) | Feasibility assessment, complexity estimate, risks |
57
57
| [LANGUAGE-CHOICE.md](docs/LANGUAGE-CHOICE.md) | Language and framework recommendation |
58
| [HELP.md](docs/HELP.md) | **User reference** (mirrored in-app Help tab) |
58
59
| [ARCHITECTURE.md](docs/ARCHITECTURE.md) | System architecture and module breakdown |
59
60
| [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
60
61
| [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
61
62
| [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
62
63
64
Documentation must stay aligned with the codebase; see `.cursor/rules/documentation.mdc`.
65
63
66
## Planned features
64
67
65
68
- Bluetooth printer support (deferred)
@@ -55,11 +55,14 @@ ESC/POS encoding is implemented in-tree.55
|----------|-------------|
55
|----------|-------------|
56
| [FEASIBILITY.md](docs/FEASIBILITY.md) | Feasibility assessment, complexity estimate, risks |
56
| [FEASIBILITY.md](docs/FEASIBILITY.md) | Feasibility assessment, complexity estimate, risks |
57
| [LANGUAGE-CHOICE.md](docs/LANGUAGE-CHOICE.md) | Language and framework recommendation |
57
| [LANGUAGE-CHOICE.md](docs/LANGUAGE-CHOICE.md) | Language and framework recommendation |
58
| [HELP.md](docs/HELP.md) | **User reference** (mirrored in-app Help tab) |
58
| [ARCHITECTURE.md](docs/ARCHITECTURE.md) | System architecture and module breakdown |
59
| [ARCHITECTURE.md](docs/ARCHITECTURE.md) | System architecture and module breakdown |
59
| [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
60
| [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
60
| [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
61
| [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
61
| [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
62
| [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
62
63
64
Documentation must stay aligned with the codebase; see `.cursor/rules/documentation.mdc`.
65
63
## Planned features
66
## Planned features
64
67
65
- Bluetooth printer support (deferred)
68
- Bluetooth printer support (deferred)
@@ -2,156 +2,179 @@
2
2
3
3
## Overview
4
4
5
posprint is a **single Rust binary** using **egui** (eframe). No separate frontend language.
5
posprint is a **single Rust binary** using **egui** (eframe). No separate frontend language, no WebView, no IPC layer.
6
6
7
7
```
8
8
┌─────────────────────────────────────────┐
9
9
│ posprint (Rust + egui) │
10
10
│ - Editor / Preview / Help tabs │
11
11
│ - DSL parse → AST │
12
│ - Preview layout + ESC/POS encode │
12
│ - Preview layout + in-tree ESC/POS │
13
13
│ - USB-serial printer discovery/print │
14
│ - `.pos` serde │
14
│ - `.pos` JSON load/save (serde) │
15
15
└─────────────────────────────────────────┘
16
16
```
17
17
18
### Crate layout
18
### Source layout
19
19
20
20
```
21
21
src/
22
├── main.rs, app.rs # egui application
23
├── lib.rs
24
├── dsl/ # Parser and AST
22
├── main.rs # eframe entry point
23
├── app.rs # egui UI (editor, preview, help, print dialog)
24
├── lib.rs # crate root; exports + HELP_MARKDOWN
25
├── dsl/ # Parser and AST (mod.rs, parser.rs)
25
26
├── params.rs # Parameter collect/substitute
26
├── escpos.rs # ESC/POS byte encoder
27
├── preview.rs # Preview model
28
├── io/ # .pos file format
29
└── print/ # USB-serial discovery and I/O
27
├── escpos.rs # ESC/POS byte encoder (in-tree)
28
├── preview.rs # Preview model for UI canvas
29
├── io/mod.rs # .pos file format (PosFile, PosMetadata)
30
└── print/mod.rs # USB-serial discovery, SerialTransport, MockTransport
30
31
```
31
32
33
### External dependencies (minimal)
34
35
| Crate | Role |
36
|-------|------|
37
| `eframe` / `egui` | Native UI |
38
| `serde` / `serde_json` | `.pos` file format |
39
| `serialport` | USB-serial enumeration and I/O |
40
| `image` | Decode/resize images for `@image` raster print |
41
| `rfd` | Native open/save file dialogs |
42
43
ESC/POS command generation is **not** delegated to a third-party crate.
44
45
---
46
47
## UI structure
48
49
| Tab / area | Module | Description |
50
|------------|--------|-------------|
51
| **Editor** | `app.rs` | Multiline `TextEdit` (monospace) for template source |
52
| **Preview** | `app.rs` + `preview.rs` | Canvas render of `PreviewModel`; auto-scale or fixed mm |
53
| **Help** | `app.rs` | Scrollable view of `docs/HELP.md` via `include_str!` |
54
| Toolbar | `app.rs` | New, Open, Save, Save As, Print |
55
| Settings | `app.rs` | Page width (mm), preview mode |
56
| Print dialog | `app.rs` | Parameter fields + USB-serial printer picker |
57
58
Bottom panel switches tabs. Top panel holds actions and settings.
59
32
60
---
33
61
34
62
## Data flow
35
63
36
64
### Edit loop (live preview)
37
65
38
1. User types in editor → debounced (e.g. 150 ms) invoke `preview_document(source, settings)`.
39
2. Core parses DSL → AST (or returns parse errors with line/col).
40
3. Core renders preview model: text lines, image refs, barcode/QR placeholders sized to page width.
41
4. UI displays preview scaled to panel width (auto) or fixed mm width.
66
1. User types in the Editor tab.
67
2. Each frame, `parse(&body)` runs; errors show in the toolbar.
68
3. On Preview tab, `render_preview(&doc, &metadata)` builds a `PreviewModel`.
69
4. Canvas draws text lines, rules, and placeholders for barcode/QR/image.
70
71
Preview is **not debounced** — it re-parses when the Preview tab is shown (and parse runs every frame for error display).
42
72
43
73
### Save / load
44
74
45
1. **Save:** UI sends `{ metadata, body }` → `save_pos(path)` → JSON on disk.
46
2. **Load:** `load_pos(path)` → populate editor and settings.
75
1. **Open:** `rfd` file dialog → `PosFile::load_from_path` → populate `body`, `metadata`, `file_path`.
76
2. **Save / Save As:** `PosFile::save_to_path` writes pretty-printed JSON.
77
78
Image paths in `@image` resolve relative to the `.pos` file directory on print.
47
79
48
80
### Print
49
81
50
1. User clicks Print → `collect_parameters(ast)` → unique sorted names.
51
2. UI shows modal; pre-fill from `last_print_params` in app state.
52
3. On confirm → `print_document(ast, params, printer_id)`.
53
4. Core: substitute → build ESC/POS → open transport → write bytes → cut (if configured).
82
1. User clicks **Print** → parse body → `collect_parameter_names(&doc)`.
83
2. Modal shows one field per unique parameter; pre-filled from `last_params` (in-memory).
84
3. User selects a USB-serial port from `list_usb_serial_printers()`.
85
4. `substitute_document` → `EscPosEncoder::encode_document` → `SerialTransport::open` (9600 baud) → `print_bytes`.
86
87
If `metadata.cut_after_print` is true and the template has no `@cut`, feed + cut are appended automatically.
54
88
55
89
---
56
90
57
## Key types (conceptual)
91
## Key types
92
93
Implemented in `dsl/mod.rs`, `io/mod.rs`, `print/mod.rs`:
58
94
59
95
```rust
60
struct Document {
61
blocks: Vec<Block>,
62
}
96
// dsl/
97
struct Document { blocks: Vec<Block> }
63
98
64
99
enum Block {
65
Paragraph { inlines: Vec<Inline>, align: Align },
66
Heading { level: u8, text: String },
100
Paragraph { align, inlines },
101
Heading { level, inlines },
67
102
Rule,
68
Image { src: String, width: ImageWidth }, // src may be ${Param}
69
Barcode { symbology: BarcodeKind, data: String, height: u8 },
70
Qr { data: String, size: QrSize },
71
Feed { lines: u8 },
103
Feed(u8),
72
104
Cut,
105
Image { path, width: ImageWidth, align },
106
Barcode { symbology, data, height, align, show_text },
107
Qr { data, size, ecc, align },
73
108
}
74
109
75
struct PosFile {
76
version: u32,
77
metadata: Metadata,
78
body: String,
79
}
80
81
struct Metadata {
82
title: Option<String>,
83
page_width_mm: f32, // 58, 80, etc.
84
preview_mode: PreviewMode, // AutoScale | Fixed
85
codepage: Option<String>,
86
cut_after_print: bool,
87
}
110
// io/
111
struct PosFile { version, metadata: PosMetadata, body }
112
struct PosMetadata { title, page_width_mm, preview_mode, chars_per_line, codepage, cut_after_print, default_feed_before_cut }
88
113
89
struct PrinterDevice {
90
id: String, // stable key for session
91
name: String,
92
transport: TransportKind,
93
// ...
94
}
114
// print/
115
struct PrinterDevice { id, display_name, port_name }
116
trait PrinterTransport { write_all, flush }
95
117
```
96
118
97
119
---
98
120
99
## Tauri commands (IPC surface)
100
101
| Command | Input | Output |
102
|---------|-------|--------|
103
| `parse_document` | `body: string` | `{ ast \| errors }` |
104
| `preview_document` | `body, metadata` | `PreviewModel` |
105
| `collect_parameters` | `body` | `string[]` (unique, sorted) |
106
| `save_pos` | `path, PosFile` | `Result<()>` |
107
| `load_pos` | `path` | `PosFile` |
108
| `list_printers` | — | `PrinterDevice[]` |
109
| `print_document` | `body, metadata, params, printer_id` | `Result<()>` |
110
111
---
112
113
121
## Preview vs print fidelity
114
122
115
123
| Aspect | Preview | Print |
116
124
|--------|---------|-------|
117
| Text font | UI monospace, scaled | Printer built-in font |
118
| Line width | Computed from `page_width_mm` | ESC/POS dot width |
119
| Images | Resized bitmap in canvas | Raster ESC/POS |
120
| Barcodes | SVG/canvas placeholder | Native printer barcode commands |
121
| Alignment | CSS / canvas | ESC/POS justify commands |
125
| Text font | egui monospace/proportional | Printer built-in font |
126
| Line width | From `chars_per_line()` | ESC/POS dot width from `page_width_mm` |
127
| Images | `[image: path]` placeholder | Monochrome raster (GS v 0) |
128
| Barcodes / QR | Text placeholder | Native ESC/POS commands |
129
| Alignment | Canvas positioning | ESC a |
122
130
123
Both paths share the **same AST and substitution**; preview and print each have their own backend (preview renderer vs `escpos` encoder).
131
Both paths share the same **AST**; substitution happens only at print time. Preview shows unresolved `${Param}` tokens as-is.
124
132
125
133
---
126
134
127
## State persistence
135
## State persistence (current)
128
136
129
| Data | Storage |
130
|------|---------|
131
| Recent files | App config (Tauri `app_data_dir`) |
132
| Last parameter values | `params.json` keyed by template path or global |
133
| Window layout | Optional, Tauri store |
134
| Selected printer | Per-machine preference |
137
| Data | Storage | Notes |
138
|------|---------|-------|
139
| Template + metadata | `.pos` file on disk | User saves explicitly |
140
| Last parameter values | `PosPrintApp.last_params` | In-memory only; lost on quit |
141
| Recent files | — | Not implemented |
142
| Selected printer | — | Not persisted between sessions |
135
143
136
144
---
137
145
138
## Testing strategy
146
## Testing
147
148
| Layer | Location | Approach |
149
|-------|----------|----------|
150
| DSL parser | `dsl/parser.rs` | Unit tests |
151
| Parameters | `params.rs` | Unit tests |
152
| ESC/POS encoder | `escpos.rs` | Byte structure tests |
153
| Preview | `preview.rs` | Unit tests |
154
| `.pos` I/O | `io/mod.rs` | Round-trip + tempfile tests |
155
| Printer I/O | `print/mod.rs` | `MockTransport`; no hardware in CI |
156
| App | `app.rs` | Default template parse/param tests |
139
157
140
| Layer | Approach |
141
|-------|----------|
142
| DSL parser | Unit tests + snapshot fixtures |
143
| Parameter collect/substitute | Unit tests |
144
| ESC/POS encoder | Byte snapshot tests |
145
| Preview layout | Snapshot images (optional) |
146
| Printer I/O | Manual hardware matrix; mock `Transport` trait in CI |
147
| UI | Component tests; E2E with mocked Tauri commands |
158
Run: `cargo test` (20 tests). CI runs this on Linux (Docker) and Windows (shell runner).
148
159
149
160
---
150
161
151
162
## Build and release
152
163
153
- **CI:** GitHub Actions — `cargo test`, `cargo clippy`, frontend lint, build Windows + Linux artifacts.
154
- **Artifacts:** `.msi` or `.exe` (Windows), `.deb` / AppImage (Linux).
155
- **Versioning:** Semver; `.pos` `version` field for file format migrations.
164
- **CI:** GitLab (`.gitlab-ci.yml`) — `cargo test` on push; release artifacts on tags.
165
- **Linux artifact:** `.deb` via `cargo-deb` (`[package.metadata.deb]` in `Cargo.toml`).
166
- **Windows artifact:** `target/release/posprint.exe`.
167
- **Versioning:** Semver in `Cargo.toml`; `.pos` `version` field for file-format migrations.
168
169
---
170
171
## Planned (not implemented)
172
173
- USB printer class (bulk OUT) without serial emulation
174
- Bluetooth SPP
175
- Network printers (TCP 9100)
176
- Baud-rate autodetect / settings UI
177
- Persisted last parameters and recent files
178
- Syntax highlighting in editor
156
179
157
See [PRINTING.md](PRINTING.md) for the device layer and [DSL-SPEC.md](DSL-SPEC.md) for language details.
180
See [PRINTING.md](PRINTING.md) and [DSL-SPEC.md](DSL-SPEC.md) for protocol and language details.
@@ -2,156 +2,179 @@2
2
3
## Overview
3
## Overview
4
4
5
posprint is a **single Rust binary** using **egui** (eframe). No separate frontend language.
5
posprint is a **single Rust binary** using **egui** (eframe). No separate frontend language, no WebView, no IPC layer.
6
6
7
```
7
```
8
┌─────────────────────────────────────────┐
8
┌─────────────────────────────────────────┐
9
│ posprint (Rust + egui) │
9
│ posprint (Rust + egui) │
10
│ - Editor / Preview / Help tabs │
10
│ - Editor / Preview / Help tabs │
11
│ - DSL parse → AST │
11
│ - DSL parse → AST │
12
│ - Preview layout + ESC/POS encode │
12
│ - Preview layout + in-tree ESC/POS │
13
│ - USB-serial printer discovery/print │
13
│ - USB-serial printer discovery/print │
14
│ - `.pos` serde │
14
│ - `.pos` JSON load/save (serde) │
15
└─────────────────────────────────────────┘
15
└─────────────────────────────────────────┘
16
```
16
```
17
17
18
### Crate layout
18
### Source layout
19
19
20
```
20
```
21
src/
21
src/
22
├── main.rs, app.rs # egui application
22
├── main.rs # eframe entry point
23
├── lib.rs
23
├── app.rs # egui UI (editor, preview, help, print dialog)
24
├── dsl/ # Parser and AST
24
├── lib.rs # crate root; exports + HELP_MARKDOWN
25
├── dsl/ # Parser and AST (mod.rs, parser.rs)
25
├── params.rs # Parameter collect/substitute
26
├── params.rs # Parameter collect/substitute
26
├── escpos.rs # ESC/POS byte encoder
27
├── escpos.rs # ESC/POS byte encoder (in-tree)
27
├── preview.rs # Preview model
28
├── preview.rs # Preview model for UI canvas
28
├── io/ # .pos file format
29
├── io/mod.rs # .pos file format (PosFile, PosMetadata)
29
└── print/ # USB-serial discovery and I/O
30
└── print/mod.rs # USB-serial discovery, SerialTransport, MockTransport
30
```
31
```
31
32
33
### External dependencies (minimal)
34
35
| Crate | Role |
36
|-------|------|
37
| `eframe` / `egui` | Native UI |
38
| `serde` / `serde_json` | `.pos` file format |
39
| `serialport` | USB-serial enumeration and I/O |
40
| `image` | Decode/resize images for `@image` raster print |
41
| `rfd` | Native open/save file dialogs |
42
43
ESC/POS command generation is **not** delegated to a third-party crate.
44
45
---
46
47
## UI structure
48
49
| Tab / area | Module | Description |
50
|------------|--------|-------------|
51
| **Editor** | `app.rs` | Multiline `TextEdit` (monospace) for template source |
52
| **Preview** | `app.rs` + `preview.rs` | Canvas render of `PreviewModel`; auto-scale or fixed mm |
53
| **Help** | `app.rs` | Scrollable view of `docs/HELP.md` via `include_str!` |
54
| Toolbar | `app.rs` | New, Open, Save, Save As, Print |
55
| Settings | `app.rs` | Page width (mm), preview mode |
56
| Print dialog | `app.rs` | Parameter fields + USB-serial printer picker |
57
58
Bottom panel switches tabs. Top panel holds actions and settings.
59
32
---
60
---
33
61
34
## Data flow
62
## Data flow
35
63
36
### Edit loop (live preview)
64
### Edit loop (live preview)
37
65
38
1. User types in editor → debounced (e.g. 150 ms) invoke `preview_document(source, settings)`.
66
1. User types in the Editor tab.
39
2. Core parses DSL → AST (or returns parse errors with line/col).
67
2. Each frame, `parse(&body)` runs; errors show in the toolbar.
40
3. Core renders preview model: text lines, image refs, barcode/QR placeholders sized to page width.
68
3. On Preview tab, `render_preview(&doc, &metadata)` builds a `PreviewModel`.
41
4. UI displays preview scaled to panel width (auto) or fixed mm width.
69
4. Canvas draws text lines, rules, and placeholders for barcode/QR/image.
70
71
Preview is **not debounced** — it re-parses when the Preview tab is shown (and parse runs every frame for error display).
42
72
43
### Save / load
73
### Save / load
44
74
45
1. **Save:** UI sends `{ metadata, body }` → `save_pos(path)` → JSON on disk.
75
1. **Open:** `rfd` file dialog → `PosFile::load_from_path` → populate `body`, `metadata`, `file_path`.
46
2. **Load:** `load_pos(path)` → populate editor and settings.
76
2. **Save / Save As:** `PosFile::save_to_path` writes pretty-printed JSON.
77
78
Image paths in `@image` resolve relative to the `.pos` file directory on print.
47
79
48
### Print
80
### Print
49
81
50
1. User clicks Print → `collect_parameters(ast)` → unique sorted names.
82
1. User clicks **Print** → parse body → `collect_parameter_names(&doc)`.
51
2. UI shows modal; pre-fill from `last_print_params` in app state.
83
2. Modal shows one field per unique parameter; pre-filled from `last_params` (in-memory).
52
3. On confirm → `print_document(ast, params, printer_id)`.
84
3. User selects a USB-serial port from `list_usb_serial_printers()`.
53
4. Core: substitute → build ESC/POS → open transport → write bytes → cut (if configured).
85
4. `substitute_document` → `EscPosEncoder::encode_document` → `SerialTransport::open` (9600 baud) → `print_bytes`.
86
87
If `metadata.cut_after_print` is true and the template has no `@cut`, feed + cut are appended automatically.
54
88
55
---
89
---
56
90
57
## Key types (conceptual)
91
## Key types
92
93
Implemented in `dsl/mod.rs`, `io/mod.rs`, `print/mod.rs`:
58
94
59
```rust
95
```rust
60
struct Document {
96
// dsl/
61
blocks: Vec<Block>,
97
struct Document { blocks: Vec<Block> }
62
}
63
98
64
enum Block {
99
enum Block {
65
Paragraph { inlines: Vec<Inline>, align: Align },
100
Paragraph { align, inlines },
66
Heading { level: u8, text: String },
101
Heading { level, inlines },
67
Rule,
102
Rule,
68
Image { src: String, width: ImageWidth }, // src may be ${Param}
103
Feed(u8),
69
Barcode { symbology: BarcodeKind, data: String, height: u8 },
70
Qr { data: String, size: QrSize },
71
Feed { lines: u8 },
72
Cut,
104
Cut,
105
Image { path, width: ImageWidth, align },
106
Barcode { symbology, data, height, align, show_text },
107
Qr { data, size, ecc, align },
73
}
108
}
74
109
75
struct PosFile {
110
// io/
76
version: u32,
111
struct PosFile { version, metadata: PosMetadata, body }
77
metadata: Metadata,
112
struct PosMetadata { title, page_width_mm, preview_mode, chars_per_line, codepage, cut_after_print, default_feed_before_cut }
78
body: String,
79
}
80
81
struct Metadata {
82
title: Option<String>,
83
page_width_mm: f32, // 58, 80, etc.
84
preview_mode: PreviewMode, // AutoScale | Fixed
85
codepage: Option<String>,
86
cut_after_print: bool,
87
}
88
113
89
struct PrinterDevice {
114
// print/
90
id: String, // stable key for session
115
struct PrinterDevice { id, display_name, port_name }
91
name: String,
116
trait PrinterTransport { write_all, flush }
92
transport: TransportKind,
93
// ...
94
}
95
```
117
```
96
118
97
---
119
---
98
120
99
## Tauri commands (IPC surface)
100
101
| Command | Input | Output |
102
|---------|-------|--------|
103
| `parse_document` | `body: string` | `{ ast \| errors }` |
104
| `preview_document` | `body, metadata` | `PreviewModel` |
105
| `collect_parameters` | `body` | `string[]` (unique, sorted) |
106
| `save_pos` | `path, PosFile` | `Result<()>` |
107
| `load_pos` | `path` | `PosFile` |
108
| `list_printers` | — | `PrinterDevice[]` |
109
| `print_document` | `body, metadata, params, printer_id` | `Result<()>` |
110
111
---
112
113
## Preview vs print fidelity
121
## Preview vs print fidelity
114
122
115
| Aspect | Preview | Print |
123
| Aspect | Preview | Print |
116
|--------|---------|-------|
124
|--------|---------|-------|
117
| Text font | UI monospace, scaled | Printer built-in font |
125
| Text font | egui monospace/proportional | Printer built-in font |
118
| Line width | Computed from `page_width_mm` | ESC/POS dot width |
126
| Line width | From `chars_per_line()` | ESC/POS dot width from `page_width_mm` |
119
| Images | Resized bitmap in canvas | Raster ESC/POS |
127
| Images | `[image: path]` placeholder | Monochrome raster (GS v 0) |
120
| Barcodes | SVG/canvas placeholder | Native printer barcode commands |
128
| Barcodes / QR | Text placeholder | Native ESC/POS commands |
121
| Alignment | CSS / canvas | ESC/POS justify commands |
129
| Alignment | Canvas positioning | ESC a |
122
130
123
Both paths share the **same AST and substitution**; preview and print each have their own backend (preview renderer vs `escpos` encoder).
131
Both paths share the same **AST**; substitution happens only at print time. Preview shows unresolved `${Param}` tokens as-is.
124
132
125
---
133
---
126
134
127
## State persistence
135
## State persistence (current)
128
136
129
| Data | Storage |
137
| Data | Storage | Notes |
130
|------|---------|
138
|------|---------|-------|
131
| Recent files | App config (Tauri `app_data_dir`) |
139
| Template + metadata | `.pos` file on disk | User saves explicitly |
132
| Last parameter values | `params.json` keyed by template path or global |
140
| Last parameter values | `PosPrintApp.last_params` | In-memory only; lost on quit |
133
| Window layout | Optional, Tauri store |
141
| Recent files | — | Not implemented |
134
| Selected printer | Per-machine preference |
142
| Selected printer | — | Not persisted between sessions |
135
143
136
---
144
---
137
145
138
## Testing strategy
146
## Testing
147
148
| Layer | Location | Approach |
149
|-------|----------|----------|
150
| DSL parser | `dsl/parser.rs` | Unit tests |
151
| Parameters | `params.rs` | Unit tests |
152
| ESC/POS encoder | `escpos.rs` | Byte structure tests |
153
| Preview | `preview.rs` | Unit tests |
154
| `.pos` I/O | `io/mod.rs` | Round-trip + tempfile tests |
155
| Printer I/O | `print/mod.rs` | `MockTransport`; no hardware in CI |
156
| App | `app.rs` | Default template parse/param tests |
139
157
140
| Layer | Approach |
158
Run: `cargo test` (20 tests). CI runs this on Linux (Docker) and Windows (shell runner).
141
|-------|----------|
142
| DSL parser | Unit tests + snapshot fixtures |
143
| Parameter collect/substitute | Unit tests |
144
| ESC/POS encoder | Byte snapshot tests |
145
| Preview layout | Snapshot images (optional) |
146
| Printer I/O | Manual hardware matrix; mock `Transport` trait in CI |
147
| UI | Component tests; E2E with mocked Tauri commands |
148
159
149
---
160
---
150
161
151
## Build and release
162
## Build and release
152
163
153
- **CI:** GitHub Actions — `cargo test`, `cargo clippy`, frontend lint, build Windows + Linux artifacts.
164
- **CI:** GitLab (`.gitlab-ci.yml`) — `cargo test` on push; release artifacts on tags.
154
- **Artifacts:** `.msi` or `.exe` (Windows), `.deb` / AppImage (Linux).
165
- **Linux artifact:** `.deb` via `cargo-deb` (`[package.metadata.deb]` in `Cargo.toml`).
155
- **Versioning:** Semver; `.pos` `version` field for file format migrations.
166
- **Windows artifact:** `target/release/posprint.exe`.
167
- **Versioning:** Semver in `Cargo.toml`; `.pos` `version` field for file-format migrations.
168
169
---
170
171
## Planned (not implemented)
172
173
- USB printer class (bulk OUT) without serial emulation
174
- Bluetooth SPP
175
- Network printers (TCP 9100)
176
- Baud-rate autodetect / settings UI
177
- Persisted last parameters and recent files
178
- Syntax highlighting in editor
156
179
157
See [PRINTING.md](PRINTING.md) for the device layer and [DSL-SPEC.md](DSL-SPEC.md) for language details.
180
See [PRINTING.md](PRINTING.md) and [DSL-SPEC.md](DSL-SPEC.md) for protocol and language details.
@@ -2,6 +2,8 @@
2
2
3
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
4
5
> **Implementation:** Parser in `src/dsl/parser.rs`. All constructs below are implemented unless listed under [Future extensions](#future-extensions-not-implemented).
6
5
7
**Design goals:** easy to author, line-oriented, explicit about POS-specific features (barcodes, cut, feed), parameter-friendly.
6
8
7
9
---
@@ -127,7 +129,7 @@ Images are converted to monochrome raster data, dithered, and scaled to width.
127
129
128
130
| Field | Values |
129
131
|-------|--------|
130
| Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A` (v1 subset) |
132
| Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39` |
131
133
| Data | Literal or `${Param}` |
132
134
| `height` | Module height in dots (default: 64) |
133
135
| `align` | `left`, `center`, `right` |
@@ -256,10 +258,12 @@ Full command details live in the print encoder module; see [PRINTING.md](PRINTIN
256
258
257
259
---
258
260
259
## Future extensions (not v1)
261
## Future extensions (not implemented)
260
262
261
263
- `@table` for columnar line items
264
- `UPC-A` barcodes
262
265
- Conditionals: `@if ${HasDiscount} ... @endif`
263
266
- Loops / repeating sections
264
267
- `@signature` for custom ESC/POS hex escape
265
268
- Multiple code pages / Unicode subset
269
- Syntax highlighting in the editor
@@ -2,6 +2,8 @@2
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.
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
4
5
> **Implementation:** Parser in `src/dsl/parser.rs`. All constructs below are implemented unless listed under [Future extensions](#future-extensions-not-implemented).
6
5
**Design goals:** easy to author, line-oriented, explicit about POS-specific features (barcodes, cut, feed), parameter-friendly.
7
**Design goals:** easy to author, line-oriented, explicit about POS-specific features (barcodes, cut, feed), parameter-friendly.
6
8
7
---
9
---
@@ -127,7 +129,7 @@ Images are converted to monochrome raster data, dithered, and scaled to width.127
129
128
| Field | Values |
130
| Field | Values |
129
|-------|--------|
131
|-------|--------|
130
| Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A` (v1 subset) |
132
| Symbology | `CODE128`, `EAN13`, `EAN8`, `CODE39` |
131
| Data | Literal or `${Param}` |
133
| Data | Literal or `${Param}` |
132
| `height` | Module height in dots (default: 64) |
134
| `height` | Module height in dots (default: 64) |
133
| `align` | `left`, `center`, `right` |
135
| `align` | `left`, `center`, `right` |
@@ -256,10 +258,12 @@ Full command details live in the print encoder module; see [PRINTING.md](PRINTIN256
258
257
---
259
---
258
260
259
## Future extensions (not v1)
261
## Future extensions (not implemented)
260
262
261
- `@table` for columnar line items
263
- `@table` for columnar line items
264
- `UPC-A` barcodes
262
- Conditionals: `@if ${HasDiscount} ... @endif`
265
- Conditionals: `@if ${HasDiscount} ... @endif`
263
- Loops / repeating sections
266
- Loops / repeating sections
264
- `@signature` for custom ESC/POS hex escape
267
- `@signature` for custom ESC/POS hex escape
265
- Multiple code pages / Unicode subset
268
- Multiple code pages / Unicode subset
269
- Syntax highlighting in the editor
@@ -1,5 +1,7 @@
1
1
# Feasibility and complexity assessment
2
2
3
> **Status:** MVP (v0.1.0) **implemented** — Rust + egui, USB-serial printing, 20 unit tests. This document retains the original feasibility analysis; see [ARCHITECTURE.md](ARCHITECTURE.md) for what is built today.
4
3
5
## Executive summary
4
6
5
7
| Question | Answer |
@@ -7,7 +9,7 @@
7
9
| Is it feasible? | **Yes** — all required capabilities exist in mature libraries or documented protocols |
8
10
| Overall complexity | **Medium–high** for a complete v1; **medium** if Bluetooth is deferred |
9
11
| 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 |
12
| Recommended MVP scope | USB-serial printers first (**done**); USB-printer-class and Bluetooth later |
11
13
12
14
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
15
@@ -61,7 +63,7 @@ Straightforward string substitution after validation. Image parameters might ref
61
63
| Generate ESC/POS QR commands | High | Low |
62
64
| Rasterize images to printer width | High | Medium |
63
65
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.
66
ESC/POS barcode, QR, and raster image commands are implemented in `src/escpos.rs` (in-tree). Preview uses text placeholders for barcodes/QR/images.
65
67
66
68
### 6. Direct USB / Bluetooth printing (raw bytes, no spooler)
67
69
@@ -81,9 +83,9 @@ Most consumer thermal printers expose one of:
81
83
82
84
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
85
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.
86
2. **USB printer class (interface 7)** — bulk transfers; **not implemented**. Would need `nusb` or Windows `usbprint.sys`.
85
87
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.
88
3. **Bluetooth Classic SPP** — **not implemented**; deferred.
87
89
88
90
4. **Network (TCP 9100)** — common in production but **out of scope** unless added later.
89
91
@@ -91,9 +93,8 @@ Most consumer thermal printers expose one of:
91
93
92
94
#### Compatibility reality
93
95
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.
96
- **MVP (done):** Epson-compatible ESC/POS over USB-serial at 9600 baud.
97
- **Future:** USB printer class, Bluetooth SPP.
97
98
98
99
Expect **per-printer testing**; some devices need init sequences, code pages, or cut commands that differ slightly.
99
100
@@ -146,8 +147,10 @@ Add 30–50% if the developer is new to Rust or ESC/POS.
146
147
147
148
---
148
149
149
## Out of scope (v1)
150
## Out of scope (current release)
150
151
152
- Bluetooth printing
153
- USB printer class (non-serial)
151
154
- Network printers (TCP 9100)
152
155
- Non-ESC/POS protocols (Star Line, ZPL)
153
156
- Multi-column layout engines
@@ -158,6 +161,6 @@ Add 30–50% if the developer is new to Rust or ESC/POS.
158
161
159
162
## Recommendation
160
163
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.
164
**MVP delivered.** Next increments: USB printer class, baud settings, persisted parameters, hardware test matrix. Bluetooth only if explicitly needed.
162
165
163
See [LANGUAGE-CHOICE.md](LANGUAGE-CHOICE.md) for stack details and [ARCHITECTURE.md](ARCHITECTURE.md) for module layout.
166
See [LANGUAGE-CHOICE.md](LANGUAGE-CHOICE.md) and [ARCHITECTURE.md](ARCHITECTURE.md).
@@ -1,5 +1,7 @@1
# Feasibility and complexity assessment
1
# Feasibility and complexity assessment
2
2
3
> **Status:** MVP (v0.1.0) **implemented** — Rust + egui, USB-serial printing, 20 unit tests. This document retains the original feasibility analysis; see [ARCHITECTURE.md](ARCHITECTURE.md) for what is built today.
4
3
## Executive summary
5
## Executive summary
4
6
5
| Question | Answer |
7
| Question | Answer |
@@ -7,7 +9,7 @@7
| Is it feasible? | **Yes** — all required capabilities exist in mature libraries or documented protocols |
9
| 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 |
10
| 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) |
11
| 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 |
12
| Recommended MVP scope | USB-serial printers first (**done**); USB-printer-class and Bluetooth later |
11
13
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**.
14
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
15
@@ -61,7 +63,7 @@ Straightforward string substitution after validation. Image parameters might ref61
| Generate ESC/POS QR commands | High | Low |
63
| Generate ESC/POS QR commands | High | Low |
62
| Rasterize images to printer width | High | Medium |
64
| Rasterize images to printer width | High | Medium |
63
65
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.
66
ESC/POS barcode, QR, and raster image commands are implemented in `src/escpos.rs` (in-tree). Preview uses text placeholders for barcodes/QR/images.
65
67
66
### 6. Direct USB / Bluetooth printing (raw bytes, no spooler)
68
### 6. Direct USB / Bluetooth printing (raw bytes, no spooler)
67
69
@@ -81,9 +83,9 @@ Most consumer thermal printers expose one of:81
83
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.**
84
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
85
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.
86
2. **USB printer class (interface 7)** — bulk transfers; **not implemented**. Would need `nusb` or Windows `usbprint.sys`.
85
87
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.
88
3. **Bluetooth Classic SPP** — **not implemented**; deferred.
87
89
88
4. **Network (TCP 9100)** — common in production but **out of scope** unless added later.
90
4. **Network (TCP 9100)** — common in production but **out of scope** unless added later.
89
91
@@ -91,9 +93,8 @@ Most consumer thermal printers expose one of:91
93
92
#### Compatibility reality
94
#### Compatibility reality
93
95
94
- **MVP:** Target Epson-compatible ESC/POS over USB-serial. Covers a large share of cheap 58/80 mm printers.
96
- **MVP (done):** Epson-compatible ESC/POS over USB-serial at 9600 baud.
95
- **v1:** Add USB printer class via `nusb` / `usbprint`.
97
- **Future:** USB printer class, Bluetooth SPP.
96
- **v1.1:** Add Bluetooth SPP discovery and pairing UX.
97
98
98
Expect **per-printer testing**; some devices need init sequences, code pages, or cut commands that differ slightly.
99
Expect **per-printer testing**; some devices need init sequences, code pages, or cut commands that differ slightly.
99
100
@@ -146,8 +147,10 @@ Add 30–50% if the developer is new to Rust or ESC/POS.146
147
147
---
148
---
148
149
149
## Out of scope (v1)
150
## Out of scope (current release)
150
151
152
- Bluetooth printing
153
- USB printer class (non-serial)
151
- Network printers (TCP 9100)
154
- Network printers (TCP 9100)
152
- Non-ESC/POS protocols (Star Line, ZPL)
155
- Non-ESC/POS protocols (Star Line, ZPL)
153
- Multi-column layout engines
156
- Multi-column layout engines
@@ -158,6 +161,6 @@ Add 30–50% if the developer is new to Rust or ESC/POS.158
161
159
## Recommendation
162
## Recommendation
160
163
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.
164
**MVP delivered.** Next increments: USB printer class, baud settings, persisted parameters, hardware test matrix. Bluetooth only if explicitly needed.
162
165
163
See [LANGUAGE-CHOICE.md](LANGUAGE-CHOICE.md) for stack details and [ARCHITECTURE.md](ARCHITECTURE.md) for module layout.
166
See [LANGUAGE-CHOICE.md](LANGUAGE-CHOICE.md) and [ARCHITECTURE.md](ARCHITECTURE.md).
@@ -142,4 +142,4 @@ interface PosMetadata {
142
142
}
143
143
```
144
144
145
Rust mirrors these with `serde` derive for 1:1 IPC across Tauri.
145
Rust types use `serde` derive in `src/io/mod.rs` and are used directly by the egui app (no IPC layer).
@@ -142,4 +142,4 @@ interface PosMetadata {142
}
142
}
143
```
143
```
144
144
145
Rust mirrors these with `serde` derive for 1:1 IPC across Tauri.
145
Rust types use `serde` derive in `src/io/mod.rs` and are used directly by the egui app (no IPC layer).
@@ -1,166 +1,83 @@
1
1
# Language and platform choice
2
2
3
## Requirements driving the decision
3
## Decision (implemented)
4
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 |
5
| Decision | Choice |
6
|----------|--------|
7
| Language | **Rust** (single codebase) |
8
| UI | **egui** via **eframe** |
9
| Print protocol | **ESC/POS** (in-tree encoder) |
10
| MVP transport | **USB-serial** via `serialport` |
11
| Packaging | GitLab CI → Linux `.deb`, Windows `.exe` |
13
12
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.
13
**Rationale:** One language, small dependency surface, direct control over ESC/POS bytes, native cross-platform UI without a WebView.
85
14
86
15
---
87
16
88
## Decision (updated)
89
90
### Selected: **Rust + egui (eframe)** — single-language, minimal dependencies
17
## Requirements
91
18
92
See [ARCHITECTURE.md](ARCHITECTURE.md) for the current layout.
19
| Requirement | How it is met |
20
|-------------|---------------|
21
| Windows + Linux | Rust + egui + GitLab CI |
22
| Raw USB-serial print (no spooler) | `serialport` crate, 9600 baud |
23
| ESC/POS generation | `src/escpos.rs` (no external ESC/POS crate) |
24
| Live preview | `src/preview.rs` + egui canvas in `app.rs` |
25
| Small distributable | No Chromium/Node; release build uses LTO + strip |
26
| Unit tests | Every module has `#[cfg(test)]` tests |
93
27
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
```
28
---
112
29
113
#### Rust crates (planned)
30
## Dependencies in use
114
31
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 |
32
| Crate | Role | Why not hand-roll? |
33
|-------|------|-------------------|
34
| `eframe` / `egui` | UI framework | Building a GUI toolkit is out of scope |
35
| `serde` / `serde_json` | `.pos` files | Error-prone to parse/emit JSON manually |
36
| `serialport` | Cross-platform COM/tty access | OS-specific serial APIs differ |
37
| `image` | PNG/JPEG/GIF/BMP decode | Many formats and decoders |
38
| `rfd` | Native file dialogs | OS-native UX expected |
123
39
124
#### Frontend (planned)
40
**Not used (by design):** `escpos`, `nusb`, `rusb`, `tauri`, TypeScript frontend.
125
41
126
| Library | Role |
127
|---------|------|
128
| CodeMirror 6 or Monaco | Syntax-aware editor |
129
| Vite + React (or Svelte) | UI framework |
130
| Tailwind or similar | Layout |
42
---
131
43
132
### Fallback: **Rust + egui**
44
## Candidates considered (historical)
133
45
134
Choose this if you want a single-language codebase and can accept a simpler text editor (egui text edit + optional syntect highlighting).
46
| Option | Verdict |
47
|--------|---------|
48
| Rust + Tauri 2 + TypeScript | Rejected — two languages, WebView dependency |
49
| Rust + egui | **Selected** |
50
| C# + Avalonia | Viable but weaker serial/ESC/POS ecosystem |
51
| Go + Fyne | Weaker hardware I/O ecosystem |
52
| Python + PyQt | Poor packaging for desktop release |
53
| Electron | Bundle size too large |
54
| C++ + Qt | Slower iteration for a small app |
135
55
136
56
---
137
57
138
## Platform-specific notes
58
## Platform notes
139
59
140
60
### Windows
141
61
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
62
- Printers appear as `COMx` after USB-serial driver install.
63
- Release: `posprint.exe` from `cargo build --release`.
64
- CI requires a GitLab runner tagged `windows` + `shell`.
146
65
147
66
### Linux
148
67
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
68
- Devices: `/dev/ttyUSB*`, `/dev/ttyACM*`, etc.
69
- User must be in the **`dialout`** group.
70
- Release: `.deb` via `cargo deb`; install with `sudo dpkg -i …`.
71
- CI uses `rust:bookworm` image with X11 dev libs for egui.
153
72
154
73
---
155
74
156
## Decision record
75
## Deferred
157
76
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 |
77
| Item | Notes |
78
|------|-------|
79
| USB printer class (bulk) | Would need `nusb` or Windows `usbprint` path |
80
| Bluetooth SPP | Paired devices as serial ports; add when requested |
81
| macOS | Same stack should work; not in CI yet |
165
82
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.
83
This document should be updated when transport or UI choices change.
@@ -1,166 +1,83 @@1
# Language and platform choice
1
# Language and platform choice
2
2
3
## Requirements driving the decision
3
## Decision (implemented)
4
4
5
| Requirement | Technical implication |
5
| Decision | Choice |
6
|-------------|----------------------|
6
|----------|--------|
7
| Windows + Linux binaries | Cross-compile friendly toolchain, native I/O |
7
| Language | **Rust** (single codebase) |
8
| Raw USB / serial / Bluetooth | Low-level device access, not browser-only |
8
| UI | **egui** via **eframe** |
9
| ESC/POS byte generation | Binary buffers, barcode/image encoding |
9
| Print protocol | **ESC/POS** (in-tree encoder) |
10
| Live preview UI | Responsive editor + rendered preview |
10
| MVP transport | **USB-serial** via `serialport` |
11
| Small distributable | Avoid heavy runtime (no full JVM, prefer no Chromium if possible) |
11
| Packaging | GitLab CI → Linux `.deb`, Windows `.exe` |
12
| Long-term maintainability | Strong typing, good deps for hardware |
13
12
14
---
13
**Rationale:** One language, small dependency surface, direct control over ESC/POS bytes, native cross-platform UI without a WebView.
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
14
86
---
15
---
87
16
88
## Decision (updated)
17
## Requirements
89
90
### Selected: **Rust + egui (eframe)** — single-language, minimal dependencies
91
18
92
See [ARCHITECTURE.md](ARCHITECTURE.md) for the current layout.
19
| Requirement | How it is met |
20
|-------------|---------------|
21
| Windows + Linux | Rust + egui + GitLab CI |
22
| Raw USB-serial print (no spooler) | `serialport` crate, 9600 baud |
23
| ESC/POS generation | `src/escpos.rs` (no external ESC/POS crate) |
24
| Live preview | `src/preview.rs` + egui canvas in `app.rs` |
25
| Small distributable | No Chromium/Node; release build uses LTO + strip |
26
| Unit tests | Every module has `#[cfg(test)]` tests |
93
27
94
### Previously considered: **Rust (core) + Tauri 2 + TypeScript (UI)**
28
---
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
29
113
#### Rust crates (planned)
30
## Dependencies in use
114
31
115
| Crate | Role |
32
| Crate | Role | Why not hand-roll? |
116
|-------|------|
33
|-------|------|-------------------|
117
| `escpos` | ESC/POS commands, barcodes, QR, raster |
34
| `eframe` / `egui` | UI framework | Building a GUI toolkit is out of scope |
118
| `serialport` | USB-serial / COM ports |
35
| `serde` / `serde_json` | `.pos` files | Error-prone to parse/emit JSON manually |
119
| `nusb` or `rusb` | USB printer class (bulk) |
36
| `serialport` | Cross-platform COM/tty access | OS-specific serial APIs differ |
120
| `serde` + `serde_json` | `.pos` file format |
37
| `image` | PNG/JPEG/GIF/BMP decode | Many formats and decoders |
121
| `image` | Decode/resize images for raster print |
38
| `rfd` | Native file dialogs | OS-native UX expected |
122
| `tauri` 2.x | App shell, IPC |
123
39
124
#### Frontend (planned)
40
**Not used (by design):** `escpos`, `nusb`, `rusb`, `tauri`, TypeScript frontend.
125
41
126
| Library | Role |
42
---
127
|---------|------|
128
| CodeMirror 6 or Monaco | Syntax-aware editor |
129
| Vite + React (or Svelte) | UI framework |
130
| Tailwind or similar | Layout |
131
43
132
### Fallback: **Rust + egui**
44
## Candidates considered (historical)
133
45
134
Choose this if you want a single-language codebase and can accept a simpler text editor (egui text edit + optional syntect highlighting).
46
| Option | Verdict |
47
|--------|---------|
48
| Rust + Tauri 2 + TypeScript | Rejected — two languages, WebView dependency |
49
| Rust + egui | **Selected** |
50
| C# + Avalonia | Viable but weaker serial/ESC/POS ecosystem |
51
| Go + Fyne | Weaker hardware I/O ecosystem |
52
| Python + PyQt | Poor packaging for desktop release |
53
| Electron | Bundle size too large |
54
| C++ + Qt | Slower iteration for a small app |
135
55
136
---
56
---
137
57
138
## Platform-specific notes
58
## Platform notes
139
59
140
### Windows
60
### Windows
141
61
142
- USB-serial: `COMx` via `serialport` crate
62
- Printers appear as `COMx` after USB-serial driver install.
143
- USB printer class: `escpos` `usbprint` feature (uses `usbprint.sys`, no Zadig)
63
- Release: `posprint.exe` from `cargo build --release`.
144
- Bluetooth SPP: paired devices as COM ports; discovery via Windows APIs (later phase)
64
- CI requires a GitLab runner tagged `windows` + `shell`.
145
- Build: MSVC toolchain, WiX or NSIS for installer
146
65
147
### Linux
66
### Linux
148
67
149
- USB-serial: `/dev/ttyUSB*`, `/dev/ttyACM*` — user must be in `dialout` group
68
- Devices: `/dev/ttyUSB*`, `/dev/ttyACM*`, etc.
150
- USB printer class: `nusb` + udev rules optional for non-root
69
- User must be in the **`dialout`** group.
151
- Bluetooth: BlueZ, `/dev/rfcomm*` after binding
70
- Release: `.deb` via `cargo deb`; install with `sudo dpkg -i …`.
152
- Build: `cargo deb` / AppImage via Tauri bundler
71
- CI uses `rust:bookworm` image with X11 dev libs for egui.
153
72
154
---
73
---
155
74
156
## Decision record
75
## Deferred
157
76
158
| Decision | Choice | Rationale |
77
| Item | Notes |
159
|----------|--------|-----------|
78
|------|-------|
160
| Core language | **Rust** | ESC/POS + USB/serial ecosystem |
79
| USB printer class (bulk) | Would need `nusb` or Windows `usbprint` path |
161
| UI shell | **Tauri 2** | Small binary, modern editor UX |
80
| Bluetooth SPP | Paired devices as serial ports; add when requested |
162
| UI language | **TypeScript** | Editor component ecosystem |
81
| macOS | Same stack should work; not in CI yet |
163
| Print protocol | **ESC/POS** | De facto POS standard |
164
| MVP transport | **USB-serial** | Highest compatibility, lowest risk |
165
82
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.
83
This document should be updated when transport or UI choices change.
@@ -1,150 +1,110 @@
1
1
# Printing subsystem
2
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).
3
Direct raw-byte printing to POS thermal printers over **USB-serial** — without the Windows print spooler or CUPS.
4
5
> **Implementation status (v0.1.0):** USB-serial only. In-tree ESC/POS encoder in `src/escpos.rs`. USB printer class and Bluetooth are **not** implemented.
4
6
5
7
---
6
8
7
9
## Goals
8
10
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)
11
1. Discover serial ports (USB-serial adapters and CDC printers)
12
2. Let the user pick a port in the print dialog
13
3. Generate ESC/POS bytes from the AST (after parameter substitution)
14
4. Write bytes at **9600 baud** (fixed for now)
13
15
14
16
---
15
17
16
18
## Protocol: ESC/POS
17
19
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 @ |
20
Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
32
21
33
### Printer initialization sequence
22
### Implemented commands
34
23
35
Every print job starts with:
24
| Feature | ESC/POS | Source |
25
|---------|---------|--------|
26
| Initialize | ESC @ | `escpos.rs` |
27
| Code page | ESC t 0 (CP437) | Always CP437 today; metadata field reserved |
28
| Bold | ESC E | Headings level 2, `**text**` flattened at encode |
29
| Double size | GS ! | Heading level 1 |
30
| Alignment | ESC a | Paragraphs, images, barcodes, QR |
31
| Line feed | LF, ESC d | Text lines, `@feed` |
32
| Partial cut | GS V 66 0 | `@cut`, auto-cut after print |
33
| Barcode | GS k | CODE128, EAN13, EAN8, CODE39 |
34
| QR Code | GS ( k | Model 2 |
35
| Raster image | GS v 0 | `@image` via `image` crate → threshold |
36
36
37
```
38
ESC @ ; reset printer
39
ESC t n ; select code page (from metadata.codepage)
40
; ... document bytes ...
41
[optional feed + cut]
42
```
37
Encoder: `EscPosEncoder` in `src/escpos.rs` — **not** the `escpos` crates.io package.
43
38
44
39
---
45
40
46
## Transport layers
41
## Transport (implemented)
47
42
48
43
```
49
┌─────────────────┐
50
│ PrintPipeline │
51
└────────┬────────┘
52
│
53
┌──────────────┼──────────────┐
54
▼ ▼ ▼
55
SerialTransport UsbTransport BtTransport
56
│ │ │
57
serialport nusb / serialport
58
usbprint (RFCOMM port)
44
Print button
45
│
46
▼
47
substitute_document()
48
│
49
▼
50
EscPosEncoder::encode_document()
51
│
52
▼
53
SerialTransport::open(port, 9600)
54
│
55
▼
56
print_bytes() → write_all + flush
59
57
```
60
58
61
### Transport trait
59
### `PrinterTransport` trait
62
60
63
61
```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<()>;
62
pub trait PrinterTransport {
63
fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
64
fn flush(&mut self) -> io::Result<()>;
69
65
}
70
66
```
71
67
72
### Phase rollout
68
| Type | Role |
69
|------|------|
70
| `SerialTransport` | Production — opens port via `serialport` |
71
| `MockTransport` | Tests — records bytes in `written` vec |
73
72
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 |
73
### Discovery
79
74
80
---
75
`list_usb_serial_printers()` calls `serialport::available_ports()` and labels USB ports with VID/PID when available. All serial ports are listed (no POS-specific filter).
81
76
82
## Device discovery
77
### `PrinterDevice`
83
78
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.
79
| Field | Example |
80
|-------|---------|
81
| `id` | `serial:COM3` |
82
| `display_name` | `COM3 — USB 04b8:0e15` |
83
| `port_name` | `COM3` |
121
84
122
85
---
123
86
124
## Printer picker UI
87
## Print dialog (UI)
125
88
126
89
```
127
90
┌─────────────────────────────────────────┐
128
│ Select printer │
91
│ Print │
129
92
├─────────────────────────────────────────┤
130
│ ○ COM3 — USB Serial (VID:04b8 PID:0e15)│
131
│ ○ /dev/ttyUSB0 — CH340 │
132
│ ○ \\.\USBPRINT\epson-tm-t20 │
93
│ Parameters (one field per unique name) │
94
│ DocumentNumber: [________] │
95
│ │
96
│ USB printer │
97
│ [ Refresh ] │
98
│ ○ COM3 — USB 04b8:0e15 │
99
│ ○ /dev/ttyUSB0 — Serial │
133
100
│ │
134
│ [ Refresh ] [ Print ] │
101
│ [ Cancel ] [ Print ] │
135
102
└─────────────────────────────────────────┘
136
103
```
137
104
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.
105
- Parameters pre-filled from `last_params` (session memory).
106
- Same parameter name → one input, applied everywhere.
107
- Errors shown inline (parse, open port, write, barcode validation).
148
108
149
109
---
150
110
@@ -154,105 +114,84 @@ Each `PrinterDevice` has:
154
114
Document body (DSL)
155
115
│
156
116
▼
157
Parse → AST
158
│
159
▼
160
Collect parameters (UI dialog)
117
parse() → Document
161
118
│
162
119
▼
163
Substitute params
120
collect_parameter_names() → UI dialog
164
121
│
165
122
▼
166
ESC/POS encoder (escpos crate)
123
substitute_document()
167
124
│
168
125
▼
169
Transport.write(all bytes)
126
EscPosEncoder (in-tree)
170
127
│
171
128
▼
172
Optional: read status (paper out, cover open)
129
SerialTransport::write_all
173
130
```
174
131
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
132
### Error handling (current)
192
133
193
Barcode/QR validation:
134
| Condition | Behaviour |
135
|-----------|-----------|
136
| Parse error | Block print; show in toolbar |
137
| Port open failure | `PrintError::Open` message in dialog |
138
| Write failure | `PrintError::Write` message in dialog |
139
| EAN13/EAN8 invalid length | `EscPosError::Barcode` before write |
140
| Linux permission denied | User must join `dialout` group (documented in Help) |
194
141
195
- EAN13 must be 12–13 digits after substitution
196
- Show validation errors before opening printer
142
Status polling (paper out, cover open) is **not** implemented.
197
143
198
144
---
199
145
200
## Images on printer
146
## Images
201
147
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
148
1. Resolve path relative to `.pos` file directory (or absolute path).
149
2. Decode with `image` crate.
150
3. Convert to luma8, resize to target width (%, dots, or full printable width).
151
4. Threshold to 1-bit raster.
152
5. Emit GS v 0.
206
153
207
Large images slow printing; warn if > 50% of paper width × tall.
154
Preview shows `[image: path]` only — no bitmap preview yet.
208
155
209
156
---
210
157
211
## Preview width vs print width
158
## Preview vs print width
212
159
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.
160
| `preview_mode` | Preview | Print |
161
|----------------|---------|-------|
162
| `autoscale` | Scales to panel width | Full paper width from metadata |
163
| `fixed` | Scaled by mm ratio | Full paper width |
219
164
220
165
---
221
166
222
## Security considerations
167
## Testing without hardware
223
168
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
169
| Method | Location |
170
|--------|----------|
171
| `MockTransport` | `print/mod.rs` tests |
172
| ESC/POS byte checks | `escpos.rs` tests |
173
| `cargo test` | 20 tests; no printer required |
227
174
228
175
---
229
176
230
## Testing without hardware
177
## Planned (not implemented)
231
178
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 |
179
| Feature | Notes |
180
|---------|-------|
181
| USB printer class | `nusb` / Windows `usbprint` |
182
| Bluetooth SPP | Serial port after OS pairing |
183
| Baud autodetect | Try 9600, 19200, 115200 |
184
| Printer status read | DLE EOT |
185
| Network TCP 9100 | Future |
186
| Image size warning in UI | Future |
237
187
238
188
---
239
189
240
## Dependencies (Rust)
190
## Dependencies
241
191
242
192
```toml
243
escpos = { version = "...", features = ["barcodes", "codes_2d", "graphics", "serial_port", "native_usb", "usbprint"] }
244
193
serialport = "4"
245
nusb = "0.2" # optional USB class
246
image = "0.25"
194
image = { features = ["png", "jpeg", "gif", "bmp"] }
247
195
```
248
196
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?
197
No `escpos`, `nusb`, or `rusb` crates.
@@ -1,150 +1,110 @@1
# Printing subsystem
1
# Printing subsystem
2
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).
3
Direct raw-byte printing to POS thermal printers over **USB-serial** — without the Windows print spooler or CUPS.
4
5
> **Implementation status (v0.1.0):** USB-serial only. In-tree ESC/POS encoder in `src/escpos.rs`. USB printer class and Bluetooth are **not** implemented.
4
6
5
---
7
---
6
8
7
## Goals
9
## Goals
8
10
9
1. Discover connected POS-capable devices
11
1. Discover serial ports (USB-serial adapters and CDC printers)
10
2. Let the user pick a printer in a dialog
12
2. Let the user pick a port in the print dialog
11
3. Generate ESC/POS bytes from the document AST (after parameter substitution)
13
3. Generate ESC/POS bytes from the AST (after parameter substitution)
12
4. Write bytes to the device and confirm completion (best-effort)
14
4. Write bytes at **9600 baud** (fixed for now)
13
15
14
---
16
---
15
17
16
## Protocol: ESC/POS
18
## Protocol: ESC/POS
17
19
18
Target **Epson ESC/POS** compatible printers (majority of 58 mm / 80 mm thermal printers).
20
Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
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
21
33
### Printer initialization sequence
22
### Implemented commands
34
23
35
Every print job starts with:
24
| Feature | ESC/POS | Source |
25
|---------|---------|--------|
26
| Initialize | ESC @ | `escpos.rs` |
27
| Code page | ESC t 0 (CP437) | Always CP437 today; metadata field reserved |
28
| Bold | ESC E | Headings level 2, `**text**` flattened at encode |
29
| Double size | GS ! | Heading level 1 |
30
| Alignment | ESC a | Paragraphs, images, barcodes, QR |
31
| Line feed | LF, ESC d | Text lines, `@feed` |
32
| Partial cut | GS V 66 0 | `@cut`, auto-cut after print |
33
| Barcode | GS k | CODE128, EAN13, EAN8, CODE39 |
34
| QR Code | GS ( k | Model 2 |
35
| Raster image | GS v 0 | `@image` via `image` crate → threshold |
36
36
37
```
37
Encoder: `EscPosEncoder` in `src/escpos.rs` — **not** the `escpos` crates.io package.
38
ESC @ ; reset printer
39
ESC t n ; select code page (from metadata.codepage)
40
; ... document bytes ...
41
[optional feed + cut]
42
```
43
38
44
---
39
---
45
40
46
## Transport layers
41
## Transport (implemented)
47
42
48
```
43
```
49
┌─────────────────┐
44
Print button
50
│ PrintPipeline │
45
│
51
└────────┬────────┘
46
▼
52
│
47
substitute_document()
53
┌──────────────┼──────────────┐
48
│
54
▼ ▼ ▼
49
▼
55
SerialTransport UsbTransport BtTransport
50
EscPosEncoder::encode_document()
56
│ │ │
51
│
57
serialport nusb / serialport
52
▼
58
usbprint (RFCOMM port)
53
SerialTransport::open(port, 9600)
54
│
55
▼
56
print_bytes() → write_all + flush
59
```
57
```
60
58
61
### Transport trait
59
### `PrinterTransport` trait
62
60
63
```rust
61
```rust
64
trait PrinterTransport {
62
pub trait PrinterTransport {
65
fn open(&mut self) -> Result<()>;
63
fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
66
fn write(&mut self, data: &[u8]) -> Result<()>;
64
fn flush(&mut self) -> io::Result<()>;
67
fn flush(&mut self) -> Result<()>;
68
fn close(&mut self) -> Result<()>;
69
}
65
}
70
```
66
```
71
67
72
### Phase rollout
68
| Type | Role |
69
|------|------|
70
| `SerialTransport` | Production — opens port via `serialport` |
71
| `MockTransport` | Tests — records bytes in `written` vec |
73
72
74
| Phase | Transport | Discovery |
73
### 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
74
80
---
75
`list_usb_serial_printers()` calls `serialport::available_ports()` and labels USB ports with VID/PID when available. All serial ports are listed (no POS-specific filter).
81
76
82
## Device discovery
77
### `PrinterDevice`
83
78
84
### USB-serial (MVP)
79
| Field | Example |
85
80
|-------|---------|
86
Use `serialport` crate:
81
| `id` | `serial:COM3` |
87
82
| `display_name` | `COM3 — USB 04b8:0e15` |
88
```rust
83
| `port_name` | `COM3` |
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
84
122
---
85
---
123
86
124
## Printer picker UI
87
## Print dialog (UI)
125
88
126
```
89
```
127
┌─────────────────────────────────────────┐
90
┌─────────────────────────────────────────┐
128
│ Select printer │
91
│ Print │
129
├─────────────────────────────────────────┤
92
├─────────────────────────────────────────┤
130
│ ○ COM3 — USB Serial (VID:04b8 PID:0e15)│
93
│ Parameters (one field per unique name) │
131
│ ○ /dev/ttyUSB0 — CH340 │
94
│ DocumentNumber: [________] │
132
│ ○ \\.\USBPRINT\epson-tm-t20 │
95
│ │
96
│ USB printer │
97
│ [ Refresh ] │
98
│ ○ COM3 — USB 04b8:0e15 │
99
│ ○ /dev/ttyUSB0 — Serial │
133
│ │
100
│ │
134
│ [ Refresh ] [ Print ] │
101
│ [ Cancel ] [ Print ] │
135
└─────────────────────────────────────────┘
102
└─────────────────────────────────────────┘
136
```
103
```
137
104
138
Each `PrinterDevice` has:
105
- Parameters pre-filled from `last_params` (session memory).
139
106
- Same parameter name → one input, applied everywhere.
140
| Field | Example |
107
- Errors shown inline (parse, open port, write, barcode validation).
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
108
149
---
109
---
150
110
@@ -154,105 +114,84 @@ Each `PrinterDevice` has:154
Document body (DSL)
114
Document body (DSL)
155
│
115
│
156
▼
116
▼
157
Parse → AST
117
parse() → Document
158
│
159
▼
160
Collect parameters (UI dialog)
161
│
118
│
162
▼
119
▼
163
Substitute params
120
collect_parameter_names() → UI dialog
164
│
121
│
165
▼
122
▼
166
ESC/POS encoder (escpos crate)
123
substitute_document()
167
│
124
│
168
▼
125
▼
169
Transport.write(all bytes)
126
EscPosEncoder (in-tree)
170
│
127
│
171
▼
128
▼
172
Optional: read status (paper out, cover open)
129
SerialTransport::write_all
173
```
130
```
174
131
175
### Error handling
132
### Error handling (current)
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
133
193
Barcode/QR validation:
134
| Condition | Behaviour |
135
|-----------|-----------|
136
| Parse error | Block print; show in toolbar |
137
| Port open failure | `PrintError::Open` message in dialog |
138
| Write failure | `PrintError::Write` message in dialog |
139
| EAN13/EAN8 invalid length | `EscPosError::Barcode` before write |
140
| Linux permission denied | User must join `dialout` group (documented in Help) |
194
141
195
- EAN13 must be 12–13 digits after substitution
142
Status polling (paper out, cover open) is **not** implemented.
196
- Show validation errors before opening printer
197
143
198
---
144
---
199
145
200
## Images on printer
146
## Images
201
147
202
1. Load image from path (or fail if param path invalid)
148
1. Resolve path relative to `.pos` file directory (or absolute path).
203
2. Convert to grayscale → threshold/dither
149
2. Decode with `image` crate.
204
3. Scale to target width (dots), respecting `page_width_mm`
150
3. Convert to luma8, resize to target width (%, dots, or full printable width).
205
4. Emit GS v 0 raster command
151
4. Threshold to 1-bit raster.
152
5. Emit GS v 0.
206
153
207
Large images slow printing; warn if > 50% of paper width × tall.
154
Preview shows `[image: path]` only — no bitmap preview yet.
208
155
209
---
156
---
210
157
211
## Preview width vs print width
158
## Preview vs print width
212
159
213
| Setting | Preview | Print |
160
| `preview_mode` | Preview | Print |
214
|---------|---------|-------|
161
|----------------|---------|-------|
215
| `autoscale` | Scale preview to panel width | Always full paper width |
162
| `autoscale` | Scales to panel width | Full paper width from metadata |
216
| `fixed` | Render at exact mm width | Full paper width |
163
| `fixed` | Scaled by mm ratio | Full paper width |
217
218
Print always uses physical paper width from metadata; preview is a visual aid.
219
164
220
---
165
---
221
166
222
## Security considerations
167
## Testing without hardware
223
168
224
- **Raw USB access:** only write to user-selected device; no automatic writes
169
| Method | Location |
225
- **Path traversal:** image paths must resolve under `.pos` directory or explicit absolute paths user provided
170
|--------|----------|
226
- **Bluetooth:** only paired devices user selects
171
| `MockTransport` | `print/mod.rs` tests |
172
| ESC/POS byte checks | `escpos.rs` tests |
173
| `cargo test` | 20 tests; no printer required |
227
174
228
---
175
---
229
176
230
## Testing without hardware
177
## Planned (not implemented)
231
178
232
| Method | Use |
179
| Feature | Notes |
233
|--------|-----|
180
|---------|-------|
234
| `FileTransport` | Write `.bin` ESC/POS to disk for hex inspection |
181
| USB printer class | `nusb` / Windows `usbprint` |
235
| ESC/POS emulator | [escpos-printer-emulator](https://github.com) / serial port loopback |
182
| Bluetooth SPP | Serial port after OS pairing |
236
| Snapshot tests | Compare generated bytes to golden files |
183
| Baud autodetect | Try 9600, 19200, 115200 |
184
| Printer status read | DLE EOT |
185
| Network TCP 9100 | Future |
186
| Image size warning in UI | Future |
237
187
238
---
188
---
239
189
240
## Dependencies (Rust)
190
## Dependencies
241
191
242
```toml
192
```toml
243
escpos = { version = "...", features = ["barcodes", "codes_2d", "graphics", "serial_port", "native_usb", "usbprint"] }
244
serialport = "4"
193
serialport = "4"
245
nusb = "0.2" # optional USB class
194
image = { features = ["png", "jpeg", "gif", "bmp"] }
246
image = "0.25"
247
```
195
```
248
196
249
Platform-specific features enabled per target in `build.rs` or Cargo features.
197
No `escpos`, `nusb`, or `rusb` crates.
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?