Files
uberbringer/internal/pkg/escpos/codepage.go
T
57_WolveandClaude Opus 5.5 4562f0cebb
Security / Vulnerability check (push) Successful in 50s
Test / Lint and test (push) Successful in 1m59s
Add box, rule and kv blocks, text folding and receipt preview
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>
2026-11-30 00:49:45 -06:00

148 lines
3.6 KiB
Go

package escpos
import (
"fmt"
"strings"
"unicode/utf8"
"golang.org/x/text/encoding/charmap"
)
// CodePage is a printer character table. It ties the ESC t table number the
// printer understands to the character map used to transcode UTF-8 text, so
// the two can never disagree.
type CodePage int
// Supported code pages. CodePage437 is the Epson factory default.
const (
CodePage437 CodePage = iota + 1
CodePage850
CodePage858
CodePage1252
)
// ParseCodePage returns the code page named by name, e.g. "cp437".
func ParseCodePage(name string) (CodePage, error) {
switch strings.ToLower(strings.TrimSpace(name)) {
case "cp437", "437", "pc437":
return CodePage437, nil
case "cp850", "850", "pc850":
return CodePage850, nil
case "cp858", "858", "pc858":
return CodePage858, nil
case "cp1252", "1252", "wpc1252", "windows-1252":
return CodePage1252, nil
}
return 0, fmt.Errorf("%w: unknown code page %q (want cp437, cp850, cp858 or cp1252)",
ErrInvalidArgument, name)
}
// String returns the canonical code page name.
func (cp CodePage) String() string {
switch cp {
case CodePage437:
return "cp437"
case CodePage850:
return "cp850"
case CodePage858:
return "cp858"
case CodePage1252:
return "cp1252"
}
return fmt.Sprintf("CodePage(%d)", int(cp))
}
// table returns the ESC t table number for cp.
func (cp CodePage) table() byte {
switch cp {
case CodePage850:
return 2
case CodePage858:
return 19
case CodePage1252:
return 16
}
return 0 // PC437, also the fallback for an invalid CodePage.
}
func (cp CodePage) charmap() *charmap.Charmap {
switch cp {
case CodePage850:
return charmap.CodePage850
case CodePage858:
return charmap.CodePage858
case CodePage1252:
return charmap.Windows1252
}
return charmap.CodePage437
}
// Encode transcodes UTF-8 text to cp, one byte per rune. Runes the code page
// cannot represent become '?'. Control characters other than newline and tab
// are dropped, because the printer would interpret them as commands.
func (cp CodePage) Encode(s string) []byte {
cm := cp.charmap()
out := make([]byte, 0, len(s))
for _, r := range s {
switch {
case r == '\n' || r == '\t':
out = append(out, byte(r))
case IsControl(r):
// Dropped: control bytes would be read as printer commands.
case r < utf8.RuneSelf:
out = append(out, byte(r))
default:
c, ok := cm.EncodeRune(r)
if !ok || c < 0x20 || c == 0x7F {
c = '?'
}
out = append(out, c)
}
}
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 {
if r == '\n' || r == '\t' {
return false
}
return r < 0x20 || r == 0x7F || (r >= 0x80 && r < 0xA0) || r == utf8.RuneError
}