diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9830090..609bb0f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,14 +24,24 @@ env: NUGET_PACKAGES: ${{ github.workspace }}/.nuget/packages DESKTOP_PROJECT: Letra200bSharp.Avalonia.Desktop/Letra200bSharp.Avalonia.Desktop.csproj ANDROID_PROJECT: Letra200bSharp.Avalonia.Android/Letra200bSharp.Avalonia.Android.csproj - + LIBRARY_PROJECTS: >- + Letra200bSharp/Letra200bSharp.csproj + Letra200bSharp.200b/Letra200bSharp.200b.csproj + FEED_URL: https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json + +# Stages: Resolve Version -> Test (Linux, Windows, macOS) -> Pack NuGet +# -> Build (Windows, Linux, Android apps) +# -> Build docs +# -> Pre-release (pull requests) / Tag & Release (main) +# -> on a new release: Publish to GitHub Packages, Publish to nuget.org, Deploy docs +# Pre-release and release need every test, package and app build to succeed. jobs: version: name: Resolve Version runs-on: ubuntu-latest outputs: - # Full version stamped into the build and artifact names: "1.5.0" on main, - # "1.5.0-pr.12.34" (PR number, workflow run number) on a pull request. + # Full version stamped into the build and artifact names: "2.0.0" on main, + # "2.0.0-pr.12.34" (PR number, workflow run number) on a pull request. version: ${{ steps.resolve.outputs.version }} version_prefix: ${{ steps.resolve.outputs.version_prefix }} version_suffix: ${{ steps.resolve.outputs.version_suffix }} @@ -83,6 +93,184 @@ jobs: echo "### Version \`$VERSION\`" >> "$GITHUB_STEP_SUMMARY" + test: + name: Test (${{ matrix.name }}) + runs-on: ${{ matrix.os }} + permissions: + contents: read + checks: write # trx-parser publishes a check run per TRX file + strategy: + fail-fast: false + matrix: + include: + - name: Linux + os: ubuntu-latest + - name: Windows + os: windows-latest + - name: macOS + os: macos-latest + + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + dotnet-quality: 'ga' + + - name: Cache NuGet + uses: actions/cache@v6 + with: + path: ${{ env.NUGET_PACKAGES }} + key: nuget-test-${{ runner.os }}-${{ hashFiles('**/*.csproj', 'Directory.Packages.props', 'Directory.Build.props', 'BuildVersion.props') }} + restore-keys: nuget-test-${{ runner.os }}- + + # Protocol (including the ESC sequence-number regression), driver registration, the + # renderer's features and history compatibility. net10.0 only, so no workload is needed. + - name: Test + shell: bash + run: | + dotnet test --project Letra200bSharp.Tests \ + -c Release \ + -p:TargetFrameworks=net10.0 \ + --results-directory TestResults \ + --report-trx \ + --report-trx-filename "${{ matrix.name }}.trx" + + - name: Upload test results + if: always() + uses: actions/upload-artifact@v7 + with: + name: test-results-${{ matrix.name }} + path: | + TestResults/*.trx + TestResults/*.html + if-no-files-found: warn + + # A fork's pull request gets a read-only token, which can't create check runs. + - name: Publish test reports + if: >- + always() && hashFiles('TestResults/*.trx') != '' && + (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) + uses: NasAmin/trx-parser@c720607ac80bcd6124fcb482e96e0bfe159f5b2f # v0.8.1 + with: + TRX_PATH: ${{ github.workspace }}/TestResults + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPORT_PREFIX: ${{ matrix.name }} + + pack: + name: Pack NuGet + runs-on: ubuntu-latest + needs: [version, test] + env: + VERSION_SUFFIX: ${{ needs.version.outputs.version_suffix }} + + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + dotnet-quality: 'ga' + + - name: Cache NuGet + uses: actions/cache@v6 + with: + path: ${{ env.NUGET_PACKAGES }} + key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', 'Directory.Packages.props', 'Directory.Build.props', 'BuildVersion.props') }} + restore-keys: nuget-${{ runner.os }}- + + # The LetraTag 200B driver also targets net10.0-android. + - name: Install android workload + run: dotnet workload install android + + - name: Pack + run: | + for PROJECT in $LIBRARY_PROJECTS; do + dotnet pack "$PROJECT" \ + -c Release \ + -o artifacts \ + -p:VersionSuffix="$VERSION_SUFFIX" \ + -p:ContinuousIntegrationBuild=true \ + -p:EnableWindowsTargeting=true + done + ls -lh artifacts + + - name: Upload NuGet artifact + uses: actions/upload-artifact@v7 + with: + name: nupkg + path: | + artifacts/*.nupkg + artifacts/*.snupkg + if-no-files-found: error + + docs: + name: Build docs + runs-on: ubuntu-latest + needs: [version] + + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + dotnet-quality: 'ga' + + - name: Cache NuGet + uses: actions/cache@v6 + with: + path: ${{ env.NUGET_PACKAGES }} + key: nuget-docs-${{ runner.os }}-${{ hashFiles('**/*.csproj', 'Directory.Packages.props', 'Directory.Build.props', 'BuildVersion.props', 'dotnet-tools.json') }} + restore-keys: nuget-docs-${{ runner.os }}- + + # DocFX reads the API reference from the built libraries and their XML docs (see + # docs/docfx.json) - net10.0 only, so no workload is needed. + - name: Build libraries + run: | + dotnet build Letra200bSharp.200b/Letra200bSharp.200b.csproj \ + -c Release \ + -p:TargetFrameworks=net10.0 \ + -p:CopyLocalLockFileAssemblies=true + + - name: Build site + run: | + dotnet tool restore + dotnet docfx docs/docfx.json --warningsAsErrors + + - name: Upload site + uses: actions/upload-pages-artifact@v5 + with: + path: docs/_site + + # Published with each new release, so the site always documents the released packages. + deploy-docs: + name: Deploy docs + runs-on: ubuntu-latest + needs: [version, docs, release] + if: needs.version.outputs.tag_exists != 'true' + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deploy.outputs.page_url }} + + steps: + - name: Deploy to GitHub Pages + id: deploy + uses: actions/deploy-pages@v5 + build-windows: name: Build Windows (${{ matrix.rid }}) runs-on: windows-latest @@ -289,7 +477,7 @@ jobs: prerelease: name: PR Pre-release runs-on: ubuntu-latest - needs: [version, build-windows, build-linux, build-android] + needs: [version, test, pack, build-windows, build-linux, build-android] # Same-repository PRs only. A fork's pull_request run gets a read-only token, and this # deliberately doesn't use pull_request_target: that would run untrusted fork code with a # write token. Fork PRs still build and upload workflow artifacts, just no GitHub pre-release. @@ -325,7 +513,7 @@ jobs: - name: Collect pre-release assets run: | mkdir -p release - find dist -type f \( -name '*.zip' -o -name '*.tar.gz' -o -name '*.apk' \) \ + find dist -type f \( -name '*.zip' -o -name '*.tar.gz' -o -name '*.apk' -o -name '*.nupkg' -o -name '*.snupkg' \) \ -exec cp {} release/ \; cd release sha256sum * > SHA256SUMS @@ -334,7 +522,7 @@ jobs: - name: Attest build provenance uses: actions/attest-build-provenance@v4 with: - subject-path: 'release/*.zip, release/*.tar.gz, release/*.apk' + subject-path: 'release/*.zip, release/*.tar.gz, release/*.apk, release/*.nupkg, release/*.snupkg' # One pre-release per PR, replaced on every push so testers always have a single, current # link. Each run gets its own tag (pr---): the repository uses immutable @@ -395,7 +583,7 @@ jobs: release: name: Tag & Release runs-on: ubuntu-latest - needs: [version, build-windows, build-linux, build-android] + needs: [version, test, pack, build-windows, build-linux, build-android] if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request' permissions: contents: write @@ -416,7 +604,7 @@ jobs: - name: Collect release assets run: | mkdir -p release - find dist -type f \( -name '*.zip' -o -name '*.tar.gz' -o -name '*.apk' \) \ + find dist -type f \( -name '*.zip' -o -name '*.tar.gz' -o -name '*.apk' -o -name '*.nupkg' -o -name '*.snupkg' \) \ -exec cp {} release/ \; ls -lh release @@ -429,7 +617,7 @@ jobs: - name: Attest build provenance uses: actions/attest-build-provenance@v4 with: - subject-path: 'release/*.zip, release/*.tar.gz, release/*.apk' + subject-path: 'release/*.zip, release/*.tar.gz, release/*.apk, release/*.nupkg, release/*.snupkg' - name: Tag release id: tag @@ -466,7 +654,7 @@ jobs: DESCRIPTION="Version v$VERSION already released — bump in BuildVersion.props, or add [no-new-version] to the commit message." elif [ "${{ steps.gh_release.outcome }}" = "success" ]; then STATE=success - DESCRIPTION="Released v$VERSION with Windows, Linux and Android artifacts." + DESCRIPTION="Released v$VERSION with the apps and the NuGet packages." else STATE=failure DESCRIPTION="Release failed with an unexpected error." @@ -475,3 +663,90 @@ jobs: -f state="$STATE" \ -f description="$DESCRIPTION" \ -f context="release" + + publish-github: + name: Publish to GitHub Packages + runs-on: ubuntu-latest + needs: [version, release] + if: needs.version.outputs.tag_exists != 'true' + permissions: + packages: write + + steps: + - name: Download NuGet artifact + uses: actions/download-artifact@v8 + with: + name: nupkg + path: nupkg + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + dotnet-quality: 'ga' + + # The same packages attested and attached in the release job. + - name: Push to GitHub Packages + run: | + dotnet nuget push "nupkg/*.nupkg" \ + --source "$FEED_URL" \ + --api-key "${{ secrets.GITHUB_TOKEN }}" \ + --skip-duplicate + + # nuget.org with Trusted Publishing (https://www.nuget.org/account/trustedpublishing): the + # workflow's OIDC token is exchanged for a short-lived API key, so no key is ever stored. Set the + # repository variable NUGET_USER to the nuget.org account owning the trusted publishing policy + # for this workflow (ci.yml); without it, skip. + publish-nuget: + name: Publish to nuget.org + runs-on: ubuntu-latest + needs: [version, release] + if: needs.version.outputs.tag_exists != 'true' + permissions: + id-token: write # nuget.org Trusted Publishing + env: + NUGET_USER: ${{ vars.NUGET_USER }} + + steps: + - name: Check configuration + id: config + run: | + if [ -n "$NUGET_USER" ]; then + echo "enabled=true" >> "$GITHUB_OUTPUT" + else + echo "::warning::The NUGET_USER repository variable isn't configured - skip nuget.org" + echo "enabled=false" >> "$GITHUB_OUTPUT" + fi + + - name: Download NuGet artifact + if: steps.config.outputs.enabled == 'true' + uses: actions/download-artifact@v8 + with: + name: nupkg + path: nupkg + + - name: Setup .NET + if: steps.config.outputs.enabled == 'true' + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + dotnet-quality: 'ga' + + - name: Log in to nuget.org + id: login + if: steps.config.outputs.enabled == 'true' + uses: NuGet/login@v1 + with: + user: ${{ env.NUGET_USER }} + + # The .snupkg symbol packages next to each .nupkg are pushed with it. + - name: Push to nuget.org + if: steps.config.outputs.enabled == 'true' + env: + API_KEY: ${{ steps.login.outputs.NUGET_API_KEY }} + run: | + dotnet nuget push "nupkg/*.nupkg" \ + --source https://api.nuget.org/v3/index.json \ + --api-key "$API_KEY" \ + --skip-duplicate + echo "### nuget.org: pushed $(ls nupkg/*.nupkg | xargs -n1 basename | tr '\n' ' ')" >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index 8a30d25..5d00519 100644 --- a/.gitignore +++ b/.gitignore @@ -396,3 +396,6 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml + +# Test reports (dotnet test --results-directory TestResults) +TestResults/ diff --git a/BuildVersion.props b/BuildVersion.props index 7d97981..d4eb1b7 100644 --- a/BuildVersion.props +++ b/BuildVersion.props @@ -1,8 +1,8 @@ - 1.7.0 + CI passes a pre-release VersionSuffix for pull request builds (pr.12.34 -> 2.0.0-pr.12.34). --> + 2.0.0 true diff --git a/Directory.Packages.props b/Directory.Packages.props index 5e60b65..20a7666 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -4,16 +4,27 @@ - - - - + + + + + + + + + + + + + + diff --git a/Letra200bSharp.200b/ImageInfo.cs b/Letra200bSharp.200b/ImageInfo.cs new file mode 100644 index 0000000..7640cd4 --- /dev/null +++ b/Letra200bSharp.200b/ImageInfo.cs @@ -0,0 +1,14 @@ +namespace Letra200bSharp.LetraTag200b +{ + /// The printer-ready dots produced by - see for the layout of . + internal sealed class ImageInfo + { + /// Dots along the feed axis (label length). + public int Width { get; init; } + + /// Dots across the print head. + public int Height { get; init; } + + public required byte[] Data { get; init; } + } +} diff --git a/Letra200bSharp.200b/Letra200bSharp.200b.csproj b/Letra200bSharp.200b/Letra200bSharp.200b.csproj new file mode 100644 index 0000000..fcd18db --- /dev/null +++ b/Letra200bSharp.200b/Letra200bSharp.200b.csproj @@ -0,0 +1,63 @@ + + + + + + + Dymo LetraTag 200B driver for Letra200bSharp: renders labels for its 32-dot head and prints them over Bluetooth LE. Register it with services.AddLetra().AddLetraTag200b(). + net10.0-windows10.0.19041;net10.0-android;net10.0 + + Letra200bSharp.LetraTag200b + enable + enable + true + + $(NoWarn);CS1591;CS1573 + + + + + internal + + + + + ResXFileCodeGenerator + Strings.Designer.cs + + + + + + + + + + + + + + + + + + + + + + + True + True + Strings.resx + + + + diff --git a/Letra200bSharp.200b/LetraTag200bBuilder.cs b/Letra200bSharp.200b/LetraTag200bBuilder.cs new file mode 100644 index 0000000..948e3cf --- /dev/null +++ b/Letra200bSharp.200b/LetraTag200bBuilder.cs @@ -0,0 +1,81 @@ +using Letra200bSharp; +using Letra200bSharp.LetraTag200b; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// Configures the Dymo LetraTag 200B driver - returned by . + public sealed class LetraTag200bBuilder + { + public LetraTag200bBuilder(IServiceCollection services) + { + Services = services ?? throw new ArgumentNullException(nameof(services)); + } + + /// The service collection the driver is registered in. + public IServiceCollection Services { get; } + + /// Amends . + public LetraTag200bBuilder Configure(Action configuration) + { + ArgumentNullException.ThrowIfNull(configuration); + Services.Configure(configuration); + return this; + } + + /// Font family used for text whose label doesn't name one - see . + public LetraTag200bBuilder SetDefaultFontFamily(string fontFamily) + { + ArgumentException.ThrowIfNullOrEmpty(fontFamily); + return Configure(options => options.DefaultFontFamily = fontFamily); + } + + /// See . + public LetraTag200bBuilder SetDeviceNamePrefix(string prefix) + { + ArgumentException.ThrowIfNullOrEmpty(prefix); + return Configure(options => options.DeviceNamePrefix = prefix); + } + + /// See . + public LetraTag200bBuilder SetReplyTimeout(TimeSpan timeout) + { + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(timeout, TimeSpan.Zero); + return Configure(options => options.ReplyTimeout = timeout); + } + + /// See . + public LetraTag200bBuilder SetPacketDelay(TimeSpan delay) + { + ArgumentOutOfRangeException.ThrowIfLessThan(delay, TimeSpan.Zero); + return Configure(options => options.PacketDelay = delay); + } + + /// See . + public LetraTag200bBuilder SetRequestedMtu(int mtu) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(mtu); + return Configure(options => options.RequestedMtu = mtu); + } + } + + /// Registers the Dymo LetraTag 200B driver with Letra. + public static class LetraTag200bLetraBuilderExtensions + { + /// Registers the Dymo LetraTag 200B driver and returns a builder to configure it. + public static LetraTag200bBuilder AddLetraTag200b(this LetraBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + builder.Services.AddOptions(); + builder.AddDriver(); + return new LetraTag200bBuilder(builder.Services); + } + + /// Registers the Dymo LetraTag 200B driver and configures it with . + public static LetraBuilder AddLetraTag200b(this LetraBuilder builder, Action configuration) + { + ArgumentNullException.ThrowIfNull(configuration); + configuration(builder.AddLetraTag200b()); + return builder; + } + } +} diff --git a/Letra200bSharp.200b/LetraTag200bDriver.cs b/Letra200bSharp.200b/LetraTag200bDriver.cs new file mode 100644 index 0000000..64a6b73 --- /dev/null +++ b/Letra200bSharp.200b/LetraTag200bDriver.cs @@ -0,0 +1,90 @@ +using Microsoft.Extensions.Options; + +namespace Letra200bSharp.LetraTag200b +{ + /// Settings of the Dymo LetraTag 200B driver - configure them with . + public sealed class LetraTag200bOptions + { + /// Font family used for text whose label doesn't name one. + public string DefaultFontFamily { get; set; } = "Arial"; + + /// Only Bluetooth devices whose advertised name starts with this are treated as printers. + public string DeviceNamePrefix { get; set; } = "Letratag"; + + /// How long to wait for the printer to report the outcome after the last packet. + public TimeSpan ReplyTimeout { get; set; } = TimeSpan.FromSeconds(10); + + /// Pause between packets - the printer drops data that arrives too fast. + public TimeSpan PacketDelay { get; set; } = TimeSpan.FromMilliseconds(20); + + /// MTU (bytes) requested from the printer before printing; firmware that rejects it is silently tolerated. + public int RequestedMtu { get; set; } = 512; + } + + /// + /// for the Dymo LetraTag 200B over Bluetooth LE. Register it with + /// services.AddLetra().AddLetraTag200b(). + /// + public sealed class LetraTag200bDriver : ILabelPrinterDriver + { + /// The driver's , as stored in . + public const string DriverName = "LetraTag200b"; + + /// key of the GATT service UUID the printer advertised. + public const string ServiceUuidDetail = "Service UUID"; + + /// key describing the MTU negotiation. + public const string MtuDetail = "MTU"; + + private readonly LetraTagBluetoothTransport _transport; + + public LetraTag200bDriver(IOptions options) + { + var value = options.Value; + _transport = new LetraTagBluetoothTransport(value); + Renderer = new LetraTagLabelRenderer(value); + } + + public string Name => DriverName; + + /// + /// 32 head dots, of which the first and last don't reliably print; head-axis dots are + /// twice the physical size of feed-axis dots, whose pitch was calibrated on real printouts. + /// + public PrinterCapabilities Capabilities { get; } = new() + { + Model = "Dymo LetraTag 200B", + HeadDots = 32, + PrintableHeadDots = 30, + HeadDotsPerMm = RenderHelper.FeedAxisPixelsPerMm / 2f, + FeedDotsPerMm = RenderHelper.FeedAxisPixelsPerMm + }; + + public ILabelRenderer Renderer { get; } + + public Task IsAvailableAsync(CancellationToken cancellationToken = default) => _transport.IsAvailableAsync(); + + public async Task> DiscoverAsync(CancellationToken cancellationToken = default) + { + var devices = await _transport.ScanAsync(cancellationToken); + return devices.Select(device => new PrinterInfo(device.Id, device.Name, DriverName)).ToList(); + } + + public Task PrintAsync(PrinterInfo printer, LabelBitmap bitmap, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(printer); + ArgumentNullException.ThrowIfNull(bitmap); + if (printer.Driver != DriverName) + { + throw new ArgumentException($"Printer '{printer.Name}' belongs to driver '{printer.Driver}', not '{DriverName}'.", nameof(printer)); + } + + if (bitmap.HeadDots != Capabilities.HeadDots) + { + throw new ArgumentException($"The LetraTag 200B prints {Capabilities.HeadDots}-dot-tall labels, but the bitmap is {bitmap.HeadDots} dots tall.", nameof(bitmap)); + } + + return _transport.PrintAsync(printer.Id, LetraTagProtocol.Encode(bitmap), cancellationToken); + } + } +} diff --git a/Letra200bSharp.200b/LetraTagBluetoothTransport.cs b/Letra200bSharp.200b/LetraTagBluetoothTransport.cs new file mode 100644 index 0000000..ac5981f --- /dev/null +++ b/Letra200bSharp.200b/LetraTagBluetoothTransport.cs @@ -0,0 +1,200 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using InTheHand.Bluetooth; +using Letra200bSharp.LetraTag200b.Resources; + +namespace Letra200bSharp.LetraTag200b +{ + /// + /// Discovers and talks to Dymo LetraTag 200B printers over Bluetooth LE. Service/characteristic + /// UUIDs and status codes come from the reverse-engineered protocol documented at + /// https://github.com/ysfchn/dymo-bluetooth. + /// + internal sealed class LetraTagBluetoothTransport + { + private static readonly BluetoothUuid PrintRequestUuid = BluetoothUuid.FromGuid(new Guid("be3dd651-2b3d-42f1-99c1-f0f749dd0678")); + private static readonly BluetoothUuid PrintReplyUuid = BluetoothUuid.FromGuid(new Guid("be3dd652-2b3d-42f1-99c1-f0f749dd0678")); + + private readonly LetraTag200bOptions _options; + + /// Devices returned by the last scans, by id - reused when printing, so a just-discovered device doesn't need resolving again. + private readonly ConcurrentDictionary _knownDevices = new(); + + public LetraTagBluetoothTransport(LetraTag200bOptions options) + { + _options = options; + } + + public async Task IsAvailableAsync() => await Bluetooth.GetAvailabilityAsync(); + + /// Scans for nearby LetraTag printers. + /// + /// The filter is passed to the platform's + /// native BLE scan, but on some platforms (notably Android) it isn't reliably honored - + /// unnamed devices or devices with an unrelated name can still come back. The results are + /// filtered again here so only devices actually named with the prefix are ever surfaced. + /// + public async Task> ScanAsync(CancellationToken cancellationToken) + { + var prefix = _options.DeviceNamePrefix; + var options = new RequestDeviceOptions { AcceptAllDevices = false }; + options.Filters.Add(new BluetoothLEScanFilter { NamePrefix = prefix }); + var devices = await Bluetooth.ScanForDevicesAsync(options, cancellationToken); + var printers = devices + .Where(d => !string.IsNullOrWhiteSpace(d.Name) && d.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + foreach (var printer in printers) + { + _knownDevices[printer.Id] = printer; + } + + return printers; + } + + /// + /// Streams (see ) to the device with + /// the given id and waits for the printer's "print reply" notification to report how it went. + /// + /// The device, its service, or its characteristics could not be resolved. + public async Task PrintAsync(string deviceId, List job, CancellationToken cancellationToken) + { + if (!_knownDevices.TryGetValue(deviceId, out var device)) + { + device = await BluetoothDevice.FromIdAsync(deviceId) + ?? throw new InvalidOperationException($"Unable to connect to bluetooth device '{deviceId}'."); + } + + var stopwatch = Stopwatch.StartNew(); + var services = await device.Gatt.GetPrimaryServicesAsync(); + var uuid = services?.FirstOrDefault(s => s.Uuid.ToString().Length == 36)?.Uuid + ?? throw new InvalidOperationException("Unable to determine UUID."); + + var serv = await device.Gatt.GetPrimaryServiceAsync(uuid) + ?? throw new InvalidOperationException($"Unable to open the printer's GATT service {uuid}."); + + var printRequest = await serv.GetCharacteristicAsync(PrintRequestUuid) + ?? throw new InvalidOperationException("Unable to find the print request characteristic."); + var printReply = await serv.GetCharacteristicAsync(PrintReplyUuid) + ?? throw new InvalidOperationException("Unable to find the print reply characteristic."); + + var replyReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + void OnValueChanged(object? sender, GattCharacteristicValueChangedEventArgs e) + { + // The printer notifies "1B 52 " (ESC 'R' ) once printing is done. + var value = e.Value; + if (value != null && value.Length >= 3 && value[0] == 0x1B && value[1] == 0x52) + { + replyReceived.TrySetResult(value[2]); + } + } + + printReply.CharacteristicValueChanged += OnValueChanged; + int i = 0; + + // Cancels the reply timeout once the reply arrives, so it doesn't linger in the background. + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + bool mtuNegotiated; + try + { + // 1. Android 16 stabilization: request the MTU BEFORE starting notifications. + try + { + await device.Gatt.RequestMtuAsync(_options.RequestedMtu); + await Task.Delay(100, cancellationToken); // Allow the hardware handshake to finish + mtuNegotiated = true; + } + catch (OperationCanceledException) + { + throw; + } + catch + { + // Silent fallback if specific firmware rejects MTU calls + mtuNegotiated = false; + } + + // 2. Start notifications on the newly stabilized MTU size. + await printReply.StartNotificationsAsync(); + await Task.Delay(100, cancellationToken); + + // 3. Write the packets, throttled - the printer drops data sent too fast. + foreach (var jobPart in job) + { + cancellationToken.ThrowIfCancellationRequested(); + i++; + await printRequest.WriteValueWithoutResponseAsync(jobPart); + await Task.Delay(_options.PacketDelay, cancellationToken); + } + + // 4. Wait for the reply, or give up after the timeout. + var timeoutTask = Task.Delay(_options.ReplyTimeout, timeoutCts.Token); + var completed = await Task.WhenAny(replyReceived.Task, timeoutTask); + cancellationToken.ThrowIfCancellationRequested(); + + var stats = new PrintStatistics + { + TotalBytes = job.Sum(p => p.Length), + PacketCount = job.Count, + Elapsed = stopwatch.Elapsed, + Details = new Dictionary + { + [LetraTag200bDriver.ServiceUuidDetail] = uuid.ToString(), + [LetraTag200bDriver.MtuDetail] = $"{_options.RequestedMtu} requested, {(mtuNegotiated ? "negotiated" : "not confirmed")}" + } + }; + + if (completed != replyReceived.Task) + { + return new PrintResult { Printed = false, Message = Strings.PrintResult_Timeout, Statistics = stats }; + } + + timeoutCts.Cancel(); + + return InterpretStatusCode(await replyReceived.Task) with { Statistics = stats }; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception e) + { + // Retain useful diagnostics for troubleshooting multi-packet jobs + var size = i > 0 ? $" Size: {job[i - 1].Length} bytes." : string.Empty; + throw new Exception($"Error transmitting packet index {i} out of {job.Count}.{size} Error: {e.Message}", e); + } + finally + { + printReply.CharacteristicValueChanged -= OnValueChanged; + try + { + await printReply.StopNotificationsAsync(); + } + catch + { + // Catch silent failures here if the printer disconnects abruptly + } + } + } + + internal static PrintResult InterpretStatusCode(byte statusCode) + { + var (printed, message) = statusCode switch + { + 0 => (true, Strings.PrintResult_StatusCompletedMaybe), + 1 => (true, Strings.PrintResult_StatusCompleted), + 2 => (false, Strings.PrintResult_StatusUnknownFailure), + 3 => (true, Strings.PrintResult_StatusLowBatteryCompleted), + 4 => (false, Strings.PrintResult_StatusCancelled), + 5 => (false, Strings.PrintResult_StatusUnknownFailure), + 6 => (false, Strings.PrintResult_StatusLowBatteryFailed), + 7 => (false, Strings.PrintResult_StatusNoCassette), + _ => (false, string.Format(Strings.PrintResult_StatusUnrecognized, statusCode)) + }; + + return new PrintResult { Printed = printed, Message = message, StatusCode = statusCode }; + } + } +} diff --git a/Letra200bSharp.200b/LetraTagLabelRenderer.cs b/Letra200bSharp.200b/LetraTagLabelRenderer.cs new file mode 100644 index 0000000..f5129b3 --- /dev/null +++ b/Letra200bSharp.200b/LetraTagLabelRenderer.cs @@ -0,0 +1,135 @@ +using SkiaSharp; + +namespace Letra200bSharp.LetraTag200b +{ + /// + /// for the Dymo LetraTag 200B: maps each onto the + /// SkiaSharp rendering pipeline in . + /// + internal sealed class LetraTagLabelRenderer : ILabelRenderer, ITwoDCodePlanner, IDinRailLayout + { + private readonly RenderHelper _render; + private readonly string _defaultFontFamily; + + public LetraTagLabelRenderer(LetraTag200bOptions options) + { + _defaultFontFamily = options.DefaultFontFamily; + _render = new RenderHelper(_defaultFontFamily); + } + + public LabelBitmap Render(Label label) + { + var (content, noCut) = RenderPrintable(label); + var image = _render.PrepareImage(content, noCut, preRendered: !IsPhoto(label)); + return new LabelBitmap(image.Width, image.Height, image.Data); + } + + public byte[] RenderPreview(Label label) => label switch + { + // Photos (and pre-rendered images) go straight through the image pipeline, the + // same as printing them does. + ImageLabel image => _render.PreviewImage(image.Image, image.EdgeToEdge, image.PreRendered), + ComposedLabel composed => _render.PreviewComposedImage(RenderParts(composed)), + _ => PreviewPrintable(label) + }; + + public byte[] RenderContent(Label label) => label switch + { + TextLabel text => RenderText(text, text.EdgeToEdge), + BarcodeLabel barcode => _render.RenderBarcodeContentImage(barcode.Data, barcode.Symbology, Caption(barcode), barcode.EdgeToEdge), + TwoDCodeLabel twoD => _render.RenderTwoDContentImage(twoD.Data, twoD.Symbology), + ImageLabel image => _render.RenderImageContentImage(image.Image, image.PreRendered, image.EdgeToEdge), + DinRailLabel dinRail => RenderDinRail(dinRail, dinRail.EdgeToEdge), + ComposedLabel composed => Encode(_render.ComposeElementImages(RenderParts(composed))), + _ => throw Unsupported(label) + }; + + public TwoDCodePlan Plan(TwoDCodeLabel label) => _render.PlanTwoDImage(label.Data, label.Symbology); + + public float LengthMm(decimal modules) => _render.DinRailLengthMm(modules); + + public float RequiredScale(DinRailLabel label, int cellIndex) + { + var cell = label.Cells[cellIndex]; + return _render.DinRailRequiredScale(cell.Text, Font(label.FontFamily), label.Style, label.UpperCase, label.Align, cell.Modules, label.EdgeToEdge, label.Formatting); + } + + /// + /// The image hands to , and whether + /// it already spans the full 32-dot head (noCut) rather than the 30 printable dots. + /// + private (byte[] Content, bool NoCut) RenderPrintable(Label label) => label switch + { + ImageLabel image => (image.Image, image.EdgeToEdge), + + // Every composed part already carries its own head-axis padding by this point - see + // RenderHelper.ComposeElementImages. + ComposedLabel => (RenderContent(label), true), + TextLabel text => (RenderContent(label), text.EdgeToEdge), + BarcodeLabel barcode => (RenderContent(label), barcode.EdgeToEdge), + TwoDCodeLabel => (RenderContent(label), false), + DinRailLabel dinRail => (RenderContent(label), dinRail.EdgeToEdge), + _ => throw Unsupported(label) + }; + + private byte[] PreviewPrintable(Label label) + { + var (content, noCut) = RenderPrintable(label); + return _render.PreviewImage(content, noCut, preRendered: true); + } + + private static bool IsPhoto(Label label) => label is ImageLabel { PreRendered: false }; + + /// + /// Each part's printable content for - + /// always laid out at the printable height (noCut: false) so the parts line up, + /// except images, which are composed as-is. + /// + private List RenderParts(ComposedLabel composed) + { + var parts = new List(); + foreach (var part in composed.Parts) + { + if (part is ComposedLabel nested) + { + parts.AddRange(RenderParts(nested)); + continue; + } + + parts.Add(part switch + { + TextLabel text => RenderText(text, noCut: false), + BarcodeLabel barcode => _render.RenderBarcodeContentImage(barcode.Data, barcode.Symbology, Caption(barcode), noCut: false), + DinRailLabel dinRail => RenderDinRail(dinRail, noCut: false), + ImageLabel { PreRendered: true } image => image.Image, + _ => RenderContent(part) + }); + } + + return parts; + } + + private byte[] RenderText(TextLabel text, bool noCut) => + _render.RenderTextContentImage(text.Text, Font(text.FontFamily), text.Size, text.Style, text.UpperCase, text.WidthScale, text.Box, text.Align, noCut, text.Formatting, text.FrameSpacing); + + private byte[] RenderDinRail(DinRailLabel dinRail, bool noCut) => + _render.RenderDinRailRowImage(dinRail.Cells.Select(c => (c.Text, c.Modules)).ToList(), Font(dinRail.FontFamily), dinRail.Style, dinRail.UpperCase, dinRail.Align, dinRail.Sizing, dinRail.ShowSeparators, noCut, dinRail.Formatting); + + private CaptionOptions Caption(BarcodeLabel barcode) => barcode.Caption ?? CaptionOptions.None; + + private string Font(string? fontFamily) => fontFamily ?? _defaultFontFamily; + + private static byte[] Encode(SKBitmap bitmap) + { + using (bitmap) + using (var image = SKImage.FromBitmap(bitmap)) + using (var encoded = image.Encode(SKEncodedImageFormat.Png, 100)) + { + return encoded.ToArray(); + } + } + + private static NotSupportedException Unsupported(Label label) => + new($"{label.GetType().Name} isn't supported by the Dymo LetraTag 200B renderer."); + } +} diff --git a/Letra200bSharp.200b/LetraTagProtocol.cs b/Letra200bSharp.200b/LetraTagProtocol.cs new file mode 100644 index 0000000..f155ddc --- /dev/null +++ b/Letra200bSharp.200b/LetraTagProtocol.cs @@ -0,0 +1,141 @@ +namespace Letra200bSharp.LetraTag200b +{ + /// + /// The Dymo LetraTag 200B's BLE wire format for a print job (header, chunked body, checksum), + /// reverse-engineered as documented at https://github.com/ysfchn/dymo-bluetooth. Knows nothing + /// about rendering - it encodes an already-rendered . + /// + internal static class LetraTagProtocol + { + /// Form feed command. + private static readonly byte[] FormFeed = { 0x1B, 0x45 }; + + /// Status command. + private static readonly byte[] Status = { 0x1B, 0x41 }; + + /// End of data. + private static readonly byte[] End = { 0x1B, 0x51 }; + + /// Start of the job. + private static readonly byte[] StartJob = { 0x1B, 0x73, 0x9A, 0x02, 0x00, 0x00 }; + + /// Body bytes per chunk (before the 1-byte sequence number). + private const int ChunkSize = 300; + + /// + /// A job always consists of the following parts: + /// - header bytes + /// - chunked body consisting of: + /// - start job + /// - print data + /// - form feed + /// - status + /// - end + /// + /// The packets to write, in order, to the printer's "print request" characteristic. + public static List Encode(LabelBitmap bitmap) + { + var dots = bitmap.Dots; + byte[] packedData = new byte[(dots.Length + 7) / 8]; + for (int i = 0; i < dots.Length; i++) + { + // Any non-zero byte is ink, as LabelBitmap's indexer reads it. + if (dots[i] != 0) + { + packedData[i / 8] |= (byte)(1 << (i % 8)); + } + } + + var body = new List(); + body.AddRange(StartJob); + body.AddRange(GetPrintData(packedData, bitmap.Length, bitmap.HeadDots)); + body.AddRange(FormFeed); + body.AddRange(Status); + body.AddRange(End); + + byte[] header = GetHeaderBytes(body.Count); + var chunks = SplitChunks(body.ToArray()); + + var result = new List { header }; + result.AddRange(chunks); + return result; + } + + private static int CalculateChecksum(ReadOnlySpan data) + { + var checksum = 0; + foreach (byte b in data) + { + checksum += b; + } + return checksum & 0xFF; + } + + private static List SplitChunks(byte[] data) + { + var chunks = new List(); + + // The 1-byte sequence number prefixing each chunk must never be 0x1B (27): + // that's the same byte the printer's firmware uses to recognize the start of + // an ESC command, so a chunk sequenced 27 gets misread as a command instead of + // data, stalling the job. Skip 27 (and, once the counter wraps past 255, 283, + // etc.) the same way the reference protocol does. + byte sequence = 0; + + for (int i = 0; i < data.Length; i += ChunkSize) + { + int end = Math.Min(i + ChunkSize, data.Length); + bool isLast = end == data.Length; + + // The last chunk carries 2 extra trailing bytes. + byte[] chunk = new byte[end - i + (isLast ? 3 : 1)]; + + if (sequence == 0x1B) // 27 + { + sequence++; + } + chunk[0] = sequence; + sequence++; + + Array.Copy(data, i, chunk, 1, end - i); + + if (isLast) + { + chunk[chunk.Length - 2] = 0x12; + chunk[chunk.Length - 1] = 0x34; + } + + chunks.Add(chunk); + } + + return chunks; + } + + private static byte[] GetHeaderBytes(int length) + { + var lengthBytes = BitConverter.GetBytes(length); + var header = new byte[5 + lengthBytes.Length]; + header[0] = 0xFF; // preamble + header[1] = 0xF0; // flags + header[2] = 0x12; // magic + header[3] = 0x34; // magic + Array.Copy(lengthBytes, 0, header, 4, lengthBytes.Length); + header[header.Length - 1] = (byte)CalculateChecksum(header.AsSpan(0, header.Length - 1)); + return header; + } + + private static byte[] GetPrintData(byte[] data, int width, int height) + { + if (width * height != data.Length * 8) + { + throw new ArgumentException($"Data does not match dimensions ({width}*{height}!={data.Length * 8})"); + } + + var printData = new List { 0x1B, 0x44, 0x01, 0x02 }; + printData.AddRange(BitConverter.GetBytes(width)); + printData.AddRange(BitConverter.GetBytes(height)); + printData.AddRange(data); + return printData.ToArray(); + } + } +} diff --git a/Letra200bSharp.200b/PublicAPI.Shipped.txt b/Letra200bSharp.200b/PublicAPI.Shipped.txt new file mode 100644 index 0000000..fec620c --- /dev/null +++ b/Letra200bSharp.200b/PublicAPI.Shipped.txt @@ -0,0 +1,36 @@ +#nullable enable +const Letra200bSharp.LetraTag200b.LetraTag200bDriver.DriverName = "LetraTag200b" -> string! +const Letra200bSharp.LetraTag200b.LetraTag200bDriver.MtuDetail = "MTU" -> string! +const Letra200bSharp.LetraTag200b.LetraTag200bDriver.ServiceUuidDetail = "Service UUID" -> string! +Letra200bSharp.LetraTag200b.LetraTag200bDriver +Letra200bSharp.LetraTag200b.LetraTag200bDriver.Capabilities.get -> Letra200bSharp.PrinterCapabilities! +Letra200bSharp.LetraTag200b.LetraTag200bDriver.DiscoverAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Letra200bSharp.LetraTag200b.LetraTag200bDriver.IsAvailableAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Letra200bSharp.LetraTag200b.LetraTag200bDriver.LetraTag200bDriver(Microsoft.Extensions.Options.IOptions! options) -> void +Letra200bSharp.LetraTag200b.LetraTag200bDriver.Name.get -> string! +Letra200bSharp.LetraTag200b.LetraTag200bDriver.PrintAsync(Letra200bSharp.PrinterInfo! printer, Letra200bSharp.LabelBitmap! bitmap, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Letra200bSharp.LetraTag200b.LetraTag200bDriver.Renderer.get -> Letra200bSharp.ILabelRenderer! +Letra200bSharp.LetraTag200b.LetraTag200bOptions +Letra200bSharp.LetraTag200b.LetraTag200bOptions.DefaultFontFamily.get -> string! +Letra200bSharp.LetraTag200b.LetraTag200bOptions.DefaultFontFamily.set -> void +Letra200bSharp.LetraTag200b.LetraTag200bOptions.DeviceNamePrefix.get -> string! +Letra200bSharp.LetraTag200b.LetraTag200bOptions.DeviceNamePrefix.set -> void +Letra200bSharp.LetraTag200b.LetraTag200bOptions.LetraTag200bOptions() -> void +Letra200bSharp.LetraTag200b.LetraTag200bOptions.PacketDelay.get -> System.TimeSpan +Letra200bSharp.LetraTag200b.LetraTag200bOptions.PacketDelay.set -> void +Letra200bSharp.LetraTag200b.LetraTag200bOptions.ReplyTimeout.get -> System.TimeSpan +Letra200bSharp.LetraTag200b.LetraTag200bOptions.ReplyTimeout.set -> void +Letra200bSharp.LetraTag200b.LetraTag200bOptions.RequestedMtu.get -> int +Letra200bSharp.LetraTag200b.LetraTag200bOptions.RequestedMtu.set -> void +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.Configure(System.Action! configuration) -> Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder! +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.LetraTag200bBuilder(Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> void +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.Services.get -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.SetDefaultFontFamily(string! fontFamily) -> Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder! +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.SetDeviceNamePrefix(string! prefix) -> Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder! +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.SetPacketDelay(System.TimeSpan delay) -> Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder! +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.SetReplyTimeout(System.TimeSpan timeout) -> Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder! +Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder.SetRequestedMtu(int mtu) -> Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder! +Microsoft.Extensions.DependencyInjection.LetraTag200bLetraBuilderExtensions +static Microsoft.Extensions.DependencyInjection.LetraTag200bLetraBuilderExtensions.AddLetraTag200b(this Letra200bSharp.LetraBuilder! builder) -> Microsoft.Extensions.DependencyInjection.LetraTag200bBuilder! +static Microsoft.Extensions.DependencyInjection.LetraTag200bLetraBuilderExtensions.AddLetraTag200b(this Letra200bSharp.LetraBuilder! builder, System.Action! configuration) -> Letra200bSharp.LetraBuilder! diff --git a/Letra200bSharp.200b/PublicAPI.Unshipped.txt b/Letra200bSharp.200b/PublicAPI.Unshipped.txt new file mode 100644 index 0000000..7dc5c58 --- /dev/null +++ b/Letra200bSharp.200b/PublicAPI.Unshipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/Letra200bSharp/RenderHelper.cs b/Letra200bSharp.200b/RenderHelper.cs similarity index 88% rename from Letra200bSharp/RenderHelper.cs rename to Letra200bSharp.200b/RenderHelper.cs index b74ee6b..7b52d2d 100644 --- a/Letra200bSharp/RenderHelper.cs +++ b/Letra200bSharp.200b/RenderHelper.cs @@ -6,15 +6,25 @@ using CodeGlyphX; using CodeGlyphX.DataMatrix; using CodeGlyphX.UpcE; +using Letra200bSharp; -namespace Letra200bSharp +namespace Letra200bSharp.LetraTag200b { /// - /// Turns label content into pixels - see for the contract and why - /// this is kept separate from 's BLE wire-protocol concerns. + /// Turns LetraTag 200B label content into pixels: a 32-dot head whose first and last dot rows + /// don't reliably print, with head-axis dots twice the physical size of feed-axis dots. Kept + /// separate from 's BLE wire-format concerns, and exposed to + /// callers only through . /// - public class RenderHelper : IRenderHelper + internal sealed class RenderHelper { + private readonly string _defaultFontFamily; + + public RenderHelper(string defaultFontFamily = "Arial") + { + _defaultFontFamily = defaultFontFamily; + } + /// /// Minimum luma distance between Otsu's two cluster means for the split to count as real /// content - below it the image is treated as uniform. Well under a yellow-on-white logo's @@ -233,7 +243,7 @@ private SKBitmap PrepareBitmap(byte[] imageBytes, bool noCut = false, bool preRe /// /// Prepare image by converting the printed bitmap (see ) /// into an array of 1s and 0s. Public (rather than kept private) so - /// can pack the result into a job. + /// can pack the result into a job. /// /// /// See . @@ -261,7 +271,7 @@ public ImageInfo PrepareImage(byte[] imageBytes, bool noCut = false, bool preRen /// /// Renders a PNG preview of what will be printed on the label, built directly from /// the same bit array () packed by - /// : a black pixel is exactly a dot + /// CreateJob: a black pixel is exactly a dot /// that is sent to the printer as "print". Regardless of , the /// printer's first and last pixel row are never actually printed, so those two rows /// are always rendered as a distinct gray marker instead of their raw bit value, to @@ -360,15 +370,15 @@ private SKBitmap RotateBitmap(SKBitmap bitmap, float degrees) } /// How far a narrower element sits from a wider one's left edge, as a fraction of the leftover space - 0 for Left, 0.5 for Center, 1 for Right. - private float AlignFactor(LetraHelper.TextAlign align) => align switch + private float AlignFactor(TextAlign align) => align switch { - LetraHelper.TextAlign.Center => 0.5f, - LetraHelper.TextAlign.Right => 1f, + TextAlign.Center => 0.5f, + TextAlign.Right => 1f, _ => 0f }; /// Width, in millimeters, of one DIN rail mounting module (EN 50022 terminal block pitch). - public const float DinRailModuleWidthMm = 18f; + public const float DinRailModuleWidthMm = DinRailLabel.ModuleWidthMm; /// /// Feed-axis (label length) pixel pitch, in pixels per millimeter. Empirically @@ -382,7 +392,7 @@ private SKBitmap RotateBitmap(SKBitmap bitmap, float degrees) /// 18.5 mm instead of the intended 18 mm - i.e. the real pitch is 18.5/231 mm/px, so /// the correct px/mm is its reciprocal, 231/18.5 = 462/37. /// - private const float FeedAxisPixelsPerMm = 462f / 37f; + internal const float FeedAxisPixelsPerMm = 462f / 37f; /// Physical printed length, in millimeters, of a DIN rail label spanning modules. public float DinRailLengthMm(decimal modules) => (float)modules * DinRailModuleWidthMm; @@ -418,7 +428,7 @@ private int DecodeWidth(byte[] image) /// one long word that can't be split, or wrapping not being enough on its own) - callers /// scale the whole image down uniformly afterward if needed (see ), /// which is what keeps the 1:1 aspect ratio intact instead of stretching only the width. - /// Renders at (edge-to-edge, no blank margin + /// Renders at LabelTextSize.XL (edge-to-edge, no blank margin /// around the glyphs) rather than the Text tab's usual size presets - the padding ratio /// doesn't change how wide the natural rendering ends up (it scales height and width the /// same way, so it cancels out once everything is fit to the target height), but it does @@ -428,7 +438,7 @@ private int DecodeWidth(byte[] image) /// already carve out their own small gap - see ). A /// blank/whitespace-only row (used as a spacer) renders as a minimal blank image. /// - private byte[] RenderDinRailSegmentNatural(string text, string fontFamily, LetraHelper.TextStyle style, bool upperCase, LetraHelper.TextAlign align, int wrapTargetWidthPx, bool noCut, LetraHelper.TextFormatting formatting = default) + private byte[] RenderDinRailSegmentNatural(string text, string fontFamily, TextStyle style, bool upperCase, TextAlign align, int wrapTargetWidthPx, bool noCut, TextFormatting formatting = default) { int targetHeight = noCut ? 32 : 30; @@ -449,7 +459,7 @@ private byte[] RenderDinRailSegmentNatural(string text, string fontFamily, Letra } } - byte[] oneLineImage = RenderTextContentImage(text, fontFamily, LetraHelper.LabelTextSize.XL, style, upperCase, 1f, LetraHelper.TextBoxStyle.None, align, noCut, formatting); + byte[] oneLineImage = RenderTextContentImage(text, fontFamily, LabelTextSize.XL, style, upperCase, 1f, TextBoxStyle.None, align, noCut, formatting); if (!text.Contains(' ')) { return oneLineImage; @@ -474,7 +484,7 @@ private byte[] RenderDinRailSegmentNatural(string text, string fontFamily, Letra } string candidate = text.Substring(0, i) + "\n" + text.Substring(i + 1); - byte[] candidateImage = RenderTextContentImage(candidate, fontFamily, LetraHelper.LabelTextSize.XL, style, upperCase, 1f, LetraHelper.TextBoxStyle.None, align, noCut, formatting); + byte[] candidateImage = RenderTextContentImage(candidate, fontFamily, LabelTextSize.XL, style, upperCase, 1f, TextBoxStyle.None, align, noCut, formatting); int candidateWidth = DecodeWidth(candidateImage); if (candidateWidth < bestWidth) { @@ -495,7 +505,7 @@ private byte[] RenderDinRailSegmentNatural(string text, string fontFamily, Letra /// rendering pipeline, so it ignores the couple of pixels a separator line would carve /// out of the segment. /// - public float DinRailRequiredScale(string text, string fontFamily, LetraHelper.TextStyle style, bool upperCase, LetraHelper.TextAlign align, decimal modules, bool noCut = false, LetraHelper.TextFormatting formatting = default) + public float DinRailRequiredScale(string text, string fontFamily, TextStyle style, bool upperCase, TextAlign align, decimal modules, bool noCut = false, TextFormatting formatting = default) { if (string.IsNullOrWhiteSpace(text)) { @@ -517,15 +527,15 @@ public float DinRailRequiredScale(string text, string fontFamily, LetraHelper.Te /// drawn left to right into one bitmap. Each row's text is rendered at its natural, /// undistorted size (see ) and then, only if it /// doesn't already fit, scaled down - uniformly in both directions, never stretched - by - /// whatever factor calls for (see ), + /// whatever factor calls for (see DinRailSizing), /// then centered vertically and aligned horizontally () within its /// segment. When is set, a thin vertical line is printed /// at the boundary between each pair of adjacent segments, carved out of the earlier /// segment's own available width rather than added on top of it, so segment widths always /// still sum to the requested total physical length. Public (rather than kept private) so - /// can build a job from it. + /// can build a job from it. /// - public byte[] RenderDinRailRowImage(IReadOnlyList<(string Text, decimal Modules)> rows, string fontFamily, LetraHelper.TextStyle style, bool upperCase, LetraHelper.TextAlign align, LetraHelper.DinRailSizing sizing, bool showSeparators, bool noCut, LetraHelper.TextFormatting formatting = default) + public byte[] RenderDinRailRowImage(IReadOnlyList<(string Text, decimal Modules)> rows, string fontFamily, TextStyle style, bool upperCase, TextAlign align, DinRailSizing sizing, bool showSeparators, bool noCut, TextFormatting formatting = default) { int targetHeight = noCut ? 32 : 30; float alignFactor = AlignFactor(align); @@ -555,7 +565,7 @@ public byte[] RenderDinRailRowImage(IReadOnlyList<(string Text, decimal Modules) { for (int i = 0; i < rows.Count; i++) { - float scale = sizing == LetraHelper.DinRailSizing.Uniform ? uniformScale : requiredScales[i]; + float scale = sizing == DinRailSizing.Uniform ? uniformScale : requiredScales[i]; bool drawSeparatorAfter = showSeparators && i < rows.Count - 1; var segmentBitmap = new SKBitmap(segmentWidths[i], targetHeight); @@ -619,25 +629,25 @@ public byte[] RenderDinRailRowImage(IReadOnlyList<(string Text, decimal Modules) } /// - /// Renders a PNG preview of what would + /// Renders a PNG preview of what would /// print for the same arguments. See . /// /// PNG-encoded bytes of the rendered label - public byte[] PreviewDinRailRowImage(IReadOnlyList<(string Text, decimal Modules)> rows, string fontFamily, LetraHelper.TextStyle style, bool upperCase, LetraHelper.TextAlign align, LetraHelper.DinRailSizing sizing, bool showSeparators, bool noCut = false, LetraHelper.TextFormatting formatting = default) + public byte[] PreviewDinRailRowImage(IReadOnlyList<(string Text, decimal Modules)> rows, string fontFamily, TextStyle style, bool upperCase, TextAlign align, DinRailSizing sizing, bool showSeparators, bool noCut = false, TextFormatting formatting = default) { byte[] imageBytes = RenderDinRailRowImage(rows, fontFamily, style, upperCase, align, sizing, showSeparators, noCut, formatting); return PreviewImage(imageBytes, noCut, preRendered: true); } - private float GetPaddingRatio(LetraHelper.LabelTextSize size) + private float GetPaddingRatio(LabelTextSize size) { switch (size) { - case LetraHelper.LabelTextSize.XS: return 0.6f; - case LetraHelper.LabelTextSize.S: return 0.35f; - case LetraHelper.LabelTextSize.M: return 0.15f; - case LetraHelper.LabelTextSize.L: return 0.05f; - case LetraHelper.LabelTextSize.XL: return 0f; + case LabelTextSize.XS: return 0.6f; + case LabelTextSize.S: return 0.35f; + case LabelTextSize.M: return 0.15f; + case LabelTextSize.L: return 0.05f; + case LabelTextSize.XL: return 0f; default: return 0.15f; } } @@ -647,15 +657,15 @@ private float GetPaddingRatio(LetraHelper.LabelTextSize size) /// two-line case: how much of the fixed height each of the two lines gets once the /// gap between them (see ) is subtracted out. /// - private int GetTwoLineHeight(LetraHelper.LabelTextSize size) + private int GetTwoLineHeight(LabelTextSize size) { switch (size) { - case LetraHelper.LabelTextSize.XS: return 12; - case LetraHelper.LabelTextSize.S: return 13; - case LetraHelper.LabelTextSize.M: return 14; - case LetraHelper.LabelTextSize.L: return 15; - case LetraHelper.LabelTextSize.XL: return 15; + case LabelTextSize.XS: return 12; + case LabelTextSize.S: return 13; + case LabelTextSize.M: return 14; + case LabelTextSize.L: return 15; + case LabelTextSize.XL: return 15; default: return 14; } } @@ -668,14 +678,14 @@ private int GetTwoLineHeight(LetraHelper.LabelTextSize size) /// content" renderer for a Text-tab-style Compose element (see ). /// /// PNG-encoded bytes of the rendered label - public byte[] RenderTextContentImage(string text, string fontFamily, LetraHelper.LabelTextSize size, LetraHelper.TextStyle style, bool upperCase, float widthScale, LetraHelper.TextBoxStyle boxStyle, LetraHelper.TextAlign align, bool noCut, LetraHelper.TextFormatting formatting = default, LetraHelper.FrameSpacing frameSpacing = default) + public byte[] RenderTextContentImage(string text, string fontFamily, LabelTextSize size, TextStyle style, bool upperCase, float widthScale, TextBoxStyle boxStyle, TextAlign align, bool noCut, TextFormatting formatting = default, FrameSpacing frameSpacing = default) { if (upperCase) { text = text.ToUpperInvariant(); } - bool rotate90 = style == LetraHelper.TextStyle.Vertical; + bool rotate90 = style == TextStyle.Vertical; if (rotate90) { text = string.Join(Environment.NewLine, text.ToCharArray()); @@ -685,7 +695,7 @@ public byte[] RenderTextContentImage(string text, string fontFamily, LetraHelper const float renderFontSize = 96; int targetHeight = noCut ? 32 : 30; - // Bold/Italic are independently toggleable (see LetraHelper.TextFormatting) and + // Bold/Italic are independently toggleable (see TextFormatting) and // combine freely with each other and with style's Outline/Shadow/Vertical - SkiaSharp // already supports a BoldItalic weight/slant combination directly. var fontStyle = new SKFontStyle( @@ -710,13 +720,13 @@ public byte[] RenderTextContentImage(string text, string fontFamily, LetraHelper // Outline flips to Stroke-only) - a dedicated always-Fill paint keeps them solid. using (var linePaint = new SKPaint { Color = SKColors.Black, IsAntialias = false, Style = SKPaintStyle.Fill }) { - if (style == LetraHelper.TextStyle.Outline) + if (style == TextStyle.Outline) { paint.Style = SKPaintStyle.Stroke; paint.StrokeWidth = renderFontSize * 0.06f; } - float shadowOffset = style == LetraHelper.TextStyle.Shadow ? renderFontSize * 0.08f : 0f; + float shadowOffset = style == TextStyle.Shadow ? renderFontSize * 0.08f : 0f; font.GetFontMetrics(out SKFontMetrics metrics); float ascent = -metrics.Ascent; @@ -789,7 +799,7 @@ void DrawLine(SKCanvas canvas, string line, float x, float y) { int targetPerLine = GetTwoLineHeight(size); int targetGapPixels = Math.Clamp(targetHeight - 2 * targetPerLine, 0, targetHeight - 1); - if (size == LetraHelper.LabelTextSize.XL) + if (size == LabelTextSize.XL) { // XL is the size DIN Rail's auto-wrap always renders at (see // RenderDinRailSegmentNatural) - its gap felt too roomy there, so pin it @@ -900,7 +910,7 @@ void DrawLine(SKCanvas canvas, string line, float x, float y) } } - if (boxStyle != LetraHelper.TextBoxStyle.None) + if (boxStyle != TextBoxStyle.None) { // Aim for a border that's still ~1.5px wide once this raw canvas // gets scaled down to targetHeight. @@ -917,11 +927,13 @@ void DrawLine(SKCanvas canvas, string line, float x, float y) // resize below applies). float perDotY = bitmap.Height / (float)targetHeight; float perDotX = perDotY * 2f; - var scaledFrameSpacing = new LetraHelper.FrameSpacing( - (int)MathF.Round(frameSpacing.Top * perDotY), - (int)MathF.Round(frameSpacing.Bottom * perDotY), - (int)MathF.Round(frameSpacing.Left * perDotX), - (int)MathF.Round(frameSpacing.Right * perDotX)); + var scaledFrameSpacing = new FrameSpacing + { + Top = (int)MathF.Round(frameSpacing.Top * perDotY), + Bottom = (int)MathF.Round(frameSpacing.Bottom * perDotY), + Left = (int)MathF.Round(frameSpacing.Left * perDotX), + Right = (int)MathF.Round(frameSpacing.Right * perDotX) + }; DrawTextBox(canvas, boxStyle, bitmap.Width, bitmap.Height, borderStrokeWidth, verticalMargin, scaledFrameSpacing); } } @@ -968,7 +980,7 @@ void DrawLine(SKCanvas canvas, string line, float x, float y) } /// Draws a decorative border/underline around the full rendered text canvas. - private void DrawTextBox(SKCanvas canvas, LetraHelper.TextBoxStyle boxStyle, float width, float height, float strokeWidth, float verticalMargin, LetraHelper.FrameSpacing frameSpacing = default) + private void DrawTextBox(SKCanvas canvas, TextBoxStyle boxStyle, float width, float height, float strokeWidth, float verticalMargin, FrameSpacing frameSpacing = default) { using (var borderPaint = new SKPaint { Color = SKColors.Black, IsAntialias = false, Style = SKPaintStyle.Stroke, StrokeWidth = strokeWidth }) { @@ -988,35 +1000,35 @@ private void DrawTextBox(SKCanvas canvas, LetraHelper.TextBoxStyle boxStyle, flo switch (boxStyle) { - case LetraHelper.TextBoxStyle.Underline: + case TextBoxStyle.Underline: canvas.DrawLine(rect.Left, rect.Bottom, rect.Right, rect.Bottom, borderPaint); break; - case LetraHelper.TextBoxStyle.Square: + case TextBoxStyle.Square: canvas.DrawRect(rect, borderPaint); break; - case LetraHelper.TextBoxStyle.Rounded: + case TextBoxStyle.Rounded: float radius = rect.Height * 0.35f; canvas.DrawRoundRect(rect, radius, radius, borderPaint); break; - case LetraHelper.TextBoxStyle.Pointed: + case TextBoxStyle.Pointed: DrawPointedBox(canvas, borderPaint, rect); break; - case LetraHelper.TextBoxStyle.Edged: + case TextBoxStyle.Edged: DrawZigzagBox(canvas, borderPaint, rect, toothSpan: rect.Height * 0.7f, amplitude: rect.Height * 0.12f); break; - case LetraHelper.TextBoxStyle.Crocodile: + case TextBoxStyle.Crocodile: DrawZigzagBox(canvas, borderPaint, rect, toothSpan: rect.Height, amplitude: rect.Height * 0.3f); break; - case LetraHelper.TextBoxStyle.Heart: + case TextBoxStyle.Heart: DrawHeartBox(canvas, borderPaint, rect); break; - case LetraHelper.TextBoxStyle.Star: + case TextBoxStyle.Star: DrawPerimeterSpikeBox(canvas, borderPaint, rect, spikeSpan: Math.Max(rect.Height * 0.6f, 1f), amplitude: Math.Min(rect.Width, rect.Height) * 0.14f); break; - case LetraHelper.TextBoxStyle.Flower: + case TextBoxStyle.Flower: DrawPerimeterSpikeBox(canvas, borderPaint, rect, spikeSpan: Math.Max(rect.Height * 0.28f, 1f), amplitude: Math.Min(rect.Width, rect.Height) * 0.05f); break; - case LetraHelper.TextBoxStyle.Ribbon: + case TextBoxStyle.Ribbon: DrawRibbonBox(canvas, borderPaint, rect); break; } @@ -1185,22 +1197,22 @@ private void DrawRibbonBox(SKCanvas canvas, SKPaint paint, SKRect rect) } /// - /// Maps our curated to CodeGlyphX's - /// . Both and - /// map to - + /// Maps our curated BarcodeSymbology to CodeGlyphX's + /// . Both BarcodeSymbology.Ean13 and + /// BarcodeSymbology.Ean8 map to - /// CodeGlyphX's EAN encoder picks 8 vs 13 from the digit count, and /// /the encoder itself already validate that. /// - private BarcodeType ToCodeGlyphXType(LetraHelper.BarcodeSymbology symbology) => symbology switch + private BarcodeType ToCodeGlyphXType(BarcodeSymbology symbology) => symbology switch { - LetraHelper.BarcodeSymbology.Code128 => BarcodeType.Code128, - LetraHelper.BarcodeSymbology.Code39 => BarcodeType.Code39, - LetraHelper.BarcodeSymbology.Codabar => BarcodeType.Codabar, - LetraHelper.BarcodeSymbology.Itf => BarcodeType.ITF, - LetraHelper.BarcodeSymbology.Ean13 => BarcodeType.EAN, - LetraHelper.BarcodeSymbology.Ean8 => BarcodeType.EAN, - LetraHelper.BarcodeSymbology.UpcA => BarcodeType.UPCA, - LetraHelper.BarcodeSymbology.UpcE => BarcodeType.UPCE, + BarcodeSymbology.Code128 => BarcodeType.Code128, + BarcodeSymbology.Code39 => BarcodeType.Code39, + BarcodeSymbology.Codabar => BarcodeType.Codabar, + BarcodeSymbology.Itf => BarcodeType.ITF, + BarcodeSymbology.Ean13 => BarcodeType.EAN, + BarcodeSymbology.Ean8 => BarcodeType.EAN, + BarcodeSymbology.UpcA => BarcodeType.UPCA, + BarcodeSymbology.UpcE => BarcodeType.UPCE, _ => throw new ArgumentOutOfRangeException(nameof(symbology)) }; @@ -1279,7 +1291,7 @@ private bool TryExpandUpcEToUpcA(string upcE, [NotNullWhen(true)] out string? up } /// - /// Resolves to a concrete symbology based + /// Resolves BarcodeSymbology.Auto to a concrete symbology based /// on 's shape: digits-only data whose length exactly matches a /// checksum-carrying symbology (Ean13/UpcA/Ean8/UpcE, checked narrowest-length-first) and /// whose check digit validates picks that symbology; other digits-only data falls back to @@ -1287,17 +1299,17 @@ private bool TryExpandUpcEToUpcA(string upcE, [NotNullWhen(true)] out string? up /// if every character fits its charset, else Code128 - same fallback ZXing's own encoder /// would need since Code128 accepts the full ASCII range. /// - private LetraHelper.BarcodeSymbology ResolveAutoSymbology(string data) + private BarcodeSymbology ResolveAutoSymbology(string data) { if (string.IsNullOrEmpty(data)) - return LetraHelper.BarcodeSymbology.Code128; + return BarcodeSymbology.Code128; if (data.All(char.IsDigit)) { if (data.Length == 13 && HasValidMod10Checksum(data)) - return LetraHelper.BarcodeSymbology.Ean13; + return BarcodeSymbology.Ean13; if (data.Length == 12 && HasValidMod10Checksum(data)) - return LetraHelper.BarcodeSymbology.UpcA; + return BarcodeSymbology.UpcA; // UpcE checked before Ean8: an 8-digit code starting 2-9 can only be Ean8 (UpcE's // number-system digit is restricted to 0/1, enforced by TryExpandUpcEToUpcA's own // guard), so this ordering doesn't change anything for those. One starting 0/1 @@ -1308,18 +1320,18 @@ private LetraHelper.BarcodeSymbology ResolveAutoSymbology(string data) // range is by definition for a single company's internal use and not something a // generic label-printing tool would plausibly be asked to auto-detect. if (data.Length == 8 && TryExpandUpcEToUpcA(data, out var expanded) && HasValidMod10Checksum(expanded)) - return LetraHelper.BarcodeSymbology.UpcE; + return BarcodeSymbology.UpcE; if (data.Length == 8 && HasValidMod10Checksum(data)) - return LetraHelper.BarcodeSymbology.Ean8; + return BarcodeSymbology.Ean8; - return data.Length % 2 == 0 ? LetraHelper.BarcodeSymbology.Itf : LetraHelper.BarcodeSymbology.Code128; + return data.Length % 2 == 0 ? BarcodeSymbology.Itf : BarcodeSymbology.Code128; } const string code39Charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%"; if (data.All(c => code39Charset.Contains(char.ToUpperInvariant(c)))) - return LetraHelper.BarcodeSymbology.Code39; + return BarcodeSymbology.Code39; - return LetraHelper.BarcodeSymbology.Code128; + return BarcodeSymbology.Code128; } /// @@ -1330,12 +1342,12 @@ private LetraHelper.BarcodeSymbology ResolveAutoSymbology(string data) /// private const int BarcodeModuleScale = 4; - /// Fraction of the printable height given to an enabled caption (see ) - kept small by default since the bars are the actual scannable payload and the caption is just a human-readable aid; the rest of the height goes to the bars themselves. - private float GetCaptionHeightRatio(LetraHelper.CaptionSize size) => size switch + /// Fraction of the printable height given to an enabled caption (see CaptionOptions) - kept small by default since the bars are the actual scannable payload and the caption is just a human-readable aid; the rest of the height goes to the bars themselves. + private float GetCaptionHeightRatio(CaptionSize size) => size switch { - LetraHelper.CaptionSize.S => 0.15f, - LetraHelper.CaptionSize.M => 0.2f, - LetraHelper.CaptionSize.L => 0.3f, + CaptionSize.S => 0.15f, + CaptionSize.M => 0.2f, + CaptionSize.L => 0.3f, _ => 0.2f }; @@ -1348,7 +1360,7 @@ private LetraHelper.BarcodeSymbology ResolveAutoSymbology(string data) /// /// Renders at the smallest legible height, bold, in /// - the caption printed alongside the bars when - /// 's caption isn't . + /// 's caption isn't CaptionPosition.None. /// /// Final pixel height of the caption (see ). private SKBitmap RenderBarcodeNumberBitmap(string data, string fontFamily, int numberHeight) @@ -1358,7 +1370,7 @@ private SKBitmap RenderBarcodeNumberBitmap(string data, string fontFamily, int n // a whole to the small height actually reserved for it, same trick // RenderDinRailSegmentNatural uses: keeps the digits' proportions correct instead of // asking SkiaSharp's font layout to work at a height too small to be meaningful. - byte[] fullHeightPng = RenderTextContentImage(data, fontFamily, LetraHelper.LabelTextSize.XL, LetraHelper.TextStyle.Normal, upperCase: false, widthScale: 1f, LetraHelper.TextBoxStyle.None, LetraHelper.TextAlign.Center, noCut: false, formatting: new LetraHelper.TextFormatting(Bold: true)); + byte[] fullHeightPng = RenderTextContentImage(data, fontFamily, LabelTextSize.XL, TextStyle.Normal, upperCase: false, widthScale: 1f, TextBoxStyle.None, TextAlign.Center, noCut: false, formatting: new TextFormatting { Bold = true }); using (var fullHeightBitmap = SKBitmap.Decode(fullHeightPng)) { int width = Math.Max(1, (int)MathF.Round(fullHeightBitmap.Width * (numberHeight / (float)fullHeightBitmap.Height))); @@ -1379,18 +1391,18 @@ private SKBitmap RenderBarcodeNumberBitmap(string data, string fontFamily, int n /// /// isn't valid for (e.g. non-numeric EAN/UPC data, or the wrong digit count). /// PNG-encoded bytes of the rendered barcode - public byte[] RenderBarcodeContentImage(string data, LetraHelper.BarcodeSymbology symbology, LetraHelper.CaptionOptions caption, bool noCut) + public byte[] RenderBarcodeContentImage(string data, BarcodeSymbology symbology, CaptionOptions caption, bool noCut) { - LetraHelper.BarcodeSymbology resolvedSymbology = symbology == LetraHelper.BarcodeSymbology.Auto ? ResolveAutoSymbology(data) : symbology; + BarcodeSymbology resolvedSymbology = symbology == BarcodeSymbology.Auto ? ResolveAutoSymbology(data) : symbology; int targetHeight = noCut ? 32 : 30; - bool showCaption = caption.Position != LetraHelper.CaptionPosition.None; + bool showCaption = caption.Position != CaptionPosition.None; // How tall a notch to leave for the caption, once its column range is known below - // not a height the bars themselves are ever encoded/resized to (see below: bars // always render at the full targetHeight; only the width directly under the caption // gets cut down to make room for it, everywhere else stays full height). The notch // sits at the top edge for Above, the bottom edge for Below. int captionHeight = showCaption ? Math.Max(4, (int)MathF.Round(targetHeight * GetCaptionHeightRatio(caption.Size))) : 0; - int notchStartY = caption.Position == LetraHelper.CaptionPosition.Above ? 0 : targetHeight - captionHeight; + int notchStartY = caption.Position == CaptionPosition.Above ? 0 : targetHeight - captionHeight; Barcode1D barcode; try @@ -1401,13 +1413,13 @@ public byte[] RenderBarcodeContentImage(string data, LetraHelper.BarcodeSymbolog // up ourselves below via a crisp nearest-neighbor resize, matching the rest of // this file's approach to keeping bars/edges sharp, rather than letting the // library rasterize it. - barcode = resolvedSymbology == LetraHelper.BarcodeSymbology.UpcE + barcode = resolvedSymbology == BarcodeSymbology.UpcE ? EncodeUpcE(data) : BarcodeEncoder.Encode(ToCodeGlyphXType(resolvedSymbology), data); } catch (Exception ex) { - throw new ArgumentException($"'{data}' isn't valid {(symbology == LetraHelper.BarcodeSymbology.Auto ? $"{resolvedSymbology} (auto-detected)" : symbology.ToString())} barcode data: {ex.Message}", nameof(data), ex); + throw new ArgumentException($"'{data}' isn't valid {(symbology == BarcodeSymbology.Auto ? $"{resolvedSymbology} (auto-detected)" : symbology.ToString())} barcode data: {ex.Message}", nameof(data), ex); } int moduleCount = barcode.TotalModules; @@ -1448,7 +1460,7 @@ public byte[] RenderBarcodeContentImage(string data, LetraHelper.BarcodeSymbolog int gapHeight = Math.Min(BarcodeNumberGapPx, captionHeight - 1); int textHeight = captionHeight - gapHeight; - using (var numberBitmap = RenderBarcodeNumberBitmap(data, caption.FontFamily, textHeight)) + using (var numberBitmap = RenderBarcodeNumberBitmap(data, caption.FontFamily ?? _defaultFontFamily, textHeight)) { int finalWidth = Math.Max(barsWidth, numberBitmap.Width); // Whichever of the bars/caption is narrower gets lined up against the @@ -1456,7 +1468,7 @@ public byte[] RenderBarcodeContentImage(string data, LetraHelper.BarcodeSymbolog // rest of the app (e.g. DIN Rail's own AlignFactor usage). float barsX = (finalWidth - barsWidth) * AlignFactor(caption.Align); float numberX = (finalWidth - numberBitmap.Width) * AlignFactor(caption.Align); - float numberY = caption.Position == LetraHelper.CaptionPosition.Above ? notchStartY : notchStartY + gapHeight; + float numberY = caption.Position == CaptionPosition.Above ? notchStartY : notchStartY + gapHeight; using (var finalBitmap = new SKBitmap(finalWidth, targetHeight)) using (var canvas = new SKCanvas(finalBitmap)) @@ -1486,23 +1498,23 @@ public byte[] RenderBarcodeContentImage(string data, LetraHelper.BarcodeSymbolog } /// - /// Renders a PNG preview of what + /// Renders a PNG preview of what /// would print for the same arguments. See . /// /// PNG-encoded bytes of the preview image /// isn't valid for . - public byte[] PreviewImage(string data, LetraHelper.BarcodeSymbology symbology, bool noCut = false, LetraHelper.CaptionOptions caption = default) + public byte[] PreviewImage(string data, BarcodeSymbology symbology, bool noCut, CaptionOptions caption) { byte[] imageBytes = RenderBarcodeContentImage(data, symbology, caption, noCut); return PreviewImage(imageBytes, noCut, preRendered: true); } /// - /// Renders a PNG preview of what + /// Renders a PNG preview of what /// would print for the same arguments. See . /// /// PNG-encoded bytes of the preview image - public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper.LabelTextSize size = LetraHelper.LabelTextSize.M, LetraHelper.TextStyle style = LetraHelper.TextStyle.Normal, bool upperCase = false, float widthScale = 1f, LetraHelper.TextBoxStyle boxStyle = LetraHelper.TextBoxStyle.None, LetraHelper.TextAlign align = LetraHelper.TextAlign.Left, bool noCut = false, LetraHelper.TextFormatting formatting = default, LetraHelper.FrameSpacing frameSpacing = default) + public byte[] PreviewImage(string text, string fontFamily = "Arial", LabelTextSize size = LabelTextSize.M, TextStyle style = TextStyle.Normal, bool upperCase = false, float widthScale = 1f, TextBoxStyle boxStyle = TextBoxStyle.None, TextAlign align = TextAlign.Left, bool noCut = false, TextFormatting formatting = default, FrameSpacing frameSpacing = default) { byte[] imageBytes = RenderTextContentImage(text, fontFamily, size, style, upperCase, widthScale, boxStyle, align, noCut, formatting, frameSpacing); return PreviewImage(imageBytes, noCut, preRendered: true); @@ -1523,10 +1535,10 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper private const int TwoDHeadBudgetPixels = 30; /// - /// Largest QR version will encode: V3 is 29 + /// Largest QR version TwoDSymbology.QrCode will encode: V3 is 29 /// modules, the most that fit at 1 dot/module. (QR's /// 21-module minimum already rules out 2 dots/module, so every QR here is in the - /// tier.) + /// tier.) /// private const int TwoDMaxQrVersion = 3; @@ -1543,10 +1555,10 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper /// /// Encodes as the requested 2D symbology and returns its raw - /// module matrix (no quiet zone) plus a display name. + /// module matrix (no quiet zone) plus a display name. TwoDSymbology.Auto /// is resolved here - see . /// - private (BitMatrix Modules, LetraHelper.TwoDSymbology Resolved, string Name) EncodeTwoD(string data, LetraHelper.TwoDSymbology symbology) + private (BitMatrix Modules, TwoDSymbology Resolved, string Name) EncodeTwoD(string data, TwoDSymbology symbology) { if (string.IsNullOrEmpty(data)) { @@ -1555,16 +1567,16 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper return symbology switch { - LetraHelper.TwoDSymbology.Auto => EncodeTwoDAuto(data), - LetraHelper.TwoDSymbology.QrCode => EncodeQr(data), - LetraHelper.TwoDSymbology.MicroQrCode => EncodeMicroQr(data), - LetraHelper.TwoDSymbology.RectangularMicroQrCode => EncodeRmQr(data), - LetraHelper.TwoDSymbology.DataMatrix => EncodeDataMatrix(data), + TwoDSymbology.Auto => EncodeTwoDAuto(data), + TwoDSymbology.QrCode => EncodeQr(data), + TwoDSymbology.MicroQrCode => EncodeMicroQr(data), + TwoDSymbology.RectangularMicroQrCode => EncodeRmQr(data), + TwoDSymbology.DataMatrix => EncodeDataMatrix(data), _ => throw new ArgumentOutOfRangeException(nameof(symbology)) }; } - private (BitMatrix, LetraHelper.TwoDSymbology, string) EncodeQr(string data) + private (BitMatrix, TwoDSymbology, string) EncodeQr(string data) { QrCode qr; try @@ -1576,10 +1588,10 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper throw new ArgumentException($"'{data}' doesn't fit a QR code of version {TwoDMaxQrVersion} or lower (the largest that fits this printer): {ex.Message}. Try rMQR or Data Matrix instead.", nameof(data), ex); } - return (qr.Modules, LetraHelper.TwoDSymbology.QrCode, $"QR V{qr.Version}"); + return (qr.Modules, TwoDSymbology.QrCode, $"QR V{qr.Version}"); } - private (BitMatrix, LetraHelper.TwoDSymbology, string) EncodeMicroQr(string data) + private (BitMatrix, TwoDSymbology, string) EncodeMicroQr(string data) { MicroQrCode code; try @@ -1602,10 +1614,10 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper throw new ArgumentException($"'{data}' doesn't fit a Micro QR code (M1-M4): {ex.Message}. Try rMQR or Data Matrix instead.", nameof(data), ex); } - return (code.Modules, LetraHelper.TwoDSymbology.MicroQrCode, $"Micro QR M{code.Version}"); + return (code.Modules, TwoDSymbology.MicroQrCode, $"Micro QR M{code.Version}"); } - private (BitMatrix, LetraHelper.TwoDSymbology, string) EncodeRmQr(string data) + private (BitMatrix, TwoDSymbology, string) EncodeRmQr(string data) { Exception? lastError = null; foreach (int maxVersion in TwoDRmQrMaxVersionByHeightBucket) @@ -1619,7 +1631,7 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper MinimumVersion = 1, MaximumVersion = maxVersion }); - return (code.Modules, LetraHelper.TwoDSymbology.RectangularMicroQrCode, $"rMQR {code.VersionName}"); + return (code.Modules, TwoDSymbology.RectangularMicroQrCode, $"rMQR {code.VersionName}"); } catch (Exception ex) { @@ -1630,7 +1642,7 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper throw new ArgumentException($"'{data}' doesn't fit any rMQR symbol: {lastError?.Message}. Try Data Matrix, or a full QR code.", nameof(data), lastError); } - private (BitMatrix, LetraHelper.TwoDSymbology, string) EncodeDataMatrix(string data) + private (BitMatrix, TwoDSymbology, string) EncodeDataMatrix(string data) { BitMatrix matrix; try @@ -1642,29 +1654,29 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper throw new ArgumentException($"'{data}' can't be encoded as a Data Matrix: {ex.Message}", nameof(data), ex); } - return (matrix, LetraHelper.TwoDSymbology.DataMatrix, $"Data Matrix {matrix.Width}×{matrix.Height}"); + return (matrix, TwoDSymbology.DataMatrix, $"Data Matrix {matrix.Width}×{matrix.Height}"); } /// - /// Resolves : encodes + /// Resolves TwoDSymbology.Auto: encodes /// as rMQR, Micro QR and Data Matrix (never full QR - it's always in the - /// tier here) and returns whichever + /// tier here) and returns whichever /// prints on the least tape (fewest feed-axis dots) while keeping every module at least 2 /// dots wide. Ties break toward the bigger module, then toward the symbology better suited /// to narrow marking (rMQR, then Micro QR, then Data Matrix). If nothing clears the 2-dot /// bar, the data is too long - the caller has to pick a symbology explicitly to accept a /// smaller, less reliable code. /// - private (BitMatrix, LetraHelper.TwoDSymbology, string) EncodeTwoDAuto(string data) + private (BitMatrix, TwoDSymbology, string) EncodeTwoDAuto(string data) { - (Func<(BitMatrix, LetraHelper.TwoDSymbology, string)> Encode, int Preference)[] attempts = + (Func<(BitMatrix, TwoDSymbology, string)> Encode, int Preference)[] attempts = { (() => EncodeRmQr(data), 0), (() => EncodeMicroQr(data), 1), (() => EncodeDataMatrix(data), 2), }; - (BitMatrix Modules, LetraHelper.TwoDSymbology Resolved, string Name, int FeedDots, int Dots, int Preference)? best = null; + (BitMatrix Modules, TwoDSymbology Resolved, string Name, int FeedDots, int Dots, int Preference)? best = null; var errors = new List(); foreach (var (encode, preference) in attempts) @@ -1712,7 +1724,7 @@ public byte[] PreviewImage(string text, string fontFamily = "Arial", LetraHelper /// that, since feed-axis dots are half the physical size, keeping modules square. /// /// The symbol's short side needs more modules than the head axis has dots. - private LetraHelper.TwoDPlan BuildTwoDPlan(BitMatrix modules, LetraHelper.TwoDSymbology resolved, string name) + private TwoDCodePlan BuildTwoDPlan(BitMatrix modules, TwoDSymbology resolved, string name) { int shortSide = Math.Min(modules.Width, modules.Height); int longSide = Math.Max(modules.Width, modules.Height); @@ -1730,17 +1742,27 @@ private LetraHelper.TwoDPlan BuildTwoDPlan(BitMatrix modules, LetraHelper.TwoDSy // head axis resolves at half as many dots per millimeter. float moduleSizeMm = dotsPerModuleShort / (FeedAxisPixelsPerMm / 2f); - return new LetraHelper.TwoDPlan(resolved, name, shortSide, longSide, dotsPerModuleShort, dotsPerModuleLong, moduleSizeMm, dotsPerModuleShort <= 1); + return new TwoDCodePlan + { + Symbology = resolved, + SymbolName = name, + ModulesShort = shortSide, + ModulesLong = longSide, + DotsPerModuleShort = dotsPerModuleShort, + DotsPerModuleLong = dotsPerModuleLong, + ModuleSizeMm = moduleSizeMm, + MayNotScanWell = dotsPerModuleShort <= 1 + }; } /// /// Encodes and lays it out for the printer without rendering - - /// see . Meant for UI feedback (showing the chosen - /// symbol and warning about ) before + /// see . Meant for UI feedback (showing the chosen + /// symbol and warning about ) before /// committing to a print. /// /// can't be encoded as at a size that fits the printer. - public LetraHelper.TwoDPlan PlanTwoDImage(string data, LetraHelper.TwoDSymbology symbology) + public TwoDCodePlan PlanTwoDImage(string data, TwoDSymbology symbology) { var (modules, resolved, name) = EncodeTwoD(data, symbology); return BuildTwoDPlan(modules, resolved, name); @@ -1759,7 +1781,7 @@ public LetraHelper.TwoDPlan PlanTwoDImage(string data, LetraHelper.TwoDSymbology /// /// PNG-encoded bytes of the rendered symbol. /// can't be encoded as at a size that fits the printer. - public byte[] RenderTwoDContentImage(string data, LetraHelper.TwoDSymbology symbology) + public byte[] RenderTwoDContentImage(string data, TwoDSymbology symbology) { var (modules, resolved, name) = EncodeTwoD(data, symbology); var plan = BuildTwoDPlan(modules, resolved, name); @@ -1770,7 +1792,7 @@ public byte[] RenderTwoDContentImage(string data, LetraHelper.TwoDSymbology symb int dotsShort = plan.DotsPerModuleShort; int dotsLong = plan.DotsPerModuleLong; - int quietModules = resolved == LetraHelper.TwoDSymbology.QrCode ? 4 : 2; + int quietModules = resolved == TwoDSymbology.QrCode ? 4 : 2; int quietFeedPx = quietModules * dotsLong; int feedPx = longSide * dotsLong + 2 * quietFeedPx; int headOffset = (TwoDHeadBudgetPixels - shortSide * dotsShort) / 2; @@ -1807,12 +1829,12 @@ public byte[] RenderTwoDContentImage(string data, LetraHelper.TwoDSymbology symb } /// - /// Renders a PNG preview of what + /// Renders a PNG preview of what /// would print for the same arguments. See . /// /// PNG-encoded bytes of the preview image. /// can't be encoded as at a size that fits the printer. - public byte[] PreviewImage(string data, LetraHelper.TwoDSymbology symbology) + public byte[] PreviewImage(string data, TwoDSymbology symbology) { byte[] imageBytes = RenderTwoDContentImage(data, symbology); return PreviewImage(imageBytes, noCut: false, preRendered: true); @@ -1857,8 +1879,8 @@ public byte[] RenderImageContentImage(byte[] imageBytes, bool preRendered, bool /// self-padded (see 's remarks). Padding the other /// 30-tall ones up here - rather than cropping the Image element's own padding back off - /// means every element in a composed strip ends up self-contained at the printer's actual - /// wire height, so can hand the whole thing to - /// as noCut: true (the + /// wire height, so can hand the whole thing to + /// as noCut: true (the /// caller has already handled the unprintable-edge padding, exactly what that flag means) /// instead of asking for a second, redundant round of padding on top. /// @@ -1897,7 +1919,7 @@ private SKBitmap PadToHeadAxis(SKBitmap bitmap) /// generalized to any element type. Every element is padded up to the full 32-dot head /// axis first (see ) so they all line up at the same height /// regardless of which Content method produced them. Public (rather than kept private) so - /// can build a job from it. + /// can build a job from it. /// /// is empty, isn't decodable, or isn't a shape accepts. public SKBitmap ComposeElementImages(IReadOnlyList elementPngs) @@ -1945,7 +1967,7 @@ public SKBitmap ComposeElementImages(IReadOnlyList elementPngs) } /// - /// Renders a PNG preview of what would print + /// Renders a PNG preview of what would print /// for the same elements. See . /// /// PNG-encoded bytes of the preview image. diff --git a/Letra200bSharp/Resources/Strings.Designer.cs b/Letra200bSharp.200b/Resources/Strings.Designer.cs similarity index 85% rename from Letra200bSharp/Resources/Strings.Designer.cs rename to Letra200bSharp.200b/Resources/Strings.Designer.cs index c9e2486..ecfd8d9 100644 --- a/Letra200bSharp/Resources/Strings.Designer.cs +++ b/Letra200bSharp.200b/Resources/Strings.Designer.cs @@ -8,7 +8,7 @@ // //------------------------------------------------------------------------------ -namespace Letra200bSharp.Resources { +namespace Letra200bSharp.LetraTag200b.Resources { using System; @@ -22,7 +22,7 @@ namespace Letra200bSharp.Resources { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class Strings { + internal class Strings { private static global::System.Resources.ResourceManager resourceMan; @@ -36,10 +36,10 @@ internal Strings() { /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Resources.ResourceManager ResourceManager { + internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Letra200bSharp.Resources.Strings", typeof(Strings).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Letra200bSharp.LetraTag200b.Resources.Strings", typeof(Strings).Assembly); resourceMan = temp; } return resourceMan; @@ -51,7 +51,7 @@ internal Strings() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Globalization.CultureInfo Culture { + internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -63,7 +63,7 @@ internal Strings() { /// /// Looks up a localized string similar to Printing was cancelled.. /// - public static string PrintResult_StatusCancelled { + internal static string PrintResult_StatusCancelled { get { return ResourceManager.GetString("PrintResult_StatusCancelled", resourceCulture); } @@ -72,7 +72,7 @@ public static string PrintResult_StatusCancelled { /// /// Looks up a localized string similar to Printing completed.. /// - public static string PrintResult_StatusCompleted { + internal static string PrintResult_StatusCompleted { get { return ResourceManager.GetString("PrintResult_StatusCompleted", resourceCulture); } @@ -81,7 +81,7 @@ public static string PrintResult_StatusCompleted { /// /// Looks up a localized string similar to Printing completed (the printer can report this even when it didn't actually print, e.g. lid open or no cassette).. /// - public static string PrintResult_StatusCompletedMaybe { + internal static string PrintResult_StatusCompletedMaybe { get { return ResourceManager.GetString("PrintResult_StatusCompletedMaybe", resourceCulture); } @@ -90,7 +90,7 @@ public static string PrintResult_StatusCompletedMaybe { /// /// Looks up a localized string similar to Printing completed, but the battery is low - it may not print again with the same batteries.. /// - public static string PrintResult_StatusLowBatteryCompleted { + internal static string PrintResult_StatusLowBatteryCompleted { get { return ResourceManager.GetString("PrintResult_StatusLowBatteryCompleted", resourceCulture); } @@ -99,7 +99,7 @@ public static string PrintResult_StatusLowBatteryCompleted { /// /// Looks up a localized string similar to Printing failed because the battery is low.. /// - public static string PrintResult_StatusLowBatteryFailed { + internal static string PrintResult_StatusLowBatteryFailed { get { return ResourceManager.GetString("PrintResult_StatusLowBatteryFailed", resourceCulture); } @@ -108,7 +108,7 @@ public static string PrintResult_StatusLowBatteryFailed { /// /// Looks up a localized string similar to Printing failed because no cassette was inserted.. /// - public static string PrintResult_StatusNoCassette { + internal static string PrintResult_StatusNoCassette { get { return ResourceManager.GetString("PrintResult_StatusNoCassette", resourceCulture); } @@ -117,7 +117,7 @@ public static string PrintResult_StatusNoCassette { /// /// Looks up a localized string similar to Printing failed for an unknown reason.. /// - public static string PrintResult_StatusUnknownFailure { + internal static string PrintResult_StatusUnknownFailure { get { return ResourceManager.GetString("PrintResult_StatusUnknownFailure", resourceCulture); } @@ -126,7 +126,7 @@ public static string PrintResult_StatusUnknownFailure { /// /// Looks up a localized string similar to Printing failed with an unrecognized status code ({0}).. /// - public static string PrintResult_StatusUnrecognized { + internal static string PrintResult_StatusUnrecognized { get { return ResourceManager.GetString("PrintResult_StatusUnrecognized", resourceCulture); } @@ -135,7 +135,7 @@ public static string PrintResult_StatusUnrecognized { /// /// Looks up a localized string similar to The printer didn't report a result within the timeout - the label may or may not have printed.. /// - public static string PrintResult_Timeout { + internal static string PrintResult_Timeout { get { return ResourceManager.GetString("PrintResult_Timeout", resourceCulture); } diff --git a/Letra200bSharp/Resources/Strings.resx b/Letra200bSharp.200b/Resources/Strings.resx similarity index 100% rename from Letra200bSharp/Resources/Strings.resx rename to Letra200bSharp.200b/Resources/Strings.resx 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..31cbd24 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.AddLetraTag200b()); /// /// 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 e12b773..1521e8e 100644 --- a/Letra200bSharp.Avalonia/Letra200bSharp.Avalonia.csproj +++ b/Letra200bSharp.Avalonia/Letra200bSharp.Avalonia.csproj @@ -37,6 +37,6 @@ - + diff --git a/Letra200bSharp.Avalonia/Services/CompositionService.cs b/Letra200bSharp.Avalonia/Services/CompositionService.cs index 0a2b7f2..f88daaa 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,30 @@ 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 - whichever of its per-tab settings + /// is set (see ). 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) - { - // 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); - } - - if (barcode is { } b) - { - return _render.RenderBarcodeContentImage(b.Data, b.ParsedSymbology, b.ToCaption(), noCut: false); - } - - if (qr is { } q) - { - return _render.RenderTwoDContentImage(q.Data, q.ParsedSymbology); - } - - if (draw is { } d) - { - return d.Png; - } - - if (image is { } i) - { - return i.ContentPng; - } - - throw new InvalidOperationException("This element has no renderable content."); + var part = new IComposablePart?[] { text, barcode, qr, draw, image }.FirstOrDefault(p => p != null) + ?? throw new InvalidOperationException("This element has no renderable content."); + return part.ToComposedPart(); } - 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..9a8401d 100644 --- a/Letra200bSharp.Avalonia/Services/PrintHistoryService.cs +++ b/Letra200bSharp.Avalonia/Services/PrintHistoryService.cs @@ -15,6 +15,19 @@ public enum HistoryKind Compose } +/// +/// A tab's saved settings that can become one part of a Compose tab strip (see +/// ). +/// +public interface IComposablePart +{ + /// + /// These settings 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. + /// + Label ToComposedPart(); +} + /// /// Enough of a Text tab's state to restore it and let the user reprint - see . /// / are independently toggleable (post-1.5); Style @@ -39,21 +52,43 @@ public sealed record TextHistoryParams( int FrameTop = 0, int FrameBottom = 0, int FrameLeft = 0, - int FrameRight = 0) + int FrameRight = 0) : IComposablePart { - /// 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); + /// + /// 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 + }; + } - [JsonIgnore] - public LetraHelper.FrameSpacing FrameSpacing => new(FrameTop, FrameBottom, FrameLeft, FrameRight); + /// Also migrates a composition staged before independently-toggleable Bold/Italic existed - see . + Label IComposablePart.ToComposedPart() => ToLabel(edgeToEdge: false); } /// @@ -69,45 +104,57 @@ public sealed record BarcodeHistoryParams( string CaptionFontFamily = "Arial", string CaptionSize = "M", string CaptionAlign = "Center", - [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool ShowNumber = false) + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool ShowNumber = false) : IComposablePart { /// 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) + }; + + /// The label these settings describe. + public BarcodeLabel ToLabel() => new(Data, ParsedSymbology) { Caption = ToCaption(), EdgeToEdge = NoCut }; - public LetraHelper.CaptionOptions ToCaption() => new( - Enum.Parse(CaptionPosition), - CaptionFontFamily, - Enum.Parse(CaptionSize), - Enum.Parse(CaptionAlign)); + Label IComposablePart.ToComposedPart() => ToLabel(); } /// /// Enough of a 2D Code tab's state to restore it and let the user reprint - see . /// Symbology is the tab's display label (see ), not the enum name. /// -public sealed record QrHistoryParams(string Data, string Symbology) +public sealed record QrHistoryParams(string Data, string Symbology) : IComposablePart { - /// 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); + + Label IComposablePart.ToComposedPart() => ToLabel(); } /// @@ -116,16 +163,28 @@ 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) : IComposablePart +{ + /// The drawing as a label - already print-sized, at the printable head height. + public ImageLabel ToLabel() => new(Png) { PreRendered = true }; + + Label IComposablePart.ToComposedPart() => ToLabel(); +} /// /// 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) : IComposablePart +{ + /// The stored content as a label, printed pixel-exact. + public ImageLabel ToLabel() => new(ContentPng) { PreRendered = true }; + + Label IComposablePart.ToComposedPart() => ToLabel(); +} /// One row of a DIN Rail strip - see . public sealed record DinRailRowParams(string Text, decimal Modules); @@ -148,13 +207,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 +237,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/AboutTabViewModel.cs b/Letra200bSharp.Avalonia/ViewModels/AboutTabViewModel.cs index 0c46c94..4c8b505 100644 --- a/Letra200bSharp.Avalonia/ViewModels/AboutTabViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/AboutTabViewModel.cs @@ -24,7 +24,7 @@ public partial class AboutTabViewModel : ViewModelBase public string AppTagline => Strings.AboutTab_Tagline; /// - /// The build's full version including any pre-release suffix (e.g. "1.5.0-pr.12.34" for a + /// The build's full version including any pre-release suffix (e.g. "2.0.0-pr.12.34" for a /// pull request pre-release), or "dev" if it was built without one. /// public string AppVersion { get; } = FormatVersion(); 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 317bf02..0789ce1 100644 --- a/Letra200bSharp.Avalonia/ViewModels/MainViewModel.cs +++ b/Letra200bSharp.Avalonia/ViewModels/MainViewModel.cs @@ -1,10 +1,10 @@ using System.Collections.ObjectModel; 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 CascadiaUI.Toasts; namespace Letra200bSharp.Avalonia.ViewModels; @@ -22,13 +22,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; } @@ -46,36 +46,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; } @@ -89,16 +90,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.AddLetraTag200b()); + _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(); @@ -107,12 +110,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; } @@ -144,13 +147,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)) @@ -170,7 +173,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 1ffe16f..fbe8aad 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 2049735..44f96ed 100644 --- a/Letra200bSharp.Avalonia/Views/ComposeTabView.axaml +++ b/Letra200bSharp.Avalonia/Views/ComposeTabView.axaml @@ -47,7 +47,7 @@