# 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 (editor + preview) / Help              │
│  - DSL parse → AST → preview + ESC/POS           │
│  - USB-direct / Win spooler / serial 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, 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)
├── bitmap_font.rs       # Checkbox glyphs (user-defined chars) + mixed-line wrap
├── preview.rs           # PreviewModel for UI canvas
├── text_wrap.rs         # Shared wrap (preview + print)
├── datetime.rs          # @date / @time formatting
├── raster.rs            # Barcode / QR bitmaps
├── 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_printers, SerialTransport, MockTransport
│   ├── usb_direct.rs    # USB printer-class (rusb)
│   └── win_spool.rs     # Windows spooler (Windows)
└── shell_integration/   # OS “Print” context menu helpers
```

### External dependencies

| Crate | Role |
|-------|------|
| `eframe` / `egui` | Native UI |
| `serde` / `serde_json` | `.pos` file format |
| `serialport` | Serial enumeration and I/O |
| `rusb` | USB printer-class devices |
| `image` | Decode/resize images |
| `rfd` | Native open/save dialogs |
| `barcoders` / `qrcode` | Raster barcodes and QR |
| `clap` | CLI |
| `chrono` | Date/time |
| `pulldown-cmark` | In-app Help markdown |

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

---

## UI structure

| Area | Module | Description |
|------|--------|-------------|
| **Design** | `app.rs` | Editor + side preview |
| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
| Settings | `app.rs` | Page width (mm), preview zoom |
| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |

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: one field per parameter; `list_printers()` for USB / spooler / serial.
3. `substitute_document` → `EscPosEncoder` → `open_printer` → `print_bytes`.
4. Serial baud is probed (`115200` first, then `9600`, …).

---

## Key types

```rust
// dsl/
struct Document { blocks: Vec<Block> }
enum Block {
    Paragraph { align, inlines },
    List { align, items },
    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) }

// 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

| Aspect | Preview | Print |
|--------|---------|-------|
| Text | egui monospace (print-matched size) | Printer Font A |
| Line width | `chars_per_line` / `printable_dots` | Same wrap model |
| Images / barcode / QR | Raster bitmaps | ESC/POS native or GS v 0 |
| Blank lines | Spacer = line spacing dots | ESC d |
| Parameters | Sample / dialog values | Substituted values |

---

## State persistence

| Data | Storage |
|------|---------|
| Template + metadata | `.pos` file |
| Last parameter values | In-memory (`print_dialog.last_params`) |
| Recent files / selected printer | Not persisted |

---

## Testing

| Layer | Location |
|-------|----------|
| DSL, params, ESC/POS, preview, wrap, I/O, print mocks | `src/**` unit tests |
| App / shell helpers | `src/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](PRINTING.md), [DSL-SPEC.md](DSL-SPEC.md), and [BUILD.md](BUILD.md).
