Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s
CI / Lint, test and scan (push) Successful in 1m41s
Restructure the daemon to follow the project's Go coding standards and
expand its features.
Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.
Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
with live printer status, `secret` and `token` subcommands.
Fixes
- Jobs are validated before anything is sent; a failed printer dial no
longer panics.
- Request logs never contain tokens; Sentry no longer receives the
Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
dedicated user and uses a current nginx TLS config.
config.toml is no longer tracked; start from configs/config.example.toml.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bb73348433
commit
6502d9551d
807 files changed
+6659
-500291
No files matched your search
@@ -0,0 +1,389 @@
|
||||
// Package receipt defines print jobs, validates them, and lays them out as
|
||||
// ESC/POS command streams with code page transcoding and word wrapping.
|
||||
package receipt
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// Element types.
|
||||
const (
|
||||
TypeText = "text"
|
||||
TypeFeed = "feed"
|
||||
TypeQR = "qr"
|
||||
TypeBarcode = "barcode"
|
||||
TypeImage = "image"
|
||||
TypeRaw = "raw"
|
||||
TypeCut = "cut"
|
||||
)
|
||||
|
||||
// Job limits.
|
||||
const (
|
||||
MaxElements = 500
|
||||
MaxCopies = 5
|
||||
)
|
||||
|
||||
// Element defaults.
|
||||
const (
|
||||
defaultQRSize = 6
|
||||
defaultBarcodeHeight = 80
|
||||
defaultBarcodeWidth = 3
|
||||
)
|
||||
|
||||
// Job is a receipt to print.
|
||||
type Job struct {
|
||||
Elements []Element `json:"elements"`
|
||||
|
||||
// Copies is how many times the receipt is printed, each with its own
|
||||
// cut. Zero means one.
|
||||
Copies int `json:"copies,omitempty"`
|
||||
}
|
||||
|
||||
// Element is one item on a receipt. Type selects which fields apply; fields
|
||||
// that do not apply to the type are ignored. Width and Height mean character
|
||||
// multipliers for text, module width and bar height for barcodes, and target
|
||||
// width in dots for images.
|
||||
type Element struct {
|
||||
Type string `json:"type"`
|
||||
|
||||
// Text.
|
||||
Text string `json:"text,omitempty"`
|
||||
Bold bool `json:"bold,omitempty"`
|
||||
Size int `json:"size,omitempty"`
|
||||
Width int `json:"width,omitempty"`
|
||||
Height int `json:"height,omitempty"`
|
||||
Font string `json:"font,omitempty"`
|
||||
Align string `json:"align,omitempty"`
|
||||
Underline int `json:"underline,omitempty"`
|
||||
Invert bool `json:"invert,omitempty"`
|
||||
Newline *bool `json:"newline,omitempty"`
|
||||
Wrap *bool `json:"wrap,omitempty"`
|
||||
|
||||
// Feed.
|
||||
Lines int `json:"lines,omitempty"`
|
||||
|
||||
// QR code and barcode.
|
||||
Data string `json:"data,omitempty"`
|
||||
Correction string `json:"correction,omitempty"`
|
||||
Symbology string `json:"symbology,omitempty"`
|
||||
HRI string `json:"hri,omitempty"`
|
||||
|
||||
// Image.
|
||||
URL string `json:"url,omitempty"`
|
||||
Base64 string `json:"base64,omitempty"`
|
||||
|
||||
// Raw.
|
||||
Hex string `json:"hex,omitempty"`
|
||||
|
||||
// Cut.
|
||||
Mode string `json:"mode,omitempty"`
|
||||
}
|
||||
|
||||
// ValidationError lists every problem found in a job.
|
||||
type ValidationError struct {
|
||||
Problems []string
|
||||
}
|
||||
|
||||
// Error implements error.
|
||||
func (e *ValidationError) Error() string {
|
||||
return "invalid job: " + strings.Join(e.Problems, "; ")
|
||||
}
|
||||
|
||||
// Validate checks the whole job and reports every problem, so nothing is sent
|
||||
// to the printer unless the entire receipt can be printed.
|
||||
func (j Job) Validate() error {
|
||||
var problems []string
|
||||
switch {
|
||||
case len(j.Elements) == 0:
|
||||
problems = append(problems, "elements: at least one element is required")
|
||||
case len(j.Elements) > MaxElements:
|
||||
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", len(j.Elements), MaxElements))
|
||||
}
|
||||
if j.Copies < 0 || j.Copies > MaxCopies {
|
||||
problems = append(problems, fmt.Sprintf("copies must be 1-%d", MaxCopies))
|
||||
}
|
||||
for i, el := range j.Elements {
|
||||
if err := el.validate(); err != nil {
|
||||
problems = append(problems, fmt.Sprintf("elements[%d] (%s): %v", i, el.Type, err))
|
||||
}
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return &ValidationError{Problems: problems}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j Job) copies() int {
|
||||
return max(j.Copies, 1)
|
||||
}
|
||||
|
||||
func (el Element) validate() error {
|
||||
var err error
|
||||
switch el.Type {
|
||||
case TypeText:
|
||||
_, err = el.textSpec()
|
||||
case TypeFeed:
|
||||
_, err = el.feedLines()
|
||||
case TypeQR:
|
||||
_, err = el.qrSpec()
|
||||
case TypeBarcode:
|
||||
_, err = el.barcodeSpec()
|
||||
case TypeImage:
|
||||
_, err = el.imageSpec()
|
||||
case TypeRaw:
|
||||
_, err = el.rawBytes()
|
||||
case TypeCut:
|
||||
_, err = el.cutMode()
|
||||
case "":
|
||||
err = fmt.Errorf("type is required")
|
||||
default:
|
||||
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw or cut)", el.Type)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type textSpec struct {
|
||||
width, height int
|
||||
bold bool
|
||||
font escpos.Font
|
||||
align escpos.Justification
|
||||
underline escpos.Underline
|
||||
invert bool
|
||||
newline bool
|
||||
wrap bool
|
||||
}
|
||||
|
||||
func (el Element) textSpec() (textSpec, error) {
|
||||
s := textSpec{
|
||||
width: 1,
|
||||
height: 1,
|
||||
bold: el.Bold,
|
||||
invert: el.Invert,
|
||||
newline: el.Newline == nil || *el.Newline,
|
||||
wrap: el.Wrap == nil || *el.Wrap,
|
||||
}
|
||||
if el.Size != 0 {
|
||||
s.width, s.height = el.Size, el.Size
|
||||
}
|
||||
if el.Width != 0 {
|
||||
s.width = el.Width
|
||||
}
|
||||
if el.Height != 0 {
|
||||
s.height = el.Height
|
||||
}
|
||||
if s.width < 1 || s.width > escpos.MaxCharacterScale || s.height < 1 || s.height > escpos.MaxCharacterScale {
|
||||
return s, fmt.Errorf("size, width and height must be 1-%d", escpos.MaxCharacterScale)
|
||||
}
|
||||
var err error
|
||||
if s.font, err = parseFont(el.Font); err != nil {
|
||||
return s, err
|
||||
}
|
||||
if s.align, err = parseAlign(el.Align); err != nil {
|
||||
return s, err
|
||||
}
|
||||
switch el.Underline {
|
||||
case 0, 1, 2:
|
||||
s.underline = escpos.Underline(el.Underline)
|
||||
default:
|
||||
return s, fmt.Errorf("underline must be 0, 1 or 2")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (el Element) feedLines() (uint8, error) {
|
||||
switch {
|
||||
case el.Lines == 0:
|
||||
return 1, nil
|
||||
case el.Lines < 1 || el.Lines > 255:
|
||||
return 0, fmt.Errorf("lines must be 1-255")
|
||||
}
|
||||
return uint8(el.Lines), nil
|
||||
}
|
||||
|
||||
type qrSpec struct {
|
||||
size int
|
||||
correction escpos.QRCorrection
|
||||
align escpos.Justification
|
||||
}
|
||||
|
||||
func (el Element) qrSpec() (qrSpec, error) {
|
||||
s := qrSpec{size: defaultQRSize, correction: escpos.QRCorrectionM}
|
||||
if el.Size != 0 {
|
||||
s.size = el.Size
|
||||
}
|
||||
switch {
|
||||
case el.Data == "":
|
||||
return s, fmt.Errorf("data is required")
|
||||
case len(el.Data) > escpos.MaxQRData:
|
||||
return s, fmt.Errorf("data is %d bytes, limit is %d", len(el.Data), escpos.MaxQRData)
|
||||
case s.size < escpos.MinQRModuleSize || s.size > escpos.MaxQRModuleSize:
|
||||
return s, fmt.Errorf("size must be %d-%d", escpos.MinQRModuleSize, escpos.MaxQRModuleSize)
|
||||
}
|
||||
var err error
|
||||
if el.Correction != "" {
|
||||
if s.correction, err = escpos.ParseQRCorrection(el.Correction); err != nil {
|
||||
return s, fmt.Errorf("correction must be L, M, Q or H")
|
||||
}
|
||||
}
|
||||
if s.align, err = parseAlign(el.Align); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type barcodeSpec struct {
|
||||
symbology escpos.Symbology
|
||||
height int
|
||||
width int
|
||||
hri escpos.HRIPosition
|
||||
align escpos.Justification
|
||||
}
|
||||
|
||||
func (el Element) barcodeSpec() (barcodeSpec, error) {
|
||||
s := barcodeSpec{height: defaultBarcodeHeight, width: defaultBarcodeWidth, hri: escpos.HRIBelow}
|
||||
if el.Symbology == "" {
|
||||
return s, fmt.Errorf("symbology is required (ean13, ean8, upca, upce, code39 or code128)")
|
||||
}
|
||||
var err error
|
||||
if s.symbology, err = escpos.ParseSymbology(el.Symbology); err != nil {
|
||||
return s, fmt.Errorf("unknown symbology %q (want ean13, ean8, upca, upce, code39 or code128)", el.Symbology)
|
||||
}
|
||||
if err := escpos.ValidateBarcode(s.symbology, el.Data); err != nil {
|
||||
return s, fmt.Errorf("data: %w", err)
|
||||
}
|
||||
if el.Height != 0 {
|
||||
s.height = el.Height
|
||||
}
|
||||
if el.Width != 0 {
|
||||
s.width = el.Width
|
||||
}
|
||||
if s.height < 1 || s.height > 255 {
|
||||
return s, fmt.Errorf("height must be 1-255 dots")
|
||||
}
|
||||
if s.width < escpos.MinBarcodeWidth || s.width > escpos.MaxBarcodeWidth {
|
||||
return s, fmt.Errorf("width must be %d-%d", escpos.MinBarcodeWidth, escpos.MaxBarcodeWidth)
|
||||
}
|
||||
switch strings.ToLower(el.HRI) {
|
||||
case "", "below":
|
||||
s.hri = escpos.HRIBelow
|
||||
case "none":
|
||||
s.hri = escpos.HRINone
|
||||
case "above":
|
||||
s.hri = escpos.HRIAbove
|
||||
case "both":
|
||||
s.hri = escpos.HRIBoth
|
||||
default:
|
||||
return s, fmt.Errorf("hri must be none, above, below or both")
|
||||
}
|
||||
if s.align, err = parseAlign(el.Align); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type imageSpec struct {
|
||||
url string
|
||||
data []byte
|
||||
width int
|
||||
align escpos.Justification
|
||||
}
|
||||
|
||||
func (el Element) imageSpec() (imageSpec, error) {
|
||||
s := imageSpec{width: el.Width}
|
||||
switch {
|
||||
case el.URL != "" && el.Base64 != "":
|
||||
return s, fmt.Errorf("set url or base64, not both")
|
||||
case el.URL != "":
|
||||
u, err := url.Parse(el.URL)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return s, fmt.Errorf("url must be an absolute http or https URL")
|
||||
}
|
||||
s.url = el.URL
|
||||
case el.Base64 != "":
|
||||
data, err := decodeBase64Image(el.Base64)
|
||||
if err != nil {
|
||||
return s, fmt.Errorf("base64: %w", err)
|
||||
}
|
||||
s.data = data
|
||||
default:
|
||||
return s, fmt.Errorf("url or base64 is required")
|
||||
}
|
||||
if s.width < 0 {
|
||||
return s, fmt.Errorf("width must be positive")
|
||||
}
|
||||
var err error
|
||||
if s.align, err = parseAlign(el.Align); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// decodeBase64Image accepts standard base64, with or without padding, and
|
||||
// data URIs such as "data:image/png;base64,....".
|
||||
func decodeBase64Image(s string) ([]byte, error) {
|
||||
if rest, ok := strings.CutPrefix(s, "data:"); ok {
|
||||
_, payload, found := strings.Cut(rest, ",")
|
||||
if !found {
|
||||
return nil, fmt.Errorf("malformed data URI")
|
||||
}
|
||||
s = payload
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if data, err := base64.StdEncoding.DecodeString(s); err == nil {
|
||||
return data, nil
|
||||
}
|
||||
data, err := base64.RawStdEncoding.DecodeString(strings.TrimRight(s, "="))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("not valid base64")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (el Element) rawBytes() ([]byte, error) {
|
||||
if el.Hex == "" {
|
||||
return nil, fmt.Errorf("hex is required")
|
||||
}
|
||||
data, err := hex.DecodeString(strings.ReplaceAll(el.Hex, " ", ""))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hex: %v", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (el Element) cutMode() (escpos.CutMode, error) {
|
||||
switch strings.ToLower(el.Mode) {
|
||||
case "", "partial":
|
||||
return escpos.CutPartial, nil
|
||||
case "full":
|
||||
return escpos.CutFull, nil
|
||||
}
|
||||
return 0, fmt.Errorf("mode must be partial or full")
|
||||
}
|
||||
|
||||
func parseAlign(s string) (escpos.Justification, error) {
|
||||
switch strings.ToLower(s) {
|
||||
case "", "left":
|
||||
return escpos.JustifyLeft, nil
|
||||
case "center", "centre":
|
||||
return escpos.JustifyCenter, nil
|
||||
case "right":
|
||||
return escpos.JustifyRight, nil
|
||||
}
|
||||
return 0, fmt.Errorf("align must be left, center or right")
|
||||
}
|
||||
|
||||
func parseFont(s string) (escpos.Font, error) {
|
||||
switch strings.ToLower(s) {
|
||||
case "", "a":
|
||||
return escpos.FontA, nil
|
||||
case "b":
|
||||
return escpos.FontB, nil
|
||||
}
|
||||
return 0, fmt.Errorf("font must be a or b")
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package receipt
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// tabWidth matches the printer's default horizontal tab stops.
|
||||
const tabWidth = 8
|
||||
|
||||
// sanitize removes control characters that would be read as printer
|
||||
// commands, keeping newlines and tabs, and normalises CRLF to LF.
|
||||
func sanitize(s string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
if escpos.IsControl(r) {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
}
|
||||
|
||||
// expandTabs replaces tabs with spaces up to the next tab stop. startCol is
|
||||
// the column the text starts at; columns restart at zero after a newline.
|
||||
func expandTabs(s string, startCol int) string {
|
||||
if !strings.ContainsRune(s, '\t') {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
col := startCol
|
||||
for _, r := range s {
|
||||
switch r {
|
||||
case '\t':
|
||||
n := tabWidth - col%tabWidth
|
||||
b.WriteString(strings.Repeat(" ", n))
|
||||
col += n
|
||||
case '\n':
|
||||
b.WriteRune(r)
|
||||
col = 0
|
||||
default:
|
||||
b.WriteRune(r)
|
||||
col++
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// wrap breaks text into lines of at most width runes, so that no word is
|
||||
// split across lines. The first line has only first runes available, because
|
||||
// it continues whatever is already on the current printer line. A first line
|
||||
// of "" means the text must start on a fresh line.
|
||||
//
|
||||
// Spaces at a break are dropped, each newline-separated paragraph wraps on
|
||||
// its own, and leading indentation on a paragraph is kept. Only a word longer
|
||||
// than a whole line is split, at the line edge.
|
||||
func wrap(text string, first, width int) []string {
|
||||
width = max(width, 1)
|
||||
first = min(max(first, 0), width)
|
||||
var lines []string
|
||||
for i, para := range strings.Split(text, "\n") {
|
||||
avail := width
|
||||
if i == 0 {
|
||||
avail = first
|
||||
}
|
||||
lines = append(lines, wrapParagraph([]rune(para), avail, width)...)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func wrapParagraph(para []rune, first, width int) []string {
|
||||
var (
|
||||
lines []string
|
||||
line []rune
|
||||
avail = first
|
||||
// pending records a break point: spaces that did not fit were
|
||||
// dropped, so the next word must start a new line.
|
||||
pending bool
|
||||
)
|
||||
breakLine := func() {
|
||||
lines = append(lines, string(trimTrailingSpaces(line)))
|
||||
line = line[:0]
|
||||
avail = width
|
||||
pending = false
|
||||
}
|
||||
|
||||
for _, tok := range tokenize(para) {
|
||||
if tok[0] == ' ' {
|
||||
switch {
|
||||
case len(line) == 0 && len(lines) > 0:
|
||||
// Spaces at the start of a wrapped line are dropped.
|
||||
case !pending && len(line)+len(tok) <= avail:
|
||||
line = append(line, tok...)
|
||||
case len(line) > 0:
|
||||
pending = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if pending {
|
||||
breakLine()
|
||||
}
|
||||
if len(line)+len(tok) > avail {
|
||||
if len(line) > 0 || avail < width {
|
||||
breakLine()
|
||||
}
|
||||
for len(tok) > width {
|
||||
line = append(line, tok[:width]...)
|
||||
breakLine()
|
||||
tok = tok[width:]
|
||||
}
|
||||
}
|
||||
line = append(line, tok...)
|
||||
}
|
||||
return append(lines, string(line))
|
||||
}
|
||||
|
||||
// tokenize splits s into alternating runs of spaces and non-spaces.
|
||||
func tokenize(s []rune) [][]rune {
|
||||
var tokens [][]rune
|
||||
start := 0
|
||||
for i := 1; i <= len(s); i++ {
|
||||
if i == len(s) || (s[i] == ' ') != (s[start] == ' ') {
|
||||
tokens = append(tokens, s[start:i])
|
||||
start = i
|
||||
}
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
|
||||
func trimTrailingSpaces(r []rune) []rune {
|
||||
end := len(r)
|
||||
for end > 0 && r[end-1] == ' ' {
|
||||
end--
|
||||
}
|
||||
return r[:end]
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package receipt
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
text string
|
||||
first, width int
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "fits", text: "hello world", first: 48, width: 48,
|
||||
want: []string{"hello world"},
|
||||
},
|
||||
{
|
||||
name: "breaks at word boundary", text: "the quick brown fox", first: 10, width: 10,
|
||||
want: []string{"the quick", "brown fox"},
|
||||
},
|
||||
{
|
||||
name: "never splits a word that fits on a line",
|
||||
text: "Thank you for shopping with us today", first: 12, width: 12,
|
||||
want: []string{"Thank you", "for shopping", "with us", "today"},
|
||||
},
|
||||
{
|
||||
name: "hard splits only words longer than a line", text: "see https://example.com/very/long ok", first: 12, width: 12,
|
||||
want: []string{"see", "https://exam", "ple.com/very", "/long ok"},
|
||||
},
|
||||
{
|
||||
name: "runs of spaces kept inside a line", text: "a b", first: 10, width: 10,
|
||||
want: []string{"a b"},
|
||||
},
|
||||
{
|
||||
name: "spaces at a break are dropped", text: "aaaa b", first: 5, width: 5,
|
||||
want: []string{"aaaa", "b"},
|
||||
},
|
||||
{
|
||||
name: "paragraphs wrap independently", text: "one two\n\nthree", first: 5, width: 5,
|
||||
want: []string{"one", "two", "", "three"},
|
||||
},
|
||||
{
|
||||
name: "indent kept on first line only", text: " indented text here", first: 10, width: 10,
|
||||
want: []string{" indented", "text here"},
|
||||
},
|
||||
{
|
||||
name: "inline continuation fits", text: " world", first: 6, width: 10,
|
||||
want: []string{" world"},
|
||||
},
|
||||
{
|
||||
name: "inline continuation breaks before the word", text: "world", first: 3, width: 10,
|
||||
want: []string{"", "world"},
|
||||
},
|
||||
{
|
||||
name: "inline continuation keeps filling then wraps", text: " big wide world", first: 8, width: 10,
|
||||
want: []string{" big", "wide world"},
|
||||
},
|
||||
{
|
||||
name: "trailing space kept for inline use", text: "Total: ", first: 48, width: 48,
|
||||
want: []string{"Total: "},
|
||||
},
|
||||
{
|
||||
name: "empty", text: "", first: 10, width: 10,
|
||||
want: []string{""},
|
||||
},
|
||||
{
|
||||
name: "unicode counted as runes", text: "Grüße an Übermorgen", first: 10, width: 10,
|
||||
want: []string{"Grüße an", "Übermorgen"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := wrap(tt.text, tt.first, tt.width)
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("wrap(%q, %d, %d) = %q, want %q", tt.text, tt.first, tt.width, got, tt.want)
|
||||
}
|
||||
for i, line := range got {
|
||||
limit := tt.width
|
||||
if i == 0 {
|
||||
limit = tt.first
|
||||
}
|
||||
if n := len([]rune(line)); n > limit {
|
||||
t.Errorf("line %d %q has %d runes, limit %d", i, line, n, limit)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandTabs(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
start int
|
||||
want string
|
||||
}{
|
||||
{"a\tb", 0, "a b"},
|
||||
{"abcdefgh\tx", 0, "abcdefgh x"},
|
||||
{"\tx", 3, " x"},
|
||||
{"a\n\tb", 5, "a\n b"},
|
||||
{"none", 0, "none"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := expandTabs(tt.in, tt.start); got != tt.want {
|
||||
t.Errorf("expandTabs(%q, %d) = %q, want %q", tt.in, tt.start, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitize(t *testing.T) {
|
||||
if got := sanitize("a\x1b@b\r\n\tc\x00"); got != "a@b\n\tc" {
|
||||
t.Errorf("sanitize = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
package receipt_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
type fakeFetcher struct {
|
||||
data []byte
|
||||
err error
|
||||
urls []string
|
||||
}
|
||||
|
||||
func (f *fakeFetcher) Fetch(_ context.Context, url string) ([]byte, error) {
|
||||
f.urls = append(f.urls, url)
|
||||
return f.data, f.err
|
||||
}
|
||||
|
||||
func newRenderer(t *testing.T, fetcher receipt.Fetcher) *receipt.Renderer {
|
||||
t.Helper()
|
||||
profile, err := escpos.LookupProfile("tm-t20")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return receipt.NewRenderer(receipt.Options{
|
||||
Profile: profile,
|
||||
CodePage: escpos.CodePage437,
|
||||
MaxPixels: 10_000_000,
|
||||
MaxHeight: 4000,
|
||||
}, fetcher)
|
||||
}
|
||||
|
||||
func pngData(t *testing.T, w, h int) []byte {
|
||||
t.Helper()
|
||||
img := image.NewGray(image.Rect(0, 0, w, h))
|
||||
for i := range img.Pix {
|
||||
img.Pix[i] = 0xFF
|
||||
}
|
||||
img.SetGray(0, 0, color.Gray{})
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func boolPtr(b bool) *bool { return &b }
|
||||
|
||||
var (
|
||||
initialize = []byte{0x1B, 0x40}
|
||||
selectCP437 = []byte{0x1B, 0x74, 0}
|
||||
partialCut = []byte{0x1D, 0x56, 66, 0}
|
||||
sizeOne = []byte{0x1D, 0x21, 0x00}
|
||||
sizeTwo = []byte{0x1D, 0x21, 0x11}
|
||||
justifyLeft = []byte{0x1B, 0x61, 0}
|
||||
justifyRight = []byte{0x1B, 0x61, 2}
|
||||
)
|
||||
|
||||
func render(t *testing.T, job receipt.Job) []byte {
|
||||
t.Helper()
|
||||
out, err := newRenderer(t, &fakeFetcher{}).Render(context.Background(), job)
|
||||
if err != nil {
|
||||
t.Fatalf("Render: %v", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// printedLines returns the text the printer would print between line feeds,
|
||||
// with ESC/POS commands removed. It understands only the commands the
|
||||
// renderer emits for text jobs.
|
||||
func printedLines(t *testing.T, out []byte) []string {
|
||||
t.Helper()
|
||||
var lines []string
|
||||
var cur []byte
|
||||
for i := 0; i < len(out); i++ {
|
||||
switch c := out[i]; c {
|
||||
case 0x1B: // ESC x n, or ESC @ / ESC 2
|
||||
switch out[i+1] {
|
||||
case '@', '2':
|
||||
i++
|
||||
default:
|
||||
i += 2
|
||||
}
|
||||
case 0x1D: // GS x n, or GS V m n
|
||||
if out[i+1] == 'V' {
|
||||
i += 3
|
||||
} else {
|
||||
i += 2
|
||||
}
|
||||
case 0x0A:
|
||||
lines = append(lines, string(cur))
|
||||
cur = nil
|
||||
default:
|
||||
cur = append(cur, c)
|
||||
}
|
||||
}
|
||||
if len(cur) > 0 {
|
||||
lines = append(lines, string(cur))
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func TestRenderTextJob(t *testing.T) {
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "Hi"}}})
|
||||
if !bytes.HasPrefix(out, append(append([]byte{}, initialize...), selectCP437...)) {
|
||||
t.Errorf("stream must start with ESC @ and ESC t 0, got % X", out[:min(5, len(out))])
|
||||
}
|
||||
if !bytes.HasSuffix(out, partialCut) {
|
||||
t.Errorf("stream must end with a partial cut, got % X", out[len(out)-4:])
|
||||
}
|
||||
if got := printedLines(t, out); len(got) != 1 || got[0] != "Hi" {
|
||||
t.Errorf("printed %q, want [\"Hi\"]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderTranscodesToCodePage437(t *testing.T) {
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "┌─┐ Ü 🎉"}}})
|
||||
if !bytes.Contains(out, []byte{0xDA, 0xC4, 0xBF, ' ', 0x9A, ' ', '?'}) {
|
||||
t.Errorf("CP437 bytes not found in % X", out)
|
||||
}
|
||||
if bytes.Contains(out, []byte("┌")) {
|
||||
t.Error("raw UTF-8 leaked into the stream")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderWrapsAtPaperWidth(t *testing.T) {
|
||||
paragraph := strings.Repeat("lorem ipsum dolor sit amet ", 12)
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "text", Text: paragraph},
|
||||
{Type: "text", Text: paragraph, Size: 2},
|
||||
}})
|
||||
lines := printedLines(t, out)
|
||||
if len(lines) < 4 {
|
||||
t.Fatalf("expected wrapped output, got %q", lines)
|
||||
}
|
||||
words := map[string]bool{"lorem": true, "ipsum": true, "dolor": true, "sit": true, "amet": true}
|
||||
for _, line := range lines {
|
||||
if len(line) > 48 {
|
||||
t.Errorf("line %q is %d chars, Font A size 1 fits 48", line, len(line))
|
||||
}
|
||||
for _, word := range strings.Fields(line) {
|
||||
if !words[word] {
|
||||
t.Errorf("word %q was split across lines", word)
|
||||
}
|
||||
}
|
||||
}
|
||||
sizeTwoStart := bytes.Index(out, sizeTwo)
|
||||
for _, line := range printedLines(t, out[sizeTwoStart:]) {
|
||||
if len(line) > 24 {
|
||||
t.Errorf("size-2 line %q is %d chars, limit 24", line, len(line))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderInlineTextContinuesLine(t *testing.T) {
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "text", Text: "Total: ", Newline: boolPtr(false)},
|
||||
{Type: "text", Text: "£5.00", Bold: true},
|
||||
}})
|
||||
if got := printedLines(t, out); len(got) != 1 || got[0] != "Total: \x9C5.00" {
|
||||
t.Errorf("printed %q, want one line", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderInlineMixedSizesWraps(t *testing.T) {
|
||||
// 40 Font A columns used, then a size-2 word needing 2x6 = 12 columns:
|
||||
// it cannot fit in the remaining 8 and must move to the next line.
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "text", Text: strings.Repeat("x", 40), Newline: boolPtr(false)},
|
||||
{Type: "text", Text: "BIGONE", Size: 2},
|
||||
}})
|
||||
lines := printedLines(t, out)
|
||||
if len(lines) != 2 || lines[0] != strings.Repeat("x", 40) || lines[1] != "BIGONE" {
|
||||
t.Errorf("printed %q", lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderNoWrap(t *testing.T) {
|
||||
long := strings.Repeat("y", 60)
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: long, Wrap: boolPtr(false)}}})
|
||||
if got := printedLines(t, out); len(got) != 1 || got[0] != long {
|
||||
t.Errorf("printed %q, want the text untouched", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderTextStyles(t *testing.T) {
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "text", Text: "x", Bold: true, Underline: 2, Invert: true, Align: "right", Font: "b"},
|
||||
}})
|
||||
for name, cmd := range map[string][]byte{
|
||||
"bold": {0x1B, 0x45, 1},
|
||||
"underline": {0x1B, 0x2D, 2},
|
||||
"reverse": {0x1D, 0x42, 1},
|
||||
"font b": {0x1B, 0x4D, 1},
|
||||
"right": justifyRight,
|
||||
} {
|
||||
if !bytes.Contains(out, cmd) {
|
||||
t.Errorf("%s command % X missing", name, cmd)
|
||||
}
|
||||
}
|
||||
// Styles are reset after the element.
|
||||
if !bytes.Contains(out, append([]byte{0x1B, 0x45, 0, 0x1B, 0x2D, 0, 0x1D, 0x42, 0}, sizeOne...)) {
|
||||
t.Error("styles not reset after text")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderElements(t *testing.T) {
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "feed", Lines: 3},
|
||||
{Type: "qr", Data: "https://example.com", Align: "center"},
|
||||
{Type: "barcode", Symbology: "code128", Data: "ABC-1"},
|
||||
{Type: "raw", Hex: "1B 40"},
|
||||
{Type: "cut", Mode: "full"},
|
||||
}})
|
||||
for name, cmd := range map[string][]byte{
|
||||
"feed": {0x1B, 0x64, 3},
|
||||
"qr store": append([]byte{0x1D, 0x28, 0x6B, 22, 0, 0x31, 0x50, 0x30}, "https://example.com"...),
|
||||
"barcode": append([]byte{0x1D, 0x6B, 73, 7}, "{BABC-1"...),
|
||||
"width": {0x1D, 0x77, 3},
|
||||
"full cut": {0x1D, 0x56, 65, 0},
|
||||
} {
|
||||
if !bytes.Contains(out, cmd) {
|
||||
t.Errorf("%s command % X missing", name, cmd)
|
||||
}
|
||||
}
|
||||
if bytes.HasSuffix(out, partialCut) {
|
||||
t.Error("an explicit final cut must not be followed by another")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderCopies(t *testing.T) {
|
||||
out := render(t, receipt.Job{Copies: 3, Elements: []receipt.Element{{Type: "text", Text: "copy"}}})
|
||||
if n := bytes.Count(out, partialCut); n != 3 {
|
||||
t.Errorf("%d cuts, want 3", n)
|
||||
}
|
||||
if n := bytes.Count(out, initialize); n != 1 {
|
||||
t.Errorf("%d initialize commands, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderBase64ImageCentered(t *testing.T) {
|
||||
data := base64.StdEncoding.EncodeToString(pngData(t, 100, 10))
|
||||
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "image", Base64: data, Align: "center"}}})
|
||||
// The image is placed on a full-width 576-dot (72-byte) canvas.
|
||||
header := []byte{0x1D, 0x76, 0x30, 0, 72, 0, 10, 0}
|
||||
i := bytes.Index(out, header)
|
||||
if i < 0 {
|
||||
t.Fatalf("raster header % X not found", header)
|
||||
}
|
||||
if !bytes.Contains(out[:i], justifyLeft) {
|
||||
t.Error("image must be sent left-justified; alignment is in the bitmap")
|
||||
}
|
||||
// The dark pixel at x=0 lands at x=(576-100)/2=238: byte 29, bit 6.
|
||||
if got := out[i+8+29]; got != 0x02 {
|
||||
t.Errorf("first row byte 29 = %08b, want 00000010", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderImageFromURL(t *testing.T) {
|
||||
fetcher := &fakeFetcher{data: pngData(t, 1200, 300)}
|
||||
out, err := newRenderer(t, fetcher).Render(context.Background(), receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "image", URL: "https://images.example/logo.png"},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fetcher.urls) != 1 || fetcher.urls[0] != "https://images.example/logo.png" {
|
||||
t.Errorf("fetched %v", fetcher.urls)
|
||||
}
|
||||
// Scaled down to 576 dots wide, 144 tall.
|
||||
if !bytes.Contains(out, []byte{0x1D, 0x76, 0x30, 0, 72, 0, 144, 0}) {
|
||||
t.Error("scaled raster header not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderFetchFailureProducesNothing(t *testing.T) {
|
||||
fetchErr := errors.New("blocked")
|
||||
out, err := newRenderer(t, &fakeFetcher{err: fetchErr}).Render(context.Background(), receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "text", Text: "before"},
|
||||
{Type: "image", URL: "https://images.example/x.png"},
|
||||
}})
|
||||
if !errors.Is(err, fetchErr) || out != nil {
|
||||
t.Errorf("Render = %d bytes, %v; want nil and the fetch error", len(out), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
job receipt.Job
|
||||
wantErr string
|
||||
}{
|
||||
{"no elements", receipt.Job{}, "at least one element"},
|
||||
{"too many copies", receipt.Job{Copies: 6, Elements: []receipt.Element{{Type: "cut"}}}, "copies must be 1-5"},
|
||||
{"missing type", receipt.Job{Elements: []receipt.Element{{}}}, "type is required"},
|
||||
{"unknown type", receipt.Job{Elements: []receipt.Element{{Type: "sparkle"}}}, `unknown type "sparkle"`},
|
||||
{"text size", receipt.Job{Elements: []receipt.Element{{Type: "text", Size: 9}}}, "elements[0] (text): size, width and height must be 1-8"},
|
||||
{"text align", receipt.Job{Elements: []receipt.Element{{Type: "text", Align: "middle"}}}, "align must be left, center or right"},
|
||||
{"text font", receipt.Job{Elements: []receipt.Element{{Type: "text", Font: "c"}}}, "font must be a or b"},
|
||||
{"underline", receipt.Job{Elements: []receipt.Element{{Type: "text", Underline: 3}}}, "underline must be 0, 1 or 2"},
|
||||
{"feed lines", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 300}}}, "lines must be 1-255"},
|
||||
{"qr data", receipt.Job{Elements: []receipt.Element{{Type: "qr"}}}, "data is required"},
|
||||
{"qr size", receipt.Job{Elements: []receipt.Element{{Type: "qr", Data: "x", Size: 17}}}, "size must be 1-16"},
|
||||
{"qr correction", receipt.Job{Elements: []receipt.Element{{Type: "qr", Data: "x", Correction: "Z"}}}, "correction must be L, M, Q or H"},
|
||||
{"barcode symbology", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Data: "1"}}}, "symbology is required"},
|
||||
{"barcode data", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Symbology: "ean13", Data: "12"}}}, "want 12 or 13 digits"},
|
||||
{"barcode width", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Symbology: "code39", Data: "A", Width: 9}}}, "width must be 2-6"},
|
||||
{"image source", receipt.Job{Elements: []receipt.Element{{Type: "image"}}}, "url or base64 is required"},
|
||||
{"image both", receipt.Job{Elements: []receipt.Element{{Type: "image", URL: "https://x/y", Base64: "AA=="}}}, "not both"},
|
||||
{"image scheme", receipt.Job{Elements: []receipt.Element{{Type: "image", URL: "file:///etc/passwd"}}}, "http or https"},
|
||||
{"image base64", receipt.Job{Elements: []receipt.Element{{Type: "image", Base64: "!!!"}}}, "not valid base64"},
|
||||
{"raw hex", receipt.Job{Elements: []receipt.Element{{Type: "raw", Hex: "zz"}}}, "hex:"},
|
||||
{"cut mode", receipt.Job{Elements: []receipt.Element{{Type: "cut", Mode: "half"}}}, "mode must be partial or full"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.job.Validate()
|
||||
var ve *receipt.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("err = %v, want *ValidationError", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("err = %q, want it to contain %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateReportsEveryProblem(t *testing.T) {
|
||||
err := receipt.Job{Elements: []receipt.Element{
|
||||
{Type: "text", Size: 0},
|
||||
{Type: "feed", Lines: -1},
|
||||
{Type: "qr"},
|
||||
}}.Validate()
|
||||
var ve *receipt.ValidationError
|
||||
if !errors.As(err, &ve) || len(ve.Problems) != 2 {
|
||||
t.Fatalf("problems = %v, want 2 (feed and qr)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAcceptsDataURI(t *testing.T) {
|
||||
job := receipt.Job{Elements: []receipt.Element{{
|
||||
Type: "image",
|
||||
Base64: "data:image/png;base64," + base64.StdEncoding.EncodeToString([]byte("x")),
|
||||
}}}
|
||||
if err := job.Validate(); err != nil {
|
||||
t.Errorf("Validate: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package receipt
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/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.
|
||||
Columns int
|
||||
|
||||
// MaxPixels caps decoded image size; MaxHeight caps printed image height
|
||||
// in dots.
|
||||
MaxPixels int
|
||||
MaxHeight int
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
var body escpos.Builder
|
||||
p := printer{b: &body, lineDots: r.textLineDots(), profile: r.options.Profile, codePage: r.options.CodePage}
|
||||
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)
|
||||
}
|
||||
}
|
||||
p.endLine()
|
||||
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
|
||||
body.Cut(escpos.CutPartial, 0)
|
||||
}
|
||||
|
||||
var out escpos.Builder
|
||||
out.Initialize()
|
||||
out.SelectCodePage(r.options.CodePage)
|
||||
for range job.copies() {
|
||||
out.Raw(body.Bytes())
|
||||
}
|
||||
return bytes.Clone(out.Bytes()), 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
|
||||
x int
|
||||
}
|
||||
|
||||
func (p *printer) element(el Element, img *image.Paletted) error {
|
||||
switch el.Type {
|
||||
case TypeText:
|
||||
return p.text(el)
|
||||
case TypeFeed:
|
||||
lines, err := el.feedLines()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.b.Feed(lines)
|
||||
p.x = 0
|
||||
case TypeQR:
|
||||
spec, err := el.qrSpec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.endLine()
|
||||
p.b.Justify(spec.align)
|
||||
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)
|
||||
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)
|
||||
return p.b.RasterImage(img)
|
||||
case TypeRaw:
|
||||
data, err := el.rawBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.b.Raw(data)
|
||||
// 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 := sanitize(el.Text)
|
||||
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.b.Text(p.codePage.Encode(line))
|
||||
p.x += utf8.RuneCountInString(line) * glyph
|
||||
}
|
||||
} else {
|
||||
p.b.Text(p.codePage.Encode(text))
|
||||
p.advance(text, glyph)
|
||||
}
|
||||
if spec.newline {
|
||||
p.b.LineFeed()
|
||||
p.x = 0
|
||||
}
|
||||
|
||||
// Reset styles so they cannot leak into barcodes, QR codes or raw data.
|
||||
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
|
||||
}
|
||||
|
||||
// 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.b.LineFeed()
|
||||
p.x = 0
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user