# System architecture

## Overview

posprint is a desktop application with a **web-based UI** (Tauri) and a **Rust backend** that owns parsing, rendering, file I/O, and printer communication.

```
┌──────────────────────────────────────────────────────────────────┐
│                         Application                              │
├────────────────────────────┬─────────────────────────────────────┤
│         UI Layer           │           Core Layer (Rust)       │
│  (TypeScript / Tauri WebView)                                    │
│                            │                                     │
│  DocumentEditor ───────────┼──► parse_dsl() → Document AST       │
│  PreviewPane ◄─────────────┼─── render_preview(ast, width)     │
│  SettingsPanel             │                                     │
│  ParameterDialog           │                                     │
│  PrinterPicker             │                                     │
│                            │                                     │
│  File menu ────────────────┼──► load_pos() / save_pos()          │
│  Print button ─────────────┼──► list_printers()                  │
│                            │    print_document(ast, params, dev) │
└────────────────────────────┴─────────────────────────────────────┘
                                      │
                    ┌─────────────────┼─────────────────┐
                    ▼                 ▼                 ▼
              Preview bitmap    ESC/POS bytes     .pos JSON file
```

---

## Modules (Rust crate layout)

```
posprint-core/          # Library — no UI, unit-testable
├── dsl/
│   ├── lexer.rs        # Tokenize source
│   ├── parser.rs       # Build AST
│   └── ast.rs          # Document, Block, Inline, Directive nodes
├── render/
│   ├── preview.rs      # Layout for UI (lines, images, barcode placeholders)
│   └── escpos.rs       # AST → ESC/POS byte buffer
├── params/
│   ├── collect.rs      # Find unique ${Name} tokens
│   └── substitute.rs   # Apply user values before render/print
├── io/
│   └── pos_file.rs     # Serde types, load/save
└── print/
    ├── discover.rs     # Enumerate serial / USB / BT devices
    ├── transport.rs    # Trait: write(bytes), read optional status
    └── pipeline.rs     # substitute → escpos → transport

posprint-app/           # Tauri binary
├── commands/           # #[tauri::command] wrappers
├── state.rs            # App state (last params, recent files)
└── main.rs
```

Frontend (`src/`):

```
src/
├── components/
│   ├── Editor.tsx
│   ├── Preview.tsx
│   ├── Toolbar.tsx
│   ├── ParameterModal.tsx
│   └── PrinterDialog.tsx
├── hooks/
│   ├── useDocument.ts
│   └── usePreview.ts
└── lib/
    └── tauri.ts        # Typed invoke wrappers
```

---

## Data flow

### Edit loop (live preview)

1. User types in editor → debounced (e.g. 150 ms) invoke `preview_document(source, settings)`.
2. Core parses DSL → AST (or returns parse errors with line/col).
3. Core renders preview model: text lines, image refs, barcode/QR placeholders sized to page width.
4. UI displays preview scaled to panel width (auto) or fixed mm width.

### Save / load

1. **Save:** UI sends `{ metadata, body }` → `save_pos(path)` → JSON on disk.
2. **Load:** `load_pos(path)` → populate editor and settings.

### Print

1. User clicks Print → `collect_parameters(ast)` → unique sorted names.
2. UI shows modal; pre-fill from `last_print_params` in app state.
3. On confirm → `print_document(ast, params, printer_id)`.
4. Core: substitute → build ESC/POS → open transport → write bytes → cut (if configured).

---

## Key types (conceptual)

```rust
struct Document {
    blocks: Vec<Block>,
}

enum Block {
    Paragraph { inlines: Vec<Inline>, align: Align },
    Heading { level: u8, text: String },
    Rule,
    Image { src: String, width: ImageWidth },  // src may be ${Param}
    Barcode { symbology: BarcodeKind, data: String, height: u8 },
    Qr { data: String, size: QrSize },
    Feed { lines: u8 },
    Cut,
}

struct PosFile {
    version: u32,
    metadata: Metadata,
    body: String,
}

struct Metadata {
    title: Option<String>,
    page_width_mm: f32,       // 58, 80, etc.
    preview_mode: PreviewMode, // AutoScale | Fixed
    codepage: Option<String>,
    cut_after_print: bool,
}

struct PrinterDevice {
    id: String,               // stable key for session
    name: String,
    transport: TransportKind,
    // ...
}
```

---

## Tauri commands (IPC surface)

| Command | Input | Output |
|---------|-------|--------|
| `parse_document` | `body: string` | `{ ast \| errors }` |
| `preview_document` | `body, metadata` | `PreviewModel` |
| `collect_parameters` | `body` | `string[]` (unique, sorted) |
| `save_pos` | `path, PosFile` | `Result<()>` |
| `load_pos` | `path` | `PosFile` |
| `list_printers` | — | `PrinterDevice[]` |
| `print_document` | `body, metadata, params, printer_id` | `Result<()>` |

---

## Preview vs print fidelity

| Aspect | Preview | Print |
|--------|---------|-------|
| Text font | UI monospace, scaled | Printer built-in font |
| Line width | Computed from `page_width_mm` | ESC/POS dot width |
| Images | Resized bitmap in canvas | Raster ESC/POS |
| Barcodes | SVG/canvas placeholder | Native printer barcode commands |
| Alignment | CSS / canvas | ESC/POS justify commands |

Both paths share the **same AST and substitution**; preview and print each have their own backend (preview renderer vs `escpos` encoder).

---

## State persistence

| Data | Storage |
|------|---------|
| Recent files | App config (Tauri `app_data_dir`) |
| Last parameter values | `params.json` keyed by template path or global |
| Window layout | Optional, Tauri store |
| Selected printer | Per-machine preference |

---

## Testing strategy

| Layer | Approach |
|-------|----------|
| DSL parser | Unit tests + snapshot fixtures |
| Parameter collect/substitute | Unit tests |
| ESC/POS encoder | Byte snapshot tests |
| Preview layout | Snapshot images (optional) |
| Printer I/O | Manual hardware matrix; mock `Transport` trait in CI |
| UI | Component tests; E2E with mocked Tauri commands |

---

## Build and release

- **CI:** GitHub Actions — `cargo test`, `cargo clippy`, frontend lint, build Windows + Linux artifacts.
- **Artifacts:** `.msi` or `.exe` (Windows), `.deb` / AppImage (Linux).
- **Versioning:** Semver; `.pos` `version` field for file format migrations.

See [PRINTING.md](PRINTING.md) for the device layer and [DSL-SPEC.md](DSL-SPEC.md) for language details.
