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>
557 lines
14 KiB
Go
557 lines
14 KiB
Go
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)
|
|
}
|