From d03c2f38809cd03b6ff01345760ce872b5b25a8c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 12:25:04 +0000 Subject: [PATCH 01/14] [ENH] Split the library into a printer-agnostic core and a Dymo driver Rework the library around a single entrypoint and pluggable printer drivers, configured OpenIddict-style: services.AddLetra().AddDymoLetraTag(dymo => dymo.SetReplyTimeout(...)); // or LabelPrinting.Create(letra => letra.AddDymoLetraTag()) Letra200bSharp (core, no rendering/transport dependencies): - Label model: TextLabel, BarcodeLabel, TwoDCodeLabel, ImageLabel, DinRailLabel, ComposedLabel - required content in the constructor, every option an init property, so new options are no longer breaking changes. Enums and option types move out of LetraHelper into the namespace. - ILabelPrinterDriver: discovery, PrinterCapabilities, ILabelRenderer and printing of a rendered LabelBitmap. A new printer is one implementation registered with LetraBuilder.AddDriver(). - ILabelPrintingService: discovery across drivers, previews and printing, routed by PrinterInfo.Driver. - Optional renderer features ITwoDCodePlanner and IDinRailLayout. Letra200bSharp.Dymo: the LetraTag 200B driver - the existing renderer, wire format and BLE transport, now internal, plus DymoLetraTagOptions (reply timeout, packet delay, MTU, default font, name prefix) and cancellation. The rendering and wire output are unchanged: 136 jobs, previews and content images (text, barcodes, 2D codes, images, DIN rail, compositions) hash identically before and after. The app and CLI move to the new API, and the new Letra200bSharp.Tests project (run in CI) covers the protocol, driver registration with a fake printer, and font-independent rendering. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRhXBxWUgnHqiT4dYByZgJ --- .github/workflows/ci.yml | 6 + Directory.Packages.props | 12 +- .../MainActivity.cs | 2 +- Letra200bSharp.Avalonia.Desktop/Cli.cs | 109 ++-- .../Letra200bSharp.Avalonia.csproj | 2 +- .../Services/CompositionService.cs | 69 +-- .../Services/PrintHistoryService.cs | 99 ++-- .../Services/SymbolLibraryService.cs | 3 +- .../ViewModels/BarcodeTabViewModel.cs | 51 +- .../ViewModels/ComposeTabViewModel.cs | 39 +- .../ViewModels/DinRailTabViewModel.cs | 116 ++--- .../ViewModels/DrawTabViewModel.cs | 37 +- .../ViewModels/ImageTabViewModel.cs | 32 +- .../ViewModels/MainViewModel.cs | 57 ++- .../ViewModels/QrTabViewModel.cs | 56 +- .../ViewModels/TextTabViewModel.cs | 104 ++-- .../Views/BarcodeTabView.axaml | 2 +- .../Views/ComposeTabView.axaml | 2 +- .../Views/DinRailTabView.axaml | 4 +- .../Views/DrawTabView.axaml | 2 +- .../Views/ImageTabView.axaml | 2 +- .../Views/MainView.axaml.cs | 2 +- Letra200bSharp.Avalonia/Views/QrTabView.axaml | 4 +- .../Views/TextTabView.axaml | 2 +- Letra200bSharp.Dymo/DymoLetraTagBuilder.cs | 81 +++ Letra200bSharp.Dymo/DymoLetraTagDriver.cs | 90 ++++ Letra200bSharp.Dymo/ImageInfo.cs | 14 + .../Letra200bSharp.Dymo.csproj | 52 ++ .../LetraTagBluetoothTransport.cs | 200 ++++++++ Letra200bSharp.Dymo/LetraTagLabelRenderer.cs | 135 +++++ Letra200bSharp.Dymo/LetraTagProtocol.cs | 140 +++++ .../RenderHelper.cs | 288 ++++++----- .../Resources/Strings.Designer.cs | 28 +- .../Resources/Strings.resx | 0 .../LabelPrintingServiceTests.cs | 158 ++++++ .../Letra200bSharp.Tests.csproj | 28 + .../LetraTagLabelRendererTests.cs | 95 ++++ Letra200bSharp.Tests/LetraTagProtocolTests.cs | 59 +++ Letra200bSharp.slnx | 3 + .../DependencyInjection/LetraBuilder.cs | 61 +++ .../LetraServiceCollectionExtensions.cs | 28 + Letra200bSharp/ILabelPrintingService.cs | 38 ++ Letra200bSharp/ILetraHelper.cs | 31 -- Letra200bSharp/IRenderHelper.cs | 66 --- Letra200bSharp/ImageInfo.cs | 9 - Letra200bSharp/LabelPrinting.cs | 23 + Letra200bSharp/LabelPrintingService.cs | 107 ++++ Letra200bSharp/Labels/Label.cs | 182 +++++++ Letra200bSharp/Labels/LabelEnums.cs | 125 +++++ Letra200bSharp/Labels/LabelOptions.cs | 70 +++ Letra200bSharp/Letra200bSharp.csproj | 39 +- Letra200bSharp/LetraHelper.cs | 481 ------------------ Letra200bSharp/LetraPrinter.cs | 206 -------- .../Printing/ILabelPrinterDriver.cs | 36 ++ Letra200bSharp/Printing/ILabelRenderer.cs | 80 +++ Letra200bSharp/Printing/PrinterTypes.cs | 102 ++++ README.md | 32 +- global.json | 5 + 58 files changed, 2539 insertions(+), 1367 deletions(-) create mode 100644 Letra200bSharp.Dymo/DymoLetraTagBuilder.cs create mode 100644 Letra200bSharp.Dymo/DymoLetraTagDriver.cs create mode 100644 Letra200bSharp.Dymo/ImageInfo.cs create mode 100644 Letra200bSharp.Dymo/Letra200bSharp.Dymo.csproj create mode 100644 Letra200bSharp.Dymo/LetraTagBluetoothTransport.cs create mode 100644 Letra200bSharp.Dymo/LetraTagLabelRenderer.cs create mode 100644 Letra200bSharp.Dymo/LetraTagProtocol.cs rename {Letra200bSharp => Letra200bSharp.Dymo}/RenderHelper.cs (88%) rename {Letra200bSharp => Letra200bSharp.Dymo}/Resources/Strings.Designer.cs (86%) rename {Letra200bSharp => Letra200bSharp.Dymo}/Resources/Strings.resx (100%) create mode 100644 Letra200bSharp.Tests/LabelPrintingServiceTests.cs create mode 100644 Letra200bSharp.Tests/Letra200bSharp.Tests.csproj create mode 100644 Letra200bSharp.Tests/LetraTagLabelRendererTests.cs create mode 100644 Letra200bSharp.Tests/LetraTagProtocolTests.cs create mode 100644 Letra200bSharp/DependencyInjection/LetraBuilder.cs create mode 100644 Letra200bSharp/DependencyInjection/LetraServiceCollectionExtensions.cs create mode 100644 Letra200bSharp/ILabelPrintingService.cs delete mode 100644 Letra200bSharp/ILetraHelper.cs delete mode 100644 Letra200bSharp/IRenderHelper.cs delete mode 100644 Letra200bSharp/ImageInfo.cs create mode 100644 Letra200bSharp/LabelPrinting.cs create mode 100644 Letra200bSharp/LabelPrintingService.cs create mode 100644 Letra200bSharp/Labels/Label.cs create mode 100644 Letra200bSharp/Labels/LabelEnums.cs create mode 100644 Letra200bSharp/Labels/LabelOptions.cs delete mode 100644 Letra200bSharp/LetraHelper.cs delete mode 100644 Letra200bSharp/LetraPrinter.cs create mode 100644 Letra200bSharp/Printing/ILabelPrinterDriver.cs create mode 100644 Letra200bSharp/Printing/ILabelRenderer.cs create mode 100644 Letra200bSharp/Printing/PrinterTypes.cs create mode 100644 global.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4a4b3b8..ed29cae 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -179,6 +179,12 @@ jobs: - name: Install android workload run: dotnet workload install android + # Library unit tests (protocol, driver registration, font-independent rendering) - once, + # on the runner that can execute them natively. + - name: Test + if: matrix.rid == 'linux-x64' + run: dotnet test --project Letra200bSharp.Tests -c Release -p:TargetFrameworks=net10.0 + - name: Publish desktop app run: | dotnet publish "$DESKTOP_PROJECT" \ diff --git a/Directory.Packages.props b/Directory.Packages.props index 8203e43..91f504f 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -4,14 +4,24 @@ - + + + + + + + + + + diff --git a/Letra200bSharp.Avalonia.Android/MainActivity.cs b/Letra200bSharp.Avalonia.Android/MainActivity.cs index 35b44e7..f55f1be 100644 --- a/Letra200bSharp.Avalonia.Android/MainActivity.cs +++ b/Letra200bSharp.Avalonia.Android/MainActivity.cs @@ -29,7 +29,7 @@ protected override void OnCreate(Bundle? savedInstanceState) /// /// Bluetooth LE scanning is a "dangerous" permission on Android and must be granted at - /// runtime, not just declared in the manifest - without this, LetraPrinter.ScanForDevicesAsync + /// runtime, not just declared in the manifest - without this, printer discovery (DiscoverAsync) /// fails with "Need android.permission.BLUETOOTH_SCAN permission ...". /// private void RequestBluetoothPermissions() diff --git a/Letra200bSharp.Avalonia.Desktop/Cli.cs b/Letra200bSharp.Avalonia.Desktop/Cli.cs index a5d69d9..bc3d506 100644 --- a/Letra200bSharp.Avalonia.Desktop/Cli.cs +++ b/Letra200bSharp.Avalonia.Desktop/Cli.cs @@ -2,6 +2,7 @@ using CommandLine.Text; using Letra200bSharp; using Letra200bSharp.Avalonia.Services; +using Microsoft.Extensions.DependencyInjection; namespace Letra200bSharp.Avalonia.Desktop; @@ -41,14 +42,14 @@ internal class TextOptions [Option("font", Default = "Arial", HelpText = "Font family name.")] public string Font { get; set; } = "Arial"; - [Option("size", Default = LetraHelper.LabelTextSize.M, HelpText = "XS, S, M, L, or XL.")] - public LetraHelper.LabelTextSize Size { get; set; } + [Option("size", Default = LabelTextSize.M, HelpText = "XS, S, M, L, or XL.")] + public LabelTextSize Size { get; set; } - [Option("style", Default = LetraHelper.TextStyle.Normal, HelpText = "Normal, Outline, Shadow, or Vertical.")] - public LetraHelper.TextStyle Style { get; set; } + [Option("style", Default = TextStyle.Normal, HelpText = "Normal, Outline, Shadow, or Vertical.")] + public TextStyle Style { get; set; } - [Option("box", Default = LetraHelper.TextBoxStyle.None, HelpText = "None, Underline, Square, Pointed, Rounded, Edged, Crocodile, Heart, Star, Flower, or Ribbon (ignored for size XL).")] - public LetraHelper.TextBoxStyle Box { get; set; } + [Option("box", Default = TextBoxStyle.None, HelpText = "None, Underline, Square, Pointed, Rounded, Edged, Crocodile, Heart, Star, Flower, or Ribbon (ignored for size XL).")] + public TextBoxStyle Box { get; set; } [Option("uppercase", HelpText = "Render the text in all uppercase.")] public bool UpperCase { get; set; } @@ -96,23 +97,23 @@ internal class BarcodeOptions [Option("data", Required = true, HelpText = "Barcode content.")] public required string Data { get; set; } - [Option("symbology", Default = LetraHelper.BarcodeSymbology.Auto, HelpText = "Auto (guesses from the data's shape/checksum), Code128, Code39, Codabar, Itf, Ean13, Ean8, UpcA, or UpcE.")] - public LetraHelper.BarcodeSymbology Symbology { get; set; } + [Option("symbology", Default = BarcodeSymbology.Auto, HelpText = "Auto (guesses from the data's shape/checksum), Code128, Code39, Codabar, Itf, Ean13, Ean8, UpcA, or UpcE.")] + public BarcodeSymbology Symbology { get; set; } [Option("no-cut", HelpText = "See PrepareBitmap - the rendered barcode already accounts for the printer's unprintable top/bottom row.")] public bool NoCut { get; set; } - [Option("caption-position", Default = LetraHelper.CaptionPosition.None, HelpText = "None, Below, or Above - prints the barcode's own data as a small caption alongside the bars.")] - public LetraHelper.CaptionPosition CaptionPosition { get; set; } + [Option("caption-position", Default = CaptionPosition.None, HelpText = "None, Below, or Above - prints the barcode's own data as a small caption alongside the bars.")] + public CaptionPosition CaptionPosition { get; set; } [Option("caption-font", Default = "Arial", HelpText = "Font family for the caption (bold, ignored if caption-position is None).")] public string CaptionFont { get; set; } = "Arial"; - [Option("caption-size", Default = LetraHelper.CaptionSize.M, HelpText = "S, M, or L - how much of the printable height the caption takes up.")] - public LetraHelper.CaptionSize CaptionSize { get; set; } + [Option("caption-size", Default = CaptionSize.M, HelpText = "S, M, or L - how much of the printable height the caption takes up.")] + public CaptionSize CaptionSize { get; set; } - [Option("caption-align", Default = LetraHelper.TextAlign.Center, HelpText = "Left, Center, or Right - alignment between the caption and the bars, whichever ends up narrower.")] - public LetraHelper.TextAlign CaptionAlign { get; set; } + [Option("caption-align", Default = TextAlign.Center, HelpText = "Left, Center, or Right - alignment between the caption and the bars, whichever ends up narrower.")] + public TextAlign CaptionAlign { get; set; } } [Verb("qr", HelpText = "Print a 2D matrix code (QR, Micro QR, rMQR, or Data Matrix).")] @@ -124,8 +125,8 @@ internal class QrOptions [Option("data", Required = true, HelpText = "Code content.")] public required string Data { get; set; } - [Option("symbology", Default = LetraHelper.TwoDSymbology.Auto, HelpText = "Auto (least tape while staying scannable), QrCode, MicroQrCode, RectangularMicroQrCode, or DataMatrix. Note: on this printer a full QR is always near the practical scanning limit - prefer rMQR or Micro QR.")] - public LetraHelper.TwoDSymbology Symbology { get; set; } + [Option("symbology", Default = TwoDSymbology.Auto, HelpText = "Auto (least tape while staying scannable), QrCode, MicroQrCode, RectangularMicroQrCode, or DataMatrix. Note: on this printer a full QR is always near the practical scanning limit - prefer rMQR or Micro QR.")] + public TwoDSymbology Symbology { get; set; } } [Verb("print-symbol", HelpText = "Print a symbol previously saved from the GUI's Draw tab symbol library.")] @@ -150,8 +151,8 @@ internal class DinOptions [Option("font", Default = "Arial", HelpText = "Font family name.")] public string Font { get; set; } = "Arial"; - [Option("style", Default = LetraHelper.TextStyle.Normal, HelpText = "Normal, Outline, or Shadow (Vertical isn't supported for DIN rail labels).")] - public LetraHelper.TextStyle Style { get; set; } + [Option("style", Default = TextStyle.Normal, HelpText = "Normal, Outline, or Shadow (Vertical isn't supported for DIN rail labels).")] + public TextStyle Style { get; set; } [Option("bold", HelpText = "Bold weight - independent of --italic, combines freely with it and with --style.")] public bool Bold { get; set; } @@ -159,11 +160,11 @@ internal class DinOptions [Option("italic", HelpText = "Italic slant - combines freely with --bold and --style.")] public bool Italic { get; set; } - [Option("align", Default = LetraHelper.TextAlign.Center, HelpText = "Left, Center, or Right.")] - public LetraHelper.TextAlign Align { get; set; } + [Option("align", Default = TextAlign.Center, HelpText = "Left, Center, or Right.")] + public TextAlign Align { get; set; } - [Option("sizing", Default = LetraHelper.DinRailSizing.MaxPerLabel, HelpText = "Uniform (every segment rendered at the same, shared scale) or MaxPerLabel (each segment independently as large as it can be).")] - public LetraHelper.DinRailSizing Sizing { get; set; } + [Option("sizing", Default = DinRailSizing.MaxPerLabel, HelpText = "Uniform (every segment rendered at the same, shared scale) or MaxPerLabel (each segment independently as large as it can be).")] + public DinRailSizing Sizing { get; set; } [Option("uppercase", HelpText = "Render every label in all uppercase.")] public bool UpperCase { get; set; } @@ -177,12 +178,12 @@ internal class DinOptions /// /// The headless counterpart of the Image/Text/Barcode/2D Code/DIN Rail tabs in the Avalonia GUI - -/// one verb per tab, exposing the same options. Replaces the old, -/// image-only letra200bsharp.Console project. +/// one verb per tab, exposing the same label options. Replaces the old, image-only +/// letra200bsharp.Console project. /// internal static class Cli { - private static readonly ILetraHelper LetraJob = new LetraHelper(new RenderHelper()); + private static readonly ILabelPrintingService Printing = LabelPrinting.Create(letra => letra.AddDymoLetraTag()); /// /// The process exit code, or null if didn't start with one @@ -232,7 +233,7 @@ private static async Task RunListDevicesAsync() { try { - var devices = await LetraPrinter.ScanForDevicesAsync(); + var devices = await Printing.DiscoverAsync(); if (devices.Count == 0) { Console.WriteLine("No Dymo LetraTag 200B found."); @@ -257,8 +258,7 @@ private static async Task RunImageAsync(ImageOptions o) try { var imageBytes = await File.ReadAllBytesAsync(o.Path); - var job = LetraJob.CreateJob(imageBytes, o.NoCut, o.PreRendered); - return await PrintAsync(o.Address, job); + return await PrintAsync(o.Address, new ImageLabel(imageBytes) { PreRendered = o.PreRendered, EdgeToEdge = o.NoCut }); } catch (Exception ex) { @@ -273,15 +273,23 @@ private static async Task RunTextAsync(TextOptions o) { // Mirrors TextTabViewModel.ComposedText: a second line only makes sense with a // size/style that leaves room for it. - bool line2Allowed = o.Style != LetraHelper.TextStyle.Vertical && o.Size != LetraHelper.LabelTextSize.L && o.Size != LetraHelper.LabelTextSize.XL; + bool line2Allowed = o.Style != TextStyle.Vertical && o.Size != LabelTextSize.L && o.Size != LabelTextSize.XL; string text = line2Allowed && !string.IsNullOrEmpty(o.Line2) ? o.Line1 + Environment.NewLine + o.Line2 : o.Line1; - var formatting = new LetraHelper.TextFormatting(o.Bold, o.Italic, o.Underline, o.Strikethrough, o.LetterSpacing); - var frameSpacing = new LetraHelper.FrameSpacing(o.FrameTop, o.FrameBottom, o.FrameLeft, o.FrameRight); - var job = LetraJob.CreateJob(text, o.Font, o.Size, o.Style, o.UpperCase, o.WidthScale, o.Box, noCut: o.NoCut, formatting: formatting, frameSpacing: frameSpacing); - return await PrintAsync(o.Address, job); + return await PrintAsync(o.Address, new TextLabel(text) + { + FontFamily = o.Font, + Size = o.Size, + Style = o.Style, + UpperCase = o.UpperCase, + WidthScale = o.WidthScale, + Box = o.Box, + Formatting = new TextFormatting { Bold = o.Bold, Italic = o.Italic, Underline = o.Underline, Strikethrough = o.Strikethrough, LetterSpacing = o.LetterSpacing }, + FrameSpacing = new FrameSpacing { Top = o.FrameTop, Bottom = o.FrameBottom, Left = o.FrameLeft, Right = o.FrameRight }, + EdgeToEdge = o.NoCut + }); } catch (Exception ex) { @@ -294,9 +302,8 @@ private static async Task RunBarcodeAsync(BarcodeOptions o) { try { - var caption = new LetraHelper.CaptionOptions(o.CaptionPosition, o.CaptionFont, o.CaptionSize, o.CaptionAlign); - var job = LetraJob.CreateJob(o.Data, o.Symbology, o.NoCut, caption); - return await PrintAsync(o.Address, job); + var caption = new CaptionOptions { Position = o.CaptionPosition, FontFamily = o.CaptionFont, Size = o.CaptionSize, Align = o.CaptionAlign }; + return await PrintAsync(o.Address, new BarcodeLabel(o.Data, o.Symbology) { Caption = caption, EdgeToEdge = o.NoCut }); } catch (Exception ex) { @@ -309,8 +316,7 @@ private static async Task RunQrAsync(QrOptions o) { try { - var job = LetraJob.CreateJob(o.Data, o.Symbology); - return await PrintAsync(o.Address, job); + return await PrintAsync(o.Address, new TwoDCodeLabel(o.Data, o.Symbology)); } catch (Exception ex) { @@ -331,8 +337,7 @@ private static async Task RunPrintSymbolAsync(PrintSymbolOptions o) return 1; } - var job = LetraJob.CreateJob(symbol.PixelPng, noCut: false, preRendered: true); - return await PrintAsync(o.Address, job); + return await PrintAsync(o.Address, new ImageLabel(symbol.PixelPng) { PreRendered = true }); } catch (Exception ex) { @@ -345,7 +350,7 @@ private static async Task RunDinAsync(DinOptions o) { try { - var rows = new List<(string Text, decimal Modules)>(); + var cells = new List(); foreach (var label in o.Labels) { int separatorIndex = label.LastIndexOf('='); @@ -355,12 +360,20 @@ private static async Task RunDinAsync(DinOptions o) return 1; } - rows.Add((label[..separatorIndex], modules)); + cells.Add(new DinRailCell(label[..separatorIndex], modules)); } - var formatting = new LetraHelper.TextFormatting(o.Bold, o.Italic); - var job = LetraJob.CreateDinRailRowJob(rows, o.Font, o.Style, o.UpperCase, o.Align, o.Sizing, showSeparators: !o.NoSeparators, o.NoCut, formatting); - return await PrintAsync(o.Address, job); + return await PrintAsync(o.Address, new DinRailLabel(cells) + { + FontFamily = o.Font, + Style = o.Style, + UpperCase = o.UpperCase, + Align = o.Align, + Sizing = o.Sizing, + ShowSeparators = !o.NoSeparators, + Formatting = new TextFormatting { Bold = o.Bold, Italic = o.Italic }, + EdgeToEdge = o.NoCut + }); } catch (Exception ex) { @@ -369,9 +382,11 @@ private static async Task RunDinAsync(DinOptions o) } } - private static async Task PrintAsync(string address, List job) + /// Prints on the printer at , handled by the default (and only) driver. + private static async Task PrintAsync(string address, Label label) { - var result = await LetraPrinter.PrintAsync(address, job); + var printer = new PrinterInfo(address, address, Printing.DefaultDriver.Name); + var result = await Printing.PrintAsync(printer, label); Console.WriteLine(result.Printed ? $"Printed: {result.Message}" : $"Error: {result.Message}"); return result.Printed ? 0 : 1; } diff --git a/Letra200bSharp.Avalonia/Letra200bSharp.Avalonia.csproj b/Letra200bSharp.Avalonia/Letra200bSharp.Avalonia.csproj index cefa6a1..4aee63e 100644 --- a/Letra200bSharp.Avalonia/Letra200bSharp.Avalonia.csproj +++ b/Letra200bSharp.Avalonia/Letra200bSharp.Avalonia.csproj @@ -38,6 +38,6 @@ - + diff --git a/Letra200bSharp.Avalonia/Services/CompositionService.cs b/Letra200bSharp.Avalonia/Services/CompositionService.cs index 0a2b7f2..8b456bf 100644 --- a/Letra200bSharp.Avalonia/Services/CompositionService.cs +++ b/Letra200bSharp.Avalonia/Services/CompositionService.cs @@ -40,13 +40,13 @@ public sealed record ComposeElement( public sealed class CompositionService { private readonly string _filePath; - private readonly IRenderHelper _render; + private readonly ILabelPrintingService _printing; public ObservableCollection Elements { get; } = new(); - public CompositionService(IRenderHelper render) + public CompositionService(ILabelPrintingService printing) { - _render = render; + _printing = printing; var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Letra200bSharp"); Directory.CreateDirectory(directory); _filePath = Path.Combine(directory, "composition.json"); @@ -54,74 +54,55 @@ public CompositionService(IRenderHelper render) } /// - /// Renders one element's printable content, always at noCut: false regardless of what - /// its own tab defaults to standalone - Text, Barcode and 2D come out 30 dots tall, Draw is - /// already 30, Image content is already padded to 32; - /// pads the 30-tall ones so they all line up. + /// One element as a part of a - which lays every part out at the + /// printable head height, whatever its own tab defaults to standalone, so they all line up. + /// Draw and Image elements are already print-sized content and are composed as-is. /// - public byte[] RenderElementImage(TextHistoryParams? text, BarcodeHistoryParams? barcode, QrHistoryParams? qr, DrawHistoryParams? draw, ImageHistoryParams? image) + public static Label ToLabel(TextHistoryParams? text, BarcodeHistoryParams? barcode, QrHistoryParams? qr, DrawHistoryParams? draw, ImageHistoryParams? image) { - if (text is { } rawT) + // TextHistoryParams.ToLabel also migrates a composition staged before independently- + // toggleable Bold/Italic existed, the same way TextTabViewModel does for its own history. + if (text != null) { - // A composition staged before independently-toggleable Bold/Italic existed may still - // carry the old "Bold"/"Italic" Style values - migrate the same way TextTabViewModel - // does for its own history. - var t = rawT.WithLegacyStyleMigrated(); - // Mirrors TextTabViewModel.ComposedText/Line2Enabled - a second line only makes sense - // with a size/style that leaves room for it. - bool line2Enabled = t.Style != nameof(LetraHelper.TextStyle.Vertical) && t.Size != "L" && t.Size != "XL"; - string composedText = line2Enabled && !string.IsNullOrEmpty(t.Line2) ? t.Line1 + Environment.NewLine + t.Line2 : t.Line1; - return _render.RenderTextContentImage( - composedText, - t.FontFamily ?? "Arial", - Enum.Parse(t.Size), - Enum.Parse(t.Style), - t.UpperCase, - (float)t.WidthScale, - Enum.Parse(t.BoxStyle), - Enum.Parse(t.Align), - noCut: false, - t.Formatting, - t.FrameSpacing); + return text.ToLabel(edgeToEdge: false); } - if (barcode is { } b) + if (barcode != null) { - return _render.RenderBarcodeContentImage(b.Data, b.ParsedSymbology, b.ToCaption(), noCut: false); + return barcode.ToLabel(); } - if (qr is { } q) + if (qr != null) { - return _render.RenderTwoDContentImage(q.Data, q.ParsedSymbology); + return qr.ToLabel(); } - if (draw is { } d) + if (draw != null) { - return d.Png; + return draw.ToLabel(); } - if (image is { } i) + if (image != null) { - return i.ContentPng; + return image.ToLabel(); } throw new InvalidOperationException("This element has no renderable content."); } - public byte[] RenderElementImage(ComposeElement element) => - RenderElementImage(element.TextParams, element.BarcodeParams, element.QrParams, element.DrawParams, element.ImageParams); + public static Label ToLabel(ComposeElement element) => + ToLabel(element.TextParams, element.BarcodeParams, element.QrParams, element.DrawParams, element.ImageParams); /// - /// A staged element's thumbnail, built through the same compose path as the final print (see - /// ) so it matches what actually gets printed - /// for every element type, whether it's 30 or 32 dots tall. + /// A staged element's thumbnail, built through the same compose path as the final print so it + /// matches what actually gets printed for every element type. /// - public byte[] RenderThumbnail(byte[] elementContentPng) => _render.PreviewComposedImage(new[] { elementContentPng }); + public byte[] RenderThumbnail(Label part) => _printing.RenderPreview(new ComposedLabel(new[] { part })); /// Renders the element's content and thumbnail, then appends it to the end of the staged list. public void Stage(ComposeElementKind kind, string summary, TextHistoryParams? text = null, BarcodeHistoryParams? barcode = null, QrHistoryParams? qr = null, DrawHistoryParams? draw = null, ImageHistoryParams? image = null) { - var thumbnail = RenderThumbnail(RenderElementImage(text, barcode, qr, draw, image)); + var thumbnail = RenderThumbnail(ToLabel(text, barcode, qr, draw, image)); Add(new ComposeElement(Guid.NewGuid(), kind, summary, thumbnail, text, barcode, qr, draw, image)); } diff --git a/Letra200bSharp.Avalonia/Services/PrintHistoryService.cs b/Letra200bSharp.Avalonia/Services/PrintHistoryService.cs index d8ef867..19d82a1 100644 --- a/Letra200bSharp.Avalonia/Services/PrintHistoryService.cs +++ b/Letra200bSharp.Avalonia/Services/PrintHistoryService.cs @@ -41,19 +41,38 @@ public sealed record TextHistoryParams( int FrameLeft = 0, int FrameRight = 0) { - /// A pre-1.5 entry stored Bold/Italic as Style values, which no longer exist on - map them onto the new independent / fields instead. + /// A pre-1.5 entry stored Bold/Italic as Style values, which no longer exist on - map them onto the new independent / fields instead. public TextHistoryParams WithLegacyStyleMigrated() => Style switch { - "Bold" => this with { Style = nameof(LetraHelper.TextStyle.Normal), Bold = true }, - "Italic" => this with { Style = nameof(LetraHelper.TextStyle.Normal), Italic = true }, + "Bold" => this with { Style = nameof(TextStyle.Normal), Bold = true }, + "Italic" => this with { Style = nameof(TextStyle.Normal), Italic = true }, _ => this }; - [JsonIgnore] - public LetraHelper.TextFormatting Formatting => new(Bold, Italic, Underline, Strikethrough, (float)LetterSpacing); - - [JsonIgnore] - public LetraHelper.FrameSpacing FrameSpacing => new(FrameTop, FrameBottom, FrameLeft, FrameRight); + /// + /// The label these settings describe. Mirrors 's + /// own composing of the two lines: a second line only makes sense with a size/style that + /// leaves room for it. + /// + public TextLabel ToLabel(bool edgeToEdge) + { + var t = WithLegacyStyleMigrated(); + bool line2Enabled = t.Style != nameof(TextStyle.Vertical) && t.Size != nameof(LabelTextSize.L) && t.Size != nameof(LabelTextSize.XL); + string text = line2Enabled && !string.IsNullOrEmpty(t.Line2) ? t.Line1 + Environment.NewLine + t.Line2 : t.Line1; + return new TextLabel(text) + { + FontFamily = t.FontFamily ?? "Arial", + Size = Enum.Parse(t.Size), + Style = Enum.Parse(t.Style), + UpperCase = t.UpperCase, + WidthScale = (float)t.WidthScale, + Box = Enum.Parse(t.BoxStyle), + Align = Enum.Parse(t.Align), + Formatting = new TextFormatting { Bold = t.Bold, Italic = t.Italic, Underline = t.Underline, Strikethrough = t.Strikethrough, LetterSpacing = (float)t.LetterSpacing }, + FrameSpacing = new FrameSpacing { Top = t.FrameTop, Bottom = t.FrameBottom, Left = t.FrameLeft, Right = t.FrameRight }, + EdgeToEdge = edgeToEdge + }; + } } /// @@ -73,18 +92,23 @@ public sealed record BarcodeHistoryParams( { /// The old fixed "show number" caption was exactly Below / Arial / M / Center. public BarcodeHistoryParams WithLegacyCaptionMigrated() => - ShowNumber && CaptionPosition == nameof(LetraHelper.CaptionPosition.None) - ? this with { CaptionPosition = nameof(LetraHelper.CaptionPosition.Below), CaptionFontFamily = "Arial", CaptionSize = nameof(LetraHelper.CaptionSize.M), CaptionAlign = nameof(LetraHelper.TextAlign.Center), ShowNumber = false } + ShowNumber && CaptionPosition == nameof(Letra200bSharp.CaptionPosition.None) + ? this with { CaptionPosition = nameof(Letra200bSharp.CaptionPosition.Below), CaptionFontFamily = "Arial", CaptionSize = nameof(Letra200bSharp.CaptionSize.M), CaptionAlign = nameof(TextAlign.Center), ShowNumber = false } : this; [JsonIgnore] - public LetraHelper.BarcodeSymbology ParsedSymbology => Enum.Parse(Symbology); + public BarcodeSymbology ParsedSymbology => Enum.Parse(Symbology); + + public CaptionOptions ToCaption() => new() + { + Position = Enum.Parse(CaptionPosition), + FontFamily = CaptionFontFamily, + Size = Enum.Parse(CaptionSize), + Align = Enum.Parse(CaptionAlign) + }; - public LetraHelper.CaptionOptions ToCaption() => new( - Enum.Parse(CaptionPosition), - CaptionFontFamily, - Enum.Parse(CaptionSize), - Enum.Parse(CaptionAlign)); + /// The label these settings describe. + public BarcodeLabel ToLabel() => new(Data, ParsedSymbology) { Caption = ToCaption(), EdgeToEdge = NoCut }; } /// @@ -93,21 +117,24 @@ public BarcodeHistoryParams WithLegacyCaptionMigrated() => /// public sealed record QrHistoryParams(string Data, string Symbology) { - /// 2D Code tab ComboBox label paired with the it selects - the labels are what gets persisted. - public static readonly IReadOnlyList<(string Label, LetraHelper.TwoDSymbology Value)> SymbologyChoices = new[] + /// 2D Code tab ComboBox label paired with the it selects - the labels are what gets persisted. + public static readonly IReadOnlyList<(string Label, TwoDSymbology Value)> SymbologyChoices = new[] { - ("Auto", LetraHelper.TwoDSymbology.Auto), - ("QR", LetraHelper.TwoDSymbology.QrCode), - ("Micro QR", LetraHelper.TwoDSymbology.MicroQrCode), - ("rMQR (rectangular)", LetraHelper.TwoDSymbology.RectangularMicroQrCode), - ("Data Matrix", LetraHelper.TwoDSymbology.DataMatrix), + ("Auto", TwoDSymbology.Auto), + ("QR", TwoDSymbology.QrCode), + ("Micro QR", TwoDSymbology.MicroQrCode), + ("rMQR (rectangular)", TwoDSymbology.RectangularMicroQrCode), + ("Data Matrix", TwoDSymbology.DataMatrix), }; - public static LetraHelper.TwoDSymbology ParseSymbology(string label) => + public static TwoDSymbology ParseSymbology(string label) => SymbologyChoices.FirstOrDefault(c => c.Label == label, SymbologyChoices[0]).Value; [JsonIgnore] - public LetraHelper.TwoDSymbology ParsedSymbology => ParseSymbology(Symbology); + public TwoDSymbology ParsedSymbology => ParseSymbology(Symbology); + + /// The label these settings describe. + public TwoDCodeLabel ToLabel() => new(Data, ParsedSymbology); } /// @@ -116,16 +143,24 @@ public static LetraHelper.TwoDSymbology ParseSymbology(string label) => /// is always a small, already print-sized monochrome drawing rather than an arbitrary photo, so /// keeping the full bytes around is cheap. /// -public sealed record DrawHistoryParams(byte[] Png, int WidthDots); +public sealed record DrawHistoryParams(byte[] Png, int WidthDots) +{ + /// The drawing as a label - already print-sized, at the printable head height. + public ImageLabel ToLabel() => new(Png) { PreRendered = true }; +} /// /// An Image tab element of a Compose tab strip (see /), /// kept as its already thresholded and print-sized content PNG (see -/// ), never the source photo. That keeps +/// ), never the source photo. That keeps /// composition.json and history.json small no matter how large the original image was, and /// avoids re-thresholding the photo on every preview. /// -public sealed record ImageHistoryParams(byte[] ContentPng); +public sealed record ImageHistoryParams(byte[] ContentPng) +{ + /// The stored content as a label, printed pixel-exact. + public ImageLabel ToLabel() => new(ContentPng) { PreRendered = true }; +} /// One row of a DIN Rail strip - see . public sealed record DinRailRowParams(string Text, decimal Modules); @@ -148,13 +183,13 @@ public sealed record DinRailHistoryParams( { public DinRailHistoryParams WithLegacyStyleMigrated() => Style switch { - "Bold" => this with { Style = nameof(LetraHelper.TextStyle.Normal), Bold = true }, - "Italic" => this with { Style = nameof(LetraHelper.TextStyle.Normal), Italic = true }, + "Bold" => this with { Style = nameof(TextStyle.Normal), Bold = true }, + "Italic" => this with { Style = nameof(TextStyle.Normal), Italic = true }, _ => this }; [JsonIgnore] - public LetraHelper.TextFormatting Formatting => new(Bold, Italic); + public TextFormatting Formatting => new() { Bold = Bold, Italic = Italic }; } /// @@ -178,7 +213,7 @@ public sealed record ComposeHistoryParams(IReadOnlyList El /// One past print job - or, since was added, one deliberately saved design /// that was never (yet) sent to a printer, for a user who wants to build up a library of labels /// without a Dymo in reach. is the same PNG bytes -/// already produces for +/// already produces for /// the tab's live preview, so it stays tiny. Every job except Image carries enough state to be /// reprinted (/////) - /// an Image job's original source bytes aren't kept around (they could be an arbitrarily large diff --git a/Letra200bSharp.Avalonia/Services/SymbolLibraryService.cs b/Letra200bSharp.Avalonia/Services/SymbolLibraryService.cs index 29ef311..c0606d6 100644 --- a/Letra200bSharp.Avalonia/Services/SymbolLibraryService.cs +++ b/Letra200bSharp.Avalonia/Services/SymbolLibraryService.cs @@ -7,8 +7,7 @@ namespace Letra200bSharp.Avalonia.Services; /// One reusable hand-drawn symbol saved from the Draw tab - is a /// pixel-exact, 1-bit-per-pixel PNG already sized to the printer's head axis (30 rows) with the /// blank columns on each side trimmed off, so it's directly usable with -/// 's preRendered -/// path - no re-encoding needed to print or reload it. +/// an with - no re-encoding needed to print or reload it. /// public sealed record SavedSymbol(Guid Id, string Name, DateTimeOffset Timestamp, int WidthDots, byte[] PixelPng); diff --git a/Letra200bSharp.Avalonia/ViewModels/BarcodeTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/BarcodeTabViewModel.cs index 0a15627..132c1fd 100644 --- a/Letra200bSharp.Avalonia/ViewModels/BarcodeTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/BarcodeTabViewModel.cs @@ -2,7 +2,6 @@ using Avalonia.Media.Imaging; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; @@ -12,44 +11,43 @@ namespace Letra200bSharp.Avalonia.ViewModels; public partial class BarcodeTabViewModel : ViewModelBase { - private readonly Func _getSelectedDevice; + private readonly Func _getSelectedDevice; private readonly Action _reportStatus; private readonly PrintHistoryService _historyService; private readonly CompositionService _composition; - private readonly IRenderHelper _render; - private readonly ILetraHelper _letra; - private readonly Action _recordStats; - - public ObservableCollection Symbologies { get; } = new(Enum.GetNames()); - public ObservableCollection CaptionPositions { get; } = new(Enum.GetNames()); - public ObservableCollection CaptionSizes { get; } = new(Enum.GetNames()); - public ObservableCollection CaptionAligns { get; } = new(Enum.GetNames()); + private readonly ILabelPrintingService _printing; + private readonly Action _recordStats; + + public ObservableCollection Symbologies { get; } = new(Enum.GetNames()); + public ObservableCollection CaptionPositions { get; } = new(Enum.GetNames()); + public ObservableCollection CaptionSizes { get; } = new(Enum.GetNames()); + public ObservableCollection CaptionAligns { get; } = new(Enum.GetNames()); public ObservableCollection FontFamilies { get; } [ObservableProperty] public partial string Data { get; set; } = ""; [ObservableProperty] - public partial string SelectedSymbology { get; set; } = nameof(LetraHelper.BarcodeSymbology.Auto); + public partial string SelectedSymbology { get; set; } = nameof(BarcodeSymbology.Auto); [ObservableProperty] public partial bool NoCut { get; set; } [ObservableProperty] [NotifyPropertyChangedFor(nameof(CaptionStyleEnabled))] - public partial string SelectedCaptionPosition { get; set; } = nameof(LetraHelper.CaptionPosition.None); + public partial string SelectedCaptionPosition { get; set; } = nameof(CaptionPosition.None); [ObservableProperty] public partial string? SelectedCaptionFontFamily { get; set; } [ObservableProperty] - public partial string SelectedCaptionSize { get; set; } = nameof(LetraHelper.CaptionSize.M); + public partial string SelectedCaptionSize { get; set; } = nameof(CaptionSize.M); [ObservableProperty] - public partial string SelectedCaptionAlign { get; set; } = nameof(LetraHelper.TextAlign.Center); + public partial string SelectedCaptionAlign { get; set; } = nameof(TextAlign.Center); - /// Font/size/align only mean anything once a caption position other than is picked - disables (rather than hides) those controls otherwise, same convention as e.g. TextTab's BoxStyleEnabled. - public bool CaptionStyleEnabled => SelectedCaptionPosition != nameof(LetraHelper.CaptionPosition.None); + /// Font/size/align only mean anything once a caption position other than is picked - disables (rather than hides) those controls otherwise, same convention as e.g. TextTab's BoxStyleEnabled. + public bool CaptionStyleEnabled => SelectedCaptionPosition != nameof(CaptionPosition.None); [ObservableProperty] public partial Bitmap? PreviewBitmap { get; set; } @@ -60,14 +58,13 @@ public partial class BarcodeTabViewModel : ViewModelBase [ObservableProperty] public partial bool IsPreviewLoading { get; set; } - public BarcodeTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, IRenderHelper render, ILetraHelper letra, Action recordStats) + public BarcodeTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, ILabelPrintingService printing, Action recordStats) { _getSelectedDevice = getSelectedDevice; _reportStatus = reportStatus; _historyService = historyService; _composition = composition; - _render = render; - _letra = letra; + _printing = printing; _recordStats = recordStats; var fontFamilies = SKFontManager.Default.FontFamilies.OrderBy(f => f).ToArray(); @@ -92,13 +89,13 @@ public void LoadFrom(BarcodeHistoryParams parameters) Data = parameters.Data; SelectedSymbology = parameters.Symbology; NoCut = parameters.NoCut; - SelectedCaptionPosition = CaptionPositions.Contains(parameters.CaptionPosition) ? parameters.CaptionPosition : nameof(LetraHelper.CaptionPosition.None); + SelectedCaptionPosition = CaptionPositions.Contains(parameters.CaptionPosition) ? parameters.CaptionPosition : nameof(CaptionPosition.None); if (parameters.CaptionFontFamily != null && FontFamilies.Contains(parameters.CaptionFontFamily)) { SelectedCaptionFontFamily = parameters.CaptionFontFamily; } - SelectedCaptionSize = CaptionSizes.Contains(parameters.CaptionSize) ? parameters.CaptionSize : nameof(LetraHelper.CaptionSize.M); - SelectedCaptionAlign = CaptionAligns.Contains(parameters.CaptionAlign) ? parameters.CaptionAlign : nameof(LetraHelper.TextAlign.Center); + SelectedCaptionSize = CaptionSizes.Contains(parameters.CaptionSize) ? parameters.CaptionSize : nameof(CaptionSize.M); + SelectedCaptionAlign = CaptionAligns.Contains(parameters.CaptionAlign) ? parameters.CaptionAlign : nameof(TextAlign.Center); PreviewCommand.Execute(null); } @@ -115,14 +112,15 @@ private async Task PreviewAsync() return; } - var parameters = BuildHistoryParams(); + var label = BuildHistoryParams().ToLabel(); + var printer = _getSelectedDevice(); try { IsPreviewLoading = true; var bitmap = await Task.Run(() => { - var previewBytes = _render.PreviewImage(parameters.Data, parameters.ParsedSymbology, parameters.NoCut, parameters.ToCaption()); + var previewBytes = _printing.RenderPreview(label, printer); using var stream = new MemoryStream(previewBytes); return new Bitmap(stream); }); @@ -163,8 +161,7 @@ private async Task PrintAsync() IsBusy = true; try { - var job = await Task.Run(() => _letra.CreateJob(parameters.Data, parameters.ParsedSymbology, parameters.NoCut, parameters.ToCaption())); - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, parameters.ToLabel()); _reportStatus(result.Message, !result.Printed); _recordStats(result); @@ -219,7 +216,7 @@ private void Save() private void RecordHistory(BarcodeHistoryParams parameters, bool printed) { - var thumbnail = _render.PreviewImage(parameters.Data, parameters.ParsedSymbology, parameters.NoCut, parameters.ToCaption()); + var thumbnail = _printing.RenderPreview(parameters.ToLabel(), _getSelectedDevice()); _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.Barcode, Summary(parameters), thumbnail, BarcodeParams: parameters, Printed: printed)); } diff --git a/Letra200bSharp.Avalonia/ViewModels/ComposeTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/ComposeTabViewModel.cs index 5ecb750..d5b2f4a 100644 --- a/Letra200bSharp.Avalonia/ViewModels/ComposeTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/ComposeTabViewModel.cs @@ -3,7 +3,6 @@ using Avalonia.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; @@ -14,20 +13,19 @@ namespace Letra200bSharp.Avalonia.ViewModels; /// Concatenates several already-configured elements - added here from Text/Barcode/2D /// Code/Draw/Image's own "Concatenate" command, not composed from scratch in this tab - into one /// continuous printed strip along the feed axis, the same idea DIN Rail already uses for text -/// segments, generalized to any element type (see ). +/// segments, generalized to any element type (see ). /// The staging list itself lives in , not here or in /// - a separate, ordered, print-order list. DIN Rail /// itself is deliberately not composable (it's already its own multi-segment strip). /// public partial class ComposeTabViewModel : ViewModelBase { - private readonly Func _getSelectedDevice; + private readonly Func _getSelectedDevice; private readonly Action _reportStatus; private readonly PrintHistoryService _historyService; private readonly CompositionService _composition; - private readonly IRenderHelper _render; - private readonly ILetraHelper _letra; - private readonly Action _recordStats; + private readonly ILabelPrintingService _printing; + private readonly Action _recordStats; /// Bumped on every preview request, so a slower, older render finishing late never overwrites a newer one. private int _previewVersion; @@ -47,14 +45,13 @@ public partial class ComposeTabViewModel : ViewModelBase [ObservableProperty] public partial bool IsPreviewLoading { get; set; } - public ComposeTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, IRenderHelper render, ILetraHelper letra, Action recordStats) + public ComposeTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, ILabelPrintingService printing, Action recordStats) { _getSelectedDevice = getSelectedDevice; _reportStatus = reportStatus; _historyService = historyService; _composition = composition; - _render = render; - _letra = letra; + _printing = printing; _recordStats = recordStats; Elements.CollectionChanged += (_, _) => @@ -112,7 +109,7 @@ public void LoadFrom(ComposeHistoryParams parameters) Guid.NewGuid(), Enum.Parse(ep.Kind), ep.Summary, - _composition.RenderThumbnail(_composition.RenderElementImage(ep.TextParams, ep.BarcodeParams, ep.QrParams, ep.DrawParams, ep.ImageParams)), + _composition.RenderThumbnail(CompositionService.ToLabel(ep.TextParams, ep.BarcodeParams, ep.QrParams, ep.DrawParams, ep.ImageParams)), ep.TextParams, ep.BarcodeParams, ep.QrParams, @@ -128,8 +125,8 @@ public void LoadFrom(ComposeHistoryParams parameters) _composition.SetAll(elements); } - private byte[][] RenderAllElements(IReadOnlyList elements) => - elements.Select(_composition.RenderElementImage).ToArray(); + private static ComposedLabel BuildLabel(IReadOnlyList elements) => + new(elements.Select(CompositionService.ToLabel).ToList()); [RelayCommand(AllowConcurrentExecutions = true)] private async Task PreviewAsync() @@ -145,14 +142,15 @@ private async Task PreviewAsync() return; } - var elements = Elements.ToList(); + var label = BuildLabel(Elements.ToList()); + var printer = _getSelectedDevice(); try { IsPreviewLoading = true; var bitmap = await Task.Run(() => { - var previewBytes = _render.PreviewComposedImage(RenderAllElements(elements)); + var previewBytes = _printing.RenderPreview(label, printer); using var stream = new MemoryStream(previewBytes); return new Bitmap(stream); }); @@ -204,9 +202,7 @@ private async Task PrintAsync() IsBusy = true; try { - var elementPngs = await Task.Run(() => RenderAllElements(elements)); - var job = await Task.Run(() => _letra.CreateComposedJob(elementPngs)); - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, BuildLabel(elements)); _reportStatus(result.Message, !result.Printed); _recordStats(result); @@ -214,7 +210,7 @@ private async Task PrintAsync() { try { - RecordHistory(elements, elementPngs, printed: true); + RecordHistory(elements, printed: true); } catch { @@ -250,7 +246,7 @@ private void Save() try { var elements = Elements.ToList(); - RecordHistory(elements, RenderAllElements(elements), printed: false); + RecordHistory(elements, printed: false); _reportStatus(Strings.Status_SavedToHistory, false); } catch (Exception ex) @@ -259,10 +255,9 @@ private void Save() } } - /// Takes the already-rendered element content so a print doesn't render everything twice. - private void RecordHistory(IReadOnlyList elements, IReadOnlyList elementPngs, bool printed) + private void RecordHistory(IReadOnlyList elements, bool printed) { - var thumbnail = _render.PreviewComposedImage(elementPngs); + var thumbnail = _printing.RenderPreview(BuildLabel(elements), _getSelectedDevice()); var elementParams = elements .Select(e => new ComposeElementParams(e.Kind.ToString(), e.Summary, e.TextParams, e.BarcodeParams, e.QrParams, e.DrawParams, e.ImageParams)) .ToList(); diff --git a/Letra200bSharp.Avalonia/ViewModels/DinRailTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/DinRailTabViewModel.cs index 67f1797..9bc1ebe 100644 --- a/Letra200bSharp.Avalonia/ViewModels/DinRailTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/DinRailTabViewModel.cs @@ -2,7 +2,6 @@ using Avalonia.Media.Imaging; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; @@ -21,7 +20,7 @@ public sealed partial class DinRailRow : ObservableObject /// /// Set by when this row's text would need heavy shrinking - /// to fit its module count (see ) - a hint that + /// to fit its module count (see ) - a hint that /// the printed text will likely be too small to read, so the user knows to either shorten it /// or add more modules instead of only discovering it after printing. /// @@ -31,28 +30,27 @@ public sealed partial class DinRailRow : ObservableObject /// /// Builds a list of text/module-count rows and prints them as one continuous DIN rail strip -/// (see ) - unlike , +/// (see ) - unlike , /// each row's text is always auto-fit (auto-wrapped to 2 lines if that helps it fit better, /// then scaled uniformly - never stretched/squeezed non-uniformly) to its own segment, with no -/// manual height/stretch controls; see for the two ways +/// manual height/stretch controls; see for the two ways /// that uniform scale can be chosen. /// public partial class DinRailTabViewModel : ViewModelBase { - private readonly Func _getSelectedDevice; + private readonly Func _getSelectedDevice; private readonly Action _reportStatus; private readonly PrintHistoryService _historyService; - private readonly IRenderHelper _render; - private readonly ILetraHelper _letra; - private readonly Action _recordStats; + private readonly ILabelPrintingService _printing; + private readonly Action _recordStats; public ObservableCollection FontFamilies { get; } - /// Same as minus - one-character-per-line doesn't combine sensibly with the automatic word-wrap each segment already does. - public ObservableCollection Styles { get; } = new(Enum.GetNames().Where(name => name != nameof(LetraHelper.TextStyle.Vertical))); + /// Same as minus - one-character-per-line doesn't combine sensibly with the automatic word-wrap each segment already does. + public ObservableCollection Styles { get; } = new(Enum.GetNames().Where(name => name != nameof(TextStyle.Vertical))); - public ObservableCollection Aligns { get; } = new(Enum.GetNames()); - public ObservableCollection Sizings { get; } = new(Enum.GetNames()); + public ObservableCollection Aligns { get; } = new(Enum.GetNames()); + public ObservableCollection Sizings { get; } = new(Enum.GetNames()); public ObservableCollection Rows { get; } = new(); @@ -60,7 +58,7 @@ public partial class DinRailTabViewModel : ViewModelBase public partial string? SelectedFontFamily { get; set; } [ObservableProperty] - public partial string SelectedStyle { get; set; } = nameof(LetraHelper.TextStyle.Normal); + public partial string SelectedStyle { get; set; } = nameof(TextStyle.Normal); /// Independently toggleable alongside and - see TextTabViewModel's Bold for the same combinable-formatting idea. [ObservableProperty] @@ -70,10 +68,10 @@ public partial class DinRailTabViewModel : ViewModelBase public partial bool Italic { get; set; } [ObservableProperty] - public partial string SelectedAlign { get; set; } = nameof(LetraHelper.TextAlign.Center); + public partial string SelectedAlign { get; set; } = nameof(TextAlign.Center); [ObservableProperty] - public partial string SelectedSizing { get; set; } = nameof(LetraHelper.DinRailSizing.MaxPerLabel); + public partial string SelectedSizing { get; set; } = nameof(DinRailSizing.MaxPerLabel); [ObservableProperty] public partial bool UpperCase { get; set; } @@ -97,16 +95,15 @@ public partial class DinRailTabViewModel : ViewModelBase [ObservableProperty] public partial string TotalModulesText { get; set; } = ""; - /// Below this required scale (see ), a row is flagged as likely too small to read once printed. + /// Below this required scale (see ), a row is flagged as likely too small to read once printed. private const float LegibilityWarningThreshold = 0.3f; - public DinRailTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, IRenderHelper render, ILetraHelper letra, Action recordStats) + public DinRailTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, ILabelPrintingService printing, Action recordStats) { _getSelectedDevice = getSelectedDevice; _reportStatus = reportStatus; _historyService = historyService; - _render = render; - _letra = letra; + _printing = printing; _recordStats = recordStats; var fontFamilies = SKFontManager.Default.FontFamilies.OrderBy(f => f).ToArray(); @@ -123,7 +120,26 @@ public DinRailTabViewModel(Func getSelectedDevice, Action RecomputeAllWarnings(); partial void OnItalicChanged(bool value) => RecomputeAllWarnings(); - private LetraHelper.TextFormatting BuildFormatting() => new(Bold, Italic); + private TextFormatting BuildFormatting() => new() { Bold = Bold, Italic = Italic }; + + /// The renderer's DIN rail measurements, or null if it doesn't provide them (see ). + private IDinRailLayout? Layout => _printing.GetRenderer(_getSelectedDevice()) as IDinRailLayout; + + /// + /// Snapshot of the tab's current settings as a label, taken before any await. Always + /// edge-to-edge: a standalone DIN rail strip uses the printer's full head height. + /// + private DinRailLabel BuildLabel(IReadOnlyList cells) => new(cells) + { + FontFamily = SelectedFontFamily ?? "Arial", + Style = Enum.Parse(SelectedStyle), + UpperCase = UpperCase, + Align = Enum.Parse(SelectedAlign), + Sizing = Enum.Parse(SelectedSizing), + ShowSeparators = ShowSeparators, + Formatting = BuildFormatting(), + EdgeToEdge = true + }; private void RecomputeAllWarnings() { @@ -135,18 +151,16 @@ private void RecomputeAllWarnings() private void RecomputeRowWarning(DinRailRow row) { - var fontFamily = SelectedFontFamily ?? "Arial"; - var style = Enum.Parse(SelectedStyle); - var align = Enum.Parse(SelectedAlign); - float scale = _render.DinRailRequiredScale(row.Text, fontFamily, style, UpperCase, align, row.Modules, true, BuildFormatting()); - row.IsTooSmallToReadWell = scale < LegibilityWarningThreshold; + var layout = Layout; + row.IsTooSmallToReadWell = layout != null + && layout.RequiredScale(BuildLabel(new[] { new DinRailCell(row.Text, row.Modules) }), 0) < LegibilityWarningThreshold; } /// Restores a previously printed DIN rail strip (see ) and refreshes the preview so the user can see what they're about to reprint. public void LoadFrom(DinRailHistoryParams rawParameters) { // Pre-1.5 entries stored Bold/Italic as SelectedStyle values, which no longer exist on - // LetraHelper.TextStyle - map them onto the new independent Bold/Italic fields instead. + // TextStyle - map them onto the new independent Bold/Italic fields instead. var parameters = rawParameters.WithLegacyStyleMigrated(); Rows.Clear(); @@ -163,10 +177,10 @@ public void LoadFrom(DinRailHistoryParams rawParameters) { SelectedFontFamily = parameters.FontFamily; } - SelectedStyle = Styles.Contains(parameters.Style) ? parameters.Style : nameof(LetraHelper.TextStyle.Normal); + SelectedStyle = Styles.Contains(parameters.Style) ? parameters.Style : nameof(TextStyle.Normal); UpperCase = parameters.UpperCase; SelectedAlign = parameters.Align; - SelectedSizing = Sizings.Contains(parameters.Sizing) ? parameters.Sizing : nameof(LetraHelper.DinRailSizing.Uniform); + SelectedSizing = Sizings.Contains(parameters.Sizing) ? parameters.Sizing : nameof(DinRailSizing.Uniform); ShowSeparators = parameters.ShowSeparators; Bold = parameters.Bold; Italic = parameters.Italic; @@ -233,14 +247,15 @@ private void RemoveRow(DinRailRow row) /// The "12 mm tall · ~X mm printed"-style caption, summed across every row's own physical segment length, plus the running modules total shown next to the column header. private void UpdateSizeNote() { - float totalMm = Rows.Sum(row => _render.DinRailLengthMm(row.Modules)); + var layout = Layout; + float totalMm = Rows.Sum(row => layout?.LengthMm(row.Modules) ?? (float)row.Modules * DinRailLabel.ModuleWidthMm); SizeNoteText = string.Format(Strings.DinRailTab_SizeNoteFormat, totalMm, Rows.Count); TotalModulesText = string.Format(Strings.DinRailTab_TotalModulesFormat, Rows.Sum(row => row.Modules)); } private bool HasAnyText => Rows.Any(row => !string.IsNullOrWhiteSpace(row.Text)); - private List<(string Text, decimal Modules)> BuildRowList() => Rows.Select(row => (row.Text, row.Modules)).ToList(); + private List BuildRowList() => Rows.Select(row => new DinRailCell(row.Text, row.Modules)).ToList(); [RelayCommand] private async Task PreviewAsync() @@ -253,21 +268,15 @@ private async Task PreviewAsync() return; } - var rows = BuildRowList(); - var fontFamily = SelectedFontFamily ?? "Arial"; - var style = Enum.Parse(SelectedStyle); - var align = Enum.Parse(SelectedAlign); - var sizing = Enum.Parse(SelectedSizing); - var upperCase = UpperCase; - var showSeparators = ShowSeparators; - var formatting = BuildFormatting(); + var label = BuildLabel(BuildRowList()); + var printer = _getSelectedDevice(); try { IsPreviewLoading = true; var bitmap = await Task.Run(() => { - var previewBytes = _render.PreviewDinRailRowImage(rows, fontFamily, style, upperCase, align, sizing, showSeparators, true, formatting); + var previewBytes = _printing.RenderPreview(label, printer); using var stream = new MemoryStream(previewBytes); return new Bitmap(stream); }); @@ -302,20 +311,12 @@ private async Task PrintAsync() return; } - var rows = BuildRowList(); - var fontFamily = SelectedFontFamily ?? "Arial"; - var style = Enum.Parse(SelectedStyle); - var align = Enum.Parse(SelectedAlign); - var sizing = Enum.Parse(SelectedSizing); - var upperCase = UpperCase; - var showSeparators = ShowSeparators; - var formatting = BuildFormatting(); + var label = BuildLabel(BuildRowList()); IsBusy = true; try { - var job = await Task.Run(() => _letra.CreateDinRailRowJob(rows, fontFamily, style, upperCase, align, sizing, showSeparators, true, formatting)); - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, label); _reportStatus(result.Message, !result.Printed); _recordStats(result); @@ -323,7 +324,7 @@ private async Task PrintAsync() { try { - RecordHistory(rows, fontFamily, style, upperCase, align, sizing, showSeparators, printed: true); + RecordHistory(label, printed: true); } catch { @@ -356,15 +357,9 @@ private void Save() return; } - var rows = BuildRowList(); - var fontFamily = SelectedFontFamily ?? "Arial"; - var style = Enum.Parse(SelectedStyle); - var align = Enum.Parse(SelectedAlign); - var sizing = Enum.Parse(SelectedSizing); - try { - RecordHistory(rows, fontFamily, style, UpperCase, align, sizing, ShowSeparators, printed: false); + RecordHistory(BuildLabel(BuildRowList()), printed: false); _reportStatus(Strings.Status_SavedToHistory, false); } catch (Exception ex) @@ -373,11 +368,12 @@ private void Save() } } - private void RecordHistory(List<(string Text, decimal Modules)> rows, string fontFamily, LetraHelper.TextStyle style, bool upperCase, LetraHelper.TextAlign align, LetraHelper.DinRailSizing sizing, bool showSeparators, bool printed) + private void RecordHistory(DinRailLabel label, bool printed) { - var thumbnail = _render.PreviewDinRailRowImage(rows, fontFamily, style, upperCase, align, sizing, showSeparators, true, BuildFormatting()); + var rows = label.Cells; + var thumbnail = _printing.RenderPreview(label, _getSelectedDevice()); var rowParams = rows.Select(row => new DinRailRowParams(row.Text, row.Modules)).ToList(); - var parameters = new DinRailHistoryParams(rowParams, fontFamily, SelectedStyle, upperCase, SelectedAlign, SelectedSizing, showSeparators, Bold, Italic); + var parameters = new DinRailHistoryParams(rowParams, label.FontFamily, SelectedStyle, label.UpperCase, SelectedAlign, SelectedSizing, label.ShowSeparators, Bold, Italic); var summary = $"{rows.Count} label{(rows.Count == 1 ? "" : "s")}: " + string.Join(" | ", rows.Select(row => row.Text)); _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.DinRail, summary, thumbnail, DinRailParams: parameters, Printed: printed)); } diff --git a/Letra200bSharp.Avalonia/ViewModels/DrawTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/DrawTabViewModel.cs index 71753de..c5194b1 100644 --- a/Letra200bSharp.Avalonia/ViewModels/DrawTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/DrawTabViewModel.cs @@ -5,7 +5,6 @@ using Avalonia.Platform; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; @@ -23,8 +22,8 @@ namespace Letra200bSharp.Avalonia.ViewModels; /// /// The canvas model () is always exactly rows /// - the printer's printable head axis - by columns (the feed -/// axis, resizable), so it's already what 's -/// preRendered path expects: no rotation or rescale needed anywhere in this class, just a +/// axis, resizable), so it's already what an with +/// expects: no rotation or rescale needed anywhere in this class, just a /// 1-bit-per-pixel PNG encode. is a separate, purely cosmetic /// - the same model redrawn at / /// screen pixels per dot (non-uniform - see for why) so editing @@ -43,14 +42,13 @@ public partial class DrawTabViewModel : ViewModelBase /// How many previous strokes can step back through. private const int MaxUndoDepth = 30; - private readonly Func _getSelectedDevice; + private readonly Func _getSelectedDevice; private readonly Action _reportStatus; private readonly PrintHistoryService _historyService; private readonly SymbolLibraryService _symbolLibrary; private readonly CompositionService _composition; - private readonly IRenderHelper _render; - private readonly ILetraHelper _letra; - private readonly Action _recordStats; + private readonly ILabelPrintingService _printing; + private readonly Action _recordStats; /// [y, x] - true is a printed (black) dot. Always rows by columns. private bool[,] _pixels = new bool[CanvasHeightDots, DefaultCanvasWidthDots]; @@ -110,7 +108,7 @@ public enum DrawTool /// /// Screen pixels for one feed-axis (horizontal) printer dot - always half , /// since a feed-axis dot is physically half the size of a head-axis one (see - /// LetraHelper.FeedAxisPixelsPerMm's remarks). The correction lands here rather than by + /// FeedAxisPixelsPerMm's remarks). The correction lands here rather than by /// inflating : the head axis is a fixed 30 dots, so keeping it in direct /// control of canvas height keeps that height exactly what it was before this 2:1 fix: the /// (already resizable, already-scrolling) feed axis is what narrows instead. Without this @@ -146,15 +144,14 @@ public enum DrawTool private DrawTool CurrentTool => Enum.Parse(SelectedTool); - public DrawTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, SymbolLibraryService symbolLibrary, CompositionService composition, IRenderHelper render, ILetraHelper letra, Action recordStats) + public DrawTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, SymbolLibraryService symbolLibrary, CompositionService composition, ILabelPrintingService printing, Action recordStats) { _getSelectedDevice = getSelectedDevice; _reportStatus = reportStatus; _historyService = historyService; _symbolLibrary = symbolLibrary; _composition = composition; - _render = render; - _letra = letra; + _printing = printing; _recordStats = recordStats; Symbols.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasSymbols)); @@ -397,7 +394,7 @@ private void StampBrush(int centerX, int centerY) /// Redraws from , nearest-neighbor, at /// screen pixels per feed-axis (horizontal) dot and /// per head-axis (vertical) dot - deliberately not a uniform - /// block like 's upscale, because on + /// block like 's upscale, because on /// the printer itself those two axes aren't the same physical size: a shape that looks square /// here has to actually be twice as wide (in dots) as it is tall to print square (see /// ) - this is what makes the live canvas WYSIWYG against the @@ -476,7 +473,7 @@ private bool HasInk() return false; } - /// Encodes as a pixel-exact, 1-bit-per-pixel PNG - the print-ready form handed to and to . + /// Encodes as a pixel-exact, 1-bit-per-pixel PNG - the print-ready form handed to the printer and to . private static byte[] EncodePixelsPng(bool[,] pixels) { int height = pixels.GetLength(0); @@ -535,12 +532,13 @@ private static byte[] EncodePixelsPng(bool[,] pixels) private async Task PreviewAsync() { var modelPng = EncodePixelsPng(_pixels); + var printer = _getSelectedDevice(); try { IsPreviewLoading = true; var bitmap = await Task.Run(() => { - var previewBytes = _render.PreviewImage(modelPng, noCut: false, preRendered: true); + var previewBytes = _printing.RenderPreview(DrawingLabel(modelPng), printer); using var stream = new MemoryStream(previewBytes); return new Bitmap(stream); }); @@ -580,8 +578,7 @@ private async Task PrintAsync() IsBusy = true; try { - var job = await Task.Run(() => _letra.CreateJob(modelPng, noCut: false, preRendered: true)); - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, DrawingLabel(modelPng)); _reportStatus(result.Message, !result.Printed); _recordStats(result); @@ -633,9 +630,12 @@ private void Save() } } + /// A canvas (or library symbol) as a label: already print-sized, at the printable head height. + private static ImageLabel DrawingLabel(byte[] png) => new(png) { PreRendered = true }; + private void RecordHistory(byte[] modelPng, bool printed) { - var thumbnail = _render.PreviewImage(modelPng, noCut: false, preRendered: true); + var thumbnail = _printing.RenderPreview(DrawingLabel(modelPng), _getSelectedDevice()); var parameters = new DrawHistoryParams(modelPng, CanvasWidthDots); _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.Draw, Strings.DrawTab_DefaultHistoryLabel, thumbnail, DrawParams: parameters, Printed: printed)); } @@ -703,8 +703,7 @@ private async Task PrintSymbolAsync(SavedSymbol symbol) IsBusy = true; try { - var job = await Task.Run(() => _letra.CreateJob(symbol.PixelPng, noCut: false, preRendered: true)); - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, DrawingLabel(symbol.PixelPng)); _reportStatus(result.Message, !result.Printed); _recordStats(result); } diff --git a/Letra200bSharp.Avalonia/ViewModels/ImageTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/ImageTabViewModel.cs index e49cb28..ad91b37 100644 --- a/Letra200bSharp.Avalonia/ViewModels/ImageTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/ImageTabViewModel.cs @@ -1,7 +1,6 @@ using Avalonia.Media.Imaging; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; @@ -10,13 +9,12 @@ namespace Letra200bSharp.Avalonia.ViewModels; public partial class ImageTabViewModel : ViewModelBase { - private readonly Func _getSelectedDevice; + private readonly Func _getSelectedDevice; private readonly Action _reportStatus; private readonly PrintHistoryService _historyService; private readonly CompositionService _composition; - private readonly IRenderHelper _render; - private readonly ILetraHelper _letra; - private readonly Action _recordStats; + private readonly ILabelPrintingService _printing; + private readonly Action _recordStats; /// /// Wired up by the view (needs a TopLevel to show a native file picker), since the @@ -56,17 +54,19 @@ public partial class ImageTabViewModel : ViewModelBase /// public bool NoCutEnabled => PreRendered; - public ImageTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, IRenderHelper render, ILetraHelper letra, Action recordStats) + public ImageTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, ILabelPrintingService printing, Action recordStats) { _getSelectedDevice = getSelectedDevice; _reportStatus = reportStatus; _historyService = historyService; _composition = composition; - _render = render; - _letra = letra; + _printing = printing; _recordStats = recordStats; } + private static ImageLabel BuildLabel(byte[] imageBytes, bool noCut, bool preRendered) => + new(imageBytes) { PreRendered = preRendered, EdgeToEdge = noCut }; + partial void OnPreRenderedChanged(bool value) { if (!value) @@ -101,15 +101,14 @@ private async Task UpdatePreviewAsync() return; } - var imageBytes = _imageBytes; - var noCut = NoCut; - var preRendered = PreRendered; + var label = BuildLabel(_imageBytes, NoCut, PreRendered); + var printer = _getSelectedDevice(); try { IsPreviewLoading = true; var bitmap = await Task.Run(() => { - var previewBytes = _render.PreviewImage(imageBytes, noCut, preRendered); + var previewBytes = _printing.RenderPreview(label, printer); using var stream = new MemoryStream(previewBytes); return new Bitmap(stream); }); @@ -151,9 +150,7 @@ private async Task PrintAsync() IsBusy = true; try { - var job = await Task.Run(() => _letra.CreateJob(imageBytes, noCut, preRendered)); - - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, BuildLabel(imageBytes, noCut, preRendered)); _reportStatus(result.Message, !result.Printed); _recordStats(result); @@ -208,7 +205,7 @@ private void Save() private void RecordHistory(byte[] imageBytes, bool noCut, bool preRendered, bool printed) { - var thumbnail = _render.PreviewImage(imageBytes, noCut, preRendered); + var thumbnail = _printing.RenderPreview(BuildLabel(imageBytes, noCut, preRendered), _getSelectedDevice()); _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.Image, ImagePath ?? Strings.ImageTab_DefaultHistoryLabel, thumbnail, Printed: printed)); } @@ -231,7 +228,8 @@ private void Concatenate() { // Forced noCut:false, like every other element type, so this lines up at the same // height as the rest of the composition regardless of what's checked on this tab. - var parameters = new ImageHistoryParams(_render.RenderImageContentImage(_imageBytes, PreRendered, noCut: false)); + var content = _printing.GetRenderer(_getSelectedDevice()).RenderContent(BuildLabel(_imageBytes, noCut: false, PreRendered)); + var parameters = new ImageHistoryParams(content); _composition.Stage(ComposeElementKind.Image, ImagePath ?? Strings.ImageTab_DefaultHistoryLabel, image: parameters); _reportStatus(Strings.Status_AddedToComposition, false); } diff --git a/Letra200bSharp.Avalonia/ViewModels/MainViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/MainViewModel.cs index a7a280f..cb4eac4 100644 --- a/Letra200bSharp.Avalonia/ViewModels/MainViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/MainViewModel.cs @@ -2,10 +2,10 @@ using Avalonia.Controls.Notifications; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; +using Microsoft.Extensions.DependencyInjection; using SukiUI.Toasts; namespace Letra200bSharp.Avalonia.ViewModels; @@ -23,13 +23,13 @@ public partial class MainViewModel : ViewModelBase public const int HistoryTabIndex = 7; public const int AboutTabIndex = 8; - public ObservableCollection Devices { get; } = new(); + public ObservableCollection Devices { get; } = new(); [ObservableProperty] public partial int SelectedTabIndex { get; set; } [ObservableProperty] - public partial BluetoothDevice? SelectedDevice { get; set; } + public partial PrinterInfo? SelectedDevice { get; set; } [ObservableProperty] public partial bool IsRefreshing { get; set; } @@ -47,36 +47,37 @@ public partial class MainViewModel : ViewModelBase [ObservableProperty] [NotifyPropertyChangedFor(nameof(StatsDisplayText))] - public partial LetraPrintResult? LastPrintResult { get; set; } + public partial PrintResult? LastPrintResult { get; set; } /// /// A YouTube "stats for nerds"-style dump of the last print attempt's protocol-level numbers - /// (see ) - purely for curiosity, not shown anywhere else. + /// (see ) - purely for curiosity, not shown anywhere else. /// public string? StatsDisplayText { get { - if (LastPrintResult is not { Stats: { } stats } result) + if (LastPrintResult is not { Statistics: { } stats } result) { return null; } - return string.Join(Environment.NewLine, + var lines = new List + { $"Job: {LastPrintKind}", $"Result: {(result.Printed ? "printed" : "failed")} (status {result.StatusCode?.ToString() ?? "none"})", $"Bytes sent: {stats.TotalBytes} B across {stats.PacketCount} packet{(stats.PacketCount == 1 ? "" : "s")}", $"Elapsed: {stats.Elapsed.TotalMilliseconds:0} ms", - $"Service UUID: {stats.ServiceUuid}", - $"MTU: {stats.RequestedMtu} requested, {(stats.MtuNegotiated ? "negotiated" : "not confirmed")}"); + }; + lines.AddRange(stats.Details.Select(detail => $"{(detail.Key + ":").PadRight(13)} {detail.Value}")); + return string.Join(Environment.NewLine, lines); } } private readonly PrintHistoryService _historyService = new(); private readonly SymbolLibraryService _symbolLibrary = new(); - private readonly IRenderHelper _renderHelper = new RenderHelper(); + private readonly ILabelPrintingService _printing; private readonly CompositionService _compositionService; - private readonly ILetraHelper _letraHelper; public ImageTabViewModel Image { get; } public TextTabViewModel Text { get; } @@ -90,16 +91,18 @@ public string? StatsDisplayText public MainViewModel() { - _letraHelper = new LetraHelper(_renderHelper); - _compositionService = new CompositionService(_renderHelper); - - Image = new ImageTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _renderHelper, _letraHelper, result => RecordPrintStats("Image", result)); - Text = new TextTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _renderHelper, _letraHelper, result => RecordPrintStats("Text", result)); - Barcode = new BarcodeTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _renderHelper, _letraHelper, result => RecordPrintStats("Barcode", result)); - Qr = new QrTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _renderHelper, _letraHelper, result => RecordPrintStats("2D Code", result)); - Draw = new DrawTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _symbolLibrary, _compositionService, _renderHelper, _letraHelper, result => RecordPrintStats("Draw", result)); - DinRail = new DinRailTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _renderHelper, _letraHelper, result => RecordPrintStats("DinRail", result)); - Compose = new ComposeTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _renderHelper, _letraHelper, result => RecordPrintStats("Compose", result)); + // Every supported printer is a driver registered here - see LetraBuilder.AddDriver for + // adding one that isn't packaged as its own Add...() extension. + _printing = LabelPrinting.Create(letra => letra.AddDymoLetraTag()); + _compositionService = new CompositionService(_printing); + + Image = new ImageTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _printing, result => RecordPrintStats("Image", result)); + Text = new TextTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _printing, result => RecordPrintStats("Text", result)); + Barcode = new BarcodeTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _printing, result => RecordPrintStats("Barcode", result)); + Qr = new QrTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _printing, result => RecordPrintStats("2D Code", result)); + Draw = new DrawTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _symbolLibrary, _compositionService, _printing, result => RecordPrintStats("Draw", result)); + DinRail = new DinRailTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _printing, result => RecordPrintStats("DinRail", result)); + Compose = new ComposeTabViewModel(() => SelectedDevice, ReportStatus, _historyService, _compositionService, _printing, result => RecordPrintStats("Compose", result)); History = new HistoryTabViewModel(_historyService, Text, Barcode, Qr, Draw, DinRail, Compose, index => SelectedTabIndex = index); About = new AboutTabViewModel(); @@ -108,12 +111,12 @@ public MainViewModel() /// /// Updates the "stats for nerds" panel with the outcome of any print attempt that got far - /// enough to produce - including failed ones (a timeout or a + /// enough to produce - including failed ones (a timeout or a /// bad status code is exactly the kind of thing worth seeing the raw numbers for). /// - private void RecordPrintStats(string kind, LetraPrintResult result) + private void RecordPrintStats(string kind, PrintResult result) { - if (result.Stats == null) + if (result.Statistics == null) { return; } @@ -146,13 +149,13 @@ private async Task RefreshDevicesAsync() // With the radio off (or no adapter at all) a scan either just comes back empty - // indistinguishable from "printer not nearby" - or, on Windows, throws a bare // "Element not found", so check up front and say what's actually wrong. - if (!await Bluetooth.GetAvailabilityAsync()) + if (!await _printing.IsAnyDriverAvailableAsync()) { ReportStatus(Strings.MainView_BluetoothUnavailable, true); return; } - var devices = await LetraPrinter.ScanForDevicesAsync(); + var devices = await _printing.DiscoverAsync(); foreach (var device in devices) { if (!Devices.Any(it => it.Id == device.Id)) @@ -172,7 +175,7 @@ private async Task RefreshDevicesAsync() bool available; try { - available = await Bluetooth.GetAvailabilityAsync(); + available = await _printing.IsAnyDriverAvailableAsync(); } catch { diff --git a/Letra200bSharp.Avalonia/ViewModels/QrTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/QrTabViewModel.cs index 93e6563..5cf7c28 100644 --- a/Letra200bSharp.Avalonia/ViewModels/QrTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/QrTabViewModel.cs @@ -2,7 +2,6 @@ using Avalonia.Media.Imaging; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; @@ -12,21 +11,20 @@ namespace Letra200bSharp.Avalonia.ViewModels; /// /// Encodes text into a 2D matrix code (QR, Micro QR, rMQR or Data Matrix) and prints it. Unlike /// the Barcode tab, module size isn't a user choice - a matrix code's modules have to stay -/// square, so picks the largest module size that fits the printer's -/// head axis and this tab just surfaces what came out (see ), +/// square, so the renderer picks the largest module size that fits the printer's +/// head axis and this tab just surfaces what came out (see ), /// warning via when the result would be too small to scan reliably. /// public partial class QrTabViewModel : ViewModelBase { - private readonly Func _getSelectedDevice; + private readonly Func _getSelectedDevice; private readonly Action _reportStatus; private readonly PrintHistoryService _historyService; private readonly CompositionService _composition; - private readonly IRenderHelper _render; - private readonly ILetraHelper _letra; - private readonly Action _recordStats; + private readonly ILabelPrintingService _printing; + private readonly Action _recordStats; - private static IReadOnlyList<(string Label, LetraHelper.TwoDSymbology Value)> SymbologyChoices => QrHistoryParams.SymbologyChoices; + private static IReadOnlyList<(string Label, TwoDSymbology Value)> SymbologyChoices => QrHistoryParams.SymbologyChoices; public ObservableCollection Symbologies { get; } = new(SymbologyChoices.Select(c => c.Label)); @@ -52,24 +50,29 @@ public partial class QrTabViewModel : ViewModelBase public bool HasSymbolInfo => !string.IsNullOrEmpty(SymbolInfoText); - /// Set when the resolved symbol only gets one printer dot per module (~0.16 mm) - see . + /// Set when the resolved symbol only gets one printer dot per module (~0.16 mm) - see . [ObservableProperty] public partial bool MayNotScanWell { get; set; } - public QrTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, IRenderHelper render, ILetraHelper letra, Action recordStats) + public QrTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, ILabelPrintingService printing, Action recordStats) { _getSelectedDevice = getSelectedDevice; _reportStatus = reportStatus; _historyService = historyService; _composition = composition; - _render = render; - _letra = letra; + _printing = printing; _recordStats = recordStats; } - private LetraHelper.TwoDSymbology CurrentSymbology => + private TwoDSymbology CurrentSymbology => QrHistoryParams.ParseSymbology(SelectedSymbology); + /// How the printer's renderer lays the code out, or null if it can't tell (see ). + private TwoDCodePlan? Plan(TwoDCodeLabel label, PrinterInfo? printer) => + (_printing.GetRenderer(printer) as ITwoDCodePlanner)?.Plan(label); + + private static string Summary(TwoDCodePlan? plan, string data) => plan == null ? data : $"{plan.SymbolName}: {data}"; + /// Restores a previously printed 2D code (see ) and refreshes the preview so the user can see what they're about to reprint. public void LoadFrom(QrHistoryParams parameters) { @@ -95,15 +98,16 @@ private async Task PreviewAsync() return; } - var symbology = CurrentSymbology; + var label = new TwoDCodeLabel(data, CurrentSymbology); + var printer = _getSelectedDevice(); try { IsPreviewLoading = true; var (bitmap, plan) = await Task.Run(() => { - var resolvedPlan = _render.PlanTwoDImage(data, symbology); - var previewBytes = _render.PreviewImage(data, symbology); + var resolvedPlan = Plan(label, printer); + var previewBytes = _printing.RenderPreview(label, printer); using var stream = new MemoryStream(previewBytes); return (new Bitmap(stream), resolvedPlan); }); @@ -112,8 +116,8 @@ private async Task PreviewAsync() PreviewBitmap = bitmap; previous?.Dispose(); - SymbolInfoText = string.Format(Strings.QrTab_SymbolInfoFormat, plan.SymbolName, plan.DotsPerModuleShort, plan.DotsPerModuleLong, plan.ModuleSizeMm); - MayNotScanWell = plan.MayNotScanWell; + SymbolInfoText = plan == null ? "" : string.Format(Strings.QrTab_SymbolInfoFormat, plan.SymbolName, plan.DotsPerModuleShort, plan.DotsPerModuleLong, plan.ModuleSizeMm); + MayNotScanWell = plan?.MayNotScanWell ?? false; } catch (Exception ex) { @@ -150,8 +154,7 @@ private async Task PrintAsync() IsBusy = true; try { - var job = await Task.Run(() => _letra.CreateJob(data, symbology)); - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, new TwoDCodeLabel(data, symbology)); _reportStatus(result.Message, !result.Printed); _recordStats(result); @@ -207,11 +210,12 @@ private void Save() /// Snapshot of the tab's current settings, taken before any await so history always records what was actually printed. private QrHistoryParams BuildHistoryParams() => new(Data, SelectedSymbology); - private void RecordHistory(QrHistoryParams parameters, LetraHelper.TwoDSymbology symbology, bool printed) + private void RecordHistory(QrHistoryParams parameters, TwoDSymbology symbology, bool printed) { - var thumbnail = _render.PreviewImage(parameters.Data, symbology); - var plan = _render.PlanTwoDImage(parameters.Data, symbology); - _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.Qr2D, $"{plan.SymbolName}: {parameters.Data}", thumbnail, QrParams: parameters, Printed: printed)); + var label = new TwoDCodeLabel(parameters.Data, symbology); + var printer = _getSelectedDevice(); + var thumbnail = _printing.RenderPreview(label, printer); + _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.Qr2D, Summary(Plan(label, printer), parameters.Data), thumbnail, QrParams: parameters, Printed: printed)); } /// Adds the current 2D code to the Compose tab's staging list (see ) - lets it become one part of a longer, multi-element printed strip. @@ -228,8 +232,8 @@ private void Concatenate() try { var parameters = BuildHistoryParams(); - var plan = _render.PlanTwoDImage(data, parameters.ParsedSymbology); - _composition.Stage(ComposeElementKind.Qr2D, $"{plan.SymbolName}: {data}", qr: parameters); + var plan = Plan(parameters.ToLabel(), _getSelectedDevice()); + _composition.Stage(ComposeElementKind.Qr2D, Summary(plan, data), qr: parameters); _reportStatus(Strings.Status_AddedToComposition, false); } catch (Exception ex) diff --git a/Letra200bSharp.Avalonia/ViewModels/TextTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/TextTabViewModel.cs index 79dc19d..0319800 100644 --- a/Letra200bSharp.Avalonia/ViewModels/TextTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/TextTabViewModel.cs @@ -2,7 +2,6 @@ using Avalonia.Media.Imaging; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using InTheHand.Bluetooth; using Letra200bSharp; using Letra200bSharp.Avalonia.Resources; using Letra200bSharp.Avalonia.Services; @@ -12,19 +11,18 @@ namespace Letra200bSharp.Avalonia.ViewModels; public partial class TextTabViewModel : ViewModelBase { - private readonly Func _getSelectedDevice; + private readonly Func _getSelectedDevice; private readonly Action _reportStatus; private readonly PrintHistoryService _historyService; private readonly CompositionService _composition; - private readonly IRenderHelper _render; - private readonly ILetraHelper _letra; - private readonly Action _recordStats; + private readonly ILabelPrintingService _printing; + private readonly Action _recordStats; public ObservableCollection FontFamilies { get; } - public ObservableCollection Sizes { get; } = new(Enum.GetNames()); - public ObservableCollection Styles { get; } = new(Enum.GetNames()); - public ObservableCollection BoxStyles { get; } = new(Enum.GetNames()); - public ObservableCollection Aligns { get; } = new(Enum.GetNames()); + public ObservableCollection Sizes { get; } = new(Enum.GetNames()); + public ObservableCollection Styles { get; } = new(Enum.GetNames()); + public ObservableCollection BoxStyles { get; } = new(Enum.GetNames()); + public ObservableCollection Aligns { get; } = new(Enum.GetNames()); [ObservableProperty] public partial string Line1 { get; set; } = "Hello world"; @@ -46,14 +44,14 @@ public partial class TextTabViewModel : ViewModelBase [ObservableProperty] [NotifyPropertyChangedFor(nameof(Line2Enabled))] [NotifyPropertyChangedFor(nameof(Line1Label))] - public partial string SelectedStyle { get; set; } = nameof(LetraHelper.TextStyle.Normal); + public partial string SelectedStyle { get; set; } = nameof(TextStyle.Normal); [ObservableProperty] [NotifyPropertyChangedFor(nameof(FrameSpacingEnabled))] - public partial string SelectedBoxStyle { get; set; } = nameof(LetraHelper.TextBoxStyle.None); + public partial string SelectedBoxStyle { get; set; } = nameof(TextBoxStyle.None); [ObservableProperty] - public partial string SelectedAlign { get; set; } = nameof(LetraHelper.TextAlign.Left); + public partial string SelectedAlign { get; set; } = nameof(TextAlign.Left); [ObservableProperty] public partial bool UpperCase { get; set; } @@ -80,7 +78,7 @@ public partial class TextTabViewModel : ViewModelBase // decimal (not int) to match how every other NumericUpDown-bound property in this tab // (e.g. WidthScale) is typed - keeps Avalonia's NumericUpDown.Value (decimal?) binding - // straightforward, converting to int only where LetraHelper.FrameSpacing actually needs it. + // straightforward, converting to int only where FrameSpacing actually needs it. [ObservableProperty] public partial decimal FrameTop { get; set; } @@ -106,29 +104,28 @@ public partial class TextTabViewModel : ViewModelBase /// A second line doesn't make sense with L/XL (barely any margin left to split between /// two lines) or with the Vertical style (already splits into one line per character). /// - public bool Line2Enabled => SelectedStyle != nameof(LetraHelper.TextStyle.Vertical) && SelectedSize != "L" && SelectedSize != "XL"; + public bool Line2Enabled => SelectedStyle != nameof(TextStyle.Vertical) && SelectedSize != "L" && SelectedSize != "XL"; /// "Text:" on its own when there's only one line, "Text Line 1:" once a second line is available too. public string Line1Label => Line2Enabled ? Strings.TextTab_Line1LabelWithLine2 : Strings.TextTab_Line1LabelSingle; /// /// XL fills the entire printable height with no margin around the text (see - /// ), so there's no room left to draw a border + /// ), so there's no room left to draw a border /// without it overlapping the text or the printer's unprintable edges. /// public bool BoxStyleEnabled => SelectedSize != "XL"; /// Per-side frame margin only means anything once a frame is actually drawn. - public bool FrameSpacingEnabled => BoxStyleEnabled && SelectedBoxStyle != nameof(LetraHelper.TextBoxStyle.None); + public bool FrameSpacingEnabled => BoxStyleEnabled && SelectedBoxStyle != nameof(TextBoxStyle.None); - public TextTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, IRenderHelper render, ILetraHelper letra, Action recordStats) + public TextTabViewModel(Func getSelectedDevice, Action reportStatus, PrintHistoryService historyService, CompositionService composition, ILabelPrintingService printing, Action recordStats) { _getSelectedDevice = getSelectedDevice; _reportStatus = reportStatus; _historyService = historyService; _composition = composition; - _render = render; - _letra = letra; + _printing = printing; _recordStats = recordStats; var fontFamilies = SKFontManager.Default.FontFamilies.OrderBy(f => f).ToArray(); @@ -140,7 +137,7 @@ public TextTabViewModel(Func getSelectedDevice, Action new(Bold, Italic, Underline, Strikethrough, (float)LetterSpacing); - - private LetraHelper.FrameSpacing BuildFrameSpacing() => new((int)FrameTop, (int)FrameBottom, (int)FrameLeft, (int)FrameRight); + /// + /// Snapshot of the tab's current settings as a label, taken before any await. Always + /// edge-to-edge: a standalone text label uses the printer's full head height. + /// + private TextLabel BuildLabel(string text) => new(text) + { + FontFamily = SelectedFontFamily ?? "Arial", + Size = Enum.Parse(SelectedSize), + Style = Enum.Parse(SelectedStyle), + UpperCase = UpperCase, + WidthScale = (float)WidthScale, + Box = Enum.Parse(SelectedBoxStyle), + Align = Enum.Parse(SelectedAlign), + Formatting = new TextFormatting { Bold = Bold, Italic = Italic, Underline = Underline, Strikethrough = Strikethrough, LetterSpacing = (float)LetterSpacing }, + FrameSpacing = new FrameSpacing { Top = (int)FrameTop, Bottom = (int)FrameBottom, Left = (int)FrameLeft, Right = (int)FrameRight }, + EdgeToEdge = true + }; partial void OnSelectedSizeChanged(string value) { if (!BoxStyleEnabled) { - SelectedBoxStyle = nameof(LetraHelper.TextBoxStyle.None); + SelectedBoxStyle = nameof(TextBoxStyle.None); } } - /// Joins the two lines with so renders them stacked. + /// Joins the two lines with so the renderer prints them stacked. private string ComposedText => Line2Enabled && !string.IsNullOrEmpty(Line2) ? Line1 + Environment.NewLine + Line2 : Line1; @@ -197,22 +208,15 @@ private async Task PreviewAsync() return; } - var fontFamily = SelectedFontFamily ?? "Arial"; - var size = Enum.Parse(SelectedSize); - var style = Enum.Parse(SelectedStyle); - var upperCase = UpperCase; - var widthScale = (float)WidthScale; - var boxStyle = Enum.Parse(SelectedBoxStyle); - var align = Enum.Parse(SelectedAlign); - var formatting = BuildFormatting(); - var frameSpacing = BuildFrameSpacing(); + var label = BuildLabel(text); + var printer = _getSelectedDevice(); try { IsPreviewLoading = true; var bitmap = await Task.Run(() => { - var previewBytes = _render.PreviewImage(text, fontFamily, size, style, upperCase, widthScale, boxStyle, align, true, formatting, frameSpacing); + var previewBytes = _printing.RenderPreview(label, printer); using var stream = new MemoryStream(previewBytes); return new Bitmap(stream); }); @@ -248,22 +252,13 @@ private async Task PrintAsync() return; } - var fontFamily = SelectedFontFamily ?? "Arial"; - var size = Enum.Parse(SelectedSize); - var style = Enum.Parse(SelectedStyle); - var upperCase = UpperCase; - var widthScale = (float)WidthScale; - var boxStyle = Enum.Parse(SelectedBoxStyle); - var align = Enum.Parse(SelectedAlign); - var formatting = BuildFormatting(); - var frameSpacing = BuildFrameSpacing(); + var label = BuildLabel(text); var parameters = BuildHistoryParams(); IsBusy = true; try { - var job = await Task.Run(() => _letra.CreateJob(text, fontFamily, size, style, upperCase, widthScale, boxStyle, align, true, formatting, frameSpacing)); - var result = await LetraPrinter.PrintAsync(device, job); + var result = await _printing.PrintAsync(device, label); _reportStatus(result.Message, !result.Printed); _recordStats(result); @@ -271,7 +266,7 @@ private async Task PrintAsync() { try { - RecordHistory(text, fontFamily, size, style, upperCase, widthScale, boxStyle, align, formatting, frameSpacing, parameters, printed: true); + RecordHistory(label, parameters, printed: true); } catch { @@ -305,16 +300,9 @@ private void Save() return; } - var fontFamily = SelectedFontFamily ?? "Arial"; - var size = Enum.Parse(SelectedSize); - var style = Enum.Parse(SelectedStyle); - var widthScale = (float)WidthScale; - var boxStyle = Enum.Parse(SelectedBoxStyle); - var align = Enum.Parse(SelectedAlign); - try { - RecordHistory(text, fontFamily, size, style, UpperCase, widthScale, boxStyle, align, BuildFormatting(), BuildFrameSpacing(), BuildHistoryParams(), printed: false); + RecordHistory(BuildLabel(text), BuildHistoryParams(), printed: false); _reportStatus(Strings.Status_SavedToHistory, false); } catch (Exception ex) @@ -328,10 +316,10 @@ private TextHistoryParams BuildHistoryParams() => new(Line1, Line2, SelectedFontFamily ?? "Arial", SelectedSize, SelectedStyle, WidthScale, SelectedBoxStyle, UpperCase, SelectedAlign, Bold, Italic, Underline, Strikethrough, LetterSpacing, (int)FrameTop, (int)FrameBottom, (int)FrameLeft, (int)FrameRight); - private void RecordHistory(string text, string fontFamily, LetraHelper.LabelTextSize size, LetraHelper.TextStyle style, bool upperCase, float widthScale, LetraHelper.TextBoxStyle boxStyle, LetraHelper.TextAlign align, LetraHelper.TextFormatting formatting, LetraHelper.FrameSpacing frameSpacing, TextHistoryParams parameters, bool printed) + private void RecordHistory(TextLabel label, TextHistoryParams parameters, bool printed) { - var thumbnail = _render.PreviewImage(text, fontFamily, size, style, upperCase, widthScale, boxStyle, align, true, formatting, frameSpacing); - _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.Text, text, thumbnail, TextParams: parameters, Printed: printed)); + var thumbnail = _printing.RenderPreview(label, _getSelectedDevice()); + _historyService.Add(new HistoryEntry(Guid.NewGuid(), DateTimeOffset.Now, HistoryKind.Text, label.Text, thumbnail, TextParams: parameters, Printed: printed)); } /// Adds the current text label to the Compose tab's staging list (see ) - lets it become one part of a longer, multi-element printed strip. diff --git a/Letra200bSharp.Avalonia/Views/BarcodeTabView.axaml b/Letra200bSharp.Avalonia/Views/BarcodeTabView.axaml index 9842c01..969fd9b 100644 --- a/Letra200bSharp.Avalonia/Views/BarcodeTabView.axaml +++ b/Letra200bSharp.Avalonia/Views/BarcodeTabView.axaml @@ -44,7 +44,7 @@ - diff --git a/Letra200bSharp.Avalonia/Views/ComposeTabView.axaml b/Letra200bSharp.Avalonia/Views/ComposeTabView.axaml index 0cd5511..28ce5aa 100644 --- a/Letra200bSharp.Avalonia/Views/ComposeTabView.axaml +++ b/Letra200bSharp.Avalonia/Views/ComposeTabView.axaml @@ -47,7 +47,7 @@