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

+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()
}
}