Files
uberbringer/internal/pkg/receipt/render.go
T
57_WolveandClaude Opus 5.5 3e9779f71a
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m50s
Add the list block and the module layer with the note module
The list block prints items with a dot, dash, number or checkbox bullet,
wrapping a long item with a hanging indent; a checkbox list ticks its
done items as [√], or [x] on code pages without √. It stands alone or
inside a box, and its items, bullet and done fields carry their enums
and limits as jsonschema tags.

internal/pkg/modules holds modules that build ordinary jobs from their
own payloads: a registry by name, an Env with the clock, time zone and
time layout, strict payload decoding that reports every problem, ErrSkip
and PayloadError. The note module prints a boxed note with an optional
checklist and a time stamp in the footer.

Three routes join the route table: POST /api/v1/print/{module} and
POST /api/v1/preview/{module}, which take ?copies and a reserved
?printer, and GET /api/v1/modules. Print and the module route share one
submit path, and preview shares one too. New error codes:
invalid_payload, invalid_query, unknown_printer, module_not_found and
module_failed; a module that builds an invalid receipt is logged and
reported to Sentry once. [format] gains timezone and time_layout, the
binary embeds the time zone database, and uberbringer preview takes
--module.

The note receipt passed on the TM-T88IV, and its bytes are pinned in
TestPaperReceipts. docs/api.md describes the list block, the module
routes and the note payload; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:55:50 -06:00

485 lines
12 KiB
Go

package receipt
import (
"bytes"
"context"
"fmt"
"image"
"strings"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/raster"
)
// Fetcher downloads remote image data.
type Fetcher interface {
Fetch(ctx context.Context, url string) ([]byte, error)
}
// Options configures a Renderer.
type Options struct {
// Profile describes the printer; its DotsPerLine is the image width.
Profile escpos.Profile
// CodePage is the character table text is transcoded to.
CodePage escpos.CodePage
// Columns, when positive, overrides the Font A characters per line used
// 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
// use.
type Renderer struct {
options Options
fetcher Fetcher
}
// NewRenderer returns a Renderer. fetcher loads images given by URL.
func NewRenderer(options Options, fetcher Fetcher) *Renderer {
if fetcher == nil {
panic("receipt.NewRenderer: fetcher must not be nil")
}
if options.Profile.DotsPerLine <= 0 || options.Profile.FontAWidth <= 0 || options.Profile.FontBWidth <= 0 {
panic("receipt.NewRenderer: profile must be set")
}
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}
}
// Render validates job, loads its images and returns the complete command
// stream. Nothing is returned unless the whole receipt rendered, so a failure
// never reaches the printer half-done.
func (r *Renderer) Render(ctx context.Context, job Job) ([]byte, error) {
if err := job.Validate(); err != nil {
return nil, err
}
images, err := r.loadImages(ctx, job)
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,
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 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 rendered{stream: bytes.Clone(out.Bytes()), raw: spans, lines: lines, unknown: unknown}, nil
}
// textLineDots is the line width used for text layout.
func (r *Renderer) textLineDots() int {
if r.options.Columns > 0 {
return r.options.Columns * r.options.Profile.FontAWidth
}
return r.options.Profile.DotsPerLine
}
// loadImages fetches, decodes and dithers every image before anything is
// rendered, keyed by element index.
func (r *Renderer) loadImages(ctx context.Context, job Job) (map[int]*image.Paletted, error) {
images := make(map[int]*image.Paletted)
for i, el := range job.Elements {
if el.Type != TypeImage {
continue
}
img, err := r.loadImage(ctx, el)
if err != nil {
return nil, fmt.Errorf("elements[%d] (image): %w", i, err)
}
images[i] = img
}
return images, nil
}
func (r *Renderer) loadImage(ctx context.Context, el Element) (*image.Paletted, error) {
spec, err := el.imageSpec()
if err != nil {
return nil, err
}
data := spec.data
if spec.url != "" {
if data, err = r.fetcher.Fetch(ctx, spec.url); err != nil {
return nil, err
}
}
src, err := raster.Decode(data, r.options.MaxPixels)
if err != nil {
return nil, err
}
paper := r.options.Profile.DotsPerLine
width := min(src.Bounds().Dx(), paper)
if spec.width > 0 {
if spec.width > paper {
return nil, fmt.Errorf("width %d is wider than the %d-dot paper", spec.width, paper)
}
width = spec.width
}
mono, err := raster.Monochrome(src, width)
if err != nil {
return nil, err
}
if h := mono.Bounds().Dy(); h > r.options.MaxHeight {
return nil, fmt.Errorf("image is %d dots tall after scaling, limit is %d", h, r.options.MaxHeight)
}
var x int
switch spec.align {
case escpos.JustifyCenter:
x = (paper - width) / 2
case escpos.JustifyRight:
x = paper - width
}
return raster.Place(mono, paper, x)
}
// 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
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, TypeList:
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()
if err != nil {
return err
}
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()
if err != nil {
return err
}
p.endLine()
p.b.Justify(spec.align)
p.b.BarcodeHeight(uint8(spec.height))
if err := p.b.BarcodeWidth(spec.width); err != nil {
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:
mode, err := el.cutMode()
if err != nil {
return err
}
p.endLine()
p.b.Cut(mode, 0)
default:
return fmt.Errorf("unknown type %q", el.Type)
}
return nil
}
func (p *printer) text(el Element) error {
spec, err := el.textSpec()
if err != nil {
return err
}
glyph := p.profile.GlyphWidth(spec.font) * spec.width
p.b.Justify(spec.align)
p.b.Font(spec.font)
if err := p.b.Size(spec.width, spec.height); err != nil {
return err
}
p.b.Bold(spec.bold)
p.b.Underline(spec.underline)
p.b.Reverse(spec.invert)
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.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.lineFeed()
}
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)
if err := p.b.Size(1, 1); err != nil {
return err
}
p.b.Font(escpos.FontA)
return nil
}
// block lays out a box, rule, kv or list 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))
case TypeList:
spec, err := el.listSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.list(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) {
if i := strings.LastIndexByte(text, '\n'); i >= 0 {
p.x = 0
text = text[i+1:]
}
p.x += utf8.RuneCountInString(text) * glyph
if p.lineDots > 0 {
p.x %= p.lineDots
}
}
// endLine finishes a partially printed line so the next element starts at
// the left margin.
func (p *printer) endLine() {
if p.x > 0 {
p.lineFeed()
}
}