BlueGit

timfa posprint

Files

posprint / docs / ARCHITECTURE.md

ARCHITECTURE.md

ARCHITECTURE.md 6.2 KiB Download Raw

System architecture

Overview

posprint is a single Rust binary using egui (eframe). No separate frontend language, no WebView, no IPC layer.

┌─────────────────────────────────────────┐
│  posprint (Rust + egui)                 │
│  - Editor / Preview / Help tabs         │
│  - DSL parse → AST                      │
│  - Preview layout + in-tree ESC/POS     │
│  - USB-serial printer discovery/print   │
│  - `.pos` JSON load/save (serde)        │
└─────────────────────────────────────────┘

Source layout

src/
├── main.rs             # eframe entry point
├── app.rs              # egui UI (editor, preview, help, print dialog)
├── lib.rs              # crate root; exports + HELP_MARKDOWN
├── dsl/                # Parser and AST (mod.rs, parser.rs)
├── params.rs           # Parameter collect/substitute
├── escpos.rs           # ESC/POS byte encoder (in-tree)
├── preview.rs          # Preview model for UI canvas
├── io/mod.rs           # .pos file format (PosFile, PosMetadata)
└── print/mod.rs        # USB-serial discovery, SerialTransport, MockTransport

External dependencies (minimal)

CrateRole
eframe / eguiNative UI
serde / serde_json.pos file format
serialportUSB-serial enumeration and I/O
imageDecode/resize images for @image raster print
rfdNative open/save file dialogs

ESC/POS command generation is not delegated to a third-party crate.

---

UI structure

Tab / areaModuleDescription
Editorapp.rsMultiline TextEdit (monospace) for template source
Previewapp.rs + preview.rsCanvas render of PreviewModel; auto-scale or fixed mm
Helpapp.rsScrollable view of docs/HELP.md via include_str!
Toolbarapp.rsNew, Open, Save, Save As, Print
Settingsapp.rsPage width (mm), preview mode
Print dialogapp.rsParameter fields + USB-serial printer picker

Bottom panel switches tabs. Top panel holds actions and settings.

---

Data flow

Edit loop (live preview)

1. User types in the Editor tab. 2. Each frame, parse(&body) runs; errors show in the toolbar. 3. On Preview tab, render_preview(&doc, &metadata) builds a PreviewModel. 4. Canvas draws text lines, rules, and placeholders for barcode/QR/image.

Preview is not debounced — it re-parses when the Preview tab is shown (and parse runs every frame for error display).

Save / load

1. Open: rfd file dialog → PosFile::load_from_path → populate body, metadata, file_path. 2. Save / Save As: PosFile::save_to_path writes pretty-printed JSON.

Image paths in @image resolve relative to the .pos file directory on print.

Print

1. User clicks Print → parse body → collect_parameter_names(&doc). 2. Modal shows one field per unique parameter; pre-filled from last_params (in-memory). 3. User selects a USB-serial port from list_usb_serial_printers(). 4. substitute_document → EscPosEncoder::encode_document → SerialTransport::open (9600 baud) → print_bytes.

---

Key types

Implemented in dsl/mod.rs, io/mod.rs, print/mod.rs:

// dsl/
struct Document { blocks: Vec<Block> }

enum Block {
    Paragraph { align, inlines },
    Heading { level, inlines },
    Rule,
    Feed(u8),
    Cut,
    Image { path, width: ImageWidth, align },
    Barcode { symbology, data, height, align, show_text },
    Qr { data, size, ecc, align },
}

// io/
struct PosFile { version, metadata: PosMetadata, body }
struct PosMetadata { title, page_width_mm, preview_mode, chars_per_line, codepage }

// print/
struct PrinterDevice { id, display_name, port_name }
trait PrinterTransport { write_all, flush }

---

Preview vs print fidelity

AspectPreviewPrint
Text fontegui monospace/proportionalPrinter built-in font
Line widthFrom chars_per_line()ESC/POS dot width from page_width_mm
Images[image: path] placeholderMonochrome raster (GS v 0)
Barcodes / QRText placeholderNative ESC/POS commands
AlignmentCanvas positioningESC a

Both paths share the same AST; substitution happens only at print time. Preview shows unresolved ${Param} tokens as-is.

---

State persistence (current)

DataStorageNotes
Template + metadata.pos file on diskUser saves explicitly
Last parameter valuesPosPrintApp.last_paramsIn-memory only; lost on quit
Recent files—Not implemented
Selected printer—Not persisted between sessions

---

Testing

LayerLocationApproach
DSL parserdsl/parser.rsUnit tests
Parametersparams.rsUnit tests
ESC/POS encoderescpos.rsByte structure tests
Previewpreview.rsUnit tests
.pos I/Oio/mod.rsRound-trip + tempfile tests
Printer I/Oprint/mod.rsMockTransport; no hardware in CI
Appapp.rsDefault template parse/param tests

Run: cargo test (20 tests). CI runs this on Linux (Docker) and Windows (shell runner).

---

Build and release

  • CI: GitLab (.gitlab-ci.yml) — cargo test on push; release artifacts on tags.
  • Linux artifact: .deb via cargo-deb ([package.metadata.deb] in Cargo.toml).
  • Windows artifact: target/release/posprint.exe.
  • Versioning: Semver in Cargo.toml; .pos version field for file-format migrations.

---

Planned (not implemented)

  • USB printer class (bulk OUT) without serial emulation
  • Bluetooth SPP
  • Network printers (TCP 9100)
  • Baud-rate autodetect / settings UI
  • Persisted last parameters and recent files
  • Syntax highlighting in editor

