BlueGit

timfa posprint

Files

posprint / docs / ARCHITECTURE.md

ARCHITECTURE.md

ARCHITECTURE.md 6.8 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)                          │
│  - Design / Help / Settings                      │
│  - DSL parse → AST → preview + ESC/POS           │
│  - USB-direct / Win spooler / serial / LAN TCP printing │
│  - `.pos` JSON load/save (serde)                 │
└──────────────────────────────────────────────────┘

Source layout

src/
├── main.rs              # CLI + eframe / print-only entry
├── app.rs               # Full designer UI
├── print_only_app.rs    # Print-only window (--print)
├── print_dialog.rs      # Shared print dialog
├── cli.rs               # clap: print, link, cli-help
├── lib.rs               # crate root; HELP_MARKDOWN
├── dsl/                 # Parser and AST
├── params.rs            # Parameter collect / substitute / preview samples
├── escpos.rs            # ESC/POS byte encoder (in-tree)
├── preview.rs           # PreviewModel for UI canvas
├── text_wrap.rs         # Shared wrap (preview + print)
├── datetime.rs          # @date / @time formatting
├── raster.rs            # Barcode / QR bitmaps
├── image_load.rs        # Local + http(s) @image loading
├── protocol_url.rs      # posprint:// encode/decode
├── referrer_verify.rs   # noconfirm referrer GET (HTTP 200)
├── editor_assist.rs     # @ autocomplete, Insert snippets
├── help_view.rs         # Markdown help renderer
├── io/mod.rs            # PosFile, PosMetadata
├── pipeline.rs          # Encode / print helpers
├── print/
│   ├── mod.rs           # list_local_printers, transports, MockTransport
│   ├── network.rs       # LAN TCP 9100 transport + subnet discovery
│   ├── usb_direct.rs    # USB printer-class (rusb)
│   └── win_spool.rs     # Windows spooler (Windows)
└── shell_integration.rs # .pos Print verb + posprint:// protocol (Windows)

External dependencies

CrateRole
eframe / eguiNative UI
serde / serde_json.pos file format
serialportSerial enumeration and I/O
rusbUSB printer-class devices
imageDecode/resize images
rfdNative open/save dialogs
barcoders / qrcodeRaster barcodes and QR
clapCLI
flate2 / base64posprint:// payloads
ureq@image http(s) download
chronoDate/time
pulldown-cmarkIn-app Help markdown

ESC/POS generation is in-tree (escpos.rs), not the escpos crates.io package.

---

UI structure

AreaModuleDescription
Designapp.rsEditor + side preview
Helphelp_view.rsdocs/HELP.md via include_str!
Settingsapp.rsDefault page width; LAN printers toggle/cache; trusted noconfirm origins
Toolbarapp.rsNew, Open, Save, Save As, Insert, Print
Document page width / zoomapp.rsPer-document width (mm), preview zoom
Print dialogprint_dialog.rsParameters + multi-transport printer picker
App configconfig.rs%APPDATA%/posprint/config.json (Windows) / ~/.config/posprint/config.json (trusted origins, default width, last printer, LAN cache)

While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.

---

Data flow

Edit loop (live preview)

1. User edits the template on the Design tab. 2. Each frame, parse(&body) runs; errors show in the toolbar. 3. render_preview builds a PreviewModel (text, rules, bitmaps, spacers). 4. Canvas draws with calibrated zoom (PREVIEW_SCREEN_CALIBRATION) and Font A–matched text size.

Save / load

1. Open: rfd → PosFile::load_from_path. 2. Save / Save As: pretty-printed JSON.

@image paths resolve relative to the .pos directory on preview and print.

Print

1. Print → parse → collect_parameter_names. 2. Dialog: text field per ${Name}, checkbox per $[Name]; local printers plus optional LAN TCP 9100 discovery. 3. substitute_document → EscPosEncoder → open_printer → print_bytes. 4. Serial baud is probed (115200 first, then 9600, …). LAN uses TCP connect (default port 9100).

---

Key types

