Add box, rule and kv blocks, text folding and receipt preview
Security / Vulnerability check (push) Successful in 50s
Test / Lint and test (push) Successful in 1m59s

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 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 00:49:45 -06:00
1 parent 9fdea32b4f
commit 4562f0cebb
109 files changed
+6383 -487

No files matched your search

+4
View File
@@ -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
+46
View File
@@ -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,
+240 -9
View File
@@ -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
```
+10
View File
@@ -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
+34 -6
View File
@@ -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.
+24 -351
View File
@@ -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=<time> cursor, token scopes, and '?' warnings in preview.
- From Design 3 (sources): a simple Notice input (the notify module), images marked optional, a cursor taken from ntfy server time, the time/tzdata import, and Submit Meta for traceability.
WHAT SHIPS WHEN (about 12-13 developer days to the end of phase 4)
1. Boxes and preview, 3-4 days. One /print element gives the single or double CP437 boxes the owner liked. POST /api/v1/preview and `uberbringer preview` show the exact output without using paper.
WHAT SHIPS WHEN (about 10 developer days to the end of phase 4)
1. Boxes and preview: done.
2. Notes and modules, 2 days. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
3. Notifications, 3 days. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged. After this phase, ntfy printing needs only a client.yml entry and no jq.
4. Built-in ntfy subscriber, 5 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog, folds floods into a digest receipt, and holds non-urgent messages during quiet hours for a morning digest.
@@ -51,15 +51,13 @@ WHAT SHIPS WHEN (about 12-13 developer days to the end of phase 4)
BACKWARD COMPATIBILITY
- Every existing element, field and response keeps its meaning, and /print stays strictly decoded.
- A byte-compatibility test, captured before any renderer change, pins today's output.
- One deliberate change (approved): characters that print as '?' today print as close ASCII matches: smart quotes, dashes and the ellipsis. An emoji sequence prints as one '?' instead of several.
- Emoji are removed only on the module and ntfy paths.
- TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts pin the bytes of existing jobs; later phases keep them passing.
- Emoji are removed only on the module and ntfy paths; /print prints an emoji sequence as one '?'.
WHERE THE JUDGES DISAGREED, AND WHAT THIS PLAN CHOSE
- list: in (phase 2), because the note module needs checklists.
- spans, table, group, banner, nested boxes and goldmark: deferred.
- Geometry checks in the HTTP handler (Renderer.Check): rejected. Layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
- Tight line spacing: off by default until a calibration print has been checked.
- Scoped tokens: in phase 3, before any integration token is handed out.
- Quiet hours: phase 4, as a morning digest (owner decision).
@@ -75,14 +73,9 @@ Before phase 4 (config, not design):
2. Topics and auth: which topics and quiet-hours window to configure. A
dedicated read-only ntfy user with an access token is assumed.
After phase 1's calibration print:
3. Are the small gaps in vertical borders acceptable, or should boxes use
tighter line spacing (box_line_spacing)?
When the second printer arrives:
4. Which jobs and ntfy topics go to which printer, and should urgent messages
3. Which jobs and ntfy topics go to which printer, and should urgent messages
print on both?
## Mockups (42 columns, CP437)
@@ -154,21 +147,6 @@ Prune finished
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
--- 6. Double box, capped title, centred
╔═╡ ACHTUNG ╞════════════════════════════╗
║ The coffee machine is being descaled. ║
║ Do not use until 10:30. ║
╚════════════════════════════════════════╝
--- 7. fit:true, one element each
┌─────────────────────┐
│ !!! ACHTUNG !!! │
└─────────────────────┘
╔═══════════════════╗
║ !!! ACHTUNG !!! ║
╚═══════════════════╝
--- 8. Box with kv, labelled rule and list
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
@@ -180,23 +158,6 @@ Prune finished
└──────────────────────── 29 Nov 21:04 ──┘
A pair can set "bold" (e.g. Used 94%).
--- 9a. rule: single double light medium
──────────────────────────────────────────
══════════════════════════════════════════
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
--- 9b. dark solid dashed dotted ascii
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
██████████████████████████████████████████
- - - - - - - - - - - - - - - - - - - - -
··········································
------------------------------------------
───────────────── TODAY ──────────────────
═════════════════ TOTAL ══════════════════
── Notes ─────────────────────────────────
The last three are labelled rules.
--- 10. kv (long value wraps) and list
Host ............................... nas01
Note ... The scrub finished with 0 errors.
@@ -210,22 +171,6 @@ Note ... The scrub finished with 0 errors.
[√] Done item
[ ] Open item
--- 11. Box styles and divider junctions
┌──────┐ ╔══════╗ ╒══════╕ ╓──────╖
│single│ ║double║ │dbl-h │ ║dbl-v ║
└──────┘ ╚══════╝ ╘══════╛ ╙──────╜
+------+
|ascii |
+------+
├──────┤ single box, single rule
╞══════╡ single box, double rule
╟──────╢ double box, single rule
╠══════╣ double box, double rule
cp850/858: double-h and double-v fall
back to double. cp1252: every box is
ascii (+-|). Preview shows the result.
--- 12. Rate-limit digest (phase 4)
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
@@ -238,8 +183,8 @@ Note ... The scrub finished with 0 errors.
One row per held message, in arrival
order. Priority 5 never waits.
Glyphs never used: • (not in any code
page), ► ◄ → ← and other 0x01-0x1F
Glyphs never used: • (only cp1252 has
it), ► ◄ → ← and other 0x01-0x1F
glyphs (printer control codes), emoji.
Use · ∙ ■ » √ ° instead.
```
@@ -249,43 +194,12 @@ Use · ∙ ■ » √ ° instead.
All /api/v1 routes keep the existing Bearer JWT, rate limiter and error shape {"error","details"}. Successful print responses keep today's 202 body plus a Location header:
{"id":"job_01kbx4n6m3ex8tq0wq3r5vrzq1","status":"queued","created_at":"2026-11-29T21:04:05Z"}
==== PHASE 1: new elements in POST /api/v1/print ====
==== Blocks in POST /api/v1/print ====
Fields shared by the blocks (box, rule, kv, list):
- size: 1-3. Scales the borders and the text together.
- font: a or b.
- Borders are never bold.
box
- style: single (default, ┌─┐│└┘), double (╔═╗║╚╝), double-h (╒═╕│╘═╛), double-v (╓─╖║╙─╜) or ascii (+-|).
- title: text set into the top border.
- title_style: inline (default, ┌─ Title ──┐) or capped (╔═╡ Title ╞═╗).
- footer: text set into the bottom border, on the right.
- text: shorthand for the body. It wraps, and "\n" starts a new paragraph. It takes bold, underline and invert.
- children: alternative to text. Allowed child types are text, rule, kv, list (phase 2) and feed.
- text and children cannot both be set.
- align: alignment of the shorthand text, and the default for text children.
- padding: 0-3, default 1.
- fit: true shrinks the box to its content and centres it.
- columns: a fixed outer width. It is clamped to the paper, and a narrower box is centred.
Children inside a box:
- text: may set bold, underline, invert, align and wrap. size, width, height and font are inherited from the box, and newline:false is not allowed.
- rule: only single or double, optionally with text as a label. It becomes a divider whose junctions join the side borders.
- Not allowed: box, qr, barcode, image, raw and cut. Place them after the box.
rule
- style: single (default) ─, double ═, light ░, medium ▒, dark ▓, solid █, dashed "- ", dotted · or ascii -.
- text: an optional label.
- align: where the label sits. center is the default.
- bold: applies to the label only.
- columns.
kv
- pairs: [{key, value, bold}], 1-100 of them.
- leader: one of . (default), ·, space, _, - or ─.
box, rule and kv, the preview (POST /api/v1/preview, `uberbringer preview`) and format.max_lines are built; README § Blocks and § Preview a receipt describe them. Validation problems name nested elements, e.g. elements[0].children[3] (qr). Still to come:
list (phase 2)
- A block like kv: size, font and columns, and allowed as a child of a box.
- items: 1-200 strings.
- bullet: dot (default), dash, number or checkbox.
- done: indexes of finished items, checkbox only. They print as [√], or [x] on code pages without √.
@@ -293,7 +207,7 @@ list (phase 2)
image (phase 3)
- New field optional: true. If the image can't be fetched or decoded, the receipt prints "[image unavailable]" instead of failing the whole job.
Example 1: a boxed note in one element (mockup 5, with list from phase 2)
Example 1: a boxed note in one element (mockup 5)
POST /api/v1/print
{"elements":[
{"type":"box","title":"Shopping","footer":"29 Nov 21:04","children":[
@@ -303,60 +217,15 @@ POST /api/v1/print
]}
]}
Example 2: the owner's test-print look (mockups 6 and 7)
{"elements":[
{"type":"box","style":"double","title":"ACHTUNG","title_style":"capped","align":"center",
"text":"The coffee machine is being descaled.\nDo not use until 10:30."},
{"type":"box","fit":true,"padding":3,"text":"!!! ACHTUNG !!!"}
]}
Example 3: status report with kv rows and a labelled divider (mockup 8)
Example 2: status report with kv rows, a labelled divider and a list (mockup 8)
{"elements":[
{"type":"box","title":"NAS REPORT","footer":"29 Nov 21:04","children":[
{"type":"kv","pairs":[{"key":"Host","value":"nas01"},{"key":"Pool","value":"tank (raidz2)"},{"key":"Used","value":"94%","bold":true}]},
{"type":"rule","text":"Services","align":"left"},
{"type":"list","items":["grafana up","offsite-backup DOWN since 19:00"]}
]},
{"type":"rule","style":"double","text":"TOTAL"},
{"type":"text","text":"Total: ","newline":false},
{"type":"text","text":"£12.50","bold":true}
]}
]}
Example 4: validation (400, same shape as today, now with nested paths)
{"error":"invalid job","details":[
"elements[0].children[3] (qr): not allowed inside a box; place it after the box",
"elements[0].children[1] (rule): inside a box, style must be single or double",
"elements[1] (box): set text or children, not both",
"elements[2] (kv): pairs[2]: key is required",
"elements[3] (rule): field \"pairs\" does not apply to rule"]}
Render-time limit:
- If a job would print more lines than [format].max_lines (default 2000), the job fails with "receipt would print 2412 lines, limit is 2000". That is visible on GET /api/v1/jobs/{id}, and synchronously on /preview.
==== PHASE 1: POST /api/v1/preview ====
- Takes the same body as /print and validates it the same way (400 on problems).
- Nothing is printed and no images are fetched.
Default response: 200 text/plain; charset=utf-8, the exact lines the bytes would print:
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
...
[qr: https://grafana.lan/d/disk]
[image 384 dots: graph.png]
- - - - - - - partial cut - - - - - - - -
With Accept: application/json:
{"columns":42,"codepage":"cp437","line_count":9,
"lines":[{"kind":"text","text":"╔═ HIGH ═══...═╗"},
{"kind":"text","text":"║ [!] Disk almost full ...║","runs":[{"from":2,"to":40,"bold":true}]},
{"kind":"qr","data":"https://grafana.lan/d/disk"},
{"kind":"cut","data":"partial"}],
"warnings":["elements[2]: 1 character not in cp437 printed as ?"]}
- 422 {"error":"receipt would print 2412 lines, limit is 2000"}
- CLI: uberbringer preview [--config c.toml] [--module ntfy] [file.json|-]. It prints to the terminal, showing bold and invert with the existing liamg/tml dependency.
==== PHASE 2: modules ====
GET /api/v1/modules
@@ -436,12 +305,9 @@ Job status:
==== PHASE 3-4: configuration (strict TOML, as today) ====
[format]
max_lines = 2000 # phase 1
[format] # max_lines is built
timezone = "Local" # phase 2; IANA name, checked with time.LoadLocation
time_layout = "02 Jan 15:04"
[printer]
box_line_spacing = 0 # phase 1; ESC 3 units around boxes; 0 = printer default (until calibrated)
[ntfy.format] # phase 3
style = "auto" # auto | box | compact
max_lines = 40
@@ -505,26 +371,12 @@ DATA FLOW
- /print/{module}: module.Build(body, Env) -> Validate (a failure here is a module bug, 422) -> Submit(job, Meta{Source: "module:<name>"}).
- Subscriber (phase 4): ntfy stream -> skip, dedupe, filter, rate limit -> modules.FromNtfy -> Card -> Validate -> Submit(job, Meta{Source: "ntfy:<sub>", Ref: <ntfy id>}).
KEY TYPES (new or changed)
escpos
func (cp CodePage) CanEncode(r rune) bool // r encodes to a byte >= 0x20, not 0x7F
func (cp CodePage) Decode(b []byte) string
type Span struct{ From, To int }
type Run struct{ From, To int; Bold, Underline, Invert bool; Font Font; W, H int }
type PreviewLine struct{ Kind string /* text|qr|barcode|image|raw|cut */; Text string; Runs []Run; Data string }
func Interpret(stream []byte, cp CodePage, opaque []Span) ([]PreviewLine, error)
KEY TYPES (new or changed; the escpos interpreter, the blocks and Renderer.Preview are built)
receipt
TypeBox, TypeRule, TypeKV (phase 1); TypeList (phase 2)
Element gains: Children []Element, Title, TitleStyle, Footer, Style, Padding *int, Fit bool,
Columns int, Pairs []Pair, Leader (phase 1); Items []string, Done []int, Bullet (phase 2);
Optional bool on image (phase 3)
type Pair struct{ Key, Value string; Bold bool }
type Preview struct{ Columns int; CodePage string; LineCount int; Lines []escpos.PreviewLine; Warnings []string }
func (r *Renderer) Preview(ctx context.Context, job Job) (Preview, error)
func StripEmoji(s string) string
Options gain MaxLines and BoxLineSpacing
TypeList (phase 2)
Element gains Items []string, Done []int, Bullet (phase 2); Optional bool on image (phase 3)
func StripEmoji(s string) string (phase 3)
modules (phase 2; Notice and Card in phase 3)
type Env struct{ Now time.Time; Location *time.Location; TimeLayout string; Card CardOptions }
@@ -544,90 +396,21 @@ ntfy
func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error
server
New(config Config, deps Deps, logger *slog.Logger)
type Deps struct{ Jobs Jobs; Printer Printer; Previewer Previewer; Modules Modules }
Deps gains Modules (phase 2): Deps{Jobs, Printer, Previewer, Modules}
printqueue
Submit(job receipt.Job, meta Meta) (Status, error)
type Meta struct{ Source, Ref string }
Status gains Source
BLOCK LAYOUT RULES (receipt/blocklayout.go and receipt/glyphs.go)
Width
- cols = Profile.Columns(font), or Options.Columns for Font A, divided by size (1-3). That gives 42 Font A or 56 Font B columns on all three Epson models.
- `columns` clamps to cols.
- `fit` sets the width to the smallest of: cols, and the larger of (widest content + 2 + 2*padding) and (title + 6).
- A block narrower than the line is centred with leading spaces.
Box
- Each body row is: border, padding, content, padding, border. The content width is width - 2 - 2*padding, which is 38 at the defaults.
- Bold, underline and invert apply only to the content run. Borders are never styled.
- Top border, inline title: ┌─ Title ───┐. The title is cut with "..." beyond width-6.
- Top border, capped title: ╔═╡ Title ╞══╗, using ┤├ on boxes with single horizontal lines.
- Bottom border: └──── footer ──┘. The footer is cut beyond width-7.
Dividers (a rule child inside a box) span the full width and join the side borders:
- single box: ├─┤ for a single rule, ╞═╡ for a double rule
- double box: ╟─╢ single, ╠═╣ double
- double-h box: ├─┤ single, ╞═╡ double
- double-v box: ╟─╢ single, ╠═╣ double
- A labelled divider looks like ├── Label ───┤.
kv
- Layout: key, a space, a leader fill of at least 2, a space, then the value.
- When the line is too long, the value wraps to width - len(key) - 4 and the continuation lines are right-aligned.
list
BLOCK LAYOUT (receipt/blocklayout.go and receipt/glyphs.go)
box, rule and kv are built; docs/design.md records their rules. list (phase 2) follows them: its width comes from the line at its size and font and from columns, every line it returns is exactly that width, and a narrower list is centred.
- Bullets: "· ", "- ", "N. " (numbers right-aligned to the widest), "[ ] " and "[√] ".
- Wrapped lines get a hanging indent.
Glyph fallback, chosen per glyph set with CanEncode
- double-h and double-v fall back to double, then single, then ascii (+ - | =).
- A junction the code page lacks first switches to the other rule weight. On cp850, ╟╢ becomes ╠╣ and ╞╡ becomes ├┤.
- Shades fall back to #, · to . and √ to x.
- Checked with the Python codecs:
- cp437 has every glyph used here.
- cp850 and cp858 lack ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫, ▌▐, ∙ and √.
- cp1252 has no box drawing or shade characters.
- No supported code page has • (U+2022).
- ► ◄ → ← map to 0x10-0x1F, which the printer reads as control codes.
Emitting lines
- For each line: Justify(left), the left margin, then for each run Font, Size, Bold, Underline and Reverse, then Text(cp.Encode(run)), then LineFeed.
- Styles are reset afterwards exactly as p.text does today.
- When Options.BoxLineSpacing > 0, ESC 3 n is sent before a box and ESC 2 after it.
Images
- Boxes cannot contain images, so loadImages keeps keying images by element index and no flatten step is needed.
- √ falls back to x where the code page lacks it (cp850, cp858), chosen with CanEncode.
TEXT NORMALIZATION (receipt/normalize.go)
It runs before wrap, so one rune is one column and one byte. Steps, in order:
1. sanitize, as today.
2. Unicode NFC, using golang.org/x/text/unicode/norm. golang.org/x/text is already a dependency.
3. Fold only runes the code page cannot encode:
- “ ” „ become "
- ‘ ’ become '
- – becomes -, and — becomes --
- … becomes ...
- • becomes ·
- → becomes -> and ← becomes <-
- ✓ and ✔ become √, or x where √ is missing
- × becomes x
- € becomes EUR (cp858 keeps €)
- ™ becomes TM
- a non-breaking space becomes a space
4. Remove U+FE0E, U+FE0F, U+200B-U+200D, skin-tone modifiers and tag characters.
5. Emoji:
- On /print, each remaining emoji cluster becomes a single '?'.
- Modules call StripEmoji after mapping a few typed emoji to markers: ⚠ to [!], ✅ to [√], ❌ to [x], 🚨 to (!), 👍 to (+1).
The number of '?' left feeds the preview warnings.
PREVIEW (receipt/preview.go and escpos/interpret.go)
- Renderer.Preview renders with a placeholder fetcher. It produces a blank raster at the requested or default width and never fetches anything.
- It records the byte range of each raw element (Builder.Len before and after), then interprets the body with escpos.Interpret. Raw ranges become "[raw N bytes]", because arbitrary raw bytes cannot be parsed reliably.
- Interpret understands every command the renderer emits: ESC @ t a M E - 3 2 d, GS ! B V, GS ( k, GS k and GS v 0.
- The tests use the same interpreter in place of printedLines, so the preview always shows what the bytes actually say.
Built: NFC, the fold table and one '?' per emoji sequence on /print. Phase 3 adds StripEmoji for modules: it maps a few typed emoji to markers (⚠ to [!], ✅ to [√], ❌ to [x], 🚨 to (!), 👍 to (+1)), then removes the remaining emoji instead of printing '?'.
NTFY AND NOTIFY CARD (modules/card.go)
The same card is used for /print/notify, /print/ntfy and the subscriber.
@@ -736,116 +519,6 @@ Images and logging
## Phases
### Phase 1: Boxes, rules, kv and preview (3-4 days)
**Goal.** One /print element gives the single and double CP437 boxes the owner liked. The output can be seen without using paper. Existing jobs print byte for byte as they do today.
**Work.**
Do this first: commit byte-compatibility fixtures. Put internal/pkg/receipt/testdata/compat/*.json and *.hex, rendered by the current code, in place before touching the renderer.
internal/pkg/escpos
- codepage.go: CanEncode(r rune) bool and Decode([]byte) string.
- interpret.go (new): Interpret(stream, cp, opaque []Span) ([]PreviewLine, error).
- It parses ESC @ t a M E - 3 2 d, GS ! B V, GS ( k, GS k and GS v 0.
- Output is text runs with their styles, plus placeholders for qr, barcode, image, raw and cut.
internal/pkg/receipt
- job.go:
- TypeBox, TypeRule and TypeKV.
- New fields: Children, Title, TitleStyle, Footer, Style, Padding *int, Fit, Columns, Pairs, Leader; type Pair.
- validate() recurses with path prefixes.
- checkFields keeps a per-type allowed set. It applies to the new types; old types stay lenient.
- Child rules allow only one level of nesting, and children count toward MaxElements.
- The doc comment explains that columns, not width, sets a block's width.
- block.go (new): boxSpec, ruleSpec and kvSpec. These checks are structural and independent of geometry.
- glyphs.go (new): border sets, the junction table and the CanEncode fallback chain.
- normalize.go (new):
- NFC, using golang.org/x/text/unicode/norm.
- The fold table, applied only to runes the code page can't encode.
- Removal of variation selectors and ZWJ.
- The emoji policy: replace on /print.
- A count of '?' left over, for warnings.
- It is called before wrap; wrap() itself is unchanged.
- cells.go (new): style, run and line types.
- blocklayout.go (new):
- layoutBox, layoutRule and layoutKV. Every line they return is exactly the block width.
- fit, columns clamping, title and footer truncation, and centring.
- render.go:
- Cases for box, rule and kv that lay out and then emit.
- Line counting against Options.MaxLines.
- ESC 3 n / ESC 2 around boxes when Options.BoxLineSpacing > 0.
- Raw elements record their byte spans for preview.
- preview.go (new): Renderer.Preview, using a placeholder fetcher and escpos.Interpret, and returning warnings.
internal/app/uberbringer/server
- server.go: New(config, Deps{Jobs, Printer, Previewer}, logger) and the route POST /api/v1/preview.
- handlers_preview.go (new): text/plain by default, JSON for Accept: application/json, 422 for max_lines.
internal/pkg/config
- [format] max_lines and [printer] box_line_spacing, with defaults and validation.
internal/app/uberbringer
- serve.go: passes MaxLines and BoxLineSpacing into receipt.Options, and the renderer as the Previewer.
- cli.go: the `preview [--config] file|-` command, rendering bold and invert with liamg/tml.
Docs and examples
- README.md: a Blocks section (field tables for box, rule and kv), a CP437 glyph cheat sheet (what prints and what doesn't), and a Preview section. Replace the hand-drawn ACHTUNG example with a box element.
- configs/config.example.toml.
- examples/blocks.json (new): a calibration gallery covering every style, padding, size 1-3, font b, dividers and fit.
**Tests.**
internal/pkg/escpos
- CanEncode tables for each code page:
- cp437 encodes every glyph used.
- cp850 and cp858 lack ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫, ▌▐, ∙ and √.
- cp1252 lacks all box and shade glyphs.
- • and ► fail everywhere.
- Decode round trip.
- Interpret applied to Builder output for every command the renderer emits, including raw spans and unknown bytes.
internal/pkg/receipt
- TestRenderCompat: the existing fixtures render identical bytes.
- Golden tests: testdata/blocks/*.json rendered to *.txt through Preview, regenerated with -update. They cover:
- box: 5 styles × inline and capped titles × padding 0-3 × size 1-3 × font a and b
- fit, columns and footer
- titles too long for the border
- every divider junction, with and without labels
- kv overflow
- every rule style
- the same set on cp850 and cp1252, to check fallbacks
- FuzzBlocks, over random block trees and options:
- every text line is exactly the block width and no wider than cols
- corners and verticals sit in the first and last columns
- no byte below 0x20 appears inside text runs
- Validation table tests:
- nested paths
- checkFields
- children that are not allowed (qr, image, raw, box)
- text together with children
- MaxElements counting children
- normalize tables:
- a decomposed é becomes one rune
- fold runs before wrap (… takes 3 columns)
- one emoji cluster becomes one '?'
- ZWJ and VS16 are dropped
- encodable text is untouched
- receipt_test.go uses escpos.Interpret in place of printedLines. All existing tests stay green.
server
- preview returns 200 text/plain and 200 JSON, 400 for an invalid job, 401 without a token, and 422 when max_lines is exceeded.
cli
- A golden test of the preview command's output.
**Done when.**
- the full gate passes (CLAUDE.md lists it), including staticcheck and govulncheck, and the compat fixtures are byte-identical.
- The README examples, mockups 6 and 7, print from one element each.
- /api/v1/preview shows the same lines.
- examples/blocks.json has been printed on the TM-T88IV and the owner has looked at the border gaps. box_line_spacing is then either set to a value checked on paper or left at 0.
### Phase 2: Notes and the module layer (2 days)
**Goal.** Basic inputs print advanced layouts. POST /api/v1/print/note with {title, text, items} prints a boxed checklist, and the module layer is ready for notifications.
+58
View File
@@ -0,0 +1,58 @@
{"elements": [
{"type": "text", "text": "Block calibration", "bold": true, "align": "center", "size": 2},
{"type": "text", "text": "Look at the gaps between the lines of the vertical borders, and at the corners and junctions.", "align": "center", "font": "b"},
{"type": "feed"},
{"type": "rule", "text": "rules", "align": "left"},
{"type": "rule"},
{"type": "rule", "style": "double"},
{"type": "rule", "style": "light"},
{"type": "rule", "style": "medium"},
{"type": "rule", "style": "dark"},
{"type": "rule", "style": "solid"},
{"type": "rule", "style": "dashed"},
{"type": "rule", "style": "dotted"},
{"type": "rule", "style": "ascii"},
{"type": "rule", "style": "double", "text": "TOTAL", "bold": true},
{"type": "feed"},
{"type": "box", "title": "single", "children": [
{"type": "text", "text": "Inline title, padding 1."},
{"type": "rule"},
{"type": "text", "text": "A single divider above, a double one below."},
{"type": "rule", "style": "double", "text": "double divider", "align": "left"},
{"type": "kv", "pairs": [{"key": "Host", "value": "nas01"}, {"key": "Used", "value": "94%", "bold": true}]}
]},
{"type": "box", "style": "double", "title": "ACHTUNG", "title_style": "capped", "align": "center",
"text": "The coffee machine is being descaled.\nDo not use until 10:30."},
{"type": "box", "style": "double", "title": "double", "footer": "29 Nov 21:04", "children": [
{"type": "text", "text": "Single divider:"},
{"type": "rule"},
{"type": "text", "text": "Double divider:"},
{"type": "rule", "style": "double"},
{"type": "text", "text": "Footer below.", "align": "right"}
]},
{"type": "box", "style": "double-h", "title": "double-h", "title_style": "capped", "children": [
{"type": "text", "text": "Double horizontal, single vertical lines."},
{"type": "rule", "style": "double"},
{"type": "text", "text": "End.", "align": "center"}
]},
{"type": "box", "style": "double-v", "title": "double-v", "children": [
{"type": "text", "text": "Single horizontal, double vertical lines."},
{"type": "rule"},
{"type": "text", "text": "End.", "align": "center"}
]},
{"type": "box", "style": "ascii", "title": "ascii", "text": "Plain ASCII for code pages without box drawing."},
{"type": "feed"},
{"type": "box", "fit": true, "padding": 0, "text": "padding 0"},
{"type": "box", "fit": true, "padding": 1, "text": "padding 1"},
{"type": "box", "fit": true, "padding": 2, "style": "double", "text": "padding 2"},
{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"},
{"type": "feed"},
{"type": "box", "size": 2, "title": "size 2", "text": "Twenty-one columns."},
{"type": "box", "size": 3, "style": "double", "fit": true, "text": "size 3"},
{"type": "box", "font": "b", "title": "font b", "footer": "56 columns", "text": "Font B is narrower and shorter, so its borders sit closer together."},
{"type": "box", "font": "b", "size": 2, "style": "double", "fit": true, "text": "font b, size 2"}
]}
+1
View File
@@ -64,6 +64,7 @@ func newRootCommand(build BuildInfo) *cobra.Command {
newVersionCommand(build),
newSecretCommand(),
newTokenCommand(&configPath),
newPreviewCommand(&configPath),
)
return root
}
+175
View File
@@ -0,0 +1,175 @@
package uberbringer
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/liamg/tml"
"github.com/spf13/cobra"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
func newPreviewCommand(configPath *string) *cobra.Command {
return &cobra.Command{
Use: "preview [file.json|-]",
Short: "Shows the lines a job would print, without printing it.",
Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" +
"lays it out for the printer in the config and writes the lines it would print.\n" +
"On a terminal, bold, underlined and inverted text is shown as such. Images are\n" +
"not loaded; each shows as a placeholder.",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load(*configPath)
if err != nil {
return err
}
data, err := readJobInput(cmd.InOrStdin(), args)
if err != nil {
return err
}
out := cmd.OutOrStdout()
return preview(cmd.Context(), cfg, data, out, cmd.ErrOrStderr(), isTerminal(out))
},
}
}
// readJobInput reads the job from the file named in args, or from stdin when
// there is none or it is "-".
func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
if len(args) == 0 || args[0] == "-" {
data, err := io.ReadAll(stdin)
if err != nil {
return nil, fmt.Errorf("reading the job from standard input: %w", err)
}
return data, nil
}
data, err := os.ReadFile(args[0])
if err != nil {
return nil, fmt.Errorf("reading the job: %w", err)
}
return data, nil
}
// preview writes the lines the job in data would print on the printer cfg
// describes to out, styled when styled is set, and its warnings to errOut.
func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut io.Writer, styled bool) error {
job, err := receipt.DecodeJob(data)
if err != nil {
return fmt.Errorf("not a valid job: %w", err)
}
options, err := rendererOptions(cfg)
if err != nil {
return err
}
p, err := receipt.NewRenderer(options, noFetch{}).Preview(ctx, job)
var ve *receipt.ValidationError
switch {
case errors.As(err, &ve):
return fmt.Errorf("invalid job:\n %s", strings.Join(ve.Problems, "\n "))
case err != nil:
return err
}
if err := writePreview(out, p, styled); err != nil {
return err
}
for _, w := range p.Warnings {
if _, err := fmt.Fprintln(errOut, "warning:", w); err != nil {
return err
}
}
return nil
}
// noFetch refuses image fetches. A preview loads no images, but a renderer
// needs a fetcher.
type noFetch struct{}
func (noFetch) Fetch(context.Context, string) ([]byte, error) {
return nil, errors.New("previews do not fetch images")
}
// writePreview writes the preview's lines. When styled is set, bold,
// underlined and inverted runs are shown with terminal attributes through
// tml. Only the tags pass through tml's parser, never the printed text, so
// a '<' in the text is not read as a tag.
func writePreview(w io.Writer, p receipt.Preview, styled bool) error {
ew := &errWriter{w: w}
styler := tml.NewParser(ew)
styler.IncludeLeadingResets = false
styler.IncludeTrailingResets = false
for _, line := range p.Lines {
runes := []rune(line.Text)
pos := 0
for _, r := range line.Runs {
tags := runTags(r)
if !styled || tags == "" {
continue
}
ew.write(string(runes[pos:r.From]))
ew.check(styler.Parse(strings.NewReader(tags)))
ew.write(string(runes[r.From:r.To]))
ew.check(styler.Parse(strings.NewReader(strings.ReplaceAll(tags, "<", "</"))))
pos = r.To
}
ew.write(string(runes[pos:]) + "\n")
}
return ew.err
}
// runTags returns the tml tags for a run's styles.
func runTags(r escpos.Run) string {
var tags string
if r.Bold {
tags += "<bold>"
}
if r.Underline != escpos.UnderlineNone {
tags += "<underline>"
}
if r.Invert {
tags += "<reverse>"
}
return tags
}
// errWriter keeps the first write error so that a loop of writes can check
// it once.
type errWriter struct {
w io.Writer
err error
}
func (e *errWriter) Write(p []byte) (int, error) {
if e.err != nil {
return 0, e.err
}
n, err := e.w.Write(p)
e.err = err
return n, err
}
func (e *errWriter) write(s string) {
_, _ = io.WriteString(e, s) // the error is kept in e.err
}
func (e *errWriter) check(err error) {
if e.err == nil {
e.err = err
}
}
// isTerminal reports whether w is a terminal, which shows text attributes.
func isTerminal(w io.Writer) bool {
f, ok := w.(*os.File)
if !ok {
return false
}
info, err := f.Stat()
return err == nil && info.Mode()&os.ModeCharDevice != 0
}
+138
View File
@@ -0,0 +1,138 @@
package uberbringer
import (
"bytes"
"flag"
"os"
"path/filepath"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/*.txt from the current output")
// writePreviewConfig writes a config for the TM-T88 at the default code page
// and returns its path.
func writePreviewConfig(t *testing.T, extra string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.toml")
body := "[api]\nsecret = \"test-only-secret-test-only-secret-0123\"\n[printer]\naddress = \"192.168.1.245\"\n" + extra
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
return path
}
// TestPreviewCommand compares the command's output for testdata's job with
// testdata/preview.txt. Run with -update to rewrite it.
func TestPreviewCommand(t *testing.T) {
cmd := newRootCommand(BuildInfo{Version: "1.2.3"})
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), filepath.Join("testdata", "preview-job.json")})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
golden := filepath.Join("testdata", "preview.txt")
if *update {
if err := os.WriteFile(golden, out.Bytes(), 0o644); err != nil {
t.Fatal(err)
}
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatal(err)
}
if out.String() != string(want) {
t.Errorf("output:\n%s\nwant:\n%s", out.String(), want)
}
if got := errOut.String(); got != "warning: elements[4]: 1 character not in cp437 printed as ?\n" {
t.Errorf("warnings = %q", got)
}
if strings.Contains(out.String(), "\x1b[") {
t.Error("output that is not a terminal must not be styled")
}
}
func TestPreviewCommandReadsStdin(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetIn(strings.NewReader(`{"elements":[{"type":"rule","text":"stdin","columns":11}]}`))
cmd.SetArgs([]string{"preview", "--config", writePreviewConfig(t, ""), "-"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if want := " ── stdin ──\n - - - - - - - partial cut - - - - - - - -\n"; out.String() != want {
t.Errorf("output = %q, want %q", out.String(), want)
}
}
func TestPreviewCommandUsesTheConfig(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetIn(strings.NewReader(`{"elements":[{"type":"box","text":"x"}]}`))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, "model = \"generic-58mm\"\ncodepage = \"cp1252\"\n")})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if lines := strings.Split(out.String(), "\n"); lines[0] != "+"+strings.Repeat("-", 30)+"+" {
t.Errorf("first line = %q, want an ascii border 32 columns wide", lines[0])
}
}
func TestPreviewCommandErrors(t *testing.T) {
tests := []struct {
name, job, config, want string
}{
{"malformed", `{"elements":`, "", "not a valid job"},
{"unknown field", `{"elements":[{"type":"rule","colour":"red"}]}`, "", `unknown field "colour"`},
{"invalid", `{"elements":[{"type":"box"},{"type":"kv"}]}`, "",
"invalid job:\n elements[0] (box): text or children is required\n elements[1] (kv): pairs: at least one pair is required"},
{"too many lines", `{"elements":[{"type":"feed","lines":20}]}`, "[format]\nmax_lines = 10\n", "receipt would print 20 lines, limit is 10"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetIn(strings.NewReader(tt.job))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, tt.config)})
err := cmd.Execute()
if err == nil || !strings.Contains(err.Error(), tt.want) {
t.Errorf("err = %v, want it to contain %q", err, tt.want)
}
})
}
}
func TestWritePreviewStyled(t *testing.T) {
p := receipt.Preview{Lines: []escpos.PreviewLine{
{Kind: escpos.LineText, Text: "a <b> c", Runs: []escpos.Run{
{From: 2, To: 5, Bold: true, Invert: true, W: 1, H: 1},
}},
{Kind: escpos.LineText, Text: "font b only", Runs: []escpos.Run{{From: 0, To: 11, Font: escpos.FontB, W: 1, H: 1}}},
{Kind: escpos.LineText, Text: "under", Runs: []escpos.Run{{From: 0, To: 5, Underline: escpos.UnderlineThick, W: 1, H: 1}}},
}}
var out bytes.Buffer
if err := writePreview(&out, p, true); err != nil {
t.Fatal(err)
}
got := out.String()
for _, want := range []string{"a \x1b[1m", "<b>", "\x1b[7m", "\x1b[0m c\n", "font b only\n", "\x1b[4munder"} {
if !strings.Contains(got, want) {
t.Errorf("output %q lacks %q", got, want)
}
}
out.Reset()
if err := writePreview(&out, p, false); err != nil {
t.Fatal(err)
}
if want := "a <b> c\nfont b only\nunder\n"; out.String() != want {
t.Errorf("plain output = %q, want %q", out.String(), want)
}
}
+30 -17
View File
@@ -50,17 +50,11 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
logger := newLogger(cfg.Log, os.Stderr)
printBanner(out, build)
profile, err := escpos.LookupProfile(cfg.Printer.Model)
options, err := rendererOptions(cfg)
if err != nil {
return fmt.Errorf("config printer.model: %w", err)
}
if cfg.Printer.PaperWidth > 0 {
profile.DotsPerLine = cfg.Printer.PaperWidth
}
codePage, err := escpos.ParseCodePage(cfg.Printer.CodePage)
if err != nil {
return fmt.Errorf("config printer.codepage: %w", err)
return err
}
profile, codePage := options.Profile, options.CodePage
flushSentry, err := initSentry(cfg.Sentry, build, logger)
if err != nil {
@@ -74,13 +68,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
AllowPrivate: cfg.Images.AllowPrivateNetworks,
AllowedHosts: cfg.Images.AllowedHosts,
})
renderer := receipt.NewRenderer(receipt.Options{
Profile: profile,
CodePage: codePage,
Columns: cfg.Printer.Columns,
MaxPixels: cfg.Images.MaxPixels,
MaxHeight: cfg.Images.MaxHeight,
}, fetcher)
renderer := receipt.NewRenderer(options, fetcher)
printerClient := printer.NewClient(
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)),
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout)
@@ -109,7 +97,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
WriteTimeout: cfg.WebServer.WriteTimeout,
IdleTimeout: cfg.WebServer.IdleTimeout,
RequestID: newRequestID,
}, queue, printerClient, logger)
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger)
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
ln, err := listen(ctx, addr)
@@ -131,6 +119,31 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
return err
}
// rendererOptions returns the receipt layout cfg describes: the printer
// profile, with any paper width override, the code page and the limits.
func rendererOptions(cfg *config.Config) (receipt.Options, error) {
profile, err := escpos.LookupProfile(cfg.Printer.Model)
if err != nil {
return receipt.Options{}, fmt.Errorf("config printer.model: %w", err)
}
if cfg.Printer.PaperWidth > 0 {
profile.DotsPerLine = cfg.Printer.PaperWidth
}
codePage, err := escpos.ParseCodePage(cfg.Printer.CodePage)
if err != nil {
return receipt.Options{}, fmt.Errorf("config printer.codepage: %w", err)
}
return receipt.Options{
Profile: profile,
CodePage: codePage,
Columns: cfg.Printer.Columns,
MaxPixels: cfg.Images.MaxPixels,
MaxHeight: cfg.Images.MaxHeight,
MaxLines: cfg.Format.MaxLines,
BoxLineSpacing: cfg.Printer.BoxLineSpacing,
}, nil
}
// newLogger builds the structured logger described by cfg.
func newLogger(cfg config.LogConfig, w io.Writer) *slog.Logger {
var level slog.Level
@@ -33,6 +33,7 @@ var (
codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"}
codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"}
codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"}
codeTooManyLines = errorCode{fiber.StatusUnprocessableEntity, "too_many_lines", "receipt would print too many lines"}
codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"}
codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"}
codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"}
+38 -20
View File
@@ -1,12 +1,10 @@
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
@@ -38,17 +36,10 @@ func handleRobots(c fiber.Ctx) error {
// handlePrint validates and queues a job.
func (s *Server) handlePrint(c fiber.Ctx) error {
job, err := decodeJob(c.Body())
job, err := decodeValidJob(c.Body())
if err != nil {
return err
}
if err := job.Validate(); err != nil {
var ve *receipt.ValidationError
if errors.As(err, &ve) {
return newAPIError(codeInvalidJob, ve.Problems...)
}
return err
}
status, err := s.jobs.Submit(job)
switch {
@@ -64,26 +55,53 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
return c.Status(fiber.StatusAccepted).JSON(status)
}
// decodeValidJob strictly decodes and validates a job body, answering
// invalid_job with every problem.
func decodeValidJob(body []byte) (receipt.Job, error) {
job, err := decodeJob(body)
if err != nil {
return job, err
}
if err := job.Validate(); err != nil {
var ve *receipt.ValidationError
if errors.As(err, &ve) {
return job, newAPIError(codeInvalidJob, ve.Problems...)
}
return job, err
}
return job, nil
}
// decodeJob strictly decodes a job body. Unknown fields are rejected so that
// typos fail loudly. An unknown "data" field gets a message that points to
// "elements" and the README instead of the decoder's text.
// typos fail loudly. A body with a top-level "data" key gets a message that
// points to "elements" and the README instead of the decoder's text.
func decodeJob(body []byte) (receipt.Job, error) {
var job receipt.Job
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(&job); err != nil {
job, err := receipt.DecodeJob(body)
switch {
case errors.Is(err, receipt.ErrTrailingData):
return job, newAPIError(codeInvalidJob.withMessage("request body has trailing data after the job"))
case err != nil:
msg := "request body is not a valid job: " + err.Error()
if strings.Contains(err.Error(), `unknown field "data"`) {
if strings.Contains(err.Error(), `unknown field "data"`) && hasTopLevelData(body) {
msg = `the {"data": [...]} format was replaced by {"elements": [...]}; see the README for the element format`
}
return job, newAPIError(codeInvalidJob.withMessage(msg))
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return job, newAPIError(codeInvalidJob.withMessage("request body has trailing data after the job"))
}
return job, nil
}
// hasTopLevelData reports whether body is a JSON object with a "data" key.
// Only that key earns the hint about "elements"; a "data" field refused
// deeper down, say in a kv pair, is an ordinary typo.
func hasTopLevelData(body []byte) bool {
var top map[string]json.RawMessage
if err := json.Unmarshal(body, &top); err != nil {
return false
}
_, ok := top["data"]
return ok
}
// handleJob returns the status of one job.
func (s *Server) handleJob(c fiber.Ctx) error {
// Clone: fasthttp reuses the buffer behind route params.
@@ -0,0 +1,100 @@
package server
import (
"errors"
"fmt"
"strings"
"github.com/gofiber/fiber/v3"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
// handlePreview answers with the lines a job would print, without printing
// it: plain text by default, or JSON with styles when the client accepts
// application/json.
func (s *Server) handlePreview(c fiber.Ctx) error {
job, err := decodeValidJob(c.Body())
if err != nil {
return err
}
preview, err := s.previewer.Preview(c.Context(), job)
var limit *receipt.LineLimitError
switch {
case errors.As(err, &limit):
return newAPIError(codeTooManyLines.withMessage(limit.Error()))
case err != nil:
return fmt.Errorf("previewing job: %w", err)
}
if c.Accepts(fiber.MIMETextPlain, fiber.MIMEApplicationJSON) == fiber.MIMEApplicationJSON {
return c.JSON(newPreviewResponse(preview))
}
var text strings.Builder
for _, line := range preview.Lines {
text.WriteString(line.Text)
text.WriteByte('\n')
}
c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
return c.SendString(text.String())
}
// previewResponse is the JSON form of a preview.
type previewResponse struct {
Columns int `json:"columns"`
CodePage string `json:"codepage"`
LineCount int `json:"line_count"`
Lines []previewLine `json:"lines"`
Warnings []string `json:"warnings"`
}
type previewLine struct {
Kind string `json:"kind"`
Text string `json:"text"`
Runs []previewRun `json:"runs,omitempty"`
Data string `json:"data,omitempty"`
}
// previewRun is a styled range of a line's text, in characters [from, to).
// Width and height are omitted at scale 1, font when it is a.
type previewRun struct {
From int `json:"from"`
To int `json:"to"`
Bold bool `json:"bold,omitempty"`
Underline int `json:"underline,omitempty"`
Invert bool `json:"invert,omitempty"`
Font string `json:"font,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
}
func newPreviewResponse(p receipt.Preview) previewResponse {
resp := previewResponse{
Columns: p.Columns,
CodePage: p.CodePage.String(),
LineCount: p.LineCount,
Lines: make([]previewLine, len(p.Lines)),
Warnings: append([]string{}, p.Warnings...),
}
scale := func(n int) int {
if n == 1 {
return 0
}
return n
}
for i, l := range p.Lines {
line := previewLine{Kind: l.Kind, Text: l.Text, Data: l.Data}
for _, r := range l.Runs {
run := previewRun{
From: r.From, To: r.To, Bold: r.Bold, Underline: int(r.Underline), Invert: r.Invert,
Width: scale(r.W), Height: scale(r.H),
}
if r.Font == escpos.FontB {
run.Font = "b"
}
line.Runs = append(line.Runs, run)
}
resp.Lines[i] = line
}
return resp
}
+23 -9
View File
@@ -36,6 +36,18 @@ type Printer interface {
Status(ctx context.Context) (escpos.Status, error)
}
// Previewer renders a job as the lines it would print, without printing it.
type Previewer interface {
Preview(ctx context.Context, job receipt.Job) (receipt.Preview, error)
}
// Deps are the services the handlers use.
type Deps struct {
Jobs Jobs
Printer Printer
Previewer Previewer
}
// Info describes the running build for the index route.
type Info struct {
Project string
@@ -79,18 +91,19 @@ const defaultHealthRecheckDelay = 750 * time.Millisecond
// Server is the HTTP API.
type Server struct {
app *fiber.App
config Config
jobs Jobs
printer Printer
logger *slog.Logger
app *fiber.App
config Config
jobs Jobs
printer Printer
previewer Previewer
logger *slog.Logger
}
// New builds the server and its routes.
func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server {
func New(config Config, deps Deps, logger *slog.Logger) *Server {
switch {
case jobs == nil || printer == nil || logger == nil:
panic("server.New: jobs, printer and logger must not be nil")
case deps.Jobs == nil || deps.Printer == nil || deps.Previewer == nil || logger == nil:
panic("server.New: jobs, printer, previewer and logger must not be nil")
case len(config.Secret) == 0:
panic("server.New: secret must not be empty")
case config.RequestID == nil:
@@ -99,7 +112,7 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
if config.HealthRecheckDelay <= 0 {
config.HealthRecheckDelay = defaultHealthRecheckDelay
}
s := &Server{config: config, jobs: jobs, printer: printer, logger: logger}
s := &Server{config: config, jobs: deps.Jobs, printer: deps.Printer, previewer: deps.Previewer, logger: logger}
s.app = fiber.New(fiber.Config{
AppName: config.Info.Project,
@@ -142,6 +155,7 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
requireBearerToken(config.Secret),
)
api.Post("/print", s.handlePrint)
api.Post("/preview", s.handlePreview)
api.Get("/jobs/:id", s.handleJob)
return s
+136 -1
View File
@@ -135,7 +135,26 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
for _, opt := range opts {
opt(&cfg)
}
return New(cfg, jobs, p, logger)
return New(cfg, Deps{Jobs: jobs, Printer: p, Previewer: testRenderer(2000)}, logger)
}
// testRenderer is a TM-T88 renderer in CP437 that previews jobs of up to
// maxLines lines.
func testRenderer(maxLines int) *receipt.Renderer {
return receipt.NewRenderer(receipt.Options{
Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9},
CodePage: escpos.CodePage437,
MaxPixels: 1000,
MaxHeight: 1000,
MaxLines: maxLines,
}, refuseFetch{})
}
// refuseFetch fails every image fetch; previews never fetch.
type refuseFetch struct{}
func (refuseFetch) Fetch(context.Context, string) ([]byte, error) {
return nil, errors.New("previews must not fetch images")
}
// logBuffer collects the server's JSON log lines.
@@ -408,6 +427,121 @@ func TestPrintValidationDetails(t *testing.T) {
}
}
func TestPrintOldFormatHintOnlyForTopLevelData(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
body := `{"elements":[{"type":"kv","pairs":[{"key":"a","data":"x"}]}]}`
resp, raw := send(t, s, printRequest(t, body, "Bearer "+validToken(t)))
e := expectError(t, resp, raw, http.StatusBadRequest, "invalid_job")
if !strings.Contains(e.Error, `unknown field "data"`) || strings.Contains(e.Error, "replaced") {
t.Errorf("error = %q, want the decoder's message", e.Error)
}
}
func previewRequest(t *testing.T, body, accept string) *http.Request {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/preview", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+validToken(t))
if accept != "" {
req.Header.Set("Accept", accept)
}
return req
}
const boxJob = `{"elements":[{"type":"box","style":"double","title":"ACHTUNG","title_style":"capped","align":"center",` +
`"text":"The coffee machine is being descaled.\nDo not use until 10:30."},` +
`{"type":"text","text":"Bold ✓","bold":true}]}`
func TestPreviewText(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
for _, accept := range []string{"", "*/*", "text/plain", "text/html"} {
resp, body := send(t, s, previewRequest(t, boxJob, accept))
if resp.StatusCode != http.StatusOK {
t.Fatalf("Accept %q: status = %d (%s)", accept, resp.StatusCode, body)
}
if ct := resp.Header.Get(fiber.HeaderContentType); ct != fiber.MIMETextPlainCharsetUTF8 {
t.Errorf("Accept %q: Content-Type = %q", accept, ct)
}
want := "╔═╡ ACHTUNG ╞════════════════════════════╗\n" +
"║ The coffee machine is being descaled. ║\n" +
"║ Do not use until 10:30. ║\n" +
"╚════════════════════════════════════════╝\n" +
"Bold √\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if string(body) != want {
t.Errorf("Accept %q: body =\n%s\nwant\n%s", accept, body, want)
}
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
t.Errorf("Cache-Control = %q, want no-store", cc)
}
}
if len(jobs.submitted) != 0 {
t.Error("a preview was queued for printing")
}
}
func TestPreviewJSON(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
job := `{"elements":[{"type":"text","text":"Hi 🎉","bold":true,"size":2,"font":"b"},{"type":"qr","data":"https://example.com"}]}`
resp, body := send(t, s, previewRequest(t, job, "application/json"))
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
want := `{"columns":42,"codepage":"cp437","line_count":2,"lines":[` +
`{"kind":"text","text":"Hi ?","runs":[{"from":0,"to":4,"bold":true,"font":"b","width":2,"height":2}]},` +
`{"kind":"qr","text":"[qr: https://example.com]","data":"https://example.com"},` +
`{"kind":"cut","text":" - - - - - - - partial cut - - - - - - - -","data":"partial"}],` +
`"warnings":["elements[0]: 1 character not in cp437 printed as ?"]}`
if string(body) != want {
t.Errorf("body =\n%s\nwant\n%s", body, want)
}
resp, body = send(t, s, previewRequest(t, validJob, "application/json"))
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), `"warnings":[]`) {
t.Errorf("status %d, body %s; want an empty warnings list", resp.StatusCode, body)
}
}
func TestPreviewRefusals(t *testing.T) {
t.Run("invalid job", func(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
resp, raw := send(t, s, previewRequest(t, `{"elements":[{"type":"box","text":"x","children":[{"type":"qr","data":"x"}]}]}`, ""))
e := expectError(t, resp, raw, http.StatusBadRequest, "invalid_job")
want := []string{
"elements[0] (box): set text or children, not both",
"elements[0].children[0] (qr): not allowed inside a box; place it after the box",
}
if strings.Join(e.Details, "\n") != strings.Join(want, "\n") {
t.Errorf("details = %q, want %q", e.Details, want)
}
})
t.Run("malformed body", func(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
resp, raw := send(t, s, previewRequest(t, `{"elements":[{"type":"rule","colour":"red"}]}`, ""))
expectError(t, resp, raw, http.StatusBadRequest, "invalid_job")
})
t.Run("no token", func(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
req := previewRequest(t, validJob, "")
req.Header.Del("Authorization")
resp, raw := send(t, s, req)
expectError(t, resp, raw, http.StatusUnauthorized, "unauthorized")
})
t.Run("too many lines", func(t *testing.T) {
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
s.previewer = testRenderer(10)
resp, raw := send(t, s, previewRequest(t, `{"copies":2,"elements":[{"type":"feed","lines":6}]}`, "application/json"))
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
if e.Error != "receipt would print 12 lines, limit is 10" {
t.Errorf("error = %q", e.Error)
}
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
t.Errorf("a refusal was logged as a failure: %v", failures)
}
})
}
func TestPrintQueueRefusals(t *testing.T) {
tests := []struct {
name string
@@ -575,6 +709,7 @@ func TestRoutesConform(t *testing.T) {
// Each authenticated route maps to a path that reaches it.
authenticated := map[string]string{
"POST /api/v1/print": "/api/v1/print",
"POST /api/v1/preview": "/api/v1/preview",
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
}
+10
View File
@@ -0,0 +1,10 @@
{"elements": [
{"type": "box", "style": "double", "title": "ACHTUNG", "title_style": "capped", "align": "center",
"text": "The coffee machine is being descaled.\nDo not use until 10:30."},
{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"},
{"type": "rule", "style": "dark", "text": "URGENT", "bold": true},
{"type": "kv", "pairs": [{"key": "Used", "value": "94%", "bold": true}]},
{"type": "text", "text": "Inverted <b>not a tag</b> 🎉", "invert": true},
{"type": "image", "url": "https://images.example/logo.png", "width": 384, "align": "center"},
{"type": "qr", "data": "https://example.com"}
]}
+13
View File
@@ -0,0 +1,13 @@
╔═╡ ACHTUNG ╞════════════════════════════╗
║ The coffee machine is being descaled. ║
║ Do not use until 10:30. ║
╚════════════════════════════════════════╝
┌─────────────────────┐
│ !!! ACHTUNG !!! │
└─────────────────────┘
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
Used ................................. 94%
Inverted <b>not a tag</b> ?
[image 384 dots: logo.png]
[qr: https://example.com]
- - - - - - - partial cut - - - - - - - -
+24
View File
@@ -18,6 +18,10 @@ import (
// shorter than the 256-bit hash output weaken the signature (RFC 7518 §3.2).
const MinSecretLength = 32
// MaxLineSpacing is the largest printer.box_line_spacing, the most ESC 3
// takes.
const MaxLineSpacing = 255
// Log formats accepted by [LogConfig.Format].
const (
LogFormatText = "text"
@@ -29,6 +33,7 @@ type Config struct {
WebServer WebServerConfig `toml:"webserver"`
API APIConfig `toml:"api"`
Printer PrinterConfig `toml:"printer"`
Format FormatConfig `toml:"format"`
Queue QueueConfig `toml:"queue"`
Images ImagesConfig `toml:"images"`
Sentry SentryConfig `toml:"sentry"`
@@ -83,6 +88,11 @@ type PrinterConfig struct {
// word wrapping. Zero derives it from the paper width.
Columns int `toml:"columns"`
// BoxLineSpacing is the line spacing, in motion units (ESC 3), used
// while a box prints, to close the gaps in its vertical borders. Zero
// keeps the printer's default spacing.
BoxLineSpacing int `toml:"box_line_spacing"`
DialTimeout time.Duration `toml:"dial_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
@@ -92,6 +102,13 @@ type PrinterConfig struct {
RetryDelay time.Duration `toml:"retry_delay"`
}
// FormatConfig configures how receipts are laid out.
type FormatConfig struct {
// MaxLines fails a job that would print more lines, all copies
// counted. It is a backstop against runaway text.
MaxLines int `toml:"max_lines"`
}
// QueueConfig configures the print queue.
type QueueConfig struct {
// Size is the number of jobs that may wait to be printed.
@@ -163,6 +180,9 @@ func Default() Config {
Retries: 3,
RetryDelay: time.Second,
},
Format: FormatConfig{
MaxLines: 2000,
},
Queue: QueueConfig{
Size: 100,
History: 1000,
@@ -239,10 +259,14 @@ func (c *Config) Validate() error {
check(validPort(p.Port), "printer.port: %d is out of range 1-65535", p.Port)
check(p.PaperWidth >= 0, "printer.paper_width must not be negative")
check(p.Columns >= 0, "printer.columns must not be negative")
check(p.BoxLineSpacing >= 0 && p.BoxLineSpacing <= MaxLineSpacing,
"printer.box_line_spacing must be 0-%d", MaxLineSpacing)
check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive")
check(p.Retries >= 0, "printer.retries must not be negative")
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
check(c.Format.MaxLines > 0, "format.max_lines must be positive")
check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative")
+30 -3
View File
@@ -50,6 +50,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
if cfg.Images.AllowPrivateNetworks {
t.Error("private networks must be blocked by default")
}
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 {
t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing)
}
}
func TestLoadOverridesAndDurations(t *testing.T) {
@@ -60,6 +63,9 @@ secret = "`+validSecret+`"
address = "printer.lan"
dial_timeout = "750ms"
paper_width = 384
box_line_spacing = 24
[format]
max_lines = 500
[images]
allowed_hosts = ["images.lan"]
[sentry]
@@ -74,8 +80,8 @@ format = "json"
if cfg.Printer.DialTimeout != 750*time.Millisecond {
t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout)
}
if cfg.Printer.PaperWidth != 384 || cfg.Log.Format != "json" {
t.Errorf("overrides not applied: %+v %+v", cfg.Printer, cfg.Log)
if cfg.Printer.PaperWidth != 384 || cfg.Printer.BoxLineSpacing != 24 || cfg.Format.MaxLines != 500 || cfg.Log.Format != "json" {
t.Errorf("overrides not applied: %+v %+v %+v", cfg.Printer, cfg.Format, cfg.Log)
}
if len(cfg.Images.AllowedHosts) != 1 || cfg.Images.AllowedHosts[0] != "images.lan" {
t.Errorf("AllowedHosts = %v", cfg.Images.AllowedHosts)
@@ -133,6 +139,26 @@ func TestLoadErrors(t *testing.T) {
body: "[webserver]\ntrusted_proxies = [\"nginx\"]\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
wantErr: `"nginx" is not an IP or CIDR`,
},
{
name: "zero max lines",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_lines = 0\n",
wantErr: "format.max_lines must be positive",
},
{
name: "negative box line spacing",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = -1\n",
wantErr: "printer.box_line_spacing must be 0-255",
},
{
name: "box line spacing too large",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n",
wantErr: "printer.box_line_spacing must be 0-255",
},
{
name: "unknown format key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n",
wantErr: "unknown keys: format.max_line",
},
{
name: "bad log level",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
@@ -162,7 +188,8 @@ func TestExampleConfigLoads(t *testing.T) {
t.Fatalf("example config: %v", err)
}
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model {
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing {
t.Error("example config values drifted from the defaults it documents")
}
}
+3
View File
@@ -115,6 +115,9 @@ func (b *Builder) Feed(lines uint8) {
b.buf.Write([]byte{esc, 'd', lines})
}
// MaxLineSpacing is the largest line spacing ESC 3 sets, in motion units.
const MaxLineSpacing = 255
// LineSpacing sets the line spacing in motion units (ESC 3 n).
func (b *Builder) LineSpacing(units uint8) {
b.buf.Write([]byte{esc, '3', units})
+35
View File
@@ -102,6 +102,41 @@ func (cp CodePage) Encode(s string) []byte {
return out
}
// CanEncode reports whether r prints as itself in cp: it maps to a byte of
// 0x20 or above other than DEL. Newline, tab and other control characters
// are not glyphs and report false, as do runes Encode turns into '?'.
func (cp CodePage) CanEncode(r rune) bool {
if r < utf8.RuneSelf {
return r >= 0x20 && r != 0x7F
}
if IsControl(r) {
return false
}
c, ok := cp.charmap().EncodeRune(r)
return ok && c >= 0x20 && c != 0x7F
}
// Decode transcodes bytes in cp to UTF-8, one rune per byte.
func (cp CodePage) Decode(b []byte) string {
cm := cp.charmap()
var sb strings.Builder
sb.Grow(len(b))
for _, c := range b {
sb.WriteRune(cm.DecodeByte(c))
}
return sb.String()
}
// codePageForTable returns the code page ESC t selects with table n.
func codePageForTable(n byte) (CodePage, bool) {
for _, cp := range []CodePage{CodePage437, CodePage850, CodePage858, CodePage1252} {
if cp.table() == n {
return cp, true
}
}
return 0, false
}
// IsControl reports whether r is a control character that [CodePage.Encode]
// drops. Newline and tab are not reported.
func IsControl(r rune) bool {
+113
View File
@@ -0,0 +1,113 @@
package escpos_test
import (
"bytes"
"testing"
"uberbringer/internal/pkg/escpos"
)
// Glyph groups the receipt blocks draw with.
const (
singleBox = "┌┐└┘─│├┤┬┴┼"
doubleBox = "╔╗╚╝═║╠╣╦╩╬"
mixedBox = "╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫"
shades = "░▒▓█"
halfBlocks = "▀▄"
sideHalves = "▌▐"
markers = "·°■"
bulletOp = "∙"
check = "√"
neverPrinted = "►◄→←" // these map to control codes 0x10-0x1F
bulletGeneral = "•"
)
func TestCanEncode(t *testing.T) {
type want struct {
cp escpos.CodePage
glyphs string
encodes bool
}
tests := []want{
{escpos.CodePage437, singleBox + doubleBox + mixedBox + shades + halfBlocks + sideHalves + markers + bulletOp + check, true},
{escpos.CodePage437, neverPrinted + bulletGeneral, false},
{escpos.CodePage850, singleBox + doubleBox + shades + halfBlocks + markers, true},
{escpos.CodePage850, mixedBox + sideHalves + bulletOp + check + neverPrinted + bulletGeneral, false},
{escpos.CodePage858, singleBox + doubleBox + shades + halfBlocks + markers + "€", true},
{escpos.CodePage858, mixedBox + sideHalves + bulletOp + check + neverPrinted + bulletGeneral, false},
// Windows-1252 has no box drawing or shades, but has the bullet
// at 0x95 and the typographic quotes and dashes.
{escpos.CodePage1252, singleBox + doubleBox + mixedBox + shades + halfBlocks + sideHalves + bulletOp + check + "■" + neverPrinted, false},
{escpos.CodePage1252, "·°" + bulletGeneral + "“”‘’–—…€™×", true},
// Every code page: printable ASCII yes, controls and newlines no.
{escpos.CodePage437, "A z~ !", true},
{escpos.CodePage437, "\n\t\x00\x1b\x7f\u0085\uFFFD", false},
{escpos.CodePage1252, "\n\t\x00\x1b\x7f\u0085\uFFFD", false},
{escpos.CodePage437, "“”‘’–—…€™×🎉漢", false},
}
for _, tt := range tests {
for _, r := range tt.glyphs {
if got := tt.cp.CanEncode(r); got != tt.encodes {
t.Errorf("%s CanEncode(%q) = %v, want %v", tt.cp, r, got, tt.encodes)
}
}
}
}
// TestCanEncodeMatchesEncode checks that CanEncode is true exactly when
// Encode prints the rune as itself rather than as '?' or not at all.
func TestCanEncodeMatchesEncode(t *testing.T) {
for _, cp := range []escpos.CodePage{escpos.CodePage437, escpos.CodePage850, escpos.CodePage858, escpos.CodePage1252} {
for r := rune(0); r < 0x2700; r++ {
if r == '?' {
continue
}
out := cp.Encode(string(r))
printsItself := len(out) == 1 && out[0] != '?' && out[0] >= 0x20
if got := cp.CanEncode(r); got != printsItself {
t.Errorf("%s CanEncode(%U) = %v, but Encode gives % X", cp, r, got, out)
}
}
}
}
func TestDecodeRoundTrip(t *testing.T) {
tests := []struct {
cp escpos.CodePage
roundTrip int // bytes 0x20-0xFF that decode to a rune encoding back to them
}{
{escpos.CodePage437, 223},
{escpos.CodePage850, 223},
{escpos.CodePage858, 223},
{escpos.CodePage1252, 218}, // 0x81, 0x8D, 0x8F, 0x90 and 0x9D are unassigned
}
for _, tt := range tests {
n := 0
for c := 0x20; c <= 0xFF; c++ {
b := []byte{byte(c)}
s := tt.cp.Decode(b)
r := []rune(s)
if len(r) != 1 {
t.Fatalf("%s Decode(% X) = %q, want one rune", tt.cp, b, s)
}
if !tt.cp.CanEncode(r[0]) {
continue
}
if got := tt.cp.Encode(s); !bytes.Equal(got, b) {
t.Errorf("%s: % X decodes to %q, which encodes to % X", tt.cp, b, s, got)
}
n++
}
if n != tt.roundTrip {
t.Errorf("%s: %d bytes round-trip, want %d", tt.cp, n, tt.roundTrip)
}
}
text := "┌─ Grüße £5 ─┐ ░▒▓ ·√°"
if got := escpos.CodePage437.Decode(escpos.CodePage437.Encode(text)); got != text {
t.Errorf("round trip = %q, want %q", got, text)
}
}
+556
View File
@@ -0,0 +1,556 @@
package escpos
import (
"fmt"
"slices"
"strings"
)
// Kinds of [PreviewLine].
const (
LineText = "text"
LineQR = "qr"
LineBarcode = "barcode"
LineImage = "image"
LineRaw = "raw"
LineCut = "cut"
)
// tabColumns is the printer's default horizontal tab spacing, in Font A
// characters.
const tabColumns = 8
// Span is the half-open byte range [From, To) of a command stream.
type Span struct {
From, To int
}
// Run is a styled range [From, To) of a preview line's text, in runes.
type Run struct {
From, To int
Bold bool
Underline Underline
Invert bool
Font Font
// W and H are the character width and height multipliers.
W, H int
}
// PreviewLine is one line the printer would print, or a placeholder for
// something that is not text.
type PreviewLine struct {
// Kind is one of LineText, LineQR, LineBarcode, LineImage, LineRaw and
// LineCut.
Kind string
// Text is the line as it prints, with leading spaces for centred and
// right-aligned lines measured in Font A columns. Other kinds carry a
// bracketed placeholder such as "[qr: https://example.com]".
Text string
// Runs lists the ranges of Text printed in anything other than plain
// Font A at scale 1.
Runs []Run
// Data is the QR code or barcode data, the image size in dots, the raw
// byte count or the cut mode.
Data string
}
// Interpret reads an ESC/POS command stream as the printer would and returns
// the lines it prints. It understands the commands [Builder] emits. The
// opaque spans are passed over unread, each shown as one LineRaw
// placeholder, because arbitrary bytes cannot be parsed reliably. Any other
// command or control byte is an error.
func Interpret(stream []byte, cp CodePage, profile Profile, opaque []Span) ([]PreviewLine, error) {
if profile.DotsPerLine <= 0 || profile.FontAWidth <= 0 || profile.FontBWidth <= 0 {
return nil, fmt.Errorf("%w: profile must be set", ErrInvalidArgument)
}
for i, s := range opaque {
if s.From < 0 || s.To < s.From || s.To > len(stream) || (i > 0 && s.From < opaque[i-1].To) {
return nil, fmt.Errorf("%w: opaque spans must be ordered ranges within the stream", ErrInvalidArgument)
}
}
in := newInterpreter(stream, cp, profile)
for {
for len(opaque) > 0 && in.pos == opaque[0].From {
in.raw(opaque[0])
opaque = opaque[1:]
}
if in.pos >= len(stream) {
break
}
if len(opaque) > 0 && in.pos > opaque[0].From {
return nil, fmt.Errorf("%w: opaque span at byte %d starts inside a command", ErrInvalidArgument, opaque[0].From)
}
if err := in.step(); err != nil {
return nil, err
}
}
if len(opaque) > 0 {
return nil, fmt.Errorf("%w: opaque span at byte %d starts inside a command", ErrInvalidArgument, opaque[0].From)
}
in.flushIfPending()
return in.lines, nil
}
// cellStyle is the print mode one character was printed in.
type cellStyle struct {
bold bool
underline Underline
invert bool
font Font
w, h int
}
func (s cellStyle) plain() bool {
return !s.bold && s.underline == UnderlineNone && !s.invert && s.font == FontA && s.w == 1 && s.h == 1
}
type cell struct {
r rune
style cellStyle
}
type interpreter struct {
stream []byte
pos int
base CodePage
cp CodePage
profile Profile
style cellStyle
justify Justification
// line holds the characters waiting in the print buffer, lineJustify
// the alignment it prints with, and x its width in dots.
line []cell
lineJustify Justification
x int
qrData []byte
// imageOpen is set while the last output was a raster band, so that
// the bands of one tall image join into one placeholder. imageWidth and
// imageRows are that image's size in dots.
imageOpen bool
imageWidth, imageRows int
lines []PreviewLine
}
func newInterpreter(stream []byte, cp CodePage, profile Profile) *interpreter {
in := &interpreter{stream: stream, base: cp, profile: profile}
in.reset()
return in
}
// reset restores the power-on settings and clears the print buffer, as
// ESC @ does.
func (in *interpreter) reset() {
in.cp = in.base
in.style = cellStyle{font: FontA, w: 1, h: 1}
in.justify = JustifyLeft
in.lineJustify = JustifyLeft
in.line = in.line[:0]
in.x = 0
}
// need returns the n bytes after the current command byte(s) at offset
// skip, or an error when the stream ends first.
func (in *interpreter) need(skip, n int, name string) ([]byte, error) {
if in.pos+skip+n > len(in.stream) {
return nil, fmt.Errorf("%w: %s at byte %d is cut short", ErrInvalidArgument, name, in.pos)
}
return in.stream[in.pos+skip : in.pos+skip+n], nil
}
func (in *interpreter) step() error {
switch c := in.stream[in.pos]; {
case c == esc:
return in.escCommand()
case c == gs:
return in.gsCommand()
case c == lf:
in.imageOpen = false
in.flush()
in.pos++
case c == ht:
in.imageOpen = false
in.tab()
in.pos++
case c < 0x20 || c == 0x7F:
return fmt.Errorf("%w: control byte 0x%02X at byte %d is not a command the interpreter knows", ErrInvalidArgument, c, in.pos)
default:
in.imageOpen = false
in.put(in.cp.charmap().DecodeByte(c))
in.pos++
}
return nil
}
func (in *interpreter) escCommand() error {
op, err := in.need(1, 1, "ESC command")
if err != nil {
return err
}
in.imageOpen = false
switch op[0] {
case '@':
in.reset()
in.pos += 2
return nil
case '2':
in.pos += 2
return nil
}
arg, err := in.need(2, 1, fmt.Sprintf("ESC %q", op[0]))
if err != nil {
return err
}
n := arg[0]
switch op[0] {
case 't':
cp, ok := codePageForTable(n)
if !ok {
return fmt.Errorf("%w: ESC t %d at byte %d selects an unsupported code page", ErrInvalidArgument, n, in.pos)
}
in.cp = cp
case 'a':
// The printer only takes a new alignment at the start of a line.
if len(in.line) == 0 {
in.justify = Justification(n % 48)
}
case 'M':
in.style.font = Font(n % 48 & 1)
case 'E':
in.style.bold = n&1 == 1
case '-':
in.style.underline = Underline(n % 48 % 3)
case '3':
// Line spacing changes the gaps between lines, not their text.
case 'd':
in.feed(int(n))
default:
return fmt.Errorf("%w: ESC 0x%02X at byte %d is not a command the interpreter knows", ErrInvalidArgument, op[0], in.pos)
}
in.pos += 3
return nil
}
func (in *interpreter) gsCommand() error {
op, err := in.need(1, 1, "GS command")
if err != nil {
return err
}
switch op[0] {
case '(':
in.imageOpen = false
return in.qrCommand()
case 'k':
in.imageOpen = false
return in.barcode()
case 'v':
return in.rasterImage()
case 'V':
in.imageOpen = false
return in.cut()
}
in.imageOpen = false
arg, err := in.need(2, 1, fmt.Sprintf("GS %q", op[0]))
if err != nil {
return err
}
n := arg[0]
switch op[0] {
case '!':
in.style.w = int(n>>4&0x07) + 1
in.style.h = int(n&0x07) + 1
case 'B':
in.style.invert = n&1 == 1
case 'h', 'w', 'H':
// Barcode height, module width and HRI position.
default:
return fmt.Errorf("%w: GS 0x%02X at byte %d is not a command the interpreter knows", ErrInvalidArgument, op[0], in.pos)
}
in.pos += 3
return nil
}
// qrCommand reads GS ( k pL pH cn fn [parameters].
func (in *interpreter) qrCommand() error {
head, err := in.need(2, 3, "GS ( command")
if err != nil {
return err
}
if head[0] != 'k' {
return fmt.Errorf("%w: GS ( 0x%02X at byte %d is not a command the interpreter knows", ErrInvalidArgument, head[0], in.pos)
}
n := int(head[1]) | int(head[2])<<8
body, err := in.need(5, n, "GS ( k")
if err != nil {
return err
}
if n < 2 || body[0] != '1' {
return fmt.Errorf("%w: GS ( k at byte %d is not a QR code command", ErrInvalidArgument, in.pos)
}
switch body[1] {
case 'A', 'C', 'E':
// Model, module size and error correction.
case 'P':
if n < 3 {
return fmt.Errorf("%w: QR store at byte %d has no data", ErrInvalidArgument, in.pos)
}
in.qrData = slices.Clone(body[3:])
case 'Q':
in.flushIfPending()
data := strings.ToValidUTF8(string(in.qrData), "?")
in.lines = append(in.lines, PreviewLine{Kind: LineQR, Text: "[qr: " + oneLine(data) + "]", Data: data})
default:
return fmt.Errorf("%w: QR function 0x%02X at byte %d is not one the interpreter knows", ErrInvalidArgument, body[1], in.pos)
}
in.pos += 5 + n
return nil
}
// barcode reads GS k m n d1...dn, or GS k m d1...NUL for function A.
func (in *interpreter) barcode() error {
head, err := in.need(2, 1, "GS k")
if err != nil {
return err
}
m := head[0]
var data []byte
var size int
switch {
case m <= 6:
end := slices.Index(in.stream[in.pos+3:], 0)
if end < 0 {
return fmt.Errorf("%w: GS k at byte %d has no terminating NUL", ErrInvalidArgument, in.pos)
}
data = in.stream[in.pos+3 : in.pos+3+end]
size = 3 + end + 1
m += byte(UPCA)
case m >= byte(UPCA) && m <= byte(CODE128):
length, err := in.need(3, 1, "GS k")
if err != nil {
return err
}
if data, err = in.need(4, int(length[0]), "GS k"); err != nil {
return err
}
size = 4 + int(length[0])
default:
return fmt.Errorf("%w: GS k barcode type %d at byte %d is not one the interpreter knows", ErrInvalidArgument, m, in.pos)
}
in.flushIfPending()
text := string(data)
if Symbology(m) == CODE128 {
text = decodeCode128(text)
}
text = strings.ToValidUTF8(text, "?")
in.lines = append(in.lines, PreviewLine{
Kind: LineBarcode,
Text: fmt.Sprintf("[barcode %s: %s]", Symbology(m), oneLine(text)),
Data: text,
})
in.pos += size
return nil
}
// decodeCode128 removes the code set selection and the escaping of '{' that
// [Builder.Barcode] adds.
func decodeCode128(s string) string {
if len(s) >= 2 && s[0] == '{' && strings.ContainsRune("ABC", rune(s[1])) {
s = s[2:]
}
return strings.ReplaceAll(s, "{{", "{")
}
// rasterImage reads GS v 0 m xL xH yL yH d1...dk.
func (in *interpreter) rasterImage() error {
head, err := in.need(2, 6, "GS v 0")
if err != nil {
return err
}
if head[0] != '0' {
return fmt.Errorf("%w: GS v 0x%02X at byte %d is not a command the interpreter knows", ErrInvalidArgument, head[0], in.pos)
}
widthBytes := int(head[2]) | int(head[3])<<8
rows := int(head[4]) | int(head[5])<<8
if _, err := in.need(8, widthBytes*rows, "GS v 0 image data"); err != nil {
return err
}
in.pos += 8 + widthBytes*rows
width := widthBytes * 8
in.flushIfPending()
if in.imageOpen && in.imageWidth == width {
in.imageRows += rows
in.lines = in.lines[:len(in.lines)-1]
} else {
in.imageWidth, in.imageRows = width, rows
}
size := fmt.Sprintf("%dx%d", in.imageWidth, in.imageRows)
in.lines = append(in.lines, PreviewLine{Kind: LineImage, Text: "[image " + size + " dots]", Data: size})
in.imageOpen = true
return nil
}
// cut reads GS V m, or GS V m n for function B.
func (in *interpreter) cut() error {
head, err := in.need(2, 1, "GS V")
if err != nil {
return err
}
size := 3
var mode string
switch m := head[0]; m {
case 0, 48:
mode = "full"
case 1, 49:
mode = "partial"
case byte(CutFull), byte(CutPartial):
if _, err := in.need(3, 1, "GS V"); err != nil {
return err
}
size = 4
mode = "partial"
if m == byte(CutFull) {
mode = "full"
}
default:
return fmt.Errorf("%w: GS V %d at byte %d is not a cut the interpreter knows", ErrInvalidArgument, m, in.pos)
}
in.flushIfPending()
in.lines = append(in.lines, PreviewLine{Kind: LineCut, Text: in.cutLine(mode + " cut"), Data: mode})
in.pos += size
return nil
}
// cutLine draws label in a dashed line across the paper.
func (in *interpreter) cutLine(label string) string {
cols := in.profile.DotsPerLine / in.profile.FontAWidth
label = " " + label + " "
left := max(0, (cols-len(label))/2)
right := max(0, cols-left-len(label))
var b strings.Builder
for d := left; d >= 1; d-- {
b.WriteByte(" -"[d%2])
}
b.WriteString(label)
for d := 1; d <= right; d++ {
b.WriteByte(" -"[d%2])
}
return strings.TrimRight(b.String(), " ")
}
func (in *interpreter) raw(s Span) {
in.imageOpen = false
in.flushIfPending()
n := s.To - s.From
in.lines = append(in.lines, PreviewLine{Kind: LineRaw, Text: fmt.Sprintf("[raw %d bytes]", n), Data: fmt.Sprint(n)})
in.pos = s.To
}
func (in *interpreter) glyphDots() int {
return in.profile.GlyphWidth(in.style.font) * in.style.w
}
// put adds one character to the print buffer, printing the buffer first
// when the character no longer fits on the line, as the printer does.
func (in *interpreter) put(r rune) {
dots := in.glyphDots()
if len(in.line) > 0 && in.x+dots > in.profile.DotsPerLine {
in.flush()
}
if len(in.line) == 0 {
in.lineJustify = in.justify
}
in.line = append(in.line, cell{r: r, style: in.style})
in.x += dots
}
// tab fills the line with spaces up to the next tab stop.
func (in *interpreter) tab() {
stop := tabColumns * in.profile.FontAWidth
next := (in.x/stop + 1) * stop
if next > in.profile.DotsPerLine {
in.flush()
return
}
for in.x < next {
in.put(' ')
}
}
// feed prints the buffer and advances n lines, as ESC d n does.
func (in *interpreter) feed(n int) {
if n == 0 {
in.flushIfPending()
return
}
in.flush()
for range n - 1 {
in.flush()
}
}
func (in *interpreter) flushIfPending() {
if len(in.line) > 0 {
in.flush()
}
}
// flush prints the buffer as one line, which may be empty.
func (in *interpreter) flush() {
var pad int
switch slack := in.profile.DotsPerLine - in.x; in.lineJustify {
case JustifyCenter:
pad = max(0, slack/2) / in.profile.FontAWidth
case JustifyRight:
pad = max(0, slack) / in.profile.FontAWidth
}
if len(in.line) == 0 {
pad = 0
}
var text strings.Builder
text.WriteString(strings.Repeat(" ", pad))
var runs []Run
for i, c := range in.line {
text.WriteRune(c.r)
if c.style.plain() {
continue
}
at := pad + i
if n := len(runs); n > 0 && runs[n-1].To == at && sameStyle(runs[n-1], c.style) {
runs[n-1].To++
continue
}
runs = append(runs, Run{
From: at, To: at + 1,
Bold: c.style.bold, Underline: c.style.underline, Invert: c.style.invert,
Font: c.style.font, W: c.style.w, H: c.style.h,
})
}
in.lines = append(in.lines, PreviewLine{Kind: LineText, Text: text.String(), Runs: runs})
in.line = in.line[:0]
in.x = 0
in.lineJustify = in.justify
}
func sameStyle(r Run, s cellStyle) bool {
return r.Bold == s.bold && r.Underline == s.underline && r.Invert == s.invert &&
r.Font == s.font && r.W == s.w && r.H == s.h
}
// oneLine replaces control characters so that a placeholder stays on one
// line of text.
func oneLine(s string) string {
return strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7F {
return ' '
}
return r
}, s)
}
+231
View File
@@ -0,0 +1,231 @@
package escpos_test
import (
"errors"
"fmt"
"image"
"reflect"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
)
var tmT88 = escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}
func interpret(t *testing.T, b *escpos.Builder, opaque ...escpos.Span) []escpos.PreviewLine {
t.Helper()
lines, err := escpos.Interpret(b.Bytes(), escpos.CodePage437, tmT88, opaque)
if err != nil {
t.Fatalf("Interpret: %v", err)
}
return lines
}
func texts(lines []escpos.PreviewLine) []string {
out := make([]string, len(lines))
for i, l := range lines {
out[i] = l.Text
}
return out
}
func mustOK(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
// TestInterpretBuilderOutput runs every command the Builder emits through
// the interpreter.
func TestInterpretBuilderOutput(t *testing.T) {
var b escpos.Builder
b.Initialize()
b.SelectCodePage(escpos.CodePage437)
b.Text(escpos.CodePage437.Encode("Plain ┌─┐ £"))
b.LineFeed()
b.Justify(escpos.JustifyCenter)
b.Bold(true)
b.Text([]byte("Hi"))
b.Bold(false)
b.LineFeed()
b.Justify(escpos.JustifyRight)
b.Text([]byte("R"))
b.LineFeed()
b.Justify(escpos.JustifyLeft)
b.Font(escpos.FontB)
mustOK(t, b.Size(2, 3))
b.Underline(escpos.UnderlineThick)
b.Reverse(true)
b.Text([]byte("big"))
b.Reverse(false)
b.Underline(escpos.UnderlineNone)
mustOK(t, b.Size(1, 1))
b.Font(escpos.FontA)
b.Text([]byte(" tail"))
b.LineFeed()
b.LineSpacing(20)
b.Text([]byte("spaced"))
b.Feed(3)
b.DefaultLineSpacing()
mustOK(t, b.QRCode([]byte("https://example.com/x"), 4, escpos.QRCorrectionH))
b.BarcodeHeight(60)
mustOK(t, b.BarcodeWidth(2))
b.BarcodeHRI(escpos.HRIBelow)
mustOK(t, b.Barcode(escpos.CODE128, "A{B-1"))
mustOK(t, b.Barcode(escpos.EAN13, "4006381333931"))
mustOK(t, b.RasterImage(image.NewGray(image.Rect(0, 0, 100, 300))))
b.Cut(escpos.CutFull, 3)
b.Text([]byte("after"))
b.Cut(escpos.CutPartial, 0)
got := interpret(t, &b)
want := []escpos.PreviewLine{
{Kind: escpos.LineText, Text: "Plain ┌─┐ £"},
{Kind: escpos.LineText, Text: strings.Repeat(" ", 20) + "Hi", Runs: []escpos.Run{{From: 20, To: 22, Bold: true, Font: escpos.FontA, W: 1, H: 1}}},
{Kind: escpos.LineText, Text: strings.Repeat(" ", 41) + "R"},
{Kind: escpos.LineText, Text: "big tail", Runs: []escpos.Run{{From: 0, To: 3, Underline: escpos.UnderlineThick, Invert: true, Font: escpos.FontB, W: 2, H: 3}}},
{Kind: escpos.LineText, Text: "spaced"},
{Kind: escpos.LineText},
{Kind: escpos.LineText},
{Kind: escpos.LineQR, Text: "[qr: https://example.com/x]", Data: "https://example.com/x"},
{Kind: escpos.LineBarcode, Text: "[barcode code128: A{B-1]", Data: "A{B-1"},
{Kind: escpos.LineBarcode, Text: "[barcode ean13: 4006381333931]", Data: "4006381333931"},
{Kind: escpos.LineImage, Text: "[image 104x300 dots]", Data: "104x300"},
{Kind: escpos.LineCut, Text: " - - - - - - - - full cut - - - - - - - -", Data: "full"},
{Kind: escpos.LineText, Text: "after"},
{Kind: escpos.LineCut, Text: " - - - - - - - partial cut - - - - - - - -", Data: "partial"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines:\n%s\nwant:\n%s", dump(got), dump(want))
}
}
func dump(lines []escpos.PreviewLine) string {
var b strings.Builder
for _, l := range lines {
fmt.Fprintf(&b, "%s %q %q %+v\n", l.Kind, l.Text, l.Data, l.Runs)
}
return b.String()
}
func TestInterpretPrinterWrapsLongLines(t *testing.T) {
var b escpos.Builder
b.Text([]byte(strings.Repeat("y", 60)))
b.LineFeed()
mustOK(t, b.Size(2, 2))
b.Text([]byte(strings.Repeat("z", 25)))
got := texts(interpret(t, &b))
want := []string{strings.Repeat("y", 42), strings.Repeat("y", 18), strings.Repeat("z", 21), strings.Repeat("z", 4)}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}
func TestInterpretJustifyTakesEffectAtLineStart(t *testing.T) {
var b escpos.Builder
b.Text([]byte("ab"))
b.Justify(escpos.JustifyRight) // mid-line: ignored by the printer
b.Text([]byte("cd"))
b.LineFeed()
b.Text([]byte("ef"))
b.LineFeed()
got := texts(interpret(t, &b))
if want := []string{"abcd", "ef"}; !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}
func TestInterpretTabs(t *testing.T) {
var b escpos.Builder
b.Text([]byte("ab\tc"))
got := texts(interpret(t, &b))
if want := []string{"ab c"}; !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}
func TestInterpretOpaqueSpans(t *testing.T) {
var b escpos.Builder
b.Text([]byte("before "))
from := b.Len()
b.Raw([]byte{0x1B, 0x61, 0x01, 0x07, 0x1C, 0xFF})
to := b.Len()
b.Text([]byte("after"))
b.LineFeed()
end := b.Len()
got := interpret(t, &b, escpos.Span{From: from, To: to}, escpos.Span{From: end, To: end})
want := []escpos.PreviewLine{
{Kind: escpos.LineText, Text: "before "},
{Kind: escpos.LineRaw, Text: "[raw 6 bytes]", Data: "6"},
{Kind: escpos.LineText, Text: "after"},
{Kind: escpos.LineRaw, Text: "[raw 0 bytes]", Data: "0"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines:\n%s\nwant:\n%s", dump(got), dump(want))
}
}
func TestInterpretFunctionAForms(t *testing.T) {
var b escpos.Builder
b.Raw([]byte{0x1D, 'k', 4})
b.Raw([]byte("AB-1"))
b.Raw([]byte{0, 0x1D, 'V', 1})
got := interpret(t, &b)
want := []escpos.PreviewLine{
{Kind: escpos.LineBarcode, Text: "[barcode code39: AB-1]", Data: "AB-1"},
{Kind: escpos.LineCut, Text: " - - - - - - - partial cut - - - - - - - -", Data: "partial"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines:\n%s\nwant:\n%s", dump(got), dump(want))
}
}
func TestInterpretRejects(t *testing.T) {
tests := []struct {
name string
stream []byte
opaque []escpos.Span
}{
{"unknown ESC command", []byte{0x1B, 'Z', 1}, nil},
{"unknown GS command", []byte{0x1D, 'Z', 1}, nil},
{"unknown GS ( function", []byte{0x1D, '(', 'L', 2, 0, '0', '1'}, nil},
{"PDF417, not QR", []byte{0x1D, '(', 'k', 3, 0, '0', 'A', 0}, nil},
{"control byte", []byte("a\x07b"), nil},
{"DEL", []byte("a\x7fb"), nil},
{"DLE EOT status request", []byte{0x10, 0x04, 1}, nil},
{"truncated ESC", []byte{0x1B}, nil},
{"truncated ESC a", []byte{0x1B, 'a'}, nil},
{"truncated QR store", []byte{0x1D, '(', 'k', 10, 0, '1', 'P', '0', 'x'}, nil},
{"truncated raster", []byte{0x1D, 'v', '0', 0, 2, 0, 2, 0, 0xFF}, nil},
{"unterminated function A barcode", []byte{0x1D, 'k', 4, 'A'}, nil},
{"unsupported code page", []byte{0x1B, 't', 99}, nil},
{"span inside a command", []byte{0x1B, 'a', 1, 'x'}, []escpos.Span{{From: 1, To: 2}}},
{"span past the end", []byte("abc"), []escpos.Span{{From: 2, To: 9}}},
{"spans out of order", []byte("abcd"), []escpos.Span{{From: 2, To: 3}, {From: 0, To: 1}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := escpos.Interpret(tt.stream, escpos.CodePage437, tmT88, tt.opaque)
if !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
})
}
}
func TestInterpretCodePageSwitch(t *testing.T) {
var b escpos.Builder
b.SelectCodePage(escpos.CodePage1252)
b.Text(escpos.CodePage1252.Encode("“€”"))
b.LineFeed()
b.Text([]byte("cleared"))
b.Initialize() // clears the print buffer and selects the default table
b.Text([]byte{0xC4})
got := texts(interpret(t, &b))
if want := []string{"“€”", "─"}; !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}
+336
View File
@@ -0,0 +1,336 @@
package receipt
import (
"fmt"
"slices"
"strings"
"uberbringer/internal/pkg/escpos"
)
// Block limits and defaults.
const (
maxBlockSize = 3
maxPadding = 3
maxColumns = 255
defaultPadding = 1
)
// boxStyle selects the border glyphs of a box.
type boxStyle int
const (
boxSingle boxStyle = iota
boxDouble
boxDoubleH
boxDoubleV
boxASCII
)
// ruleStyle selects the line a rule is drawn with.
type ruleStyle int
const (
ruleSingle ruleStyle = iota
ruleDouble
ruleLight
ruleMedium
ruleDark
ruleSolid
ruleDashed
ruleDotted
ruleASCII
)
// field is one JSON field of Element and the test for whether a job set it.
type field struct {
name string
set func(Element) bool
}
// fields lists every Element field in JSON order.
var fields = []field{
{"text", func(e Element) bool { return e.Text != "" }},
{"bold", func(e Element) bool { return e.Bold }},
{"size", func(e Element) bool { return e.Size != 0 }},
{"width", func(e Element) bool { return e.Width != 0 }},
{"height", func(e Element) bool { return e.Height != 0 }},
{"font", func(e Element) bool { return e.Font != "" }},
{"align", func(e Element) bool { return e.Align != "" }},
{"underline", func(e Element) bool { return e.Underline != 0 }},
{"invert", func(e Element) bool { return e.Invert }},
{"newline", func(e Element) bool { return e.Newline != nil }},
{"wrap", func(e Element) bool { return e.Wrap != nil }},
{"lines", func(e Element) bool { return e.Lines != 0 }},
{"data", func(e Element) bool { return e.Data != "" }},
{"correction", func(e Element) bool { return e.Correction != "" }},
{"symbology", func(e Element) bool { return e.Symbology != "" }},
{"hri", func(e Element) bool { return e.HRI != "" }},
{"url", func(e Element) bool { return e.URL != "" }},
{"base64", func(e Element) bool { return e.Base64 != "" }},
{"hex", func(e Element) bool { return e.Hex != "" }},
{"mode", func(e Element) bool { return e.Mode != "" }},
{"children", func(e Element) bool { return e.Children != nil }},
{"title", func(e Element) bool { return e.Title != "" }},
{"title_style", func(e Element) bool { return e.TitleStyle != "" }},
{"footer", func(e Element) bool { return e.Footer != "" }},
{"style", func(e Element) bool { return e.Style != "" }},
{"padding", func(e Element) bool { return e.Padding != nil }},
{"fit", func(e Element) bool { return e.Fit }},
{"columns", func(e Element) bool { return e.Columns != 0 }},
{"pairs", func(e Element) bool { return e.Pairs != nil }},
{"leader", func(e Element) bool { return e.Leader != "" }},
}
// blockOnly are the fields no other type takes.
var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader")
// blockFields are the fields each block takes at the top level.
var blockFields = map[string]map[string]bool{
TypeBox: fieldSet("text bold underline invert align size font children title title_style footer style padding fit columns"),
TypeRule: fieldSet("text bold align size font style columns"),
TypeKV: fieldSet("pairs leader size font columns"),
}
// childFields are the fields each type takes inside a box.
var childFields = map[string]map[string]bool{
TypeText: fieldSet("text bold underline invert align wrap newline"),
TypeFeed: fieldSet("lines"),
TypeRule: fieldSet("text bold align style"),
TypeKV: fieldSet("pairs leader"),
}
// inherited are the fields a child takes from its box.
var inherited = fieldSet("size width height font")
func fieldSet(names string) map[string]bool {
set := make(map[string]bool)
for _, name := range strings.Fields(names) {
set[name] = true
}
return set
}
// checkFields reports fields set on el that its type does not take. The
// blocks and the children of a box take only their own fields; the other
// types ignore unrelated fields, except the block fields.
func (el Element) checkFields(inBox bool) []string {
allowed, strict := blockFields[el.Type]
if inBox {
allowed, strict = childFields[el.Type]
}
known := strict || slices.Contains([]string{TypeText, TypeFeed, TypeQR, TypeBarcode, TypeImage, TypeRaw, TypeCut}, el.Type)
if !known {
return nil
}
var problems []string
for _, f := range fields {
if !f.set(el) {
continue
}
switch {
case inBox && inherited[f.name]:
problems = append(problems, fmt.Sprintf("%s is inherited from the box", f.name))
case inBox && !allowed[f.name]:
problems = append(problems, fmt.Sprintf("field %q does not apply to %s inside a box", f.name, el.Type))
case strict && !allowed[f.name], !strict && blockOnly[f.name]:
problems = append(problems, fmt.Sprintf("field %q does not apply to %s", f.name, el.Type))
}
}
return problems
}
// blockScale returns the size and font of a block, which scale its borders
// and its text together.
func (el Element) blockScale() (int, escpos.Font, error) {
size := max(el.Size, 1)
if el.Size < 0 || el.Size > maxBlockSize {
return 0, 0, fmt.Errorf("size must be 1-%d", maxBlockSize)
}
font, err := parseFont(el.Font)
return size, font, err
}
func checkColumns(columns int) error {
if columns < 0 || columns > maxColumns {
return fmt.Errorf("columns must be 1-%d", maxColumns)
}
return nil
}
type boxSpec struct {
style boxStyle
capped bool
text textStyle
align escpos.Justification
padding int
fit bool
columns int
size int
font escpos.Font
}
func (el Element) boxSpec() (boxSpec, error) {
s := boxSpec{
text: textStyle{bold: el.Bold, invert: el.Invert},
padding: defaultPadding,
fit: el.Fit,
columns: el.Columns,
}
var err error
if s.size, s.font, err = el.blockScale(); err != nil {
return s, err
}
if s.style, err = parseBoxStyle(el.Style); err != nil {
return s, err
}
switch strings.ToLower(el.TitleStyle) {
case "", "inline":
case "capped":
s.capped = true
default:
return s, fmt.Errorf("title_style must be inline or capped")
}
if el.Padding != nil {
if *el.Padding < 0 || *el.Padding > maxPadding {
return s, fmt.Errorf("padding must be 0-%d", maxPadding)
}
s.padding = *el.Padding
}
if err := checkColumns(el.Columns); err != nil {
return s, err
}
if s.text.underline, err = parseUnderline(el.Underline); err != nil {
return s, err
}
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
switch {
case el.Text != "" && len(el.Children) > 0:
return s, fmt.Errorf("set text or children, not both")
case el.Text == "" && len(el.Children) == 0:
return s, fmt.Errorf("text or children is required")
}
return s, nil
}
func parseBoxStyle(s string) (boxStyle, error) {
switch strings.ToLower(s) {
case "", "single":
return boxSingle, nil
case "double":
return boxDouble, nil
case "double-h":
return boxDoubleH, nil
case "double-v":
return boxDoubleV, nil
case "ascii":
return boxASCII, nil
}
return 0, fmt.Errorf("style must be single, double, double-h, double-v or ascii")
}
type ruleSpec struct {
style ruleStyle
align escpos.Justification
bold bool
columns int
size int
font escpos.Font
}
// ruleSpec checks a rule. Inside a box a rule is a divider, which only
// comes in the weights the borders have.
func (el Element) ruleSpec(inBox bool) (ruleSpec, error) {
s := ruleSpec{align: escpos.JustifyCenter, bold: el.Bold, columns: el.Columns}
var err error
if s.size, s.font, err = el.blockScale(); err != nil {
return s, err
}
if s.style, err = parseRuleStyle(el.Style); err != nil {
return s, err
}
if inBox && s.style != ruleSingle && s.style != ruleDouble {
return s, fmt.Errorf("inside a box, style must be single or double")
}
if el.Align != "" {
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
}
if err := checkColumns(el.Columns); err != nil {
return s, err
}
return s, nil
}
func parseRuleStyle(s string) (ruleStyle, error) {
switch strings.ToLower(s) {
case "", "single":
return ruleSingle, nil
case "double":
return ruleDouble, nil
case "light":
return ruleLight, nil
case "medium":
return ruleMedium, nil
case "dark":
return ruleDark, nil
case "solid":
return ruleSolid, nil
case "dashed":
return ruleDashed, nil
case "dotted":
return ruleDotted, nil
case "ascii":
return ruleASCII, nil
}
return 0, fmt.Errorf("style must be single, double, light, medium, dark, solid, dashed, dotted or ascii")
}
type kvSpec struct {
leader string
columns int
size int
font escpos.Font
}
func (el Element) kvSpec() (kvSpec, error) {
s := kvSpec{columns: el.Columns}
var err error
if s.size, s.font, err = el.blockScale(); err != nil {
return s, err
}
switch el.Leader {
case "", ".":
s.leader = "."
case "·", " ", "_", "-", "─":
s.leader = el.Leader
case "space":
s.leader = " "
default:
return s, fmt.Errorf(`leader must be ".", "·", " ", "_", "-" or "─"`)
}
if err := checkColumns(el.Columns); err != nil {
return s, err
}
switch n := len(el.Pairs); {
case n == 0:
return s, fmt.Errorf("pairs: at least one pair is required")
case n > MaxPairs:
return s, fmt.Errorf("pairs: %d pairs, limit is %d", n, MaxPairs)
}
return s, nil
}
// pairProblems reports every pair without a key.
func (el Element) pairProblems() []string {
var problems []string
for i, p := range el.Pairs {
if p.Key == "" {
problems = append(problems, fmt.Sprintf("pairs[%d]: key is required", i))
}
}
return problems
}
+405
View File
@@ -0,0 +1,405 @@
package receipt
import (
"strings"
"uberbringer/internal/pkg/escpos"
)
// Room a box needs around its title and footer, and a rule or divider
// around its label: corners, fills of at least one (title, footer) or two
// (labels) characters, and a space on each side of the text.
const (
inlineTitleRoom = 6 // ┌─ Title ─┐
cappedTitleRoom = 8 // ╔═╡ Title ╞═╗
footerRoom = 7 // └─ footer ──┘
labelRoom = 6 // ── Label ──
minBoxWidth = 3
// kvMinWidth fits a one-character key, a space, a two-character
// leader, a space and a one-character value.
kvMinWidth = 6
)
// layout lays out blocks in one code page. It normalizes their text as it
// goes and counts the characters that print as '?'.
type layout struct {
cp escpos.CodePage
unknown int
}
func (lo *layout) text(s string) string {
s, n := normalize(s, lo.cp)
lo.unknown += n
return expandTabs(s, 0)
}
func (lo *layout) line(s string) string {
s, n := normalizeLine(s, lo.cp)
lo.unknown += n
return s
}
// centre places lines of width cells in the middle of cols cells.
func centre(lines []blockLine, width, cols int) []blockLine {
margin := (cols - width) / 2
if margin <= 0 {
return lines
}
for i, l := range lines {
lines[i] = append(blockLine{plain(spaces(margin))}, l...)
}
return lines
}
// blockWidth is the width of a block with the given columns field on a
// line of cols cells.
func blockWidth(columns, cols int) int {
if columns > 0 {
return min(columns, cols)
}
return cols
}
// Kinds of item in a box body.
const (
itemText = iota
itemFeed
itemDivider
itemKV
)
// boxItem is one part of a box body, with its text already normalized.
type boxItem struct {
kind int
// itemText.
text string
style textStyle
align escpos.Justification
wrap bool
// itemFeed.
lines int
// itemDivider: label, style and alignment, and the weight of the line.
double bool
// itemKV.
pairs []kvRow
leader string
}
// kvRow is a Pair with its text normalized.
type kvRow struct {
key, value string
bold bool
}
// box lays out a box on a line of cols cells. Every line it returns, apart
// from the centring margin, is exactly the box width.
func (lo *layout) box(el Element, spec boxSpec, cols int) []blockLine {
set := bordersFor(spec.style, lo.cp)
items := lo.boxItems(el, spec)
title, footer := lo.line(el.Title), lo.line(el.Footer)
titleRoom := inlineTitleRoom
if spec.capped {
titleRoom = cappedTitleRoom
}
width := blockWidth(spec.columns, cols)
padding := spec.padding
if spec.fit {
need := minBoxWidth + 2*padding
if title != "" {
need = max(need, runeLen(title)+titleRoom)
}
if footer != "" {
need = max(need, runeLen(footer)+footerRoom)
}
for _, it := range items {
if it.kind == itemDivider {
if it.text != "" {
// The label needs its room inside the two junctions.
need = max(need, runeLen(it.text)+labelRoom+2)
}
continue
}
need = max(need, it.naturalWidth(width-2-2*padding)+2+2*padding)
}
width = min(width, need)
}
// Narrow boxes give up padding before they give up content.
width = max(width, minBoxWidth)
padding = min(padding, (width-minBoxWidth)/2)
content := width - 2 - 2*padding
lines := []blockLine{set.top(title, spec.capped, width)}
for _, it := range items {
if it.kind == itemDivider {
lines = append(lines, lo.divider(set, it, width))
continue
}
for _, row := range it.contentLines(content) {
line := blockLine{plain(string(set.vertical) + spaces(padding))}
line = append(line, row...)
line = append(line, plain(spaces(padding)+string(set.vertical)))
lines = append(lines, line)
}
}
lines = append(lines, set.bottom(footer, width))
return centre(lines, width, cols)
}
// boxItems turns the body of a box, its text or its children, into items.
// The job has been validated, so the children's specs parse; their errors
// are not checked again here.
func (lo *layout) boxItems(el Element, spec boxSpec) []boxItem {
if len(el.Children) == 0 {
return []boxItem{{kind: itemText, text: lo.text(el.Text), style: spec.text, align: spec.align, wrap: true}}
}
var items []boxItem
for _, child := range el.Children {
switch child.Type {
case TypeText:
ts, _ := child.textSpec()
align := ts.align
if child.Align == "" {
align = spec.align
}
items = append(items, boxItem{
kind: itemText,
text: lo.text(child.Text),
style: textStyle{bold: ts.bold, underline: ts.underline, invert: ts.invert},
align: align,
wrap: ts.wrap,
})
case TypeFeed:
n, _ := child.feedLines()
items = append(items, boxItem{kind: itemFeed, lines: int(n)})
case TypeRule:
rs, _ := child.ruleSpec(true)
items = append(items, boxItem{
kind: itemDivider,
text: lo.line(child.Text),
style: textStyle{bold: rs.bold},
align: rs.align,
double: rs.style == ruleDouble,
})
case TypeKV:
ks, _ := child.kvSpec()
items = append(items, boxItem{kind: itemKV, pairs: lo.kvRows(child.Pairs), leader: leaderFor(ks.leader, lo.cp)})
}
}
return items
}
// naturalWidth is the content width a text or kv item needs, given at most
// limit cells; fit boxes shrink to the widest item.
func (it boxItem) naturalWidth(limit int) int {
limit = max(limit, 1)
switch it.kind {
case itemText:
widest := 0
for _, row := range it.rows(limit) {
widest = max(widest, runeLen(row))
}
return widest
case itemKV:
widest := 0
for _, p := range it.pairs {
widest = max(widest, runeLen(p.key)+4+runeLen(p.value))
}
return min(widest, limit)
}
return 0
}
// rows splits a text item into lines of at most width runes.
func (it boxItem) rows(width int) []string {
if it.wrap {
return wrap(it.text, width, width)
}
var rows []string
for _, para := range strings.Split(it.text, "\n") {
r := []rune(para)
for len(r) > width {
rows = append(rows, string(r[:width]))
r = r[width:]
}
rows = append(rows, string(r))
}
return rows
}
// contentLines lays out a text, feed or kv item at exactly width cells.
func (it boxItem) contentLines(width int) []blockLine {
switch it.kind {
case itemFeed:
lines := make([]blockLine, it.lines)
for i := range lines {
lines[i] = blockLine{plain(spaces(width))}
}
return lines
case itemKV:
return kvLines(it.pairs, it.leader, width)
}
var lines []blockLine
for _, row := range it.rows(width) {
n := runeLen(row)
left := 0
switch it.align {
case escpos.JustifyCenter:
left = (width - n) / 2
case escpos.JustifyRight:
left = width - n
}
lines = append(lines, blockLine{
plain(spaces(left)),
{text: row, style: it.style},
plain(spaces(width - n - left)),
})
}
return lines
}
// top draws the top border, with the title set into it.
func (b borders) top(title string, capped bool, width int) blockLine {
h := string(b.horizontal)
inner := width - 2
room := inlineTitleRoom
if capped {
room = cappedTitleRoom
}
title = truncate(title, width-room)
if title == "" {
return blockLine{plain(string(b.topLeft) + fill(h, inner) + string(b.topRight))}
}
head := string(b.topLeft) + h + " "
tail := " "
if capped {
head = string(b.topLeft) + h + string(b.capLeft) + " "
tail = " " + string(b.capRight)
}
rest := width - runeLen(head) - runeLen(title) - runeLen(tail) - 1
return blockLine{
plain(head),
plain(title),
plain(tail + fill(h, rest) + string(b.topRight)),
}
}
// bottom draws the bottom border, with the footer set into it on the right.
func (b borders) bottom(footer string, width int) blockLine {
h := string(b.horizontal)
footer = truncate(footer, width-footerRoom)
if footer == "" {
return blockLine{plain(string(b.bottomLeft) + fill(h, width-2) + string(b.bottomRight))}
}
rest := width - runeLen(footer) - 6
return blockLine{
plain(string(b.bottomLeft) + fill(h, rest) + " "),
plain(footer),
plain(" " + fill(h, 2) + string(b.bottomRight)),
}
}
// divider draws a rule inside a box, joined to its borders.
func (lo *layout) divider(b borders, it boxItem, width int) blockLine {
left, h, right := b.divider(it.double, lo.cp)
line := blockLine{plain(string(left))}
line = append(line, labelled(string(h), it.text, it.style, it.align, width-2)...)
return append(line, plain(string(right)))
}
// labelled draws a line of pattern, width cells long, with label set into
// it at align.
func labelled(pattern, label string, style textStyle, align escpos.Justification, width int) blockLine {
label = truncate(label, width-labelRoom)
if label == "" {
return blockLine{plain(fill(pattern, width))}
}
rest := width - runeLen(label) - 2
var left int
switch align {
case escpos.JustifyLeft:
left = 2
case escpos.JustifyRight:
left = rest - 2
default:
left = rest / 2
}
return blockLine{
plain(fillTowards(pattern, left, true) + " "),
{text: label, style: style},
plain(" " + fillTowards(pattern, rest-left, false)),
}
}
// rule lays out a rule on a line of cols cells.
func (lo *layout) rule(el Element, spec ruleSpec, cols int) []blockLine {
width := blockWidth(spec.columns, cols)
line := labelled(rulePattern(spec.style, lo.cp), lo.line(el.Text), textStyle{bold: spec.bold}, spec.align, width)
return centre([]blockLine{line}, width, cols)
}
// kv lays out a kv block on a line of cols cells.
func (lo *layout) kv(el Element, spec kvSpec, cols int) []blockLine {
width := blockWidth(spec.columns, cols)
lines := kvLines(lo.kvRows(el.Pairs), leaderFor(spec.leader, lo.cp), width)
return centre(lines, width, cols)
}
func (lo *layout) kvRows(pairs []Pair) []kvRow {
rows := make([]kvRow, len(pairs))
for i, p := range pairs {
rows[i] = kvRow{key: lo.line(p.Key), value: lo.text(p.Value), bold: p.Bold}
}
return rows
}
// kvLines lays out rows at exactly width cells: the key, a space, a leader
// of at least two, a space and the value. A value too long for the line
// wraps to the room after the key, and its further lines are right-aligned.
func kvLines(rows []kvRow, leader string, width int) []blockLine {
if width < kvMinWidth {
return narrowKVLines(rows, width)
}
var lines []blockLine
for _, row := range rows {
style := textStyle{bold: row.bold}
key := truncate(row.key, max(width-8, 1))
room := max(width-runeLen(key)-4, 1)
values := wrap(row.value, room, room)
first := values[0]
dots := width - runeLen(key) - 2 - runeLen(first)
tail := blockLine{plain(" "), {text: first, style: style}}
if first == "" {
dots++
tail = nil
}
line := blockLine{{text: key, style: style}, plain(" " + fill(leader, dots))}
lines = append(lines, append(line, tail...))
for _, v := range values[1:] {
lines = append(lines, blockLine{plain(spaces(width - runeLen(v))), {text: v, style: style}})
}
}
return lines
}
// narrowKVLines lays out rows on lines too narrow for a key, a leader and a
// value side by side: the key on a line of its own, then the value,
// right-aligned.
func narrowKVLines(rows []kvRow, width int) []blockLine {
width = max(width, 1)
var lines []blockLine
for _, row := range rows {
style := textStyle{bold: row.bold}
key := truncate(row.key, width)
lines = append(lines, blockLine{{text: key, style: style}, plain(spaces(width - runeLen(key)))})
for _, v := range wrap(row.value, width, width) {
lines = append(lines, blockLine{plain(spaces(width - runeLen(v))), {text: v, style: style}})
}
}
return lines
}
+356
View File
@@ -0,0 +1,356 @@
package receipt_test
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
func intPtr(n int) *int { return &n }
// previewLines previews job on a TM-T88 in cp and returns its text lines,
// without the final cut.
func previewLines(t *testing.T, cp escpos.CodePage, elements ...receipt.Element) []string {
t.Helper()
p, err := newPreviewer(t, "tm-t88", cp).Preview(context.Background(), receipt.Job{Elements: elements})
if err != nil {
t.Fatalf("Preview: %v", err)
}
var lines []string
for _, l := range p.Lines {
if l.Kind == escpos.LineText {
lines = append(lines, l.Text)
}
}
return lines
}
func expectLines(t *testing.T, got []string, want ...string) {
t.Helper()
if strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Errorf("printed:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}
// TestMockups pins the boxes the README shows, each printed from one
// element.
func TestMockups(t *testing.T) {
t.Run("double box, capped title, centred", func(t *testing.T) {
got := previewLines(t, escpos.CodePage437, receipt.Element{
Type: "box", Style: "double", Title: "ACHTUNG", TitleStyle: "capped", Align: "center",
Text: "The coffee machine is being descaled.\nDo not use until 10:30.",
})
expectLines(t, got,
"╔═╡ ACHTUNG ╞════════════════════════════╗",
"║ The coffee machine is being descaled. ║",
"║ Do not use until 10:30. ║",
"╚════════════════════════════════════════╝",
)
})
t.Run("fit, single", func(t *testing.T) {
got := previewLines(t, escpos.CodePage437, receipt.Element{Type: "box", Fit: true, Padding: intPtr(3), Text: "!!! ACHTUNG !!!"})
expectLines(t, got,
" ┌─────────────────────┐",
" │ !!! ACHTUNG !!! │",
" └─────────────────────┘",
)
})
t.Run("fit, double", func(t *testing.T) {
got := previewLines(t, escpos.CodePage437, receipt.Element{Type: "box", Style: "double", Fit: true, Padding: intPtr(2), Text: "!!! ACHTUNG !!!"})
expectLines(t, got,
" ╔═══════════════════╗",
" ║ !!! ACHTUNG !!! ║",
" ╚═══════════════════╝",
)
})
}
// TestBoxMatrix lays out every box style, title style, padding, size and
// font in every golden code page, and checks the geometry of each line.
func TestBoxMatrix(t *testing.T) {
styles := []string{"single", "double", "double-h", "double-v", "ascii"}
const (
tops = "┌╔╒╓+"
topEnds = "┐╗╕╖+"
sides = "│║|"
bottoms = "└╚╘╙+"
botEnds = "┘╝╛╜+"
joins = "├╞╟╠+"
joinEnd = "┤╡╢╣+"
)
for _, cp := range goldenCodePages {
r := newPreviewer(t, "tm-t88", cp)
for _, style := range styles {
for _, titleStyle := range []string{"inline", "capped"} {
for padding := range 4 {
for size := 1; size <= 3; size++ {
for _, font := range []string{"a", "b"} {
el := receipt.Element{
Type: "box", Style: style, Title: "Title", TitleStyle: titleStyle,
Padding: intPtr(padding), Size: size, Font: font, Footer: "foot",
Children: []receipt.Element{
{Type: "text", Text: "Some text that wraps across the lines of the box."},
{Type: "rule", Text: "label"},
{Type: "kv", Pairs: []receipt.Pair{{Key: "k", Value: "value"}}},
{Type: "rule", Style: "double"},
},
}
name := fmt.Sprintf("%s/%s/%s/p%d/s%d/%s", cp, style, titleStyle, padding, size, font)
p, err := r.Preview(context.Background(), receipt.Job{Elements: []receipt.Element{el}})
if err != nil {
t.Fatalf("%s: %v", name, err)
}
glyph := map[string]int{"a": 12, "b": 9}[font]
cols := 512 / (glyph * size)
var lines []string
for _, l := range p.Lines {
if l.Kind == escpos.LineText {
lines = append(lines, l.Text)
}
}
for i, line := range lines {
runes := []rune(line)
if len(runes) != cols {
t.Errorf("%s: line %d %q is %d wide, want %d", name, i, line, len(runes), cols)
continue
}
first, last := string(runes[0]), string(runes[len(runes)-1])
var wantFirst, wantLast string
switch {
case i == 0:
wantFirst, wantLast = tops, topEnds
case i == len(lines)-1:
wantFirst, wantLast = bottoms, botEnds
case strings.Contains(joins, first):
wantFirst, wantLast = joins, joinEnd
default:
wantFirst, wantLast = sides, sides
}
if !strings.Contains(wantFirst, first) || !strings.Contains(wantLast, last) {
t.Errorf("%s: line %d %q does not start and end with a border", name, i, line)
}
for _, r := range line {
if !cp.CanEncode(r) {
t.Errorf("%s: line %d has %q, which %s cannot print", name, i, r, cp)
}
}
}
}
}
}
}
}
}
}
func TestBlockStyleRuns(t *testing.T) {
p, err := newPreviewer(t, "tm-t88", escpos.CodePage437).Preview(context.Background(), receipt.Job{Elements: []receipt.Element{
{Type: "box", Text: "Bold", Bold: true, Underline: 1, Invert: true, Title: "T"},
{Type: "kv", Pairs: []receipt.Pair{{Key: "Key", Value: "Value", Bold: true}}},
{Type: "rule", Text: "Label", Bold: true, Size: 2},
}})
if err != nil {
t.Fatal(err)
}
styled := func(line int) []escpos.Run { return p.Lines[line].Runs }
bold := escpos.Run{Bold: true, Font: escpos.FontA, W: 1, H: 1}
tests := []struct {
line int
want []escpos.Run
}{
{0, nil}, // the top border, title included, is plain
{1, []escpos.Run{{From: 2, To: 6, Bold: true, Underline: escpos.UnderlineThin, Invert: true, Font: escpos.FontA, W: 1, H: 1}}},
{2, nil},
{3, []escpos.Run{withSpan(bold, 0, 3), withSpan(bold, 37, 42)}},
{4, []escpos.Run{
{From: 0, To: 8, Font: escpos.FontA, W: 2, H: 2},
{From: 8, To: 13, Bold: true, Font: escpos.FontA, W: 2, H: 2},
{From: 13, To: 21, Font: escpos.FontA, W: 2, H: 2},
}},
}
for _, tt := range tests {
if got := styled(tt.line); fmt.Sprint(got) != fmt.Sprint(tt.want) {
t.Errorf("line %d %q runs = %+v, want %+v", tt.line, p.Lines[tt.line].Text, got, tt.want)
}
}
}
func withSpan(r escpos.Run, from, to int) escpos.Run {
r.From, r.To = from, to
return r
}
func TestBoxLineSpacing(t *testing.T) {
r := receipt.NewRenderer(receipt.Options{
Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9},
CodePage: escpos.CodePage437,
MaxPixels: 1000,
MaxHeight: 1000,
BoxLineSpacing: 24,
}, &fakeFetcher{})
out, err := r.Render(context.Background(), receipt.Job{Elements: []receipt.Element{
{Type: "rule"},
{Type: "box", Text: "spaced"},
{Type: "kv", Pairs: []receipt.Pair{{Key: "a", Value: "b"}}},
}})
if err != nil {
t.Fatal(err)
}
set, reset := []byte{0x1B, '3', 24}, []byte{0x1B, '2'}
if bytes.Count(out, set) != 1 || bytes.Count(out, reset) != 1 {
t.Fatalf("want one ESC 3 24 and one ESC 2, got % X", out)
}
top := bytes.Index(out, escpos.CodePage437.Encode("┌"))
bottom := bytes.Index(out, escpos.CodePage437.Encode("┘"))
if i := bytes.Index(out, set); i > top || bytes.Index(out, reset) < bottom {
t.Error("the line spacing must be set before the box and restored after it")
}
if i := bytes.Index(out, set); i < bytes.LastIndex(out[:top], escpos.CodePage437.Encode("─")) {
t.Error("the rule before the box must keep the default spacing")
}
plain := render(t, receipt.Job{Elements: []receipt.Element{{Type: "box", Text: "default"}}})
if bytes.Contains(plain, set[:2]) || bytes.Contains(plain, reset) {
t.Error("without BoxLineSpacing no line spacing command may be sent")
}
}
func TestLineLimit(t *testing.T) {
r := receipt.NewRenderer(receipt.Options{
Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9},
CodePage: escpos.CodePage437,
MaxPixels: 1000,
MaxHeight: 1000,
MaxLines: 100,
}, &fakeFetcher{})
tests := []struct {
name string
job receipt.Job
lines int // 0 when the job is within the limit
}{
{"within", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 99}}}, 0},
{"exactly the limit", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 99}, {Type: "text", Text: "x"}}}, 0},
{"one over", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 100}, {Type: "text", Text: "x"}}}, 101},
{"copies count", receipt.Job{Copies: 3, Elements: []receipt.Element{{Type: "feed", Lines: 40}}}, 120},
{"wrapped text", receipt.Job{Elements: []receipt.Element{{Type: "text", Text: strings.Repeat("word ", 1000)}}}, 120},
{"box", receipt.Job{Elements: []receipt.Element{{Type: "box", Text: strings.Repeat("\n", 98)}}}, 101},
{"kv rows in a box", receipt.Job{Elements: []receipt.Element{{Type: "box", Children: []receipt.Element{{Type: "kv", Pairs: manyPairs(100)}}}}}, 102},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, renderErr := r.Render(context.Background(), tt.job)
p, previewErr := r.Preview(context.Background(), tt.job)
for name, err := range map[string]error{"Render": renderErr, "Preview": previewErr} {
var limit *receipt.LineLimitError
switch {
case tt.lines == 0 && err != nil:
t.Errorf("%s: %v", name, err)
case tt.lines > 0 && !errors.As(err, &limit):
t.Errorf("%s: err = %v, want *LineLimitError", name, err)
case tt.lines > 0 && tt.name != "wrapped text" && limit.Lines != tt.lines:
t.Errorf("%s: %d lines, want %d", name, limit.Lines, tt.lines)
case tt.lines > 0 && limit.Error() != fmt.Sprintf("receipt would print %d lines, limit is 100", limit.Lines):
t.Errorf("%s: message %q", name, limit.Error())
}
}
if tt.lines == 0 && p.LineCount > 100 {
t.Errorf("LineCount = %d", p.LineCount)
}
})
}
}
func manyPairs(n int) []receipt.Pair {
pairs := make([]receipt.Pair, n)
for i := range pairs {
pairs[i] = receipt.Pair{Key: "k", Value: "v"}
}
return pairs
}
func TestPreview(t *testing.T) {
fetcher := &fakeFetcher{err: errors.New("preview must not fetch")}
r := receipt.NewRenderer(receipt.Options{
Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9},
CodePage: escpos.CodePage437,
MaxPixels: 1000,
MaxHeight: 1000,
}, fetcher)
job := receipt.Job{Copies: 2, Elements: []receipt.Element{
{Type: "text", Text: "Tea “Earl Grey” 🍵", Align: "center"},
{Type: "raw", Hex: "1B 61 01 07"},
{Type: "image", URL: "https://images.example/logo.png?size=2", Width: 384},
{Type: "image", Base64: "iVBORw0KGgo=", Width: 600},
{Type: "qr", Data: "https://example.com"},
{Type: "barcode", Symbology: "ean8", Data: "9638507"},
{Type: "cut", Mode: "full"},
}}
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatal(err)
}
if len(fetcher.urls) != 0 {
t.Errorf("preview fetched %v", fetcher.urls)
}
copyLines := []string{
strings.Repeat(" ", 12) + `Tea "Earl Grey" ?`,
"[raw 4 bytes]",
"[image 384 dots: logo.png]",
"[image 600 dots: base64]",
"[qr: https://example.com]",
"[barcode ean8: 9638507]",
" - - - - - - - - full cut - - - - - - - -",
}
var got []string
for _, l := range p.Lines {
got = append(got, l.Text)
}
expectLines(t, got, append(copyLines, copyLines...)...)
if p.Lines[2].Data != "https://images.example/logo.png?size=2" || p.Lines[3].Data != "base64" {
t.Errorf("image data = %q, %q", p.Lines[2].Data, p.Lines[3].Data)
}
if p.Columns != 42 || p.CodePage != escpos.CodePage437 || p.LineCount != 10 {
t.Errorf("columns %d, code page %s, %d lines; want 42, cp437 and 10", p.Columns, p.CodePage, p.LineCount)
}
wantWarnings := []string{
"elements[0]: 1 character not in cp437 printed as ?",
"elements[3] (image): width 600 is wider than the 512-dot paper, so the job would fail",
}
if strings.Join(p.Warnings, "\n") != strings.Join(wantWarnings, "\n") {
t.Errorf("warnings = %q, want %q", p.Warnings, wantWarnings)
}
}
func TestPreviewRejectsInvalidJobs(t *testing.T) {
_, err := newPreviewer(t, "tm-t88", escpos.CodePage437).Preview(context.Background(), receipt.Job{})
var ve *receipt.ValidationError
if !errors.As(err, &ve) {
t.Errorf("err = %v, want *ValidationError", err)
}
}
// TestRenderBlocksBytes pins the commands a block is printed with.
func TestRenderBlocksBytes(t *testing.T) {
out := render(t, receipt.Job{Elements: []receipt.Element{
{Type: "text", Text: "x", Newline: boolPtr(false)},
{Type: "rule", Columns: 4, Size: 2, Text: "", Style: "double"},
}})
want := []byte{
'x', 0x1B, 'E', 0, 0x1B, '-', 0, 0x1D, 'B', 0, 0x1D, '!', 0, 0x1B, 'M', 0, // the text and its reset
0x0A, // the inline line is ended before the block
0x1B, 'a', 0, 0x1B, 'M', 0, 0x1D, '!', 0x11, // left, Font A, size 2
0x1B, 'E', 0, 0x1B, '-', 0, 0x1D, 'B', 0, // plain
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // centred on 24 columns
0xCD, 0xCD, 0xCD, 0xCD, 0x0A,
0x1B, 'E', 0, 0x1B, '-', 0, 0x1D, 'B', 0, 0x1D, '!', 0, 0x1B, 'M', 0, // reset
}
if !bytes.Contains(out, want) {
t.Errorf("stream % X does not contain % X", out, want)
}
}
+83
View File
@@ -0,0 +1,83 @@
package receipt
import (
"strings"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
)
// textStyle is how a run of block text prints. Borders, fills, padding and
// margins are always plain.
type textStyle struct {
bold bool
underline escpos.Underline
invert bool
}
// run is text printed in one style. Each rune is one character cell.
type run struct {
text string
style textStyle
}
// blockLine is one printed line of a block.
type blockLine []run
func plain(s string) run {
return run{text: s}
}
func spaces(n int) string {
return strings.Repeat(" ", max(n, 0))
}
// fill repeats pattern to exactly n runes.
func fill(pattern string, n int) string {
p := []rune(pattern)
if n <= 0 || len(p) == 0 {
return ""
}
out := make([]rune, n)
for i := range out {
out[i] = p[i%len(p)]
}
return string(out)
}
// fillTowards is fill for the n runes before (towards the right end) or
// after something, laid out so that the pattern starts next to it. A
// dashed fill then always ends in a dash, never a space, at a label.
func fillTowards(pattern string, n int, before bool) string {
p := []rune(pattern)
if n <= 0 || len(p) == 0 {
return ""
}
out := make([]rune, n)
for i := range out {
d := i
if before {
d = n - 1 - i
}
out[i] = p[d%len(p)]
}
return string(out)
}
// truncate shortens s to at most n runes, marking the cut with "...".
func truncate(s string, n int) string {
r := []rune(s)
switch {
case n <= 0:
return ""
case len(r) <= n:
return s
case n <= 3:
return string(r[:n])
}
return string(r[:n-3]) + "..."
}
func runeLen(s string) int {
return utf8.RuneCountInString(s)
}
+195
View File
@@ -0,0 +1,195 @@
package receipt_test
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"flag"
"os"
"path/filepath"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
// updateCompat rewrites the .hex files from the current renderer. It is a
// flag of its own so that refreshing other golden files can never rewrite
// these by accident.
var updateCompat = flag.Bool("update-compat", false, "rewrite testdata/compat/*.hex from the current renderer")
// compatFixture is one testdata/compat/*.json file: a job and the renderer
// options it is rendered with.
type compatFixture struct {
Options struct {
Model string `json:"model"`
CodePage string `json:"codepage"`
Columns int `json:"columns"`
} `json:"options"`
Job receipt.Job `json:"job"`
}
// TestRenderCompat renders each fixture job and compares the bytes with its
// .hex file, so that any change to the bytes of these jobs fails a test.
func TestRenderCompat(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "compat", "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no fixtures in testdata/compat")
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
got := renderCompatFixture(t, path)
hexPath := strings.TrimSuffix(path, ".json") + ".hex"
if *updateCompat {
if err := os.WriteFile(hexPath, []byte(formatHex(got)), 0o644); err != nil {
t.Fatal(err)
}
return
}
raw, err := os.ReadFile(hexPath)
if err != nil {
t.Fatal(err)
}
want, err := hex.DecodeString(strings.Join(strings.Fields(string(raw)), ""))
if err != nil {
t.Fatalf("%s: %v", hexPath, err)
}
if !bytes.Equal(got, want) {
at := firstDifference(got, want)
t.Errorf("rendered %d bytes, want %d; first difference at byte %d:\n got % X\nwant % X",
len(got), len(want), at, window(got, at), window(want, at))
}
})
}
}
// updatePaper rewrites the bytes of receipts that were checked on paper.
// Use it only after the new bytes have been printed and checked again.
var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex from the current renderer")
// paperReceipts are jobs whose printed result was checked on the TM-T88IV,
// with the file their bytes are pinned in. The bytes are rendered for a
// TM-T88 in CP437 with the default options.
var paperReceipts = []struct{ job, hex string }{
{filepath.Join("..", "..", "..", "examples", "blocks.json"), filepath.Join("testdata", "paper", "blocks.hex")},
}
// TestPaperReceipts fails when the bytes of a receipt checked on paper
// change, so that the change is printed and checked again.
func TestPaperReceipts(t *testing.T) {
for _, receiptFile := range paperReceipts {
t.Run(filepath.Base(receiptFile.job), func(t *testing.T) {
profile, err := escpos.LookupProfile("tm-t88")
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile,
CodePage: escpos.CodePage437,
MaxPixels: 25_000_000,
MaxHeight: 4000,
MaxLines: 2000,
}, &fakeFetcher{})
got, err := r.Render(context.Background(), readJob(t, receiptFile.job))
if err != nil {
t.Fatal(err)
}
if *updatePaper {
if err := os.MkdirAll(filepath.Dir(receiptFile.hex), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(receiptFile.hex, []byte(formatHex(got)), 0o644); err != nil {
t.Fatal(err)
}
return
}
raw, err := os.ReadFile(receiptFile.hex)
if err != nil {
t.Fatal(err)
}
want, err := hex.DecodeString(strings.Join(strings.Fields(string(raw)), ""))
if err != nil {
t.Fatalf("%s: %v", receiptFile.hex, err)
}
if !bytes.Equal(got, want) {
at := firstDifference(got, want)
t.Errorf("%s renders %d bytes, %d were checked on paper; first difference at byte %d:\n got % X\nwant % X\nPrint it, have it checked, then run with -update-paper.",
receiptFile.job, len(got), len(want), at, window(got, at), window(want, at))
}
})
}
}
func renderCompatFixture(t *testing.T, path string) []byte {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var fixture compatFixture
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&fixture); err != nil {
t.Fatalf("%s: %v", path, err)
}
opts := fixture.Options
if opts.Model == "" {
opts.Model = "tm-t88"
}
if opts.CodePage == "" {
opts.CodePage = "cp437"
}
profile, err := escpos.LookupProfile(opts.Model)
if err != nil {
t.Fatal(err)
}
codePage, err := escpos.ParseCodePage(opts.CodePage)
if err != nil {
t.Fatal(err)
}
renderer := receipt.NewRenderer(receipt.Options{
Profile: profile,
CodePage: codePage,
Columns: opts.Columns,
MaxPixels: 10_000_000,
MaxHeight: 4000,
}, &fakeFetcher{})
out, err := renderer.Render(context.Background(), fixture.Job)
if err != nil {
t.Fatalf("Render: %v", err)
}
return out
}
// formatHex writes data as lowercase hex, 32 bytes per line.
func formatHex(data []byte) string {
var b strings.Builder
for len(data) > 0 {
n := min(32, len(data))
b.WriteString(hex.EncodeToString(data[:n]))
b.WriteByte('\n')
data = data[n:]
}
return b.String()
}
func firstDifference(a, b []byte) int {
for i := range min(len(a), len(b)) {
if a[i] != b[i] {
return i
}
}
return min(len(a), len(b))
}
// window returns up to 16 bytes of data starting a few bytes before at.
func window(data []byte, at int) []byte {
from := max(0, at-4)
return data[min(from, len(data)):min(at+12, len(data))]
}
+170
View File
@@ -0,0 +1,170 @@
package receipt_test
import (
"bytes"
"context"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
// FuzzBlocks lays out random boxes, rules and kv blocks on random printers
// and code pages, and checks that every line is exactly the block's width,
// no wider than the line, with the borders in the first and last columns,
// and that no control byte reaches the printer inside the text.
func FuzzBlocks(f *testing.F) {
f.Add(uint8(0), uint8(0), uint8(0), uint8(1), uint8(0), uint8(1), false, uint8(0), "Title", "Footer", "Some text that wraps", "key", "value")
f.Add(uint8(0x3C), uint8(1), uint8(9), uint8(2), uint8(1), uint8(3), true, uint8(12), "“A long title” — with folds…", "", "line\nline\ttab 🎉👨\u200D👩\u200D👧", "k", "")
f.Add(uint8(1), uint8(2), uint8(6), uint8(0), uint8(0), uint8(0), false, uint8(200), "", "", "Label", "", "")
f.Add(uint8(2), uint8(3), uint8(4), uint8(1), uint8(1), uint8(2), false, uint8(7), "", "", "", "A key that is long", "a value that wraps over several lines")
f.Add(uint8(0xF8), uint8(4), uint8(3), uint8(2), uint8(0), uint8(0), true, uint8(3), "\x1b@\x00", "\x07", "\x1bd\x05 text \x1dV", "\x0a", "\x09")
f.Fuzz(func(t *testing.T, kind, printerSel, style, size, font, padding uint8, fit bool, columns uint8,
title, footer, text, key, value string) {
el := fuzzBlock(kind, style, size, font, padding, fit, columns, title, footer, text, key, value)
job := receipt.Job{Elements: []receipt.Element{el}}
if job.Validate() != nil {
return
}
models := []string{"tm-t88", "tm-t20", "generic-58mm"}
codePages := []escpos.CodePage{escpos.CodePage437, escpos.CodePage850, escpos.CodePage858, escpos.CodePage1252}
profile, err := escpos.LookupProfile(models[int(printerSel)%len(models)])
if err != nil {
t.Fatal(err)
}
cp := codePages[int(printerSel/3)%len(codePages)]
override := 0
if printerSel&0x80 != 0 {
override = 30
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: cp, Columns: override,
MaxPixels: 1000, MaxHeight: 1000, MaxLines: 100_000,
}, &fakeFetcher{})
out, err := r.Render(context.Background(), job)
if err != nil {
t.Fatalf("Render: %v", err)
}
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("Preview: %v", err)
}
var lines []string
for _, l := range p.Lines {
if l.Kind == escpos.LineText {
lines = append(lines, l.Text)
}
}
if len(lines) == 0 {
t.Fatal("a block printed no lines")
}
lineDots := profile.DotsPerLine
if override > 0 {
lineDots = override * profile.FontAWidth
}
blockSize := max(el.Size, 1)
cols := lineDots / (profile.GlyphWidth(fontOf(el.Font)) * blockSize)
width := len([]rune(lines[0]))
for i, line := range lines {
n := len([]rune(line))
if n != width || n > cols {
t.Fatalf("line %d %q is %d wide; want %d like line 0, and at most %d", i, line, n, width, cols)
}
}
if el.Type == "box" {
checkBoxBorders(t, lines)
}
// No tab may reach the printer, and every line feed ends a line.
if bytes.IndexByte(out, '\t') >= 0 {
t.Errorf("stream has a tab: % X", out)
}
if n := bytes.Count(out, []byte{'\n'}); n != len(lines) {
t.Errorf("stream has %d line feeds for %d lines", n, len(lines))
}
})
}
func fontOf(name string) escpos.Font {
if strings.EqualFold(name, "b") {
return escpos.FontB
}
return escpos.FontA
}
// fuzzBlock builds a box, rule or kv element from the fuzzer's values. The
// low bits of kind pick the type; for a box, the others pick its children.
func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8, title, footer, text, key, value string) receipt.Element {
boxStyles := []string{"single", "double", "double-h", "double-v", "ascii"}
ruleStyles := []string{"single", "double", "light", "medium", "dark", "solid", "dashed", "dotted", "ascii"}
leaders := []string{".", "·", " ", "_", "-", "─"}
aligns := []string{"left", "center", "right"}
el := receipt.Element{Size: 1 + int(size)%3, Columns: int(columns)}
if font%2 == 1 {
el.Font = "b"
}
switch kind % 3 {
case 0:
el.Type = "box"
el.Style = boxStyles[int(style)%len(boxStyles)]
el.Title, el.Footer, el.Fit = title, footer, fit
el.Padding = intPtr(int(padding) % 4)
el.Align = aligns[int(style)%len(aligns)]
if style&0x10 != 0 {
el.TitleStyle = "capped"
}
children := kind >> 2
if children == 0 {
el.Text = text
if el.Text == "" {
el.Text = "x"
}
break
}
if children&1 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "text", Text: text, Align: aligns[int(padding)%3], Wrap: boolPtr(children&0x10 == 0)})
}
if children&2 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "rule", Text: key, Style: []string{"single", "double"}[int(style)%2], Align: aligns[int(size)%3]})
}
if children&4 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "kv", Leader: leaders[int(font)%len(leaders)], Pairs: []receipt.Pair{{Key: key + "k", Value: value}}})
}
if children&8 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "feed", Lines: 1 + int(padding)%3})
}
case 1:
el.Type = "rule"
el.Style = ruleStyles[int(style)%len(ruleStyles)]
el.Text = text
el.Align = aligns[int(padding)%3]
default:
el.Type = "kv"
el.Leader = leaders[int(style)%len(leaders)]
el.Pairs = []receipt.Pair{{Key: key + "k", Value: value}, {Key: title + "t", Value: text, Bold: fit}}
}
return el
}
// checkBoxBorders checks that each box line, after its centring margin,
// starts and ends with a border glyph.
func checkBoxBorders(t *testing.T, lines []string) {
t.Helper()
const (
left = "┌╔╒╓+│║|└╚╘╙├╞╟╠"
right = "┐╗╕╖+│║|┘╝╛╜┤╡╢╣"
)
margin := len(lines[0]) - len(strings.TrimLeft(lines[0], " "))
for i, line := range lines {
runes := []rune(line[margin:])
if line[:margin] != strings.Repeat(" ", margin) || len(runes) < 2 {
t.Fatalf("line %d %q does not share the box margin %d", i, line, margin)
}
if !strings.ContainsRune(left, runes[0]) || !strings.ContainsRune(right, runes[len(runes)-1]) {
t.Fatalf("line %d %q does not start and end with a border", i, line)
}
}
}
+145
View File
@@ -0,0 +1,145 @@
package receipt
import "uberbringer/internal/pkg/escpos"
// borders are the glyphs one box style draws with.
type borders struct {
topLeft, topRight, bottomLeft, bottomRight rune
horizontal, vertical rune
// capLeft and capRight close the top border around a capped title.
capLeft, capRight rune
// doubleH and doubleV give the weight of the lines, so that dividers
// and caps can join them.
doubleH, doubleV bool
ascii bool
}
var borderSets = map[boxStyle]borders{
boxSingle: {'┌', '┐', '└', '┘', '─', '│', '┤', '├', false, false, false},
boxDouble: {'╔', '╗', '╚', '╝', '═', '║', '╡', '╞', true, true, false},
boxDoubleH: {'╒', '╕', '╘', '╛', '═', '│', '╡', '╞', true, false, false},
boxDoubleV: {'╓', '╖', '╙', '╜', '─', '║', '┤', '├', false, true, false},
boxASCII: {'+', '+', '+', '+', '-', '|', '|', '|', false, false, true},
}
// borderFallback is the order in which styles are tried when the code page
// lacks a glyph of the style asked for. ascii prints everywhere.
var borderFallback = map[boxStyle][]boxStyle{
boxSingle: {boxSingle, boxASCII},
boxDouble: {boxDouble, boxSingle, boxASCII},
boxDoubleH: {boxDoubleH, boxDouble, boxSingle, boxASCII},
boxDoubleV: {boxDoubleV, boxDouble, boxSingle, boxASCII},
boxASCII: {boxASCII},
}
// bordersFor returns the first style in style's fallback chain that cp can
// print. Caps the code page lacks switch to the other vertical weight, so
// on cp850 a double box caps its title with ╣ ╠ instead of ╡ ╞.
func bordersFor(style boxStyle, cp escpos.CodePage) borders {
for _, s := range borderFallback[style] {
b := borderSets[s]
if !encodesAll(cp, b.topLeft, b.topRight, b.bottomLeft, b.bottomRight, b.horizontal, b.vertical) {
continue
}
if !b.ascii && !encodesAll(cp, b.capLeft, b.capRight) {
left, right := junction(true, b.doubleH)
if encodesAll(cp, left, right) {
b.capLeft, b.capRight = right, left
} else {
b.capLeft, b.capRight = b.vertical, b.vertical
}
}
return b
}
return borderSets[boxASCII]
}
// junction returns the glyphs where a horizontal line meets a vertical one
// from the right (├) and from the left (┤), for the given line weights.
func junction(verticalDouble, horizontalDouble bool) (left, right rune) {
switch {
case verticalDouble && horizontalDouble:
return '╠', '╣'
case verticalDouble:
return '╟', '╢'
case horizontalDouble:
return '╞', '╡'
}
return '├', '┤'
}
// divider returns the glyphs of a divider across a box with borders b: a
// double line when double is set, joined to both sides. A junction the code
// page lacks first switches to the other line weight, so on cp850 ╟─╢
// becomes ╠═╣ and ╞═╡ becomes ├─┤.
func (b borders) divider(double bool, cp escpos.CodePage) (left, horizontal, right rune) {
if !b.ascii {
for _, d := range []bool{double, !double} {
left, right := junction(b.doubleV, d)
horizontal := '─'
if d {
horizontal = '═'
}
if encodesAll(cp, left, horizontal, right) {
return left, horizontal, right
}
}
}
if double {
return '+', '=', '+'
}
return '+', '-', '+'
}
// rulePatterns are the fills of each rule style, best first; the pattern
// repeats across the line.
var rulePatterns = map[ruleStyle][]string{
ruleSingle: {"─", "-"},
ruleDouble: {"═", "="},
ruleLight: {"░", "#"},
ruleMedium: {"▒", "#"},
ruleDark: {"▓", "#"},
ruleSolid: {"█", "#"},
ruleDashed: {"- "},
ruleDotted: {"·", "."},
ruleASCII: {"-"},
}
// leaderFallbacks lists replacements for kv leaders a code page lacks.
var leaderFallbacks = map[string][]string{
"·": {"·", "."},
"─": {"─", "-"},
}
// rulePattern returns the fill of style that cp can print.
func rulePattern(style ruleStyle, cp escpos.CodePage) string {
return firstPrintable(rulePatterns[style], cp, "-")
}
// leaderFor returns leader, or its replacement when cp lacks it.
func leaderFor(leader string, cp escpos.CodePage) string {
if alternatives, ok := leaderFallbacks[leader]; ok {
return firstPrintable(alternatives, cp, ".")
}
return leader
}
func firstPrintable(candidates []string, cp escpos.CodePage, last string) string {
for _, c := range candidates {
if printable(c, cp) {
return c
}
}
return last
}
func encodesAll(cp escpos.CodePage, runes ...rune) bool {
for _, r := range runes {
if !cp.CanEncode(r) {
return false
}
}
return true
}
+152
View File
@@ -0,0 +1,152 @@
package receipt_test
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/blocks/*.txt from the current renderer")
// goldenCodePages are the code pages every block golden is rendered in, to
// cover the glyph fallbacks.
var goldenCodePages = []escpos.CodePage{escpos.CodePage437, escpos.CodePage850, escpos.CodePage1252}
// TestBlockGoldens previews each testdata/blocks/*.json job on a TM-T88 in
// every golden code page and compares the lines with NAME.CODEPAGE.txt.
// Run with -update to rewrite the .txt files, then review the diff.
func TestBlockGoldens(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "blocks", "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no jobs in testdata/blocks")
}
for _, path := range paths {
job := readJob(t, path)
for _, cp := range goldenCodePages {
name := strings.TrimSuffix(filepath.Base(path), ".json") + "." + cp.String()
t.Run(name, func(t *testing.T) {
got := previewText(t, newPreviewer(t, "tm-t88", cp), job)
golden := filepath.Join("testdata", "blocks", name+".txt")
if *update {
if err := os.WriteFile(golden, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("%v (run go test -run TestBlockGoldens -update)", err)
}
if got != string(want) {
t.Errorf("preview differs from %s:\n%s", golden, diffLines(string(want), got))
}
})
}
}
}
// TestExampleJobs keeps the jobs in examples/ valid: each previews on a
// TM-T88 in CP437 with nothing printed as '?'.
func TestExampleJobs(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("..", "..", "..", "examples", "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no jobs in examples/")
}
for _, path := range paths {
t.Run(filepath.Base(path), func(t *testing.T) {
p, err := newPreviewer(t, "tm-t88", escpos.CodePage437).Preview(context.Background(), readJob(t, path))
if err != nil {
t.Fatal(err)
}
if len(p.Warnings) > 0 {
t.Errorf("warnings: %q", p.Warnings)
}
})
}
}
func readJob(t *testing.T, path string) receipt.Job {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var job receipt.Job
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&job); err != nil {
t.Fatalf("%s: %v", path, err)
}
return job
}
func newPreviewer(t *testing.T, model string, cp escpos.CodePage) *receipt.Renderer {
t.Helper()
profile, err := escpos.LookupProfile(model)
if err != nil {
t.Fatal(err)
}
return receipt.NewRenderer(receipt.Options{
Profile: profile,
CodePage: cp,
MaxPixels: 10_000_000,
MaxHeight: 4000,
MaxLines: 2000,
}, &fakeFetcher{})
}
// previewText is the preview of job as text: its lines, then its warnings.
func previewText(t *testing.T, r *receipt.Renderer, job receipt.Job) string {
t.Helper()
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("Preview: %v", err)
}
var b strings.Builder
for _, l := range p.Lines {
b.WriteString(l.Text)
b.WriteByte('\n')
}
if len(p.Warnings) > 0 {
b.WriteString("=== warnings\n")
for _, w := range p.Warnings {
b.WriteString(w)
b.WriteByte('\n')
}
}
return b.String()
}
// diffLines shows the lines of got that differ from want.
func diffLines(want, got string) string {
w, g := strings.Split(want, "\n"), strings.Split(got, "\n")
var b strings.Builder
for i := range max(len(w), len(g)) {
var wl, gl string
if i < len(w) {
wl = w[i]
}
if i < len(g) {
gl = g[i]
}
if wl != gl {
fmt.Fprintf(&b, "line %d:\n want |%s|\n got |%s|\n", i+1, wl, gl)
}
}
return b.String()
}
+124 -20
View File
@@ -3,16 +3,25 @@
package receipt
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"strings"
"uberbringer/internal/pkg/escpos"
)
// Element types.
// ErrTrailingData is returned by DecodeJob for input with more after the
// job.
var ErrTrailingData = errors.New("trailing data after the job")
// Element types. Box, rule and kv are blocks: they are laid out to the
// paper width when the job is rendered.
const (
TypeText = "text"
TypeFeed = "feed"
@@ -21,12 +30,16 @@ const (
TypeImage = "image"
TypeRaw = "raw"
TypeCut = "cut"
TypeBox = "box"
TypeRule = "rule"
TypeKV = "kv"
)
// Job limits.
// Job limits. MaxElements counts the children of boxes too.
const (
MaxElements = 500
MaxCopies = 5
MaxPairs = 100
)
// Element defaults.
@@ -45,10 +58,13 @@ type Job struct {
Copies int `json:"copies,omitempty"`
}
// Element is one item on a receipt. Type selects which fields apply; fields
// that do not apply to the type are ignored. Width and Height mean character
// multipliers for text, module width and bar height for barcodes, and target
// width in dots for images.
// Element is one item on a receipt. Type selects which fields apply. On the
// blocks (box, rule and kv) and inside a box, a field that does not apply is
// an error; on the other types it is ignored, except for the block fields.
// Width and Height mean character multipliers for text, module width and
// bar height for barcodes, and target width in dots for images. A block's
// width is set by Columns, in characters of its own size and font, never by
// Width; without Columns a block spans the line.
type Element struct {
Type string `json:"type"`
@@ -83,6 +99,42 @@ type Element struct {
// Cut.
Mode string `json:"mode,omitempty"`
// Blocks. Style is the border or line style of a box or rule. Children
// are the body of a box, one level deep.
Children []Element `json:"children,omitempty"`
Title string `json:"title,omitempty"`
TitleStyle string `json:"title_style,omitempty"`
Footer string `json:"footer,omitempty"`
Style string `json:"style,omitempty"`
Padding *int `json:"padding,omitempty"`
Fit bool `json:"fit,omitempty"`
Columns int `json:"columns,omitempty"`
Pairs []Pair `json:"pairs,omitempty"`
Leader string `json:"leader,omitempty"`
}
// Pair is one row of a kv block: a key, a leader and a value.
type Pair struct {
Key string `json:"key"`
Value string `json:"value"`
Bold bool `json:"bold,omitempty"`
}
// DecodeJob strictly decodes one JSON job. An unknown field is an error, so
// that a typo fails loudly instead of being ignored, and so is anything
// after the job. It does not validate the job.
func DecodeJob(data []byte) (Job, error) {
var job Job
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&job); err != nil {
return Job{}, err
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return Job{}, ErrTrailingData
}
return job, nil
}
// ValidationError lists every problem found in a job.
@@ -99,19 +151,23 @@ func (e *ValidationError) Error() string {
// to the printer unless the entire receipt can be printed.
func (j Job) Validate() error {
var problems []string
switch {
children := 0
for _, el := range j.Elements {
children += len(el.Children)
}
switch total := len(j.Elements) + children; {
case len(j.Elements) == 0:
problems = append(problems, "elements: at least one element is required")
case len(j.Elements) > MaxElements:
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", len(j.Elements), MaxElements))
case total > MaxElements && children > 0:
problems = append(problems, fmt.Sprintf("elements: %d elements including %d box children, limit is %d", total, children, MaxElements))
case total > MaxElements:
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", total, MaxElements))
}
if j.Copies < 0 || j.Copies > MaxCopies {
problems = append(problems, fmt.Sprintf("copies must be 1-%d", MaxCopies))
}
for i, el := range j.Elements {
if err := el.validate(); err != nil {
problems = append(problems, fmt.Sprintf("elements[%d] (%s): %v", i, el.Type, err))
}
problems = append(problems, el.problems(fmt.Sprintf("elements[%d]", i), false)...)
}
if len(problems) > 0 {
return &ValidationError{Problems: problems}
@@ -123,11 +179,44 @@ func (j Job) copies() int {
return max(j.Copies, 1)
}
func (el Element) validate() error {
// problems returns every problem with el, and with its children when it is
// a box, each prefixed with its path, e.g. "elements[0].children[3] (qr): ".
func (el Element) problems(path string, inBox bool) []string {
prefix := fmt.Sprintf("%s (%s): ", path, el.Type)
var messages []string
for _, msg := range el.validate(inBox) {
messages = append(messages, prefix+msg)
}
if el.Type == TypeBox && !inBox {
for i, child := range el.Children {
messages = append(messages, child.problems(fmt.Sprintf("%s.children[%d]", path, i), true)...)
}
}
return messages
}
// validate checks el's own fields. inBox is set for the children of a box,
// which allow fewer types and fields.
func (el Element) validate(inBox bool) []string {
if inBox {
switch el.Type {
case TypeText, TypeFeed, TypeRule, TypeKV:
case TypeBox, TypeQR, TypeBarcode, TypeImage, TypeRaw, TypeCut:
return []string{"not allowed inside a box; place it after the box"}
case "":
return []string{"type is required"}
default:
return []string{fmt.Sprintf("unknown type %q (inside a box, want text, feed, rule or kv)", el.Type)}
}
}
problems := el.checkFields(inBox)
var err error
switch el.Type {
case TypeText:
_, err = el.textSpec()
if err == nil && inBox && el.Newline != nil && !*el.Newline {
err = fmt.Errorf("newline:false is not allowed inside a box")
}
case TypeFeed:
_, err = el.feedLines()
case TypeQR:
@@ -140,12 +229,22 @@ func (el Element) validate() error {
_, err = el.rawBytes()
case TypeCut:
_, err = el.cutMode()
case TypeBox:
_, err = el.boxSpec()
case TypeRule:
_, err = el.ruleSpec(inBox)
case TypeKV:
_, err = el.kvSpec()
problems = append(problems, el.pairProblems()...)
case "":
err = fmt.Errorf("type is required")
default:
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw or cut)", el.Type)
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule or kv)", el.Type)
}
return err
if err != nil {
problems = append(problems, err.Error())
}
return problems
}
type textSpec struct {
@@ -187,15 +286,20 @@ func (el Element) textSpec() (textSpec, error) {
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
switch el.Underline {
case 0, 1, 2:
s.underline = escpos.Underline(el.Underline)
default:
return s, fmt.Errorf("underline must be 0, 1 or 2")
if s.underline, err = parseUnderline(el.Underline); err != nil {
return s, err
}
return s, nil
}
func parseUnderline(n int) (escpos.Underline, error) {
switch n {
case 0, 1, 2:
return escpos.Underline(n), nil
}
return 0, fmt.Errorf("underline must be 0, 1 or 2")
}
func (el Element) feedLines() (uint8, error) {
switch {
case el.Lines == 0:
+162
View File
@@ -0,0 +1,162 @@
package receipt
import (
"strings"
"golang.org/x/text/unicode/norm"
"uberbringer/internal/pkg/escpos"
)
// zeroWidthJoiner joins emoji into one sequence, such as a family.
const zeroWidthJoiner = '\u200D'
// folds lists ASCII look-alikes for characters the code pages often lack,
// best first. A fold is used only when the code page cannot print the
// character itself, and only when it can print every rune of the fold.
var folds = map[rune][]string{
'“': {`"`},
'”': {`"`},
'„': {`"`},
'‘': {"'"},
'’': {"'"},
'–': {"-"},
'—': {"--"},
'…': {"..."},
'•': {"·", "."},
'→': {"->"},
'←': {"<-"},
'✓': {"√", "x"},
'✔': {"√", "x"},
'×': {"x"},
'€': {"EUR"},
'™': {"TM"},
'\u00A0': {" "},
}
// normalize prepares text for printing in cp, so that each rune of the
// result prints as one character and wrap can count columns in runes. It
// removes control characters, composes the text to NFC, folds characters
// the code page lacks to look-alikes, drops invisible selectors and
// joiners, and turns each emoji sequence and every other character cp
// cannot print into one '?'. It returns the text and the number of '?' it
// introduced.
func normalize(s string, cp escpos.CodePage) (string, int) {
s = sanitize(s)
if printable(s, cp) {
return s, 0
}
runes := []rune(norm.NFC.String(s))
var (
b strings.Builder
unknown int
)
b.Grow(len(s))
for i := 0; i < len(runes); i++ {
r := runes[i]
switch {
case r == '\n' || r == '\t' || cp.CanEncode(r):
b.WriteRune(r)
case invisible(r):
default:
if fold, ok := foldFor(r, cp); ok {
b.WriteString(fold)
continue
}
if pictographic(r) {
i = emojiSequenceEnd(runes, i)
}
b.WriteByte('?')
unknown++
}
}
return b.String(), unknown
}
// normalizeLine is normalize for text that must stay on one line, such as
// a title: newlines and tabs become spaces.
func normalizeLine(s string, cp escpos.CodePage) (string, int) {
s, unknown := normalize(s, cp)
return strings.Map(func(r rune) rune {
if r == '\n' || r == '\t' {
return ' '
}
return r
}, s), unknown
}
// printable reports whether cp prints every rune of s as itself.
func printable(s string, cp escpos.CodePage) bool {
for _, r := range s {
if r != '\n' && r != '\t' && !cp.CanEncode(r) {
return false
}
}
return true
}
func foldFor(r rune, cp escpos.CodePage) (string, bool) {
for _, fold := range folds[r] {
if printable(fold, cp) {
return fold, true
}
}
return "", false
}
// invisible reports whether r only changes how the characters around it
// look: variation selectors, zero-width spaces and joiners, emoji skin
// tones, tag characters and the keycap mark.
func invisible(r rune) bool {
switch {
case r == '\uFE0E' || r == '\uFE0F':
case r >= '\u200B' && r <= zeroWidthJoiner:
case r >= 0x1F3FB && r <= 0x1F3FF:
case r >= 0xE0000 && r <= 0xE007F:
case r == '\u20E3':
default:
return false
}
return true
}
// pictographic reports whether r is in a block of symbols that are drawn
// as emoji.
func pictographic(r rune) bool {
switch {
case r >= 0x1F000 && r <= 0x1FAFF:
case r >= 0x2190 && r <= 0x21FF:
case r >= 0x2300 && r <= 0x23FF:
case r >= 0x25A0 && r <= 0x27BF:
case r >= 0x2B00 && r <= 0x2BFF:
case r == 0x203C || r == 0x2049 || r == 0x3030 || r == 0x303D || r == 0x3297 || r == 0x3299:
default:
return false
}
return true
}
func regionalIndicator(r rune) bool {
return r >= 0x1F1E6 && r <= 0x1F1FF
}
// emojiSequenceEnd returns the index of the last rune of the emoji sequence
// that starts at runes[i]: the emoji with its selectors and modifiers, any
// emoji joined to it with a zero-width joiner, or the second half of a flag.
func emojiSequenceEnd(runes []rune, i int) int {
if regionalIndicator(runes[i]) && i+1 < len(runes) && regionalIndicator(runes[i+1]) {
return i + 1
}
for i+1 < len(runes) {
next := runes[i+1]
switch {
case next == zeroWidthJoiner && i+2 < len(runes) && pictographic(runes[i+2]):
i += 2
case invisible(next) && next != zeroWidthJoiner:
i++
default:
return i
}
}
return i
}
+90
View File
@@ -0,0 +1,90 @@
package receipt
import (
"reflect"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
)
func TestNormalize(t *testing.T) {
cp437, cp850, cp858, cp1252 := escpos.CodePage437, escpos.CodePage850, escpos.CodePage858, escpos.CodePage1252
tests := []struct {
name string
cp escpos.CodePage
in string
want string
unknown int
}{
{"decomposed é becomes one rune", cp437, "cafe\u0301", "café", 0},
{"decomposed ü too", cp850, "u\u0308ber", "über", 0},
{"smart quotes", cp437, "“double” „low” ‘single’", `"double" "low" 'single'`, 0},
{"dashes", cp437, "a–b—c", "a-b--c", 0},
{"ellipsis", cp437, "wait…", "wait...", 0},
{"bullet", cp437, "• item", "· item", 0},
{"arrows", cp437, "a → b ← c", "a -> b <- c", 0},
{"check marks", cp437, "✓ ✔", "√ √", 0},
{"check marks without √", cp850, "✓ ✔", "x x", 0},
{"times", cp437, "3×", "3x", 0},
{"times kept where it prints", cp850, "3×", "3×", 0},
{"euro", cp437, "5 €", "5 EUR", 0},
{"euro kept on cp858", cp858, "5 €", "5 €", 0},
{"trademark", cp437, "Brand™", "BrandTM", 0},
{"cp1252 keeps its own typography", cp1252, "“q” – — … • € ™", "“q” – — … • € ™", 0},
{"one emoji", cp437, "a 🎉 b", "a ? b", 1},
{"skin tone", cp437, "👍🏽", "?", 1},
{"zero-width joiner sequence", cp437, "👨\u200D👩\u200D👧 family", "? family", 1},
{"flags pair up", cp437, "🇩🇪🇫🇷", "??", 2},
{"tag sequence", cp437, "🏴\U000E0067\U000E0062\U000E0065\U000E006E\U000E0067\U000E007F!", "?!", 1},
{"variation selector after an emoji", cp437, "⚠\uFE0F careful", "? careful", 1},
{"keycap", cp437, "1\uFE0F\u20E3 first", "1 first", 0},
{"VS16 after a printable character", cp437, "x\uFE0F", "x", 0},
{"zero-width characters dropped", cp437, "a\u200Bb\u200Cc\u200Dd", "abcd", 0},
{"other missing characters", cp437, "漢字 ¤", "?? ?", 3},
{"controls stripped", cp437, "a\x1b@b\r\n\tc\x00", "a@b\n\tc", 0},
{"two emoji are two", cp437, "🎉🎉", "??", 2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, unknown := normalize(tt.in, tt.cp)
if got != tt.want || unknown != tt.unknown {
t.Errorf("normalize(%q, %s) = %q, %d; want %q, %d", tt.in, tt.cp, got, unknown, tt.want, tt.unknown)
}
for _, r := range got {
if r != '\n' && r != '\t' && !tt.cp.CanEncode(r) {
t.Errorf("result %q has %q, which %s cannot print", got, r, tt.cp)
}
}
})
}
}
func TestNormalizeLeavesPrintableTextAlone(t *testing.T) {
samples := map[escpos.CodePage]string{
escpos.CodePage437: "┌─┐│└┘ ╔═╗ ░▒▓█ £ é ü Ω ·√° \u00A0 plain ASCII ~!@#",
escpos.CodePage850: "╔═╗ ┌─┐ ░▒▓ × © ® Ø ß £ àéîõü \u00A0",
escpos.CodePage858: "€ ╔═╗ ß",
escpos.CodePage1252: "“q” ‘q’ – — … • € ™ × é",
}
for cp, s := range samples {
if got, unknown := normalize(s, cp); got != s || unknown != 0 {
t.Errorf("%s: normalize(%q) = %q, %d", cp, s, got, unknown)
}
}
}
func TestNormalizeRunsBeforeWrap(t *testing.T) {
// The ellipsis takes three columns, so "word…" no longer fits in 6.
text, _ := normalize("ab word…", escpos.CodePage437)
if got := wrap(text, 6, 6); !reflect.DeepEqual(got, []string{"ab", "word..", "."}) {
t.Errorf("wrap = %q", got)
}
line, _ := normalizeLine("a\nb\tc", escpos.CodePage437)
if line != "a b c" {
t.Errorf("normalizeLine = %q", line)
}
if strings.ContainsAny(line, "\n\t") {
t.Error("normalizeLine kept a newline or tab")
}
}
+137
View File
@@ -0,0 +1,137 @@
package receipt
import (
"context"
"fmt"
"image"
"image/color"
"net/url"
"path"
"uberbringer/internal/pkg/escpos"
)
// Preview is what a job prints, read back from its command stream.
type Preview struct {
// Columns is the number of Font A characters on a line.
Columns int
CodePage escpos.CodePage
// LineCount is the number of lines the job prints, all copies counted:
// text lines, fed lines, and one for each QR code, barcode and image.
// Options.MaxLines limits it.
LineCount int
// Lines are the printed lines. Image lines name the image's source
// instead of its size, since a preview loads no images.
Lines []escpos.PreviewLine
// Warnings name the elements with characters the code page lacks and
// images that would fail to print.
Warnings []string
}
// Preview validates and renders job as Render does, then reads the command
// stream back with escpos.Interpret, so that it shows what the bytes say. It
// neither fetches nor decodes images: each prints as a blank placeholder. A
// job over Options.MaxLines fails with a *LineLimitError, as it does when it
// prints.
func (r *Renderer) Preview(ctx context.Context, job Job) (Preview, error) {
if err := job.Validate(); err != nil {
return Preview{}, err
}
if err := ctx.Err(); err != nil {
return Preview{}, err
}
images, imageWarnings := r.placeholderImages(job)
out, err := r.render(job, images)
if err != nil {
return Preview{}, err
}
lines, err := escpos.Interpret(out.stream, r.options.CodePage, r.options.Profile, out.raw)
if err != nil {
return Preview{}, fmt.Errorf("reading back the rendered receipt: %w", err)
}
labelImages(lines, job)
var warnings []string
for i := range job.Elements {
if w, ok := imageWarnings[i]; ok {
warnings = append(warnings, w)
}
if n := out.unknown[i]; n > 0 {
noun := "characters"
if n == 1 {
noun = "character"
}
warnings = append(warnings, fmt.Sprintf("elements[%d]: %d %s not in %s printed as ?", i, n, noun, r.options.CodePage))
}
}
return Preview{
Columns: r.textLineDots() / r.options.Profile.FontAWidth,
CodePage: r.options.CodePage,
LineCount: out.lines,
Lines: lines,
Warnings: warnings,
}, nil
}
// placeholderImages returns a blank one-row raster across the paper for
// every image element, and a warning for each image that would fail to
// print because it is wider than the paper.
func (r *Renderer) placeholderImages(job Job) (map[int]*image.Paletted, map[int]string) {
paper := r.options.Profile.DotsPerLine
images := make(map[int]*image.Paletted)
warnings := make(map[int]string)
for i, el := range job.Elements {
if el.Type != TypeImage {
continue
}
if el.Width > paper {
warnings[i] = fmt.Sprintf("elements[%d] (image): width %d is wider than the %d-dot paper, so the job would fail", i, el.Width, paper)
}
images[i] = image.NewPaletted(image.Rect(0, 0, paper, 1), color.Palette{color.White, color.Black})
}
return images, warnings
}
// labelImages replaces the size of each image placeholder with the source
// of its element, in order, copy after copy.
func labelImages(lines []escpos.PreviewLine, job Job) {
var sources []Element
for _, el := range job.Elements {
if el.Type == TypeImage {
sources = append(sources, el)
}
}
n := 0
for i := range lines {
if lines[i].Kind != escpos.LineImage || len(sources) == 0 {
continue
}
el := sources[n%len(sources)]
n++
name, data := "base64", "base64"
if el.URL != "" {
name, data = imageName(el.URL), el.URL
}
lines[i].Text = fmt.Sprintf("[image: %s]", name)
if el.Width > 0 {
lines[i].Text = fmt.Sprintf("[image %d dots: %s]", el.Width, name)
}
lines[i].Data = data
}
}
// imageName is the last path segment of an image URL, or its host.
func imageName(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return raw
}
if name := path.Base(u.Path); name != "." && name != "/" {
return name
}
return u.Host
}
+25 -34
View File
@@ -26,14 +26,19 @@ func (f *fakeFetcher) Fetch(_ context.Context, url string) ([]byte, error) {
return f.data, f.err
}
func newRenderer(t *testing.T, fetcher receipt.Fetcher) *receipt.Renderer {
func tmT20(t *testing.T) escpos.Profile {
t.Helper()
profile, err := escpos.LookupProfile("tm-t20")
if err != nil {
t.Fatal(err)
}
return profile
}
func newRenderer(t *testing.T, fetcher receipt.Fetcher) *receipt.Renderer {
t.Helper()
return receipt.NewRenderer(receipt.Options{
Profile: profile,
Profile: tmT20(t),
CodePage: escpos.CodePage437,
MaxPixels: 10_000_000,
MaxHeight: 4000,
@@ -75,39 +80,21 @@ func render(t *testing.T, job receipt.Job) []byte {
return out
}
// printedLines returns the text the printer would print between line feeds,
// with ESC/POS commands removed. It understands only the commands the
// renderer emits for text jobs.
// printedLines returns the text lines a TM-T20 prints for out, read back
// with escpos.Interpret. Placeholders such as cuts are left out.
func printedLines(t *testing.T, out []byte) []string {
t.Helper()
var lines []string
var cur []byte
for i := 0; i < len(out); i++ {
switch c := out[i]; c {
case 0x1B: // ESC x n, or ESC @ / ESC 2
switch out[i+1] {
case '@', '2':
i++
default:
i += 2
}
case 0x1D: // GS x n, or GS V m n
if out[i+1] == 'V' {
i += 3
} else {
i += 2
}
case 0x0A:
lines = append(lines, string(cur))
cur = nil
default:
cur = append(cur, c)
lines, err := escpos.Interpret(out, escpos.CodePage437, tmT20(t), nil)
if err != nil {
t.Fatalf("Interpret: %v", err)
}
var texts []string
for _, l := range lines {
if l.Kind == escpos.LineText {
texts = append(texts, l.Text)
}
}
if len(cur) > 0 {
lines = append(lines, string(cur))
}
return lines
return texts
}
func TestRenderTextJob(t *testing.T) {
@@ -167,7 +154,7 @@ func TestRenderInlineTextContinuesLine(t *testing.T) {
{Type: "text", Text: "Total: ", Newline: boolPtr(false)},
{Type: "text", Text: "£5.00", Bold: true},
}})
if got := printedLines(t, out); len(got) != 1 || got[0] != "Total: \x9C5.00" {
if got := printedLines(t, out); len(got) != 1 || got[0] != "Total: £5.00" {
t.Errorf("printed %q, want one line", got)
}
}
@@ -188,8 +175,12 @@ func TestRenderInlineMixedSizesWraps(t *testing.T) {
func TestRenderNoWrap(t *testing.T) {
long := strings.Repeat("y", 60)
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: long, Wrap: boolPtr(false)}}})
if got := printedLines(t, out); len(got) != 1 || got[0] != long {
t.Errorf("printed %q, want the text untouched", got)
if !bytes.Contains(out, []byte(long+"\n")) {
t.Error("the renderer must send unwrapped text untouched")
}
// The printer wraps it at its own edge, 48 columns on a TM-T20.
if got := printedLines(t, out); len(got) != 2 || got[0] != long[:48] || got[1] != long[48:] {
t.Errorf("printed %q, want 48 and 12 characters", got)
}
}
+199 -17
View File
@@ -26,13 +26,33 @@ type Options struct {
CodePage escpos.CodePage
// Columns, when positive, overrides the Font A characters per line used
// for word wrapping.
// for word wrapping and block widths.
Columns int
// MaxPixels caps decoded image size; MaxHeight caps printed image height
// in dots.
MaxPixels int
MaxHeight int
// MaxLines, when positive, fails a job that would print more lines,
// all copies counted. It is a backstop against runaway text.
MaxLines int
// BoxLineSpacing, when positive, is the line spacing in motion units
// (ESC 3) used while a box prints, to close the gaps in its vertical
// borders. Zero keeps the printer's default spacing.
BoxLineSpacing int
}
// LineLimitError is returned for a job that would print more lines than
// Options.MaxLines allows.
type LineLimitError struct {
Lines, Limit int
}
// Error implements error.
func (e *LineLimitError) Error() string {
return fmt.Sprintf("receipt would print %d lines, limit is %d", e.Lines, e.Limit)
}
// Renderer turns jobs into ESC/POS command streams. It is safe for concurrent
@@ -53,6 +73,9 @@ func NewRenderer(options Options, fetcher Fetcher) *Renderer {
if options.MaxPixels <= 0 || options.MaxHeight <= 0 {
panic("receipt.NewRenderer: image limits must be positive")
}
if options.MaxLines < 0 || options.BoxLineSpacing < 0 || options.BoxLineSpacing > escpos.MaxLineSpacing {
panic("receipt.NewRenderer: MaxLines must not be negative and BoxLineSpacing must be 0-255")
}
return &Renderer{options: options, fetcher: fetcher}
}
@@ -67,26 +90,68 @@ func (r *Renderer) Render(ctx context.Context, job Job) ([]byte, error) {
if err != nil {
return nil, err
}
out, err := r.render(job, images)
if err != nil {
return nil, err
}
return out.stream, nil
}
// rendered is a job's command stream and what Preview needs to read it back.
type rendered struct {
stream []byte
// raw holds the byte range of every raw element in stream.
raw []escpos.Span
// lines is the number of lines the stream prints.
lines int
// unknown counts, by element index, the characters printed as '?'.
unknown map[int]int
}
// render lays out a validated job with its images loaded.
func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, error) {
var body escpos.Builder
p := printer{b: &body, lineDots: r.textLineDots(), profile: r.options.Profile, codePage: r.options.CodePage}
p := printer{
b: &body,
lineDots: r.textLineDots(),
profile: r.options.Profile,
codePage: r.options.CodePage,
lineSpacing: r.options.BoxLineSpacing,
}
unknown := make(map[int]int)
for i, el := range job.Elements {
if err := p.element(el, images[i]); err != nil {
return nil, fmt.Errorf("rendering elements[%d] (%s): %w", i, el.Type, err)
return rendered{}, fmt.Errorf("rendering elements[%d] (%s): %w", i, el.Type, err)
}
if p.unknown > 0 {
unknown[i] = p.unknown
p.unknown = 0
}
}
p.endLine()
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
body.Cut(escpos.CutPartial, 0)
}
lines := p.lines * job.copies()
if limit := r.options.MaxLines; limit > 0 && lines > limit {
return rendered{}, &LineLimitError{Lines: lines, Limit: limit}
}
var out escpos.Builder
out.Initialize()
out.SelectCodePage(r.options.CodePage)
var spans []escpos.Span
for range job.copies() {
offset := out.Len()
for _, s := range p.raw {
spans = append(spans, escpos.Span{From: s.From + offset, To: s.To + offset})
}
out.Raw(body.Bytes())
}
return bytes.Clone(out.Bytes()), nil
return rendered{stream: bytes.Clone(out.Bytes()), raw: spans, lines: lines, unknown: unknown}, nil
}
// textLineDots is the line width used for text layout.
@@ -159,23 +224,37 @@ func (r *Renderer) loadImage(ctx context.Context, el Element) (*image.Paletted,
// printer writes elements to a Builder while tracking the horizontal print
// position, in dots, so inline text can continue and wrap across elements.
type printer struct {
b *escpos.Builder
lineDots int
profile escpos.Profile
codePage escpos.CodePage
x int
b *escpos.Builder
lineDots int
profile escpos.Profile
codePage escpos.CodePage
lineSpacing int
x int
// lines counts printed lines: text lines, fed lines, and one for each
// QR code, barcode and image.
lines int
// unknown counts the characters of the current element printed as '?'.
unknown int
// raw holds the byte range of each raw element in the Builder.
raw []escpos.Span
}
func (p *printer) element(el Element, img *image.Paletted) error {
switch el.Type {
case TypeText:
return p.text(el)
case TypeBox, TypeRule, TypeKV:
return p.block(el)
case TypeFeed:
lines, err := el.feedLines()
if err != nil {
return err
}
p.b.Feed(lines)
p.lines += int(lines)
p.x = 0
case TypeQR:
spec, err := el.qrSpec()
@@ -184,6 +263,7 @@ func (p *printer) element(el Element, img *image.Paletted) error {
}
p.endLine()
p.b.Justify(spec.align)
p.lines++
return p.b.QRCode([]byte(el.Data), spec.size, spec.correction)
case TypeBarcode:
spec, err := el.barcodeSpec()
@@ -197,18 +277,22 @@ func (p *printer) element(el Element, img *image.Paletted) error {
return err
}
p.b.BarcodeHRI(spec.hri)
p.lines++
return p.b.Barcode(spec.symbology, el.Data)
case TypeImage:
p.endLine()
// Alignment is baked into the image; see Renderer.loadImage.
p.b.Justify(escpos.JustifyLeft)
p.lines++
return p.b.RasterImage(img)
case TypeRaw:
data, err := el.rawBytes()
if err != nil {
return err
}
from := p.b.Len()
p.b.Raw(data)
p.raw = append(p.raw, escpos.Span{From: from, To: p.b.Len()})
// The position after arbitrary bytes is unknown; assume a fresh line.
p.x = 0
case TypeCut:
@@ -240,28 +324,33 @@ func (p *printer) text(el Element) error {
p.b.Underline(spec.underline)
p.b.Reverse(spec.invert)
text := sanitize(el.Text)
text, unknown := normalize(el.Text, p.codePage)
p.unknown += unknown
if spec.wrap {
text = expandTabs(text, p.x/glyph)
lines := wrap(text, (p.lineDots-p.x)/glyph, p.lineDots/glyph)
for i, line := range lines {
if i > 0 {
p.b.LineFeed()
p.x = 0
p.lineFeed()
}
p.b.Text(p.codePage.Encode(line))
p.x += utf8.RuneCountInString(line) * glyph
}
} else {
p.b.Text(p.codePage.Encode(text))
p.lines += strings.Count(text, "\n")
p.advance(text, glyph)
}
if spec.newline {
p.b.LineFeed()
p.x = 0
p.lineFeed()
}
// Reset styles so they cannot leak into barcodes, QR codes or raw data.
return p.resetStyle()
}
// resetStyle restores plain Font A at scale 1, so styles cannot leak into
// barcodes, QR codes or raw data.
func (p *printer) resetStyle() error {
p.b.Bold(false)
p.b.Underline(escpos.UnderlineNone)
p.b.Reverse(false)
@@ -272,6 +361,100 @@ func (p *printer) text(el Element) error {
return nil
}
// block lays out a box, rule or kv element and prints it line by line,
// each line left-justified and exactly as wide as the layout made it.
func (p *printer) block(el Element) error {
lo := layout{cp: p.codePage}
var (
lines []blockLine
size int
font escpos.Font
box bool
)
switch el.Type {
case TypeBox:
spec, err := el.boxSpec()
if err != nil {
return err
}
size, font, box = spec.size, spec.font, true
lines = lo.box(el, spec, p.blockColumns(font, size))
case TypeRule:
spec, err := el.ruleSpec(false)
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.rule(el, spec, p.blockColumns(font, size))
default:
spec, err := el.kvSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.kv(el, spec, p.blockColumns(font, size))
}
p.unknown += lo.unknown
p.endLine()
spaced := box && p.lineSpacing > 0
if spaced {
p.b.LineSpacing(uint8(p.lineSpacing))
}
p.b.Justify(escpos.JustifyLeft)
p.b.Font(font)
if err := p.b.Size(size, size); err != nil {
return err
}
var current textStyle
p.b.Bold(false)
p.b.Underline(escpos.UnderlineNone)
p.b.Reverse(false)
for _, line := range lines {
for _, r := range line {
if r.text == "" {
continue
}
p.changeStyle(current, r.style)
current = r.style
p.b.Text(p.codePage.Encode(r.text))
}
p.lineFeed()
}
if err := p.resetStyle(); err != nil {
return err
}
if spaced {
p.b.DefaultLineSpacing()
}
return nil
}
// blockColumns is how many characters of font at size fit on a text line.
func (p *printer) blockColumns(font escpos.Font, size int) int {
return max(p.lineDots/(p.profile.GlyphWidth(font)*size), 1)
}
// changeStyle sends the commands that turn style from into style to.
func (p *printer) changeStyle(from, to textStyle) {
if from.bold != to.bold {
p.b.Bold(to.bold)
}
if from.underline != to.underline {
p.b.Underline(to.underline)
}
if from.invert != to.invert {
p.b.Reverse(to.invert)
}
}
// lineFeed ends the current line.
func (p *printer) lineFeed() {
p.b.LineFeed()
p.lines++
p.x = 0
}
// advance updates the position after unwrapped text, which the printer wraps
// by itself when it overflows.
func (p *printer) advance(text string, glyph int) {
@@ -289,7 +472,6 @@ func (p *printer) advance(text string, glyph int) {
// the left margin.
func (p *printer) endLine() {
if p.x > 0 {
p.b.LineFeed()
p.x = 0
p.lineFeed()
}
}
@@ -0,0 +1,15 @@
inline text before a box
+- Children -----------------------------+
| Centred by the box. |
| Left by its own align. |
| Bold and right. |
| |
| |
| Unwrapped text is split at the content |
| width instead of at spaces. |
| Tabs line up from the content edge. |
| Newline true is allowed. |
+----------------------------------------+
After the box, text continues at the left
margin.
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,15 @@
inline text before a box
┌─ Children ─────────────────────────────┐
│ Centred by the box. │
│ Left by its own align. │
│ Bold and right. │
│ │
│ │
│ Unwrapped text is split at the content │
│ width instead of at spaces. │
│ Tabs line up from the content edge. │
│ Newline true is allowed. │
└────────────────────────────────────────┘
After the box, text continues at the left
margin.
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,15 @@
inline text before a box
┌─ Children ─────────────────────────────┐
│ Centred by the box. │
│ Left by its own align. │
│ Bold and right. │
│ │
│ │
│ Unwrapped text is split at the content │
│ width instead of at spaces. │
│ Tabs line up from the content edge. │
│ Newline true is allowed. │
└────────────────────────────────────────┘
After the box, text continues at the left
margin.
- - - - - - - partial cut - - - - - - - -
+13
View File
@@ -0,0 +1,13 @@
{"elements": [
{"type": "text", "text": "inline text before a box ", "newline": false},
{"type": "box", "title": "Children", "align": "center", "children": [
{"type": "text", "text": "Centred by the box."},
{"type": "text", "text": "Left by its own align.", "align": "left"},
{"type": "text", "text": "Bold and right.", "bold": true, "align": "right"},
{"type": "feed", "lines": 2},
{"type": "text", "text": "Unwrapped text is split at the content width instead of at spaces.", "wrap": false, "align": "left"},
{"type": "text", "text": "Tabs\tline up\tfrom the content edge.", "align": "left"},
{"type": "text", "text": "Newline true is allowed.", "newline": true}
]},
{"type": "text", "text": "After the box, text continues at the left margin."}
]}
+52
View File
@@ -0,0 +1,52 @@
+-----+
| fit |
+-----+
+- A title longer than the text -+
| short |
+--------------------------------+
+--------------------------+
| short |
+- a footer that is long --+
+-| capped |-+
| x |
+------------+
+---------------------------------------+
| A fit box with more text than fits on |
| one line wraps at the full width. |
+---------------------------------------+
+--------------+
|Line one |
|is longer than|
|line three |
+--------------+
+---------------------+
| Fit ............ kv |
+-- a divider label --+
| |
+---------------------+
+- columns 20 -----+
| A fixed width, |
| centred on the |
| paper. |
+------------------+
+-------------------+
| Odd columns |
| centre with the |
| extra space on |
| the right. |
+-------------------+
+- columns 200 --------------------------+
| Clamped to the paper. |
+----------------------------------------+
+----------------------+
| fit inside a columns |
| limit that is |
| narrower than the |
| text |
+----------------------+
+-+
|x|
|y|
|z|
+-+
- - - - - - - partial cut - - - - - - - -
+52
View File
@@ -0,0 +1,52 @@
┌─────┐
│ fit │
└─────┘
┌─ A title longer than the text ─┐
│ short │
└────────────────────────────────┘
┌──────────────────────────┐
│ short │
└─ a footer that is long ──┘
╔═╡ capped ╞═╗
║ x ║
╚════════════╝
┌───────────────────────────────────────┐
│ A fit box with more text than fits on │
│ one line wraps at the full width. │
└───────────────────────────────────────┘
┌──────────────┐
│Line one │
│is longer than│
│line three │
└──────────────┘
┌─────────────────────┐
│ Fit ............ kv │
├── a divider label ──┤
│ │
└─────────────────────┘
┌─ columns 20 ─────┐
│ A fixed width, │
│ centred on the │
│ paper. │
└──────────────────┘
┌───────────────────┐
│ Odd columns │
│ centre with the │
│ extra space on │
│ the right. │
└───────────────────┘
┌─ columns 200 ──────────────────────────┐
│ Clamped to the paper. │
└────────────────────────────────────────┘
┌──────────────────────┐
│ fit inside a columns │
│ limit that is │
│ narrower than the │
│ text │
└──────────────────────┘
┌─┐
│x│
│y│
│z│
└─┘
- - - - - - - partial cut - - - - - - - -
+52
View File
@@ -0,0 +1,52 @@
┌─────┐
│ fit │
└─────┘
┌─ A title longer than the text ─┐
│ short │
└────────────────────────────────┘
┌──────────────────────────┐
│ short │
└─ a footer that is long ──┘
╔═╣ capped ╠═╗
║ x ║
╚════════════╝
┌───────────────────────────────────────┐
│ A fit box with more text than fits on │
│ one line wraps at the full width. │
└───────────────────────────────────────┘
┌──────────────┐
│Line one │
│is longer than│
│line three │
└──────────────┘
┌─────────────────────┐
│ Fit ............ kv │
├── a divider label ──┤
│ │
└─────────────────────┘
┌─ columns 20 ─────┐
│ A fixed width, │
│ centred on the │
│ paper. │
└──────────────────┘
┌───────────────────┐
│ Odd columns │
│ centre with the │
│ extra space on │
│ the right. │
└───────────────────┘
┌─ columns 200 ──────────────────────────┐
│ Clamped to the paper. │
└────────────────────────────────────────┘
┌──────────────────────┐
│ fit inside a columns │
│ limit that is │
│ narrower than the │
│ text │
└──────────────────────┘
┌─┐
│x│
│y│
│z│
└─┘
- - - - - - - partial cut - - - - - - - -
+18
View File
@@ -0,0 +1,18 @@
{"elements": [
{"type": "box", "fit": true, "text": "fit"},
{"type": "box", "fit": true, "title": "A title longer than the text", "text": "short"},
{"type": "box", "fit": true, "footer": "a footer that is long", "text": "short"},
{"type": "box", "fit": true, "style": "double", "title": "capped", "title_style": "capped", "text": "x"},
{"type": "box", "fit": true, "text": "A fit box with more text than fits on one line wraps at the full width."},
{"type": "box", "fit": true, "padding": 0, "text": "Line one\nis longer than\nline three"},
{"type": "box", "fit": true, "children": [
{"type": "kv", "pairs": [{"key": "Fit", "value": "kv"}]},
{"type": "rule", "text": "a divider label"},
{"type": "feed"}
]},
{"type": "box", "columns": 20, "title": "columns 20", "text": "A fixed width, centred on the paper."},
{"type": "box", "columns": 21, "text": "Odd columns centre with the extra space on the right."},
{"type": "box", "columns": 200, "title": "columns 200", "text": "Clamped to the paper."},
{"type": "box", "columns": 24, "fit": true, "text": "fit inside a columns limit that is narrower than the text"},
{"type": "box", "columns": 2, "padding": 3, "text": "xyz"}
]}
@@ -0,0 +1,16 @@
+- padding 0 ----------------------------+
|Text runs right up to the borders when |
|the padding is zero. |
+----------------------------------------+
+- padding 1 ----------------------------+
| One space each side is the default |
| padding. |
+----------------------------------------+
+- padding 2 ----------------------------+
| Two spaces each side. |
+----------------------------------------+
+- padding 3 ----------------------------+
| Three spaces each side, the most |
| there is. |
+----------------------------------------+
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,16 @@
┌─ padding 0 ────────────────────────────┐
│Text runs right up to the borders when │
│the padding is zero. │
└────────────────────────────────────────┘
┌─ padding 1 ────────────────────────────┐
│ One space each side is the default │
│ padding. │
└────────────────────────────────────────┘
┌─ padding 2 ────────────────────────────┐
│ Two spaces each side. │
└────────────────────────────────────────┘
╔═ padding 3 ════════════════════════════╗
║ Three spaces each side, the most ║
║ there is. ║
╚════════════════════════════════════════╝
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,16 @@
┌─ padding 0 ────────────────────────────┐
│Text runs right up to the borders when │
│the padding is zero. │
└────────────────────────────────────────┘
┌─ padding 1 ────────────────────────────┐
│ One space each side is the default │
│ padding. │
└────────────────────────────────────────┘
┌─ padding 2 ────────────────────────────┐
│ Two spaces each side. │
└────────────────────────────────────────┘
╔═ padding 3 ════════════════════════════╗
║ Three spaces each side, the most ║
║ there is. ║
╚════════════════════════════════════════╝
- - - - - - - partial cut - - - - - - - -
+6
View File
@@ -0,0 +1,6 @@
{"elements": [
{"type": "box", "padding": 0, "title": "padding 0", "text": "Text runs right up to the borders when the padding is zero."},
{"type": "box", "padding": 1, "title": "padding 1", "text": "One space each side is the default padding."},
{"type": "box", "padding": 2, "title": "padding 2", "text": "Two spaces each side.", "align": "center"},
{"type": "box", "padding": 3, "style": "double", "title": "padding 3", "text": "Three spaces each side, the most there is.", "align": "right"}
]}
@@ -0,0 +1,22 @@
+- size 1 -------------------------------+
| Forty-two columns of Font A. |
+----------------------------------- a --+
+- size 2 ----------+
| Twenty-one |
| columns. |
+-------------- a --+
+- size 3 ---+
| Fourteen |
| columns. |
+------- a --+
+- size 1 font b --------------------------------------+
| Fifty-six columns of Font B on the same paper. |
+------------------------------------------------- b --+
+- size 2 font b ----------+
| Twenty-eight columns. |
+--------------------- b --+
+- size 3 b -----+
| Eighteen |
| columns. |
+----------- b --+
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,22 @@
┌─ size 1 ───────────────────────────────┐
│ Forty-two columns of Font A. │
└─────────────────────────────────── a ──┘
┌─ size 2 ──────────┐
│ Twenty-one │
│ columns. │
└────────────── a ──┘
╔═ size 3 ═══╗
║ Fourteen ║
║ columns. ║
╚═══════ a ══╝
┌─ size 1 font b ──────────────────────────────────────┐
│ Fifty-six columns of Font B on the same paper. │
└───────────────────────────────────────────────── b ──┘
┌─ size 2 font b ──────────┐
│ Twenty-eight columns. │
└───────────────────── b ──┘
╔═ size 3 b ═════╗
║ Eighteen ║
║ columns. ║
╚═══════════ b ══╝
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,22 @@
┌─ size 1 ───────────────────────────────┐
│ Forty-two columns of Font A. │
└─────────────────────────────────── a ──┘
┌─ size 2 ──────────┐
│ Twenty-one │
│ columns. │
└────────────── a ──┘
╔═ size 3 ═══╗
║ Fourteen ║
║ columns. ║
╚═══════ a ══╝
┌─ size 1 font b ──────────────────────────────────────┐
│ Fifty-six columns of Font B on the same paper. │
└───────────────────────────────────────────────── b ──┘
┌─ size 2 font b ──────────┐
│ Twenty-eight columns. │
└───────────────────── b ──┘
╔═ size 3 b ═════╗
║ Eighteen ║
║ columns. ║
╚═══════════ b ══╝
- - - - - - - partial cut - - - - - - - -
+8
View File
@@ -0,0 +1,8 @@
{"elements": [
{"type": "box", "size": 1, "title": "size 1", "footer": "a", "text": "Forty-two columns of Font A."},
{"type": "box", "size": 2, "title": "size 2", "footer": "a", "text": "Twenty-one columns."},
{"type": "box", "size": 3, "style": "double", "title": "size 3", "footer": "a", "text": "Fourteen columns."},
{"type": "box", "size": 1, "font": "b", "title": "size 1 font b", "footer": "b", "text": "Fifty-six columns of Font B on the same paper."},
{"type": "box", "size": 2, "font": "b", "title": "size 2 font b", "footer": "b", "text": "Twenty-eight columns."},
{"type": "box", "size": 3, "font": "B", "style": "double", "title": "size 3 b", "footer": "b", "text": "Eighteen columns."}
]}
@@ -0,0 +1,41 @@
+- single -------------------------------+
| Inline title, default style. |
+----------------------------------------+
+- double -------------------------------+
| Inline title. |
+----------------------------------------+
+- double-h -----------------------------+
| Inline title. |
+----------------------------------------+
+- double-v -----------------------------+
| Inline title. |
+----------------------------------------+
+- ascii --------------------------------+
| Inline title. |
+----------------------------------------+
+-| single |-----------------------------+
| Capped title. |
+----------------------------------------+
+-| double |-----------------------------+
| Capped title. |
+----------------------------------------+
+-| double-h |---------------------------+
| Capped title. |
+----------------------------------------+
+-| double-v |---------------------------+
| Capped title. |
+----------------------------------------+
+-| ascii |------------------------------+
| Capped title. |
+----------------------------------------+
+----------------------------------------+
| No title, a footer, and a long |
| paragraph that wraps inside the |
| borders. |
| A second paragraph. |
+------------------------ 29 Nov 21:04 --+
+----------------------------------------+
| Bold, underlined and inverted body |
| text; the borders stay plain. |
+----------------------------------------+
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,41 @@
┌─ single ───────────────────────────────┐
│ Inline title, default style. │
└────────────────────────────────────────┘
╔═ double ═══════════════════════════════╗
║ Inline title. ║
╚════════════════════════════════════════╝
╒═ double-h ═════════════════════════════╕
│ Inline title. │
╘════════════════════════════════════════╛
╓─ double-v ─────────────────────────────╖
║ Inline title. ║
╙────────────────────────────────────────╜
+- ascii --------------------------------+
| Inline title. |
+----------------------------------------+
┌─┤ single ├─────────────────────────────┐
│ Capped title. │
└────────────────────────────────────────┘
╔═╡ double ╞═════════════════════════════╗
║ Capped title. ║
╚════════════════════════════════════════╝
╒═╡ double-h ╞═══════════════════════════╕
│ Capped title. │
╘════════════════════════════════════════╛
╓─┤ double-v ├───────────────────────────╖
║ Capped title. ║
╙────────────────────────────────────────╜
+-| ascii |------------------------------+
| Capped title. |
+----------------------------------------+
╔════════════════════════════════════════╗
║ No title, a footer, and a long ║
║ paragraph that wraps inside the ║
║ borders. ║
║ A second paragraph. ║
╚════════════════════════ 29 Nov 21:04 ══╝
┌────────────────────────────────────────┐
│ Bold, underlined and inverted body │
│ text; the borders stay plain. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,41 @@
┌─ single ───────────────────────────────┐
│ Inline title, default style. │
└────────────────────────────────────────┘
╔═ double ═══════════════════════════════╗
║ Inline title. ║
╚════════════════════════════════════════╝
╔═ double-h ═════════════════════════════╗
║ Inline title. ║
╚════════════════════════════════════════╝
╔═ double-v ═════════════════════════════╗
║ Inline title. ║
╚════════════════════════════════════════╝
+- ascii --------------------------------+
| Inline title. |
+----------------------------------------+
┌─┤ single ├─────────────────────────────┐
│ Capped title. │
└────────────────────────────────────────┘
╔═╣ double ╠═════════════════════════════╗
║ Capped title. ║
╚════════════════════════════════════════╝
╔═╣ double-h ╠═══════════════════════════╗
║ Capped title. ║
╚════════════════════════════════════════╝
╔═╣ double-v ╠═══════════════════════════╗
║ Capped title. ║
╚════════════════════════════════════════╝
+-| ascii |------------------------------+
| Capped title. |
+----------------------------------------+
╔════════════════════════════════════════╗
║ No title, a footer, and a long ║
║ paragraph that wraps inside the ║
║ borders. ║
║ A second paragraph. ║
╚════════════════════════ 29 Nov 21:04 ══╝
┌────────────────────────────────────────┐
│ Bold, underlined and inverted body │
│ text; the borders stay plain. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
+14
View File
@@ -0,0 +1,14 @@
{"elements": [
{"type": "box", "title": "single", "text": "Inline title, default style."},
{"type": "box", "style": "double", "title": "double", "text": "Inline title."},
{"type": "box", "style": "double-h", "title": "double-h", "text": "Inline title."},
{"type": "box", "style": "double-v", "title": "double-v", "text": "Inline title."},
{"type": "box", "style": "ascii", "title": "ascii", "text": "Inline title."},
{"type": "box", "title": "single", "title_style": "capped", "text": "Capped title."},
{"type": "box", "style": "double", "title": "double", "title_style": "capped", "text": "Capped title."},
{"type": "box", "style": "double-h", "title": "double-h", "title_style": "capped", "text": "Capped title."},
{"type": "box", "style": "double-v", "title": "double-v", "title_style": "capped", "text": "Capped title."},
{"type": "box", "style": "ascii", "title": "ascii", "title_style": "capped", "text": "Capped title."},
{"type": "box", "style": "DOUBLE", "footer": "29 Nov 21:04", "text": "No title, a footer, and a long paragraph that wraps inside the borders.\nA second paragraph."},
{"type": "box", "text": "Bold, underlined and inverted body text; the borders stay plain.", "bold": true, "underline": 1, "invert": true, "align": "right"}
]}
@@ -0,0 +1,23 @@
+- An inline title that is far too l... -+
| Cut with an ellipsis. |
+----------------------------------------+
+-| A capped title that is far too ... |-+
| Cut two columns earlier. |
+----------------------------------------+
+- Exactly thirty-six characters long!! -+
| The longest inline title that fits. |
+----------------------------------------+
+- Thirty-seven characters long, too!!! -+
| One more and it is cut. |
+----------------------------------------+
+----------------------------------------+
| Cut with an ellipsis. |
+- A footer that is far too long fo... --+
+- Title with a newline and a tab -------+
| Newlines and tabs in titles and |
| footers become spaces. |
+------------------------- Footer also --+
+- A lon... -+
| Big |
+- A lo... --+
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,23 @@
┌─ An inline title that is far too l... ─┐
│ Cut with an ellipsis. │
└────────────────────────────────────────┘
╔═╡ A capped title that is far too ... ╞═╗
║ Cut two columns earlier. ║
╚════════════════════════════════════════╝
┌─ Exactly thirty-six characters long!! ─┐
│ The longest inline title that fits. │
└────────────────────────────────────────┘
┌─ Thirty-seven characters long, too!!! ─┐
│ One more and it is cut. │
└────────────────────────────────────────┘
┌────────────────────────────────────────┐
│ Cut with an ellipsis. │
└─ A footer that is far too long fo... ──┘
┌─ Title with a newline and a tab ───────┐
│ Newlines and tabs in titles and │
│ footers become spaces. │
└───────────────────────── Footer also ──┘
┌─ A lon... ─┐
│ Big │
└─ A lo... ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,23 @@
┌─ An inline title that is far too l... ─┐
│ Cut with an ellipsis. │
└────────────────────────────────────────┘
╔═╣ A capped title that is far too ... ╠═╗
║ Cut two columns earlier. ║
╚════════════════════════════════════════╝
┌─ Exactly thirty-six characters long!! ─┐
│ The longest inline title that fits. │
└────────────────────────────────────────┘
┌─ Thirty-seven characters long, too!!! ─┐
│ One more and it is cut. │
└────────────────────────────────────────┘
┌────────────────────────────────────────┐
│ Cut with an ellipsis. │
└─ A footer that is far too long fo... ──┘
┌─ Title with a newline and a tab ───────┐
│ Newlines and tabs in titles and │
│ footers become spaces. │
└───────────────────────── Footer also ──┘
┌─ A lon... ─┐
│ Big │
└─ A lo... ──┘
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
{"elements": [
{"type": "box", "title": "An inline title that is far too long for the top border of the box", "text": "Cut with an ellipsis."},
{"type": "box", "style": "double", "title_style": "capped", "title": "A capped title that is far too long for the top border of the box", "text": "Cut two columns earlier."},
{"type": "box", "title": "Exactly thirty-six characters long!!", "text": "The longest inline title that fits."},
{"type": "box", "title": "Thirty-seven characters long, too!!!", "text": "One more and it is cut."},
{"type": "box", "footer": "A footer that is far too long for the bottom border", "text": "Cut with an ellipsis."},
{"type": "box", "title": "Title\nwith a newline\tand a tab", "footer": "Footer\nalso", "text": "Newlines and tabs in titles and footers become spaces."},
{"type": "box", "size": 3, "title": "A long title", "footer": "A long footer", "text": "Big"}
]}
@@ -0,0 +1,45 @@
+- single box ---------------------------+
| single rule |
+----------------------------------------+
| double rule |
+========================================+
| labelled |
+-- Left --------------------------------+
+---------------- Centre ----------------+
+=============================== Right ==+
| end |
+----------------------------------------+
+- double box ---------------------------+
| single rule |
+----------------------------------------+
| double rule |
+================ Label =================+
| end |
+----------------------------------------+
+- double-h box -------------------------+
| single rule |
+----------------------------------------+
| double rule |
+================ Label =================+
| end |
+----------------------------------------+
+- double-v box -------------------------+
| single rule |
+----------------------------------------+
| double rule |
+================ Label =================+
| end |
+----------------------------------------+
+- ascii box ----------------------------+
| single rule |
+----------------------------------------+
| double rule |
+================ Label =================+
| end |
+----------------------------------------+
+------------+
| narrow |
+-- too... --+
+--- fits ---+
+------------+
- - - - - - - partial cut - - - - - - - -
+45
View File
@@ -0,0 +1,45 @@
┌─ single box ───────────────────────────┐
│ single rule │
├────────────────────────────────────────┤
│ double rule │
╞════════════════════════════════════════╡
│ labelled │
├── Left ────────────────────────────────┤
├──────────────── Centre ────────────────┤
╞═══════════════════════════════ Right ══╡
│ end │
└────────────────────────────────────────┘
╔═ double box ═══════════════════════════╗
║ single rule ║
╟────────────────────────────────────────╢
║ double rule ║
╠════════════════ Label ═════════════════╣
║ end ║
╚════════════════════════════════════════╝
╒═ double-h box ═════════════════════════╕
│ single rule │
├────────────────────────────────────────┤
│ double rule │
╞════════════════ Label ═════════════════╡
│ end │
╘════════════════════════════════════════╛
╓─ double-v box ─────────────────────────╖
║ single rule ║
╟────────────────────────────────────────╢
║ double rule ║
╠════════════════ Label ═════════════════╣
║ end ║
╙────────────────────────────────────────╜
+- ascii box ----------------------------+
| single rule |
+----------------------------------------+
| double rule |
+================ Label =================+
| end |
+----------------------------------------+
┌────────────┐
│ narrow │
├── too... ──┤
├─── fits ───┤
└────────────┘
- - - - - - - partial cut - - - - - - - -
+45
View File
@@ -0,0 +1,45 @@
┌─ single box ───────────────────────────┐
│ single rule │
├────────────────────────────────────────┤
│ double rule │
├────────────────────────────────────────┤
│ labelled │
├── Left ────────────────────────────────┤
├──────────────── Centre ────────────────┤
├─────────────────────────────── Right ──┤
│ end │
└────────────────────────────────────────┘
╔═ double box ═══════════════════════════╗
║ single rule ║
╠════════════════════════════════════════╣
║ double rule ║
╠════════════════ Label ═════════════════╣
║ end ║
╚════════════════════════════════════════╝
╔═ double-h box ═════════════════════════╗
║ single rule ║
╠════════════════════════════════════════╣
║ double rule ║
╠════════════════ Label ═════════════════╣
║ end ║
╚════════════════════════════════════════╝
╔═ double-v box ═════════════════════════╗
║ single rule ║
╠════════════════════════════════════════╣
║ double rule ║
╠════════════════ Label ═════════════════╣
║ end ║
╚════════════════════════════════════════╝
+- ascii box ----------------------------+
| single rule |
+----------------------------------------+
| double rule |
+================ Label =================+
| end |
+----------------------------------------+
┌────────────┐
│ narrow │
├── too... ──┤
├─── fits ───┤
└────────────┘
- - - - - - - partial cut - - - - - - - -
+46
View File
@@ -0,0 +1,46 @@
{"elements": [
{"type": "box", "title": "single box", "children": [
{"type": "text", "text": "single rule"},
{"type": "rule"},
{"type": "text", "text": "double rule"},
{"type": "rule", "style": "double"},
{"type": "text", "text": "labelled"},
{"type": "rule", "text": "Left", "align": "left"},
{"type": "rule", "text": "Centre"},
{"type": "rule", "text": "Right", "align": "right", "style": "double", "bold": true},
{"type": "text", "text": "end"}
]},
{"type": "box", "style": "double", "title": "double box", "children": [
{"type": "text", "text": "single rule"},
{"type": "rule"},
{"type": "text", "text": "double rule"},
{"type": "rule", "style": "double", "text": "Label"},
{"type": "text", "text": "end"}
]},
{"type": "box", "style": "double-h", "title": "double-h box", "children": [
{"type": "text", "text": "single rule"},
{"type": "rule"},
{"type": "text", "text": "double rule"},
{"type": "rule", "style": "double", "text": "Label"},
{"type": "text", "text": "end"}
]},
{"type": "box", "style": "double-v", "title": "double-v box", "children": [
{"type": "text", "text": "single rule"},
{"type": "rule"},
{"type": "text", "text": "double rule"},
{"type": "rule", "style": "double", "text": "Label"},
{"type": "text", "text": "end"}
]},
{"type": "box", "style": "ascii", "title": "ascii box", "children": [
{"type": "text", "text": "single rule"},
{"type": "rule"},
{"type": "text", "text": "double rule"},
{"type": "rule", "style": "double", "text": "Label"},
{"type": "text", "text": "end"}
]},
{"type": "box", "columns": 14, "children": [
{"type": "text", "text": "narrow"},
{"type": "rule", "text": "too long a label"},
{"type": "rule", "text": "fits"}
]}
]}
+15
View File
@@ -0,0 +1,15 @@
+- “Quoted” — title… --------------------+
| ‘Single’ – dash; ellipsis… • bullet -> |
| arrow <- back x x × € ™ done |
+----------------------------------------+
Emoji: ? one sequence, ? a family, ? a
flag, 1 a keycap, ? a sign.
Price .......................... 12 € — 3×
Emoji ................................. ??
---------------- “Label” -----------------
Decomposed: café, naïve; zerowidth and
joiner gone.
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[1]: 4 characters not in cp1252 printed as ?
elements[2]: 2 characters not in cp1252 printed as ?
+15
View File
@@ -0,0 +1,15 @@
┌─ "Quoted" -- title... ─────────────────┐
│ 'Single' - dash; ellipsis... · bullet │
│ -> arrow <- back √ √ x EUR TM done │
└────────────────────────────────────────┘
Emoji: ? one sequence, ? a family, ? a
flag, 1 a keycap, ? a sign.
Price ....................... 12 EUR -- 3x
Emoji ................................. ??
──────────────── "Label" ─────────────────
Decomposed: café, naïve; zerowidth and
joiner gone.
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[1]: 4 characters not in cp437 printed as ?
elements[2]: 2 characters not in cp437 printed as ?
+15
View File
@@ -0,0 +1,15 @@
┌─ "Quoted" -- title... ─────────────────┐
│ 'Single' - dash; ellipsis... · bullet │
│ -> arrow <- back x x × EUR TM done │
└────────────────────────────────────────┘
Emoji: ? one sequence, ? a family, ? a
flag, 1 a keycap, ? a sign.
Price ....................... 12 EUR -- 3×
Emoji ................................. ??
──────────────── "Label" ─────────────────
Decomposed: café, naïve; zerowidth and
joiner gone.
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[1]: 4 characters not in cp850 printed as ?
elements[2]: 2 characters not in cp850 printed as ?
+7
View File
@@ -0,0 +1,7 @@
{"elements": [
{"type": "box", "title": "“Quoted” — title…", "text": "‘Single’ – dash; ellipsis… • bullet → arrow ← back ✓ ✔ × € ™ done"},
{"type": "text", "text": "Emoji: 👍🏽 one sequence, 👨\u200D👩\u200D👧 a family, 🇩🇪 a flag, 1\uFE0F\u20E3 a keycap, ⚠\uFE0F a sign."},
{"type": "kv", "pairs": [{"key": "Price", "value": "12 € — 3×"}, {"key": "Emoji", "value": "🎉🎉"}]},
{"type": "rule", "text": "“Label”"},
{"type": "text", "text": "Decomposed: cafe\u0301, nai\u0308ve; zero\u200Bwidth and joiner\u200D gone."}
]}
+29
View File
@@ -0,0 +1,29 @@
Host ............................... nas01
Note ... The scrub finished with 0 errors.
Next scrub Sunday 03:00.
Used ................................. 94%
Empty ....................................
A key that is much too long to ... ..... v
URL .. https://example.com/a/very/long/pat
h/without/any/spaces/in/it
Lines .................... first paragraph
second paragraph
··········································
Middle dots ···························· ·
Spaces justified
space the same
Underscores ____________________________ _
Dashes --------------------------------- -
Line ----------------------------------- ?
Columns .... 24, centred
Size .............. 2
Total ........ £12.50
Font B .......................... fifty-six columns wide
+- kv in a box --------------------------+
| Inside ........... the content width |
| Wraps ..... a value that is too long |
| for one line of the box |
+----------------------------------------+
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[7]: 1 character not in cp1252 printed as ?
+27
View File
@@ -0,0 +1,27 @@
Host ............................... nas01
Note ... The scrub finished with 0 errors.
Next scrub Sunday 03:00.
Used ................................. 94%
Empty ....................................
A key that is much too long to ... ..... v
URL .. https://example.com/a/very/long/pat
h/without/any/spaces/in/it
Lines .................... first paragraph
second paragraph
··········································
Middle dots ···························· ·
Spaces justified
space the same
Underscores ____________________________ _
Dashes --------------------------------- -
Line ─────────────────────────────────── ─
Columns .... 24, centred
Size .............. 2
Total ........ £12.50
Font B .......................... fifty-six columns wide
┌─ kv in a box ──────────────────────────┐
│ Inside ........... the content width │
│ Wraps ..... a value that is too long │
│ for one line of the box │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
+27
View File
@@ -0,0 +1,27 @@
Host ............................... nas01
Note ... The scrub finished with 0 errors.
Next scrub Sunday 03:00.
Used ................................. 94%
Empty ....................................
A key that is much too long to ... ..... v
URL .. https://example.com/a/very/long/pat
h/without/any/spaces/in/it
Lines .................... first paragraph
second paragraph
··········································
Middle dots ···························· ·
Spaces justified
space the same
Underscores ____________________________ _
Dashes --------------------------------- -
Line ─────────────────────────────────── ─
Columns .... 24, centred
Size .............. 2
Total ........ £12.50
Font B .......................... fifty-six columns wide
┌─ kv in a box ──────────────────────────┐
│ Inside ........... the content width │
│ Wraps ..... a value that is too long │
│ for one line of the box │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
+24
View File
@@ -0,0 +1,24 @@
{"elements": [
{"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},
{"key": "Empty", "value": ""},
{"key": "A key that is much too long to leave room for its value", "value": "v"},
{"key": "URL", "value": "https://example.com/a/very/long/path/without/any/spaces/in/it"},
{"key": "Lines", "value": "first paragraph\nsecond paragraph"}
]},
{"type": "rule", "style": "dotted"},
{"type": "kv", "leader": "·", "pairs": [{"key": "Middle dots", "value": "·"}]},
{"type": "kv", "leader": " ", "pairs": [{"key": "Spaces", "value": "justified"}]},
{"type": "kv", "leader": "space", "pairs": [{"key": "space", "value": "the same"}]},
{"type": "kv", "leader": "_", "pairs": [{"key": "Underscores", "value": "_"}]},
{"type": "kv", "leader": "-", "pairs": [{"key": "Dashes", "value": "-"}]},
{"type": "kv", "leader": "─", "pairs": [{"key": "Line", "value": "─"}]},
{"type": "kv", "columns": 24, "pairs": [{"key": "Columns", "value": "24, centred"}]},
{"type": "kv", "size": 2, "pairs": [{"key": "Size", "value": "2"}, {"key": "Total", "value": "£12.50", "bold": true}]},
{"type": "kv", "font": "b", "pairs": [{"key": "Font B", "value": "fifty-six columns wide"}]},
{"type": "box", "title": "kv in a box", "padding": 2, "children": [
{"type": "kv", "pairs": [{"key": "Inside", "value": "the content width"}, {"key": "Wraps", "value": "a value that is too long for one line of the box"}]}
]}
]}
+24
View File
@@ -0,0 +1,24 @@
+-| ACHTUNG |----------------------------+
| The coffee machine is being descaled. |
| Do not use until 10:30. |
+----------------------------------------+
+---------------------+
| !!! ACHTUNG !!! |
+---------------------+
+-------------------+
| !!! ACHTUNG !!! |
+-------------------+
+- NAS REPORT ---------------------------+
| Host ........................... nas01 |
| Pool ................... tank (raidz2) |
| Used ............................. 94% |
+-- Services ----------------------------+
| · grafana up |
| · offsite-backup DOWN since 19:00 |
+------------------------ 29 Nov 21:04 --+
================= TOTAL ==================
Total: £12.50
- - - - - - - partial cut - - - - - - - -
+24
View File
@@ -0,0 +1,24 @@
╔═╡ ACHTUNG ╞════════════════════════════╗
║ The coffee machine is being descaled. ║
║ Do not use until 10:30. ║
╚════════════════════════════════════════╝
┌─────────────────────┐
│ !!! ACHTUNG !!! │
└─────────────────────┘
╔═══════════════════╗
║ !!! ACHTUNG !!! ║
╚═══════════════════╝
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
═════════════════ TOTAL ══════════════════
Total: £12.50
- - - - - - - partial cut - - - - - - - -
+24
View File
@@ -0,0 +1,24 @@
╔═╣ ACHTUNG ╠════════════════════════════╗
║ The coffee machine is being descaled. ║
║ Do not use until 10:30. ║
╚════════════════════════════════════════╝
┌─────────────────────┐
│ !!! ACHTUNG !!! │
└─────────────────────┘
╔═══════════════════╗
║ !!! ACHTUNG !!! ║
╚═══════════════════╝
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
═════════════════ TOTAL ══════════════════
Total: £12.50
- - - - - - - partial cut - - - - - - - -
+17
View File
@@ -0,0 +1,17 @@
{"elements": [
{"type": "box", "style": "double", "title": "ACHTUNG", "title_style": "capped", "align": "center",
"text": "The coffee machine is being descaled.\nDo not use until 10:30."},
{"type": "feed"},
{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"},
{"type": "feed"},
{"type": "box", "style": "double", "fit": true, "padding": 2, "text": "!!! ACHTUNG !!!"},
{"type": "feed"},
{"type": "box", "title": "NAS REPORT", "footer": "29 Nov 21:04", "children": [
{"type": "kv", "pairs": [{"key": "Host", "value": "nas01"}, {"key": "Pool", "value": "tank (raidz2)"}, {"key": "Used", "value": "94%", "bold": true}]},
{"type": "rule", "text": "Services", "align": "left"},
{"type": "text", "text": "· grafana up\n· offsite-backup DOWN since 19:00"}
]},
{"type": "rule", "style": "double", "text": "TOTAL"},
{"type": "text", "text": "Total: ", "newline": false},
{"type": "text", "text": "£12.50", "bold": true}
]}
+22
View File
@@ -0,0 +1,22 @@
------------------------------------------
==========================================
##########################################
##########################################
##########################################
##########################################
- - - - - - - - - - - - - - - - - - - - -
··········································
------------------------------------------
----------------- TODAY ------------------
================= TOTAL ==================
-- Notes ---------------------------------
--------------------------------- Right --
################# URGENT #################
- dashed - - - - - - - - - - - - - - - -
- - - - - - - - - dashed - - - - - - - - -
································ dotted ··
-- A label far too long to fit insid... --
-------- 20 --------
======== BIG ========
------------------------ Font B ------------------------
- - - - - - - partial cut - - - - - - - -
+22
View File
@@ -0,0 +1,22 @@
──────────────────────────────────────────
══════════════════════════════════════════
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
██████████████████████████████████████████
- - - - - - - - - - - - - - - - - - - - -
··········································
------------------------------------------
───────────────── TODAY ──────────────────
═════════════════ TOTAL ══════════════════
── Notes ─────────────────────────────────
───────────────────────────────── Right ──
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
- dashed - - - - - - - - - - - - - - - -
- - - - - - - - - dashed - - - - - - - - -
································ dotted ··
── A label far too long to fit insid... ──
──────── 20 ────────
════════ BIG ════════
──────────────────────── Font B ────────────────────────
- - - - - - - partial cut - - - - - - - -
+22
View File
@@ -0,0 +1,22 @@
──────────────────────────────────────────
══════════════════════════════════════════
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
██████████████████████████████████████████
- - - - - - - - - - - - - - - - - - - - -
··········································
------------------------------------------
───────────────── TODAY ──────────────────
═════════════════ TOTAL ══════════════════
── Notes ─────────────────────────────────
───────────────────────────────── Right ──
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
- dashed - - - - - - - - - - - - - - - -
- - - - - - - - - dashed - - - - - - - - -
································ dotted ··
── A label far too long to fit insid... ──
──────── 20 ────────
════════ BIG ════════
──────────────────────── Font B ────────────────────────
- - - - - - - partial cut - - - - - - - -
+23
View File
@@ -0,0 +1,23 @@
{"elements": [
{"type": "rule"},
{"type": "rule", "style": "double"},
{"type": "rule", "style": "light"},
{"type": "rule", "style": "medium"},
{"type": "rule", "style": "dark"},
{"type": "rule", "style": "solid"},
{"type": "rule", "style": "dashed"},
{"type": "rule", "style": "dotted"},
{"type": "rule", "style": "ascii"},
{"type": "rule", "text": "TODAY"},
{"type": "rule", "style": "double", "text": "TOTAL", "bold": true},
{"type": "rule", "text": "Notes", "align": "left"},
{"type": "rule", "text": "Right", "align": "right"},
{"type": "rule", "style": "dark", "text": "URGENT"},
{"type": "rule", "style": "dashed", "text": "dashed", "align": "left"},
{"type": "rule", "style": "dashed", "text": "dashed"},
{"type": "rule", "style": "dotted", "text": "dotted", "align": "right"},
{"type": "rule", "text": "A label far too long to fit inside a rule on this paper"},
{"type": "rule", "columns": 20, "text": "20"},
{"type": "rule", "size": 2, "style": "double", "text": "BIG"},
{"type": "rule", "font": "b", "text": "Font B"}
]}
+8
View File
@@ -0,0 +1,8 @@
1b401b74101b61001b4d001d21001b45001b2d001d420093536d617274207175
6f7465739420616e64209173696e676c6592209620656e206461736820972065
6d0a64617368208520656c6c697073697320952062756c6c65740a1b45001b2d
001d42001d21001b4d001b61001b4d001d21001b45001b2d001d42008020392c
3939209920d720f720a920ae20b020b120b520bc20bd20be209c208a209e209f
0a1b45001b2d001d42001d21001b4d001b61001b4d001d21001b45001b2d001d
42004d697373696e6720686572653a203f203f203f203f203f203f0a1b45001b
2d001d42001d21001b4d001d564200
+10
View File
@@ -0,0 +1,10 @@
{
"options": {"codepage": "cp1252"},
"job": {
"elements": [
{"type": "text", "text": "“Smart quotes” and ‘single’ – en dash — em dash … ellipsis • bullet"},
{"type": "text", "text": "€ 9,99 ™ × ÷ © ® ° ± µ ¼ ½ ¾ œ Š ž Ÿ"},
{"type": "text", "text": "Missing here: ─ │ ░ √ 🎉 Ω"}
]
}
}
+17
View File
@@ -0,0 +1,17 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200b2b2b2b2b2b2b2b2b2
b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2
b20a1b45001b2d001d42001d21001b4d001b61011b4d001d21001b45001b2d00
1d4200dac4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4bf0ab320202021
21212041434854554e4720212121202020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4
c4c4c4c4c4c4c4c4c4d90a1b45001b2d001d42001d21001b4d001b61001b4d00
1d21001b45001b2d001d4200c9cdbb20d6c4b720d5cdb820b0b1b2db20dcdfdd
de20fe20faf9fb20f8f1fd20e620abac0ae0e1e2e3e4e50a1b45001b2d001d42
001d21001b4d001b61001b4d001d21001b45001b2d001d42009c31322e353020
9a6265726272696e6765722063616682206e618b7665208020a420a8ad209d20
9b0a1b45001b2d001d42001d21001b4d001b61001b4d001d21001b45001b2d00
1d42004d697373696e673a203f203f203f2c2070726573656e743a20ea0a1b45
001b2d001d42001d21001b4d001b61001b4d001d21001b45001b2d001d420043
6f6e74726f6c732073747269707065640a62656c6c20676f6e654020616e6420
45534320746f6f0a1b45001b2d001d42001d21001b4d001b61001b4d001d2100
1b45001b2d001d42004e6fff627265616b2073706163650a1b45001b2d001d42
001d21001b4d001d564200
+13
View File
@@ -0,0 +1,13 @@
{
"job": {
"elements": [
{"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"},
{"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"},
{"type": "text", "text": "╔═╗ ╓─╖ ╒═╕ ░▒▓█ ▄▀▌▐ ■ ·∙√ °±² µ ½¼ αßΓπΣσ"},
{"type": "text", "text": "£12.50 Überbringer café naïve Ç ñ ¿¡ ¥ ¢"},
{"type": "text", "text": "Missing: 🎉 漢 ¤, present: Ω"},
{"type": "text", "text": "Controls\u0007 stripped\r\nbell gone\u001b@ and ESC too\u0000"},
{"type": "text", "text": "No\u00A0break space"}
]
}
}
+6
View File
@@ -0,0 +1,6 @@
1b401b74021b61001b4d001d21001b45001b2d001d4200c9cdbbbac8bc20dac4
bfb3c0d920c3b420ccb920b0b1b2db20cf20b820a9209d209b209e0a1b45001b
2d001d42001d21001b4d001b61001b4d001d21001b45001b2d001d42009a6265
72677294e165209c352085828ce48120b790d7e59a0a1b45001b2d001d42001d
21001b4d001b61001b4d001d21001b45001b2d001d42004d697373696e672068
6572653a203f203f203f203f0a1b45001b2d001d42001d21001b4d001d564200
+10
View File
@@ -0,0 +1,10 @@
{
"options": {"codepage": "cp850"},
"job": {
"elements": [
{"type": "text", "text": "╔═╗║╚╝ ┌─┐│└┘ ├┤ ╠╣ ░▒▓█ ¤ © ® Ø ø ×"},
{"type": "text", "text": "Übergröße £5 àéîõü ÀÉÎÕÜ"},
{"type": "text", "text": "Missing here: √ ╒ ╟ Ω"}
]
}
}
+4
View File
@@ -0,0 +1,4 @@
1b401b74131b61001b4d001d21001b45001b2d001d420050726963653a203132
2c353020d5202863703835382068617320746865206575726f207369676e290a
1b45001b2d001d42001d21001b4d001b61001b4d001d21001b45001b2d001d42
00c9cdbb20b0b1b2209c20e10a1b45001b2d001d42001d21001b4d001d564200
+9
View File
@@ -0,0 +1,9 @@
{
"options": {"codepage": "cp858"},
"job": {
"elements": [
{"type": "text", "text": "Price: 12,50 € (cp858 has the euro sign)"},
{"type": "text", "text": "╔═╗ ░▒▓ £ ß"}
]
}
}
+36
View File
@@ -0,0 +1,36 @@
1b401b74001b61001b4d001d21001b45001b2d001d42004265666f7265207468
6520636f6465730a1b45001b2d001d42001d21001b4d001b64031b64011b6101
1d286b0400314132001d286b03003143061d286b03003145311d286b16003150
3068747470733a2f2f6578616d706c652e636f6d1d286b03003151301b61021d
286b0400314132001d286b03003143031d286b03003145331d286b1c00315030
536d616c6c2051522c206869676820636f7272656374696f6e1d286b03003151
301b61001d286b0400314132001d286b03003143101d286b03003145321d286b
1800315030515220617420746865206c656674207769746820511d286b030031
51301b61001d68501d77031d48021d6b490a7b424142432d7b7b317d1b61011d
683c1d77021d48031d6b430d343030363338313333333933311b61001d68501d
77031d48001d6b4407393633383530371b61021d68501d77031d48011d6b410b
30333630303032393134351b61001d68ff1d77061d48021d6b42083031323334
3536351b61001d68501d77031d48021d6b450c434f44452033392d242f2b251b
61001b4d001d21001b45001b2d001d4200696e6c696e65206265666f72652072
6177201b45001b2d001d42001d21001b4d001b61011b61001b4d001d21001b45
001b2d001d42006166746572207261770a1b45001b2d001d42001d21001b4d00
1d5641001b61001b4d001d21001b45001b2d001d420041667465722061206675
6c6c206375740a1b45001b2d001d42001d21001b4d001d5642001b61001b4d00
1d21001b45001b2d001d42004265666f72652074686520636f6465730a1b4500
1b2d001d42001d21001b4d001b64031b64011b61011d286b0400314132001d28
6b03003143061d286b03003145311d286b160031503068747470733a2f2f6578
616d706c652e636f6d1d286b03003151301b61021d286b0400314132001d286b
03003143031d286b03003145331d286b1c00315030536d616c6c2051522c2068
69676820636f7272656374696f6e1d286b03003151301b61001d286b04003141
32001d286b03003143101d286b03003145321d286b1800315030515220617420
746865206c656674207769746820511d286b03003151301b61001d68501d7703
1d48021d6b490a7b424142432d7b7b317d1b61011d683c1d77021d48031d6b43
0d343030363338313333333933311b61001d68501d77031d48001d6b44073936
33383530371b61021d68501d77031d48011d6b410b3033363030303239313435
1b61001d68ff1d77061d48021d6b420830313233343536351b61001d68501d77
031d48021d6b450c434f44452033392d242f2b251b61001b4d001d21001b4500
1b2d001d4200696e6c696e65206265666f726520726177201b45001b2d001d42
001d21001b4d001b61011b61001b4d001d21001b45001b2d001d420061667465
72207261770a1b45001b2d001d42001d21001b4d001d5641001b61001b4d001d
21001b45001b2d001d4200416674657220612066756c6c206375740a1b45001b
2d001d42001d21001b4d001d564200
+25
View File
@@ -0,0 +1,25 @@
{
"job": {
"copies": 2,
"elements": [
{"type": "text", "text": "Before the codes"},
{"type": "feed", "lines": 3},
{"type": "feed"},
{"type": "qr", "data": "https://example.com", "align": "center"},
{"type": "qr", "data": "Small QR, high correction", "size": 3, "correction": "H", "align": "right"},
{"type": "qr", "data": "QR at the left with Q", "size": 16, "correction": "q"},
{"type": "barcode", "symbology": "code128", "data": "ABC-{1}"},
{"type": "barcode", "symbology": "ean13", "data": "4006381333931", "height": 60, "width": 2, "hri": "both", "align": "center"},
{"type": "barcode", "symbology": "ean8", "data": "9638507", "hri": "none"},
{"type": "barcode", "symbology": "upca", "data": "03600029145", "hri": "above", "align": "right"},
{"type": "barcode", "symbology": "upce", "data": "01234565", "width": 6, "height": 255},
{"type": "barcode", "symbology": "code39", "data": "CODE 39-$/+%"},
{"type": "text", "text": "inline before raw ", "newline": false},
{"type": "raw", "hex": "1B 61 01"},
{"type": "text", "text": "after raw"},
{"type": "cut", "mode": "full"},
{"type": "text", "text": "After a full cut"},
{"type": "cut"}
]
}
}
+45
View File
@@ -0,0 +1,45 @@
1b401b74001b61001d76300040000600ff548000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000eaa20f00000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000b4907f00000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000009203f500000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000403faa00000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000011fd5400000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000001b61001d76300040000c000000000000
000000000000000000000000000000000000000000000000fffedaa900000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000ff6b6aa4a9200000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000fbb5aa4800ff0000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000dd5a490221ff0000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000eb6aa4503eed0000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000554910007ff70000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000b524400fdf5a0000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000aa910a9ff5aa0000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000044440fef6ed50000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000029009fbbb5540000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000008007edfd552a0000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000002403ff55aa900000
0000000000000000000000000000000000000000000000000000001b61001b4d
001d21001b45001b2d001d42006265747765656e1b45001b2d001d42001d2100
1b4d000a1b61001d763000400003000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000001e820000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000105f0000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000005f41d564200
+10
View File
@@ -0,0 +1,10 @@
{
"job": {
"elements": [
{"type": "image", "base64": "iVBORw0KGgoAAAANSUhEUgAAABgAAAAGCAAAAAD8wAHPAAAAJElEQVR4nGJh4MYOWFRhLGIkVLFKqGLVgeCxqGIR5Obm5gYMAArvByihTpiMAAAAAElFTkSuQmCC"},
{"type": "image", "base64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAGCAAAAAD8wAHPAAAAJElEQVR4nGJh4MYOWFRhLGIkVLFKqGLVgeCxqGIR5Obm5gYMAArvByihTpiMAAAAAElFTkSuQmCC", "align": "center", "width": 48},
{"type": "text", "text": "between", "newline": false},
{"type": "image", "base64": "iVBORw0KGgoAAAANSUhEUgAAABgAAAAGCAAAAAD8wAHPAAAAJElEQVR4nGJh4MYOWFRhLGIkVLFKqGLVgeCxqGIR5Obm5gYMAArvByihTpiMAAAAAElFTkSuQmCC", "align": "right", "width": 13}
]
}
}
+22
View File
@@ -0,0 +1,22 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200546f74616c3a201b45
001b2d001d42001d21001b4d001b61001b4d001d21001b45011b2d001d420031
322e35300a1b45001b2d001d42001d21001b4d001b61001b4d001d21001b4500
1b2d001d42007878787878787878787878787878787878787878787878787878
78787878787878787878787878781b45001b2d001d42001d21001b4d001b6100
1b4d001d21111b45001b2d001d42000a4249474f4e450a1b45001b2d001d4200
1d21001b4d001b61001b4d001d21001b45001b2d001d42004d69786564201b45
001b2d001d42001d21001b4d001b61001b4d001d21111b45001b2d001d420053
495a4553201b45001b2d001d42001d21001b4d001b61001b4d001d21001b4500
1b2d001d42006f6e206f6e65206c696e652074686174206b656570730a676f69
6e6720756e74696c2069742068617320746f20777261701b45001b2d001d4200
1d21001b4d001b61001b4d001d21001b45001b2d001d420020616e6420656e64
7320686572652e0a1b45001b2d001d42001d21001b4d001b61001b4d001d2100
1b45001b2d001d42004974656d20202020517479202020202050726963650a1b
45001b2d001d42001d21001b4d001b61001b4d001d21001b45001b2d001d4200
54656120202020203220202020202020332e30300a1b45001b2d001d42001d21
001b4d001b61001b4d001d21001b45001b2d001d42006162631b45001b2d001d
42001d21001b4d001b61001b4d001d21001b45001b2d001d4200202020202061
667465722061207461620a20202020202020206e657874206c696e650a1b4500
1b2d001d42001d21001b4d001b61001b4d001d21001b45001b2d001d42006e6f
206e65776c696e652061742074686520656e641b45001b2d001d42001d21001b
4d000a1d564200
+19
View File
@@ -0,0 +1,19 @@
{
"job": {
"elements": [
{"type": "text", "text": "Total: ", "newline": false},
{"type": "text", "text": "12.50", "bold": true},
{"type": "text", "text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "newline": false},
{"type": "text", "text": "BIGONE", "size": 2},
{"type": "text", "text": "Mixed ", "newline": false},
{"type": "text", "text": "SIZES ", "size": 2, "newline": false},
{"type": "text", "text": "on one line that keeps going until it has to wrap", "newline": false},
{"type": "text", "text": " and ends here."},
{"type": "text", "text": "Item\tQty\tPrice"},
{"type": "text", "text": "Tea\t2\t3.00"},
{"type": "text", "text": "abc", "newline": false},
{"type": "text", "text": "\tafter a tab\n\tnext line"},
{"type": "text", "text": "no newline at the end", "newline": false}
]
}
}
+9
View File
@@ -0,0 +1,9 @@
1b401b74001b61001b4d001d21001b45001b2d001d420054686972747920636f
6c756d6e73206f6620466f6e7420412066726f6d0a74686520636f6c756d6e73
206f766572726964652c206f6e20612035380a6d6d2070726f66696c652e0a1b
45001b2d001d42001d21001b4d001b61001b4d011d21001b45001b2d001d4200
466f6e7420422075736573207468652073616d65206c696e6520776964746820
696e20646f74732c0a736f206974206669747320666f72747920636861726163
7465727320686572652e0a1b45001b2d001d42001d21001b4d001b61011b4d00
1d21111b45001b2d001d420054696e790a1b45001b2d001d42001d21001b4d00
1d564200
+10
View File
@@ -0,0 +1,10 @@
{
"options": {"model": "generic-58mm", "columns": 30},
"job": {
"elements": [
{"type": "text", "text": "Thirty columns of Font A from the columns override, on a 58 mm profile."},
{"type": "text", "text": "Font B uses the same line width in dots, so it fits forty characters here.", "font": "b"},
{"type": "text", "text": "Tiny", "size": 2, "align": "center"}
]
}
}
+13
View File
@@ -0,0 +1,13 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200797979797979797979
7979797979797979797979797979797979797979797979797979797979797979
797979797979797979797979797979797979790a1b45001b2d001d42001d2100
1b4d001b61001b4d001d21001b45001b2d001d4200556e777261707065640a77
6974682061206e65776c696e6509616e642061207461620a1b45001b2d001d42
001d21001b4d001b61001b4d001d21001b45001b2d001d4200696e6c696e6520
756e77726170706564201b45001b2d001d42001d21001b4d001b61001b4d001d
21001b45001b2d001d42007468656e2077726170706564207465787420746861
740a636f6e74696e756573206f6e207468652073616d65206c696e6520616e64
2077726170730a1b45001b2d001d42001d21001b4d001b61001b4d001d21001b
45001b2d001d4200b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2
b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b20a1b45001b2d001d42001d21001b
4d001d564200
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more