# 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)

| Crate | Role |
|-------|------|
| `eframe` / `egui` | Native UI |
| `serde` / `serde_json` | `.pos` file format |
| `serialport` | USB-serial enumeration and I/O |
| `image` | Decode/resize images for `@image` raster print |
| `rfd` | Native open/save file dialogs |

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

---

## UI structure

| Tab / area | Module | Description |
|------------|--------|-------------|
| **Editor** | `app.rs` | Multiline `TextEdit` (monospace) for template source |
| **Preview** | `app.rs` + `preview.rs` | Canvas render of `PreviewModel`; auto-scale or fixed mm |
| **Help** | `app.rs` | Scrollable view of `docs/HELP.md` via `include_str!` |
| Toolbar | `app.rs` | New, Open, Save, Save As, Print |
| Settings | `app.rs` | Page width (mm), preview mode |
| Print dialog | `app.rs` | Parameter 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`:

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

| Aspect | Preview | Print |
|--------|---------|-------|
| Text font | egui monospace/proportional | Printer built-in font |
| Line width | From `chars_per_line()` | ESC/POS dot width from `page_width_mm` |
| Images | `[image: path]` placeholder | Monochrome raster (GS v 0) |
| Barcodes / QR | Text placeholder | Native ESC/POS commands |
| Alignment | Canvas positioning | ESC a |

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

---

## State persistence (current)

| Data | Storage | Notes |
|------|---------|-------|
| Template + metadata | `.pos` file on disk | User saves explicitly |
| Last parameter values | `PosPrintApp.last_params` | In-memory only; lost on quit |
| Recent files | — | Not implemented |
| Selected printer | — | Not persisted between sessions |

---

## Testing

| Layer | Location | Approach |
|-------|----------|----------|
| DSL parser | `dsl/parser.rs` | Unit tests |
| Parameters | `params.rs` | Unit tests |
| ESC/POS encoder | `escpos.rs` | Byte structure tests |
| Preview | `preview.rs` | Unit tests |
| `.pos` I/O | `io/mod.rs` | Round-trip + tempfile tests |
| Printer I/O | `print/mod.rs` | `MockTransport`; no hardware in CI |
| App | `app.rs` | Default 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](PRINTING.md) and [DSL-SPEC.md](DSL-SPEC.md) for protocol and language details.