// dsl/
struct Document { blocks: Vec<Block> }
enum Block {
    Paragraph { align, inlines },
    AlignedRow { parts }, // same-line :left:/:center:/:right: → space pad
    List { align, items: Vec<ListItem> }, // ListItem { depth, inlines }
    Heading { level, align, inlines },
    Rule, Feed(u8), Cut,
    Image { path, width, align },
    Barcode { mode, symbology, data, height, align, show_text },
    Qr { mode, data, size, ecc, version, align },
    Date { format, align },
    Time { format, align },
}
enum Inline { Text(String), Param(String), CheckboxParam(String), Checkbox { checked } }

// io/
struct PosMetadata { title, page_width_mm, chars_per_line, codepage }
// printable_dots() = chars_per_line() * 12

// print/
enum PrinterTarget { Serial(String), UsbDirect { … }, WinSpooler(String) }

Legacy JSON fields preview_mode and cut_after_print are ignored if present.

---

Preview vs print fidelity

AspectPreviewPrint
Textegui monospace (print-matched size)Printer Font A
Line widthchars_per_line / printable_dotsSame wrap model
Images / barcode / QRRaster bitmapsESC/POS native or GS v 0
Blank linesSpacer = line spacing dotsESC d
ParametersSample / dialog valuesSubstituted values

---

State persistence

DataStorage
Template + metadata.pos file
Last parameter valuesIn-memory (print_dialog.last_params)
Default page width / trusted origins / last printerconfig.rs → platform config JSON
Recent filesNot persisted

---

Testing