See PRINTING.md and DSL-SPEC.md for protocol and language details.

Source
1# System architecture
2
3## Overview
4
5posprint is a **single Rust binary** using **egui** (eframe). No separate frontend language, no WebView, no IPC layer.
6
7```
8┌─────────────────────────────────────────┐
9│ posprint (Rust + egui) │
10│ - Editor / Preview / Help tabs │
11│ - DSL parse → AST │
12│ - Preview layout + in-tree ESC/POS │
13│ - USB-serial printer discovery/print │
14│ - `.pos` JSON load/save (serde) │
15└─────────────────────────────────────────┘
16```
17
18### Source layout
19
20```
21src/
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)
26├── params.rs # Parameter collect/substitute
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
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
43ESC/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
58Bottom panel switches tabs. Top panel holds actions and settings.
59
60---
61
62## Data flow
63
64### Edit loop (live preview)
65
661. User types in the Editor tab.
672. Each frame, `parse(&body)` runs; errors show in the toolbar.
683. On Preview tab, `render_preview(&doc, &metadata)` builds a `PreviewModel`.
694. Canvas draws text lines, rules, and placeholders for barcode/QR/image.
70
71Preview is **not debounced** — it re-parses when the Preview tab is shown (and parse runs every frame for error display).
72
73### Save / load
74
751. **Open:** `rfd` file dialog → `PosFile::load_from_path` → populate `body`, `metadata`, `file_path`.
762. **Save / Save As:** `PosFile::save_to_path` writes pretty-printed JSON.
77
78Image paths in `@image` resolve relative to the `.pos` file directory on print.
79
80### Print
81
821. User clicks **Print** → parse body → `collect_parameter_names(&doc)`.
832. Modal shows one field per unique parameter; pre-filled from `last_params` (in-memory).
843. User selects a USB-serial port from `list_usb_serial_printers()`.
854. `substitute_document` → `EscPosEncoder::encode_document` → `SerialTransport::open` (9600 baud) → `print_bytes`.
86
87---
88
89## Key types
90
91Implemented in `dsl/mod.rs`, `io/mod.rs`, `print/mod.rs`:
92
93```rust
94// dsl/
95struct Document { blocks: Vec<Block> }
96
97enum Block {
98 Paragraph { align, inlines },
99 Heading { level, inlines },
100 Rule,
101 Feed(u8),
102 Cut,
103 Image { path, width: ImageWidth, align },
104 Barcode { symbology, data, height, align, show_text },
105 Qr { data, size, ecc, align },
106}
107
108// io/
109struct PosFile { version, metadata: PosMetadata, body }
110struct PosMetadata { title, page_width_mm, preview_mode, chars_per_line, codepage }
111
112// print/
113struct PrinterDevice { id, display_name, port_name }
114trait PrinterTransport { write_all, flush }
115```
116
117---
118
119## Preview vs print fidelity
120
121| Aspect | Preview | Print |
122|--------|---------|-------|
123| Text font | egui monospace/proportional | Printer built-in font |
124| Line width | From `chars_per_line()` | ESC/POS dot width from `page_width_mm` |
125| Images | `[image: path]` placeholder | Monochrome raster (GS v 0) |
126| Barcodes / QR | Text placeholder | Native ESC/POS commands |
127| Alignment | Canvas positioning | ESC a |
128
129Both paths share the same **AST**; substitution happens only at print time. Preview shows unresolved `${Param}` tokens as-is.
130
131---
132
133## State persistence (current)
134
135| Data | Storage | Notes |
136|------|---------|-------|
137| Template + metadata | `.pos` file on disk | User saves explicitly |
138| Last parameter values | `PosPrintApp.last_params` | In-memory only; lost on quit |
139| Recent files | — | Not implemented |
140| Selected printer | — | Not persisted between sessions |
141
142---
143
144## Testing
145
146| Layer | Location | Approach |
147|-------|----------|----------|
148| DSL parser | `dsl/parser.rs` | Unit tests |
149| Parameters | `params.rs` | Unit tests |
150| ESC/POS encoder | `escpos.rs` | Byte structure tests |
151| Preview | `preview.rs` | Unit tests |
152| `.pos` I/O | `io/mod.rs` | Round-trip + tempfile tests |
153| Printer I/O | `print/mod.rs` | `MockTransport`; no hardware in CI |
154| App | `app.rs` | Default template parse/param tests |
155
156Run: `cargo test` (20 tests). CI runs this on Linux (Docker) and Windows (shell runner).
157
158---
159
160## Build and release
161
162- **CI:** GitLab (`.gitlab-ci.yml`) — `cargo test` on push; release artifacts on tags.
163- **Linux artifact:** `.deb` via `cargo-deb` (`[package.metadata.deb]` in `Cargo.toml`).
164- **Windows artifact:** `target/release/posprint.exe`.
165- **Versioning:** Semver in `Cargo.toml`; `.pos` `version` field for file-format migrations.
166
167---
168
169## Planned (not implemented)
170
171- USB printer class (bulk OUT) without serial emulation
172- Bluetooth SPP
173- Network printers (TCP 9100)
174- Baud-rate autodetect / settings UI
175- Persisted last parameters and recent files
176- Syntax highlighting in editor
177
178See [PRINTING.md](PRINTING.md) and [DSL-SPEC.md](DSL-SPEC.md) for protocol and language details.