From 0252f475ebb2477dbaacaa7ae6e07277ea8310bd Mon Sep 17 00:00:00 2001 From: adcondev Date: Sun, 18 Oct 2026 12:35:52 -0700 Subject: [PATCH] feat(graphics): add Floyd-Steinberg and Bayer dithering, PDF417, and ESC/POS byte parser --- api/v1/TICKET_DOCUMENT_V1.md | 35 +- api/v1/ticket_document.schema.json | 70 +- pkg/commands/qrcode/pdf417.go | 157 +++++ pkg/commands/qrcode/pdf417_test.go | 281 ++++++++ pkg/constants/constants.go | 9 +- pkg/document/builder/command_builder.go | 5 + pkg/document/builder/pdf417_build.go | 97 +++ pkg/document/builder/pdf417_build_test.go | 124 ++++ pkg/document/executor/handler_executor.go | 1 + pkg/document/executor/image_handler.go | 9 +- pkg/document/executor/pdf417_handler.go | 82 +++ pkg/document/executor/pdf417_handler_test.go | 249 +++++++ pkg/document/schema/commands.go | 11 + pkg/emulator/byte_parser.go | 347 ++++++++++ pkg/emulator/byte_parser_test.go | 651 +++++++++++++++++++ pkg/graphics/barcode.go | 14 +- pkg/graphics/graph_engine.go | 123 +++- pkg/graphics/graph_engine_test.go | 204 ++++++ pkg/profile/escpos_profile.go | 4 + pkg/service/printer_service.go | 24 + 20 files changed, 2467 insertions(+), 30 deletions(-) create mode 100644 pkg/commands/qrcode/pdf417.go create mode 100644 pkg/commands/qrcode/pdf417_test.go create mode 100644 pkg/document/builder/pdf417_build.go create mode 100644 pkg/document/builder/pdf417_build_test.go create mode 100644 pkg/document/executor/pdf417_handler.go create mode 100644 pkg/document/executor/pdf417_handler_test.go create mode 100644 pkg/emulator/byte_parser.go create mode 100644 pkg/emulator/byte_parser_test.go diff --git a/api/v1/TICKET_DOCUMENT_V1.md b/api/v1/TICKET_DOCUMENT_V1.md index 83c202d..64cddf4 100644 --- a/api/v1/TICKET_DOCUMENT_V1.md +++ b/api/v1/TICKET_DOCUMENT_V1.md @@ -54,7 +54,7 @@ Define las características de la impresora: | Campo | Tipo | Requerido | Descripción | Valores | |--------|--------|-----------|-------------------------------|-------------------------------------------------------| -| `type` | string | ✓ | Tipo de comando | text, image, separator, feed, cut, qr, table, barcode | +| `type` | string | ✓ | Tipo de comando | text, image, separator, feed, cut, qr, pdf417, table, barcode, raw, pulse, beep | | `data` | object | ✓ | Datos específicos del comando | Varía según el tipo | ### 1. Text Command @@ -147,7 +147,7 @@ Imprime imágenes en formato base64: | `pixel_width` | integer | | Ancho deseado en píxeles | 128 | Mínimo: 1 | | `align` | string | | Alineación de la imagen | center | left, center, right | | `threshold` | integer | | Umbral B/N (0-255) | 128 | 0-255 | -| `dithering` | string | | Algoritmo de dithering | atkinson | threshold, atkinson | +| `dithering` | string | | Algoritmo de dithering | atkinson | threshold, atkinson, floyd_steinberg, ordered | | `scaling` | string | | Algoritmo de escalado | bilinear | bilinear, nns | ### 3. Barcode Command @@ -171,7 +171,7 @@ Genera códigos de barras: | Campo | Tipo | Requerido | Descripción | Default | Valores | |----------------|---------|-----------|-----------------------|---------|--------------------------------------------------------| -| `symbology` | string | ✓ | Tipo de simbología | | upca, upce, ean13, ean8, code39, code128, itf, codabar | +| `symbology` | string | ✓ | Tipo de simbología | | upca, upce, ean13, ean8, code39, code128, itf, codabar, code93, gs1_128, code128_auto | | `data` | string | ✓ | Datos a codificar | | 1-25 caracteres | | `width` | integer | | Ancho del módulo | | 2-6 | | `height` | integer | | Altura en puntos | | 1-255 | @@ -208,6 +208,35 @@ Genera códigos QR: | `logo` | string | | Logo en Base64 | | | | `circle_shape` | boolean | | Usar bloques circulares (solo para QR < 256px) | | | +### 4b. PDF417 Command + +Genera códigos bidimensionales PDF417: + +```json +{ + "type": "pdf417", + "data": { + "data": "PDF417-PAYLOAD-DATA", + "columns": 0, + "rows": 0, + "module_width": 3, + "row_height": 3, + "error_correction": 2, + "align": "center" + } +} +``` + +| Campo | Tipo | Requerido | Descripción | Default | Valores | +|--------------------|---------|-----------|----------------------------------------------|---------|---------------------| +| `data` | string | ✓ | Datos a codificar en el PDF417 | | | +| `columns` | integer | | Número de columnas (0 = auto) | 0 | 0-30 | +| `rows` | integer | | Número de filas (0 = auto) | 0 | 0, 3-90 | +| `module_width` | integer | | Ancho del módulo en dots | 3 | 2-8 | +| `row_height` | integer | | Multiplicador de altura de fila | 3 | 2-8 | +| `error_correction` | integer | | Nivel de corrección de errores | 2 | 0-8 | +| `align` | string | | Alineación del código | center | left, center, right | + ### 5. Table Command Crea tablas formateadas: diff --git a/api/v1/ticket_document.schema.json b/api/v1/ticket_document.schema.json index 7fc4f77..802c8e5 100644 --- a/api/v1/ticket_document.schema.json +++ b/api/v1/ticket_document.schema.json @@ -95,6 +95,7 @@ "feed", "cut", "qr", + "pdf417", "table", "barcode", "raw", @@ -124,6 +125,9 @@ { "$ref": "#/definitions/QRCommand" }, + { + "$ref": "#/definitions/PDF417Command" + }, { "$ref": "#/definitions/TableCommand" }, @@ -295,7 +299,9 @@ "type": "string", "enum": [ "threshold", - "atkinson" + "atkinson", + "floyd_steinberg", + "ordered" ], "default": "atkinson" }, @@ -410,6 +416,63 @@ } } }, + "PDF417Command": { + "type": "object", + "required": [ + "data" + ], + "properties": { + "data": { + "type": "string", + "description": "PDF417 barcode data to encode" + }, + "columns": { + "type": "integer", + "description": "Number of columns (0-30, 0 = auto)", + "minimum": 0, + "maximum": 30, + "default": 0 + }, + "rows": { + "type": "integer", + "description": "Number of rows (0 or 3-90, 0 = auto)", + "minimum": 0, + "maximum": 90, + "default": 0 + }, + "module_width": { + "type": "integer", + "description": "Module width in dots (2-8)", + "minimum": 2, + "maximum": 8, + "default": 3 + }, + "row_height": { + "type": "integer", + "description": "Row height multiplier (2-8)", + "minimum": 2, + "maximum": 8, + "default": 3 + }, + "error_correction": { + "type": "integer", + "description": "Error correction level (0-8)", + "minimum": 0, + "maximum": 8, + "default": 2 + }, + "align": { + "type": "string", + "enum": [ + "left", + "center", + "right" + ], + "description": "PDF417 barcode alignment", + "default": "center" + } + } + }, "BarcodeCommand": { "type": "object", "required": [ @@ -427,7 +490,10 @@ "code39", "code128", "itf", - "codabar" + "codabar", + "code93", + "gs1_128", + "code128_auto" ], "description": "Barcode symbology type", "default": "code128" diff --git a/pkg/commands/qrcode/pdf417.go b/pkg/commands/qrcode/pdf417.go new file mode 100644 index 0000000..3c3a343 --- /dev/null +++ b/pkg/commands/qrcode/pdf417.go @@ -0,0 +1,157 @@ +package qrcode + +import ( + "errors" + "fmt" + + "github.com/adcondev/poster/pkg/commands/shared" +) + +// PDF417 command constants and limits. +const ( + // MaxPDF417Columns defines the maximum number of columns in a PDF417 barcode. + MaxPDF417Columns = 30 + // MinPDF417Rows defines the minimum number of rows when specified. + MinPDF417Rows = 3 + // MaxPDF417Rows defines the maximum number of rows in a PDF417 barcode. + MaxPDF417Rows = 90 + // MinPDF417ModuleWidth defines the minimum module width in dots. + MinPDF417ModuleWidth = 2 + // MaxPDF417ModuleWidth defines the maximum module width in dots. + MaxPDF417ModuleWidth = 8 + // MinPDF417RowHeight defines the minimum row height multiplier. + MinPDF417RowHeight = 2 + // MaxPDF417RowHeight defines the maximum row height multiplier. + MaxPDF417RowHeight = 8 + // MaxPDF417ErrorCorrection defines the maximum error correction level. + MaxPDF417ErrorCorrection = 8 + // MaxPDF417DataLength defines the maximum byte length of PDF417 data. + MaxPDF417DataLength = 65532 +) + +var ( + // ErrPDF417Columns indicates an invalid column count (0-30). + ErrPDF417Columns = errors.New("invalid PDF417 columns (try 0-30)") + // ErrPDF417Rows indicates an invalid row count (0 or 3-90). + ErrPDF417Rows = errors.New("invalid PDF417 rows (try 0, or 3-90)") + // ErrPDF417ModuleWidth indicates an invalid module width (2-8). + ErrPDF417ModuleWidth = errors.New("invalid PDF417 module width (try 2-8)") + // ErrPDF417RowHeight indicates an invalid row height (2-8). + ErrPDF417RowHeight = errors.New("invalid PDF417 row height (try 2-8)") + // ErrPDF417ErrorCorrection indicates an invalid error correction level (0-8). + ErrPDF417ErrorCorrection = errors.New("invalid PDF417 error correction level (try 0-8)") + // ErrPDF417DataEmpty indicates empty PDF417 data payload. + ErrPDF417DataEmpty = errors.New("PDF417 data cannot be empty") + // ErrPDF417DataTooLong indicates data payload exceeds 65532 bytes. + ErrPDF417DataTooLong = errors.New("PDF417 data too long (maximum 65532 bytes)") +) + +// SetPDF417Columns sets the number of columns in the PDF417 data area (fn = 65). +// Range: 0 <= columns <= 30 (0 sets automatic processing). +func SetPDF417Columns(columns byte) ([]byte, error) { + if columns > MaxPDF417Columns { + return nil, fmt.Errorf("%w: columns=%d", ErrPDF417Columns, columns) + } + return []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, columns}, nil +} + +// SetPDF417Rows sets the number of rows in the PDF417 data area (fn = 66). +// Range: rows == 0 || (rows >= 3 && rows <= 90) (0 sets automatic processing). +func SetPDF417Rows(rows byte) ([]byte, error) { + if rows != 0 && (rows < MinPDF417Rows || rows > MaxPDF417Rows) { + return nil, fmt.Errorf("%w: rows=%d", ErrPDF417Rows, rows) + } + return []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, rows}, nil +} + +// SetPDF417ModuleWidth sets the module width of the PDF417 symbol (fn = 67). +// Range: 2 <= width <= 8 dots. +func SetPDF417ModuleWidth(width byte) ([]byte, error) { + if width < MinPDF417ModuleWidth || width > MaxPDF417ModuleWidth { + return nil, fmt.Errorf("%w: width=%d", ErrPDF417ModuleWidth, width) + } + return []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 67, width}, nil +} + +// SetPDF417RowHeight sets the row height of the PDF417 symbol (fn = 68). +// Range: 2 <= height <= 8 (height = module width × row height). +func SetPDF417RowHeight(height byte) ([]byte, error) { + if height < MinPDF417RowHeight || height > MaxPDF417RowHeight { + return nil, fmt.Errorf("%w: height=%d", ErrPDF417RowHeight, height) + } + return []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 68, height}, nil +} + +// SetPDF417ErrorCorrection sets the error correction level for PDF417 (fn = 69, m = 48). +// Range: 0 <= level <= 8. +func SetPDF417ErrorCorrection(level byte) ([]byte, error) { + if level > MaxPDF417ErrorCorrection { + return nil, fmt.Errorf("%w: level=%d", ErrPDF417ErrorCorrection, level) + } + return []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 69, 48, 48 + level}, nil +} + +// StorePDF417Data stores symbol data into the PDF417 symbol storage area (fn = 80, m = 48). +// Range: 1 <= len(data) <= 65532 bytes. +func StorePDF417Data(data []byte) ([]byte, error) { + if len(data) == 0 { + return nil, ErrPDF417DataEmpty + } + if len(data) > MaxPDF417DataLength { + return nil, fmt.Errorf("%w: %d bytes", ErrPDF417DataTooLong, len(data)) + } + + length := len(data) + 3 + pL := byte(length & 0xFF) + pH := byte((length >> 8) & 0xFF) + + cmd := make([]byte, 0, 8+len(data)) + cmd = append(cmd, shared.GS, '(', 'k', pL, pH, 48, 80, 48) + cmd = append(cmd, data...) + return cmd, nil +} + +// PrintPDF417 prints the PDF417 symbol data stored in the symbol storage area (fn = 81, m = 48). +func PrintPDF417() []byte { + return []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 81, 48} +} + +// ComposePDF417 combines all setup commands, data storage, and the print command into a single atomic byte sequence. +func ComposePDF417(columns, rows, width, rowHeight, ecLevel byte, data []byte) ([]byte, error) { + colCmd, err := SetPDF417Columns(columns) + if err != nil { + return nil, fmt.Errorf("pdf417 set columns: %w", err) + } + rowCmd, err := SetPDF417Rows(rows) + if err != nil { + return nil, fmt.Errorf("pdf417 set rows: %w", err) + } + widthCmd, err := SetPDF417ModuleWidth(width) + if err != nil { + return nil, fmt.Errorf("pdf417 set module width: %w", err) + } + heightCmd, err := SetPDF417RowHeight(rowHeight) + if err != nil { + return nil, fmt.Errorf("pdf417 set row height: %w", err) + } + ecCmd, err := SetPDF417ErrorCorrection(ecLevel) + if err != nil { + return nil, fmt.Errorf("pdf417 set error correction: %w", err) + } + storeCmd, err := StorePDF417Data(data) + if err != nil { + return nil, fmt.Errorf("pdf417 store data: %w", err) + } + printCmd := PrintPDF417() + + totalLen := len(colCmd) + len(rowCmd) + len(widthCmd) + len(heightCmd) + len(ecCmd) + len(storeCmd) + len(printCmd) + buf := make([]byte, 0, totalLen) + buf = append(buf, colCmd...) + buf = append(buf, rowCmd...) + buf = append(buf, widthCmd...) + buf = append(buf, heightCmd...) + buf = append(buf, ecCmd...) + buf = append(buf, storeCmd...) + buf = append(buf, printCmd...) + return buf, nil +} diff --git a/pkg/commands/qrcode/pdf417_test.go b/pkg/commands/qrcode/pdf417_test.go new file mode 100644 index 0000000..d9f019a --- /dev/null +++ b/pkg/commands/qrcode/pdf417_test.go @@ -0,0 +1,281 @@ +package qrcode + +import ( + "bytes" + "errors" + "testing" + + "github.com/adcondev/poster/pkg/commands/shared" +) + +func TestSetPDF417Columns(t *testing.T) { + tests := []struct { + name string + columns byte + wantBytes []byte + wantErr bool + }{ + {"auto (0)", 0, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, 0}, false}, + {"mid (15)", 15, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, 15}, false}, + {"max (30)", 30, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, 30}, false}, + {"over limit (31)", 31, nil, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SetPDF417Columns(tt.columns) + if (err != nil) != tt.wantErr { + t.Fatalf("SetPDF417Columns(%d) error = %v, wantErr %v", tt.columns, err, tt.wantErr) + } + if !tt.wantErr && !bytes.Equal(got, tt.wantBytes) { + t.Errorf("SetPDF417Columns(%d) = %v, want %v", tt.columns, got, tt.wantBytes) + } + if tt.wantErr && !errors.Is(err, ErrPDF417Columns) { + t.Errorf("expected ErrPDF417Columns, got %v", err) + } + }) + } +} + +func TestSetPDF417Rows(t *testing.T) { + tests := []struct { + name string + rows byte + wantBytes []byte + wantErr bool + }{ + {"auto (0)", 0, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, 0}, false}, + {"min (3)", 3, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, 3}, false}, + {"mid (45)", 45, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, 45}, false}, + {"max (90)", 90, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, 90}, false}, + {"invalid below min (1)", 1, nil, true}, + {"invalid below min (2)", 2, nil, true}, + {"invalid above max (91)", 91, nil, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SetPDF417Rows(tt.rows) + if (err != nil) != tt.wantErr { + t.Fatalf("SetPDF417Rows(%d) error = %v, wantErr %v", tt.rows, err, tt.wantErr) + } + if !tt.wantErr && !bytes.Equal(got, tt.wantBytes) { + t.Errorf("SetPDF417Rows(%d) = %v, want %v", tt.rows, got, tt.wantBytes) + } + if tt.wantErr && !errors.Is(err, ErrPDF417Rows) { + t.Errorf("expected ErrPDF417Rows, got %v", err) + } + }) + } +} + +func TestSetPDF417ModuleWidth(t *testing.T) { + tests := []struct { + name string + width byte + wantBytes []byte + wantErr bool + }{ + {"min (2)", 2, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 67, 2}, false}, + {"mid (5)", 5, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 67, 5}, false}, + {"max (8)", 8, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 67, 8}, false}, + {"invalid below min (1)", 1, nil, true}, + {"invalid above max (9)", 9, nil, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SetPDF417ModuleWidth(tt.width) + if (err != nil) != tt.wantErr { + t.Fatalf("SetPDF417ModuleWidth(%d) error = %v, wantErr %v", tt.width, err, tt.wantErr) + } + if !tt.wantErr && !bytes.Equal(got, tt.wantBytes) { + t.Errorf("SetPDF417ModuleWidth(%d) = %v, want %v", tt.width, got, tt.wantBytes) + } + if tt.wantErr && !errors.Is(err, ErrPDF417ModuleWidth) { + t.Errorf("expected ErrPDF417ModuleWidth, got %v", err) + } + }) + } +} + +func TestSetPDF417RowHeight(t *testing.T) { + tests := []struct { + name string + height byte + wantBytes []byte + wantErr bool + }{ + {"min (2)", 2, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 68, 2}, false}, + {"mid (5)", 5, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 68, 5}, false}, + {"max (8)", 8, []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 68, 8}, false}, + {"invalid below min (1)", 1, nil, true}, + {"invalid above max (9)", 9, nil, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SetPDF417RowHeight(tt.height) + if (err != nil) != tt.wantErr { + t.Fatalf("SetPDF417RowHeight(%d) error = %v, wantErr %v", tt.height, err, tt.wantErr) + } + if !tt.wantErr && !bytes.Equal(got, tt.wantBytes) { + t.Errorf("SetPDF417RowHeight(%d) = %v, want %v", tt.height, got, tt.wantBytes) + } + if tt.wantErr && !errors.Is(err, ErrPDF417RowHeight) { + t.Errorf("expected ErrPDF417RowHeight, got %v", err) + } + }) + } +} + +func TestSetPDF417ErrorCorrection(t *testing.T) { + tests := []struct { + name string + level byte + wantBytes []byte + wantErr bool + }{ + {"level 0", 0, []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 69, 48, 48}, false}, + {"level 2", 2, []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 69, 48, 50}, false}, + {"level 8", 8, []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 69, 48, 56}, false}, + {"invalid level (9)", 9, nil, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SetPDF417ErrorCorrection(tt.level) + if (err != nil) != tt.wantErr { + t.Fatalf("SetPDF417ErrorCorrection(%d) error = %v, wantErr %v", tt.level, err, tt.wantErr) + } + if !tt.wantErr && !bytes.Equal(got, tt.wantBytes) { + t.Errorf("SetPDF417ErrorCorrection(%d) = %v, want %v", tt.level, got, tt.wantBytes) + } + if tt.wantErr && !errors.Is(err, ErrPDF417ErrorCorrection) { + t.Errorf("expected ErrPDF417ErrorCorrection, got %v", err) + } + }) + } +} + +func TestStorePDF417Data(t *testing.T) { + t.Run("valid single byte", func(t *testing.T) { + data := []byte("A") + got, err := StorePDF417Data(data) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + // length = 1 + 3 = 4 -> pL = 0x04, pH = 0x00 + want := []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 80, 48, 'A'} + if !bytes.Equal(got, want) { + t.Errorf("got %v, want %v", got, want) + } + }) + + t.Run("empty data", func(t *testing.T) { + _, err := StorePDF417Data(nil) + if !errors.Is(err, ErrPDF417DataEmpty) { + t.Errorf("expected ErrPDF417DataEmpty, got %v", err) + } + }) + + t.Run("data too long", func(t *testing.T) { + data := make([]byte, 65533) + _, err := StorePDF417Data(data) + if !errors.Is(err, ErrPDF417DataTooLong) { + t.Errorf("expected ErrPDF417DataTooLong, got %v", err) + } + }) + + t.Run("max valid data length", func(t *testing.T) { + data := make([]byte, MaxPDF417DataLength) + got, err := StorePDF417Data(data) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + // length = 65532 + 3 = 65535 (0xFFFF) -> pL = 0xFF, pH = 0xFF + if got[3] != 0xFF || got[4] != 0xFF { + t.Errorf("expected length bytes 0xFF 0xFF, got %02X %02X", got[3], got[4]) + } + if len(got) != 8+MaxPDF417DataLength { + t.Errorf("expected total length %d, got %d", 8+MaxPDF417DataLength, len(got)) + } + }) +} + +func TestPrintPDF417(t *testing.T) { + got := PrintPDF417() + want := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 81, 48} + if !bytes.Equal(got, want) { + t.Errorf("PrintPDF417() = %v, want %v", got, want) + } +} + +func TestComposePDF417(t *testing.T) { + t.Run("valid compose", func(t *testing.T) { + data := []byte("TEST-PDF417-DATA") + got, err := ComposePDF417(5, 10, 3, 4, 2, data) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + // Verify first command is columns + wantCol := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, 5} + if !bytes.HasPrefix(got, wantCol) { + t.Errorf("expected prefix %v, got %v", wantCol, got[:len(wantCol)]) + } + + // Verify last command is print + wantPrint := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 81, 48} + if !bytes.HasSuffix(got, wantPrint) { + t.Errorf("expected suffix %v, got %v", wantPrint, got[len(got)-len(wantPrint):]) + } + + // Verify data is contained + if !bytes.Contains(got, data) { + t.Errorf("expected composed bytes to contain data %s", string(data)) + } + }) + + t.Run("invalid column fails", func(t *testing.T) { + _, err := ComposePDF417(35, 0, 3, 3, 2, []byte("ok")) + if err == nil { + t.Fatal("expected error on invalid columns") + } + }) + + t.Run("invalid rows fails", func(t *testing.T) { + _, err := ComposePDF417(0, 1, 3, 3, 2, []byte("ok")) + if err == nil { + t.Fatal("expected error on invalid rows") + } + }) + + t.Run("invalid module width fails", func(t *testing.T) { + _, err := ComposePDF417(0, 0, 1, 3, 2, []byte("ok")) + if err == nil { + t.Fatal("expected error on invalid module width") + } + }) + + t.Run("invalid row height fails", func(t *testing.T) { + _, err := ComposePDF417(0, 0, 3, 10, 2, []byte("ok")) + if err == nil { + t.Fatal("expected error on invalid row height") + } + }) + + t.Run("invalid error correction fails", func(t *testing.T) { + _, err := ComposePDF417(0, 0, 3, 3, 9, []byte("ok")) + if err == nil { + t.Fatal("expected error on invalid error correction") + } + }) + + t.Run("empty data fails", func(t *testing.T) { + _, err := ComposePDF417(0, 0, 3, 3, 2, nil) + if err == nil { + t.Fatal("expected error on empty data") + } + }) +} diff --git a/pkg/constants/constants.go b/pkg/constants/constants.go index ebc4110..6d6672d 100644 --- a/pkg/constants/constants.go +++ b/pkg/constants/constants.go @@ -64,7 +64,8 @@ const ( Atkinson Dithering = "atkinson" // FloydSteinberg uses Floyd-Steinberg dithering algorithm FloydSteinberg Dithering = "floyd_steinberg" - // TODO: Add more dithering algorithms if needed + // Ordered uses ordered dithering algorithm + Ordered Dithering = "ordered" ) // ============================================================================ @@ -339,6 +340,12 @@ const ( JAN13 Symbology = "jan13" // JAN8 symbology (alias for EAN8) JAN8 Symbology = "jan8" + // CODE93 symbology + CODE93 Symbology = "code93" + // GS1128 symbology (GS1-128 / UCC/EAN-128) + GS1128 Symbology = "gs1_128" + // CODE128Auto symbology + CODE128Auto Symbology = "code128_auto" ) // ============================================================================ diff --git a/pkg/document/builder/command_builder.go b/pkg/document/builder/command_builder.go index 5b3bc9c..56648b9 100644 --- a/pkg/document/builder/command_builder.go +++ b/pkg/document/builder/command_builder.go @@ -98,6 +98,11 @@ func (b *DocumentBuilder) QR(data string) *QRBuilder { return newQRBuilder(b, data) } +// PDF417 starts building a PDF417 2D barcode command +func (b *DocumentBuilder) PDF417(data string) *PDF417Builder { + return newPDF417Builder(b, data) +} + // Barcode starts building a barcode command func (b *DocumentBuilder) Barcode(symbology, data string) *BarcodeBuilder { return newBarcodeBuilder(b, symbology, data) diff --git a/pkg/document/builder/pdf417_build.go b/pkg/document/builder/pdf417_build.go new file mode 100644 index 0000000..784a2a1 --- /dev/null +++ b/pkg/document/builder/pdf417_build.go @@ -0,0 +1,97 @@ +package builder + +import ( + "github.com/adcondev/poster/pkg/constants" + "github.com/adcondev/poster/pkg/document/schema" +) + +// PDF417Builder constructs PDF417 2D barcode commands. +type PDF417Builder struct { + parent *DocumentBuilder + data string + columns int + rows int + moduleWidth int + rowHeight int + errorCorrection int + align string +} + +func newPDF417Builder(parent *DocumentBuilder, data string) *PDF417Builder { + return &PDF417Builder{ + parent: parent, + data: data, + moduleWidth: 3, + rowHeight: 3, + errorCorrection: 2, + align: constants.Center.String(), + } +} + +// Columns sets the number of data columns (0-30, 0 = automatic). +func (pb *PDF417Builder) Columns(columns int) *PDF417Builder { + pb.columns = columns + return pb +} + +// Rows sets the number of rows (0 or 3-90, 0 = automatic). +func (pb *PDF417Builder) Rows(rows int) *PDF417Builder { + pb.rows = rows + return pb +} + +// ModuleWidth sets module width in dots (2-8). +func (pb *PDF417Builder) ModuleWidth(width int) *PDF417Builder { + pb.moduleWidth = width + return pb +} + +// RowHeight sets row height multiplier (2-8). +func (pb *PDF417Builder) RowHeight(height int) *PDF417Builder { + pb.rowHeight = height + return pb +} + +// ErrorCorrection sets error correction level (0-8). +func (pb *PDF417Builder) ErrorCorrection(level int) *PDF417Builder { + pb.errorCorrection = level + return pb +} + +// Align sets the PDF417 alignment (left, center, right). +func (pb *PDF417Builder) Align(align string) *PDF417Builder { + pb.align = align + return pb +} + +// Left aligns PDF417 barcode to the left. +func (pb *PDF417Builder) Left() *PDF417Builder { + pb.align = constants.Left.String() + return pb +} + +// Center centers the PDF417 barcode (default). +func (pb *PDF417Builder) Center() *PDF417Builder { + pb.align = constants.Center.String() + return pb +} + +// Right aligns PDF417 barcode to the right. +func (pb *PDF417Builder) Right() *PDF417Builder { + pb.align = constants.Right.String() + return pb +} + +// End finishes the PDF417 command and appends it to the document. +func (pb *PDF417Builder) End() *DocumentBuilder { + cmd := schema.PDF417Command{ + Data: pb.data, + Columns: pb.columns, + Rows: pb.rows, + ModuleWidth: pb.moduleWidth, + RowHeight: pb.rowHeight, + ErrorCorrection: pb.errorCorrection, + Align: pb.align, + } + return pb.parent.addCommand("pdf417", cmd) +} diff --git a/pkg/document/builder/pdf417_build_test.go b/pkg/document/builder/pdf417_build_test.go new file mode 100644 index 0000000..d111029 --- /dev/null +++ b/pkg/document/builder/pdf417_build_test.go @@ -0,0 +1,124 @@ +package builder + +import ( + "encoding/json" + "testing" + + "github.com/adcondev/poster/pkg/constants" + "github.com/adcondev/poster/pkg/document/schema" +) + +func TestPDF417Builder(t *testing.T) { + doc := NewDocument(). + SetProfile("Test", 80, "WPC1252"). + PDF417("https://example.com/ticket"). + Columns(5). + Rows(10). + ModuleWidth(4). + RowHeight(5). + ErrorCorrection(3). + Center(). + End(). + Build() + + if len(doc.Commands) != 1 { + t.Fatalf("expected 1 command, got %d", len(doc.Commands)) + } + + if doc.Commands[0].Type != "pdf417" { + t.Errorf("expected type 'pdf417', got '%s'", doc.Commands[0].Type) + } + + var cmd schema.PDF417Command + if err := json.Unmarshal(doc.Commands[0].Data, &cmd); err != nil { + t.Fatalf("failed to unmarshal command data: %v", err) + } + + if cmd.Data != "https://example.com/ticket" { + t.Errorf("expected data 'https://example.com/ticket', got '%s'", cmd.Data) + } + if cmd.Columns != 5 { + t.Errorf("expected columns 5, got %d", cmd.Columns) + } + if cmd.Rows != 10 { + t.Errorf("expected rows 10, got %d", cmd.Rows) + } + if cmd.ModuleWidth != 4 { + t.Errorf("expected module width 4, got %d", cmd.ModuleWidth) + } + if cmd.RowHeight != 5 { + t.Errorf("expected row height 5, got %d", cmd.RowHeight) + } + if cmd.ErrorCorrection != 3 { + t.Errorf("expected error correction 3, got %d", cmd.ErrorCorrection) + } + if cmd.Align != constants.Center.String() { + t.Errorf("expected align 'center', got '%s'", cmd.Align) + } +} + +func TestPDF417BuilderDefaults(t *testing.T) { + doc := NewDocument(). + SetProfile("Test", 80, "WPC1252"). + PDF417("default-data"). + End(). + Build() + + if len(doc.Commands) != 1 { + t.Fatalf("expected 1 command, got %d", len(doc.Commands)) + } + + var cmd schema.PDF417Command + if err := json.Unmarshal(doc.Commands[0].Data, &cmd); err != nil { + t.Fatalf("failed to unmarshal command data: %v", err) + } + + if cmd.Data != "default-data" { + t.Errorf("expected data 'default-data', got '%s'", cmd.Data) + } + if cmd.Columns != 0 { + t.Errorf("expected default columns 0, got %d", cmd.Columns) + } + if cmd.Rows != 0 { + t.Errorf("expected default rows 0, got %d", cmd.Rows) + } + if cmd.ModuleWidth != 3 { + t.Errorf("expected default module width 3, got %d", cmd.ModuleWidth) + } + if cmd.RowHeight != 3 { + t.Errorf("expected default row height 3, got %d", cmd.RowHeight) + } + if cmd.ErrorCorrection != 2 { + t.Errorf("expected default error correction 2, got %d", cmd.ErrorCorrection) + } + if cmd.Align != constants.Center.String() { + t.Errorf("expected default align 'center', got '%s'", cmd.Align) + } +} + +func TestPDF417BuilderAlignment(t *testing.T) { + tests := []struct { + name string + align func(*PDF417Builder) *PDF417Builder + expected string + }{ + {"Left", func(pb *PDF417Builder) *PDF417Builder { return pb.Left() }, constants.Left.String()}, + {"Center", func(pb *PDF417Builder) *PDF417Builder { return pb.Center() }, constants.Center.String()}, + {"Right", func(pb *PDF417Builder) *PDF417Builder { return pb.Right() }, constants.Right.String()}, + {"Custom Align", func(pb *PDF417Builder) *PDF417Builder { return pb.Align("right") }, "right"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + doc := NewDocument() + tt.align(doc.PDF417("data")).End() + bDoc := doc.Build() + + var cmd schema.PDF417Command + _ = json.Unmarshal(bDoc.Commands[0].Data, &cmd) + if cmd.Align != tt.expected { + t.Errorf("expected align '%s', got '%s'", tt.expected, cmd.Align) + } + }) + } +} diff --git a/pkg/document/executor/handler_executor.go b/pkg/document/executor/handler_executor.go index 26c4196..28d0913 100644 --- a/pkg/document/executor/handler_executor.go +++ b/pkg/document/executor/handler_executor.go @@ -45,6 +45,7 @@ func NewExecutor(printer service.PrinterActions) *Executor { e.registerHandler("image", e.handleImage) e.registerHandler("qr", e.handleQR) e.registerHandler("barcode", e.handleBarcode) + e.registerHandler("pdf417", e.handlePDF417) // Register layout & raw handlers e.registerHandler("table", e.handleTable) diff --git a/pkg/document/executor/image_handler.go b/pkg/document/executor/image_handler.go index 33082b2..da17aaa 100644 --- a/pkg/document/executor/image_handler.go +++ b/pkg/document/executor/image_handler.go @@ -49,12 +49,9 @@ func (e *Executor) handleImage(printer service.PrinterActions, data json.RawMess opts.Threshold = constants.DefaultImageThreshold } - switch strings.ToLower(cmd.Dithering) { - case constants.Atkinson.String(): - opts.Dithering = graphics.Atkinson - case constants.Threshold.String(): - opts.Dithering = graphics.Threshold - default: + if ditherMode, ok := graphics.DitherMap[strings.ToLower(strings.TrimSpace(cmd.Dithering))]; ok { + opts.Dithering = ditherMode + } else { opts.Dithering = graphics.DitherMap[constants.DefaultImageDithering.String()] } diff --git a/pkg/document/executor/pdf417_handler.go b/pkg/document/executor/pdf417_handler.go new file mode 100644 index 0000000..b213caf --- /dev/null +++ b/pkg/document/executor/pdf417_handler.go @@ -0,0 +1,82 @@ +package executor + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/adcondev/poster/pkg/commands/qrcode" + "github.com/adcondev/poster/pkg/constants" + "github.com/adcondev/poster/pkg/document/schema" + "github.com/adcondev/poster/pkg/service" +) + +// handlePDF417 manages PDF417 2D barcode commands. +func (e *Executor) handlePDF417(printer service.PrinterActions, data json.RawMessage) error { + var cmd schema.PDF417Command + if err := json.Unmarshal(data, &cmd); err != nil { + return fmt.Errorf("failed to parse PDF417 command: %w", err) + } + + if cmd.Data == "" { + return fmt.Errorf("PDF417 data cannot be empty") + } + + columns := byte(0) + if cmd.Columns >= 0 && cmd.Columns <= 30 { + columns = byte(cmd.Columns) + } + + rows := byte(0) + if cmd.Rows >= 3 && cmd.Rows <= 90 { + rows = byte(cmd.Rows) + } + + moduleWidth := byte(3) + if cmd.ModuleWidth >= 2 && cmd.ModuleWidth <= 8 { + moduleWidth = byte(cmd.ModuleWidth) + } + + rowHeight := byte(3) + if cmd.RowHeight >= 2 && cmd.RowHeight <= 8 { + rowHeight = byte(cmd.RowHeight) + } + + ecLevel := byte(2) + if cmd.ErrorCorrection > 0 && cmd.ErrorCorrection <= 8 { + ecLevel = byte(cmd.ErrorCorrection) + } + + align := constants.DefaultQrAlignment.String() + if cmd.Align != "" { + align = strings.ToLower(cmd.Align) + } + + switch align { + case constants.Left.String(): + if err := printer.AlignLeft(); err != nil { + return err + } + case constants.Right.String(): + if err := printer.AlignRight(); err != nil { + return err + } + case constants.Center.String(): + fallthrough + default: + if err := printer.AlignCenter(); err != nil { + return err + } + } + + rawCmd, err := qrcode.ComposePDF417(columns, rows, moduleWidth, rowHeight, ecLevel, []byte(cmd.Data)) + if err != nil { + return fmt.Errorf("failed to compose PDF417 command: %w", err) + } + + if err := printer.Write(rawCmd); err != nil { + return fmt.Errorf("failed to write PDF417 command: %w", err) + } + + return printer.AlignLeft() +} diff --git a/pkg/document/executor/pdf417_handler_test.go b/pkg/document/executor/pdf417_handler_test.go new file mode 100644 index 0000000..601e009 --- /dev/null +++ b/pkg/document/executor/pdf417_handler_test.go @@ -0,0 +1,249 @@ +package executor + +import ( + "bytes" + "encoding/json" + "testing" + + "github.com/adcondev/poster/pkg/commands/shared" + "github.com/adcondev/poster/pkg/document/schema" + "github.com/adcondev/poster/pkg/service" +) + +func TestHandlePDF417_Success(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + data := json.RawMessage(`{"data": "TEST-PDF417", "align": "center"}`) + err := exec.handlePDF417(mock, data) + if err != nil { + t.Fatalf("handlePDF417 failed: %v", err) + } + + // Verify alignment calls: AlignCenter followed by Write followed by AlignLeft + calls := mock.Calls + if len(calls) < 3 { + t.Fatalf("expected at least 3 calls on mock printer, got %d", len(calls)) + } + + hasCenter := false + hasWrite := false + for _, call := range calls { + if call.Method == "AlignCenter" { + hasCenter = true + } + if call.Method == "Write" { + hasWrite = true + writtenBytes := call.Args[0].([]byte) + if !bytes.Contains(writtenBytes, []byte("TEST-PDF417")) { + t.Errorf("written bytes missing payload data") + } + } + } + + if !hasCenter { + t.Error("expected AlignCenter call") + } + if !hasWrite { + t.Error("expected Write call") + } + + lastCall := mock.LastCall() + if lastCall == nil || lastCall.Method != "AlignLeft" { + t.Errorf("expected last call to be AlignLeft, got %v", lastCall) + } +} + +func TestHandlePDF417_EmptyData(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + data := json.RawMessage(`{"data": ""}`) + err := exec.handlePDF417(mock, data) + if err == nil { + t.Fatal("expected error for empty PDF417 data, got nil") + } +} + +func TestHandlePDF417_InvalidJSON(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + data := json.RawMessage(`{not-valid-json}`) + err := exec.handlePDF417(mock, data) + if err == nil { + t.Fatal("expected error for invalid json, got nil") + } +} + +func TestHandlePDF417_DefaultsApplied(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + data := json.RawMessage(`{"data": "DEFAULT-DATA"}`) + err := exec.handlePDF417(mock, data) + if err != nil { + t.Fatalf("handlePDF417 failed: %v", err) + } + + var writtenBytes []byte + for _, call := range mock.Calls { + if call.Method == "Write" { + writtenBytes = call.Args[0].([]byte) + break + } + } + if writtenBytes == nil { + t.Fatal("no Write call found on mock printer") + } + + // Verify defaults: + // columns: 0 -> []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, 0} + wantCol := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, 0} + if !bytes.Contains(writtenBytes, wantCol) { + t.Errorf("expected default columns cmd %v", wantCol) + } + + // rows: 0 -> []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, 0} + wantRows := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, 0} + if !bytes.Contains(writtenBytes, wantRows) { + t.Errorf("expected default rows cmd %v", wantRows) + } + + // moduleWidth: 3 -> []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 67, 3} + wantWidth := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 67, 3} + if !bytes.Contains(writtenBytes, wantWidth) { + t.Errorf("expected default moduleWidth cmd %v", wantWidth) + } + + // rowHeight: 3 -> []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 68, 3} + wantHeight := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 68, 3} + if !bytes.Contains(writtenBytes, wantHeight) { + t.Errorf("expected default rowHeight cmd %v", wantHeight) + } + + // ecLevel: 2 -> []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 69, 48, 50} + wantEC := []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 69, 48, 50} + if !bytes.Contains(writtenBytes, wantEC) { + t.Errorf("expected default ecLevel cmd %v", wantEC) + } +} + +func TestHandlePDF417_CustomOptions(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + data := json.RawMessage(`{ + "data": "CUSTOM-DATA", + "columns": 5, + "rows": 10, + "module_width": 4, + "row_height": 5, + "error_correction": 4, + "align": "right" + }`) + err := exec.handlePDF417(mock, data) + if err != nil { + t.Fatalf("handlePDF417 failed: %v", err) + } + + hasRight := false + var writtenBytes []byte + for _, call := range mock.Calls { + if call.Method == "AlignRight" { + hasRight = true + } + if call.Method == "Write" { + writtenBytes = call.Args[0].([]byte) + } + } + if !hasRight { + t.Error("expected AlignRight call") + } + if writtenBytes == nil { + t.Fatal("expected Write call") + } + + wantCol := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 65, 5} + if !bytes.Contains(writtenBytes, wantCol) { + t.Errorf("expected custom columns cmd %v", wantCol) + } + + wantRows := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 66, 10} + if !bytes.Contains(writtenBytes, wantRows) { + t.Errorf("expected custom rows cmd %v", wantRows) + } + + wantWidth := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 67, 4} + if !bytes.Contains(writtenBytes, wantWidth) { + t.Errorf("expected custom module width cmd %v", wantWidth) + } + + wantHeight := []byte{shared.GS, '(', 'k', 0x03, 0x00, 48, 68, 5} + if !bytes.Contains(writtenBytes, wantHeight) { + t.Errorf("expected custom row height cmd %v", wantHeight) + } + + wantEC := []byte{shared.GS, '(', 'k', 0x04, 0x00, 48, 69, 48, 52} + if !bytes.Contains(writtenBytes, wantEC) { + t.Errorf("expected custom ecLevel cmd %v", wantEC) + } +} + +func TestHandlePDF417_AlignLeft(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + data := json.RawMessage(`{"data": "LEFT-DATA", "align": "left"}`) + err := exec.handlePDF417(mock, data) + if err != nil { + t.Fatalf("handlePDF417 failed: %v", err) + } + + alignLeftCount := 0 + for _, call := range mock.Calls { + if call.Method == "AlignLeft" { + alignLeftCount++ + } + } + // Once before write, once to reset after write + if alignLeftCount < 2 { + t.Errorf("expected at least 2 AlignLeft calls, got %d", alignLeftCount) + } +} + +func TestExecutor_Execute_PDF417Document(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + doc := &schema.Document{ + Version: "1.0", + Profile: schema.ProfileConfig{ + Model: "POS-80", + }, + Commands: []schema.Command{ + { + Type: "pdf417", + Data: json.RawMessage(`{"data": "END-TO-END-PDF417"}`), + }, + }, + } + + if err := exec.Execute(doc); err != nil { + t.Fatalf("exec.Execute failed: %v", err) + } + + hasWrite := false + for _, call := range mock.Calls { + if call.Method == "Write" { + writtenBytes := call.Args[0].([]byte) + if bytes.Contains(writtenBytes, []byte("END-TO-END-PDF417")) { + hasWrite = true + break + } + } + } + if !hasWrite { + t.Error("expected PDF417 command to be written during document execution") + } +} diff --git a/pkg/document/schema/commands.go b/pkg/document/schema/commands.go index 6ed717d..b2569e9 100644 --- a/pkg/document/schema/commands.go +++ b/pkg/document/schema/commands.go @@ -84,6 +84,17 @@ type QRCommand struct { CircleShape bool `json:"circle_shape,omitempty"` } +// PDF417Command represents a 2D PDF417 barcode command payload. +type PDF417Command struct { + Data string `json:"data"` + Columns int `json:"columns,omitempty"` + Rows int `json:"rows,omitempty"` + ModuleWidth int `json:"module_width,omitempty"` + RowHeight int `json:"row_height,omitempty"` + ErrorCorrection int `json:"error_correction,omitempty"` + Align string `json:"align,omitempty"` +} + // BarcodeCommand represents a 1D barcode command payload. type BarcodeCommand struct { Symbology string `json:"symbology"` diff --git a/pkg/emulator/byte_parser.go b/pkg/emulator/byte_parser.go new file mode 100644 index 0000000..5f8ef3b --- /dev/null +++ b/pkg/emulator/byte_parser.go @@ -0,0 +1,347 @@ +package emulator + +import ( + "bytes" + "fmt" + + "github.com/adcondev/poster/pkg/constants" + "github.com/adcondev/poster/pkg/graphics" +) + +// ParseESC parses a raw ESC/POS byte stream and renders the resulting formatting +// and content onto the emulator Engine canvas. +func (e *Engine) ParseESC(raw []byte) error { + var textBuf bytes.Buffer + flushText := func() { + if textBuf.Len() > 0 { + e.Print(textBuf.String()) + textBuf.Reset() + } + } + + i := 0 + for i < len(raw) { + switch raw[i] { + case 0x0A: // LF + flushText() + e.NewLine() + i++ + case 0x0D: // CR + flushText() + if i+1 < len(raw) && raw[i+1] == 0x0A { + i++ + } else { + e.NewLine() + i++ + } + case 0x1B: // ESC + flushText() + i = e.parseESCCommand(raw, i) + case 0x1D: // GS + flushText() + i = e.parseGSCommand(raw, i) + default: + if raw[i] >= 0x20 { + textBuf.WriteByte(raw[i]) + } + i++ + } + + if i > len(raw) { + i = len(raw) + } + } + + flushText() + return nil +} + +// parseESCCommand processes an ESC (0x1B) command sequence and returns the new byte index. +func (e *Engine) parseESCCommand(raw []byte, i int) int { + if i+1 >= len(raw) { + return len(raw) + } + + cmd := raw[i+1] + switch cmd { + case '@': // Initialize printer + e.Reset() + return i + 2 + case '2': // Default line spacing + e.state.LineSpacing = float64(constants.DefaultLineSpacing) + return i + 2 + case 'E', '-', 'M', 'd', '3', 't': + if i+2 >= len(raw) { + return len(raw) + } + e.handleESCSingleParam(cmd, raw[i+2]) + return i + 3 + case 'a': + return e.handleESCAlign(raw, i) + case '!': + return e.handleESCPrintMode(raw, i) + case 'p': + return skipESCPulse(raw, i) + case 'B': + return skipESCBeep(raw, i) + default: + return i + 2 + } +} + +func (e *Engine) handleESCSingleParam(cmd, arg byte) { + switch cmd { + case 'E': // Bold + e.SetBold((arg & 0x01) != 0) + case '-': // Underline + mode := int(arg) + if mode >= '0' && mode <= '2' { + mode -= '0' + } + e.SetUnderline(mode) + case 'M': // Font A / B + if arg == 1 || arg == '1' { + e.SetFont("B") + } else { + e.SetFont("A") + } + case 'd': // Feed lines + e.Feed(int(arg)) + case '3': // Set line spacing + e.state.LineSpacing = float64(arg) + case 't': // Code table selection (ignored by emulator) + } +} + +func (e *Engine) handleESCAlign(raw []byte, i int) int { + if i+2 >= len(raw) { + return len(raw) + } + switch raw[i+2] { + case 1, '1': + e.AlignCenter() + case 2, '2': + e.AlignRight() + default: + e.AlignLeft() + } + return i + 3 +} + +func (e *Engine) handleESCPrintMode(raw []byte, i int) int { + if i+2 >= len(raw) { + return len(raw) + } + n := raw[i+2] + if (n & 0x01) != 0 { + e.SetFont("B") + } else { + e.SetFont("A") + } + e.SetBold((n & 0x08) != 0) + w, h := 1, 1 + if (n & 0x10) != 0 { + h = 2 + } + if (n & 0x20) != 0 { + w = 2 + } + e.SetSize(w, h) + if (n & 0x80) != 0 { + e.SetUnderline(1) + } else { + e.SetUnderline(0) + } + return i + 3 +} + +func skipESCPulse(raw []byte, i int) int { + if i+4 < len(raw) { + return i + 5 + } + return len(raw) +} + +func skipESCBeep(raw []byte, i int) int { + if i+3 < len(raw) { + return i + 4 + } + return len(raw) +} + +// parseGSCommand processes a GS (0x1D) command sequence and returns the new byte index. +func (e *Engine) parseGSCommand(raw []byte, i int) int { + if i+1 >= len(raw) { + return len(raw) + } + + switch raw[i+1] { + case '!': // Select character size + return e.handleGSSize(raw, i) + case 'B': // White/black reverse mode + return e.handleGSInverse(raw, i) + case 'V': // Cut paper + return e.handleGSCut(raw, i) + case 'v': // Print raster bit image + return e.handleGSRaster(raw, i) + case 'h', 'w', 'H', 'f': // Barcode height, width, HRI position, HRI font + if i+2 < len(raw) { + return i + 3 + } + return len(raw) + case 'k': // Print barcode + return skipGSBarcode(raw, i) + case '(': // 2D barcode / special function + return skipGS2DFunction(raw, i) + default: + return i + 2 + } +} + +func (e *Engine) handleGSSize(raw []byte, i int) int { + if i+2 >= len(raw) { + return len(raw) + } + n := raw[i+2] + w := int((n>>4)&0x07) + 1 + h := int(n&0x07) + 1 + e.SetSize(w, h) + return i + 3 +} + +func (e *Engine) handleGSInverse(raw []byte, i int) int { + if i+2 >= len(raw) { + return len(raw) + } + e.SetInverse((raw[i+2] & 0x01) != 0) + return i + 3 +} + +func (e *Engine) handleGSCut(raw []byte, i int) int { + if i+2 >= len(raw) { + return len(raw) + } + m := raw[i+2] + step := 3 + if m == 65 || m == 66 || m == 97 || m == 98 || m == 103 || m == 104 { + if i+3 < len(raw) { + e.Feed(int(raw[i+3])) + step = 4 + } + } + partial := m != 0 && m != '0' && m != 65 + e.Cut(partial) + return i + step +} + +func (e *Engine) handleGSRaster(raw []byte, i int) int { + if i+2 >= len(raw) || raw[i+2] != '0' { + return i + 2 + } + if i+7 >= len(raw) { + return len(raw) + } + + xBytes := int(raw[i+4]) | (int(raw[i+5]) << 8) + yDots := int(raw[i+6]) | (int(raw[i+7]) << 8) + dataLen := xBytes * yDots + start := i + 8 + end := start + dataLen + if end > len(raw) { + end = len(raw) + } + if xBytes > 0 && yDots > 0 { + e.renderRasterBitmap(raw[start:end], xBytes, yDots) + } + return end +} + +func (e *Engine) renderRasterBitmap(raster []byte, xBytes, yDots int) { + bmp := graphics.NewMonochromeBitmap(xBytes*8, yDots) + for y := 0; y < yDots; y++ { + for bx := 0; bx < xBytes; bx++ { + idx := y*xBytes + bx + if idx >= len(raster) { + break + } + b := raster[idx] + for bit := 0; bit < 8; bit++ { + if (b & (1 << uint(7-bit))) != 0 { + bmp.SetPixel(bx*8+bit, y, true) + } + } + } + } + _ = e.PrintImageAligned(bmp.ToImage(), xBytes*8, e.state.Align) +} + +func skipGSBarcode(raw []byte, i int) int { + if i+2 >= len(raw) { + return len(raw) + } + m := raw[i+2] + if m <= 6 { + j := i + 3 + for j < len(raw) && raw[j] != 0x00 { + j++ + } + if j < len(raw) { + return j + 1 + } + return len(raw) + } + if i+3 < len(raw) { + n := int(raw[i+3]) + end := i + 4 + n + if end > len(raw) { + return len(raw) + } + return end + } + return len(raw) +} + +func skipGS2DFunction(raw []byte, i int) int { + if i+4 < len(raw) { + pL := int(raw[i+3]) + pH := int(raw[i+4]) + end := i + 5 + (pL | (pH << 8)) + if end > len(raw) { + return len(raw) + } + return end + } + return len(raw) +} + +// RenderBytesToPNG parses raw ESC/POS commands with default 80mm configuration and returns PNG bytes. +func RenderBytesToPNG(raw []byte) ([]byte, error) { + eng, err := NewDefaultEngine() + if err != nil { + return nil, fmt.Errorf("creating default engine: %w", err) + } + if err := eng.ParseESC(raw); err != nil { + return nil, fmt.Errorf("parsing esc/pos: %w", err) + } + var buf bytes.Buffer + if err := eng.WritePNG(&buf); err != nil { + return nil, fmt.Errorf("writing png: %w", err) + } + return buf.Bytes(), nil +} + +// RenderBytesToPNGWithConfig parses raw ESC/POS commands with a custom configuration and returns PNG bytes. +func RenderBytesToPNGWithConfig(raw []byte, cfg Config) ([]byte, error) { + eng, err := NewEngine(cfg) + if err != nil { + return nil, fmt.Errorf("creating engine with config: %w", err) + } + if err := eng.ParseESC(raw); err != nil { + return nil, fmt.Errorf("parsing esc/pos: %w", err) + } + var buf bytes.Buffer + if err := eng.WritePNG(&buf); err != nil { + return nil, fmt.Errorf("writing png: %w", err) + } + return buf.Bytes(), nil +} diff --git a/pkg/emulator/byte_parser_test.go b/pkg/emulator/byte_parser_test.go new file mode 100644 index 0000000..5db89cd --- /dev/null +++ b/pkg/emulator/byte_parser_test.go @@ -0,0 +1,651 @@ +package emulator_test + +import ( + "bytes" + "image/png" + "testing" + + "github.com/adcondev/poster/pkg/commands/mechanismcontrol" + "github.com/adcondev/poster/pkg/composer" + "github.com/adcondev/poster/pkg/constants" + "github.com/adcondev/poster/pkg/emulator" +) + +// ============================================================================ +// Text and Newline Parsing Tests +// ============================================================================ + +func TestParseESC_EmptyAndNonPrintable(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + if err := eng.ParseESC(nil); err != nil { + t.Errorf("ParseESC(nil) error = %v", err) + } + + if err := eng.ParseESC([]byte{}); err != nil { + t.Errorf("ParseESC([]byte{}) error = %v", err) + } + + // Non-printable control characters should be safely skipped + nonPrintable := []byte{0x00, 0x01, 0x04, 0x07, 0x11} + if err := eng.ParseESC(nonPrintable); err != nil { + t.Errorf("ParseESC(nonPrintable) error = %v", err) + } +} + +func TestParseESC_TextAndNewlines(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + initialY := eng.State().CursorY + + // LF + if err := eng.ParseESC([]byte("Line 1\nLine 2\n")); err != nil { + t.Fatalf("ParseESC() error = %v", err) + } + yAfterLF := eng.State().CursorY + if yAfterLF <= initialY { + t.Errorf("CursorY after LF = %v, expected > %v", yAfterLF, initialY) + } + + // CR LF + eng.Reset() + if err := eng.ParseESC([]byte("Line A\r\nLine B\r\n")); err != nil { + t.Fatalf("ParseESC() error = %v", err) + } + yAfterCRLF := eng.State().CursorY + if yAfterCRLF <= initialY { + t.Errorf("CursorY after CRLF = %v, expected > %v", yAfterCRLF, initialY) + } + + // CR alone + eng.Reset() + if err := eng.ParseESC([]byte("Line X\rLine Y\r")); err != nil { + t.Fatalf("ParseESC() error = %v", err) + } + yAfterCR := eng.State().CursorY + if yAfterCR <= initialY { + t.Errorf("CursorY after CR = %v, expected > %v", yAfterCR, initialY) + } +} + +// ============================================================================ +// ESC Command Tests +// ============================================================================ + +func TestParseESC_Initialize(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + // Set bold, inverse, double size + eng.SetBold(true) + eng.SetInverse(true) + eng.SetSize(2, 2) + + // Send ESC @ (0x1B 0x40) + if err := eng.ParseESC([]byte{0x1B, '@'}); err != nil { + t.Fatalf("ParseESC(ESC @) error = %v", err) + } + + state := eng.State() + if state.IsBold { + t.Error("IsBold = true, expected false after reset") + } + if state.IsInverse { + t.Error("IsInverse = true, expected false after reset") + } + if state.ScaleW != 1.0 || state.ScaleH != 1.0 { + t.Errorf("Scale = (%v, %v), expected (1.0, 1.0) after reset", state.ScaleW, state.ScaleH) + } +} + +func TestParseESC_Bold(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + // ESC E 1 -> bold on + if err := eng.ParseESC([]byte{0x1B, 'E', 0x01}); err != nil { + t.Fatalf("ParseESC(ESC E 1) error = %v", err) + } + if !eng.State().IsBold { + t.Error("IsBold = false, want true") + } + + // ESC E 0 -> bold off + if err := eng.ParseESC([]byte{0x1B, 'E', 0x00}); err != nil { + t.Fatalf("ParseESC(ESC E 0) error = %v", err) + } + if eng.State().IsBold { + t.Error("IsBold = true, want false") + } +} + +func TestParseESC_Underline(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + tests := []struct { + input []byte + want int + }{ + {[]byte{0x1B, '-', 0x01}, 1}, + {[]byte{0x1B, '-', 0x02}, 2}, + {[]byte{0x1B, '-', 0x00}, 0}, + {[]byte{0x1B, '-', '1'}, 1}, + {[]byte{0x1B, '-', '2'}, 2}, + {[]byte{0x1B, '-', '0'}, 0}, + } + + for _, tt := range tests { + if err := eng.ParseESC(tt.input); err != nil { + t.Fatalf("ParseESC(%v) error = %v", tt.input, err) + } + if got := eng.State().IsUnderline; got != tt.want { + t.Errorf("ParseESC(%v) IsUnderline = %d, want %d", tt.input, got, tt.want) + } + } +} + +func TestParseESC_Font(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + tests := []struct { + input []byte + want string + }{ + {[]byte{0x1B, 'M', 0x01}, "B"}, + {[]byte{0x1B, 'M', 0x00}, "A"}, + {[]byte{0x1B, 'M', '1'}, "B"}, + {[]byte{0x1B, 'M', '0'}, "A"}, + } + + for _, tt := range tests { + if err := eng.ParseESC(tt.input); err != nil { + t.Fatalf("ParseESC(%v) error = %v", tt.input, err) + } + if got := eng.State().FontName; got != tt.want { + t.Errorf("ParseESC(%v) FontName = %q, want %q", tt.input, got, tt.want) + } + } +} + +func TestParseESC_Alignment(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + tests := []struct { + input []byte + want string + }{ + {[]byte{0x1B, 'a', 0x00}, "left"}, + {[]byte{0x1B, 'a', 0x01}, "center"}, + {[]byte{0x1B, 'a', 0x02}, "right"}, + {[]byte{0x1B, 'a', '0'}, "left"}, + {[]byte{0x1B, 'a', '1'}, "center"}, + {[]byte{0x1B, 'a', '2'}, "right"}, + {[]byte{0x1B, 'a', 99}, "left"}, // fallback + } + + for _, tt := range tests { + if err := eng.ParseESC(tt.input); err != nil { + t.Fatalf("ParseESC(%v) error = %v", tt.input, err) + } + if got := eng.State().Align; got != tt.want { + t.Errorf("ParseESC(%v) Align = %q, want %q", tt.input, got, tt.want) + } + } +} + +func TestParseESC_FeedLines(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + initialY := eng.State().CursorY + if err := eng.ParseESC([]byte{0x1B, 'd', 0x03}); err != nil { + t.Fatalf("ParseESC(ESC d 3) error = %v", err) + } + + if got := eng.State().CursorY; got <= initialY { + t.Errorf("CursorY = %v, expected advance after ESC d 3", got) + } +} + +func TestParseESC_LineSpacing(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + // ESC 3 n: set line spacing + if err := eng.ParseESC([]byte{0x1B, '3', 50}); err != nil { + t.Fatalf("ParseESC(ESC 3 50) error = %v", err) + } + if got := eng.State().LineSpacing; got != 50.0 { + t.Errorf("LineSpacing = %v, want 50.0", got) + } + + // ESC 2: select default line spacing + if err := eng.ParseESC([]byte{0x1B, '2'}); err != nil { + t.Fatalf("ParseESC(ESC 2) error = %v", err) + } + if got := eng.State().LineSpacing; got != float64(constants.DefaultLineSpacing) { + t.Errorf("LineSpacing = %v, want %v", got, float64(constants.DefaultLineSpacing)) + } +} + +func TestParseESC_PrintMode(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + // ESC ! with font B (0x01) | bold (0x08) | double-height (0x10) | double-width (0x20) | underline (0x80) + mode := byte(0x01 | 0x08 | 0x10 | 0x20 | 0x80) + if err := eng.ParseESC([]byte{0x1B, '!', mode}); err != nil { + t.Fatalf("ParseESC(ESC ! mode) error = %v", err) + } + + state := eng.State() + if state.FontName != "B" { + t.Errorf("FontName = %q, want \"B\"", state.FontName) + } + if !state.IsBold { + t.Error("IsBold = false, want true") + } + if state.ScaleW != 2.0 || state.ScaleH != 2.0 { + t.Errorf("Scale = (%v, %v), want (2.0, 2.0)", state.ScaleW, state.ScaleH) + } + if state.IsUnderline != 1 { + t.Errorf("IsUnderline = %d, want 1", state.IsUnderline) + } + + // Clear print mode + if err := eng.ParseESC([]byte{0x1B, '!', 0x00}); err != nil { + t.Fatalf("ParseESC(ESC ! 0) error = %v", err) + } + state = eng.State() + if state.FontName != "A" { + t.Errorf("FontName = %q, want \"A\"", state.FontName) + } + if state.IsBold { + t.Error("IsBold = true, want false") + } + if state.ScaleW != 1.0 || state.ScaleH != 1.0 { + t.Errorf("Scale = (%v, %v), want (1.0, 1.0)", state.ScaleW, state.ScaleH) + } + if state.IsUnderline != 0 { + t.Errorf("IsUnderline = %d, want 0", state.IsUnderline) + } +} + +func TestParseESC_SkippedCommands(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + // ESC t (code table), ESC p (pulse), ESC B (beep), and unknown ESC + raw := []byte{ + 0x1B, 't', 0x00, + 0x1B, 'p', 0x00, 0x19, 0x32, + 0x1B, 'B', 0x02, 0x03, + 0x1B, 0xFF, + } + + if err := eng.ParseESC(raw); err != nil { + t.Fatalf("ParseESC(skipped commands) error = %v", err) + } +} + +// ============================================================================ +// GS Command Tests +// ============================================================================ + +func TestParseESC_GSCharacterSize(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + tests := []struct { + n byte + wantW float64 + wantH float64 + }{ + {0x00, 1.0, 1.0}, + {0x11, 2.0, 2.0}, + {0x77, 8.0, 8.0}, + {0x31, 4.0, 2.0}, // width multiplier 3+1=4, height multiplier 1+1=2 + } + + for _, tt := range tests { + if err := eng.ParseESC([]byte{0x1D, '!', tt.n}); err != nil { + t.Fatalf("ParseESC(GS ! %d) error = %v", tt.n, err) + } + state := eng.State() + if state.ScaleW != tt.wantW || state.ScaleH != tt.wantH { + t.Errorf("GS ! %d Scale = (%v, %v), want (%v, %v)", + tt.n, state.ScaleW, state.ScaleH, tt.wantW, tt.wantH) + } + } +} + +func TestParseESC_GSInverse(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + // GS B 1: inverse on + if err := eng.ParseESC([]byte{0x1D, 'B', 0x01}); err != nil { + t.Fatalf("ParseESC(GS B 1) error = %v", err) + } + if !eng.State().IsInverse { + t.Error("IsInverse = false, want true") + } + + // GS B 0: inverse off + if err := eng.ParseESC([]byte{0x1D, 'B', 0x00}); err != nil { + t.Fatalf("ParseESC(GS B 0) error = %v", err) + } + if eng.State().IsInverse { + t.Error("IsInverse = true, want false") + } +} + +func TestParseESC_GSCut(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + // GS V 0 (full cut) + if err := eng.ParseESC([]byte{0x1D, 'V', 0x00}); err != nil { + t.Fatalf("ParseESC(GS V 0) error = %v", err) + } + + // GS V 1 (partial cut) + if err := eng.ParseESC([]byte{0x1D, 'V', 0x01}); err != nil { + t.Fatalf("ParseESC(GS V 1) error = %v", err) + } + + // GS V 65 n (feed n lines and cut) + if err := eng.ParseESC([]byte{0x1D, 'V', 65, 3}); err != nil { + t.Fatalf("ParseESC(GS V 65 3) error = %v", err) + } + + // GS V 66 n (feed n lines and partial cut) + if err := eng.ParseESC([]byte{0x1D, 'V', 66, 2}); err != nil { + t.Fatalf("ParseESC(GS V 66 2) error = %v", err) + } +} + +func TestParseESC_GSRasterBitImage(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + initialY := eng.State().CursorY + + // Construct a 16x8 monochrome raster image: + // xL=2, xH=0 (2 bytes = 16 dots per row), yL=8, yH=0 (8 dots high) + // total data bytes = 2 * 8 = 16 bytes + xBytes := 2 + yDots := 8 + cmd := make([]byte, 0, 8+xBytes*yDots) + cmd = append(cmd, 0x1D, 'v', '0', 0x00, byte(xBytes), 0x00, byte(yDots), 0x00) + for i := 0; i < xBytes*yDots; i++ { + cmd = append(cmd, 0xAA) + } + + if err := eng.ParseESC(cmd); err != nil { + t.Fatalf("ParseESC(GS v 0) error = %v", err) + } + + if got := eng.State().CursorY; got <= initialY { + t.Errorf("CursorY = %v, expected advance after raster image", got) + } + + // Zero dimension raster bit image should be safely ignored + zeroCmd := []byte{0x1D, 'v', '0', 0x00, 0x00, 0x00, 0x00, 0x00} + if err := eng.ParseESC(zeroCmd); err != nil { + t.Fatalf("ParseESC(zero raster) error = %v", err) + } +} + +func TestParseESC_GSBarcodeAnd2DSkip(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + raw := []byte{ + // Barcode formatting parameters + 0x1D, 'h', 80, // height + 0x1D, 'w', 3, // width + 0x1D, 'H', 2, // HRI position + 0x1D, 'f', 0, // HRI font + // Barcode type m <= 6 (null terminated) + 0x1D, 'k', 2, '1', '2', '3', '4', 0x00, + // Barcode type m > 6 (explicit length prefix) + 0x1D, 'k', 67, 4, '9', '8', '7', '6', + // 2D function GS ( k pL pH ... + 0x1D, '(', 'k', 0x04, 0x00, 0x31, 0x50, 0x30, 0x00, + // Unknown GS command + 0x1D, 0xFE, + } + + if err := eng.ParseESC(raw); err != nil { + t.Fatalf("ParseESC(barcode and 2D skip) error = %v", err) + } +} + +// ============================================================================ +// Truncated and Malformed Stream Tests +// ============================================================================ + +func TestParseESC_TruncatedInputs(t *testing.T) { + eng, err := emulator.NewDefaultEngine() + if err != nil { + t.Fatalf("NewDefaultEngine() error = %v", err) + } + + cases := map[string][]byte{ + "bare ESC": {0x1B}, + "bare GS": {0x1D}, + "ESC E truncated": {0x1B, 'E'}, + "ESC - truncated": {0x1B, '-'}, + "ESC M truncated": {0x1B, 'M'}, + "ESC a truncated": {0x1B, 'a'}, + "ESC d truncated": {0x1B, 'd'}, + "ESC 3 truncated": {0x1B, '3'}, + "ESC ! truncated": {0x1B, '!'}, + "ESC t truncated": {0x1B, 't'}, + "ESC p truncated 1": {0x1B, 'p'}, + "ESC p truncated 2": {0x1B, 'p', 0x00, 0x10}, + "ESC B truncated 1": {0x1B, 'B'}, + "ESC B truncated 2": {0x1B, 'B', 0x01}, + "GS ! truncated": {0x1D, '!'}, + "GS B truncated": {0x1D, 'B'}, + "GS V truncated 1": {0x1D, 'V'}, + "GS V 65 truncated": {0x1D, 'V', 65}, + "GS v truncated": {0x1D, 'v'}, + "GS v 0 truncated header": {0x1D, 'v', '0', 0x00, 0x02}, + "GS v 0 truncated data": {0x1D, 'v', '0', 0x00, 0x02, 0x00, 0x08, 0x00, 0xFF}, + "GS h truncated": {0x1D, 'h'}, + "GS k truncated": {0x1D, 'k'}, + "GS k type 0 missing null": {0x1D, 'k', 0x00, '1', '2', '3'}, + "GS k type 67 truncated data": {0x1D, 'k', 67, 10, '1'}, + "GS ( truncated header": {0x1D, '(', 'k'}, + "GS ( truncated data": {0x1D, '(', 'k', 0x20, 0x00, 0x01}, + "trailing ESC after text": {'T', 'e', 'x', 't', 0x1B}, + "trailing GS after text": {'T', 'e', 'x', 't', 0x1D}, + "trailing CR": {'T', 'e', 'x', 't', 0x0D}, + } + + for name, data := range cases { + t.Run(name, func(t *testing.T) { + if err := eng.ParseESC(data); err != nil { + t.Fatalf("ParseESC(%s) unexpected error = %v", name, err) + } + }) + } +} + +// ============================================================================ +// RenderBytesToPNG Tests +// ============================================================================ + +func TestRenderBytesToPNG_ValidOutput(t *testing.T) { + raw := []byte("Header Line\nItem 1 $10.00\nTotal $10.00\n") + pngBytes, err := emulator.RenderBytesToPNG(raw) + if err != nil { + t.Fatalf("RenderBytesToPNG() error = %v", err) + } + + if len(pngBytes) == 0 { + t.Fatal("RenderBytesToPNG() returned empty bytes") + } + + img, err := png.Decode(bytes.NewReader(pngBytes)) + if err != nil { + t.Fatalf("png.Decode() error = %v", err) + } + + if got := img.Bounds().Dx(); got != constants.PaperPxWidth80mm { + t.Errorf("Image width = %d, want %d", got, constants.PaperPxWidth80mm) + } + + if got := img.Bounds().Dy(); got <= 0 { + t.Errorf("Image height = %d, want > 0", got) + } +} + +func TestRenderBytesToPNG_EmptyCanvas(t *testing.T) { + pngBytes, err := emulator.RenderBytesToPNG([]byte{}) + if err != nil { + t.Fatalf("RenderBytesToPNG([]byte{}) error = %v", err) + } + + img, err := png.Decode(bytes.NewReader(pngBytes)) + if err != nil { + t.Fatalf("png.Decode() error = %v", err) + } + + if got := img.Bounds().Dx(); got != constants.PaperPxWidth80mm { + t.Errorf("Image width = %d, want %d", got, constants.PaperPxWidth80mm) + } +} + +// ============================================================================ +// RenderBytesToPNGWithConfig Tests +// ============================================================================ + +func TestRenderBytesToPNGWithConfig_58mm(t *testing.T) { + cfg := emulator.Config{ + PaperPxWidth: constants.PaperPxWidth58mm, + DPI: constants.DefaultDPI, + } + + raw := []byte("58mm Thermal Receipt\nItem A $5.00\n") + pngBytes, err := emulator.RenderBytesToPNGWithConfig(raw, cfg) + if err != nil { + t.Fatalf("RenderBytesToPNGWithConfig() error = %v", err) + } + + img, err := png.Decode(bytes.NewReader(pngBytes)) + if err != nil { + t.Fatalf("png.Decode() error = %v", err) + } + + if got := img.Bounds().Dx(); got != constants.PaperPxWidth58mm { + t.Errorf("Image width = %d, want %d", got, constants.PaperPxWidth58mm) + } +} + +func TestRenderBytesToPNGWithConfig_InvalidConfig(t *testing.T) { + cfg := emulator.Config{ + PaperPxWidth: -100, + } + + _, err := emulator.RenderBytesToPNGWithConfig([]byte("Test"), cfg) + if err == nil { + t.Fatal("RenderBytesToPNGWithConfig() expected error for negative width, got nil") + } +} + +// ============================================================================ +// Composer Integration Tests +// ============================================================================ + +func TestParseESC_ComposerIntegration(t *testing.T) { + proto := composer.NewEscpos() + + var buf bytes.Buffer + buf.Write(proto.InitializePrinter()) + buf.Write(proto.CenterAlign()) + + line1, err := proto.PrintLn("SAMPLE RECEIPT") + if err != nil { + t.Fatalf("PrintLn error = %v", err) + } + buf.Write(line1) + + buf.Write(proto.LeftAlign()) + buf.Write(proto.DoubleSizeText()) + + line2, err := proto.PrintLn("Large Coffee") + if err != nil { + t.Fatalf("PrintLn error = %v", err) + } + buf.Write(line2) + + buf.Write(proto.SingleSizeText()) + line3, err := proto.PrintLn("Total: $4.50") + if err != nil { + t.Fatalf("PrintLn error = %v", err) + } + buf.Write(line3) + + cutCmd, err := proto.MechanismControl.CutPaper(mechanismcontrol.CutModePartial) + if err != nil { + t.Fatalf("CutPaper error = %v", err) + } + buf.Write(cutCmd) + + pngBytes, err := emulator.RenderBytesToPNG(buf.Bytes()) + if err != nil { + t.Fatalf("RenderBytesToPNG() error = %v", err) + } + + img, err := png.Decode(bytes.NewReader(pngBytes)) + if err != nil { + t.Fatalf("png.Decode() error = %v", err) + } + + if got := img.Bounds().Dx(); got != constants.PaperPxWidth80mm { + t.Errorf("Image width = %d, want %d", got, constants.PaperPxWidth80mm) + } + if got := img.Bounds().Dy(); got <= 0 { + t.Errorf("Image height = %d, want > 0", got) + } +} diff --git a/pkg/graphics/barcode.go b/pkg/graphics/barcode.go index f3b661e..68b7a88 100644 --- a/pkg/graphics/barcode.go +++ b/pkg/graphics/barcode.go @@ -9,8 +9,6 @@ import ( ) var ( - // TODO: Agregar soporte para más simbologías si el paquete barcode lo permite - // symMap mapea nombres de simbologías a constantes del paquete barcode symMap = map[string]barcode.Symbology{ constants.UPCA.String(): barcode.UPCA, @@ -24,6 +22,11 @@ var ( // Agregar soporte para sinónimos comunes constants.JAN13.String(): barcode.EAN13, // JAN13 es equivalente a EAN13 constants.JAN8.String(): barcode.EAN8, // JAN8 es equivalente a EAN8 + "code93": barcode.CODE93, + "gs1128": barcode.GS1128, + "gs1_128": barcode.GS1128, + "code128auto": barcode.CODE128Auto, + "code128_auto": barcode.CODE128Auto, } // hriPosMap mapea posiciones HRI a constantes del paquete barcode @@ -44,12 +47,12 @@ var ( // MapSymbology mapea los nombres del schema a las constantes del paquete barcode func MapSymbology(sym string) (barcode.Symbology, error) { // Normalizar el input - normalized := strings.ToLower(strings.ReplaceAll(sym, "-", "")) + normalized := strings.NewReplacer("-", "", "_", "").Replace(strings.ToLower(strings.TrimSpace(sym))) symbology, ok := symMap[normalized] if !ok { // Listar simbologías soportadas en el error - return 0, fmt.Errorf("unsupported barcode symbology: %s (supported: UPC-A, UPC-E, EAN13, EAN8, CODE39, CODE128, ITF, CODABAR)", sym) + return 0, fmt.Errorf("unsupported barcode symbology: %s (supported: UPC-A, UPC-E, EAN13, EAN8, CODE39, CODE128, ITF, CODABAR, CODE93, GS1-128, CODE128_AUTO)", sym) } return symbology, nil @@ -108,8 +111,7 @@ type BarcodeConfig struct { Height barcode.Height // Altura en dots HRIPosition barcode.HRIPosition // Posición del texto HRIFont barcode.HRIFont // Fuente del texto - // TODO: Check CodeSet only applies to CODE128 and do it automatically - CodeSet barcode.Code128Set // Opcional: Específico para CODE128 manual + CodeSet barcode.Code128Set // Opcional: Específico para CODE128 manual } // DefaultBarcodeConfig devuelve una configuración segura diff --git a/pkg/graphics/graph_engine.go b/pkg/graphics/graph_engine.go index 91f0416..4785757 100644 --- a/pkg/graphics/graph_engine.go +++ b/pkg/graphics/graph_engine.go @@ -10,25 +10,24 @@ import ( // DitherMode defines how images are converted to monochrome type DitherMode int -// TODO: Implement Floyd-Steinberg and Ordered dithering methods in future - const ( // Threshold applies simple threshold conversion Threshold DitherMode = iota // Atkinson applies Atkinson dithering algorithm Atkinson - // FloydSteinberg applies Floyd-Steinberg dithering (future) - // FloydSteinberg - // Ordered applies ordered dithering with Bayer matrix (future) - // Ordered + // FloydSteinberg applies Floyd-Steinberg dithering algorithm + FloydSteinberg + // Ordered applies ordered dithering with a 4x4 Bayer matrix + Ordered ) // DitherMap maps constants to DitherMode var DitherMap = map[string]DitherMode{ - constants.Threshold.String(): Threshold, - constants.Atkinson.String(): Atkinson, - // constants.DitheringFloydSteinberg: FloydSteinberg, - // constants.DitheringOrdered: Ordered, + constants.Threshold.String(): Threshold, + constants.Atkinson.String(): Atkinson, + constants.FloydSteinberg.String(): FloydSteinberg, + constants.Ordered.String(): Ordered, + "bayer": Ordered, } // ScaleMode defines the scaling algorithm @@ -105,6 +104,10 @@ func (p *Pipeline) Process(img image.Image) (*MonochromeBitmap, error) { switch p.opts.Dithering { case Atkinson: mono = p.applyAtkinson(gray) + case FloydSteinberg: + mono = p.applyFloydSteinberg(gray) + case Ordered: + mono = p.applyOrdered(gray) case Threshold: fallthrough default: @@ -204,8 +207,6 @@ func (p *Pipeline) applyThreshold(gray *image.Gray) *MonochromeBitmap { return mono } -// TODO: Implement Floyd-Steinberg and Ordered dithering methods in future - // applyAtkinson implements Atkinson dithering algorithm func (p *Pipeline) applyAtkinson(gray *image.Gray) *MonochromeBitmap { bounds := gray.Bounds() @@ -274,3 +275,101 @@ func (p *Pipeline) applyAtkinson(gray *image.Gray) *MonochromeBitmap { return mono } + +// applyFloydSteinberg implements Floyd-Steinberg error diffusion dithering. +func (p *Pipeline) applyFloydSteinberg(gray *image.Gray) *MonochromeBitmap { + bounds := gray.Bounds() + width, height := bounds.Dx(), bounds.Dy() + mono := NewMonochromeBitmap(width, height) + if width <= 0 || height <= 0 { + return mono + } + + work := make([]int, width*height) + for y := 0; y < height; y++ { + rowOffset := y * width + for x := 0; x < width; x++ { + work[rowOffset+x] = int(gray.GrayAt(bounds.Min.X+x, bounds.Min.Y+y).Y) + } + } + + threshold := int(p.opts.Threshold) + + for y := 0; y < height; y++ { + rowOffset := y * width + nextRowOffset := (y + 1) * width + + for x := 0; x < width; x++ { + idx := rowOffset + x + oldPixel := work[idx] + newPixel := 0 + if oldPixel > threshold { + newPixel = 255 + } + + mono.SetPixel(x, y, newPixel == 0) + + err := oldPixel - newPixel + + if x+1 < width { + work[idx+1] += err * 7 / 16 + } + if y+1 < height { + if x-1 >= 0 { + work[nextRowOffset+(x-1)] += err * 3 / 16 + } + work[nextRowOffset+x] += err * 5 / 16 + if x+1 < width { + work[nextRowOffset+(x+1)] += err * 1 / 16 + } + } + } + } + + return mono +} + +// applyOrdered implements ordered dithering using a 4x4 Bayer matrix. +func (p *Pipeline) applyOrdered(gray *image.Gray) *MonochromeBitmap { + bounds := gray.Bounds() + width, height := bounds.Dx(), bounds.Dy() + mono := NewMonochromeBitmap(width, height) + if width <= 0 || height <= 0 { + return mono + } + + bayer4x4 := [4][4]int{ + {0, 8, 2, 10}, + {12, 4, 14, 6}, + {3, 11, 1, 9}, + {15, 7, 13, 5}, + } + + baseThreshold := int(p.opts.Threshold) + + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + bayerVal := (bayer4x4[y%4][x%4]*16 + 8) - 128 + localThreshold := baseThreshold + bayerVal/2 + val := int(gray.GrayAt(bounds.Min.X+x, bounds.Min.Y+y).Y) + if val < localThreshold { + mono.SetPixel(x, y, true) + } + } + } + + return mono +} + +// SubBand extracts a horizontal band of the monochrome bitmap from startY with bandHeight. +func (m *MonochromeBitmap) SubBand(startY, bandHeight int) *MonochromeBitmap { + if m == nil || startY < 0 || startY >= m.Height || bandHeight <= 0 { + return NewMonochromeBitmap(0, 0) + } + if startY+bandHeight > m.Height { + bandHeight = m.Height - startY + } + sub := NewMonochromeBitmap(m.Width, bandHeight) + copy(sub.data, m.data[startY*m.bytesPerRow:(startY+bandHeight)*m.bytesPerRow]) + return sub +} diff --git a/pkg/graphics/graph_engine_test.go b/pkg/graphics/graph_engine_test.go index 5a10892..eb89f7b 100644 --- a/pkg/graphics/graph_engine_test.go +++ b/pkg/graphics/graph_engine_test.go @@ -199,3 +199,207 @@ func TestPipeline_Process_Atkinson_DiffusionLogic(t *testing.T) { }) } } + +func TestDitherMap_Lookups(t *testing.T) { + tests := []struct { + key string + expected graphics.DitherMode + }{ + {"threshold", graphics.Threshold}, + {"atkinson", graphics.Atkinson}, + {"floyd_steinberg", graphics.FloydSteinberg}, + {"ordered", graphics.Ordered}, + {"bayer", graphics.Ordered}, + } + + for _, tt := range tests { + t.Run(tt.key, func(t *testing.T) { + mode, ok := graphics.DitherMap[tt.key] + if !ok { + t.Fatalf("DitherMap missing key %q", tt.key) + } + if mode != tt.expected { + t.Errorf("DitherMap[%q] = %v, want %v", tt.key, mode, tt.expected) + } + }) + } +} + +func TestPipeline_Process_FloydSteinberg(t *testing.T) { + opts := graphics.DefaultOptions() + opts.Dithering = graphics.FloydSteinberg + opts.Threshold = 128 + p := graphics.NewPipeline(opts) + + // Test with mid-gray image + img := image.NewGray(image.Rect(0, 0, 8, 8)) + for i := 0; i < 64; i++ { + img.SetGray(i%8, i/8, color.Gray{Y: 128}) + } + + mono, err := p.Process(img) + if err != nil { + t.Fatalf("Process failed: %v", err) + } + + blackCount := 0 + for y := 0; y < 8; y++ { + for x := 0; x < 8; x++ { + if mono.GetPixel(x, y) { + blackCount++ + } + } + } + + // Mid-gray should yield a mix of black and white pixels + if blackCount == 0 || blackCount == 64 { + t.Errorf("Floyd-Steinberg dithering produced uniform output for gray input: %d/64 black", blackCount) + } + + // Test extreme inputs: all white should produce 0 black pixels + whiteImg := image.NewGray(image.Rect(0, 0, 4, 4)) + for i := 0; i < 16; i++ { + whiteImg.SetGray(i%4, i/4, color.Gray{Y: 255}) + } + whiteMono, err := p.Process(whiteImg) + if err != nil { + t.Fatalf("Process whiteImg failed: %v", err) + } + for y := 0; y < 4; y++ { + for x := 0; x < 4; x++ { + if whiteMono.GetPixel(x, y) { + t.Errorf("Expected white pixel at (%d, %d)", x, y) + } + } + } +} + +func TestPipeline_Process_Ordered(t *testing.T) { + opts := graphics.DefaultOptions() + opts.Dithering = graphics.Ordered + opts.Threshold = 128 + p := graphics.NewPipeline(opts) + + // Mid-gray image (128) + img := image.NewGray(image.Rect(0, 0, 4, 4)) + for i := 0; i < 16; i++ { + img.SetGray(i%4, i/4, color.Gray{Y: 128}) + } + + mono, err := p.Process(img) + if err != nil { + t.Fatalf("Process failed: %v", err) + } + + blackCount := 0 + for y := 0; y < 4; y++ { + for x := 0; x < 4; x++ { + if mono.GetPixel(x, y) { + blackCount++ + } + } + } + + // In a 4x4 Bayer matrix with base threshold 128, mid-gray produces a balanced pattern + if blackCount == 0 || blackCount == 16 { + t.Errorf("Ordered dithering produced uniform output for gray input: %d/16 black", blackCount) + } + + // Test solid black input + blackImg := image.NewGray(image.Rect(0, 0, 4, 4)) + for i := 0; i < 16; i++ { + blackImg.SetGray(i%4, i/4, color.Gray{Y: 0}) + } + blackMono, err := p.Process(blackImg) + if err != nil { + t.Fatalf("Process blackImg failed: %v", err) + } + for y := 0; y < 4; y++ { + for x := 0; x < 4; x++ { + if !blackMono.GetPixel(x, y) { + t.Errorf("Expected black pixel at (%d, %d)", x, y) + } + } + } +} + +func TestMonochromeBitmap_SubBand(t *testing.T) { + // Create a 16x10 bitmap + bm := graphics.NewMonochromeBitmap(16, 10) + // Set specific pixels + bm.SetPixel(0, 0, true) + bm.SetPixel(5, 2, true) + bm.SetPixel(10, 4, true) + bm.SetPixel(15, 7, true) + bm.SetPixel(7, 9, true) + + t.Run("first band", func(t *testing.T) { + band := bm.SubBand(0, 4) + if band.Width != 16 || band.Height != 4 { + t.Fatalf("unexpected band dimensions: %dx%d, want 16x4", band.Width, band.Height) + } + if !band.GetPixel(0, 0) { + t.Error("expected pixel at (0, 0) to be black") + } + if !band.GetPixel(5, 2) { + t.Error("expected pixel at (5, 2) to be black") + } + if band.GetPixel(10, 3) { + t.Error("expected pixel at (10, 3) to be white") + } + }) + + t.Run("middle band", func(t *testing.T) { + band := bm.SubBand(4, 4) + if band.Width != 16 || band.Height != 4 { + t.Fatalf("unexpected band dimensions: %dx%d, want 16x4", band.Width, band.Height) + } + // Pixel at (10, 4) in original is at y=0 in band + if !band.GetPixel(10, 0) { + t.Error("expected pixel at (10, 0) in band to be black") + } + // Pixel at (15, 7) in original is at y=3 in band + if !band.GetPixel(15, 3) { + t.Error("expected pixel at (15, 3) in band to be black") + } + }) + + t.Run("tail band clamped to height", func(t *testing.T) { + band := bm.SubBand(8, 4) // 8 + 4 = 12 > 10, clamped to 2 rows + if band.Width != 16 || band.Height != 2 { + t.Fatalf("unexpected band dimensions: %dx%d, want 16x2", band.Width, band.Height) + } + // Pixel at (7, 9) in original is at y=1 in band + if !band.GetPixel(7, 1) { + t.Error("expected pixel at (7, 1) in band to be black") + } + }) + + t.Run("invalid bounds return empty bitmap", func(t *testing.T) { + invalidCases := []struct { + name string + bm *graphics.MonochromeBitmap + startY int + height int + }{ + {"negative startY", bm, -1, 4}, + {"startY at height", bm, 10, 2}, + {"startY beyond height", bm, 15, 2}, + {"zero height", bm, 0, 0}, + {"negative height", bm, 0, -2}, + {"nil bitmap", nil, 0, 4}, + } + + for _, ic := range invalidCases { + t.Run(ic.name, func(t *testing.T) { + sub := ic.bm.SubBand(ic.startY, ic.height) + if sub == nil { + t.Fatal("SubBand returned nil, expected empty bitmap") + } + if sub.Width != 0 || sub.Height != 0 { + t.Errorf("SubBand returned %dx%d, want 0x0", sub.Width, sub.Height) + } + }) + } + }) +} diff --git a/pkg/profile/escpos_profile.go b/pkg/profile/escpos_profile.go index 5461ec1..a6510ab 100644 --- a/pkg/profile/escpos_profile.go +++ b/pkg/profile/escpos_profile.go @@ -39,6 +39,7 @@ type Escpos struct { // Configuración avanzada (opcional) ImageThreshold int // Umbral para conversión B/N (0-255) Dithering graphics.DitherMode // Tipo de dithering por defecto + MaxBandHeight int // MaxBandHeight splits large raster bitmaps into horizontal bands (0 = no split) // Debug info DebugLog bool // Habilitar logs de depuración @@ -52,6 +53,7 @@ func CreatePt210() *Escpos { p.CodeTable = character.PC850 p.QRMaxSize = 19 // Máxima versión QR soportada p.HasQR = true // Soporta QR nativo + p.MaxBandHeight = 256 return p } @@ -61,6 +63,7 @@ func CreateGP58N() *Escpos { p.Model = "58mm GP-58N" p.CodeTable = character.PC850 + p.MaxBandHeight = 256 return p } @@ -83,6 +86,7 @@ func CreateProfile58mm() *Escpos { CodeTable: character.PC850, ImageThreshold: 128, + MaxBandHeight: 256, } } diff --git a/pkg/service/printer_service.go b/pkg/service/printer_service.go index a4f5db4..b308a0e 100644 --- a/pkg/service/printer_service.go +++ b/pkg/service/printer_service.go @@ -367,6 +367,30 @@ func (p *Printer) PrintBitmap(bitmap *graphics.MonochromeBitmap) error { return fmt.Errorf("bitmap height %d exceeds uint16 max %d", height, maxUint16) } + if p.Profile.MaxBandHeight > 0 && bitmap.Height > p.Profile.MaxBandHeight { + for y := 0; y < bitmap.Height; y += p.Profile.MaxBandHeight { + band := bitmap.SubBand(y, p.Profile.MaxBandHeight) + bandWidth := band.GetWidthBytes() + bandHeight := band.Height + if bandWidth < 0 || bandWidth > maxUint16 || bandHeight < 0 || bandHeight > maxUint16 { + return fmt.Errorf("band dimensions out of range at y=%d: %dx%d", y, bandWidth, bandHeight) + } + cmd, err := p.Protocol.BitImage.PrintRasterBitImage( + 0, // normal mode + uint16(bandWidth), + uint16(bandHeight), + band.GetRasterData(), + ) + if err != nil { + return fmt.Errorf("generate raster band at y=%d: %w", y, err) + } + if err := p.Write(cmd); err != nil { + return fmt.Errorf("write raster band at y=%d: %w", y, err) + } + } + return nil + } + cmd, err := p.Protocol.BitImage.PrintRasterBitImage( 0, // normal mode uint16(width),