From 4562f0cebbbe6b66995e1f17e6ea7ebe5137aec7 Mon Sep 17 00:00:00 2001 From: William Gill Date: Mon, 30 Nov 2026 00:49:45 -0600 Subject: [PATCH] Add box, rule and kv blocks, text folding and receipt preview Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from one /print element, and a way to see a receipt without using paper. - receipt: box, rule and kv elements, laid out when the job renders from the printer profile, size and font (never fixed widths). Boxes take a title (inline or capped), a footer, padding, fit and columns, and a body of text or children (text, feed, kv, and rules as dividers joined to the borders). Glyphs a code page lacks fall back per set: double-h and double-v to double, then single, then ascii; a missing junction switches line weight first. - Validation names nested elements (elements[0].children[3] (qr)), checks fields per block type, allows one level of children and counts them toward the 500-element limit. Block fields on the older types are problems, as they were unknown fields before. - Text is composed to NFC and characters the code page lacks fold to look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro, trademark), as the owner approved on 2026-11-29. An emoji sequence prints as one '?'. Encodable text is untouched. - escpos: CodePage.CanEncode and Decode, and Interpret, which reads a command stream back as the printer would print it. It takes the profile so that it can follow the printer's own wrapping and alignment; raw spans stay opaque. - POST /api/v1/preview and `uberbringer preview` show the lines a job prints, as text or JSON with styles, without fetching images. - Config: [format] max_lines (default 2000), refused with 422 too_many_lines on preview; printer.box_line_spacing (default 0). Byte compatibility: testdata/compat fixtures were rendered by 9b91109 before the renderer changed, and still match it and the new renderer. examples/blocks.json was printed on the TM-T88IV; the owner judged the border gaps at the default spacing fine (2026-11-30), so box_line_spacing stays 0, and TestPaperReceipts pins its bytes. Co-Authored-By: Claude Opus 5.5 --- .editorconfig | 4 + CHANGELOG.md | 46 ++ README.md | 249 +++++++- configs/config.example.toml | 10 + docs/design.md | 40 +- docs/plans/formatters.md | 375 +----------- examples/blocks.json | 58 ++ internal/app/uberbringer/cli.go | 1 + internal/app/uberbringer/preview.go | 175 ++++++ internal/app/uberbringer/preview_test.go | 138 +++++ internal/app/uberbringer/serve.go | 47 +- internal/app/uberbringer/server/errors.go | 1 + internal/app/uberbringer/server/handlers.go | 58 +- .../uberbringer/server/handlers_preview.go | 100 ++++ internal/app/uberbringer/server/server.go | 32 +- .../app/uberbringer/server/server_test.go | 137 ++++- .../app/uberbringer/testdata/preview-job.json | 10 + internal/app/uberbringer/testdata/preview.txt | 13 + internal/pkg/config/config.go | 24 + internal/pkg/config/config_test.go | 33 +- internal/pkg/escpos/builder.go | 3 + internal/pkg/escpos/codepage.go | 35 ++ internal/pkg/escpos/codepage_test.go | 113 ++++ internal/pkg/escpos/interpret.go | 556 ++++++++++++++++++ internal/pkg/escpos/interpret_test.go | 231 ++++++++ internal/pkg/receipt/block.go | 336 +++++++++++ internal/pkg/receipt/blocklayout.go | 405 +++++++++++++ internal/pkg/receipt/blocks_test.go | 356 +++++++++++ internal/pkg/receipt/cells.go | 83 +++ internal/pkg/receipt/compat_test.go | 195 ++++++ internal/pkg/receipt/fuzz_test.go | 170 ++++++ internal/pkg/receipt/glyphs.go | 145 +++++ internal/pkg/receipt/golden_test.go | 152 +++++ internal/pkg/receipt/job.go | 144 ++++- internal/pkg/receipt/normalize.go | 162 +++++ internal/pkg/receipt/normalize_test.go | 90 +++ internal/pkg/receipt/preview.go | 137 +++++ internal/pkg/receipt/receipt_test.go | 59 +- internal/pkg/receipt/render.go | 216 ++++++- .../testdata/blocks/box-children.cp1252.txt | 15 + .../testdata/blocks/box-children.cp437.txt | 15 + .../testdata/blocks/box-children.cp850.txt | 15 + .../receipt/testdata/blocks/box-children.json | 13 + .../testdata/blocks/box-fit.cp1252.txt | 52 ++ .../receipt/testdata/blocks/box-fit.cp437.txt | 52 ++ .../receipt/testdata/blocks/box-fit.cp850.txt | 52 ++ .../pkg/receipt/testdata/blocks/box-fit.json | 18 + .../testdata/blocks/box-padding.cp1252.txt | 16 + .../testdata/blocks/box-padding.cp437.txt | 16 + .../testdata/blocks/box-padding.cp850.txt | 16 + .../receipt/testdata/blocks/box-padding.json | 6 + .../testdata/blocks/box-scale.cp1252.txt | 22 + .../testdata/blocks/box-scale.cp437.txt | 22 + .../testdata/blocks/box-scale.cp850.txt | 22 + .../receipt/testdata/blocks/box-scale.json | 8 + .../testdata/blocks/box-styles.cp1252.txt | 41 ++ .../testdata/blocks/box-styles.cp437.txt | 41 ++ .../testdata/blocks/box-styles.cp850.txt | 41 ++ .../receipt/testdata/blocks/box-styles.json | 14 + .../testdata/blocks/box-titles.cp1252.txt | 23 + .../testdata/blocks/box-titles.cp437.txt | 23 + .../testdata/blocks/box-titles.cp850.txt | 23 + .../receipt/testdata/blocks/box-titles.json | 9 + .../testdata/blocks/dividers.cp1252.txt | 45 ++ .../testdata/blocks/dividers.cp437.txt | 45 ++ .../testdata/blocks/dividers.cp850.txt | 45 ++ .../pkg/receipt/testdata/blocks/dividers.json | 46 ++ .../receipt/testdata/blocks/folds.cp1252.txt | 15 + .../receipt/testdata/blocks/folds.cp437.txt | 15 + .../receipt/testdata/blocks/folds.cp850.txt | 15 + .../pkg/receipt/testdata/blocks/folds.json | 7 + .../pkg/receipt/testdata/blocks/kv.cp1252.txt | 29 + .../pkg/receipt/testdata/blocks/kv.cp437.txt | 27 + .../pkg/receipt/testdata/blocks/kv.cp850.txt | 27 + internal/pkg/receipt/testdata/blocks/kv.json | 24 + .../testdata/blocks/mockups.cp1252.txt | 24 + .../receipt/testdata/blocks/mockups.cp437.txt | 24 + .../receipt/testdata/blocks/mockups.cp850.txt | 24 + .../pkg/receipt/testdata/blocks/mockups.json | 17 + .../receipt/testdata/blocks/rules.cp1252.txt | 22 + .../receipt/testdata/blocks/rules.cp437.txt | 22 + .../receipt/testdata/blocks/rules.cp850.txt | 22 + .../pkg/receipt/testdata/blocks/rules.json | 23 + .../pkg/receipt/testdata/compat/cp1252.hex | 8 + .../pkg/receipt/testdata/compat/cp1252.json | 10 + .../pkg/receipt/testdata/compat/cp437.hex | 17 + .../pkg/receipt/testdata/compat/cp437.json | 13 + .../pkg/receipt/testdata/compat/cp850.hex | 6 + .../pkg/receipt/testdata/compat/cp850.json | 10 + .../pkg/receipt/testdata/compat/cp858.hex | 4 + .../pkg/receipt/testdata/compat/cp858.json | 9 + .../pkg/receipt/testdata/compat/elements.hex | 36 ++ .../pkg/receipt/testdata/compat/elements.json | 25 + .../pkg/receipt/testdata/compat/images.hex | 45 ++ .../pkg/receipt/testdata/compat/images.json | 10 + .../pkg/receipt/testdata/compat/inline.hex | 22 + .../pkg/receipt/testdata/compat/inline.json | 19 + .../pkg/receipt/testdata/compat/narrow.hex | 9 + .../pkg/receipt/testdata/compat/narrow.json | 10 + .../pkg/receipt/testdata/compat/nowrap.hex | 13 + .../pkg/receipt/testdata/compat/nowrap.json | 11 + .../receipt/testdata/compat/text-styles.hex | 20 + .../receipt/testdata/compat/text-styles.json | 20 + .../pkg/receipt/testdata/compat/tm-t20.hex | 11 + .../pkg/receipt/testdata/compat/tm-t20.json | 10 + internal/pkg/receipt/testdata/compat/wrap.hex | 33 ++ .../pkg/receipt/testdata/compat/wrap.json | 14 + .../pkg/receipt/testdata/paper/blocks.hex | 121 ++++ internal/pkg/receipt/validate_test.go | 132 +++++ 109 files changed, 6383 insertions(+), 487 deletions(-) create mode 100644 examples/blocks.json create mode 100644 internal/app/uberbringer/preview.go create mode 100644 internal/app/uberbringer/preview_test.go create mode 100644 internal/app/uberbringer/server/handlers_preview.go create mode 100644 internal/app/uberbringer/testdata/preview-job.json create mode 100644 internal/app/uberbringer/testdata/preview.txt create mode 100644 internal/pkg/escpos/codepage_test.go create mode 100644 internal/pkg/escpos/interpret.go create mode 100644 internal/pkg/escpos/interpret_test.go create mode 100644 internal/pkg/receipt/block.go create mode 100644 internal/pkg/receipt/blocklayout.go create mode 100644 internal/pkg/receipt/blocks_test.go create mode 100644 internal/pkg/receipt/cells.go create mode 100644 internal/pkg/receipt/compat_test.go create mode 100644 internal/pkg/receipt/fuzz_test.go create mode 100644 internal/pkg/receipt/glyphs.go create mode 100644 internal/pkg/receipt/golden_test.go create mode 100644 internal/pkg/receipt/normalize.go create mode 100644 internal/pkg/receipt/normalize_test.go create mode 100644 internal/pkg/receipt/preview.go create mode 100644 internal/pkg/receipt/testdata/blocks/box-children.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-children.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-children.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-children.json create mode 100644 internal/pkg/receipt/testdata/blocks/box-fit.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-fit.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-fit.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-fit.json create mode 100644 internal/pkg/receipt/testdata/blocks/box-padding.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-padding.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-padding.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-padding.json create mode 100644 internal/pkg/receipt/testdata/blocks/box-scale.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-scale.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-scale.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-scale.json create mode 100644 internal/pkg/receipt/testdata/blocks/box-styles.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-styles.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-styles.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-styles.json create mode 100644 internal/pkg/receipt/testdata/blocks/box-titles.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-titles.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-titles.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/box-titles.json create mode 100644 internal/pkg/receipt/testdata/blocks/dividers.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/dividers.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/dividers.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/dividers.json create mode 100644 internal/pkg/receipt/testdata/blocks/folds.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/folds.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/folds.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/folds.json create mode 100644 internal/pkg/receipt/testdata/blocks/kv.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/kv.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/kv.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/kv.json create mode 100644 internal/pkg/receipt/testdata/blocks/mockups.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/mockups.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/mockups.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/mockups.json create mode 100644 internal/pkg/receipt/testdata/blocks/rules.cp1252.txt create mode 100644 internal/pkg/receipt/testdata/blocks/rules.cp437.txt create mode 100644 internal/pkg/receipt/testdata/blocks/rules.cp850.txt create mode 100644 internal/pkg/receipt/testdata/blocks/rules.json create mode 100644 internal/pkg/receipt/testdata/compat/cp1252.hex create mode 100644 internal/pkg/receipt/testdata/compat/cp1252.json create mode 100644 internal/pkg/receipt/testdata/compat/cp437.hex create mode 100644 internal/pkg/receipt/testdata/compat/cp437.json create mode 100644 internal/pkg/receipt/testdata/compat/cp850.hex create mode 100644 internal/pkg/receipt/testdata/compat/cp850.json create mode 100644 internal/pkg/receipt/testdata/compat/cp858.hex create mode 100644 internal/pkg/receipt/testdata/compat/cp858.json create mode 100644 internal/pkg/receipt/testdata/compat/elements.hex create mode 100644 internal/pkg/receipt/testdata/compat/elements.json create mode 100644 internal/pkg/receipt/testdata/compat/images.hex create mode 100644 internal/pkg/receipt/testdata/compat/images.json create mode 100644 internal/pkg/receipt/testdata/compat/inline.hex create mode 100644 internal/pkg/receipt/testdata/compat/inline.json create mode 100644 internal/pkg/receipt/testdata/compat/narrow.hex create mode 100644 internal/pkg/receipt/testdata/compat/narrow.json create mode 100644 internal/pkg/receipt/testdata/compat/nowrap.hex create mode 100644 internal/pkg/receipt/testdata/compat/nowrap.json create mode 100644 internal/pkg/receipt/testdata/compat/text-styles.hex create mode 100644 internal/pkg/receipt/testdata/compat/text-styles.json create mode 100644 internal/pkg/receipt/testdata/compat/tm-t20.hex create mode 100644 internal/pkg/receipt/testdata/compat/tm-t20.json create mode 100644 internal/pkg/receipt/testdata/compat/wrap.hex create mode 100644 internal/pkg/receipt/testdata/compat/wrap.json create mode 100644 internal/pkg/receipt/testdata/paper/blocks.hex create mode 100644 internal/pkg/receipt/validate_test.go diff --git a/.editorconfig b/.editorconfig index 804550f..6a9e8dd 100644 --- a/.editorconfig +++ b/.editorconfig @@ -20,3 +20,7 @@ indent_size = 2 [*.md] trim_trailing_whitespace = false + +# Golden files hold printed lines, whose trailing spaces are part of them. +[**/testdata/**] +trim_trailing_whitespace = false diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a0aa53..80d9685 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,52 @@ version may break callers; such changes are listed under **Breaking**. ## [Unreleased] +### Added + +- Blocks, laid out to the printer model's width when the job prints: + - `box`: `single`, `double`, `double-h`, `double-v` or `ascii` borders, a + title set into the top border (`inline` or `capped`), a footer in the + bottom border, `padding`, `fit` and `columns`. Its body is `text` or + `children`: text, feed, kv and rules, which print as dividers joined to + the borders. + - `rule`: nine line styles, from `single` and `double` to shades, dashes + and dots, with an optional label. + - `kv`: key-value rows joined by a leader; long values wrap. + + `size` (1–3) and `font` scale a block's borders and text together. On + cp850, cp858 and cp1252, glyphs the code page lacks fall back to ones it + has. README § Blocks lists the fields. +- `POST /api/v1/preview` and `uberbringer preview [file.json|-]` show the + lines a job would print, read back from its rendered bytes, without + printing it or fetching images. The route answers plain text, or JSON with + the styled runs, the line count and warnings for characters printed as + `?`. +- `[format]` with `max_lines` (default 2000): a job that would print more + lines fails instead of printing. `/api/v1/preview` answers such a job with + `422` and the new code `too_many_lines`. +- `printer.box_line_spacing` (default 0): the line spacing used while a box + prints, to close the gaps in its vertical borders. The default, the + printer's own spacing, was checked on paper on the TM-T88IV. +- `examples/blocks.json`, a receipt with every block style, padding, size + and junction, for checking the borders on paper. + +### Changed + +- Text is composed to Unicode NFC before it is printed, so a decomposed `é` + prints as `é`. Characters the code page lacks fold to look-alikes instead + of printing as `?`: curly quotes print as `"` and `'`, `–` as `-`, `—` as + `--`, `…` as `...`, `•` as `·`, `→ ←` as `-> <-`, `✓ ✔` as `√` (or `x`), + `×` as `x`, `€` as `EUR` and `™` as `TM`. An emoji sequence, with its skin + tone, variation selector or joined emoji, prints as one `?` instead of + one per code point, and zero-width spaces and joiners are removed. A + character the code page has prints as before, so cp1252 keeps its curly + quotes and cp858 its `€`. +- `invalid_job` details name nested elements by their path, e.g. + `elements[0].children[3] (qr): not allowed inside a box; place it after the + box`. A block field on another element type, such as `title` on `text`, is + listed there (`field "title" does not apply to text`) instead of failing + the whole decode as an unknown field. + ## [0.2.0] - 2026-11-30 The daemon is rewritten, and so are its install script and release process, diff --git a/README.md b/README.md index 943dab8..9ddc565 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,15 @@ REST API and prints them on an EPSON ESC/POS network receipt printer. order on a background worker, with retries when the printer is offline. - **Plain-text input**: send UTF-8 text, including accents, `£ ° ±` and box-drawing `┌─┐│└┘░▒▓`. It is transcoded to the printer's code page - (CP437 by default). + (CP437 by default), and typographic quotes, dashes and the ellipsis + print as ASCII look-alikes where the code page lacks them. - **Word wrap**: text wraps at word boundaries for the paper width and character size, so words are never cut in half. - **Rich elements**: bold, underline, inverse, sizes 1–8, two fonts, alignment, QR codes, EAN/UPC/CODE39/CODE128 barcodes, images, raw ESC/POS. +- **Boxes, rules and key-value rows**: single or double CP437 borders with + titles, dividers and footers, sized to the paper when the job prints. +- **Preview**: see the exact lines a job prints, without using paper. - **Images that print well**: PNG, JPEG, GIF or WebP from a URL or base64, scaled to the paper and dithered. Image URLs can't reach internal network addresses unless you allow it. @@ -23,6 +27,7 @@ REST API and prints them on an EPSON ESC/POS network receipt printer. - [Quick start](#quick-start) - [API](#api) - [Elements](#elements) +- [Blocks](#blocks) - [Migrating from the old format](#migrating-from-the-old-format) - [Configuration](#configuration) - [Command line](#command-line) @@ -121,6 +126,7 @@ included, carry `Cache-Control: no-store`. | Method | Path | Purpose | |--------|--------------------|------------------------------------------| | POST | `/api/v1/print` | Queue a print job | +| POST | `/api/v1/preview` | Show the lines a job prints, without printing it | | GET | `/api/v1/jobs/:id` | Job status | | GET | `/healthz` | Printer and queue health (no auth) | | GET | `/` | Version information (no auth) | @@ -133,8 +139,8 @@ curl -X POST https://printer.example.com/api/v1/print \ -H "Content-Type: application/json" \ -d '{ "elements": [ - {"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"}, - {"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"}, + {"type": "rule", "style": "dark"}, + {"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"}, {"type": "text", "text": "Überbringer", "size": 2, "bold": true, "align": "center"}, {"type": "feed"}, {"type": "text", "text": "Long paragraphs wrap at word boundaries for the paper width, so a word is never split across two lines."}, @@ -175,6 +181,70 @@ curl -H "Authorization: Bearer $TOKEN" https://printer.example.com/api/v1/jobs/j `status` is `queued`, `printing`, `done` or `failed`. A failed job includes an `error` field. The last `queue.history` finished jobs are kept. +### Preview a receipt + +`POST /api/v1/preview` takes the same body as `/api/v1/print` and validates +it the same way, but prints nothing and fetches no images. It answers `200` +with the lines the printer would print, as `text/plain; charset=utf-8`: + +```sh +curl -X POST https://printer.example.com/api/v1/preview \ + -H "Authorization: Bearer $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"elements": [{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"}, + {"type": "qr", "data": "https://example.com"}]}' +``` + +```text + ┌─────────────────────┐ + │ !!! ACHTUNG !!! │ + └─────────────────────┘ +[qr: https://example.com] + - - - - - - - partial cut - - - - - - - - +``` + +- The preview is read back from the bytes the job renders to, so it shows + what the printer receives: wrapping, folded characters, `?` for missing + ones and the final cut. +- Centred and right-aligned text is indented as the printer places it, + counted in Font A columns. Text at a larger size shows each character + once. +- QR codes, barcodes, images, `raw` bytes and cuts print as placeholders + such as `[barcode ean13: 4006381333931]`, `[image 384 dots: logo.png]` and + `[raw 3 bytes]`. + +With `Accept: application/json` the answer carries the styles too. For +`[{"type": "kv", "pairs": [{"key": "Total", "value": "£12.50", "bold": true}]}, +{"type": "text", "text": "Thanks 🎉", "align": "center"}, +{"type": "qr", "data": "https://example.com"}]`: + +```json +{"columns": 42, "codepage": "cp437", "line_count": 3, + "lines": [{"kind": "text", "text": "Total ............................. £12.50", + "runs": [{"from": 0, "to": 5, "bold": true}, {"from": 36, "to": 42, "bold": true}]}, + {"kind": "text", "text": " Thanks ?"}, + {"kind": "qr", "text": "[qr: https://example.com]", "data": "https://example.com"}, + {"kind": "cut", "text": " - - - - - - - partial cut - - - - - - - -", "data": "partial"}], + "warnings": ["elements[1]: 1 character not in cp437 printed as ?"]} +``` + +| Field | Meaning | +|-------|---------| +| `columns` | Font A characters per line | +| `codepage` | The code page text is printed in | +| `line_count` | Lines the receipt prints, all copies counted: text lines, fed lines, and one for each QR code, barcode and image. [`format.max_lines`](#configuration) limits it | +| `lines[].kind` | `text`, `qr`, `barcode`, `image`, `raw` or `cut` | +| `lines[].text` | The line as it prints, or the placeholder | +| `lines[].runs` | Styled parts of `text`, in characters from `from` up to `to`: `bold`, `underline` (1 or 2), `invert`, `font` (`b`), and `width` and `height` when scaled. Plain Font A text at size 1 has no run | +| `lines[].data` | QR code or barcode data, the image URL (or `base64`), the number of raw bytes, or the cut mode | +| `warnings` | Elements with characters the code page lacks, and images wider than the paper | + +A job that would print more than `format.max_lines` lines answers `422` +`too_many_lines`, for example `receipt would print 2412 lines, limit is +2000`. Sent to `/api/v1/print`, the same job is accepted and then fails +when the worker renders it, before anything is sent; its `error` reads +`rendering: receipt would print 2412 lines, limit is 2000`. + ### Health `GET /healthz` returns `200` when the printer is reachable and ready, and @@ -213,7 +283,9 @@ Errors are JSON: - `code` is stable and meant for clients to match on. - `error` is for people and may change. It never repeats the HTTP framework's own text; for example, an unknown route answers `not found`. -- `details` appears only when an `invalid_job` fails validation. +- `details` appears only when an `invalid_job` fails validation. Each entry + names the element by its path, e.g. + `elements[0].children[3] (qr): not allowed inside a box; place it after the box`. | Status | `code` | Meaning | |--------|--------|---------| @@ -225,6 +297,7 @@ Errors are JSON: | 405 | `method_not_allowed` | Known route, wrong method, e.g. `DELETE /api/v1/print` with a valid token (without one, `/api/v1` answers `401` first). Sent with `Allow` | | 408 | `request_timeout` | The request was not received in time | | 413 | `body_too_large` | Body larger than `webserver.body_limit` | +| 422 | `too_many_lines` | From `/api/v1/preview`: the job would print more than `format.max_lines` lines | | 429 | `rate_limited` | Rate limit exceeded. `Retry-After` gives the seconds to wait | | 431 | `headers_too_large` | Request headers too large | | 500 | `internal_error` | Unexpected failure. The cause is logged and reported to Sentry, never sent to the client | @@ -244,7 +317,8 @@ to the printer unless the whole receipt rendered. A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is cut separately. A partial cut is added after the last element unless that -element is already a `cut`. +element is already a `cut`. Boxes, rules and key-value rows are described +under [Blocks](#blocks). ### `text` @@ -262,8 +336,21 @@ element is already a `cut`. | `wrap` | `true` | `false` sends the text as-is and lets the printer wrap | **Encoding.** Text is transcoded from UTF-8 to `printer.codepage`, CP437 by -default. Characters the code page lacks, such as emoji, print as `?`. Control -characters are removed so text can never be read as printer commands. +default. Control characters are removed so text can never be read as printer +commands. Before that, the text is prepared for the code page: + +- It is composed (Unicode NFC), so a decomposed `é` (an `e` and a combining + accent) prints as `é`. +- Characters the code page lacks fold to look-alikes: `“ ” „` print as `"`, + `‘ ’` as `'`, `–` as `-`, `—` as `--`, `…` as `...`, `•` as `·`, `→` as + `->`, `←` as `<-`, `✓ ✔` as `√` (or `x` without `√`), `×` as `x`, `€` as + `EUR` and `™` as `TM`. Where the code page has the character, as cp1252 + has curly quotes and cp858 has `€`, it prints as itself. +- An emoji prints as one `?`, together with its skin tone, its variation + selector and any emoji joined to it, so `👨‍👩‍👧` is one `?`. Zero-width + spaces and joiners are removed. +- Any other character the code page lacks prints as `?`. The + [preview](#preview-a-receipt) lists the elements that have one. **Word wrap.** The line width comes from the printer model and the character size: on a TM-T88, 42 characters at size 1, 21 at size 2, and so on. Lines break at spaces, @@ -325,6 +412,133 @@ or link-local addresses (including cloud metadata endpoints) are refused unless |--------|-----------|--------| | `mode` | `partial` | `partial`, `full` | +## Blocks + +`box`, `rule` and `kv` are blocks: they are laid out when the job prints, from +the printer model, so one job fits the TM-T88's 42 columns as well as the +TM-T20's 48. A block starts on a new line, and what follows it starts at the +left margin. These fields work on all three: + +| Field | Default | Values | +|-----------|---------|--------| +| `size` | `1` | 1–3. Scales the borders and the text together: 42, 21 or 14 columns on a TM-T88 | +| `font` | `a` | `a`, or `b` (56 columns at size 1 on a TM-T88) | +| `columns` | the line | 1–255. A fixed width in characters of the block's own size and font. It is cut to the line, and a narrower block is centred | + +Borders and fills are never bold, underlined or inverted. On the blocks, a +field that does not apply is an error, e.g. +`elements[3] (rule): field "pairs" does not apply to rule`. A long title, +footer or label is cut with `...` instead of failing. + +### `box` + +```json +{"type": "box", "style": "double", "title": "ACHTUNG", "title_style": "capped", "align": "center", + "text": "The coffee machine is being descaled.\nDo not use until 10:30."} +``` + +```text +╔═╡ ACHTUNG ╞════════════════════════════╗ +║ The coffee machine is being descaled. ║ +║ Do not use until 10:30. ║ +╚════════════════════════════════════════╝ +``` + +```json +{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"} +``` + +```text + ┌─────────────────────┐ + │ !!! ACHTUNG !!! │ + └─────────────────────┘ +``` + +| Field | Default | Values | +|---------------|----------|--------| +| `text` | | The body. It wraps at word boundaries, and `\n` starts a new paragraph. Set `text` or `children`, not both | +| `children` | | The body as elements; see below | +| `style` | `single` | `single` ┌─┐, `double` ╔═╗, `double-h` ╒═╕ (double lines across, single down), `double-v` ╓─╖ (single across, double down), `ascii` +-+ | +| `title` | | Text set into the top border | +| `title_style` | `inline` | `inline` `┌─ Title ───┐`, or `capped` `╔═╡ Title ╞══╗` | +| `footer` | | Text set into the bottom border, on the right: `└──── footer ──┘` | +| `align` | `left` | Alignment of `text`, and the default for text children | +| `bold`, `underline`, `invert` | | Styles of `text`, as on a `text` element | +| `padding` | `1` | 0–3 spaces between the side borders and the body | +| `fit` | `false` | `true` shrinks the box to its widest line, title and footer included, and centres it. `columns` is then the most it may take | + +**Children.** A box takes one level of these, and each prints inside the +borders: + +| Type | Fields | Inside a box | +|--------|--------|--------------| +| `text` | `text`, `bold`, `underline`, `invert`, `align`, `wrap` | `size` and `font` come from the box. `"newline": false` is not allowed. `"wrap": false` splits lines at the box edge instead of at spaces | +| `feed` | `lines` | Empty lines between the borders | +| `rule` | `style` (`single` or `double`), `text`, `align`, `bold` | A divider joined to the side borders: `├──┤`, `╞══╡`, `╟──╢` or `╠══╣` to suit the box. A label reads `├── Label ───┤` | +| `kv` | `pairs`, `leader` | Key-value rows across the inside of the box | + +`box`, `qr`, `barcode`, `image`, `raw` and `cut` cannot go inside a box; +place them after it. Children count toward the 500-element limit. + +### `rule` + +| Field | Default | Values | +|---------|----------|--------| +| `style` | `single` | `single` ─, `double` ═, `light` ░, `medium` ▒, `dark` ▓, `solid` █, `dashed` `- -`, `dotted` ·, `ascii` - | +| `text` | | A label set into the line | +| `align` | `center` | Where the label sits: `───── TODAY ─────`, or `── Notes ──────` at the left | +| `bold` | `false` | Prints the label bold | + +### `kv` + +```json +{"type": "kv", "pairs": [{"key": "Host", "value": "nas01"}, + {"key": "Note", "value": "The scrub finished with 0 errors. Next scrub Sunday 03:00."}, + {"key": "Used", "value": "94%", "bold": true}]} +``` + +```text +Host ............................... nas01 +Note ... The scrub finished with 0 errors. + Next scrub Sunday 03:00. +Used ................................. 94% +``` + +| Field | Default | Values | +|----------|---------|--------| +| `pairs` | | Required. 1–100 rows of `{"key": "...", "value": "...", "bold": false}`. `key` is required; `bold` prints the key and the value bold | +| `leader` | `.` | The fill between key and value: `.`, `·`, `" "` (or `"space"`), `_`, `-` or `─` | + +A value too long for its line wraps into the room after the key, and its +further lines are right-aligned. A key too long for the line is cut with +`...`. + +### Glyphs and code pages + +CP437, the default, has every glyph the blocks draw with. Other code pages +fall back, and the [preview](#preview-a-receipt) shows the result: + +| Code page | Boxes | Rules | +|-----------|-------|-------| +| `cp437` | All styles as listed | All styles | +| `cp850`, `cp858` | `double-h` and `double-v` print as `double`. A divider whose junction the page lacks switches to the other line weight, so `╞══╡` prints as `├──┤` and `╟──╢` as `╠══╣`. A capped title on double lines uses `╣ ╠` | All styles | +| `cp1252` | Every box is `ascii`, drawn with `+`, `-` and `\|`, with `=` for double dividers | `─ ═` print as `- =`, shades as `#` | + +For your own text on CP437: + +- **Prints:** box drawing `┌─┐│└┘├┤┬┴┼ ╔═╗║╚╝╠╣╦╩╬ ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫`, + shades and blocks `░▒▓█▀▄▌▐■`, and `· ∙ √ ° ± » « £ ¥ ½ ¼` and accented + Latin letters. +- **Never prints as itself:** `•` and emoji, and `► ◄ → ←` and the other + symbols CP437 keeps at byte values below 0x20, which the printer reads as + commands. `•` folds to `·` and `→ ←` to `-> <-`; the rest print as `?`. Use + `· ∙ ■ » √ °` instead. + +`examples/blocks.json` prints every style, padding, size and junction on one +receipt, for checking the borders on paper. Send it as the body of +`/api/v1/print`, or look at it first with +`uberbringer preview examples/blocks.json`. + ## Migrating from the old format The endpoint is still `POST /api/v1/print`, but the body changed from @@ -405,6 +619,14 @@ Settings worth knowing: `columns` (Font A characters per line) override the model. - `printer.codepage`: `cp437` (default), `cp850`, `cp858` (has €) or `cp1252`. +- `printer.box_line_spacing` (default `0`): the line spacing, in motion + units (ESC 3, 0–255), used while a box prints. Lines of box drawing leave + small gaps in the vertical borders at the printer's default spacing; a + value checked on paper closes them. `0` keeps the default, which was + checked on a TM-T88IV with `examples/blocks.json` and looks fine. +- `format.max_lines` (default `2000`): a job that would print more lines, + all copies counted, fails instead of printing. It is a backstop against + runaway text; `/api/v1/preview` answers such a job with `422`. - `webserver.trusted_proxies` / `proxy_header`: the real client IP for per-client rate limits comes from the `X-Real-IP` header set by nginx on `127.0.0.1`. @@ -433,9 +655,17 @@ Settings worth knowing: uberbringer [--config config.toml] run the daemon (default command) uberbringer secret print a new random API secret uberbringer token [--subject s] [--ttl 720h] print a signed bearer token +uberbringer preview [file.json|-] show the lines a job would print uberbringer version print the version ``` +`preview` reads a job from the file, or from standard input with `-` or no +argument, and lays it out for the printer in the config, as +`/api/v1/preview` does. It prints nothing and fetches no images. On a +terminal it shows bold, underlined and inverted text as such; warnings go +to standard error. It reads the same config as the daemon, so +`api.secret` and `printer.address` must be set even though neither is used. + The daemon shuts down gracefully on SIGINT/SIGTERM. A receipt that is already printing is finished, and jobs still waiting are marked failed. @@ -486,13 +716,14 @@ cmd/uberbringer/ main: build info, signals, exit code internal/app/uberbringer/ CLI commands and wiring server/ Fiber HTTP API, auth, health internal/pkg/config/ TOML config: defaults and validation -internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status -internal/pkg/receipt/ Job format, validation, word wrap, rendering +internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter +internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview internal/pkg/raster/ Image decoding, scaling and dithering internal/pkg/safehttp/ SSRF-guarded image fetching internal/pkg/printer/ TCP printer client (port 9100) and status queries internal/pkg/printqueue/ Job queue, worker and status history configs/ Example configuration +examples/ Example jobs, such as the block calibration receipt packaging/ systemd unit docs/ Design notes and feature plans ``` diff --git a/configs/config.example.toml b/configs/config.example.toml index 1fc74d3..74a9374 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -48,11 +48,21 @@ # paper_width = 512 # printable dots; overrides the model # columns = 42 # Font A characters per line for word wrap + # Line spacing in motion units (ESC 3, 0-255) while a box prints, to + # close the small gaps in its vertical borders. 0 keeps the printer's + # default spacing. + box_line_spacing = 0 + dial_timeout = "5s" write_timeout = "30s" retries = 3 # resend attempts when the printer is unreachable retry_delay = "1s" # doubles after each attempt +[format] + # A job that would print more lines than this, all copies counted, fails + # instead of printing; /api/v1/preview answers 422. + max_lines = 2000 + [queue] size = 100 # jobs that may wait; more get 503 history = 1000 # finished jobs whose status is kept diff --git a/docs/design.md b/docs/design.md index 90b5cf8..a5aa01d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -48,6 +48,37 @@ client ─HTTPS─▶ nginx ─▶ server ── validate ──▶ printqueue ( the owner prints (owner, 2026-11-29). Control characters are stripped, so data can never become a printer command. Only the `raw` element sends bytes as given. + - Before wrapping, text is composed to NFC, and characters the code page + lacks fold to ASCII look-alikes (curly quotes, dashes, the ellipsis and + a few symbols). An emoji sequence prints as one `?` (owner, 2026-11-29). + A fold applies only where the code page lacks the character, so cp1252 + keeps its curly quotes. After this step one rune is one column and one + byte, which is what wrap counts. +- **Blocks are laid out when the job renders.** `box`, `rule` and `kv` take + their width from the profile (or `printer.columns`) and their own size and + font, never from fixed numbers, so a job stays printer-neutral. Layout + never fails on a valid job: widths clamp, titles and labels are cut with + `...`, and a box narrower than its padding gives up the padding. The only + render-time failure added is `format.max_lines`. Validation stays + structural, because geometry depends on the printer. + - Glyphs the code page lacks fall back per glyph set: `double-h` and + `double-v` to `double`, then `single`, then `ascii`. A divider junction + the page lacks switches to the other line weight first, and a capped + title on double lines uses `╣ ╠`, which cp850 has, instead of `╡ ╞`. + - Block fields are rejected on the older element types, which otherwise + stay lenient, so a block field sent to the wrong type still fails as an + unknown field did before blocks existed. + - Boxes print at the printer's default line spacing. The small gaps that + leaves in vertical borders were judged acceptable on the TM-T88IV + (owner, 2026-11-30), so `printer.box_line_spacing` stays 0 by default. + The bytes of that calibration receipt, `examples/blocks.json`, are + pinned in a receipt test. +- **The preview reads the bytes back.** `escpos.Interpret` parses the stream + the renderer produced, so the preview and the tests show what the printer + receives rather than what the layout meant. It simulates the printer's own + wrapping and alignment, which needs the profile. `raw` bytes stay opaque, + since arbitrary bytes cannot be parsed reliably, and images are blank + placeholders, so a preview never fetches anything. - **Profiles set the layout, and the default is the narrower one.** Columns are the profile's dots per line divided by the glyph width; nothing hard-codes 42 or 512. The first paper test ran the 576-dot `tm-t20` @@ -99,9 +130,9 @@ client ─HTTPS─▶ nginx ─▶ server ── validate ──▶ printqueue ( ## Planned: formatters -Layout blocks and modules, ntfy among them, that turn plain input into -receipts. The plan is `docs/plans/formatters.md`. Decided so far (owner, -2026-11-29): +Modules, ntfy among them, that turn plain input into receipts built from the +blocks. The plan is `docs/plans/formatters.md`; its first phase, the blocks +and the preview, is built. Decided so far (owner, 2026-11-29): - ntfy is an input: its notifications are printed. The server is self-hosted at a public URL, the subscriber authenticates with a token, and @@ -109,9 +140,6 @@ receipts. The plan is `docs/plans/formatters.md`. Decided so far (owner, private-network exception. - Which priorities print is configurable per subscription. By default every priority prints, and priorities 1 and 2 print in a compact form. -- On `/print`, characters the code page lacks fold to ASCII look-alikes - (smart quotes, dashes, the ellipsis), and an emoji sequence prints as one - `?`. Today each such character prints as `?`. - Labels are in English. The footer's time zone and date format come from the config. diff --git a/docs/plans/formatters.md b/docs/plans/formatters.md index eb6da19..39881d3 100644 --- a/docs/plans/formatters.md +++ b/docs/plans/formatters.md @@ -1,6 +1,6 @@ # Plan: CP437 blocks, modules and ntfy printing -Status: **phase 1 in progress.** Every design decision for phases 1-4 is made; the open questions left are an assumed default, config values, a calibration check and the second printer. Each phase runs in its own session, briefed from its section. +Status: **phase 1 is done**: box, rule and kv, text folding and the preview are built and checked on paper (README § Blocks, design.md). Phases 2-5 are not started. Every design decision for phases 2-4 is made; the open questions left are an assumed default, config values and the second printer. Each phase runs in its own session, briefed from its section. ## Decisions (owner, 2026-11-29) @@ -42,8 +42,8 @@ Ideas taken from the other designs: - From Design 2 (templates): fit boxes, a hand-written markdown subset with no new dependency, a plain fallback receipt, a since=