LayerLocation
DSL, params, ESC/POS, preview, wrap, I/O, print mockssrc/** unit tests
App / shell helperssrc/main.rs tests

Run: cargo test (~100 tests). CI: tests on merge requests; release artifacts on tags.

---

Build and release

  • CI: GitLab (.gitlab-ci.yml)
  • Artifacts: Windows .exe, Debian .deb, Arch .pkg.tar.zst
  • Versioning: Semver in Cargo.toml; .pos version for file-format migrations

See PRINTING.md, DSL-SPEC.md, and BUILD.md.

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│ - Design / Help / Settings │
11│ - DSL parse → AST → preview + ESC/POS │
12│ - USB-direct / Win spooler / serial / LAN TCP printing │
13│ - `.pos` JSON load/save (serde) │
14└──────────────────────────────────────────────────┘
15```
16
17### Source layout
18
19```
20src/
21├── main.rs # CLI + eframe / print-only entry
22├── app.rs # Full designer UI
23├── print_only_app.rs # Print-only window (--print)
24├── print_dialog.rs # Shared print dialog
25├── cli.rs # clap: print, link, cli-help
26├── lib.rs # crate root; HELP_MARKDOWN
27├── dsl/ # Parser and AST
28├── params.rs # Parameter collect / substitute / preview samples
29├── escpos.rs # ESC/POS byte encoder (in-tree)
30├── preview.rs # PreviewModel for UI canvas
31├── text_wrap.rs # Shared wrap (preview + print)
32├── datetime.rs # @date / @time formatting
33├── raster.rs # Barcode / QR bitmaps
34├── image_load.rs # Local + http(s) @image loading
35├── protocol_url.rs # posprint:// encode/decode
36├── referrer_verify.rs # noconfirm referrer GET (HTTP 200)
37├── editor_assist.rs # @ autocomplete, Insert snippets
38├── help_view.rs # Markdown help renderer
39├── io/mod.rs # PosFile, PosMetadata
40├── pipeline.rs # Encode / print helpers
41├── print/
42│ ├── mod.rs # list_local_printers, transports, MockTransport
43│ ├── network.rs # LAN TCP 9100 transport + subnet discovery
44│ ├── usb_direct.rs # USB printer-class (rusb)
45│ └── win_spool.rs # Windows spooler (Windows)
46└── shell_integration.rs # .pos Print verb + posprint:// protocol (Windows)
47```
48
49### External dependencies
50
51| Crate | Role |
52|-------|------|
53| `eframe` / `egui` | Native UI |
54| `serde` / `serde_json` | `.pos` file format |
55| `serialport` | Serial enumeration and I/O |
56| `rusb` | USB printer-class devices |
57| `image` | Decode/resize images |
58| `rfd` | Native open/save dialogs |
59| `barcoders` / `qrcode` | Raster barcodes and QR |
60| `clap` | CLI |
61| `flate2` / `base64` | `posprint://` payloads |
62| `ureq` | `@image http(s)` download |
63| `chrono` | Date/time |
64| `pulldown-cmark` | In-app Help markdown |
65
66ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io package.
67
68---
69
70## UI structure
71
72| Area | Module | Description |
73|------|--------|-------------|
74| **Design** | `app.rs` | Editor + side preview |
75| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |
76| **Settings** | `app.rs` | Default page width; LAN printers toggle/cache; trusted `noconfirm` origins |
77| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
78| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
79| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |
80| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (trusted origins, default width, last printer, LAN cache) |
81
82While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
83
84---
85
86## Data flow
87
88### Edit loop (live preview)
89
901. User edits the template on the Design tab.
912. Each frame, `parse(&body)` runs; errors show in the toolbar.
923. `render_preview` builds a `PreviewModel` (text, rules, bitmaps, spacers).
934. Canvas draws with calibrated zoom (`PREVIEW_SCREEN_CALIBRATION`) and Font A–matched text size.
94
95### Save / load
96
971. **Open:** `rfd` → `PosFile::load_from_path`.
982. **Save / Save As:** pretty-printed JSON.
99
100`@image` paths resolve relative to the `.pos` directory on preview and print.
101
102### Print
103
1041. **Print** → parse → `collect_parameter_names`.
1052. Dialog: text field per `${Name}`, checkbox per `$[Name]`; local printers plus optional LAN TCP 9100 discovery.
1063. `substitute_document` → `EscPosEncoder` → `open_printer` → `print_bytes`.
1074. Serial baud is probed (`115200` first, then `9600`, …). LAN uses TCP connect (default port 9100).
108
109---
110
111## Key types
112
113```rust
114// dsl/
115struct Document { blocks: Vec<Block> }
116enum Block {
117 Paragraph { align, inlines },
118 AlignedRow { parts }, // same-line :left:/:center:/:right: → space pad
119 List { align, items: Vec<ListItem> }, // ListItem { depth, inlines }
120 Heading { level, align, inlines },
121 Rule, Feed(u8), Cut,
122 Image { path, width, align },
123 Barcode { mode, symbology, data, height, align, show_text },
124 Qr { mode, data, size, ecc, version, align },
125 Date { format, align },
126 Time { format, align },
127}
128enum Inline { Text(String), Param(String), CheckboxParam(String), Checkbox { checked } }
129
130// io/
131struct PosMetadata { title, page_width_mm, chars_per_line, codepage }
132// printable_dots() = chars_per_line() * 12
133
134// print/
135enum PrinterTarget { Serial(String), UsbDirect { … }, WinSpooler(String) }
136```
137
138Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.
139
140---
141
142## Preview vs print fidelity
143
144| Aspect | Preview | Print |
145|--------|---------|-------|
146| Text | egui monospace (print-matched size) | Printer Font A |
147| Line width | `chars_per_line` / `printable_dots` | Same wrap model |
148| Images / barcode / QR | Raster bitmaps | ESC/POS native or GS v 0 |
149| Blank lines | Spacer = line spacing dots | ESC d |
150| Parameters | Sample / dialog values | Substituted values |
151
152---
153
154## State persistence
155
156| Data | Storage |
157|------|---------|
158| Template + metadata | `.pos` file |
159| Last parameter values | In-memory (`print_dialog.last_params`) |
160| Default page width / trusted origins / last printer | `config.rs` → platform config JSON |
161| Recent files | Not persisted |
162
163---
164
165## Testing
166
167| Layer | Location |
168|-------|----------|
169| DSL, params, ESC/POS, preview, wrap, I/O, print mocks | `src/**` unit tests |
170| App / shell helpers | `src/main.rs` tests |
171
172Run: `cargo test` (~100 tests). CI: tests on merge requests; release artifacts on tags.
173
174---
175
176## Build and release
177
178- **CI:** GitLab (`.gitlab-ci.yml`)
179- **Artifacts:** Windows `.exe`, Debian `.deb`, Arch `.pkg.tar.zst`
180- **Versioning:** Semver in `Cargo.toml`; `.pos` `version` for file-format migrations
181
182See [PRINTING.md](PRINTING.md), [DSL-SPEC.md](DSL-SPEC.md), and [BUILD.md](BUILD.md).