From 05cfefb564936aa0460354b2684220d4f8ed629e Mon Sep 17 00:00:00 2001 From: adcondev Date: Sun, 18 Oct 2026 12:20:55 -0700 Subject: [PATCH] feat(profile): add typography normalization, multi-codepage switching, and profile presets --- cmd/poster/parsing.go | 40 +-- pkg/constants/defaults.go | 6 +- pkg/document/executor/handler_executor.go | 22 +- .../executor/handler_executor_test.go | 96 ++++++ pkg/profile/escpos_encoding.go | 64 ++++ pkg/profile/escpos_encoding_test.go | 7 + pkg/profile/escpos_profile.go | 13 +- pkg/profile/magic_encode.go | 118 +++++++ pkg/profile/magic_encode_test.go | 300 ++++++++++++++++++ pkg/profile/profile_factory.go | 109 +++++++ pkg/profile/profile_test.go | 296 +++++++++++++++++ pkg/service/printer_service.go | 4 +- 12 files changed, 1029 insertions(+), 46 deletions(-) create mode 100644 pkg/profile/magic_encode.go create mode 100644 pkg/profile/magic_encode_test.go create mode 100644 pkg/profile/profile_factory.go create mode 100644 pkg/profile/profile_test.go diff --git a/cmd/poster/parsing.go b/cmd/poster/parsing.go index 9dacd53..f5eebc1 100644 --- a/cmd/poster/parsing.go +++ b/cmd/poster/parsing.go @@ -7,7 +7,6 @@ import ( "log" "os" "path/filepath" - "strings" "github.com/adcondev/poster/internal/load" "github.com/adcondev/poster/pkg/constants" @@ -153,40 +152,27 @@ func getPrinterNameFromDocument(config *Config, jsonData []byte) (string, error) } func createProfile(doc *schema.Document) *profile.Escpos { - var prof *profile.Escpos - - // Select profile based on paper width or model - if doc.Profile.Model != "" { - switch strings.ToLower(doc.Profile.Model) { - case "80mm ec-pm-80250", "ec-pm-80250": - prof = profile.CreateECPM80250() - case "58mm pt-210", "pt-210": - prof = profile.CreatePt210() - case "58mm gp-58n", "gp-58n": - prof = profile.CreateGP58N() - default: - if doc.Profile.PaperWidth >= 80 { - prof = profile.CreateProfile80mm() - } else { - prof = profile.CreateProfile58mm() - } - } - } else { - // Default based on paper width - if doc.Profile.PaperWidth >= 80 { - prof = profile.CreateProfile80mm() - } else { + prof, ok := profile.ProfileFromModel(doc.Profile.Model) + if !ok { + if doc.Profile.PaperWidth == 58 { prof = profile.CreateProfile58mm() + } else { + prof = profile.CreateProfile80mm() } } - // Apply JSON overrides - if doc.Profile.Model != "" { - prof.Model = doc.Profile.Model + prof.Model = doc.Profile.Model + if doc.Profile.PaperWidth > 0 { + prof.PaperWidth = float64(doc.Profile.PaperWidth) } if doc.Profile.DPI > 0 { prof.DPI = doc.Profile.DPI } + if doc.Profile.CodeTable != "" { + if ct, ok := profile.ParseCodeTable(doc.Profile.CodeTable); ok { + prof.CodeTable = ct + } + } prof.HasQR = doc.Profile.HasQR return prof diff --git a/pkg/constants/defaults.go b/pkg/constants/defaults.go index 1622f60..c61e0c7 100644 --- a/pkg/constants/defaults.go +++ b/pkg/constants/defaults.go @@ -33,7 +33,11 @@ var ( ValidDPIs = []int{DefaultDPI, 300, 600} // ValidCodeTables for character encoding - ValidCodeTables = []string{"WPC1252", "PC850", "PC437", "PC858"} + ValidCodeTables = []string{ + "PC437", "PC850", "PC852", "PC855", "PC858", "PC860", "PC862", "PC863", "PC865", "PC866", + "WPC1250", "WPC1251", "WPC1252", "WPC1253", "WPC1254", "WPC1255", "WPC1256", "WPC1257", "WPC1258", + "ISO88592", "ISO88597", "ISO885915", "Katakana", "Hiragana", "ShiftJIS", + } ) // Text defaults diff --git a/pkg/document/executor/handler_executor.go b/pkg/document/executor/handler_executor.go index 61a2b7f..26c4196 100644 --- a/pkg/document/executor/handler_executor.go +++ b/pkg/document/executor/handler_executor.go @@ -8,6 +8,7 @@ import ( "github.com/adcondev/poster/pkg/commands/character" "github.com/adcondev/poster/pkg/constants" "github.com/adcondev/poster/pkg/document/schema" + "github.com/adcondev/poster/pkg/profile" "github.com/adcondev/poster/pkg/service" ) @@ -105,16 +106,7 @@ func (e *Executor) Execute(doc *schema.Document) error { // setCodeTable configures the character code table with fallback to Windows-1252. func (e *Executor) setCodeTable(tableName string) error { - tables := map[string]character.CodeTable{ - "PC437": character.PC437, - "PC850": character.PC850, - "PC852": character.PC852, - "WPC1252": character.WPC1252, - "PC866": character.PC866, - "PC858": character.PC858, - } - - table, ok := tables[tableName] + table, ok := profile.ParseCodeTable(tableName) if !ok { return e.printer.SetCodeTable(character.WPC1252) } @@ -165,10 +157,14 @@ func (e *Executor) applyProfileFromDocument(doc *schema.Document) error { // applyProfileOrDefaults applies default profile settings when omitted in JSON. func (e *Executor) applyProfileOrDefaults(config schema.ProfileConfig) error { prof := e.printer.GetProfile() - if config.PaperWidth == 0 { - prof.PaperWidth = constants.Paper80mm - } else { + if config.PaperWidth > 0 { prof.PaperWidth = float64(config.PaperWidth) + } else { + if preset, ok := profile.ProfileFromModel(config.Model); ok && preset.PaperWidth > 0 { + prof.PaperWidth = preset.PaperWidth + } else if prof.PaperWidth <= 0 { + prof.PaperWidth = constants.Paper80mm + } } if config.CodeTable == "" { diff --git a/pkg/document/executor/handler_executor_test.go b/pkg/document/executor/handler_executor_test.go index 4fac10c..c613b97 100644 --- a/pkg/document/executor/handler_executor_test.go +++ b/pkg/document/executor/handler_executor_test.go @@ -5,6 +5,8 @@ import ( "strings" "testing" + "github.com/adcondev/poster/pkg/commands/character" + "github.com/adcondev/poster/pkg/constants" "github.com/adcondev/poster/pkg/document/schema" "github.com/adcondev/poster/pkg/service" ) @@ -653,3 +655,97 @@ func BenchmarkCommandUnmarshal_Table(b *testing.B) { _ = json.Unmarshal(data, &cmd) } } + +// ============================================================================ +// CodeTable Resolution & Preset Profile Tests +// ============================================================================ + +func TestSetCodeTable_AllSupportedTablesAndFallback(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + testCases := []struct { + name string + input string + expected character.CodeTable + }{ + {"PC437", "PC437", character.PC437}, + {"CP437 alias", "CP437", character.PC437}, + {"PC850", "PC850", character.PC850}, + {"PC852", "PC852", character.PC852}, + {"PC855", "PC855", character.PC855}, + {"PC858", "PC858", character.PC858}, + {"PC860", "PC860", character.PC860}, + {"PC862", "PC862", character.PC862}, + {"PC863", "PC863", character.PC863}, + {"PC865", "PC865", character.PC865}, + {"PC866", "PC866", character.PC866}, + {"WPC1250", "WPC1250", character.WPC1250}, + {"WPC1251", "WPC1251", character.WPC1251}, + {"WPC1252", "WPC1252", character.WPC1252}, + {"WPC1253", "WPC1253", character.WPC1253}, + {"WPC1254", "WPC1254", character.WPC1254}, + {"WPC1255", "WPC1255", character.WPC1255}, + {"WPC1256", "WPC1256", character.WPC1256}, + {"WPC1257", "WPC1257", character.WPC1257}, + {"WPC1258", "WPC1258", character.WPC1258}, + {"ISO88592", "ISO88592", character.ISO88592}, + {"ISO88597", "ISO88597", character.ISO88597}, + {"ISO885915", "ISO885915", character.ISO885915}, + {"Katakana", "Katakana", character.Katakana}, + {"Hiragana", "Hiragana", character.Hiragana}, + {"ShiftJIS", "ShiftJIS", character.Katakana}, + {"Unknown fallback", "UNKNOWN_TABLE", character.WPC1252}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + err := exec.setCodeTable(tc.input) + if err != nil { + t.Fatalf("setCodeTable(%s) failed: %v", tc.input, err) + } + lastCall := mock.LastCall() + if lastCall == nil || lastCall.Method != "SetCodeTable" { + t.Fatalf("expected SetCodeTable call on mock") + } + got := lastCall.Args[0].(character.CodeTable) + if got != tc.expected { + t.Errorf("setCodeTable(%s): got %v, expected %v", tc.input, got, tc.expected) + } + }) + } +} + +func TestExecutor_Execute_58mmPresetPreservesPaperWidth(t *testing.T) { + mock := service.NewMockPrinter() + exec := NewExecutor(mock) + + // Document has Model = "58mm PT-210" and PaperWidth = 0 (omitted / default) + doc := &schema.Document{ + Version: "1.0", + Profile: schema.ProfileConfig{ + Model: "58mm PT-210", + PaperWidth: 0, + DPI: 203, + }, + Commands: []schema.Command{ + { + Type: "feed", + Data: json.RawMessage(`{"lines": 1}`), + }, + }, + } + + if err := exec.Execute(doc); err != nil { + t.Fatalf("exec.Execute failed: %v", err) + } + + prof := mock.GetProfile() + if prof.PaperWidth != 58 { + t.Errorf("expected PaperWidth == 58, got %v", prof.PaperWidth) + } + if prof.DotsPerLine != constants.PaperPxWidth58mm { + t.Errorf("expected DotsPerLine == %d, got %d", constants.PaperPxWidth58mm, prof.DotsPerLine) + } +} + diff --git a/pkg/profile/escpos_encoding.go b/pkg/profile/escpos_encoding.go index 0dff915..76bf414 100644 --- a/pkg/profile/escpos_encoding.go +++ b/pkg/profile/escpos_encoding.go @@ -2,6 +2,7 @@ package profile import ( "fmt" + "strings" "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" @@ -57,6 +58,7 @@ var codeTableMap = map[character.CodeTable]encoding.Encoding{ // EncodeString encodes a string using the specified code table func (e *Escpos) EncodeString(text string) (string, error) { + text = NormalizeTypography(text) enc := e.getEncoding(e.CodeTable) result, err := enc.String(text) if err != nil { @@ -65,6 +67,68 @@ func (e *Escpos) EncodeString(text string) (string, error) { return result, nil } +// ParseCodeTable normalizes a code table name or alias and returns the corresponding character.CodeTable. +// It removes hyphens, underscores, and spaces and converts to uppercase before matching. +func ParseCodeTable(name string) (character.CodeTable, bool) { + clean := strings.ToUpper(strings.TrimSpace(name)) + clean = strings.ReplaceAll(clean, "-", "") + clean = strings.ReplaceAll(clean, "_", "") + clean = strings.ReplaceAll(clean, " ", "") + + switch clean { + case "PC437", "CP437", "437": + return character.PC437, true + case "PC850", "CP850", "850": + return character.PC850, true + case "PC852", "CP852", "852": + return character.PC852, true + case "PC855", "CP855", "855": + return character.PC855, true + case "PC858", "CP858", "858": + return character.PC858, true + case "PC860", "CP860", "860": + return character.PC860, true + case "PC862", "CP862", "862": + return character.PC862, true + case "PC863", "CP863", "863": + return character.PC863, true + case "PC865", "CP865", "865": + return character.PC865, true + case "PC866", "CP866", "866": + return character.PC866, true + case "WPC1250", "CP1250", "WINDOWS1250", "1250": + return character.WPC1250, true + case "WPC1251", "CP1251", "WINDOWS1251", "1251": + return character.WPC1251, true + case "WPC1252", "CP1252", "WINDOWS1252", "1252": + return character.WPC1252, true + case "WPC1253", "CP1253", "WINDOWS1253", "1253": + return character.WPC1253, true + case "WPC1254", "CP1254", "WINDOWS1254", "1254": + return character.WPC1254, true + case "WPC1255", "CP1255", "WINDOWS1255", "1255": + return character.WPC1255, true + case "WPC1256", "CP1256", "WINDOWS1256", "1256": + return character.WPC1256, true + case "WPC1257", "CP1257", "WINDOWS1257", "1257": + return character.WPC1257, true + case "WPC1258", "CP1258", "WINDOWS1258", "1258": + return character.WPC1258, true + case "ISO88592", "88592": + return character.ISO88592, true + case "ISO88597", "88597": + return character.ISO88597, true + case "ISO885915", "885915": + return character.ISO885915, true + case "KATAKANA", "SHIFTJIS", "SJIS": + return character.Katakana, true + case "HIRAGANA": + return character.Hiragana, true + default: + return 0, false + } +} + // getEncoding returns the encoding.Encoder for the specified code table func (e *Escpos) getEncoding(codeTable character.CodeTable) *encoding.Encoder { enc, ok := codeTableMap[codeTable] diff --git a/pkg/profile/escpos_encoding_test.go b/pkg/profile/escpos_encoding_test.go index 888a550..ba468b9 100644 --- a/pkg/profile/escpos_encoding_test.go +++ b/pkg/profile/escpos_encoding_test.go @@ -52,6 +52,13 @@ func TestEncodeString(t *testing.T) { expectedError: false, expectedBytes: []byte("test"), }, + { + name: "Typography normalization in EncodeString", + codeTable: character.PC437, + input: "“Hello”", + expectedError: false, + expectedBytes: []byte("\"Hello\""), + }, } p := profile.CreateProfile58mm() diff --git a/pkg/profile/escpos_profile.go b/pkg/profile/escpos_profile.go index afb02c7..5461ec1 100644 --- a/pkg/profile/escpos_profile.go +++ b/pkg/profile/escpos_profile.go @@ -31,6 +31,11 @@ type Escpos struct { // Code table and encoding configuration CodeTable character.CodeTable + // Encoding behavior options + StrictEncoding bool // Return error on unencodable runes instead of '?' replacement + AutoSwitchCodePage bool // Automatically switch code tables inline (ESC t n) for mixed UTF-8 + FallbackCodePages []character.CodeTable // Candidate code tables for AutoSwitchCodePage + // Configuración avanzada (opcional) ImageThreshold int // Umbral para conversión B/N (0-255) Dithering graphics.DitherMode // Tipo de dithering por defecto @@ -40,7 +45,6 @@ type Escpos struct { } // CreatePt210 crea un perfil para impresora térmica de 58mm PT-58N -// TODO: Hardcoded Models: Factory functions for specific models might become hard to maintain. Consider configuration-based approach. func CreatePt210() *Escpos { p := CreateProfile58mm() p.Model = "58mm PT-210" @@ -67,8 +71,8 @@ func CreateProfile58mm() *Escpos { PaperWidth: 58, DPI: 203, - DotsPerLine: 384, // Típico para 58mm a 203 DPI - PrintWidth: 48, // Ancho de impresión efectivo + DotsPerLine: shared.Dpl58mm203dpi, // Típico para 58mm a 203 DPI + PrintWidth: 48, // Ancho de impresión efectivo SupportsGraphics: true, SupportsBarcode: true, @@ -77,6 +81,8 @@ func CreateProfile58mm() *Escpos { SupportsDrawer: false, CodeTable: character.PC850, + + ImageThreshold: 128, } } @@ -95,6 +101,7 @@ func CreateProfile80mm() *Escpos { PaperWidth: 80, DPI: 203, DotsPerLine: shared.Dpl80mm203dpi, // Típico para 80mm (72mm) a 203 DPI + PrintWidth: 72, SupportsGraphics: true, SupportsBarcode: true, diff --git a/pkg/profile/magic_encode.go b/pkg/profile/magic_encode.go new file mode 100644 index 0000000..0a6078d --- /dev/null +++ b/pkg/profile/magic_encode.go @@ -0,0 +1,118 @@ +package profile + +import ( + "strings" + + "github.com/adcondev/poster/pkg/commands/character" +) + +// NormalizeTypography converts typographical/smart Unicode characters (smart quotes, +// dashes, ellipsis, non-breaking spaces) to their standard ASCII printer-friendly equivalents. +func NormalizeTypography(text string) string { + if text == "" { + return "" + } + + var sb strings.Builder + sb.Grow(len(text)) + + for _, r := range text { + switch r { + case '\u2018', '\u2019', '\u201A', '\u201B': // ‘, ’, ‚, ‛ + sb.WriteRune('\'') + case '\u201C', '\u201D', '\u201E', '\u201F': // “, ”, „, ‟ + sb.WriteRune('"') + case '\u2013', '\u2014', '\u2015', '\u2212': // –, —, ―, − + sb.WriteRune('-') + case '\u2026': // … + sb.WriteString("...") + case '\u00A0', '\u202F': // NBSP, narrow NBSP + sb.WriteRune(' ') + default: + sb.WriteRune(r) + } + } + + return sb.String() +} + +// EncodeBytesSafe encodes text to printer-compatible bytes. +// +// If StrictEncoding is true, it encodes text strictly using the active code table +// and returns an error if any character cannot be represented. +// +// Otherwise, it performs safe rune-by-rune encoding: +// - If a rune cannot be encoded in the current code page and AutoSwitchCodePage +// is enabled, it attempts to switch to an appropriate fallback code page +// (emitting the ESC t n command: 0x1B, 0x74, byte(cand)). +// - If no candidate code page supports the rune, it substitutes '?' (0x3F). +func (p *Escpos) EncodeBytesSafe(text string) ([]byte, error) { + text = NormalizeTypography(text) + + if p.StrictEncoding { + s, err := p.EncodeString(text) + if err != nil { + return nil, err + } + return []byte(s), nil + } + + activeTable := p.CodeTable + if !p.IsSupported(activeTable) { + activeTable = character.WPC1252 + } + + var out []byte + + candidates := p.FallbackCodePages + if len(candidates) == 0 { + candidates = []character.CodeTable{ + character.PC858, + character.WPC1252, + character.PC437, + character.PC850, + character.PC866, + character.WPC1251, + character.ISO88597, + } + } + + for _, r := range text { + rStr := string(r) + enc, ok := codeTableMap[activeTable] + if ok { + if encoded, err := enc.NewEncoder().String(rStr); err == nil { + out = append(out, encoded...) + continue + } + } + + if p.AutoSwitchCodePage { + switched := false + for _, cand := range candidates { + if cand == activeTable { + continue + } + candEnc, cOk := codeTableMap[cand] + if !cOk { + continue + } + if candEncoded, cErr := candEnc.NewEncoder().String(rStr); cErr == nil { + out = append(out, 0x1B, 0x74, byte(cand)) + activeTable = cand + p.CodeTable = cand + out = append(out, candEncoded...) + switched = true + break + } + } + if switched { + continue + } + } + + out = append(out, '?') + } + + return out, nil +} diff --git a/pkg/profile/magic_encode_test.go b/pkg/profile/magic_encode_test.go new file mode 100644 index 0000000..a4482ed --- /dev/null +++ b/pkg/profile/magic_encode_test.go @@ -0,0 +1,300 @@ +package profile_test + +import ( + "bytes" + "testing" + + "github.com/adcondev/poster/pkg/commands/character" + "github.com/adcondev/poster/pkg/profile" +) + +func TestNormalizeTypography(t *testing.T) { + tests := []struct { + name string + input string + expected string + }{ + { + name: "empty", + input: "", + expected: "", + }, + { + name: "plain ascii unchanged", + input: "Hello, world! 123", + expected: "Hello, world! 123", + }, + { + name: "smart single quotes", + input: "\u2018single\u2019 and \u201Aquote\u201B", + expected: "'single' and 'quote'", + }, + { + name: "smart double quotes", + input: "\u201Cdouble\u201D and \u201Equote\u201F", + expected: "\"double\" and \"quote\"", + }, + { + name: "dashes and minus", + input: "en\u2013dash, em\u2014dash, bar\u2015bar, minus\u2212sign", + expected: "en-dash, em-dash, bar-bar, minus-sign", + }, + { + name: "ellipsis", + input: "Wait for it\u2026", + expected: "Wait for it...", + }, + { + name: "non-breaking spaces", + input: "NBSP\u00A0space and narrow\u202FNBSP", + expected: "NBSP space and narrow NBSP", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := profile.NormalizeTypography(tt.input) + if got != tt.expected { + t.Errorf("NormalizeTypography(%q) = %q, want %q", tt.input, got, tt.expected) + } + }) + } +} + +func TestParseCodeTable(t *testing.T) { + tests := []struct { + input string + expected character.CodeTable + found bool + }{ + // PC437 + {"PC437", character.PC437, true}, + {"CP437", character.PC437, true}, + {"437", character.PC437, true}, + {"pc-437", character.PC437, true}, + {"cp_437", character.PC437, true}, + + // PC850 + {"PC850", character.PC850, true}, + {"CP850", character.PC850, true}, + {"850", character.PC850, true}, + + // PC852 + {"PC852", character.PC852, true}, + {"CP852", character.PC852, true}, + {"852", character.PC852, true}, + + // PC855 + {"PC855", character.PC855, true}, + {"CP855", character.PC855, true}, + {"855", character.PC855, true}, + + // PC858 + {"PC858", character.PC858, true}, + {"CP858", character.PC858, true}, + {"858", character.PC858, true}, + + // PC860 + {"PC860", character.PC860, true}, + {"CP860", character.PC860, true}, + {"860", character.PC860, true}, + + // PC862 + {"PC862", character.PC862, true}, + {"CP862", character.PC862, true}, + {"862", character.PC862, true}, + + // PC863 + {"PC863", character.PC863, true}, + {"CP863", character.PC863, true}, + {"863", character.PC863, true}, + + // PC865 + {"PC865", character.PC865, true}, + {"CP865", character.PC865, true}, + {"865", character.PC865, true}, + + // PC866 + {"PC866", character.PC866, true}, + {"CP866", character.PC866, true}, + {"866", character.PC866, true}, + + // Windows code pages + {"WPC1250", character.WPC1250, true}, + {"CP1250", character.WPC1250, true}, + {"WINDOWS1250", character.WPC1250, true}, + {"windows-1250", character.WPC1250, true}, + + {"WPC1251", character.WPC1251, true}, + {"CP1251", character.WPC1251, true}, + {"WINDOWS1251", character.WPC1251, true}, + + {"WPC1252", character.WPC1252, true}, + {"CP1252", character.WPC1252, true}, + {"WINDOWS1252", character.WPC1252, true}, + + {"WPC1253", character.WPC1253, true}, + {"CP1253", character.WPC1253, true}, + {"WINDOWS1253", character.WPC1253, true}, + + {"WPC1254", character.WPC1254, true}, + {"CP1254", character.WPC1254, true}, + {"WINDOWS1254", character.WPC1254, true}, + + {"WPC1255", character.WPC1255, true}, + {"CP1255", character.WPC1255, true}, + {"WINDOWS1255", character.WPC1255, true}, + + {"WPC1256", character.WPC1256, true}, + {"CP1256", character.WPC1256, true}, + {"WINDOWS1256", character.WPC1256, true}, + + {"WPC1257", character.WPC1257, true}, + {"CP1257", character.WPC1257, true}, + {"WINDOWS1257", character.WPC1257, true}, + + {"WPC1258", character.WPC1258, true}, + {"CP1258", character.WPC1258, true}, + {"WINDOWS1258", character.WPC1258, true}, + + // ISO-8859 + {"ISO88592", character.ISO88592, true}, + {"iso-8859-2", character.ISO88592, true}, + {"ISO88597", character.ISO88597, true}, + {"iso-8859-7", character.ISO88597, true}, + {"ISO885915", character.ISO885915, true}, + {"iso-8859-15", character.ISO885915, true}, + + // Asian + {"KATAKANA", character.Katakana, true}, + {"katakana", character.Katakana, true}, + {"SHIFTJIS", character.Katakana, true}, + {"shift_jis", character.Katakana, true}, + {"HIRAGANA", character.Hiragana, true}, + {"hiragana", character.Hiragana, true}, + + // Invalid + {"UNKNOWN_CODEPAGE", 0, false}, + {"", 0, false}, + {"12345", 0, false}, + } + + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + got, ok := profile.ParseCodeTable(tt.input) + if ok != tt.found { + t.Fatalf("ParseCodeTable(%q) found = %v, want %v", tt.input, ok, tt.found) + } + if ok && got != tt.expected { + t.Errorf("ParseCodeTable(%q) = %v, want %v", tt.input, got, tt.expected) + } + }) + } +} + +func TestEncodeBytesSafe_NonStrict(t *testing.T) { + p := profile.CreateProfile80mm() + p.CodeTable = character.PC437 + p.StrictEncoding = false + p.AutoSwitchCodePage = false + + // '🚀' cannot be represented in PC437, should be replaced with '?' + out, err := p.EncodeBytesSafe("Total: $10 🚀") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + expected := "Total: $10 ?" + if string(out) != expected { + t.Errorf("EncodeBytesSafe() = %q, want %q", string(out), expected) + } +} + +func TestEncodeBytesSafe_Strict(t *testing.T) { + p := profile.CreateProfile80mm() + p.CodeTable = character.PC437 + p.StrictEncoding = true + + // PC437 does not support Euro '€' + _, err := p.EncodeBytesSafe("Price: 10 €") + if err == nil { + t.Fatal("expected error in strict mode for unsupported rune '€', got nil") + } + + // But valid PC437 characters should succeed + out, err := p.EncodeBytesSafe("Price: $10") + if err != nil { + t.Fatalf("unexpected error for valid ASCII: %v", err) + } + if string(out) != "Price: $10" { + t.Errorf("got %q, want 'Price: $10'", string(out)) + } +} + +func TestEncodeBytesSafe_AutoSwitchCodePage(t *testing.T) { + p := profile.CreateProfile80mm() + p.CodeTable = character.PC437 + p.StrictEncoding = false + p.AutoSwitchCodePage = true + + // String containing: + // - Box drawing "┌─┐" (present in PC437) + // - Euro sign "€" (requires PC858, code table 19) + // - Cyrillic "Д" (requires PC866, code table 17) + input := "┌─┐€Д" + out, err := p.EncodeBytesSafe(input) + if err != nil { + t.Fatalf("EncodeBytesSafe failed: %v", err) + } + + // Verify ESC t sequences were emitted + // Switch to PC858: 0x1B, 0x74, 19 + escPC858 := []byte{0x1B, 0x74, byte(character.PC858)} + if !bytes.Contains(out, escPC858) { + t.Errorf("expected output to contain ESC t %d for PC858, got %x", character.PC858, out) + } + + // Switch to PC866: 0x1B, 0x74, 17 + escPC866 := []byte{0x1B, 0x74, byte(character.PC866)} + if !bytes.Contains(out, escPC866) { + t.Errorf("expected output to contain ESC t %d for PC866, got %x", character.PC866, out) + } + + // Verify final CodeTable on profile is PC866 + if p.CodeTable != character.PC866 { + t.Errorf("expected profile.CodeTable to be updated to PC866 (%d), got %d", character.PC866, p.CodeTable) + } +} + +func TestEncodeBytesSafe_AutoSwitchWithFallbackList(t *testing.T) { + p := profile.CreateProfile80mm() + p.CodeTable = character.PC437 + p.StrictEncoding = false + p.AutoSwitchCodePage = true + // Restrict fallbacks to WPC1252 only + p.FallbackCodePages = []character.CodeTable{character.WPC1252} + + // '€' is in WPC1252 (0x80) + out, err := p.EncodeBytesSafe("€") + if err != nil { + t.Fatalf("EncodeBytesSafe failed: %v", err) + } + + escWPC1252 := []byte{0x1B, 0x74, byte(character.WPC1252)} + if !bytes.Contains(out, escWPC1252) { + t.Errorf("expected ESC t %d for WPC1252, got %x", character.WPC1252, out) + } + if p.CodeTable != character.WPC1252 { + t.Errorf("expected CodeTable = WPC1252, got %v", p.CodeTable) + } + + // Now try Cyrillic 'Д', which is not in WPC1252 + out2, err := p.EncodeBytesSafe("Д") + if err != nil { + t.Fatalf("EncodeBytesSafe failed: %v", err) + } + // Since WPC1252 doesn't have 'Д' and FallbackCodePages only has WPC1252, it should fallback to '?' + if string(out2) != "?" { + t.Errorf("expected '?', got %q", string(out2)) + } +} diff --git a/pkg/profile/profile_factory.go b/pkg/profile/profile_factory.go new file mode 100644 index 0000000..1e2dc3f --- /dev/null +++ b/pkg/profile/profile_factory.go @@ -0,0 +1,109 @@ +package profile + +import ( + "strings" + + "github.com/adcondev/poster/pkg/commands/character" +) + +// CreateEpsonTMT20III creates a profile for the Epson TM-T20III thermal receipt printer. +func CreateEpsonTMT20III() *Escpos { + p := CreateProfile80mm() + p.Model = "Epson TM-T20III" + p.CodeTable = character.PC858 + p.AutoSwitchCodePage = true + return p +} + +// CreateEpsonTMT88VI creates a profile for the high-speed Epson TM-T88VI thermal receipt printer. +func CreateEpsonTMT88VI() *Escpos { + p := CreateProfile80mm() + p.Model = "Epson TM-T88VI" + p.CodeTable = character.PC858 + p.AutoSwitchCodePage = true + return p +} + +// CreateStarTSP100 creates a profile for the Star Micronics TSP100 thermal receipt printer. +func CreateStarTSP100() *Escpos { + p := CreateProfile80mm() + p.Model = "Star TSP100" + p.CodeTable = character.WPC1252 + p.AutoSwitchCodePage = true + return p +} + +// CreateBixolonSRP350III creates a profile for the Bixolon SRP-350III thermal receipt printer. +func CreateBixolonSRP350III() *Escpos { + p := CreateProfile80mm() + p.Model = "Bixolon SRP-350III" + p.CodeTable = character.PC858 + p.AutoSwitchCodePage = true + return p +} + +// CreateXprinterXP58 creates a profile for the Xprinter XP-58 58mm thermal receipt printer. +func CreateXprinterXP58() *Escpos { + p := CreateProfile58mm() + p.Model = "Xprinter XP-58" + p.CodeTable = character.PC850 + p.HasQR = false + p.SupportsCutter = false + p.SupportsDrawer = true + return p +} + +// CreateXprinterXP80 creates a profile for the Xprinter XP-80 80mm thermal receipt printer. +func CreateXprinterXP80() *Escpos { + p := CreateProfile80mm() + p.Model = "Xprinter XP-80" + p.CodeTable = character.PC858 + p.HasQR = true + p.SupportsCutter = true + p.SupportsDrawer = true + return p +} + +// FromModel resolves a printer model string into an Escpos profile. +// It is an alias for ProfileFromModel. +func FromModel(model string) (*Escpos, bool) { + return ProfileFromModel(model) +} + +// ProfileFromModel resolves a printer model string into an Escpos profile. +// Matching is case-insensitive and supports model name substrings. +// +//nolint:revive // ProfileFromModel is the canonical name specified for catalog resolution +func ProfileFromModel(model string) (*Escpos, bool) { + m := strings.ToLower(strings.TrimSpace(model)) + if m == "" { + return nil, false + } + + switch { + case strings.Contains(m, "pt-210") || strings.Contains(m, "pt210"): + return CreatePt210(), true + case strings.Contains(m, "gp-58n") || strings.Contains(m, "gp58n"): + return CreateGP58N(), true + case strings.Contains(m, "ec-pm-80250") || strings.Contains(m, "ecpm80250"): + return CreateECPM80250(), true + case strings.Contains(m, "tm-t20") || strings.Contains(m, "tmt20"): + return CreateEpsonTMT20III(), true + case strings.Contains(m, "tm-t88") || strings.Contains(m, "tmt88"): + return CreateEpsonTMT88VI(), true + case strings.Contains(m, "tsp100") || strings.Contains(m, "tsp-100"): + return CreateStarTSP100(), true + case strings.Contains(m, "srp-350") || strings.Contains(m, "srp350"): + return CreateBixolonSRP350III(), true + case strings.Contains(m, "xp-58") || strings.Contains(m, "xp58"): + return CreateXprinterXP58(), true + case strings.Contains(m, "xp-80") || strings.Contains(m, "xp80"): + return CreateXprinterXP80(), true + case strings.Contains(m, "58mm") || strings.Contains(m, "58"): + return CreateProfile58mm(), true + case strings.Contains(m, "80mm") || strings.Contains(m, "80"): + return CreateProfile80mm(), true + default: + return nil, false + } +} diff --git a/pkg/profile/profile_test.go b/pkg/profile/profile_test.go new file mode 100644 index 0000000..3a57a1e --- /dev/null +++ b/pkg/profile/profile_test.go @@ -0,0 +1,296 @@ +package profile_test + +import ( + "testing" + + "github.com/adcondev/poster/pkg/commands/character" + "github.com/adcondev/poster/pkg/profile" +) + +func TestCreateEpsonTMT20III(t *testing.T) { + p := profile.CreateEpsonTMT20III() + + if p.Model != "Epson TM-T20III" { + t.Errorf("expected model 'Epson TM-T20III', got '%s'", p.Model) + } + if p.PaperWidth != 80 { + t.Errorf("expected PaperWidth 80, got %f", p.PaperWidth) + } + if p.DPI != 203 { + t.Errorf("expected DPI 203, got %d", p.DPI) + } + if p.DotsPerLine != 576 { + t.Errorf("expected DotsPerLine 576, got %d", p.DotsPerLine) + } + if p.PrintWidth != 72 { + t.Errorf("expected PrintWidth 72, got %d", p.PrintWidth) + } + if p.CodeTable != character.PC858 { + t.Errorf("expected CodeTable PC858, got %v", p.CodeTable) + } + if !p.HasQR { + t.Error("expected HasQR to be true") + } + if !p.SupportsCutter { + t.Error("expected SupportsCutter to be true") + } + if !p.SupportsDrawer { + t.Error("expected SupportsDrawer to be true") + } + if !p.AutoSwitchCodePage { + t.Error("expected AutoSwitchCodePage to be true") + } +} + +func TestCreateEpsonTMT88VI(t *testing.T) { + p := profile.CreateEpsonTMT88VI() + + if p.Model != "Epson TM-T88VI" { + t.Errorf("expected model 'Epson TM-T88VI', got '%s'", p.Model) + } + if p.PaperWidth != 80 { + t.Errorf("expected PaperWidth 80, got %f", p.PaperWidth) + } + if p.DPI != 203 { + t.Errorf("expected DPI 203, got %d", p.DPI) + } + if p.DotsPerLine != 576 { + t.Errorf("expected DotsPerLine 576, got %d", p.DotsPerLine) + } + if p.PrintWidth != 72 { + t.Errorf("expected PrintWidth 72, got %d", p.PrintWidth) + } + if p.CodeTable != character.PC858 { + t.Errorf("expected CodeTable PC858, got %v", p.CodeTable) + } + if !p.HasQR { + t.Error("expected HasQR to be true") + } + if !p.SupportsCutter { + t.Error("expected SupportsCutter to be true") + } + if !p.SupportsDrawer { + t.Error("expected SupportsDrawer to be true") + } + if !p.AutoSwitchCodePage { + t.Error("expected AutoSwitchCodePage to be true") + } +} + +func TestCreateStarTSP100(t *testing.T) { + p := profile.CreateStarTSP100() + + if p.Model != "Star TSP100" { + t.Errorf("expected model 'Star TSP100', got '%s'", p.Model) + } + if p.PaperWidth != 80 { + t.Errorf("expected PaperWidth 80, got %f", p.PaperWidth) + } + if p.DPI != 203 { + t.Errorf("expected DPI 203, got %d", p.DPI) + } + if p.DotsPerLine != 576 { + t.Errorf("expected DotsPerLine 576, got %d", p.DotsPerLine) + } + if p.PrintWidth != 72 { + t.Errorf("expected PrintWidth 72, got %d", p.PrintWidth) + } + if p.CodeTable != character.WPC1252 { + t.Errorf("expected CodeTable WPC1252, got %v", p.CodeTable) + } + if !p.HasQR { + t.Error("expected HasQR to be true") + } + if !p.SupportsCutter { + t.Error("expected SupportsCutter to be true") + } + if !p.SupportsDrawer { + t.Error("expected SupportsDrawer to be true") + } + if !p.AutoSwitchCodePage { + t.Error("expected AutoSwitchCodePage to be true") + } +} + +func TestCreateBixolonSRP350III(t *testing.T) { + p := profile.CreateBixolonSRP350III() + + if p.Model != "Bixolon SRP-350III" { + t.Errorf("expected model 'Bixolon SRP-350III', got '%s'", p.Model) + } + if p.PaperWidth != 80 { + t.Errorf("expected PaperWidth 80, got %f", p.PaperWidth) + } + if p.DPI != 203 { + t.Errorf("expected DPI 203, got %d", p.DPI) + } + if p.DotsPerLine != 576 { + t.Errorf("expected DotsPerLine 576, got %d", p.DotsPerLine) + } + if p.PrintWidth != 72 { + t.Errorf("expected PrintWidth 72, got %d", p.PrintWidth) + } + if p.CodeTable != character.PC858 { + t.Errorf("expected CodeTable PC858, got %v", p.CodeTable) + } + if !p.HasQR { + t.Error("expected HasQR to be true") + } + if !p.SupportsCutter { + t.Error("expected SupportsCutter to be true") + } + if !p.SupportsDrawer { + t.Error("expected SupportsDrawer to be true") + } + if !p.AutoSwitchCodePage { + t.Error("expected AutoSwitchCodePage to be true") + } +} + +func TestCreateXprinterXP58(t *testing.T) { + p := profile.CreateXprinterXP58() + + if p.Model != "Xprinter XP-58" { + t.Errorf("expected model 'Xprinter XP-58', got '%s'", p.Model) + } + if p.PaperWidth != 58 { + t.Errorf("expected PaperWidth 58, got %f", p.PaperWidth) + } + if p.DPI != 203 { + t.Errorf("expected DPI 203, got %d", p.DPI) + } + if p.DotsPerLine != 384 { + t.Errorf("expected DotsPerLine 384, got %d", p.DotsPerLine) + } + if p.PrintWidth != 48 { + t.Errorf("expected PrintWidth 48, got %d", p.PrintWidth) + } + if p.CodeTable != character.PC850 { + t.Errorf("expected CodeTable PC850, got %v", p.CodeTable) + } + if p.HasQR { + t.Error("expected HasQR to be false") + } + if p.SupportsCutter { + t.Error("expected SupportsCutter to be false") + } + if !p.SupportsDrawer { + t.Error("expected SupportsDrawer to be true") + } +} + +func TestCreateXprinterXP80(t *testing.T) { + p := profile.CreateXprinterXP80() + + if p.Model != "Xprinter XP-80" { + t.Errorf("expected model 'Xprinter XP-80', got '%s'", p.Model) + } + if p.PaperWidth != 80 { + t.Errorf("expected PaperWidth 80, got %f", p.PaperWidth) + } + if p.DPI != 203 { + t.Errorf("expected DPI 203, got %d", p.DPI) + } + if p.DotsPerLine != 576 { + t.Errorf("expected DotsPerLine 576, got %d", p.DotsPerLine) + } + if p.PrintWidth != 72 { + t.Errorf("expected PrintWidth 72, got %d", p.PrintWidth) + } + if p.CodeTable != character.PC858 { + t.Errorf("expected CodeTable PC858, got %v", p.CodeTable) + } + if !p.HasQR { + t.Error("expected HasQR to be true") + } + if !p.SupportsCutter { + t.Error("expected SupportsCutter to be true") + } + if !p.SupportsDrawer { + t.Error("expected SupportsDrawer to be true") + } +} + +func TestProfileFromModel(t *testing.T) { + tests := []struct { + input string + wantModel string + wantFound bool + }{ + {"pt-210", "58mm PT-210", true}, + {"PT210", "58mm PT-210", true}, + {"58mm pt-210 portable", "58mm PT-210", true}, + {"gp-58n", "58mm GP-58N", true}, + {"GP58N", "58mm GP-58N", true}, + {"ec-pm-80250", "80mm EC-PM-80250", true}, + {"ECPM80250", "80mm EC-PM-80250", true}, + {"tm-t20", "Epson TM-T20III", true}, + {"tmt20", "Epson TM-T20III", true}, + {"Epson TM-T20III", "Epson TM-T20III", true}, + {"tm-t88", "Epson TM-T88VI", true}, + {"tmt88", "Epson TM-T88VI", true}, + {"Epson TM-T88VI Receipt", "Epson TM-T88VI", true}, + {"tsp100", "Star TSP100", true}, + {"tsp-100", "Star TSP100", true}, + {"Star TSP100 Cutter", "Star TSP100", true}, + {"srp-350", "Bixolon SRP-350III", true}, + {"srp350", "Bixolon SRP-350III", true}, + {"xp-58", "Xprinter XP-58", true}, + {"xp58", "Xprinter XP-58", true}, + {"xp-80", "Xprinter XP-80", true}, + {"xp80", "Xprinter XP-80", true}, + {"58mm", "Generic 58mm", true}, + {"58", "Generic 58mm", true}, + {"80mm", "Generic 80mm", true}, + {"80", "Generic 80mm", true}, + {"Unknown Model", "", false}, + {"", "", false}, + {" ", "", false}, + } + + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + got, found := profile.ProfileFromModel(tt.input) + if found != tt.wantFound { + t.Fatalf("ProfileFromModel(%q) found = %v, want %v", tt.input, found, tt.wantFound) + } + if found && got.Model != tt.wantModel { + t.Errorf("ProfileFromModel(%q) model = %q, want %q", tt.input, got.Model, tt.wantModel) + } + if !found && got != nil { + t.Errorf("ProfileFromModel(%q) got non-nil profile when not found: %+v", tt.input, got) + } + }) + } +} + +func TestEscposProfileOptions(t *testing.T) { + p58 := profile.CreateProfile58mm() + if p58.PrintWidth != 48 { + t.Errorf("expected Generic 58mm PrintWidth 48, got %d", p58.PrintWidth) + } + if p58.ImageThreshold != 128 { + t.Errorf("expected Generic 58mm ImageThreshold 128, got %d", p58.ImageThreshold) + } + if p58.StrictEncoding { + t.Error("expected default StrictEncoding to be false") + } + if p58.AutoSwitchCodePage { + t.Error("expected default AutoSwitchCodePage to be false") + } + + p80 := profile.CreateProfile80mm() + if p80.PrintWidth != 72 { + t.Errorf("expected Generic 80mm PrintWidth 72, got %d", p80.PrintWidth) + } + if p80.ImageThreshold != 128 { + t.Errorf("expected Generic 80mm ImageThreshold 128, got %d", p80.ImageThreshold) + } +} + +func TestFromModel(t *testing.T) { + p, ok := profile.FromModel("tm-t20") + if !ok || p == nil || p.Model != "Epson TM-T20III" { + t.Errorf("FromModel(\"tm-t20\") failed: got (%+v, %v)", p, ok) + } +} diff --git a/pkg/service/printer_service.go b/pkg/service/printer_service.go index b4b31f2..a4f5db4 100644 --- a/pkg/service/printer_service.go +++ b/pkg/service/printer_service.go @@ -132,11 +132,11 @@ func (p *Printer) Write(data []byte) error { // Print sends text without line feed func (p *Printer) Print(text string) error { - encText, err := p.Profile.EncodeString(text) + encoded, err := p.Profile.EncodeBytesSafe(text) if err != nil { return err } - cmd, err := p.Protocol.Print.Text(encText) + cmd, err := p.Protocol.Print.Text(string(encoded)) if err != nil { return err }