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

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