From bc55c4649b42409c6cbd9d8d77e0a3bf4c0e4583 Mon Sep 17 00:00:00 2001 From: TheXamlGuy Date: Fri, 26 Apr 2024 23:05:36 +0100 Subject: [PATCH] tidy --- .../ClassicDesktopStyleApplicationHandler.cs | 2 +- Toolkit.Avalonia/ContentControlHandler.cs | 4 +- Toolkit.Avalonia/ContentDialogHandler.cs | 8 +- Toolkit.Avalonia/ContentTemplate.cs | 4 +- Toolkit.Avalonia/FrameHandler.cs | 22 +- Toolkit.Avalonia/NavigationContext.cs | 3 +- Toolkit.Avalonia/NavigationPageFactory.cs | 4 +- .../SingleViewApplicationHandler.cs | 2 +- Toolkit.Foundation/AsyncLock.cs | 6 +- Toolkit.Foundation/CommandViewModel.cs | 4 +- Toolkit.Foundation/ComponentBuilder.cs | 6 +- Toolkit.Foundation/ComponentConfiguration.cs | 1 - .../ComponentConfigurationViewModel.cs | 6 +- Toolkit.Foundation/ComponentHost.cs | 3 +- Toolkit.Foundation/ComponentHostCollection.cs | 2 +- Toolkit.Foundation/ComponentInitializer.cs | 17 +- Toolkit.Foundation/ComponentScope.cs | 2 +- .../ComponentScopeCollection.cs | 4 +- .../ConfigurationChangedHandler.cs | 1 - Toolkit.Foundation/ConfigurationDescriptor.cs | 2 +- Toolkit.Foundation/ConfigurationFactory.cs | 4 +- Toolkit.Foundation/ConfigurationFile.cs | 4 +- .../ConfigurationInitializer.cs | 4 +- Toolkit.Foundation/ConfigurationMonitor.cs | 2 +- Toolkit.Foundation/ConfigurationReader.cs | 2 +- Toolkit.Foundation/ConfigurationSource.cs | 2 +- Toolkit.Foundation/ConfigurationValue.cs | 4 +- .../ContentTemplateDescriptor.cs | 2 +- .../ContentTemplateDescriptorProvider.cs | 2 +- Toolkit.Foundation/Create.cs | 5 +- Toolkit.Foundation/DefaultBuilder.cs | 8 +- .../DictionaryStringObjectJsonConverter.cs | 15 +- Toolkit.Foundation/Disposer.cs | 16 +- Toolkit.Foundation/HandlerWrapper.cs | 4 +- Toolkit.Foundation/ICache.cs | 6 +- .../IComponentConfigurationViewModel.cs | 3 +- Toolkit.Foundation/IComponentHost.cs | 2 +- .../IComponentScopeCollection.cs | 5 +- Toolkit.Foundation/IComponentScopeProvider.cs | 3 +- Toolkit.Foundation/IConfigurationChanged.cs | 2 +- .../IConfigurationDescriptor.cs | 2 +- Toolkit.Foundation/IConfigurationFactory.cs | 4 +- Toolkit.Foundation/IConfigurationFile.cs | 2 +- .../IConfigurationInitializer.cs | 2 +- Toolkit.Foundation/IConfigurationMonitor.cs | 5 +- Toolkit.Foundation/IConfigurationReader.cs | 2 +- Toolkit.Foundation/IConfigurationSource.cs | 2 +- Toolkit.Foundation/IContentTemplate.cs | 1 - .../IContentTemplateDescriptorProvider.cs | 2 +- Toolkit.Foundation/IDeactivating.cs | 2 +- Toolkit.Foundation/IDispatcher.cs | 2 +- Toolkit.Foundation/IDisposer.cs | 4 +- Toolkit.Foundation/IFactory.cs | 3 +- Toolkit.Foundation/IHostBuilderExtensions.cs | 6 +- Toolkit.Foundation/IMediator.cs | 16 +- Toolkit.Foundation/INavigateHandler.cs | 2 +- Toolkit.Foundation/INavigation.cs | 3 +- .../INavigationContextCollection.cs | 2 +- .../INavigationContextProvider.cs | 2 +- Toolkit.Foundation/INavigationProvider.cs | 2 +- Toolkit.Foundation/INavigationScope.cs | 5 +- .../IObservableCollectionViewModel.cs | 4 +- Toolkit.Foundation/IPrimaryConfirmation.cs | 3 +- Toolkit.Foundation/IProxyService.cs | 2 +- Toolkit.Foundation/IPublisher.cs | 3 +- Toolkit.Foundation/IRequest.cs | 6 - .../IServiceCollectionExtensions.cs | 19 +- Toolkit.Foundation/IServiceFactory.cs | 2 +- Toolkit.Foundation/IServiceScopeFactory.cs | 2 +- Toolkit.Foundation/IServiceScopeProvider.cs | 2 +- Toolkit.Foundation/ISubscriptionManager.cs | 2 +- Toolkit.Foundation/IWritableConfiguration.cs | 2 +- Toolkit.Foundation/Insert.cs | 4 +- Toolkit.Foundation/KeyAccelerator.cs | 3 +- Toolkit.Foundation/Mediator.cs | 8 +- Toolkit.Foundation/MethodInfoExtensions.cs | 2 +- Toolkit.Foundation/Navigate.cs | 10 +- Toolkit.Foundation/NavigateBack.cs | 2 +- Toolkit.Foundation/NavigateBackHandler.cs | 4 +- Toolkit.Foundation/NavigateHandler.cs | 6 +- Toolkit.Foundation/NavigatingFrom.cs | 7 - Toolkit.Foundation/Navigation.cs | 5 +- .../NavigationContextAttribute.cs | 2 +- .../NavigationContextCollection.cs | 4 +- .../NavigationContextProvider.cs | 4 +- Toolkit.Foundation/NavigationProvider.cs | 2 +- Toolkit.Foundation/NavigationScope.cs | 11 +- .../NavigationTargetAttribute.cs | 4 +- .../NotificationHandlerDelegate.cs | 2 +- .../NotificationHandlerWrapper.cs | 4 +- Toolkit.Foundation/ObjectExtensions.cs | 2 +- .../ObservableCollectionViewModel.cs | 13 +- Toolkit.Foundation/ObservableViewModel.cs | 4 +- Toolkit.Foundation/Publisher.cs | 25 +- Toolkit.Foundation/Remove.cs | 3 +- Toolkit.Foundation/Replace.cs | 3 +- Toolkit.Foundation/ServiceFactory.cs | 2 +- Toolkit.Foundation/ServiceScopeFactory.cs | 2 +- Toolkit.Foundation/ServiceScopeProvider.cs | 4 +- Toolkit.Foundation/SetupRequiredAttribute.cs | 2 +- Toolkit.Foundation/StartProcess.cs | 2 +- Toolkit.Foundation/Subscriber.cs | 6 +- Toolkit.Foundation/SubscriptionCollection.cs | 2 +- Toolkit.Foundation/SubscriptionManager.cs | 10 +- Toolkit.Foundation/TypeExtensions.cs | 2 +- Toolkit.Foundation/ValueViewModel.cs | 3 +- Toolkit.Foundation/VirtualKey.cs | 2 +- Toolkit.Foundation/WritableConfiguration.cs | 2 +- Toolkit.UI.Avalonia/AttachedBehavior.cs | 2 +- Toolkit.UI.Avalonia/ComparisonCondition.cs | 6 +- Toolkit.UI.Avalonia/ComparisonLogic.cs | 21 +- Toolkit.UI.Avalonia/ConditionAction.cs | 2 +- Toolkit.UI.Avalonia/ConditionCollection.cs | 2 +- Toolkit.UI.Avalonia/ConditionalExpression.cs | 7 +- Toolkit.UI.Avalonia/ForwardChaining.cs | 2 +- Toolkit.UI.Avalonia/ICondition.cs | 2 +- .../KeyBindingTriggerBehavior.cs | 8 +- Toolkit.UI.Avalonia/NavigateAction.cs | 8 +- Toolkit.UI.Avalonia/NavigateBackAction.cs | 2 +- Toolkit.UI.Avalonia/ParameterBinding.cs | 3 +- .../AsyncImage/AsyncImage.cs | 2 +- .../BlurBehind/BlurBehind.cs | 45 +- .../CarouselView/CarouselView.cs | 18 +- .../CarouselView/CarouselViewItem.cs | 2 +- .../FastNoiseBackgroundRenderer.cs | 16 +- .../FastNoiseRendererOptions.cs | 2 +- .../FastRendererBackground.cs | 8 +- Toolkit.UI.Controls.Avalonia/Frame/Frame.cs | 6 +- .../Helpers/ScopedBatchHelper.cs | 1 + .../NavigationView/NavigationView.cs | 4 +- .../NavigationView/NavigationViewItem.cs | 2 +- .../QrCode/Encoding/BitList.cs | 207 +++--- .../QrCode/Encoding/BitMatrix.cs | 34 +- .../QrCode/Encoding/BitMatrixBase.cs | 44 +- .../DataEncodation/CharCountIndicatorTable.cs | 80 ++- .../Encoding/DataEncodation/DataEncode.cs | 79 ++- .../QrCode/Encoding/DataEncodation/ECISet.cs | 425 ++++++------ .../DataEncodation/EightBitByteEncoder.cs | 106 ++- .../DataEncodation/EncodationStruct.cs | 16 +- .../Encoding/DataEncodation/EncoderBase.cs | 74 +-- .../InputRecognition/InputRecognise.cs | 81 ++- .../InputRecognition/ModeEncodeCheck.cs | 122 ++-- .../InputRecognition/RecognitionStruct.cs | 14 +- .../Encoding/EncodingRegion/BCHCalculator.cs | 106 +-- .../Encoding/EncodingRegion/Codeword.cs | 112 ++-- .../EncodingRegion/FormatInformation.cs | 181 +++-- .../EncodingRegion/VersionInformation.cs | 98 ++- .../Encoding/ErrorCorrection/ECGenerator.cs | 130 ++-- .../QrCode/Encoding/ErrorCorrectionLevel.cs | 10 +- .../Encoding/InputOutOfBoundaryException.cs | 16 +- .../Encoding/Masking/MaskPatternType.cs | 18 +- .../Encoding/Masking/MatrixExtensions.cs | 65 +- .../QrCode/Encoding/Masking/Pattern.cs | 12 +- .../QrCode/Encoding/Masking/Pattern0.cs | 16 +- .../QrCode/Encoding/Masking/Pattern1.cs | 16 +- .../QrCode/Encoding/Masking/Pattern2.cs | 16 +- .../QrCode/Encoding/Masking/Pattern3.cs | 16 +- .../QrCode/Encoding/Masking/Pattern4.cs | 16 +- .../QrCode/Encoding/Masking/Pattern5.cs | 16 +- .../QrCode/Encoding/Masking/Pattern6.cs | 15 +- .../QrCode/Encoding/Masking/Pattern7.cs | 16 +- .../QrCode/Encoding/Masking/PatternFactory.cs | 49 +- .../Masking/Scoring/MatrixScoreCalculator.cs | 58 +- .../Encoding/Masking/Scoring/Penalty.cs | 4 +- .../Encoding/Masking/Scoring/Penalty1.cs | 142 ++-- .../Encoding/Masking/Scoring/Penalty2.cs | 82 +-- .../Encoding/Masking/Scoring/Penalty3.cs | 252 +++---- .../Encoding/Masking/Scoring/Penalty4.cs | 48 +- .../Masking/Scoring/PenaltyFactory.cs | 41 +- .../Encoding/Masking/Scoring/PenaltyRules.cs | 10 +- .../QrCode/Encoding/MatrixPoint.cs | 24 +- .../QrCode/Encoding/MatrixRectangle.cs | 43 +- .../QrCode/Encoding/MatrixSize.cs | 26 +- .../QrCode/Encoding/MatrixStatus.cs | 8 +- .../Positioning/PositioninngPatternBuilder.cs | 16 +- .../Positioning/Stencils/AlignmentPattern.cs | 184 +++--- .../Stencils/DarkDotAtLeftBottom.cs | 20 +- .../Stencils/PatternStencilBase.cs | 38 +- .../Stencils/PositionDetectionPattern.cs | 60 +- .../Positioning/Stencils/TimingPattern.cs | 52 +- .../QrCode/Encoding/QRCodeConstantVariable.cs | 70 +- .../QrCode/Encoding/QRCodeEncode.cs | 32 +- .../QrCode/Encoding/QrCode.cs | 32 +- .../QrCode/Encoding/QrEncoder.cs | 64 +- .../Encoding/ReedSolomon/GaloisField256.cs | 186 +++--- .../ReedSolomon/GeneratorPolynomial.cs | 96 ++- .../Encoding/ReedSolomon/PolyDivideStruct.cs | 18 +- .../QrCode/Encoding/ReedSolomon/Polynomial.cs | 404 ++++++------ .../ReedSolomon/ReedSolomonEncoder.cs | 134 ++-- .../QrCode/Encoding/StateMatrix.cs | 38 +- .../QrCode/Encoding/Terminate/Terminator.cs | 122 ++-- .../QrCode/Encoding/TriStateMatrix.cs | 70 +- .../QrCode/Encoding/VersionDetail.cs | 42 +- .../Encoding/Versions/ErrorCorrectionBlock.cs | 18 +- .../Versions/ErrorCorrectionBlocks.cs | 70 +- .../QrCode/Encoding/Versions/QRCodeVersion.cs | 50 +- .../Encoding/Versions/VersionControl.cs | 211 +++--- .../Encoding/Versions/VersionControlStruct.cs | 8 +- .../QrCode/Encoding/Versions/VersionTable.cs | 616 +++++++++--------- Toolkit.UI.Controls.Avalonia/QrCode/QrCode.cs | 41 +- .../SettingsExpander/SettingsExpander.cs | 4 +- .../SpacedGrid/ISpacingDefinition.cs | 2 +- .../SpacedGrid/SpacedGrid.cs | 2 +- .../SpacedGrid/SpacingColumnDefinition.cs | 2 +- .../SpacedGrid/SpacingRowDefinition.cs | 2 +- .../Themes/ThemeResources.axaml.cs | 2 +- 206 files changed, 3106 insertions(+), 3204 deletions(-) delete mode 100644 Toolkit.Foundation/IRequest.cs delete mode 100644 Toolkit.Foundation/NavigatingFrom.cs diff --git a/Toolkit.Avalonia/ClassicDesktopStyleApplicationHandler.cs b/Toolkit.Avalonia/ClassicDesktopStyleApplicationHandler.cs index 42d67c0..94d3087 100644 --- a/Toolkit.Avalonia/ClassicDesktopStyleApplicationHandler.cs +++ b/Toolkit.Avalonia/ClassicDesktopStyleApplicationHandler.cs @@ -11,7 +11,7 @@ public class ClassicDesktopStyleApplicationHandler(INavigationContext navigation public Task Handle(Navigate args, CancellationToken cancellationToken = default) { - if (Application.Current?.ApplicationLifetime is + if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifeTime) { if (args.Template is Window window) diff --git a/Toolkit.Avalonia/ContentControlHandler.cs b/Toolkit.Avalonia/ContentControlHandler.cs index f159b64..3905680 100644 --- a/Toolkit.Avalonia/ContentControlHandler.cs +++ b/Toolkit.Avalonia/ContentControlHandler.cs @@ -4,7 +4,7 @@ using Toolkit.Foundation; namespace Toolkit.Avalonia; -public class ContentControlHandler(INavigationContext navigationContext) : +public class ContentControlHandler(INavigationContext navigationContext) : INavigateHandler { public async Task Handle(Navigate args, @@ -57,4 +57,4 @@ public class ContentControlHandler(INavigationContext navigationContext) : } } } -} +} \ No newline at end of file diff --git a/Toolkit.Avalonia/ContentDialogHandler.cs b/Toolkit.Avalonia/ContentDialogHandler.cs index 33394ae..18c20d8 100644 --- a/Toolkit.Avalonia/ContentDialogHandler.cs +++ b/Toolkit.Avalonia/ContentDialogHandler.cs @@ -3,7 +3,7 @@ using Toolkit.UI.Controls.Avalonia; namespace Toolkit.Avalonia; -public class ContentDialogHandler(IDispatcher dispatcher) : +public class ContentDialogHandler(IDispatcher dispatcher) : INavigateHandler { public async Task Handle(Navigate args, @@ -50,7 +50,7 @@ public class ContentDialogHandler(IDispatcher dispatcher) : async void HandleClosing(FluentAvalonia.UI.Controls.ContentDialog sender, FluentAvalonia.UI.Controls.ContentDialogClosingEventArgs args) { - if (args.Result == FluentAvalonia.UI.Controls.ContentDialogResult.Primary || + if (args.Result == FluentAvalonia.UI.Controls.ContentDialogResult.Primary || args.Result == FluentAvalonia.UI.Controls.ContentDialogResult.Secondary) { contentDialog.Closing -= HandleClosing; @@ -93,12 +93,12 @@ public class ContentDialogHandler(IDispatcher dispatcher) : } if (content is IActivated activated) - { + { await activated.Activated(); } } } - + contentDialog.Opened += HandleOpened; contentDialog.Closing += HandleClosing; contentDialog.PrimaryButtonClick += HandlePrimaryButtonClick; diff --git a/Toolkit.Avalonia/ContentTemplate.cs b/Toolkit.Avalonia/ContentTemplate.cs index 95b753c..5a02417 100644 --- a/Toolkit.Avalonia/ContentTemplate.cs +++ b/Toolkit.Avalonia/ContentTemplate.cs @@ -54,7 +54,7 @@ public class ContentTemplate : control.Loaded += HandleLoaded; control.Unloaded += HandleUnloaded; - + viewModelContentBinder?.Set(control); return control; @@ -67,4 +67,4 @@ public class ContentTemplate : } public bool Match(object? data) => true; -} +} \ No newline at end of file diff --git a/Toolkit.Avalonia/FrameHandler.cs b/Toolkit.Avalonia/FrameHandler.cs index ffe6781..68b0bd8 100644 --- a/Toolkit.Avalonia/FrameHandler.cs +++ b/Toolkit.Avalonia/FrameHandler.cs @@ -7,7 +7,7 @@ using Toolkit.UI.Controls.Avalonia; namespace Toolkit.Avalonia; -public class FrameHandler(INavigationContext navigationContext) : +public class FrameHandler(INavigationContext navigationContext) : INavigateHandler, INavigateBackHandler { @@ -19,13 +19,13 @@ public class FrameHandler(INavigationContext navigationContext) : frame.NavigationPageFactory ??= new NavigationPageFactory(); if (args.Template is Control control) { - void NavigatingFrom(object? sender, + void NavigatingFrom(object? sender, Control control) { - async void HandleNavigatingFrom(object? _, + async void HandleNavigatingFrom(object? _, NavigatingCancelEventArgs args) { - Dictionary results = []; + Dictionary results = []; control.RemoveHandler(Frame.NavigatingFromEvent, HandleNavigatingFrom); NavigatedFrom(sender, control, () => results); @@ -71,13 +71,13 @@ public class FrameHandler(INavigationContext navigationContext) : } } } - } + } } control.AddHandler(Frame.NavigatingFromEvent, HandleNavigatingFrom); } - void NavigatedFrom(object? sender, + void NavigatedFrom(object? sender, Control control, Func> resultCallBack) { @@ -109,9 +109,9 @@ public class FrameHandler(INavigationContext navigationContext) : contract.GetGenericArguments() is { Length: 1 } arguments) { if (contentType.GetMethods().FirstOrDefault(x => - x.Name == "NavigatedToAsync" && + x.Name == "NavigatedToAsync" && x.GetCustomAttribute() - is NavigationContextAttribute attribute && results.ContainsKey(attribute.Name)) + is NavigationContextAttribute attribute && results.ContainsKey(attribute.Name)) is MethodInfo methodInfo) { if (methodInfo.GetCustomAttribute() @@ -153,10 +153,10 @@ public class FrameHandler(INavigationContext navigationContext) : control.AddHandler(Frame.NavigatedFromEvent, HandleNavigatedFrom); } - void NavigatedTo(object? sender, + void NavigatedTo(object? sender, Control control) { - async void HandleNavigatedTo(object? _, + async void HandleNavigatedTo(object? _, NavigationEventArgs __) { control.RemoveHandler(Frame.NavigatedToEvent, HandleNavigatedTo); @@ -200,4 +200,4 @@ public class FrameHandler(INavigationContext navigationContext) : return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/Toolkit.Avalonia/NavigationContext.cs b/Toolkit.Avalonia/NavigationContext.cs index e87034d..4ea4635 100644 --- a/Toolkit.Avalonia/NavigationContext.cs +++ b/Toolkit.Avalonia/NavigationContext.cs @@ -33,5 +33,4 @@ public class NavigationContext(INavigationContextCollection contexts) : } } } -} - +} \ No newline at end of file diff --git a/Toolkit.Avalonia/NavigationPageFactory.cs b/Toolkit.Avalonia/NavigationPageFactory.cs index e7d1657..ab16eb3 100644 --- a/Toolkit.Avalonia/NavigationPageFactory.cs +++ b/Toolkit.Avalonia/NavigationPageFactory.cs @@ -3,10 +3,10 @@ using FluentAvalonia.UI.Controls; namespace Toolkit.Avalonia; -public class NavigationPageFactory : +public class NavigationPageFactory : INavigationPageFactory { public Control? GetPage(Type srcType) => default; public Control GetPageFromObject(object target) => (Control)target; -} +} \ No newline at end of file diff --git a/Toolkit.Avalonia/SingleViewApplicationHandler.cs b/Toolkit.Avalonia/SingleViewApplicationHandler.cs index 530bade..5dc4d4f 100644 --- a/Toolkit.Avalonia/SingleViewApplicationHandler.cs +++ b/Toolkit.Avalonia/SingleViewApplicationHandler.cs @@ -25,4 +25,4 @@ public class SingleViewApplicationHandler(INavigationContext navigationContext) return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/AsyncLock.cs b/Toolkit.Foundation/AsyncLock.cs index 56dc549..5646f49 100644 --- a/Toolkit.Foundation/AsyncLock.cs +++ b/Toolkit.Foundation/AsyncLock.cs @@ -2,8 +2,8 @@ namespace Toolkit.Foundation; -public class AsyncLock(int initial = 1, - int maximum = 1) : +public class AsyncLock(int initial = 1, + int maximum = 1) : IDisposable { private readonly SemaphoreSlim semaphore = new(initial, maximum); @@ -20,4 +20,4 @@ public class AsyncLock(int initial = 1, await semaphore.WaitAsync(); return this; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/CommandViewModel.cs b/Toolkit.Foundation/CommandViewModel.cs index 20e3596..8727673 100644 --- a/Toolkit.Foundation/CommandViewModel.cs +++ b/Toolkit.Foundation/CommandViewModel.cs @@ -10,9 +10,9 @@ public partial class CommandViewModel(IServiceProvider provider, IDisposer disposer) : ObservableViewModel(provider, factory, mediator, publisher, subscriber, disposer) { - public IRelayCommand InvokeCommand => + public IRelayCommand InvokeCommand => new AsyncRelayCommand(InvokeAsync); - protected virtual Task InvokeAsync() => + protected virtual Task InvokeAsync() => Task.CompletedTask; } \ No newline at end of file diff --git a/Toolkit.Foundation/ComponentBuilder.cs b/Toolkit.Foundation/ComponentBuilder.cs index 35292c5..dde604e 100644 --- a/Toolkit.Foundation/ComponentBuilder.cs +++ b/Toolkit.Foundation/ComponentBuilder.cs @@ -4,7 +4,7 @@ using Microsoft.Extensions.Hosting; namespace Toolkit.Foundation; -public class ComponentBuilder : +public class ComponentBuilder : IComponentBuilder { private readonly IHostBuilder hostBuilder; @@ -65,7 +65,7 @@ public class ComponentBuilder : } public IComponentBuilder AddConfiguration(string section, - TConfiguration? configuration = null) + TConfiguration? configuration = null) where TConfiguration : ComponentConfiguration, new() { @@ -88,7 +88,7 @@ public class ComponentBuilder : return this; } - public IComponentBuilder AddConfiguration(string section) + public IComponentBuilder AddConfiguration(string section) where TConfiguration : ComponentConfiguration, new() { AddConfiguration(section, null); diff --git a/Toolkit.Foundation/ComponentConfiguration.cs b/Toolkit.Foundation/ComponentConfiguration.cs index f16b093..1bf75b0 100644 --- a/Toolkit.Foundation/ComponentConfiguration.cs +++ b/Toolkit.Foundation/ComponentConfiguration.cs @@ -2,5 +2,4 @@ public record ComponentConfiguration { - } \ No newline at end of file diff --git a/Toolkit.Foundation/ComponentConfigurationViewModel.cs b/Toolkit.Foundation/ComponentConfigurationViewModel.cs index 76c09da..b74dd71 100644 --- a/Toolkit.Foundation/ComponentConfigurationViewModel.cs +++ b/Toolkit.Foundation/ComponentConfigurationViewModel.cs @@ -8,17 +8,16 @@ public partial class ComponentConfigurationViewModel> where TConfiguration : class { - public ComponentConfigurationViewModel(IServiceProvider provider, + public ComponentConfigurationViewModel(IServiceProvider provider, IServiceFactory factory, IMediator mediator, IPublisher publisher, - ISubscriber subscriber, + ISubscriber subscriber, IDisposer disposer, THeader header, TDescription description, TAction action) : base(provider, factory, mediator, publisher, subscriber, disposer) { - } public Task Handle(Changed args, @@ -58,6 +57,7 @@ public partial class ComponentConfigurationViewModel args, CancellationToken cancellationToken = default) { diff --git a/Toolkit.Foundation/ComponentHost.cs b/Toolkit.Foundation/ComponentHost.cs index 907a694..686b6ef 100644 --- a/Toolkit.Foundation/ComponentHost.cs +++ b/Toolkit.Foundation/ComponentHost.cs @@ -15,7 +15,6 @@ public class ComponentHost(IServiceProvider services, public void Dispose() { - } public async Task StartAsync(CancellationToken cancellationToken = default) @@ -38,4 +37,4 @@ public class ComponentHost(IServiceProvider services, await service.StopAsync(cancellationToken); } } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ComponentHostCollection.cs b/Toolkit.Foundation/ComponentHostCollection.cs index c55e2d7..08f2d7f 100644 --- a/Toolkit.Foundation/ComponentHostCollection.cs +++ b/Toolkit.Foundation/ComponentHostCollection.cs @@ -18,4 +18,4 @@ public class ComponentHostCollection : IEnumerator IEnumerable.GetEnumerator() => hosts.GetEnumerator(); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ComponentInitializer.cs b/Toolkit.Foundation/ComponentInitializer.cs index be18151..3221117 100644 --- a/Toolkit.Foundation/ComponentInitializer.cs +++ b/Toolkit.Foundation/ComponentInitializer.cs @@ -1,5 +1,4 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; namespace Toolkit.Foundation; @@ -17,22 +16,22 @@ public class ComponentInitializer(IEnumerable components, IComponentBuilder builder = component.Create(); builder.AddServices(services => { - services.AddTransient(_ => + services.AddTransient(_ => provider.GetRequiredService>()); services.AddTransient(_ => provider.GetRequiredService>()); - services.AddScoped(_ => + services.AddScoped(_ => provider.GetRequiredService()); - - services.AddScoped(_ => + + services.AddScoped(_ => provider.GetRequiredService()); - services.AddScoped(_ => + services.AddScoped(_ => provider.GetRequiredService()); - services.AddTransient(_ => + services.AddTransient(_ => provider.GetRequiredService()); services.AddRange(typedServices.Services); @@ -49,4 +48,4 @@ public class ComponentInitializer(IEnumerable components, await host.StartAsync(); } } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ComponentScope.cs b/Toolkit.Foundation/ComponentScope.cs index c403c54..1c50570 100644 --- a/Toolkit.Foundation/ComponentScope.cs +++ b/Toolkit.Foundation/ComponentScope.cs @@ -1,3 +1,3 @@ namespace Toolkit.Foundation; -public record ComponentScope(string Name); +public record ComponentScope(string Name); \ No newline at end of file diff --git a/Toolkit.Foundation/ComponentScopeCollection.cs b/Toolkit.Foundation/ComponentScopeCollection.cs index b9a42a7..e9d40a2 100644 --- a/Toolkit.Foundation/ComponentScopeCollection.cs +++ b/Toolkit.Foundation/ComponentScopeCollection.cs @@ -1,4 +1,4 @@ namespace Toolkit.Foundation; -public class ComponentScopeCollection : List, - IComponentScopeCollection; +public class ComponentScopeCollection : List, + IComponentScopeCollection; \ No newline at end of file diff --git a/Toolkit.Foundation/ConfigurationChangedHandler.cs b/Toolkit.Foundation/ConfigurationChangedHandler.cs index de6d8cf..e142bcc 100644 --- a/Toolkit.Foundation/ConfigurationChangedHandler.cs +++ b/Toolkit.Foundation/ConfigurationChangedHandler.cs @@ -12,7 +12,6 @@ public class ConfigurationChangedHandler(ConfigurationVa { if (configurationValue.TryUpdate(configuration, out TValue value)) { - } } diff --git a/Toolkit.Foundation/ConfigurationDescriptor.cs b/Toolkit.Foundation/ConfigurationDescriptor.cs index 347195c..79d0079 100644 --- a/Toolkit.Foundation/ConfigurationDescriptor.cs +++ b/Toolkit.Foundation/ConfigurationDescriptor.cs @@ -9,4 +9,4 @@ public class ConfigurationDescriptor(string section, public TConfiguration Value => reader.Read(); public string Section => section; -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ConfigurationFactory.cs b/Toolkit.Foundation/ConfigurationFactory.cs index d41debd..cbf981b 100644 --- a/Toolkit.Foundation/ConfigurationFactory.cs +++ b/Toolkit.Foundation/ConfigurationFactory.cs @@ -1,9 +1,9 @@ namespace Toolkit.Foundation; public class ConfigurationFactory(Func factory) : - IConfigurationFactory + IConfigurationFactory where TConfiguration : class { public object Create() => factory.Invoke(); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ConfigurationFile.cs b/Toolkit.Foundation/ConfigurationFile.cs index 50fcd4c..c0c19d4 100644 --- a/Toolkit.Foundation/ConfigurationFile.cs +++ b/Toolkit.Foundation/ConfigurationFile.cs @@ -2,10 +2,10 @@ namespace Toolkit.Foundation; -public class ConfigurationFile(IFileInfo fileInfo) : +public class ConfigurationFile(IFileInfo fileInfo) : IConfigurationFile where TConfiguration : class { public IFileInfo FileInfo => fileInfo; -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ConfigurationInitializer.cs b/Toolkit.Foundation/ConfigurationInitializer.cs index f969c89..b7240eb 100644 --- a/Toolkit.Foundation/ConfigurationInitializer.cs +++ b/Toolkit.Foundation/ConfigurationInitializer.cs @@ -1,6 +1,6 @@ namespace Toolkit.Foundation; -public class ConfigurationInitializer(IConfigurationReader reader, +public class ConfigurationInitializer(IConfigurationReader reader, IConfigurationWriter writer, IConfigurationFactory factory, IPublisher publisher) : @@ -22,4 +22,4 @@ public class ConfigurationInitializer(IConfigurationReader(configuration)); } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ConfigurationMonitor.cs b/Toolkit.Foundation/ConfigurationMonitor.cs index cfe6228..df9b908 100644 --- a/Toolkit.Foundation/ConfigurationMonitor.cs +++ b/Toolkit.Foundation/ConfigurationMonitor.cs @@ -43,4 +43,4 @@ public class ConfigurationMonitor(IConfigurationFile(IConfigurationSource(IConfigurationFile(currentNode[segments[lastIndex]], + value = JsonSerializer.Deserialize(currentNode[segments[lastIndex]], serializerOptions ?? defaultSerializerOptions()); return true; } diff --git a/Toolkit.Foundation/ConfigurationValue.cs b/Toolkit.Foundation/ConfigurationValue.cs index 4efe3ab..2eff43f 100644 --- a/Toolkit.Foundation/ConfigurationValue.cs +++ b/Toolkit.Foundation/ConfigurationValue.cs @@ -1,12 +1,12 @@ namespace Toolkit.Foundation; public class ConfigurationValue(Func> changed) - where TValue : + where TValue : class, new() { private TValue? currentValue; - public bool TryUpdate(TConfiguration configuration, + public bool TryUpdate(TConfiguration configuration, out TValue value) { TValue newValue = new(); diff --git a/Toolkit.Foundation/ContentTemplateDescriptor.cs b/Toolkit.Foundation/ContentTemplateDescriptor.cs index 427d71e..565fd18 100644 --- a/Toolkit.Foundation/ContentTemplateDescriptor.cs +++ b/Toolkit.Foundation/ContentTemplateDescriptor.cs @@ -1,7 +1,7 @@ namespace Toolkit.Foundation; public class ContentTemplateDescriptor(object key, - Type viewModelType, + Type viewModelType, Type viewType, params object[]? parameters) : IContentTemplateDescriptor diff --git a/Toolkit.Foundation/ContentTemplateDescriptorProvider.cs b/Toolkit.Foundation/ContentTemplateDescriptorProvider.cs index fef28cb..fd30799 100644 --- a/Toolkit.Foundation/ContentTemplateDescriptorProvider.cs +++ b/Toolkit.Foundation/ContentTemplateDescriptorProvider.cs @@ -13,4 +13,4 @@ public class ContentTemplateDescriptorProvider(IEnumerable(TValue Value); @@ -8,6 +7,6 @@ public record Create public static Create As(TValue value) => new(value); - public static Create As() where TValue : new() => + public static Create As() where TValue : new() => new(new TValue()); } \ No newline at end of file diff --git a/Toolkit.Foundation/DefaultBuilder.cs b/Toolkit.Foundation/DefaultBuilder.cs index 55eb938..2d0309f 100644 --- a/Toolkit.Foundation/DefaultBuilder.cs +++ b/Toolkit.Foundation/DefaultBuilder.cs @@ -144,13 +144,13 @@ public static class Test services.AddTransient(provider => provider.GetRequiredKeyedService>(section).Value); } - }); return builder; } } -public class DefaultBuilder : + +public class DefaultBuilder : HostBuilder { public static IHostBuilder Create() @@ -166,7 +166,7 @@ public class DefaultBuilder : services.AddScoped(provider => new ServiceFactory((type, parameters) => ActivatorUtilities.CreateInstance(provider, type, parameters!))); - services.AddSingleton(); services.AddScoped(); @@ -211,4 +211,4 @@ public class DefaultBuilder : services.AddHostedService(); }); } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/DictionaryStringObjectJsonConverter.cs b/Toolkit.Foundation/DictionaryStringObjectJsonConverter.cs index 595fb6e..8ab6df9 100644 --- a/Toolkit.Foundation/DictionaryStringObjectJsonConverter.cs +++ b/Toolkit.Foundation/DictionaryStringObjectJsonConverter.cs @@ -3,15 +3,15 @@ using System.Text.Json.Serialization; namespace Toolkit.Foundation; -public class DictionaryStringObjectJsonConverter : +public class DictionaryStringObjectJsonConverter : JsonConverter> { public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Dictionary) || typeToConvert == typeof(Dictionary); - public override Dictionary Read(ref Utf8JsonReader reader, - Type typeToConvert, + public override Dictionary Read(ref Utf8JsonReader reader, + Type typeToConvert, JsonSerializerOptions options) { Dictionary dictionary = []; @@ -42,7 +42,7 @@ public class DictionaryStringObjectJsonConverter : public override void Write(Utf8JsonWriter writer, Dictionary value, - JsonSerializerOptions options) => + JsonSerializerOptions options) => JsonSerializer.Serialize(writer, (IDictionary)value, options); private object? ExtractValue(ref Utf8JsonReader reader, @@ -56,20 +56,26 @@ public class DictionaryStringObjectJsonConverter : return date; } return reader.GetString(); + case JsonTokenType.False: return false; + case JsonTokenType.True: return true; + case JsonTokenType.Null: return null; + case JsonTokenType.Number: if (reader.TryGetInt64(out var result)) { return result; } return reader.GetDecimal(); + case JsonTokenType.StartObject: return Read(ref reader, null!, options); + case JsonTokenType.StartArray: List list = []; while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) @@ -77,6 +83,7 @@ public class DictionaryStringObjectJsonConverter : list.Add(ExtractValue(ref reader, options)); } return list; + default: return default; } diff --git a/Toolkit.Foundation/Disposer.cs b/Toolkit.Foundation/Disposer.cs index 093120c..c7d03fc 100644 --- a/Toolkit.Foundation/Disposer.cs +++ b/Toolkit.Foundation/Disposer.cs @@ -1,10 +1,10 @@ -using System.Reactive.Disposables; -using System.Collections; +using System.Collections; using System.Collections.Concurrent; +using System.Reactive.Disposables; namespace Toolkit.Foundation; -public class Disposer : +public class Disposer : IDisposer { private readonly ConcurrentDictionary subjects = []; @@ -45,10 +45,10 @@ public class Disposer : } } - public TDisposable Replace(object subject, - IDisposable disposer, + public TDisposable Replace(object subject, + IDisposable disposer, TDisposable replacement) - where TDisposable : + where TDisposable : IDisposable { CompositeDisposable disposables = subjects.GetOrAdd(subject, args => new CompositeDisposable()); @@ -61,7 +61,7 @@ public class Disposer : return replacement; } - public void Remove(object subject, + public void Remove(object subject, IDisposable disposer) { CompositeDisposable disposables = subjects.GetOrAdd(subject, args => new CompositeDisposable()); @@ -78,4 +78,4 @@ public class Disposer : disposables?.Dispose(); } } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/HandlerWrapper.cs b/Toolkit.Foundation/HandlerWrapper.cs index 9cc8ae0..e1f464d 100644 --- a/Toolkit.Foundation/HandlerWrapper.cs +++ b/Toolkit.Foundation/HandlerWrapper.cs @@ -4,10 +4,10 @@ public class HandlerWrapper(IHandler h IEnumerable> pipelineBehaviours) where TRequest : class { - private readonly IEnumerable> pipelineBehaviours = + private readonly IEnumerable> pipelineBehaviours = pipelineBehaviours.Reverse(); - public async Task Handle(TRequest request, + public async Task Handle(TRequest request, CancellationToken cancellationToken) { HandlerDelegate currentHandler = handler.Handle; diff --git a/Toolkit.Foundation/ICache.cs b/Toolkit.Foundation/ICache.cs index de9420c..2143da6 100644 --- a/Toolkit.Foundation/ICache.cs +++ b/Toolkit.Foundation/ICache.cs @@ -14,10 +14,10 @@ public interface ICache : IEnumerable> where TKey : notnull - where TValue : + where TValue : notnull { - void Add(TKey key, + void Add(TKey key, TValue value); void Clear(); @@ -27,4 +27,4 @@ public interface ICache : bool Remove(TKey key); bool TryGetValue(TKey key, out TValue? value); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IComponentConfigurationViewModel.cs b/Toolkit.Foundation/IComponentConfigurationViewModel.cs index f7eb4cd..56ff184 100644 --- a/Toolkit.Foundation/IComponentConfigurationViewModel.cs +++ b/Toolkit.Foundation/IComponentConfigurationViewModel.cs @@ -2,5 +2,4 @@ public interface IComponentConfigurationViewModel { - -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IComponentHost.cs b/Toolkit.Foundation/IComponentHost.cs index 3990386..260a74c 100644 --- a/Toolkit.Foundation/IComponentHost.cs +++ b/Toolkit.Foundation/IComponentHost.cs @@ -2,7 +2,7 @@ namespace Toolkit.Foundation; -public interface IComponentHost : +public interface IComponentHost : IHost { ComponentConfiguration? Configuration { get; } diff --git a/Toolkit.Foundation/IComponentScopeCollection.cs b/Toolkit.Foundation/IComponentScopeCollection.cs index 1dc26fa..d198369 100644 --- a/Toolkit.Foundation/IComponentScopeCollection.cs +++ b/Toolkit.Foundation/IComponentScopeCollection.cs @@ -1,5 +1,4 @@ namespace Toolkit.Foundation; -public interface IComponentScopeCollection : - IList; - +public interface IComponentScopeCollection : + IList; \ No newline at end of file diff --git a/Toolkit.Foundation/IComponentScopeProvider.cs b/Toolkit.Foundation/IComponentScopeProvider.cs index 220446e..062cca8 100644 --- a/Toolkit.Foundation/IComponentScopeProvider.cs +++ b/Toolkit.Foundation/IComponentScopeProvider.cs @@ -3,5 +3,4 @@ public interface IComponentScopeProvider { ComponentScopeDescriptor? Get(string key); -} - +} \ No newline at end of file diff --git a/Toolkit.Foundation/IConfigurationChanged.cs b/Toolkit.Foundation/IConfigurationChanged.cs index f00fe22..d0f8eee 100644 --- a/Toolkit.Foundation/IConfigurationChanged.cs +++ b/Toolkit.Foundation/IConfigurationChanged.cs @@ -1,4 +1,4 @@ namespace Toolkit.Foundation; -public interface IConfigurationChanged : +public interface IConfigurationChanged : IInitializer; \ No newline at end of file diff --git a/Toolkit.Foundation/IConfigurationDescriptor.cs b/Toolkit.Foundation/IConfigurationDescriptor.cs index cad357a..ac80a0a 100644 --- a/Toolkit.Foundation/IConfigurationDescriptor.cs +++ b/Toolkit.Foundation/IConfigurationDescriptor.cs @@ -7,4 +7,4 @@ public interface IConfigurationDescriptor TConfiguration Value { get; } string Section { get; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IConfigurationFactory.cs b/Toolkit.Foundation/IConfigurationFactory.cs index 916812a..52702dd 100644 --- a/Toolkit.Foundation/IConfigurationFactory.cs +++ b/Toolkit.Foundation/IConfigurationFactory.cs @@ -1,7 +1,7 @@ namespace Toolkit.Foundation; -public interface IConfigurationFactory - where TConfiguration : +public interface IConfigurationFactory + where TConfiguration : class { object Create(); diff --git a/Toolkit.Foundation/IConfigurationFile.cs b/Toolkit.Foundation/IConfigurationFile.cs index baec244..80fb81a 100644 --- a/Toolkit.Foundation/IConfigurationFile.cs +++ b/Toolkit.Foundation/IConfigurationFile.cs @@ -7,4 +7,4 @@ public interface IConfigurationFile class { IFileInfo FileInfo { get; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IConfigurationInitializer.cs b/Toolkit.Foundation/IConfigurationInitializer.cs index 597609f..a573f89 100644 --- a/Toolkit.Foundation/IConfigurationInitializer.cs +++ b/Toolkit.Foundation/IConfigurationInitializer.cs @@ -1,6 +1,6 @@ namespace Toolkit.Foundation; -public interface IConfigurationInitializer +public interface IConfigurationInitializer where TConfiguration : class { diff --git a/Toolkit.Foundation/IConfigurationMonitor.cs b/Toolkit.Foundation/IConfigurationMonitor.cs index 3a18e99..c3aafac 100644 --- a/Toolkit.Foundation/IConfigurationMonitor.cs +++ b/Toolkit.Foundation/IConfigurationMonitor.cs @@ -1,9 +1,8 @@ - -using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Hosting; namespace Toolkit.Foundation; -public interface IConfigurationMonitor : +public interface IConfigurationMonitor : IHostedService where TConfiguration : class; \ No newline at end of file diff --git a/Toolkit.Foundation/IConfigurationReader.cs b/Toolkit.Foundation/IConfigurationReader.cs index 7e2f5e5..e703305 100644 --- a/Toolkit.Foundation/IConfigurationReader.cs +++ b/Toolkit.Foundation/IConfigurationReader.cs @@ -7,4 +7,4 @@ public interface IConfigurationReader bool TryRead(out TConfiguration? configuration); TConfiguration Read(); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IConfigurationSource.cs b/Toolkit.Foundation/IConfigurationSource.cs index 626e754..13d46f1 100644 --- a/Toolkit.Foundation/IConfigurationSource.cs +++ b/Toolkit.Foundation/IConfigurationSource.cs @@ -9,4 +9,4 @@ public interface IConfigurationSource void Set(TConfiguration value); void Set(object value); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IContentTemplate.cs b/Toolkit.Foundation/IContentTemplate.cs index 6eb73fb..b3ce145 100644 --- a/Toolkit.Foundation/IContentTemplate.cs +++ b/Toolkit.Foundation/IContentTemplate.cs @@ -2,5 +2,4 @@ public interface IContentTemplate { - } \ No newline at end of file diff --git a/Toolkit.Foundation/IContentTemplateDescriptorProvider.cs b/Toolkit.Foundation/IContentTemplateDescriptorProvider.cs index 9475494..aa0da56 100644 --- a/Toolkit.Foundation/IContentTemplateDescriptorProvider.cs +++ b/Toolkit.Foundation/IContentTemplateDescriptorProvider.cs @@ -3,4 +3,4 @@ public interface IContentTemplateDescriptorProvider { IContentTemplateDescriptor? Get(object key); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IDeactivating.cs b/Toolkit.Foundation/IDeactivating.cs index 032b5fd..0c9a25a 100644 --- a/Toolkit.Foundation/IDeactivating.cs +++ b/Toolkit.Foundation/IDeactivating.cs @@ -5,7 +5,7 @@ public interface IDeactivating Task Deactivating(); } -public interface IDeactivating +public interface IDeactivating { Task Deactivating(); } \ No newline at end of file diff --git a/Toolkit.Foundation/IDispatcher.cs b/Toolkit.Foundation/IDispatcher.cs index d85772d..7a4f6ce 100644 --- a/Toolkit.Foundation/IDispatcher.cs +++ b/Toolkit.Foundation/IDispatcher.cs @@ -3,4 +3,4 @@ public interface IDispatcher { Task InvokeAsync(Action action); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IDisposer.cs b/Toolkit.Foundation/IDisposer.cs index aff06d6..212f697 100644 --- a/Toolkit.Foundation/IDisposer.cs +++ b/Toolkit.Foundation/IDisposer.cs @@ -2,14 +2,14 @@ public interface IDisposer { - void Add(object subject, + void Add(object subject, params object[] objects); TDisposable Replace(object subject, IDisposable disposer, TDisposable replacement) where TDisposable : IDisposable; - void Remove(object subject, + void Remove(object subject, IDisposable disposer); void Dispose(object subject); diff --git a/Toolkit.Foundation/IFactory.cs b/Toolkit.Foundation/IFactory.cs index f6837e1..f17c2ed 100644 --- a/Toolkit.Foundation/IFactory.cs +++ b/Toolkit.Foundation/IFactory.cs @@ -5,8 +5,7 @@ public interface IFactory TService? Create(TParameter value); } - public interface IFactory { TService? Create(); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IHostBuilderExtensions.cs b/Toolkit.Foundation/IHostBuilderExtensions.cs index cb72ce3..bf3ed92 100644 --- a/Toolkit.Foundation/IHostBuilderExtensions.cs +++ b/Toolkit.Foundation/IHostBuilderExtensions.cs @@ -4,16 +4,16 @@ namespace Toolkit.Foundation; public static class IHostBuilderExtensions { - public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, + public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string contentRoot, bool createDirectory) { if (createDirectory) - { + { Directory.CreateDirectory(contentRoot); } hostBuilder.UseContentRoot(contentRoot); return hostBuilder; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IMediator.cs b/Toolkit.Foundation/IMediator.cs index e87d071..df84e29 100644 --- a/Toolkit.Foundation/IMediator.cs +++ b/Toolkit.Foundation/IMediator.cs @@ -1,11 +1,9 @@ -namespace Toolkit.Foundation; - -public interface IMediator + +namespace Toolkit.Foundation { - Task Handle(TRequest request, - CancellationToken cancellationToken = default) - where TRequest : notnull; - - Task Handle(object request, CancellationToken - cancellationToken = default); + public interface IMediator + { + Task Handle(object message, CancellationToken cancellationToken = default); + Task Handle(TRequest request, CancellationToken cancellationToken = default) where TRequest : notnull; + } } \ No newline at end of file diff --git a/Toolkit.Foundation/INavigateHandler.cs b/Toolkit.Foundation/INavigateHandler.cs index 199faad..0cc5571 100644 --- a/Toolkit.Foundation/INavigateHandler.cs +++ b/Toolkit.Foundation/INavigateHandler.cs @@ -4,4 +4,4 @@ public interface INavigateHandler; public interface INavigateHandler : INotificationHandler>, - INavigateHandler; + INavigateHandler; \ No newline at end of file diff --git a/Toolkit.Foundation/INavigation.cs b/Toolkit.Foundation/INavigation.cs index 4298399..3d63189 100644 --- a/Toolkit.Foundation/INavigation.cs +++ b/Toolkit.Foundation/INavigation.cs @@ -3,5 +3,4 @@ public interface INavigation { Type Type { get; set; } -} - +} \ No newline at end of file diff --git a/Toolkit.Foundation/INavigationContextCollection.cs b/Toolkit.Foundation/INavigationContextCollection.cs index e867d10..9bdae1f 100644 --- a/Toolkit.Foundation/INavigationContextCollection.cs +++ b/Toolkit.Foundation/INavigationContextCollection.cs @@ -1,4 +1,4 @@ namespace Toolkit.Foundation; public interface INavigationContextCollection : - IDictionary; + IDictionary; \ No newline at end of file diff --git a/Toolkit.Foundation/INavigationContextProvider.cs b/Toolkit.Foundation/INavigationContextProvider.cs index 08ddc03..fb44955 100644 --- a/Toolkit.Foundation/INavigationContextProvider.cs +++ b/Toolkit.Foundation/INavigationContextProvider.cs @@ -4,6 +4,6 @@ public interface INavigationContextProvider { object? Get(object key); - bool TryGet(object key, + bool TryGet(object key, out object? value); } \ No newline at end of file diff --git a/Toolkit.Foundation/INavigationProvider.cs b/Toolkit.Foundation/INavigationProvider.cs index b6255cb..227bb91 100644 --- a/Toolkit.Foundation/INavigationProvider.cs +++ b/Toolkit.Foundation/INavigationProvider.cs @@ -3,4 +3,4 @@ public interface INavigationProvider { INavigation? Get(Type type); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/INavigationScope.cs b/Toolkit.Foundation/INavigationScope.cs index 6fa029b..bdab8e8 100644 --- a/Toolkit.Foundation/INavigationScope.cs +++ b/Toolkit.Foundation/INavigationScope.cs @@ -2,9 +2,8 @@ public interface INavigationScope { - Task NavigateAsync(string route, object? sender = null, object? context = null, + Task NavigateAsync(string route, object? sender = null, object? context = null, EventHandler? navigated = null, object[]? parameters = null, CancellationToken cancellationToken = default); Task NavigateBackAsync(object? context, CancellationToken cancellationToken = default); -} - +} \ No newline at end of file diff --git a/Toolkit.Foundation/IObservableCollectionViewModel.cs b/Toolkit.Foundation/IObservableCollectionViewModel.cs index 9e12d1e..9e4de44 100644 --- a/Toolkit.Foundation/IObservableCollectionViewModel.cs +++ b/Toolkit.Foundation/IObservableCollectionViewModel.cs @@ -1,4 +1,4 @@ namespace Toolkit.Foundation; -public interface IObservableCollectionViewModel : - IObservableViewModel; +public interface IObservableCollectionViewModel : + IObservableViewModel; \ No newline at end of file diff --git a/Toolkit.Foundation/IPrimaryConfirmation.cs b/Toolkit.Foundation/IPrimaryConfirmation.cs index 975ed5c..efce945 100644 --- a/Toolkit.Foundation/IPrimaryConfirmation.cs +++ b/Toolkit.Foundation/IPrimaryConfirmation.cs @@ -8,5 +8,4 @@ public interface IPrimaryConfirmation public interface IConfirmation { Task Confirm(); -} - +} \ No newline at end of file diff --git a/Toolkit.Foundation/IProxyService.cs b/Toolkit.Foundation/IProxyService.cs index bb1747e..4689185 100644 --- a/Toolkit.Foundation/IProxyService.cs +++ b/Toolkit.Foundation/IProxyService.cs @@ -3,4 +3,4 @@ public interface IProxyService { TService Proxy { get; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IPublisher.cs b/Toolkit.Foundation/IPublisher.cs index 4f0feec..36d973a 100644 --- a/Toolkit.Foundation/IPublisher.cs +++ b/Toolkit.Foundation/IPublisher.cs @@ -19,6 +19,7 @@ public interface IPublisher object key, CancellationToken cancellationToken = default) where TMessage : notnull; + Task PublishUI(object key, CancellationToken cancellationToken = default) where TMessage : new(); @@ -42,4 +43,4 @@ public interface IPublisher where TMessage : new(); public Task Publish(object message, CancellationToken cancellationToken = default); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IRequest.cs b/Toolkit.Foundation/IRequest.cs deleted file mode 100644 index 33f891a..0000000 --- a/Toolkit.Foundation/IRequest.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Toolkit.Foundation; - -public interface IRequest : - IMessage; - -public interface IRequest : IRequest; \ No newline at end of file diff --git a/Toolkit.Foundation/IServiceCollectionExtensions.cs b/Toolkit.Foundation/IServiceCollectionExtensions.cs index 20eeebb..bee5f85 100644 --- a/Toolkit.Foundation/IServiceCollectionExtensions.cs +++ b/Toolkit.Foundation/IServiceCollectionExtensions.cs @@ -1,5 +1,4 @@ -using Microsoft.Extensions.Configuration.Json; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; @@ -29,7 +28,7 @@ public static class IServiceCollectionExtensions } public static IServiceCollection AddComponent(this IServiceCollection services) - where TComponent : class, + where TComponent : class, IComponent { services.AddTransient(); @@ -48,13 +47,13 @@ public static class IServiceCollectionExtensions return services; } - public static IServiceCollection AddConfiguration(this IServiceCollection services, + public static IServiceCollection AddConfiguration(this IServiceCollection services, string section) where TConfiguration : class, new() => services.AddConfiguration(section, "Settings.json", null); public static IServiceCollection AddConfiguration(this IServiceCollection services) - where TConfiguration : class, new() => + where TConfiguration : class, new() => services.AddConfiguration(typeof(TConfiguration).Name, "Settings.json", null); public static IServiceCollection AddConfiguration(this IServiceCollection services, @@ -85,7 +84,7 @@ public static class IServiceCollectionExtensions public static IServiceCollection AddConfiguration(this IServiceCollection services, object configuration) - where TConfiguration : class, new() => + where TConfiguration : class, new() => services.AddConfiguration(configuration.GetType().Name, "Settings.json", (TConfiguration?)configuration); @@ -130,7 +129,7 @@ public static class IServiceCollectionExtensions services.TryAddKeyedTransient>(section, (provider, key) => new ConfigurationWriter(provider.GetRequiredKeyedService>(key))); - services.TryAddKeyedTransient>(section, (provider, key) => + services.TryAddKeyedTransient>(section, (provider, key) => new ConfigurationFactory(() => defaultConfiguration ?? new TConfiguration())); services.AddTransient>(provider => @@ -147,7 +146,7 @@ public static class IServiceCollectionExtensions services.TryAddKeyedTransient>(section, (provider, key) => new ConfigurationDescriptor(section, provider.GetRequiredKeyedService>(key))); - services.AddTransient(provider => + services.AddTransient(provider => provider.GetRequiredKeyedService>(section)); services.AddTransient(provider => @@ -258,7 +257,7 @@ public static class IServiceCollectionExtensions key ??= viewModelType.Name.Replace("ViewModel", ""); - services.AddTransient(viewModelType, provider => + services.AddTransient(viewModelType, provider => provider.GetRequiredService().Create(parameters)!); services.AddTransient(viewType); @@ -268,7 +267,7 @@ public static class IServiceCollectionExtensions services.AddKeyedTransient(viewType, key); - services.AddTransient(provider => + services.AddTransient(provider => new ContentTemplateDescriptor(key, viewModelType, viewType, parameters)); return services; diff --git a/Toolkit.Foundation/IServiceFactory.cs b/Toolkit.Foundation/IServiceFactory.cs index be6aee8..c69fb20 100644 --- a/Toolkit.Foundation/IServiceFactory.cs +++ b/Toolkit.Foundation/IServiceFactory.cs @@ -5,4 +5,4 @@ public interface IServiceFactory object Create(Type type, params object?[]? parameters); TService Create(params object?[]? parameters); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IServiceScopeFactory.cs b/Toolkit.Foundation/IServiceScopeFactory.cs index dc3bae6..891139d 100644 --- a/Toolkit.Foundation/IServiceScopeFactory.cs +++ b/Toolkit.Foundation/IServiceScopeFactory.cs @@ -3,4 +3,4 @@ public interface IServiceScopeFactory { TService? Create(params object?[] parameters); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IServiceScopeProvider.cs b/Toolkit.Foundation/IServiceScopeProvider.cs index d0aa9ab..46dff06 100644 --- a/Toolkit.Foundation/IServiceScopeProvider.cs +++ b/Toolkit.Foundation/IServiceScopeProvider.cs @@ -5,4 +5,4 @@ namespace Toolkit.Foundation; public interface IServiceScopeProvider { bool TryGet(TService service, out IServiceScope? serviceScope); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ISubscriptionManager.cs b/Toolkit.Foundation/ISubscriptionManager.cs index 71177e0..c6866b8 100644 --- a/Toolkit.Foundation/ISubscriptionManager.cs +++ b/Toolkit.Foundation/ISubscriptionManager.cs @@ -7,4 +7,4 @@ public interface ISubscriptionManager void Remove(object subscriber); void Add(object subscriber); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/IWritableConfiguration.cs b/Toolkit.Foundation/IWritableConfiguration.cs index 0c537e1..6b261d1 100644 --- a/Toolkit.Foundation/IWritableConfiguration.cs +++ b/Toolkit.Foundation/IWritableConfiguration.cs @@ -5,4 +5,4 @@ public interface IWritableConfiguration class { void Write(Action updateDelegate); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/Insert.cs b/Toolkit.Foundation/Insert.cs index a5ac4d7..08f8301 100644 --- a/Toolkit.Foundation/Insert.cs +++ b/Toolkit.Foundation/Insert.cs @@ -7,6 +7,6 @@ public record Insert public static Insert As(int index, TValue value) => new(index, value); - public static Insert As(int index) where TValue : new() => + public static Insert As(int index) where TValue : new() => new(index, new TValue()); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/KeyAccelerator.cs b/Toolkit.Foundation/KeyAccelerator.cs index 0d3d045..2b7f265 100644 --- a/Toolkit.Foundation/KeyAccelerator.cs +++ b/Toolkit.Foundation/KeyAccelerator.cs @@ -1,5 +1,4 @@ namespace Toolkit.Foundation; public record KeyAccelerator(VirtualKey Key, - VirtualKey[]? Modifiers = null) : - IRequest; + VirtualKey[]? Modifiers = null); \ No newline at end of file diff --git a/Toolkit.Foundation/Mediator.cs b/Toolkit.Foundation/Mediator.cs index f6d649d..3e9d354 100644 --- a/Toolkit.Foundation/Mediator.cs +++ b/Toolkit.Foundation/Mediator.cs @@ -12,7 +12,7 @@ public class Mediator(IServiceProvider provider) : Type handlerType = typeof(HandlerWrapper<,>).MakeGenericType(request.GetType(), typeof(TResponse)); - if (provider.GetService(handlerType) + if (provider.GetService(handlerType) is object handler) { if (handlerType.GetMethod("Handle") is MethodInfo handleMethod) @@ -27,14 +27,14 @@ public class Mediator(IServiceProvider provider) : public Task Handle(object message, CancellationToken cancellationToken = default) { - if (message.GetType().GetInterface(typeof(IRequest<>).Name) is Type requestType && + if (message.GetType().GetInterface(message.GetType().Name) is Type requestType && requestType.GetGenericArguments().Length == 1) { Type responseType = requestType.GetGenericArguments()[0]; - Type handlerType = typeof(HandlerWrapper<,>).MakeGenericType(message.GetType(), + Type handlerType = typeof(HandlerWrapper<,>).MakeGenericType(message.GetType(), responseType); - if (provider.GetService(handlerType) + if (provider.GetService(handlerType) is object handler) { if (handlerType.GetMethod("Handle") is MethodInfo handleMethod) diff --git a/Toolkit.Foundation/MethodInfoExtensions.cs b/Toolkit.Foundation/MethodInfoExtensions.cs index 374a4f7..4a64a03 100644 --- a/Toolkit.Foundation/MethodInfoExtensions.cs +++ b/Toolkit.Foundation/MethodInfoExtensions.cs @@ -12,7 +12,7 @@ public static class MethodInfoExtensions } public static async Task InvokeAsync(this MethodInfo methodInfo, - object? obj, + object? obj, params object[] parameters) { await (dynamic?)methodInfo.Invoke(obj, parameters); diff --git a/Toolkit.Foundation/Navigate.cs b/Toolkit.Foundation/Navigate.cs index 9b889c2..0b2cec9 100644 --- a/Toolkit.Foundation/Navigate.cs +++ b/Toolkit.Foundation/Navigate.cs @@ -1,14 +1,14 @@ namespace Toolkit.Foundation; -public record Navigate(string Route, - object? Context = null, - string? Scope = null, +public record Navigate(string Route, + object? Context = null, + string? Scope = null, object? Sender = null, EventHandler? Navigated = null, object[]? Parameters = null); -public record Navigate(object Context, - object Template, +public record Navigate(object Context, + object Template, object Content, object? Sender = null, object[]? Parameters = null); \ No newline at end of file diff --git a/Toolkit.Foundation/NavigateBack.cs b/Toolkit.Foundation/NavigateBack.cs index 224de35..48feb09 100644 --- a/Toolkit.Foundation/NavigateBack.cs +++ b/Toolkit.Foundation/NavigateBack.cs @@ -2,4 +2,4 @@ public record NavigateBack(object? Context = null, string? Scope = null); -public record NavigateBack(object? Context); +public record NavigateBack(object? Context); \ No newline at end of file diff --git a/Toolkit.Foundation/NavigateBackHandler.cs b/Toolkit.Foundation/NavigateBackHandler.cs index 2efa23d..fdd07a3 100644 --- a/Toolkit.Foundation/NavigateBackHandler.cs +++ b/Toolkit.Foundation/NavigateBackHandler.cs @@ -17,6 +17,4 @@ public class NavigateBackHandler(IComponentScopeProvider provider) : } } } -} - - +} \ No newline at end of file diff --git a/Toolkit.Foundation/NavigateHandler.cs b/Toolkit.Foundation/NavigateHandler.cs index e91cfd3..f1a4905 100644 --- a/Toolkit.Foundation/NavigateHandler.cs +++ b/Toolkit.Foundation/NavigateHandler.cs @@ -6,10 +6,10 @@ public class NavigateHandler(ComponentScope scope, IComponentScopeProvider provider) : INotificationHandler { - public async Task Handle(Navigate args, + public async Task Handle(Navigate args, CancellationToken cancellationToken) { - if (provider.Get(args.Scope ?? scope.Name) + if (provider.Get(args.Scope ?? scope.Name) is ComponentScopeDescriptor descriptor) { if (descriptor?.Services?.GetService() is INavigationScope navigationScope) @@ -19,4 +19,4 @@ public class NavigateHandler(ComponentScope scope, } } } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/NavigatingFrom.cs b/Toolkit.Foundation/NavigatingFrom.cs deleted file mode 100644 index 8d8e611..0000000 --- a/Toolkit.Foundation/NavigatingFrom.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Toolkit.Foundation; - -public record NavigatingFrom(object Content) : - IRequest>; - -public record NavigatingTo(object Content) : - IRequest>; diff --git a/Toolkit.Foundation/Navigation.cs b/Toolkit.Foundation/Navigation.cs index 4a1c6e0..6e6835a 100644 --- a/Toolkit.Foundation/Navigation.cs +++ b/Toolkit.Foundation/Navigation.cs @@ -1,8 +1,7 @@ namespace Toolkit.Foundation; -public record Navigation : +public record Navigation : INavigation { public required Type Type { get; set; } -} - +} \ No newline at end of file diff --git a/Toolkit.Foundation/NavigationContextAttribute.cs b/Toolkit.Foundation/NavigationContextAttribute.cs index 651c12d..62a889b 100644 --- a/Toolkit.Foundation/NavigationContextAttribute.cs +++ b/Toolkit.Foundation/NavigationContextAttribute.cs @@ -9,4 +9,4 @@ public class NavigationContextAttribute : Attribute } public string Name { get; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/NavigationContextCollection.cs b/Toolkit.Foundation/NavigationContextCollection.cs index a36d908..0cdf540 100644 --- a/Toolkit.Foundation/NavigationContextCollection.cs +++ b/Toolkit.Foundation/NavigationContextCollection.cs @@ -1,4 +1,4 @@ namespace Toolkit.Foundation; -public class NavigationContextCollection : Dictionary, - INavigationContextCollection; +public class NavigationContextCollection : Dictionary, + INavigationContextCollection; \ No newline at end of file diff --git a/Toolkit.Foundation/NavigationContextProvider.cs b/Toolkit.Foundation/NavigationContextProvider.cs index 74865bb..a0173ef 100644 --- a/Toolkit.Foundation/NavigationContextProvider.cs +++ b/Toolkit.Foundation/NavigationContextProvider.cs @@ -6,7 +6,7 @@ public class NavigationContextProvider(INavigationContextCollection contexts) : public object? Get(object key) => contexts.TryGetValue(key, out object? target) ? target : default; - public bool TryGet(object name, + public bool TryGet(object name, out object? value) { if (contexts.TryGetValue(name, @@ -21,4 +21,4 @@ public class NavigationContextProvider(INavigationContextCollection contexts) : return false; } } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/NavigationProvider.cs b/Toolkit.Foundation/NavigationProvider.cs index 2135e07..8a23026 100644 --- a/Toolkit.Foundation/NavigationProvider.cs +++ b/Toolkit.Foundation/NavigationProvider.cs @@ -13,4 +13,4 @@ public class NavigationProvider(IEnumerable navigations) : return default; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/NavigationScope.cs b/Toolkit.Foundation/NavigationScope.cs index 5748090..bc8320e 100644 --- a/Toolkit.Foundation/NavigationScope.cs +++ b/Toolkit.Foundation/NavigationScope.cs @@ -7,16 +7,16 @@ public class NavigationScope(IPublisher publisher, IServiceFactory factory, INavigationProvider navigationProvider, INavigationContextProvider navigationContextProvider, - IContentTemplateDescriptorProvider contentTemplateDescriptorProvider) : + IContentTemplateDescriptorProvider contentTemplateDescriptorProvider) : INavigationScope { - public async Task NavigateAsync(string route, object? sender = null, object? context = null, + public async Task NavigateAsync(string route, object? sender = null, object? context = null, EventHandler? navigated = null, object[]? parameters = null, CancellationToken cancellationToken = default) { string[] segments = route.Split('/'); int segmentCount = segments.Length; int currentSegmentIndex = 0; - + foreach (object segment in segments) { currentSegmentIndex++; @@ -79,7 +79,7 @@ public class NavigationScope(IPublisher publisher, } } - public async Task NavigateBackAsync(object? context, + public async Task NavigateBackAsync(object? context, CancellationToken cancellationToken = default) { if (context is not null) @@ -100,5 +100,4 @@ public class NavigationScope(IPublisher publisher, } } } -} - +} \ No newline at end of file diff --git a/Toolkit.Foundation/NavigationTargetAttribute.cs b/Toolkit.Foundation/NavigationTargetAttribute.cs index c4e3f75..4529d86 100644 --- a/Toolkit.Foundation/NavigationTargetAttribute.cs +++ b/Toolkit.Foundation/NavigationTargetAttribute.cs @@ -1,8 +1,8 @@ namespace Toolkit.Foundation; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] -public class NavigationTargetAttribute(string name) : +public class NavigationTargetAttribute(string name) : Attribute { public string Name => name; -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/NotificationHandlerDelegate.cs b/Toolkit.Foundation/NotificationHandlerDelegate.cs index 01c0dea..448ac77 100644 --- a/Toolkit.Foundation/NotificationHandlerDelegate.cs +++ b/Toolkit.Foundation/NotificationHandlerDelegate.cs @@ -1,4 +1,4 @@ namespace Toolkit.Foundation; public delegate Task NotificationHandlerDelegate(TMessage message, - CancellationToken cancellationToken); + CancellationToken cancellationToken); \ No newline at end of file diff --git a/Toolkit.Foundation/NotificationHandlerWrapper.cs b/Toolkit.Foundation/NotificationHandlerWrapper.cs index 91a67c4..b6391bf 100644 --- a/Toolkit.Foundation/NotificationHandlerWrapper.cs +++ b/Toolkit.Foundation/NotificationHandlerWrapper.cs @@ -18,7 +18,7 @@ public class NotificationHandlerWrapper(INotificationHandler await behaviour.Handle(args, previousHandler, token); }; } - + await currentHandler(message, cancellationToken); } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ObjectExtensions.cs b/Toolkit.Foundation/ObjectExtensions.cs index 9cad647..1bd67f1 100644 --- a/Toolkit.Foundation/ObjectExtensions.cs +++ b/Toolkit.Foundation/ObjectExtensions.cs @@ -18,7 +18,7 @@ public static class ObjectExtensions return null; } - public static TAttribute? GetAttribute(this object obj) + public static TAttribute? GetAttribute(this object obj) where TAttribute : Attribute { Type type = obj.GetType(); diff --git a/Toolkit.Foundation/ObservableCollectionViewModel.cs b/Toolkit.Foundation/ObservableCollectionViewModel.cs index 7ef445d..569f831 100644 --- a/Toolkit.Foundation/ObservableCollectionViewModel.cs +++ b/Toolkit.Foundation/ObservableCollectionViewModel.cs @@ -5,6 +5,7 @@ using System.Collections.Specialized; using System.Reactive.Disposables; namespace Toolkit.Foundation; + public partial class ObservableCollectionViewModel : ObservableObject, IObservableCollectionViewModel, @@ -22,7 +23,7 @@ public partial class ObservableCollectionViewModel : INotificationHandler>, INotificationHandler>, INotificationHandler> - where TViewModel : + where TViewModel : notnull { private readonly ObservableCollection collection = []; @@ -113,7 +114,6 @@ public partial class ObservableCollectionViewModel : } catch (InvalidCastException) { - } this[index] = item!; @@ -172,7 +172,6 @@ public partial class ObservableCollectionViewModel : } catch (InvalidCastException) { - } Add(item!); @@ -280,7 +279,7 @@ public partial class ObservableCollectionViewModel : return Task.CompletedTask; } - public Task Handle(Replace args, + public Task Handle(Replace args, CancellationToken cancellationToken) { if (args.Value is TViewModel item) @@ -366,7 +365,7 @@ public partial class ObservableCollectionViewModel : public void RemoveAt(int index) => RemoveItem(index); - public bool Replace(int index, + public bool Replace(int index, TViewModel item) { if (index <= Count - 1) @@ -409,12 +408,12 @@ public partial class ObservableCollectionViewModel : private static bool IsCompatibleObject(object? value) => (value is TViewModel) || (value == null && default(TViewModel) == null); - private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) => + private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) => CollectionChanged?.Invoke(this, args); } public class ObservableCollectionViewModel(IServiceProvider provider, - IServiceFactory factory, + IServiceFactory factory, IMediator mediator, IPublisher publisher, ISubscriber subscriber, diff --git a/Toolkit.Foundation/ObservableViewModel.cs b/Toolkit.Foundation/ObservableViewModel.cs index 87f0ec8..60b3585 100644 --- a/Toolkit.Foundation/ObservableViewModel.cs +++ b/Toolkit.Foundation/ObservableViewModel.cs @@ -2,7 +2,7 @@ namespace Toolkit.Foundation; -public partial class ObservableViewModel : +public partial class ObservableViewModel : ObservableObject, IObservableViewModel, IInitializer, @@ -73,4 +73,4 @@ public partial class ObservableViewModel : IsInitialized = true; return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/Publisher.cs b/Toolkit.Foundation/Publisher.cs index 172608c..ac17c94 100644 --- a/Toolkit.Foundation/Publisher.cs +++ b/Toolkit.Foundation/Publisher.cs @@ -5,18 +5,18 @@ namespace Toolkit.Foundation; public class Publisher(ISubscriptionManager subscriptionManager, IServiceProvider provider, - IDispatcher dispatcher) : + IDispatcher dispatcher) : IPublisher { public Task Publish(object key, CancellationToken cancellationToken = default) - where TMessage : new() => + where TMessage : new() => Publish(new TMessage(), async args => await args(), key, cancellationToken); public Task Publish(TMessage message, CancellationToken cancellationToken = default) - where TMessage : notnull => + where TMessage : notnull => Publish(message, async args => await args(), null, cancellationToken); @@ -24,7 +24,7 @@ public class Publisher(ISubscriptionManager subscriptionManager, object key, CancellationToken cancellationToken = default) where TMessage : notnull => - Publish(message, async args => await args(), + Publish(message, async args => await args(), key, cancellationToken); public async Task Publish(object message, @@ -65,31 +65,32 @@ public class Publisher(ISubscriptionManager subscriptionManager, async args => await args(), null, cancellationToken); - public Task Publish(CancellationToken cancellationToken = default) - where TMessage : new() => + public Task Publish(CancellationToken cancellationToken = default) + where TMessage : new() => Publish(new TMessage(), async args => await args(), null, cancellationToken); public Task PublishUI(object key, CancellationToken cancellationToken = default) - where TMessage : new() => - Publish(new TMessage(), args => dispatcher.InvokeAsync(async () => await args()), + where TMessage : new() => + Publish(new TMessage(), args => dispatcher.InvokeAsync(async () => await args()), key, cancellationToken); public Task PublishUI(TMessage message, CancellationToken cancellationToken = default) - where TMessage : notnull => + where TMessage : notnull => Publish(message, args => dispatcher.InvokeAsync(async () => await args()), null, cancellationToken); public Task PublishUI(TMessage message, object key, CancellationToken cancellationToken = default) - where TMessage : notnull => + where TMessage : notnull => Publish(message, args => dispatcher.InvokeAsync(async () => await args()), key, cancellationToken); + public Task PublishUI(CancellationToken cancellationToken = default) - where TMessage : new() => + where TMessage : new() => Publish(new TMessage(), args => dispatcher.InvokeAsync(async () => await args()), null, cancellationToken); @@ -97,4 +98,4 @@ public class Publisher(ISubscriptionManager subscriptionManager, CancellationToken cancellationToken = default) => Publish(message, args => dispatcher.InvokeAsync(async () => await args()), null, cancellationToken); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/Remove.cs b/Toolkit.Foundation/Remove.cs index 4b63bd7..6cf37d8 100644 --- a/Toolkit.Foundation/Remove.cs +++ b/Toolkit.Foundation/Remove.cs @@ -1,5 +1,4 @@ - -namespace Toolkit.Foundation; +namespace Toolkit.Foundation; public record Remove(TValue Value); diff --git a/Toolkit.Foundation/Replace.cs b/Toolkit.Foundation/Replace.cs index 919c49e..b784976 100644 --- a/Toolkit.Foundation/Replace.cs +++ b/Toolkit.Foundation/Replace.cs @@ -1,5 +1,4 @@ - -namespace Toolkit.Foundation; +namespace Toolkit.Foundation; public record Replace(int Index, TValue Value); diff --git a/Toolkit.Foundation/ServiceFactory.cs b/Toolkit.Foundation/ServiceFactory.cs index 39e892e..d98b2bc 100644 --- a/Toolkit.Foundation/ServiceFactory.cs +++ b/Toolkit.Foundation/ServiceFactory.cs @@ -6,6 +6,6 @@ public class ServiceFactory(Func factory) : public TService Create(params object?[]? parameters) => (TService)factory(typeof(TService), parameters); - public object Create(Type type, params object?[]? parameters) => + public object Create(Type type, params object?[]? parameters) => factory(type, parameters); } \ No newline at end of file diff --git a/Toolkit.Foundation/ServiceScopeFactory.cs b/Toolkit.Foundation/ServiceScopeFactory.cs index c86aec1..2ea2332 100644 --- a/Toolkit.Foundation/ServiceScopeFactory.cs +++ b/Toolkit.Foundation/ServiceScopeFactory.cs @@ -2,7 +2,7 @@ namespace Toolkit.Foundation; -public class ServiceScopeFactory(IServiceScopeFactory serviceScopeFactory, +public class ServiceScopeFactory(IServiceScopeFactory serviceScopeFactory, ICache cache) : IServiceScopeFactory where TService : notnull diff --git a/Toolkit.Foundation/ServiceScopeProvider.cs b/Toolkit.Foundation/ServiceScopeProvider.cs index 11ccc9b..639db09 100644 --- a/Toolkit.Foundation/ServiceScopeProvider.cs +++ b/Toolkit.Foundation/ServiceScopeProvider.cs @@ -6,7 +6,7 @@ public class ServiceScopeProvider(ICache cach IServiceScopeProvider where TService : notnull { - public bool TryGet(TService service, + public bool TryGet(TService service, out IServiceScope? serviceScope) { if (cache.TryGetValue(service, out IServiceScope? value)) @@ -18,4 +18,4 @@ public class ServiceScopeProvider(ICache cach serviceScope = null; return false; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/SetupRequiredAttribute.cs b/Toolkit.Foundation/SetupRequiredAttribute.cs index 6f2c67d..d2f4cf5 100644 --- a/Toolkit.Foundation/SetupRequiredAttribute.cs +++ b/Toolkit.Foundation/SetupRequiredAttribute.cs @@ -4,4 +4,4 @@ public class NavigationRouteAttribute(string route) : Attribute { public string Route => route; -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/StartProcess.cs b/Toolkit.Foundation/StartProcess.cs index c2cae16..ed075a5 100644 --- a/Toolkit.Foundation/StartProcess.cs +++ b/Toolkit.Foundation/StartProcess.cs @@ -1,3 +1,3 @@ namespace Toolkit.Foundation; -public record StartProcess(string Process) : IRequest; \ No newline at end of file +public record StartProcess(string Process); \ No newline at end of file diff --git a/Toolkit.Foundation/Subscriber.cs b/Toolkit.Foundation/Subscriber.cs index 8d13d8f..83898a2 100644 --- a/Toolkit.Foundation/Subscriber.cs +++ b/Toolkit.Foundation/Subscriber.cs @@ -1,11 +1,11 @@ namespace Toolkit.Foundation; -public class Subscriber(ISubscriptionManager subscriptionManager) : +public class Subscriber(ISubscriptionManager subscriptionManager) : ISubscriber { - public void Remove(object subscriber) => + public void Remove(object subscriber) => subscriptionManager.Remove(subscriber); - public void Add(object subscriber) => + public void Add(object subscriber) => subscriptionManager.Add(subscriber); } \ No newline at end of file diff --git a/Toolkit.Foundation/SubscriptionCollection.cs b/Toolkit.Foundation/SubscriptionCollection.cs index 67cbbc4..82f4572 100644 --- a/Toolkit.Foundation/SubscriptionCollection.cs +++ b/Toolkit.Foundation/SubscriptionCollection.cs @@ -3,4 +3,4 @@ namespace Toolkit.Foundation; public class SubscriptionCollection : - ConcurrentDictionary>; + ConcurrentDictionary>; \ No newline at end of file diff --git a/Toolkit.Foundation/SubscriptionManager.cs b/Toolkit.Foundation/SubscriptionManager.cs index 2d8eae3..d6f92a5 100644 --- a/Toolkit.Foundation/SubscriptionManager.cs +++ b/Toolkit.Foundation/SubscriptionManager.cs @@ -1,13 +1,11 @@ -using System.Reflection; - -namespace Toolkit.Foundation; +namespace Toolkit.Foundation; public class SubscriptionManager(SubscriptionCollection subscriptions) : ISubscriptionManager { public IEnumerable GetHandlers(Type notificationType, object key) { - if (subscriptions.TryGetValue($"{(key is not null ? $"{key}:" : "")}{notificationType}", + if (subscriptions.TryGetValue($"{(key is not null ? $"{key}:" : "")}{notificationType}", out List? subscribers)) { foreach (WeakReference weakRef in subscribers.ToArray()) @@ -72,7 +70,7 @@ public class SubscriptionManager(SubscriptionCollection subscriptions) : : null; } - private static IEnumerable GetHandlerInterfaces(Type handlerType) => + private static IEnumerable GetHandlerInterfaces(Type handlerType) => handlerType.GetInterfaces().Where(interfaceType => interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(INotificationHandler<>)); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/TypeExtensions.cs b/Toolkit.Foundation/TypeExtensions.cs index 76ea051..791b0ae 100644 --- a/Toolkit.Foundation/TypeExtensions.cs +++ b/Toolkit.Foundation/TypeExtensions.cs @@ -14,4 +14,4 @@ public static class TypeExtensions return null; } -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/ValueViewModel.cs b/Toolkit.Foundation/ValueViewModel.cs index a43ba96..aed8932 100644 --- a/Toolkit.Foundation/ValueViewModel.cs +++ b/Toolkit.Foundation/ValueViewModel.cs @@ -15,8 +15,7 @@ public partial class ValueViewModel(IServiceProvider provider, protected virtual void OnChanged(TValue? value) { - } partial void OnValueChanged(TValue? value) => OnChanged(value); -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/VirtualKey.cs b/Toolkit.Foundation/VirtualKey.cs index 67ca644..d02ae56 100644 --- a/Toolkit.Foundation/VirtualKey.cs +++ b/Toolkit.Foundation/VirtualKey.cs @@ -172,4 +172,4 @@ public enum VirtualKey GamepadRightThumbstickDown = 216, GamepadRightThumbstickRight = 217, GamepadRightThumbstickLeft = 218 -} +} \ No newline at end of file diff --git a/Toolkit.Foundation/WritableConfiguration.cs b/Toolkit.Foundation/WritableConfiguration.cs index 4f1f4f1..11f5727 100644 --- a/Toolkit.Foundation/WritableConfiguration.cs +++ b/Toolkit.Foundation/WritableConfiguration.cs @@ -6,4 +6,4 @@ public class WritableConfiguration(IConfigurationWriter updateDelegate) => writer.Write(updateDelegate); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/AttachedBehavior.cs b/Toolkit.UI.Avalonia/AttachedBehavior.cs index eae5e7c..d9d61ae 100644 --- a/Toolkit.UI.Avalonia/AttachedBehavior.cs +++ b/Toolkit.UI.Avalonia/AttachedBehavior.cs @@ -9,4 +9,4 @@ public class AttachedBehavior : Trigger Interaction.ExecuteActions(AssociatedObject, Actions, null); base.OnAttachedToVisualTree(); } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/ComparisonCondition.cs b/Toolkit.UI.Avalonia/ComparisonCondition.cs index bde4777..83e271c 100644 --- a/Toolkit.UI.Avalonia/ComparisonCondition.cs +++ b/Toolkit.UI.Avalonia/ComparisonCondition.cs @@ -3,8 +3,8 @@ using Avalonia.Xaml.Interactivity; namespace Toolkit.UI.Avalonia; -public class ComparisonCondition : - AvaloniaObject, +public class ComparisonCondition : + AvaloniaObject, ICondition { public static readonly StyledProperty LeftOperandProperty = @@ -36,4 +36,4 @@ public class ComparisonCondition : public bool Evaluate() => ComparisonLogic.Evaluate(LeftOperand, Operator, RightOperand); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/ComparisonLogic.cs b/Toolkit.UI.Avalonia/ComparisonLogic.cs index 96415a3..2e1f281 100644 --- a/Toolkit.UI.Avalonia/ComparisonLogic.cs +++ b/Toolkit.UI.Avalonia/ComparisonLogic.cs @@ -6,8 +6,8 @@ namespace Toolkit.UI.Avalonia; internal static class ComparisonLogic { - internal static bool Evaluate(object leftOperand, - ComparisonConditionType operatorType, + internal static bool Evaluate(object leftOperand, + ComparisonConditionType operatorType, object? rightOperand) { bool result = false; @@ -17,14 +17,13 @@ internal static class ComparisonLogic Type leftType = leftOperand.GetType(); if (rightOperand != null) - { + { TypeConverter typeConverter = TypeDescriptor.GetConverter(leftType); rightOperand = typeConverter.ConvertFrom(rightOperand); } } - - if (leftOperand is IComparable leftComparableOperand && + if (leftOperand is IComparable leftComparableOperand && rightOperand is IComparable rightComparableOperand) { return EvaluateComparable(leftComparableOperand, operatorType, rightComparableOperand); @@ -35,6 +34,7 @@ internal static class ComparisonLogic case ComparisonConditionType.Equal: result = Equals(leftOperand, rightOperand); break; + case ComparisonConditionType.NotEqual: result = !Equals(leftOperand, rightOperand); break; @@ -43,7 +43,7 @@ internal static class ComparisonLogic } private static bool EvaluateComparable(IComparable leftOperand, - ComparisonConditionType operatorType, + ComparisonConditionType operatorType, IComparable rightOperand) { object? convertedOperand = null; @@ -54,11 +54,9 @@ internal static class ComparisonLogic } catch (FormatException) { - } catch (InvalidCastException) { - } if (convertedOperand == null) @@ -74,18 +72,23 @@ internal static class ComparisonLogic case ComparisonConditionType.Equal: result = comparison == 0; break; + case ComparisonConditionType.GreaterThan: result = comparison > 0; break; + case ComparisonConditionType.GreaterThanOrEqual: result = comparison >= 0; break; + case ComparisonConditionType.LessThan: result = comparison < 0; break; + case ComparisonConditionType.LessThanOrEqual: result = comparison <= 0; break; + case ComparisonConditionType.NotEqual: result = comparison != 0; break; @@ -93,4 +96,4 @@ internal static class ComparisonLogic return result; } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/ConditionAction.cs b/Toolkit.UI.Avalonia/ConditionAction.cs index 29a25a1..23cf491 100644 --- a/Toolkit.UI.Avalonia/ConditionAction.cs +++ b/Toolkit.UI.Avalonia/ConditionAction.cs @@ -4,7 +4,7 @@ using Avalonia.Xaml.Interactivity; namespace Toolkit.UI.Avalonia; -public class ConditionAction : +public class ConditionAction : AvaloniaObject, IAction { diff --git a/Toolkit.UI.Avalonia/ConditionCollection.cs b/Toolkit.UI.Avalonia/ConditionCollection.cs index 36f0c69..d8bee8c 100644 --- a/Toolkit.UI.Avalonia/ConditionCollection.cs +++ b/Toolkit.UI.Avalonia/ConditionCollection.cs @@ -5,4 +5,4 @@ namespace Toolkit.UI.Avalonia; public class ConditionCollection : ObservableCollection { -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/ConditionalExpression.cs b/Toolkit.UI.Avalonia/ConditionalExpression.cs index 8b6d28d..14c35ab 100644 --- a/Toolkit.UI.Avalonia/ConditionalExpression.cs +++ b/Toolkit.UI.Avalonia/ConditionalExpression.cs @@ -1,10 +1,9 @@ using Avalonia; using Avalonia.Metadata; -using Toolkit.UI.Avalonia; namespace Toolkit.UI.Avalonia; -public class ConditionalExpression : +public class ConditionalExpression : AvaloniaObject, ICondition { @@ -18,7 +17,7 @@ public class ConditionalExpression : SetValue(ConditionsProperty, []); [Content] - public ConditionCollection Conditions => + public ConditionCollection Conditions => GetValue(ConditionsProperty); public ForwardChaining ForwardChaining @@ -47,4 +46,4 @@ public class ConditionalExpression : return result; } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/ForwardChaining.cs b/Toolkit.UI.Avalonia/ForwardChaining.cs index 7dac9ee..d716d8b 100644 --- a/Toolkit.UI.Avalonia/ForwardChaining.cs +++ b/Toolkit.UI.Avalonia/ForwardChaining.cs @@ -4,4 +4,4 @@ public enum ForwardChaining { And, Or -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/ICondition.cs b/Toolkit.UI.Avalonia/ICondition.cs index 5f95e0b..f64733a 100644 --- a/Toolkit.UI.Avalonia/ICondition.cs +++ b/Toolkit.UI.Avalonia/ICondition.cs @@ -3,4 +3,4 @@ public interface ICondition { bool Evaluate(); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/KeyBindingTriggerBehavior.cs b/Toolkit.UI.Avalonia/KeyBindingTriggerBehavior.cs index 68c54c9..50c0775 100644 --- a/Toolkit.UI.Avalonia/KeyBindingTriggerBehavior.cs +++ b/Toolkit.UI.Avalonia/KeyBindingTriggerBehavior.cs @@ -5,8 +5,8 @@ using System.Windows.Input; namespace Toolkit.UI.Avalonia; -public class KeyBindingTriggerBehavior : - Trigger, +public class KeyBindingTriggerBehavior : + Trigger, ICommand { public static readonly StyledProperty GestureProperty = @@ -38,6 +38,6 @@ public class KeyBindingTriggerBehavior : public bool CanExecute(object? parameter) => true; - public void Execute(object? parameter) => + public void Execute(object? parameter) => Interaction.ExecuteActions(AssociatedObject, Actions, null); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/NavigateAction.cs b/Toolkit.UI.Avalonia/NavigateAction.cs index 1ff15ef..eb1ce4c 100644 --- a/Toolkit.UI.Avalonia/NavigateAction.cs +++ b/Toolkit.UI.Avalonia/NavigateAction.cs @@ -51,6 +51,7 @@ public class NavigateAction : get => GetValue(RouteProperty); set => SetValue(RouteProperty, value); } + public string Scope { get => GetValue(ScopeProperty); @@ -62,12 +63,13 @@ public class NavigateAction : { if (sender is TemplatedControl control) { - Dictionary arguments = + Dictionary arguments = new(StringComparer.InvariantCultureIgnoreCase); if (control.DataContext is IObservableViewModel observableViewModel) { - object[] parameters = [.. Parameters ?? Enumerable.Empty(), .. + object[] parameters = [.. Parameters ?? Enumerable.Empty(), + .. ParameterBindings is { Count: > 0 } ? ParameterBindings.Select(binding => new KeyValuePair(binding.Key, binding.Value)).ToArray() : Enumerable.Empty>()]; @@ -79,4 +81,4 @@ public class NavigateAction : return true; } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/NavigateBackAction.cs b/Toolkit.UI.Avalonia/NavigateBackAction.cs index 93d66db..10bd27c 100644 --- a/Toolkit.UI.Avalonia/NavigateBackAction.cs +++ b/Toolkit.UI.Avalonia/NavigateBackAction.cs @@ -41,4 +41,4 @@ public class NavigateBackAction : return true; } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Avalonia/ParameterBinding.cs b/Toolkit.UI.Avalonia/ParameterBinding.cs index abb7803..16ec964 100644 --- a/Toolkit.UI.Avalonia/ParameterBinding.cs +++ b/Toolkit.UI.Avalonia/ParameterBinding.cs @@ -16,9 +16,10 @@ public class ParameterBinding : get => GetValue(KeyProperty); set => SetValue(KeyProperty, value); } + public object Value { get => GetValue(ValueProperty); set => SetValue(ValueProperty, value); } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/AsyncImage/AsyncImage.cs b/Toolkit.UI.Controls.Avalonia/AsyncImage/AsyncImage.cs index bacad06..a0da572 100644 --- a/Toolkit.UI.Controls.Avalonia/AsyncImage/AsyncImage.cs +++ b/Toolkit.UI.Controls.Avalonia/AsyncImage/AsyncImage.cs @@ -5,4 +5,4 @@ public class AsyncImage : { protected override Type StyleKeyOverride => typeof(global::Avalonia.Labs.Controls.AsyncImage); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/BlurBehind/BlurBehind.cs b/Toolkit.UI.Controls.Avalonia/BlurBehind/BlurBehind.cs index 8284e95..35fc4eb 100644 --- a/Toolkit.UI.Controls.Avalonia/BlurBehind/BlurBehind.cs +++ b/Toolkit.UI.Controls.Avalonia/BlurBehind/BlurBehind.cs @@ -9,29 +9,29 @@ using SkiaSharp; namespace Toolkit.UI.Controls.Avalonia; -public class BlurBehind : +public class BlurBehind : Control { public static readonly StyledProperty MaterialProperty = AvaloniaProperty.Register("Material"); - public static readonly ImmutableExperimentalAcrylicMaterial DefaultAcrylicMaterialDark = + public static readonly ImmutableExperimentalAcrylicMaterial DefaultAcrylicMaterialDark = (ImmutableExperimentalAcrylicMaterial)new ExperimentalAcrylicMaterial() - { - MaterialOpacity = 0.25, - TintColor = Colors.Black, - TintOpacity = 0.7, - PlatformTransparencyCompensationLevel = 0 - }.ToImmutable(); + { + MaterialOpacity = 0.25, + TintColor = Colors.Black, + TintOpacity = 0.7, + PlatformTransparencyCompensationLevel = 0 + }.ToImmutable(); - public static readonly ImmutableExperimentalAcrylicMaterial DefaultAcrylicMaterialLight = + public static readonly ImmutableExperimentalAcrylicMaterial DefaultAcrylicMaterialLight = (ImmutableExperimentalAcrylicMaterial)new ExperimentalAcrylicMaterial() - { - MaterialOpacity = 0.0, - TintColor = Colors.White, - TintOpacity = 0.3, - PlatformTransparencyCompensationLevel = 0 - }.ToImmutable(); + { + MaterialOpacity = 0.0, + TintColor = Colors.White, + TintOpacity = 0.3, + PlatformTransparencyCompensationLevel = 0 + }.ToImmutable(); static BlurBehind() { @@ -49,7 +49,7 @@ public class BlurBehind : ImmutableExperimentalAcrylicMaterial material = Material is not null ? (ImmutableExperimentalAcrylicMaterial)Material.ToImmutable() : Application.Current?.ActualThemeVariant == ThemeVariant.Dark ? DefaultAcrylicMaterialDark : DefaultAcrylicMaterialLight; - + context.Custom(new BlurBehindRenderOperation(material, new Rect(default, Bounds.Size))); } @@ -63,18 +63,17 @@ public class BlurBehind : public void Dispose() { - } - public bool Equals(ICustomDrawOperation? other) => - other is BlurBehindRenderOperation behindRenderOperation && + public bool Equals(ICustomDrawOperation? other) => + other is BlurBehindRenderOperation behindRenderOperation && behindRenderOperation.bounds == bounds && behindRenderOperation.material.Equals(material); public bool HitTest(Point point) => bounds.Contains(point); public void Render(ImmediateDrawingContext context) { - if (context.TryGetFeature() is ISkiaSharpApiLeaseFeature leaseFeature) + if (context.TryGetFeature() is ISkiaSharpApiLeaseFeature leaseFeature) { using ISkiaSharpApiLease? lease = leaseFeature.Lease(); if (lease.SkCanvas is SKCanvas canvas) @@ -92,7 +91,7 @@ public class BlurBehind : SKImageInfo.PlatformColorType, SKAlphaType.Premul)); using (SKImageFilter filter = SKImageFilter.CreateBlur(8, 8, SKShaderTileMode.Clamp)) - using (SKPaint blurPaint = new() { Shader = backdropShader, ImageFilter = filter }) + using (SKPaint blurPaint = new() { Shader = backdropShader, ImageFilter = filter }) blurred.Canvas.DrawRect(5, 5, (float)bounds.Width - 20, (float)bounds.Height - 20, blurPaint); using SKImage blurSnap = blurred.Snapshot(); @@ -105,11 +104,9 @@ public class BlurBehind : canvas.DrawRect(0, 0, (float)bounds.Width, (float)bounds.Height, blurSnapPaint); } - } } } } } -} - +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselView.cs b/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselView.cs index 23de510..2887ac5 100644 --- a/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselView.cs +++ b/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselView.cs @@ -78,7 +78,7 @@ public class CarouselView : indicatorVisual = ElementComposition.GetElementVisual(indicator); touchAreaVisual = ElementComposition.GetElementVisual(container); if (touchAreaVisual is not null) - { + { compositor = touchAreaVisual.Compositor; } @@ -136,7 +136,7 @@ public class CarouselView : protected override void OnPointerReleased(PointerReleasedEventArgs args) { - if (isPressed && container is not null + if (isPressed && container is not null && items is not null && indicatorVisual is not null) { @@ -167,12 +167,12 @@ public class CarouselView : } private void ArrangeItems(int newIndex, - int oldIndex = -1, + int oldIndex = -1, bool isAnimating = false) { - if (compositor is not null - && container is not null - && items is not null + if (compositor is not null + && container is not null + && items is not null && indicatorVisual is not null) { double containerHeight = Bounds.Height; @@ -237,15 +237,14 @@ public class CarouselView : scopedBatch.Completed += () => { - this.isAnimating = false; + this.isAnimating = false; for (int i = 0; i < columnCount; i++) { itemVisuals[(newIndex + i - 2 + columnCount) % columnCount].Offset = new Vector3((float)(offsets[i] - centreOffset), 0, 0); - } }; - + indicatorVisual.StartAnimation("Offset", indicatorAnimation); scopedBatch.Start(animationDuration); @@ -253,6 +252,7 @@ public class CarouselView : } } } + private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) => ArrangeItems(newIndex); diff --git a/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselViewItem.cs b/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselViewItem.cs index ed75a5f..a593889 100644 --- a/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselViewItem.cs +++ b/Toolkit.UI.Controls.Avalonia/CarouselView/CarouselViewItem.cs @@ -9,4 +9,4 @@ public class CarouselViewItem : { PseudoClasses.Set(":selected", selected); } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseBackgroundRenderer.cs b/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseBackgroundRenderer.cs index 58a9cf8..76d854e 100644 --- a/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseBackgroundRenderer.cs +++ b/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseBackgroundRenderer.cs @@ -1,9 +1,9 @@ -using Avalonia.Media.Imaging; -using Avalonia.Styling; -using Avalonia; -using SukiUI.Utilities.Background; -using Avalonia.Platform; +using Avalonia; using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using Avalonia.Styling; +using SukiUI.Utilities.Background; namespace Toolkit.UI.Controls.Avalonia; @@ -28,7 +28,7 @@ public class FastNoiseBackgroundRenderer public FastNoiseBackgroundRenderer(FastNoiseRendererOptions? options = null) { - FastNoiseRendererOptions opt = options ?? + FastNoiseRendererOptions opt = options ?? new FastNoiseRendererOptions(FastNoiseLite.NoiseType.OpenSimplex2); NoiseGen.SetNoiseType(opt.Type); @@ -130,7 +130,7 @@ public class FastNoiseBackgroundRenderer return ARGB(A(back), resultR, resultG, resultB); } - private static byte G(uint col) => + private static byte G(uint col) => (byte)(col >> 8); private static uint GetBackgroundColour(Color input) @@ -159,7 +159,7 @@ public class FastNoiseBackgroundRenderer private static byte R(uint col) => (byte)(col >> 16); - private static uint ToUInt32(Color colour) => + private static uint ToUInt32(Color colour) => (uint)(colour.A << 24 | colour.R << 16 | colour.G << 8 | colour.B); private static uint WithAlpha(uint col, byte a) => col & 0x00FFFFFF | (uint)(a << 24); diff --git a/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseRendererOptions.cs b/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseRendererOptions.cs index 48052e6..b496aa5 100644 --- a/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseRendererOptions.cs +++ b/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastNoiseRendererOptions.cs @@ -20,4 +20,4 @@ public readonly struct FastNoiseRendererOptions( public float XSeed { get; } = xSeed * seedScale; public float YSeed { get; } = ySeed * seedScale; -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastRendererBackground.cs b/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastRendererBackground.cs index 33dcef4..195894b 100644 --- a/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastRendererBackground.cs +++ b/Toolkit.UI.Controls.Avalonia/FastNoiseBackground/FastRendererBackground.cs @@ -7,13 +7,13 @@ using Avalonia.Styling; namespace Toolkit.UI.Controls.Avalonia; -public class FastRendererBackground : +public class FastRendererBackground : Image, IDisposable { private const int ImageWidth = 100; private const int ImageHeight = 100; - private readonly WriteableBitmap bitmap = new(new PixelSize(ImageWidth, ImageHeight), + private readonly WriteableBitmap bitmap = new(new PixelSize(ImageWidth, ImageHeight), new Vector(96, 96), PixelFormat.Bgra8888); private readonly FastNoiseBackgroundRenderer renderer = new(); @@ -29,7 +29,7 @@ public class FastRendererBackground : base.EndInit(); if (Application.Current?.ActualThemeVariant is ThemeVariant theme) { - renderer.UpdateValues((Color)Application.Current.FindResource("SystemAccentColorLight3"), + renderer.UpdateValues((Color)Application.Current.FindResource("SystemAccentColorLight3"), (Color)Application.Current.FindResource("SystemAccentColorDark3"), theme); } @@ -41,4 +41,4 @@ public class FastRendererBackground : GC.SuppressFinalize(this); bitmap.Dispose(); } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/Frame/Frame.cs b/Toolkit.UI.Controls.Avalonia/Frame/Frame.cs index 9d60880..2fbe63d 100644 --- a/Toolkit.UI.Controls.Avalonia/Frame/Frame.cs +++ b/Toolkit.UI.Controls.Avalonia/Frame/Frame.cs @@ -1,8 +1,8 @@ namespace Toolkit.UI.Controls.Avalonia; -public class Frame : +public class Frame : FluentAvalonia.UI.Controls.Frame { - protected override Type StyleKeyOverride => + protected override Type StyleKeyOverride => typeof(FluentAvalonia.UI.Controls.Frame); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/Helpers/ScopedBatchHelper.cs b/Toolkit.UI.Controls.Avalonia/Helpers/ScopedBatchHelper.cs index 5b7b451..adbf661 100644 --- a/Toolkit.UI.Controls.Avalonia/Helpers/ScopedBatchHelper.cs +++ b/Toolkit.UI.Controls.Avalonia/Helpers/ScopedBatchHelper.cs @@ -1,6 +1,7 @@ using Avalonia.Threading; namespace Toolkit.UI.Controls.Avalonia; + public class ScopedBatchHelper { private DispatcherTimer? timer; diff --git a/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationView.cs b/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationView.cs index 6594341..369fee4 100644 --- a/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationView.cs +++ b/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationView.cs @@ -3,6 +3,6 @@ public class NavigationView : FluentAvalonia.UI.Controls.NavigationView { - protected override Type StyleKeyOverride => + protected override Type StyleKeyOverride => typeof(FluentAvalonia.UI.Controls.NavigationView); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationViewItem.cs b/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationViewItem.cs index cd86847..f65fade 100644 --- a/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationViewItem.cs +++ b/Toolkit.UI.Controls.Avalonia/NavigationView/NavigationViewItem.cs @@ -5,4 +5,4 @@ public class NavigationViewItem : { protected override Type StyleKeyOverride => typeof(FluentAvalonia.UI.Controls.NavigationViewItem); -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitList.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitList.cs index ec8cd02..d725ab4 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitList.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitList.cs @@ -1,127 +1,124 @@ -using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; namespace Gma.QrCodeNet.Encoding; internal sealed class BitList : IEnumerable { - internal BitList() - { - Count = 0; - List = new List(32); - } + internal BitList() + { + Count = 0; + List = new List(32); + } - internal BitList(IEnumerable byteArray) - { - Count = byteArray.Count(); - List = byteArray.ToList(); - } + internal BitList(IEnumerable byteArray) + { + Count = byteArray.Count(); + List = byteArray.ToList(); + } - internal List List { get; } + internal List List { get; } - internal int Count { get; private set; } + internal int Count { get; private set; } - internal bool this[int index] - { - get - { - if (index < 0 || index >= Count) - { - throw new ArgumentOutOfRangeException(nameof(index), "Index out of range"); - } + internal bool this[int index] + { + get + { + if (index < 0 || index >= Count) + { + throw new ArgumentOutOfRangeException(nameof(index), "Index out of range"); + } - int value_Renamed = List[index >> 3] & 0xff; - return ((value_Renamed >> (7 - (index & 0x7))) & 1) == 1; - } - } + int value_Renamed = List[index >> 3] & 0xff; + return ((value_Renamed >> (7 - (index & 0x7))) & 1) == 1; + } + } - public IEnumerator GetEnumerator() - { - int numBytes = Count >> 3; - int remainder = Count & 0x7; - byte value; - for (int index = 0; index < numBytes; index++) - { - value = List[index]; - for (int shiftNum = 7; shiftNum >= 0; shiftNum--) - { - yield return ((value >> shiftNum) & 1) == 1; - } - } - if (remainder > 0) - { - value = List[numBytes]; - for (int index = 0; index < remainder; index++) - { - yield return ((value >> (7 - index)) & 1) == 1; - } - } - } + public IEnumerator GetEnumerator() + { + int numBytes = Count >> 3; + int remainder = Count & 0x7; + byte value; + for (int index = 0; index < numBytes; index++) + { + value = List[index]; + for (int shiftNum = 7; shiftNum >= 0; shiftNum--) + { + yield return ((value >> shiftNum) & 1) == 1; + } + } + if (remainder > 0) + { + value = List[numBytes]; + for (int index = 0; index < remainder; index++) + { + yield return ((value >> (7 - index)) & 1) == 1; + } + } + } - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } - private int ToBit(bool item) - { - return item ? 1 : 0; - } + private int ToBit(bool item) + { + return item ? 1 : 0; + } - internal void Add(bool item) - { - int numBitsinLastByte = Count & 0x7; + internal void Add(bool item) + { + int numBitsinLastByte = Count & 0x7; - // Add one more byte to List when we have no bits in the last byte. - if (numBitsinLastByte == 0) - { - List.Add(0); - } + // Add one more byte to List when we have no bits in the last byte. + if (numBitsinLastByte == 0) + { + List.Add(0); + } - List[Count >> 3] |= (byte)(ToBit(item) << (7 - numBitsinLastByte)); - Count++; - } + List[Count >> 3] |= (byte)(ToBit(item) << (7 - numBitsinLastByte)); + Count++; + } - internal void Add(IEnumerable items) - { - foreach (bool item in items) - { - Add(item); - } - } + internal void Add(IEnumerable items) + { + foreach (bool item in items) + { + Add(item); + } + } - internal void Add(int value, int bitCount) - { - if (bitCount is < 0 or > 32) - { - throw new ArgumentOutOfRangeException(nameof(bitCount), $"{nameof(bitCount)} must be greater than or equal to 0"); - } + internal void Add(int value, int bitCount) + { + if (bitCount is < 0 or > 32) + { + throw new ArgumentOutOfRangeException(nameof(bitCount), $"{nameof(bitCount)} must be greater than or equal to 0"); + } - int numBitsLeft = bitCount; + int numBitsLeft = bitCount; - while (numBitsLeft > 0) - { - if ((Count & 0x7) == 0 && numBitsLeft >= 8) - { - // Add one more byte to List. - byte newByte = (byte)((value >> (numBitsLeft - 8)) & 0xFF); - AppendByte(newByte); - numBitsLeft -= 8; - } - else - { - bool bit = ((value >> (numBitsLeft - 1)) & 1) == 1; - Add(bit); - numBitsLeft--; - } - } - } + while (numBitsLeft > 0) + { + if ((Count & 0x7) == 0 && numBitsLeft >= 8) + { + // Add one more byte to List. + byte newByte = (byte)((value >> (numBitsLeft - 8)) & 0xFF); + AppendByte(newByte); + numBitsLeft -= 8; + } + else + { + bool bit = ((value >> (numBitsLeft - 1)) & 1) == 1; + Add(bit); + numBitsLeft--; + } + } + } - private void AppendByte(byte item) - { - List.Add(item); - Count += 8; - } -} + private void AppendByte(byte item) + { + List.Add(item); + Count += 8; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrix.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrix.cs index ae0fb52..ed44f68 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrix.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrix.cs @@ -2,23 +2,23 @@ namespace Gma.QrCodeNet.Encoding; public abstract class BitMatrix { - public abstract int Width { get; } - public abstract int Height { get; } - public abstract bool[,] InternalArray { get; } + public abstract int Width { get; } + public abstract int Height { get; } + public abstract bool[,] InternalArray { get; } - public abstract bool this[int i, int j] { get; set; } + public abstract bool this[int i, int j] { get; set; } - internal void CopyTo(TriStateMatrix target, MatrixRectangle sourceArea, MatrixPoint targetPoint, MatrixStatus mstatus) - { - for (int j = 0; j < sourceArea.Size.Height; j++) - { - for (int i = 0; i < sourceArea.Size.Width; i++) - { - bool value = this[sourceArea.Location.X + i, sourceArea.Location.Y + j]; - target[targetPoint.X + i, targetPoint.Y + j, mstatus] = value; - } - } - } + internal void CopyTo(TriStateMatrix target, MatrixRectangle sourceArea, MatrixPoint targetPoint, MatrixStatus mstatus) + { + for (int j = 0; j < sourceArea.Size.Height; j++) + { + for (int i = 0; i < sourceArea.Size.Width; i++) + { + bool value = this[sourceArea.Location.X + i, sourceArea.Location.Y + j]; + target[targetPoint.X + i, targetPoint.Y + j, mstatus] = value; + } + } + } - internal void CopyTo(TriStateMatrix target, MatrixPoint targetPoint, MatrixStatus mstatus) => CopyTo(target, new MatrixRectangle(new MatrixPoint(0, 0), new MatrixSize(Width, Height)), targetPoint, mstatus); -} + internal void CopyTo(TriStateMatrix target, MatrixPoint targetPoint, MatrixStatus mstatus) => CopyTo(target, new MatrixRectangle(new MatrixPoint(0, 0), new MatrixSize(Width, Height)), targetPoint, mstatus); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrixBase.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrixBase.cs index aaa4ba5..6a577e2 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrixBase.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/BitMatrixBase.cs @@ -2,30 +2,30 @@ namespace Gma.QrCodeNet.Encoding; public abstract class BitMatrixBase : BitMatrix { - protected BitMatrixBase(int width, bool[,] internalArray) - { - Width = width; - InternalArray = internalArray; - } + protected BitMatrixBase(int width, bool[,] internalArray) + { + Width = width; + InternalArray = internalArray; + } - protected BitMatrixBase(bool[,] internalArray) - { - InternalArray = internalArray; - int width = internalArray.GetLength(0); - Width = width; - } + protected BitMatrixBase(bool[,] internalArray) + { + InternalArray = internalArray; + int width = internalArray.GetLength(0); + Width = width; + } - public override bool[,] InternalArray { get; } + public override bool[,] InternalArray { get; } - public override int Width { get; } + public override int Width { get; } - public static bool CanCreate(bool[,] internalArray) - { - if (internalArray is null) - { - return false; - } + public static bool CanCreate(bool[,] internalArray) + { + if (internalArray is null) + { + return false; + } - return internalArray.GetLength(0) == internalArray.GetLength(1); - } -} + return internalArray.GetLength(0) == internalArray.GetLength(1); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/CharCountIndicatorTable.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/CharCountIndicatorTable.cs index 9a6c752..c66d6b2 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/CharCountIndicatorTable.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/CharCountIndicatorTable.cs @@ -1,48 +1,46 @@ -using System; - namespace Gma.QrCodeNet.Encoding.DataEncodation; public static class CharCountIndicatorTable { - /// ISO/IEC 18004:2000 Table 3 Page 18 - public static int[] GetCharCountIndicatorSet() - { - return new int[] { 8, 16, 16 }; - } + /// ISO/IEC 18004:2000 Table 3 Page 18 + public static int[] GetCharCountIndicatorSet() + { + return new int[] { 8, 16, 16 }; + } - public static int GetBitCountInCharCountIndicator(int version) - { - int[] charCountIndicatorSet = GetCharCountIndicatorSet(); - int versionGroup = GetVersionGroup(version); + public static int GetBitCountInCharCountIndicator(int version) + { + int[] charCountIndicatorSet = GetCharCountIndicatorSet(); + int versionGroup = GetVersionGroup(version); - return charCountIndicatorSet[versionGroup]; - } + return charCountIndicatorSet[versionGroup]; + } - /// - /// Used to define length of the Character Count Indicator - /// - /// Returns the 0 based index of the row from Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator. - private static int GetVersionGroup(int version) - { - if (version > 40) - { - throw new InvalidOperationException($"Unexpected version: {version}."); - } - else if (version >= 27) - { - return 2; - } - else if (version >= 10) - { - return 1; - } - else if (version > 0) - { - return 0; - } - else - { - throw new InvalidOperationException($"Unexpected version: {version}."); - } - } -} + /// + /// Used to define length of the Character Count Indicator + /// + /// Returns the 0 based index of the row from Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator. + private static int GetVersionGroup(int version) + { + if (version > 40) + { + throw new InvalidOperationException($"Unexpected version: {version}."); + } + else if (version >= 27) + { + return 2; + } + else if (version >= 10) + { + return 1; + } + else if (version > 0) + { + return 0; + } + else + { + throw new InvalidOperationException($"Unexpected version: {version}."); + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/DataEncode.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/DataEncode.cs index 2a3c222..f36ec90 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/DataEncode.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/DataEncode.cs @@ -1,4 +1,3 @@ -using System; using Gma.QrCodeNet.Encoding.DataEncodation.InputRecognition; using Gma.QrCodeNet.Encoding.Terminate; using Gma.QrCodeNet.Encoding.Versions; @@ -10,53 +9,53 @@ namespace Gma.QrCodeNet.Encoding.DataEncodation; /// Which uses sub functions under several different namespaces internal static class DataEncode { - internal static EncodationStruct Encode(string content, ErrorCorrectionLevel ecLevel) - { - RecognitionStruct recognitionResult = InputRecognise.Recognise(content); - EncoderBase encoderBase = CreateEncoder(recognitionResult.EncodingName); + internal static EncodationStruct Encode(string content, ErrorCorrectionLevel ecLevel) + { + RecognitionStruct recognitionResult = InputRecognise.Recognise(content); + EncoderBase encoderBase = CreateEncoder(recognitionResult.EncodingName); - BitList encodeContent = encoderBase.GetDataBits(content); + BitList encodeContent = encoderBase.GetDataBits(content); - int encodeContentLength = encodeContent.Count; + int encodeContentLength = encodeContent.Count; - VersionControlStruct vcStruct = - VersionControl.InitialSetup(encodeContentLength, ecLevel, recognitionResult.EncodingName); + VersionControlStruct vcStruct = + VersionControl.InitialSetup(encodeContentLength, ecLevel, recognitionResult.EncodingName); - BitList dataCodewords = new(); + BitList dataCodewords = new(); - // Eci header - if (vcStruct.IsContainECI && vcStruct.ECIHeader is { }) - { - dataCodewords.Add(vcStruct.ECIHeader); - } + // Eci header + if (vcStruct.IsContainECI && vcStruct.ECIHeader is { }) + { + dataCodewords.Add(vcStruct.ECIHeader); + } - // Header - dataCodewords.Add(encoderBase.GetModeIndicator()); - int numLetter = encodeContentLength >> 3; - dataCodewords.Add(encoderBase.GetCharCountIndicator(numLetter, vcStruct.VersionDetail.Version)); + // Header + dataCodewords.Add(encoderBase.GetModeIndicator()); + int numLetter = encodeContentLength >> 3; + dataCodewords.Add(encoderBase.GetCharCountIndicator(numLetter, vcStruct.VersionDetail.Version)); - // Data - dataCodewords.Add(encodeContent); + // Data + dataCodewords.Add(encodeContent); - // Terminator Padding - dataCodewords.TerminateBites(dataCodewords.Count, vcStruct.VersionDetail.NumDataBytes); + // Terminator Padding + dataCodewords.TerminateBites(dataCodewords.Count, vcStruct.VersionDetail.NumDataBytes); - int dataCodewordsCount = dataCodewords.Count; - if ((dataCodewordsCount & 0x7) != 0) - { - throw new ArgumentException($"{nameof(dataCodewords)} is not byte sized."); - } - else if (dataCodewordsCount >> 3 != vcStruct.VersionDetail.NumDataBytes) - { - throw new ArgumentException($"{nameof(dataCodewords)} num of bytes not equal to {nameof(vcStruct.VersionDetail.NumDataBytes)} for current version"); - } + int dataCodewordsCount = dataCodewords.Count; + if ((dataCodewordsCount & 0x7) != 0) + { + throw new ArgumentException($"{nameof(dataCodewords)} is not byte sized."); + } + else if (dataCodewordsCount >> 3 != vcStruct.VersionDetail.NumDataBytes) + { + throw new ArgumentException($"{nameof(dataCodewords)} num of bytes not equal to {nameof(vcStruct.VersionDetail.NumDataBytes)} for current version"); + } - var encStruct = new EncodationStruct(vcStruct, dataCodewords); - return encStruct; - } + var encStruct = new EncodationStruct(vcStruct, dataCodewords); + return encStruct; + } - private static EncoderBase CreateEncoder(string encodingName) - { - return new EightBitByteEncoder(encodingName); - } -} + private static EncoderBase CreateEncoder(string encodingName) + { + return new EightBitByteEncoder(encodingName); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/ECISet.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/ECISet.cs index 9afdc5d..1709b4c 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/ECISet.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/ECISet.cs @@ -1,255 +1,252 @@ -using System; -using System.Collections.Generic; - namespace Gma.QrCodeNet.Encoding.DataEncodation; public sealed class ECISet { - /// - /// ISO/IEC 18004:2006 Chapter 6.4.2 Mode indicator = 0111 Page 23 - /// - private const int ECIMode = 7; + /// + /// ISO/IEC 18004:2006 Chapter 6.4.2 Mode indicator = 0111 Page 23 + /// + private const int ECIMode = 7; - private const int ECIIndicatorNumBits = 4; + private const int ECIIndicatorNumBits = 4; - private Dictionary? _nameToValue; - private Dictionary? _valueToName; + private Dictionary? _nameToValue; + private Dictionary? _valueToName; - /// - /// Initialize ECI Set. - /// - /// AppendOption is enum under ECISet - /// Use NameToValue during Encode. ValueToName during Decode - internal ECISet(AppendOption option) - { - Initialize(option); - } + /// + /// Initialize ECI Set. + /// + /// AppendOption is enum under ECISet + /// Use NameToValue during Encode. ValueToName during Decode + internal ECISet(AppendOption option) + { + Initialize(option); + } - public enum AppendOption - { - NameToValue, - ValueToName, - Both - } + public enum AppendOption + { + NameToValue, + ValueToName, + Both + } - /// - /// Length indicator for number of ECI codewords - /// - /// ISO/IEC 18004:2006 Chapter 6.4.2 Page 24. - /// 1 codeword length = 0. Any additional codeword add 1 to front. Eg: 3 = 110 - /// Bits required for each one is: - /// one = 1, two = 2, three = 3 - private enum ECICodewordsLength - { - One = 0, - Two = 2, - Three = 6 - } + /// + /// Length indicator for number of ECI codewords + /// + /// ISO/IEC 18004:2006 Chapter 6.4.2 Page 24. + /// 1 codeword length = 0. Any additional codeword add 1 to front. Eg: 3 = 110 + /// Bits required for each one is: + /// one = 1, two = 2, three = 3 + private enum ECICodewordsLength + { + One = 0, + Two = 2, + Three = 6 + } - /// ISO/IEC 18004:2006E ECI Designator Page 24 - /// Range: 0 ~ 999999 - /// Number of Codewords(Byte) for ECI Assignment Value - private static int NumOfCodewords(int eCIValue) - { - if (eCIValue is >= 0 and <= 127) - { - return 1; - } - else if (eCIValue is > 127 and <= 16383) - { - return 2; - } - else if (eCIValue is > 16383 and <= 999999) - { - return 3; - } - else - { - throw new ArgumentOutOfRangeException($"{nameof(eCIValue)} should be in range: 0 to 999999."); - } - } + /// ISO/IEC 18004:2006E ECI Designator Page 24 + /// Range: 0 ~ 999999 + /// Number of Codewords(Byte) for ECI Assignment Value + private static int NumOfCodewords(int eCIValue) + { + if (eCIValue is >= 0 and <= 127) + { + return 1; + } + else if (eCIValue is > 127 and <= 16383) + { + return 2; + } + else if (eCIValue is > 16383 and <= 999999) + { + return 3; + } + else + { + throw new ArgumentOutOfRangeException($"{nameof(eCIValue)} should be in range: 0 to 999999."); + } + } - /// ISO/IEC 18004:2006E ECI Designator Page 24 - /// Range: 0 ~ 999999 - /// Number of bits for ECI Assignment Value - private static int NumOfAssignmentBits(int eCIValue) => NumOfCodewords(eCIValue) * 8; + /// ISO/IEC 18004:2006E ECI Designator Page 24 + /// Range: 0 ~ 999999 + /// Number of bits for ECI Assignment Value + private static int NumOfAssignmentBits(int eCIValue) => NumOfCodewords(eCIValue) * 8; - private void AppendECI(string name, int value, AppendOption option) - { - switch (option) - { - case AppendOption.NameToValue: - _nameToValue?.Add(name, value); - break; + private void AppendECI(string name, int value, AppendOption option) + { + switch (option) + { + case AppendOption.NameToValue: + _nameToValue?.Add(name, value); + break; - case AppendOption.ValueToName: - _valueToName?.Add(value, name); - break; + case AppendOption.ValueToName: + _valueToName?.Add(value, name); + break; - case AppendOption.Both: - _nameToValue?.Add(name, value); - _valueToName?.Add(value, name); - break; + case AppendOption.Both: + _nameToValue?.Add(name, value); + _valueToName?.Add(value, name); + break; - default: - throw new InvalidOperationException($"There is no such {nameof(AppendOption)}."); - } - } + default: + throw new InvalidOperationException($"There is no such {nameof(AppendOption)}."); + } + } - private void Initialize(AppendOption option) - { - switch (option) - { - case AppendOption.NameToValue: - _nameToValue = new Dictionary(); - break; + private void Initialize(AppendOption option) + { + switch (option) + { + case AppendOption.NameToValue: + _nameToValue = new Dictionary(); + break; - case AppendOption.ValueToName: - _valueToName = new Dictionary(); - break; + case AppendOption.ValueToName: + _valueToName = new Dictionary(); + break; - case AppendOption.Both: - _nameToValue = new Dictionary(); - _valueToName = new Dictionary(); - break; + case AppendOption.Both: + _nameToValue = new Dictionary(); + _valueToName = new Dictionary(); + break; - default: - throw new InvalidOperationException($"There is no such {nameof(AppendOption)}."); - } + default: + throw new InvalidOperationException($"There is no such {nameof(AppendOption)}."); + } - // ECI table. Source 01 URL: http://strokescribe.com/en/ECI.html - // ECI table. Source 02 URL: http://lab.must.or.kr/Extended-Channel-Interpretations-ECI-Encoding.ashx - // ToDo. Fill up remaining missing table. - AppendECI("iso-8859-1", 1, option); - AppendECI("IBM437", 2, option); + // ECI table. Source 01 URL: http://strokescribe.com/en/ECI.html + // ECI table. Source 02 URL: http://lab.must.or.kr/Extended-Channel-Interpretations-ECI-Encoding.ashx + // ToDo. Fill up remaining missing table. + AppendECI("iso-8859-1", 1, option); + AppendECI("IBM437", 2, option); - // AppendECI("iso-8859-1", 3, option); //ECI value 1 is default encoding. - AppendECI("iso-8859-2", 4, option); - AppendECI("iso-8859-3", 5, option); - AppendECI("iso-8859-4", 6, option); - AppendECI("iso-8859-5", 7, option); - AppendECI("iso-8859-6", 8, option); - AppendECI("iso-8859-7", 9, option); - AppendECI("iso-8859-8", 10, option); - AppendECI("iso-8859-9", 11, option); - AppendECI("windows-874", 13, option); - AppendECI("iso-8859-13", 15, option); - AppendECI("iso-8859-15", 17, option); - AppendECI("shift_jis", 20, option); - AppendECI("utf-8", 26, option); - } + // AppendECI("iso-8859-1", 3, option); //ECI value 1 is default encoding. + AppendECI("iso-8859-2", 4, option); + AppendECI("iso-8859-3", 5, option); + AppendECI("iso-8859-4", 6, option); + AppendECI("iso-8859-5", 7, option); + AppendECI("iso-8859-6", 8, option); + AppendECI("iso-8859-7", 9, option); + AppendECI("iso-8859-8", 10, option); + AppendECI("iso-8859-9", 11, option); + AppendECI("windows-874", 13, option); + AppendECI("iso-8859-13", 15, option); + AppendECI("iso-8859-15", 17, option); + AppendECI("shift_jis", 20, option); + AppendECI("utf-8", 26, option); + } - /// ISO/IEC 18004:2006E ECI Designator Page 24 - /// Range: 0 ~ 999999 - /// Number of bits for ECI Header - internal static int NumOfECIHeaderBits(int eCIValue) => NumOfAssignmentBits(eCIValue) + 4; + /// ISO/IEC 18004:2006E ECI Designator Page 24 + /// Range: 0 ~ 999999 + /// Number of bits for ECI Header + internal static int NumOfECIHeaderBits(int eCIValue) => NumOfAssignmentBits(eCIValue) + 4; - internal int GetECIValueByName(string encodingName) - { - if (_nameToValue is null) - { - Initialize(AppendOption.NameToValue); - } + internal int GetECIValueByName(string encodingName) + { + if (_nameToValue is null) + { + Initialize(AppendOption.NameToValue); + } - if (_nameToValue!.TryGetValue(encodingName, out int eCIValue)) - { - return eCIValue; - } - else - { - throw new ArgumentOutOfRangeException($"ECI does not contain encoding: {encodingName}."); - } - } + if (_nameToValue!.TryGetValue(encodingName, out int eCIValue)) + { + return eCIValue; + } + else + { + throw new ArgumentOutOfRangeException($"ECI does not contain encoding: {encodingName}."); + } + } - internal string GetECINameByValue(int eCIValue) - { - if (_valueToName is null) - { - Initialize(AppendOption.ValueToName); - } + internal string GetECINameByValue(int eCIValue) + { + if (_valueToName is null) + { + Initialize(AppendOption.ValueToName); + } - if (_valueToName!.TryGetValue(eCIValue, out var eCIName)) - { - return eCIName; - } - else - { - throw new ArgumentOutOfRangeException($"ECI does not contain value: {eCIValue}."); - } - } + if (_valueToName!.TryGetValue(eCIValue, out var eCIName)) + { + return eCIName; + } + else + { + throw new ArgumentOutOfRangeException($"ECI does not contain value: {eCIValue}."); + } + } - /// ECI table in Dictionary collection - public Dictionary? GetECITable() - { - if (_nameToValue is null) - { - Initialize(AppendOption.NameToValue); - } + /// ECI table in Dictionary collection + public Dictionary? GetECITable() + { + if (_nameToValue is null) + { + Initialize(AppendOption.NameToValue); + } - return _nameToValue; - } + return _nameToValue; + } - public bool ContainsECIName(string encodingName) - { - if (_nameToValue is null) - { - Initialize(AppendOption.NameToValue); - } + public bool ContainsECIName(string encodingName) + { + if (_nameToValue is null) + { + Initialize(AppendOption.NameToValue); + } - return _nameToValue!.ContainsKey(encodingName); - } + return _nameToValue!.ContainsKey(encodingName); + } - public bool ContainsECIValue(int eciValue) - { - if (_valueToName is null) - { - Initialize(AppendOption.ValueToName); - } + public bool ContainsECIValue(int eciValue) + { + if (_valueToName is null) + { + Initialize(AppendOption.ValueToName); + } - return _valueToName!.ContainsKey(eciValue); - } + return _valueToName!.ContainsKey(eciValue); + } - /// ISO/IEC 18004:2006 Chapter 6.4.2 Page 24. - internal BitList GetECIHeader(string encodingName) - { - int eciValue = GetECIValueByName(encodingName); + /// ISO/IEC 18004:2006 Chapter 6.4.2 Page 24. + internal BitList GetECIHeader(string encodingName) + { + int eciValue = GetECIValueByName(encodingName); - BitList dataBits = new() - { - { ECIMode, ECIIndicatorNumBits } - }; + BitList dataBits = new() + { + { ECIMode, ECIIndicatorNumBits } + }; - int eciAssignmentByte = NumOfCodewords(eciValue); + int eciAssignmentByte = NumOfCodewords(eciValue); - // Number of bits = Num codewords indicator + codeword value = Number of codewords * 8 - // Chapter 6.4.2.1 ECI Designator ISOIEC 18004:2006 Page 24 - int eciAssignmentBits; - switch (eciAssignmentByte) - { - case 1: - // Indicator = 0. Page 24. Chapter 6.4.2.1 - dataBits.Add((int)ECICodewordsLength.One, 1); - eciAssignmentBits = (eciAssignmentByte * 8) - 1; - break; + // Number of bits = Num codewords indicator + codeword value = Number of codewords * 8 + // Chapter 6.4.2.1 ECI Designator ISOIEC 18004:2006 Page 24 + int eciAssignmentBits; + switch (eciAssignmentByte) + { + case 1: + // Indicator = 0. Page 24. Chapter 6.4.2.1 + dataBits.Add((int)ECICodewordsLength.One, 1); + eciAssignmentBits = (eciAssignmentByte * 8) - 1; + break; - case 2: - // Indicator = 10. Page 24. Chapter 6.4.2.1 - dataBits.Add((int)ECICodewordsLength.Two, 2); - eciAssignmentBits = (eciAssignmentByte * 8) - 2; - break; + case 2: + // Indicator = 10. Page 24. Chapter 6.4.2.1 + dataBits.Add((int)ECICodewordsLength.Two, 2); + eciAssignmentBits = (eciAssignmentByte * 8) - 2; + break; - case 3: - // Indicator = 110. Page 24. Chapter 6.4.2.1 - dataBits.Add((int)ECICodewordsLength.Three, 3); - eciAssignmentBits = (eciAssignmentByte * 8) - 3; - break; + case 3: + // Indicator = 110. Page 24. Chapter 6.4.2.1 + dataBits.Add((int)ECICodewordsLength.Three, 3); + eciAssignmentBits = (eciAssignmentByte * 8) - 3; + break; - default: - throw new InvalidOperationException("Assignment Codewords should be either 1, 2 or 3."); - } + default: + throw new InvalidOperationException("Assignment Codewords should be either 1, 2 or 3."); + } - dataBits.Add(eciValue, eciAssignmentBits); + dataBits.Add(eciValue, eciAssignmentBits); - return dataBits; - } -} + return dataBits; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EightBitByteEncoder.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EightBitByteEncoder.cs index e8ffe7b..866f94b 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EightBitByteEncoder.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EightBitByteEncoder.cs @@ -1,5 +1,3 @@ -using System; - namespace Gma.QrCodeNet.Encoding.DataEncodation; /// @@ -14,67 +12,67 @@ namespace Gma.QrCodeNet.Encoding.DataEncodation; /// ISO/IEC 18004:2000 Chapter 8.4.4 Page 22 internal class EightBitByteEncoder : EncoderBase { - private const string DefaultEncoding = QRCodeConstantVariable.DefaultEncoding; + private const string DefaultEncoding = QRCodeConstantVariable.DefaultEncoding; - /// - /// Bitcount, Chapter 8.4.4, P.24 - /// - private const int EightBitByteBitcount = 8; + /// + /// Bitcount, Chapter 8.4.4, P.24 + /// + private const int EightBitByteBitcount = 8; - /// - /// EightBitByte encoder's encoding will change according to different region - /// - /// Default encoding is "iso-8859-1" - internal EightBitByteEncoder(string encoding) : base() - { - Encoding = encoding ?? DefaultEncoding; - } + /// + /// EightBitByte encoder's encoding will change according to different region + /// + /// Default encoding is "iso-8859-1" + internal EightBitByteEncoder(string encoding) : base() + { + Encoding = encoding ?? DefaultEncoding; + } - internal EightBitByteEncoder() : base() - { - Encoding = DefaultEncoding; - } + internal EightBitByteEncoder() : base() + { + Encoding = DefaultEncoding; + } - internal string Encoding { get; private set; } + internal string Encoding { get; private set; } - protected byte[] EncodeContent(string content, string encoding) => System.Text.Encoding.GetEncoding(encoding).GetBytes(content); + protected byte[] EncodeContent(string content, string encoding) => System.Text.Encoding.GetEncoding(encoding).GetBytes(content); - internal override BitList GetDataBits(string content) - { - var eciSet = new ECISet(ECISet.AppendOption.NameToValue); - if (!eciSet.ContainsECIName(Encoding)) - { - throw new ArgumentOutOfRangeException( - nameof(Encoding), - $"Current ECI table does not support this encoding. Please check {nameof(ECISet)} class for more info."); - } + internal override BitList GetDataBits(string content) + { + var eciSet = new ECISet(ECISet.AppendOption.NameToValue); + if (!eciSet.ContainsECIName(Encoding)) + { + throw new ArgumentOutOfRangeException( + nameof(Encoding), + $"Current ECI table does not support this encoding. Please check {nameof(ECISet)} class for more info."); + } - byte[] contentBytes = EncodeContent(content, Encoding); + byte[] contentBytes = EncodeContent(content, Encoding); - return GetDataBitsByByteArray(contentBytes, Encoding); - } + return GetDataBitsByByteArray(contentBytes, Encoding); + } - internal BitList GetDataBitsByByteArray(byte[] encodeContent, string encodingName) - { - var dataBits = new BitList(); + internal BitList GetDataBitsByByteArray(byte[] encodeContent, string encodingName) + { + var dataBits = new BitList(); - // Current plan for UTF8 support is put Byte order Mark in front of content byte. - // Also include ECI header before encoding header. Which will be add with encoding header. - if (encodingName == "utf-8") - { - byte[] utf8BOM = QRCodeConstantVariable.UTF8ByteOrderMark; - for (int index = 0; index < utf8BOM.Length; index++) - { - dataBits.Add(utf8BOM[index], EightBitByteBitcount); - } - } + // Current plan for UTF8 support is put Byte order Mark in front of content byte. + // Also include ECI header before encoding header. Which will be add with encoding header. + if (encodingName == "utf-8") + { + byte[] utf8BOM = QRCodeConstantVariable.UTF8ByteOrderMark; + for (int index = 0; index < utf8BOM.Length; index++) + { + dataBits.Add(utf8BOM[index], EightBitByteBitcount); + } + } - for (int index = 0; index < encodeContent.Length; index++) - { - dataBits.Add(encodeContent[index], EightBitByteBitcount); - } - return dataBits; - } + for (int index = 0; index < encodeContent.Length; index++) + { + dataBits.Add(encodeContent[index], EightBitByteBitcount); + } + return dataBits; + } - protected override int GetBitCountInCharCountIndicator(int version) => CharCountIndicatorTable.GetBitCountInCharCountIndicator(version); -} + protected override int GetBitCountInCharCountIndicator(int version) => CharCountIndicatorTable.GetBitCountInCharCountIndicator(version); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncodationStruct.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncodationStruct.cs index f9a854f..ec31c7a 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncodationStruct.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncodationStruct.cs @@ -4,12 +4,12 @@ namespace Gma.QrCodeNet.Encoding.DataEncodation; internal struct EncodationStruct { - internal EncodationStruct(VersionControlStruct vcStruct, BitList dataCodewords) - { - VersionDetail = vcStruct.VersionDetail; - DataCodewords = dataCodewords; - } + internal EncodationStruct(VersionControlStruct vcStruct, BitList dataCodewords) + { + VersionDetail = vcStruct.VersionDetail; + DataCodewords = dataCodewords; + } - internal VersionDetail VersionDetail { get; set; } - internal BitList DataCodewords { get; set; } -} + internal VersionDetail VersionDetail { get; set; } + internal BitList DataCodewords { get; set; } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncoderBase.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncoderBase.cs index b04dc73..454fab6 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncoderBase.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/EncoderBase.cs @@ -2,45 +2,45 @@ namespace Gma.QrCodeNet.Encoding.DataEncodation; public abstract class EncoderBase { - internal EncoderBase() - { - } + internal EncoderBase() + { + } - protected virtual int GetDataLength(string content) => content.Length; + protected virtual int GetDataLength(string content) => content.Length; - /// - /// Returns the bit representation of input data. - /// - internal abstract BitList GetDataBits(string content); + /// + /// Returns the bit representation of input data. + /// + internal abstract BitList GetDataBits(string content); - /// - /// Returns bit representation of Modevalue. - /// - /// See Chapter 8.4 Data encodation, Table 2 — Mode indicators - internal BitList GetModeIndicator() - { - BitList modeIndicatorBits = new() - { - { 0001 << 2, 4 } - }; - return modeIndicatorBits; - } + /// + /// Returns bit representation of Modevalue. + /// + /// See Chapter 8.4 Data encodation, Table 2 — Mode indicators + internal BitList GetModeIndicator() + { + BitList modeIndicatorBits = new() + { + { 0001 << 2, 4 } + }; + return modeIndicatorBits; + } - internal BitList GetCharCountIndicator(int characterCount, int version) - { - BitList characterCountBits = new(); - int bitCount = GetBitCountInCharCountIndicator(version); - characterCountBits.Add(characterCount, bitCount); - return characterCountBits; - } + internal BitList GetCharCountIndicator(int characterCount, int version) + { + BitList characterCountBits = new(); + int bitCount = GetBitCountInCharCountIndicator(version); + characterCountBits.Add(characterCount, bitCount); + return characterCountBits; + } - /// - /// Defines the length of the Character Count Indicator, - /// which varies according to the mode and the symbol version in use - /// - /// Number of bits in Character Count Indicator. - /// - /// See Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator. - /// - protected abstract int GetBitCountInCharCountIndicator(int version); -} + /// + /// Defines the length of the Character Count Indicator, + /// which varies according to the mode and the symbol version in use + /// + /// Number of bits in Character Count Indicator. + /// + /// See Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator. + /// + protected abstract int GetBitCountInCharCountIndicator(int version); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/InputRecognise.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/InputRecognise.cs index b08a97e..b751a85 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/InputRecognise.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/InputRecognise.cs @@ -1,57 +1,54 @@ -using System; -using System.Collections.Generic; - namespace Gma.QrCodeNet.Encoding.DataEncodation.InputRecognition; public static class InputRecognise { - public static RecognitionStruct Recognise(string content) - { - string encodingName = EightBitByteRecognision(content, 0, content.Length); - return new RecognitionStruct(encodingName); - } + public static RecognitionStruct Recognise(string content) + { + string encodingName = EightBitByteRecognision(content, 0, content.Length); + return new RecognitionStruct(encodingName); + } - private static string EightBitByteRecognision(string content, int startPos, int contentLength) - { - if(string.IsNullOrEmpty(content)) + private static string EightBitByteRecognision(string content, int startPos, int contentLength) + { + if (string.IsNullOrEmpty(content)) throw new ArgumentNullException(nameof(content)); - var eciSets = new ECISet(ECISet.AppendOption.NameToValue); + var eciSets = new ECISet(ECISet.AppendOption.NameToValue); - Dictionary? eciSet = eciSets.GetECITable(); + Dictionary? eciSet = eciSets.GetECITable(); - if(eciSet == null) + if (eciSet == null) return string.Empty; - // we will not check for utf8 encoding. - eciSet.Remove(QRCodeConstantVariable.UTF8Encoding); - eciSet.Remove(QRCodeConstantVariable.DefaultEncoding); + // we will not check for utf8 encoding. + eciSet.Remove(QRCodeConstantVariable.UTF8Encoding); + eciSet.Remove(QRCodeConstantVariable.DefaultEncoding); - int scanPos = startPos; + int scanPos = startPos; - // default encoding as priority - scanPos = ModeEncodeCheck.TryEncodeEightBitByte(content, QRCodeConstantVariable.DefaultEncoding, scanPos, contentLength); - if (scanPos == -1) - { - return QRCodeConstantVariable.DefaultEncoding; - } + // default encoding as priority + scanPos = ModeEncodeCheck.TryEncodeEightBitByte(content, QRCodeConstantVariable.DefaultEncoding, scanPos, contentLength); + if (scanPos == -1) + { + return QRCodeConstantVariable.DefaultEncoding; + } - foreach (KeyValuePair kvp in eciSet) - { - scanPos = ModeEncodeCheck.TryEncodeEightBitByte(content, kvp.Key, scanPos, contentLength); - if (scanPos == -1) - { - return kvp.Key; - } - } + foreach (KeyValuePair kvp in eciSet) + { + scanPos = ModeEncodeCheck.TryEncodeEightBitByte(content, kvp.Key, scanPos, contentLength); + if (scanPos == -1) + { + return kvp.Key; + } + } - if (scanPos == -1) - { - throw new ArgumentException("foreach Loop check give wrong result."); - } - else - { - return QRCodeConstantVariable.UTF8Encoding; - } - } -} + if (scanPos == -1) + { + throw new ArgumentException("foreach Loop check give wrong result."); + } + else + { + return QRCodeConstantVariable.UTF8Encoding; + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/ModeEncodeCheck.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/ModeEncodeCheck.cs index ac9d215..f480a49 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/ModeEncodeCheck.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/ModeEncodeCheck.cs @@ -1,72 +1,70 @@ -using System; - namespace Gma.QrCodeNet.Encoding.DataEncodation.InputRecognition; public static class ModeEncodeCheck { - /// - /// Encoding.GetEncoding.GetBytes will transform char to 0x3F if that char not belong to current encoding table. - /// 0x3F is '?' - /// - private const int QuestionMarkChar = 0x3F; + /// + /// Encoding.GetEncoding.GetBytes will transform char to 0x3F if that char not belong to current encoding table. + /// 0x3F is '?' + /// + private const int QuestionMarkChar = 0x3F; - /// - /// Use given encoding to check input string from starting position. If encoding table is suitable solution. - /// it will return -1. Else it will return failed encoding position. - /// - /// Input string - /// Encoding name. Check ECI table - /// Returns -1 if from starting position to end encoding success. Else returns fail position - internal static int TryEncodeEightBitByte(string content, string encodingName, int startingPosition, int contentLength) - { - if (string.IsNullOrEmpty(content)) - { - throw new IndexOutOfRangeException("Input cannot be null or empty."); - } + /// + /// Use given encoding to check input string from starting position. If encoding table is suitable solution. + /// it will return -1. Else it will return failed encoding position. + /// + /// Input string + /// Encoding name. Check ECI table + /// Returns -1 if from starting position to end encoding success. Else returns fail position + internal static int TryEncodeEightBitByte(string content, string encodingName, int startingPosition, int contentLength) + { + if (string.IsNullOrEmpty(content)) + { + throw new IndexOutOfRangeException("Input cannot be null or empty."); + } - System.Text.Encoding encoding; - try - { - encoding = System.Text.Encoding.GetEncoding(encodingName); - } - catch (ArgumentException) - { - return startingPosition; - } + System.Text.Encoding encoding; + try + { + encoding = System.Text.Encoding.GetEncoding(encodingName); + } + catch (ArgumentException) + { + return startingPosition; + } - char[] currentChar = new char[1]; - byte[] bytes; + char[] currentChar = new char[1]; + byte[] bytes; - for (int index = startingPosition; index < contentLength; index++) - { - currentChar[0] = content[index]; - bytes = encoding.GetBytes(currentChar); - int length = bytes.Length; - if (currentChar[0] != '?' && length == 1 && bytes[0] == QuestionMarkChar) - { - return index; - } - else if (length > 1) - { - return index; - } - } + for (int index = startingPosition; index < contentLength; index++) + { + currentChar[0] = content[index]; + bytes = encoding.GetBytes(currentChar); + int length = bytes.Length; + if (currentChar[0] != '?' && length == 1 && bytes[0] == QuestionMarkChar) + { + return index; + } + else if (length > 1) + { + return index; + } + } - for (int index = 0; index < startingPosition; index++) - { - currentChar[0] = content[index]; - bytes = encoding.GetBytes(currentChar); - int length = bytes.Length; - if (currentChar[0] != '?' && length == 1 && bytes[0] == QuestionMarkChar) - { - return index; - } - else if (length > 1) - { - return index; - } - } + for (int index = 0; index < startingPosition; index++) + { + currentChar[0] = content[index]; + bytes = encoding.GetBytes(currentChar); + int length = bytes.Length; + if (currentChar[0] != '?' && length == 1 && bytes[0] == QuestionMarkChar) + { + return index; + } + else if (length > 1) + { + return index; + } + } - return -1; - } -} + return -1; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/RecognitionStruct.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/RecognitionStruct.cs index 256b3cf..986c923 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/RecognitionStruct.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/DataEncodation/InputRecognition/RecognitionStruct.cs @@ -2,11 +2,11 @@ namespace Gma.QrCodeNet.Encoding.DataEncodation.InputRecognition; public struct RecognitionStruct { - public RecognitionStruct(string encodingName) - : this() - { - EncodingName = encodingName; - } + public RecognitionStruct(string encodingName) + : this() + { + EncodingName = encodingName; + } - public string EncodingName { get; private set; } -} + public string EncodingName { get; private set; } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/BCHCalculator.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/BCHCalculator.cs index a9fec96..a4434f7 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/BCHCalculator.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/BCHCalculator.cs @@ -2,59 +2,59 @@ namespace Gma.QrCodeNet.Encoding.EncodingRegion; internal static class BCHCalculator { - /// - /// Calculate int length by search for Most significant bit - /// - /// Input Number - /// Most significant bit - internal static int PosMSB(int num) => num == 0 ? 0 : BinarySearchPos(num, 0, 32) + 1; + /// + /// Calculate int length by search for Most significant bit + /// + /// Input Number + /// Most significant bit + internal static int PosMSB(int num) => num == 0 ? 0 : BinarySearchPos(num, 0, 32) + 1; - /// - /// Search for right side bit of Most significant bit - /// - /// Input number - /// Lower boundary. At start should be 0 - /// Higher boundary. At start should be 32 - /// Most significant bit - 1 - private static int BinarySearchPos(int num, int lowBoundary, int highBoundary) - { - int mid = (lowBoundary + highBoundary) / 2; - int shiftResult = num >> mid; - if (shiftResult == 1) - { - return mid; - } - else if (shiftResult < 1) - { - return BinarySearchPos(num, lowBoundary, mid); - } - else - { - return BinarySearchPos(num, mid, highBoundary); - } - } + /// + /// Search for right side bit of Most significant bit + /// + /// Input number + /// Lower boundary. At start should be 0 + /// Higher boundary. At start should be 32 + /// Most significant bit - 1 + private static int BinarySearchPos(int num, int lowBoundary, int highBoundary) + { + int mid = (lowBoundary + highBoundary) / 2; + int shiftResult = num >> mid; + if (shiftResult == 1) + { + return mid; + } + else if (shiftResult < 1) + { + return BinarySearchPos(num, lowBoundary, mid); + } + else + { + return BinarySearchPos(num, mid, highBoundary); + } + } - /// - /// With input number and polynomial number. Method will calculate BCH value and return - /// - /// Input number - /// Polynomial number - /// BCH value - internal static int CalculateBCH(int num, int poly) - { - int polyMSB = PosMSB(poly); + /// + /// With input number and polynomial number. Method will calculate BCH value and return + /// + /// Input number + /// Polynomial number + /// BCH value + internal static int CalculateBCH(int num, int poly) + { + int polyMSB = PosMSB(poly); - // num's length will be old length + new length - 1. - // Once divide poly number. BCH number will be one length short than Poly number's length. - num <<= (polyMSB - 1); - int numMSB = PosMSB(num); - while (PosMSB(num) >= polyMSB) - { - // left shift Poly number to same level as num. Then xor. - // Remove most significant bits of num. - num ^= poly << (numMSB - polyMSB); - numMSB = PosMSB(num); - } - return num; - } -} + // num's length will be old length + new length - 1. + // Once divide poly number. BCH number will be one length short than Poly number's length. + num <<= (polyMSB - 1); + int numMSB = PosMSB(num); + while (PosMSB(num) >= polyMSB) + { + // left shift Poly number to same level as num. Then xor. + // Remove most significant bits of num. + num ^= poly << (numMSB - polyMSB); + numMSB = PosMSB(num); + } + return num; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/Codeword.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/Codeword.cs index d6b1c0a..5afeb9e 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/Codeword.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/Codeword.cs @@ -1,72 +1,70 @@ -using System; - namespace Gma.QrCodeNet.Encoding.EncodingRegion; /// ISO/IEC 18004:2000 Chapter 8.7.3 Page 46 internal static class Codeword { - internal static void TryEmbedCodewords(this TriStateMatrix tsMatrix, BitList codewords) - { - int sWidth = tsMatrix.Width; - int codewordsSize = codewords.Count; + internal static void TryEmbedCodewords(this TriStateMatrix tsMatrix, BitList codewords) + { + int sWidth = tsMatrix.Width; + int codewordsSize = codewords.Count; - int bitIndex = 0; - int directionUp = -1; + int bitIndex = 0; + int directionUp = -1; - int x = sWidth - 1; - int y = sWidth - 1; + int x = sWidth - 1; + int y = sWidth - 1; - while (x > 0) - { - // Skip vertical timing pattern - if (x == 6) - { - x -= 1; - } + while (x > 0) + { + // Skip vertical timing pattern + if (x == 6) + { + x -= 1; + } - while (y >= 0 && y < sWidth) - { - for (int xOffset = 0; xOffset < 2; xOffset++) - { - int xPos = x - xOffset; - if (tsMatrix.MStatus(xPos, y) == MatrixStatus.None) - { - bool bit; - if (bitIndex < codewordsSize) - { - bit = codewords[bitIndex]; - bitIndex++; - } - else - { - bit = false; - } + while (y >= 0 && y < sWidth) + { + for (int xOffset = 0; xOffset < 2; xOffset++) + { + int xPos = x - xOffset; + if (tsMatrix.MStatus(xPos, y) == MatrixStatus.None) + { + bool bit; + if (bitIndex < codewordsSize) + { + bit = codewords[bitIndex]; + bitIndex++; + } + else + { + bit = false; + } - tsMatrix[xPos, y, MatrixStatus.Data] = bit; - } - } + tsMatrix[xPos, y, MatrixStatus.Data] = bit; + } + } - y = NextY(y, directionUp); - } + y = NextY(y, directionUp); + } - directionUp = ChangeDirection(directionUp); - y = NextY(y, directionUp); - x -= 2; - } + directionUp = ChangeDirection(directionUp); + y = NextY(y, directionUp); + x -= 2; + } - if (bitIndex != codewordsSize) - { - throw new Exception($"Not all bits from {nameof(codewords)} consumed by matrix: {bitIndex} / {codewordsSize}."); - } - } + if (bitIndex != codewordsSize) + { + throw new Exception($"Not all bits from {nameof(codewords)} consumed by matrix: {bitIndex} / {codewordsSize}."); + } + } - internal static int NextY(int y, int directionUp) - { - return y + directionUp; - } + internal static int NextY(int y, int directionUp) + { + return y + directionUp; + } - internal static int ChangeDirection(int directionUp) - { - return -directionUp; - } -} + internal static int ChangeDirection(int directionUp) + { + return -directionUp; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/FormatInformation.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/FormatInformation.cs index eaaf733..3edc1c5 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/FormatInformation.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/FormatInformation.cs @@ -1,4 +1,3 @@ -using System; using Gma.QrCodeNet.Encoding.Masking; namespace Gma.QrCodeNet.Encoding.EncodingRegion; @@ -10,105 +9,105 @@ namespace Gma.QrCodeNet.Encoding.EncodingRegion; /// ISO/IEC 18004:2000 Chapter 8.9 Page 53 internal static class FormatInformation { - /// - /// From Appendix C in JISX0510:2004 (p.65). - /// - private const int FormatInfoPoly = 0x537; + /// + /// From Appendix C in JISX0510:2004 (p.65). + /// + private const int FormatInfoPoly = 0x537; - /// - /// From Appendix C in JISX0510:2004 (p.65). - /// - private const int FormatInfoMaskPattern = 0x5412; + /// + /// From Appendix C in JISX0510:2004 (p.65). + /// + private const int FormatInfoMaskPattern = 0x5412; - /// - /// Embed format information to tristatematrix. - /// Process combination of create info bits, BCH error correction bits calculation, embed towards matrix. - /// - /// ISO/IEC 18004:2000 Chapter 8.9 Page 53 - internal static void EmbedFormatInformation(this TriStateMatrix triMatrix, ErrorCorrectionLevel errorLevel, Pattern pattern) - { - BitList formatInfo = GetFormatInfoBits(errorLevel, pattern); - int width = triMatrix.Width; - for (int index = 0; index < 15; index++) - { - MatrixPoint point = PointForInfo1(index); - bool bit = formatInfo[index]; - triMatrix[point.X, point.Y, MatrixStatus.NoMask] = bit; + /// + /// Embed format information to tristatematrix. + /// Process combination of create info bits, BCH error correction bits calculation, embed towards matrix. + /// + /// ISO/IEC 18004:2000 Chapter 8.9 Page 53 + internal static void EmbedFormatInformation(this TriStateMatrix triMatrix, ErrorCorrectionLevel errorLevel, Pattern pattern) + { + BitList formatInfo = GetFormatInfoBits(errorLevel, pattern); + int width = triMatrix.Width; + for (int index = 0; index < 15; index++) + { + MatrixPoint point = PointForInfo1(index); + bool bit = formatInfo[index]; + triMatrix[point.X, point.Y, MatrixStatus.NoMask] = bit; - if (index < 7) - { - triMatrix[8, width - 1 - index, MatrixStatus.NoMask] = bit; - } - else - { - triMatrix[width - 8 + (index - 7), 8, MatrixStatus.NoMask] = bit; - } - } - } + if (index < 7) + { + triMatrix[8, width - 1 - index, MatrixStatus.NoMask] = bit; + } + else + { + triMatrix[width - 8 + (index - 7), 8, MatrixStatus.NoMask] = bit; + } + } + } - private static MatrixPoint PointForInfo1(int bitsIndex) - { - if (bitsIndex <= 7) - { - return bitsIndex >= 6 - ? new MatrixPoint(bitsIndex + 1, 8) - : new MatrixPoint(bitsIndex, 8); - } - else - { - return bitsIndex == 8 - ? new MatrixPoint(8, 8 - (bitsIndex - 7)) - : new MatrixPoint(8, 8 - (bitsIndex - 7) - 1); - } - } + private static MatrixPoint PointForInfo1(int bitsIndex) + { + if (bitsIndex <= 7) + { + return bitsIndex >= 6 + ? new MatrixPoint(bitsIndex + 1, 8) + : new MatrixPoint(bitsIndex, 8); + } + else + { + return bitsIndex == 8 + ? new MatrixPoint(8, 8 - (bitsIndex - 7)) + : new MatrixPoint(8, 8 - (bitsIndex - 7) - 1); + } + } - private static BitList GetFormatInfoBits(ErrorCorrectionLevel errorLevel, Pattern pattern) - { - int formatInfo = (int)pattern.MaskPatternType; + private static BitList GetFormatInfoBits(ErrorCorrectionLevel errorLevel, Pattern pattern) + { + int formatInfo = (int)pattern.MaskPatternType; - // Pattern bits length = 3 - formatInfo |= GetErrorCorrectionIndicatorBits(errorLevel) << 3; + // Pattern bits length = 3 + formatInfo |= GetErrorCorrectionIndicatorBits(errorLevel) << 3; - int bchCode = BCHCalculator.CalculateBCH(formatInfo, FormatInfoPoly); + int bchCode = BCHCalculator.CalculateBCH(formatInfo, FormatInfoPoly); - // bchCode length = 10 - formatInfo = (formatInfo << 10) | bchCode; + // bchCode length = 10 + formatInfo = (formatInfo << 10) | bchCode; - // xor maskPattern - formatInfo ^= FormatInfoMaskPattern; + // xor maskPattern + formatInfo ^= FormatInfoMaskPattern; - BitList resultBits = new() - { - { formatInfo, 15 } - }; + BitList resultBits = new() + { + { formatInfo, 15 } + }; - if (resultBits.Count != 15) - { - throw new Exception("FormatInfoBits length is not 15"); - } - else - { - return resultBits; - } - } + if (resultBits.Count != 15) + { + throw new Exception("FormatInfoBits length is not 15"); + } + else + { + return resultBits; + } + } - /// - /// According Table 25 — Error correction level indicators - /// Using these bits as enum values would destroy their order which currently corresponds to error correction strength. - /// - internal static int GetErrorCorrectionIndicatorBits(ErrorCorrectionLevel errorLevel) - { - // L 01 - // M 00 - // Q 11 - // H 10 - return errorLevel switch - { - ErrorCorrectionLevel.H => 0x02, - ErrorCorrectionLevel.L => 0x01, - ErrorCorrectionLevel.M => 0x00, - ErrorCorrectionLevel.Q => 0x03, - _ => throw new ArgumentException($"Unsupported error correction level [{errorLevel}]", nameof(errorLevel)) - }; - } -} + /// + /// According Table 25 — Error correction level indicators + /// Using these bits as enum values would destroy their order which currently corresponds to error correction strength. + /// + internal static int GetErrorCorrectionIndicatorBits(ErrorCorrectionLevel errorLevel) + { + // L 01 + // M 00 + // Q 11 + // H 10 + return errorLevel switch + { + ErrorCorrectionLevel.H => 0x02, + ErrorCorrectionLevel.L => 0x01, + ErrorCorrectionLevel.M => 0x00, + ErrorCorrectionLevel.Q => 0x03, + _ => throw new ArgumentException($"Unsupported error correction level [{errorLevel}]", nameof(errorLevel)) + }; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/VersionInformation.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/VersionInformation.cs index 11b9718..acf3577 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/VersionInformation.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/EncodingRegion/VersionInformation.cs @@ -1,5 +1,3 @@ -using System; - namespace Gma.QrCodeNet.Encoding.EncodingRegion; /// @@ -8,63 +6,63 @@ namespace Gma.QrCodeNet.Encoding.EncodingRegion; /// ISO/IEC 18004:2000 Chapter 8.10 Page 54 internal static class VersionInformation { - private const int VIRectangleHeight = 3; - private const int VIRectangleWidth = 6; + private const int VIRectangleHeight = 3; + private const int VIRectangleWidth = 6; - private const int LengthDataBits = 6; - private const int LengthECBits = 12; - private const int VersionBCHPoly = 0x1f25; + private const int LengthDataBits = 6; + private const int LengthECBits = 12; + private const int VersionBCHPoly = 0x1f25; - /// - /// Embed version information to Matrix - /// Only for version greater than or equal to 7 - /// - internal static void EmbedVersionInformation(this TriStateMatrix tsMatrix, int version) - { - if (version < 7) - { - return; - } + /// + /// Embed version information to Matrix + /// Only for version greater than or equal to 7 + /// + internal static void EmbedVersionInformation(this TriStateMatrix tsMatrix, int version) + { + if (version < 7) + { + return; + } - BitList versionInfo = VersionInfoBitList(version); + BitList versionInfo = VersionInfoBitList(version); - int matrixWidth = tsMatrix.Width; + int matrixWidth = tsMatrix.Width; - // 1 cell between version info and position stencil - int shiftLength = QRCodeConstantVariable.PositionStencilWidth + VIRectangleHeight + 1; + // 1 cell between version info and position stencil + int shiftLength = QRCodeConstantVariable.PositionStencilWidth + VIRectangleHeight + 1; - // Reverse order input - int viIndex = LengthDataBits + LengthECBits - 1; + // Reverse order input + int viIndex = LengthDataBits + LengthECBits - 1; - for (int viWidth = 0; viWidth < VIRectangleWidth; viWidth++) - { - for (int viHeight = 0; viHeight < VIRectangleHeight; viHeight++) - { - bool bit = versionInfo[viIndex]; - viIndex--; + for (int viWidth = 0; viWidth < VIRectangleWidth; viWidth++) + { + for (int viHeight = 0; viHeight < VIRectangleHeight; viHeight++) + { + bool bit = versionInfo[viIndex]; + viIndex--; - // Bottom left - tsMatrix[viWidth, (matrixWidth - shiftLength + viHeight), MatrixStatus.NoMask] = bit; + // Bottom left + tsMatrix[viWidth, (matrixWidth - shiftLength + viHeight), MatrixStatus.NoMask] = bit; - // Top right - tsMatrix[(matrixWidth - shiftLength + viHeight), viWidth, MatrixStatus.NoMask] = bit; - } - } - } + // Top right + tsMatrix[(matrixWidth - shiftLength + viHeight), viWidth, MatrixStatus.NoMask] = bit; + } + } + } - private static BitList VersionInfoBitList(int version) - { - BitList result = new() - { - { version, LengthDataBits }, - { BCHCalculator.CalculateBCH(version, VersionBCHPoly), LengthECBits } - }; + private static BitList VersionInfoBitList(int version) + { + BitList result = new() + { + { version, LengthDataBits }, + { BCHCalculator.CalculateBCH(version, VersionBCHPoly), LengthECBits } + }; - if (result.Count != (LengthECBits + LengthDataBits)) - { - throw new Exception("Version Info creation error. Result is not 18 bits"); - } + if (result.Count != (LengthECBits + LengthDataBits)) + { + throw new Exception("Version Info creation error. Result is not 18 bits"); + } - return result; - } -} + return result; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrection/ECGenerator.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrection/ECGenerator.cs index b9a3dff..b1c6b10 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrection/ECGenerator.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrection/ECGenerator.cs @@ -1,84 +1,82 @@ using Gma.QrCodeNet.Encoding.ReedSolomon; -using System; -using System.Collections.Generic; namespace Gma.QrCodeNet.Encoding.ErrorCorrection; internal static class ECGenerator { - internal static BitList FillECCodewords(BitList dataCodewords, VersionDetail vd) - { - List dataCodewordsByte = dataCodewords.List; + internal static BitList FillECCodewords(BitList dataCodewords, VersionDetail vd) + { + List dataCodewordsByte = dataCodewords.List; - int ecBlockGroup1 = vd.ECBlockGroup1; - int numDataBytesGroup1 = vd.NumDataBytesGroup1; - int numDataBytesGroup2 = vd.NumDataBytesGroup2; + int ecBlockGroup1 = vd.ECBlockGroup1; + int numDataBytesGroup1 = vd.NumDataBytesGroup1; + int numDataBytesGroup2 = vd.NumDataBytesGroup2; - int ecBytesPerBlock = vd.NumECBytesPerBlock; + int ecBytesPerBlock = vd.NumECBytesPerBlock; - int dataBytesOffset = 0; - byte[][] dByteJArray = new byte[vd.NumECBlocks][]; - byte[][] ecByteJArray = new byte[vd.NumECBlocks][]; + int dataBytesOffset = 0; + byte[][] dByteJArray = new byte[vd.NumECBlocks][]; + byte[][] ecByteJArray = new byte[vd.NumECBlocks][]; - GaloisField256 gf256 = GaloisField256.QRCodeGaloisField; - GeneratorPolynomial generator = new(gf256); + GaloisField256 gf256 = GaloisField256.QRCodeGaloisField; + GeneratorPolynomial generator = new(gf256); - for (int blockId = 0; blockId < vd.NumECBlocks; blockId++) - { - if (blockId < ecBlockGroup1) - { - dByteJArray[blockId] = new byte[numDataBytesGroup1]; - for (int index = 0; index < numDataBytesGroup1; index++) - { - dByteJArray[blockId][index] = dataCodewordsByte[dataBytesOffset + index]; - } - dataBytesOffset += numDataBytesGroup1; - } - else - { - dByteJArray[blockId] = new byte[numDataBytesGroup2]; - for (int index = 0; index < numDataBytesGroup2; index++) - { - dByteJArray[blockId][index] = dataCodewordsByte[dataBytesOffset + index]; - } - dataBytesOffset += numDataBytesGroup2; - } + for (int blockId = 0; blockId < vd.NumECBlocks; blockId++) + { + if (blockId < ecBlockGroup1) + { + dByteJArray[blockId] = new byte[numDataBytesGroup1]; + for (int index = 0; index < numDataBytesGroup1; index++) + { + dByteJArray[blockId][index] = dataCodewordsByte[dataBytesOffset + index]; + } + dataBytesOffset += numDataBytesGroup1; + } + else + { + dByteJArray[blockId] = new byte[numDataBytesGroup2]; + for (int index = 0; index < numDataBytesGroup2; index++) + { + dByteJArray[blockId][index] = dataCodewordsByte[dataBytesOffset + index]; + } + dataBytesOffset += numDataBytesGroup2; + } - ecByteJArray[blockId] = ReedSolomonEncoder.Encode(dByteJArray[blockId], ecBytesPerBlock, generator); - } - if (vd.NumDataBytes != dataBytesOffset) - { - throw new ArgumentException("Data bytes do not match offset"); - } + ecByteJArray[blockId] = ReedSolomonEncoder.Encode(dByteJArray[blockId], ecBytesPerBlock, generator); + } + if (vd.NumDataBytes != dataBytesOffset) + { + throw new ArgumentException("Data bytes do not match offset"); + } - BitList codewords = new(); + BitList codewords = new(); - int maxDataLength = ecBlockGroup1 == vd.NumECBlocks ? numDataBytesGroup1 : numDataBytesGroup2; + int maxDataLength = ecBlockGroup1 == vd.NumECBlocks ? numDataBytesGroup1 : numDataBytesGroup2; - for (int dataId = 0; dataId < maxDataLength; dataId++) - { - for (int blockId = 0; blockId < vd.NumECBlocks; blockId++) - { - if (!(dataId == numDataBytesGroup1 && blockId < ecBlockGroup1)) - { - codewords.Add(dByteJArray[blockId][dataId], 8); - } - } - } + for (int dataId = 0; dataId < maxDataLength; dataId++) + { + for (int blockId = 0; blockId < vd.NumECBlocks; blockId++) + { + if (!(dataId == numDataBytesGroup1 && blockId < ecBlockGroup1)) + { + codewords.Add(dByteJArray[blockId][dataId], 8); + } + } + } - for (int ecId = 0; ecId < ecBytesPerBlock; ecId++) - { - for (int blockId = 0; blockId < vd.NumECBlocks; blockId++) - { - codewords.Add(ecByteJArray[blockId][ecId], 8); - } - } + for (int ecId = 0; ecId < ecBytesPerBlock; ecId++) + { + for (int blockId = 0; blockId < vd.NumECBlocks; blockId++) + { + codewords.Add(ecByteJArray[blockId][ecId], 8); + } + } - if (vd.NumTotalBytes != codewords.Count >> 3) - { - throw new ArgumentException($"Total bytes: {vd.NumTotalBytes}. Actual bits: {codewords.Count}"); - } + if (vd.NumTotalBytes != codewords.Count >> 3) + { + throw new ArgumentException($"Total bytes: {vd.NumTotalBytes}. Actual bits: {codewords.Count}"); + } - return codewords; - } -} + return codewords; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrectionLevel.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrectionLevel.cs index 8fb6fb2..37e12cc 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrectionLevel.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ErrorCorrectionLevel.cs @@ -2,8 +2,8 @@ namespace Gma.QrCodeNet.Encoding; public enum ErrorCorrectionLevel { - L, - M, - Q, - H -} + L, + M, + Q, + H +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/InputOutOfBoundaryException.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/InputOutOfBoundaryException.cs index ffd2890..cfc7982 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/InputOutOfBoundaryException.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/InputOutOfBoundaryException.cs @@ -1,5 +1,3 @@ -using System; - namespace Gma.QrCodeNet.Encoding; /// @@ -7,11 +5,11 @@ namespace Gma.QrCodeNet.Encoding; /// public class InputOutOfBoundaryException : Exception { - public InputOutOfBoundaryException() : base() - { - } + public InputOutOfBoundaryException() : base() + { + } - public InputOutOfBoundaryException(string message) : base(message) - { - } -} + public InputOutOfBoundaryException(string message) : base(message) + { + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MaskPatternType.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MaskPatternType.cs index f95f6ab..b98fef9 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MaskPatternType.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MaskPatternType.cs @@ -2,12 +2,12 @@ namespace Gma.QrCodeNet.Encoding.Masking; public enum MaskPatternType { - Type0 = 0, - Type1 = 1, - Type2 = 2, - Type3 = 3, - Type4 = 4, - Type5 = 5, - Type6 = 6, - Type7 = 7 -} + Type0 = 0, + Type1 = 1, + Type2 = 2, + Type3 = 3, + Type4 = 4, + Type5 = 5, + Type6 = 6, + Type7 = 7 +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MatrixExtensions.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MatrixExtensions.cs index fa8c1eb..350a37a 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MatrixExtensions.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/MatrixExtensions.cs @@ -1,44 +1,43 @@ -using System; using Gma.QrCodeNet.Encoding.EncodingRegion; namespace Gma.QrCodeNet.Encoding.Masking; public static class MatrixExtensions { - public static TriStateMatrix Xor(this TriStateMatrix first, Pattern second, ErrorCorrectionLevel errorLevel) - { - TriStateMatrix result = XorMatrix(first, second); - result.EmbedFormatInformation(errorLevel, second); - return result; - } + public static TriStateMatrix Xor(this TriStateMatrix first, Pattern second, ErrorCorrectionLevel errorLevel) + { + TriStateMatrix result = XorMatrix(first, second); + result.EmbedFormatInformation(errorLevel, second); + return result; + } - private static TriStateMatrix XorMatrix(TriStateMatrix first, BitMatrix second) - { - int width = first.Width; - TriStateMatrix maskedMatrix = new(width); - for (int x = 0; x < width; x++) - { - for (int y = 0; y < width; y++) - { - MatrixStatus states = first.MStatus(x, y); - switch (states) - { - case MatrixStatus.NoMask: - maskedMatrix[x, y, MatrixStatus.NoMask] = first[x, y]; - break; + private static TriStateMatrix XorMatrix(TriStateMatrix first, BitMatrix second) + { + int width = first.Width; + TriStateMatrix maskedMatrix = new(width); + for (int x = 0; x < width; x++) + { + for (int y = 0; y < width; y++) + { + MatrixStatus states = first.MStatus(x, y); + switch (states) + { + case MatrixStatus.NoMask: + maskedMatrix[x, y, MatrixStatus.NoMask] = first[x, y]; + break; - case MatrixStatus.Data: - maskedMatrix[x, y, MatrixStatus.Data] = first[x, y] ^ second[x, y]; - break; + case MatrixStatus.Data: + maskedMatrix[x, y, MatrixStatus.Data] = first[x, y] ^ second[x, y]; + break; - default: - throw new ArgumentException($"{nameof(TriStateMatrix)} has None value cell.", nameof(first)); - } - } - } + default: + throw new ArgumentException($"{nameof(TriStateMatrix)} has None value cell.", nameof(first)); + } + } + } - return maskedMatrix; - } + return maskedMatrix; + } - public static TriStateMatrix Apply(this TriStateMatrix matrix, Pattern pattern, ErrorCorrectionLevel errorLevel) => matrix.Xor(pattern, errorLevel); -} + public static TriStateMatrix Apply(this TriStateMatrix matrix, Pattern pattern, ErrorCorrectionLevel errorLevel) => matrix.Xor(pattern, errorLevel); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern.cs index ee5a3e3..6303438 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern.cs @@ -1,13 +1,11 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; public abstract class Pattern : BitMatrix { - public override int Width => throw new NotSupportedException(); - public override int Height => throw new NotSupportedException(); + public override int Width => throw new NotSupportedException(); + public override int Height => throw new NotSupportedException(); - public override bool[,] InternalArray => throw new NotImplementedException(); + public override bool[,] InternalArray => throw new NotImplementedException(); - public abstract MaskPatternType MaskPatternType { get; } -} + public abstract MaskPatternType MaskPatternType { get; } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern0.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern0.cs index 7134912..1e5d594 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern0.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern0.cs @@ -1,14 +1,12 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern0 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type0; + public override MaskPatternType MaskPatternType => MaskPatternType.Type0; - public override bool this[int i, int j] - { - get => (j + i) % 2 == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => (j + i) % 2 == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern1.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern1.cs index 63903ac..3f94b65 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern1.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern1.cs @@ -1,14 +1,12 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern1 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type1; + public override MaskPatternType MaskPatternType => MaskPatternType.Type1; - public override bool this[int i, int j] - { - get => j % 2 == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => j % 2 == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern2.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern2.cs index 0bf6e3b..a170fb5 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern2.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern2.cs @@ -1,14 +1,12 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern2 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type2; + public override MaskPatternType MaskPatternType => MaskPatternType.Type2; - public override bool this[int i, int j] - { - get => i % 3 == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => i % 3 == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern3.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern3.cs index ce9d7f3..7a9cf83 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern3.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern3.cs @@ -1,14 +1,12 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern3 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type3; + public override MaskPatternType MaskPatternType => MaskPatternType.Type3; - public override bool this[int i, int j] - { - get => (j + i) % 3 == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => (j + i) % 3 == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern4.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern4.cs index 6da839c..1ce0521 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern4.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern4.cs @@ -1,14 +1,12 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern4 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type4; + public override MaskPatternType MaskPatternType => MaskPatternType.Type4; - public override bool this[int i, int j] - { - get => ((j / 2) + (i / 3)) % 2 == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => ((j / 2) + (i / 3)) % 2 == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern5.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern5.cs index 632aba3..ab62f07 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern5.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern5.cs @@ -1,14 +1,12 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern5 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type5; + public override MaskPatternType MaskPatternType => MaskPatternType.Type5; - public override bool this[int i, int j] - { - get => (((i * j) % 2) + ((i * j) % 3)) == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => (((i * j) % 2) + ((i * j) % 3)) == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern6.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern6.cs index 7ad6eeb..69cde6f 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern6.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern6.cs @@ -1,13 +1,12 @@ -using System; namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern6 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type6; + public override MaskPatternType MaskPatternType => MaskPatternType.Type6; - public override bool this[int i, int j] - { - get => ((((i * j) % 2) + ((i * j) % 3)) % 2) == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => ((((i * j) % 2) + ((i * j) % 3)) % 2) == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern7.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern7.cs index d70b05c..4e1f436 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern7.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Pattern7.cs @@ -1,14 +1,12 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking; internal class Pattern7 : Pattern { - public override MaskPatternType MaskPatternType => MaskPatternType.Type7; + public override MaskPatternType MaskPatternType => MaskPatternType.Type7; - public override bool this[int i, int j] - { - get => (((i * j) % 3) + (((i + j) % 2) % 2)) == 0; - set => throw new NotSupportedException(); - } -} + public override bool this[int i, int j] + { + get => (((i * j) % 3) + (((i + j) % 2) % 2)) == 0; + set => throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/PatternFactory.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/PatternFactory.cs index 986c541..4a5de40 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/PatternFactory.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/PatternFactory.cs @@ -1,31 +1,28 @@ -using System; -using System.Collections.Generic; - namespace Gma.QrCodeNet.Encoding.Masking; internal class PatternFactory { - internal Pattern CreateByType(MaskPatternType maskPatternType) - { - return maskPatternType switch - { - MaskPatternType.Type0 => new Pattern0(), - MaskPatternType.Type1 => new Pattern1(), - MaskPatternType.Type2 => new Pattern2(), - MaskPatternType.Type3 => new Pattern3(), - MaskPatternType.Type4 => new Pattern4(), - MaskPatternType.Type5 => new Pattern5(), - MaskPatternType.Type6 => new Pattern6(), - MaskPatternType.Type7 => new Pattern7(), - _ => throw new NotSupportedException("This should never happen.") - }; - } + internal Pattern CreateByType(MaskPatternType maskPatternType) + { + return maskPatternType switch + { + MaskPatternType.Type0 => new Pattern0(), + MaskPatternType.Type1 => new Pattern1(), + MaskPatternType.Type2 => new Pattern2(), + MaskPatternType.Type3 => new Pattern3(), + MaskPatternType.Type4 => new Pattern4(), + MaskPatternType.Type5 => new Pattern5(), + MaskPatternType.Type6 => new Pattern6(), + MaskPatternType.Type7 => new Pattern7(), + _ => throw new NotSupportedException("This should never happen.") + }; + } - internal IEnumerable AllPatterns() - { - foreach (MaskPatternType patternType in Enum.GetValues(typeof(MaskPatternType))) - { - yield return CreateByType(patternType); - } - } -} + internal IEnumerable AllPatterns() + { + foreach (MaskPatternType patternType in Enum.GetValues(typeof(MaskPatternType))) + { + yield return CreateByType(patternType); + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/MatrixScoreCalculator.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/MatrixScoreCalculator.cs index 1105279..2b5fd5a 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/MatrixScoreCalculator.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/MatrixScoreCalculator.cs @@ -1,36 +1,34 @@ -using System.Linq; - namespace Gma.QrCodeNet.Encoding.Masking.Scoring; internal static class MatrixScoreCalculator { - internal static BitMatrix GetLowestPenaltyMatrix(this TriStateMatrix matrix, ErrorCorrectionLevel errorLevel) - { - PatternFactory patternFactory = new(); - int score = int.MaxValue; - int tempScore; - TriStateMatrix result = new(matrix.Width); - TriStateMatrix triMatrix; - foreach (Pattern pattern in patternFactory.AllPatterns()) - { - triMatrix = matrix.Apply(pattern, errorLevel); - tempScore = triMatrix.PenaltyScore(); - if (tempScore < score) - { - score = tempScore; - result = triMatrix; - } - } + internal static BitMatrix GetLowestPenaltyMatrix(this TriStateMatrix matrix, ErrorCorrectionLevel errorLevel) + { + PatternFactory patternFactory = new(); + int score = int.MaxValue; + int tempScore; + TriStateMatrix result = new(matrix.Width); + TriStateMatrix triMatrix; + foreach (Pattern pattern in patternFactory.AllPatterns()) + { + triMatrix = matrix.Apply(pattern, errorLevel); + tempScore = triMatrix.PenaltyScore(); + if (tempScore < score) + { + score = tempScore; + result = triMatrix; + } + } - return result; - } + return result; + } - internal static int PenaltyScore(this BitMatrix matrix) - { - PenaltyFactory penaltyFactory = new(); - return - penaltyFactory - .AllRules() - .Sum(penalty => penalty.PenaltyCalculate(matrix)); - } -} + internal static int PenaltyScore(this BitMatrix matrix) + { + PenaltyFactory penaltyFactory = new(); + return + penaltyFactory + .AllRules() + .Sum(penalty => penalty.PenaltyCalculate(matrix)); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty.cs index 761e5a4..39b000f 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty.cs @@ -2,5 +2,5 @@ namespace Gma.QrCodeNet.Encoding.Masking.Scoring; public abstract class Penalty { - internal abstract int PenaltyCalculate(BitMatrix matrix); -} + internal abstract int PenaltyCalculate(BitMatrix matrix); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty1.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty1.cs index ff80b32..c8be43e 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty1.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty1.cs @@ -5,81 +5,81 @@ namespace Gma.QrCodeNet.Encoding.Masking.Scoring; /// internal class Penalty1 : Penalty { - /// - /// Calculate penalty value for first rule. - /// - internal override int PenaltyCalculate(BitMatrix matrix) - { - int penaltyValue = PenaltyCalculation(matrix, true) + PenaltyCalculation(matrix, false); - return penaltyValue; - } + /// + /// Calculate penalty value for first rule. + /// + internal override int PenaltyCalculate(BitMatrix matrix) + { + int penaltyValue = PenaltyCalculation(matrix, true) + PenaltyCalculation(matrix, false); + return penaltyValue; + } - private int PenaltyCalculation(BitMatrix matrix, bool isHorizontal) - { - int penalty = 0; - int width = matrix.Width; + private int PenaltyCalculation(BitMatrix matrix, bool isHorizontal) + { + int penalty = 0; + int width = matrix.Width; - int i = 0; - int j = 0; + int i = 0; + int j = 0; - while (i < width) - { - while (j < width - 4) - { - bool preBit = isHorizontal - ? matrix[j + 4, i] - : matrix[i, j + 4]; - int numSameBitCell = 1; + while (i < width) + { + while (j < width - 4) + { + bool preBit = isHorizontal + ? matrix[j + 4, i] + : matrix[i, j + 4]; + int numSameBitCell = 1; - for (int x = 1; x <= 4; x++) - { - bool bit = isHorizontal - ? matrix[j + 4 - x, i] - : matrix[i, j + 4 - x]; - if (bit == preBit) - { - numSameBitCell++; - } - else - { - break; - } - } + for (int x = 1; x <= 4; x++) + { + bool bit = isHorizontal + ? matrix[j + 4 - x, i] + : matrix[i, j + 4 - x]; + if (bit == preBit) + { + numSameBitCell++; + } + else + { + break; + } + } - if (numSameBitCell == 1) - { - j += 4; - } - else - { - int x = 5; - while ((j + x) < width) - { - bool bit = isHorizontal - ? matrix[j + x, i] - : matrix[i, j + x]; - if (bit == preBit) - { - numSameBitCell++; - } - else - { - break; - } - x++; - } - if (numSameBitCell >= 5) - { - penalty += (3 + (numSameBitCell - 5)); - } + if (numSameBitCell == 1) + { + j += 4; + } + else + { + int x = 5; + while ((j + x) < width) + { + bool bit = isHorizontal + ? matrix[j + x, i] + : matrix[i, j + x]; + if (bit == preBit) + { + numSameBitCell++; + } + else + { + break; + } + x++; + } + if (numSameBitCell >= 5) + { + penalty += (3 + (numSameBitCell - 5)); + } - j += x; - } - } - j = 0; - i++; - } + j += x; + } + } + j = 0; + i++; + } - return penalty; - } -} + return penalty; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty2.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty2.cs index f99e6d8..283da24 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty2.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty2.cs @@ -5,47 +5,47 @@ namespace Gma.QrCodeNet.Encoding.Masking.Scoring; /// internal class Penalty2 : Penalty { - internal override int PenaltyCalculate(BitMatrix matrix) - { - int width = matrix.Width; - int x = 0; - int y = 0; - int penalty = 0; + internal override int PenaltyCalculate(BitMatrix matrix) + { + int width = matrix.Width; + int x = 0; + int y = 0; + int penalty = 0; - while (y < (width - 1)) - { - while (x < (width - 1)) - { - bool topR = matrix[x + 1, y]; + while (y < (width - 1)) + { + while (x < (width - 1)) + { + bool topR = matrix[x + 1, y]; - if (topR == matrix[x + 1, y + 1]) // Bottom Right - { - if (topR == matrix[x, y + 1]) // Bottom Left - { - if (topR == matrix[x, y]) // Top Left - { - penalty += 3; - x += 1; - } - else - { - x += 1; - } - } - else - { - x += 1; - } - } - else - { - x += 2; - } - } + if (topR == matrix[x + 1, y + 1]) // Bottom Right + { + if (topR == matrix[x, y + 1]) // Bottom Left + { + if (topR == matrix[x, y]) // Top Left + { + penalty += 3; + x += 1; + } + else + { + x += 1; + } + } + else + { + x += 1; + } + } + else + { + x += 2; + } + } - x = 0; - y++; - } - return penalty; - } -} + x = 0; + y++; + } + return penalty; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty3.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty3.cs index 4b0ce1b..7bc285f 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty3.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty3.cs @@ -5,137 +5,137 @@ namespace Gma.QrCodeNet.Encoding.Masking.Scoring; /// internal class Penalty3 : Penalty { - /// - /// Calculate penalty value for Third rule. - /// - internal override int PenaltyCalculate(BitMatrix matrix) => PenaltyCalculation(matrix, true) + PenaltyCalculation(matrix, false); + /// + /// Calculate penalty value for Third rule. + /// + internal override int PenaltyCalculate(BitMatrix matrix) => PenaltyCalculation(matrix, true) + PenaltyCalculation(matrix, false); - private int PenaltyCalculation(BitMatrix matrix, bool isHorizontal) - { - int i = 0; - int j = 1; - int penalty = 0; - int width = matrix.Width; - bool bit; - while (i < width) - { - while (j < width - 5) - { - bit = isHorizontal - ? matrix[j + 4, i] - : matrix[i, j + 4]; - if (!bit) - { - bit = isHorizontal - ? matrix[j, i] - : matrix[i, j]; - if (!bit) - { - penalty += PatternCheck(matrix, i, j, isHorizontal); - j += 4; - } - else - { - j += 4; - } - } - else - { - for (int num = 4; num > 0; num--) - { - bit = isHorizontal - ? matrix[j + num, i] - : matrix[i, j + num]; - if (!bit) - { - j += num; - break; - } - if (num == 1) - { - j += 5; - } - } - } - } - j = 0; - i++; - } - return penalty; - } + private int PenaltyCalculation(BitMatrix matrix, bool isHorizontal) + { + int i = 0; + int j = 1; + int penalty = 0; + int width = matrix.Width; + bool bit; + while (i < width) + { + while (j < width - 5) + { + bit = isHorizontal + ? matrix[j + 4, i] + : matrix[i, j + 4]; + if (!bit) + { + bit = isHorizontal + ? matrix[j, i] + : matrix[i, j]; + if (!bit) + { + penalty += PatternCheck(matrix, i, j, isHorizontal); + j += 4; + } + else + { + j += 4; + } + } + else + { + for (int num = 4; num > 0; num--) + { + bit = isHorizontal + ? matrix[j + num, i] + : matrix[i, j + num]; + if (!bit) + { + j += num; + break; + } + if (num == 1) + { + j += 5; + } + } + } + } + j = 0; + i++; + } + return penalty; + } - private int PatternCheck(BitMatrix matrix, int i, int j, bool isHorizontal) - { - bool bit; - for (int num = 3; num >= 1; num--) - { - bit = isHorizontal - ? matrix[j + num, i] - : matrix[i, j + num]; - if (!bit) - { - return 0; - } - } + private int PatternCheck(BitMatrix matrix, int i, int j, bool isHorizontal) + { + bool bit; + for (int num = 3; num >= 1; num--) + { + bit = isHorizontal + ? matrix[j + num, i] + : matrix[i, j + num]; + if (!bit) + { + return 0; + } + } - // Check for left side and right side x ( xoxxxox ). - if ((j - 1) < 0 || (j + 1) >= matrix.Width) - { - return 0; - } + // Check for left side and right side x ( xoxxxox ). + if ((j - 1) < 0 || (j + 1) >= matrix.Width) + { + return 0; + } - bit = isHorizontal - ? matrix[j + 5, i] - : matrix[i, j + 5]; - if (!bit) - { - return 0; - } + bit = isHorizontal + ? matrix[j + 5, i] + : matrix[i, j + 5]; + if (!bit) + { + return 0; + } - bit = isHorizontal - ? matrix[j - 1, i] - : matrix[i, j - 1]; - if (!bit) - { - return 0; - } + bit = isHorizontal + ? matrix[j - 1, i] + : matrix[i, j - 1]; + if (!bit) + { + return 0; + } - if ((j - 5) >= 0) - { - for (int num = -2; num >= -5; num--) - { - bit = isHorizontal - ? matrix[j + num, i] - : matrix[i, j + num]; - if (bit) - { - break; - } + if ((j - 5) >= 0) + { + for (int num = -2; num >= -5; num--) + { + bit = isHorizontal + ? matrix[j + num, i] + : matrix[i, j + num]; + if (bit) + { + break; + } - if (num == -5) - { - return 40; - } - } - } + if (num == -5) + { + return 40; + } + } + } - if ((j + 9) < matrix.Width) - { - for (int num = 6; num <= 9; num++) - { - bit = isHorizontal - ? matrix[j + num, i] - : matrix[i, j + num]; - if (bit) - { - return 0; - } - } - return 40; - } - else - { - return 0; - } - } -} + if ((j + 9) < matrix.Width) + { + for (int num = 6; num <= 9; num++) + { + bit = isHorizontal + ? matrix[j + num, i] + : matrix[i, j + num]; + if (bit) + { + return 0; + } + } + return 40; + } + else + { + return 0; + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty4.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty4.cs index 88382f5..0eeab71 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty4.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/Penalty4.cs @@ -1,5 +1,3 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Masking.Scoring; /// @@ -7,30 +5,30 @@ namespace Gma.QrCodeNet.Encoding.Masking.Scoring; /// internal class Penalty4 : Penalty { - /// - /// Calculate penalty value for Fourth rule. - /// Perform O(n) search for available x modules - /// - internal override int PenaltyCalculate(BitMatrix matrix) - { - int width = matrix.Width; - int darkBitCount = 0; + /// + /// Calculate penalty value for Fourth rule. + /// Perform O(n) search for available x modules + /// + internal override int PenaltyCalculate(BitMatrix matrix) + { + int width = matrix.Width; + int darkBitCount = 0; - for (int j = 0; j < width; j++) - { - for (int i = 0; i < width; i++) - { - if (matrix[i, j]) - { - darkBitCount++; - } - } - } + for (int j = 0; j < width; j++) + { + for (int i = 0; i < width; i++) + { + if (matrix[i, j]) + { + darkBitCount++; + } + } + } - int matrixCount = width * width; + int matrixCount = width * width; - double ratio = (double)darkBitCount / matrixCount; + double ratio = (double)darkBitCount / matrixCount; - return Math.Abs((int)((ratio * 100) - 50)) / 5 * 10; - } -} + return Math.Abs((int)((ratio * 100) - 50)) / 5 * 10; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyFactory.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyFactory.cs index 36d1797..691933a 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyFactory.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyFactory.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; - namespace Gma.QrCodeNet.Encoding.Masking.Scoring; /// @@ -8,23 +5,23 @@ namespace Gma.QrCodeNet.Encoding.Masking.Scoring; /// internal class PenaltyFactory { - internal Penalty CreateByRule(PenaltyRules penaltyRule) - { - return penaltyRule switch - { - PenaltyRules.Rule01 => new Penalty1(), - PenaltyRules.Rule02 => new Penalty2(), - PenaltyRules.Rule03 => new Penalty3(), - PenaltyRules.Rule04 => new Penalty4(), - _ => throw new ArgumentException($"Unsupport penalty rule: {penaltyRule}", nameof(penaltyRule)) - }; - } + internal Penalty CreateByRule(PenaltyRules penaltyRule) + { + return penaltyRule switch + { + PenaltyRules.Rule01 => new Penalty1(), + PenaltyRules.Rule02 => new Penalty2(), + PenaltyRules.Rule03 => new Penalty3(), + PenaltyRules.Rule04 => new Penalty4(), + _ => throw new ArgumentException($"Unsupport penalty rule: {penaltyRule}", nameof(penaltyRule)) + }; + } - internal IEnumerable AllRules() - { - foreach (PenaltyRules penaltyRule in Enum.GetValues(typeof(PenaltyRules))) - { - yield return CreateByRule(penaltyRule); - } - } -} + internal IEnumerable AllRules() + { + foreach (PenaltyRules penaltyRule in Enum.GetValues(typeof(PenaltyRules))) + { + yield return CreateByRule(penaltyRule); + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyRules.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyRules.cs index 3cac9ed..c58ae1e 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyRules.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Masking/Scoring/PenaltyRules.cs @@ -2,8 +2,8 @@ namespace Gma.QrCodeNet.Encoding.Masking.Scoring; public enum PenaltyRules { - Rule01 = 1, - Rule02 = 2, - Rule03 = 3, - Rule04 = 4 -} + Rule01 = 1, + Rule02 = 2, + Rule03 = 3, + Rule04 = 4 +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixPoint.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixPoint.cs index 66f73de..9f5cac9 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixPoint.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixPoint.cs @@ -2,19 +2,19 @@ namespace Gma.QrCodeNet.Encoding; public struct MatrixPoint { - internal MatrixPoint(int x, int y) - : this() - { - X = x; - Y = y; - } + internal MatrixPoint(int x, int y) + : this() + { + X = x; + Y = y; + } - public int X { get; private set; } - public int Y { get; private set; } + public int X { get; private set; } + public int Y { get; private set; } - public MatrixPoint Offset(MatrixPoint offset) => new(offset.X + X, offset.Y + Y); + public MatrixPoint Offset(MatrixPoint offset) => new(offset.X + X, offset.Y + Y); - internal MatrixPoint Offset(int offsetX, int offsetY) => Offset(new MatrixPoint(offsetX, offsetY)); + internal MatrixPoint Offset(int offsetX, int offsetY) => Offset(new MatrixPoint(offsetX, offsetY)); - public override string ToString() => $"Point({X};{Y})"; -} + public override string ToString() => $"Point({X};{Y})"; +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixRectangle.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixRectangle.cs index 2a9b202..b3e62cf 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixRectangle.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixRectangle.cs @@ -1,32 +1,31 @@ using System.Collections; -using System.Collections.Generic; namespace Gma.QrCodeNet.Encoding; internal struct MatrixRectangle : IEnumerable { - internal MatrixRectangle(MatrixPoint location, MatrixSize size) : - this() - { - Location = location; - Size = size; - } + internal MatrixRectangle(MatrixPoint location, MatrixSize size) : + this() + { + Location = location; + Size = size; + } - public MatrixPoint Location { get; private set; } - public MatrixSize Size { get; private set; } + public MatrixPoint Location { get; private set; } + public MatrixSize Size { get; private set; } - public IEnumerator GetEnumerator() - { - for (int j = Location.Y; j < Location.Y + Size.Height; j++) - { - for (int i = Location.X; i < Location.X + Size.Width; i++) - { - yield return new MatrixPoint(i, j); - } - } - } + public IEnumerator GetEnumerator() + { + for (int j = Location.Y; j < Location.Y + Size.Height; j++) + { + for (int i = Location.X; i < Location.X + Size.Width; i++) + { + yield return new MatrixPoint(i, j); + } + } + } - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public override string ToString() => $"Rectangle({Location.X};{Location.Y}):({Size.Width} x {Size.Height})"; -} + public override string ToString() => $"Rectangle({Location.X};{Location.Y}):({Size.Width} x {Size.Height})"; +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixSize.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixSize.cs index cc6b2b3..a5b2705 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixSize.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixSize.cs @@ -2,18 +2,18 @@ namespace Gma.QrCodeNet.Encoding; public struct MatrixSize { - internal MatrixSize(int width, int height) - : this() - { - Width = width; - Height = height; - } + internal MatrixSize(int width, int height) + : this() + { + Width = width; + Height = height; + } - public int Width { get; private set; } - public int Height { get; private set; } + public int Width { get; private set; } + public int Height { get; private set; } - public override string ToString() - { - return $"Size({Width};{Height})"; - } -} + public override string ToString() + { + return $"Size({Width};{Height})"; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixStatus.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixStatus.cs index 4cd3647..d996b40 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixStatus.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/MatrixStatus.cs @@ -2,7 +2,7 @@ namespace Gma.QrCodeNet.Encoding; public enum MatrixStatus { - None, - NoMask, - Data -} + None, + NoMask, + Data +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/PositioninngPatternBuilder.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/PositioninngPatternBuilder.cs index 3d695cb..d33bb0b 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/PositioninngPatternBuilder.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/PositioninngPatternBuilder.cs @@ -4,11 +4,11 @@ namespace Gma.QrCodeNet.Encoding.Positioning; internal static class PositioningPatternBuilder { - internal static void EmbedBasicPatterns(int version, TriStateMatrix matrix) - { - new PositionDetectionPattern(version).ApplyTo(matrix); - new DarkDotAtLeftBottom(version).ApplyTo(matrix); - new AlignmentPattern(version).ApplyTo(matrix); - new TimingPattern(version).ApplyTo(matrix); - } -} + internal static void EmbedBasicPatterns(int version, TriStateMatrix matrix) + { + new PositionDetectionPattern(version).ApplyTo(matrix); + new DarkDotAtLeftBottom(version).ApplyTo(matrix); + new AlignmentPattern(version).ApplyTo(matrix); + new TimingPattern(version).ApplyTo(matrix); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/AlignmentPattern.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/AlignmentPattern.cs index 17c8b7e..ed186b1 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/AlignmentPattern.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/AlignmentPattern.cs @@ -1,105 +1,101 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Gma.QrCodeNet.Encoding.Positioning.Stencils; internal class AlignmentPattern : PatternStencilBase { - public AlignmentPattern(int version) - : base(version) - { - } + public AlignmentPattern(int version) + : base(version) + { + } - private static bool[,] AlignmentPatternArray { get; } = - new[,] - { - { X, X, X, X, X }, - { X, O, O, O, X }, - { X, O, X, O, X }, - { X, O, O, O, X }, - { X, X, X, X, X } - }; + private static bool[,] AlignmentPatternArray { get; } = + new[,] + { + { X, X, X, X, X }, + { X, O, O, O, X }, + { X, O, X, O, X }, + { X, O, O, O, X }, + { X, X, X, X, X } + }; - public override bool[,] Stencil => AlignmentPatternArray; + public override bool[,] Stencil => AlignmentPatternArray; - // Table E.1 — Row/column coordinates of center module of Alignment Patterns - private static byte[][] AlignmentPatternCoordinatesByVersion { get; } = - new[] - { - Array.Empty(), - Array.Empty(), - new byte[] { 6, 18 }, - new byte[] { 6, 22 }, - new byte[] { 6, 26 }, - new byte[] { 6, 30 }, - new byte[] { 6, 34 }, - new byte[] { 6, 22, 38 }, - new byte[] { 6, 24, 42 }, - new byte[] { 6, 26, 46 }, - new byte[] { 6, 28, 50 }, - new byte[] { 6, 30, 54 }, - new byte[] { 6, 32, 58 }, - new byte[] { 6, 34, 62 }, - new byte[] { 6, 26, 46, 66 }, - new byte[] { 6, 26, 48, 70 }, - new byte[] { 6, 26, 50, 74 }, - new byte[] { 6, 30, 54, 78 }, - new byte[] { 6, 30, 56, 82 }, - new byte[] { 6, 30, 58, 86 }, - new byte[] { 6, 34, 62, 90 }, - new byte[] { 6, 28, 50, 72, 94 }, - new byte[] { 6, 26, 50, 74, 98 }, - new byte[] { 6, 30, 54, 78, 102 }, - new byte[] { 6, 28, 54, 80, 106 }, - new byte[] { 6, 32, 58, 84, 110 }, - new byte[] { 6, 30, 58, 86, 114 }, - new byte[] { 6, 34, 62, 90, 118 }, - new byte[] { 6, 26, 50, 74, 98, 122 }, - new byte[] { 6, 30, 54, 78, 102, 126 }, - new byte[] { 6, 26, 52, 78, 104, 130 }, - new byte[] { 6, 30, 56, 82, 108, 134 }, - new byte[] { 6, 34, 60, 86, 112, 138 }, - new byte[] { 6, 30, 58, 86, 114, 142 }, - new byte[] { 6, 34, 62, 90, 118, 146 }, - new byte[] { 6, 30, 54, 78, 102, 126, 150 }, - new byte[] { 6, 24, 50, 76, 102, 128, 154 }, - new byte[] { 6, 28, 54, 80, 106, 132, 158 }, - new byte[] { 6, 32, 58, 84, 110, 136, 162 }, - new byte[] { 6, 26, 54, 82, 110, 138, 166 }, - new byte[] { 6, 30, 58, 86, 114, 142, 170 } - }; + // Table E.1 — Row/column coordinates of center module of Alignment Patterns + private static byte[][] AlignmentPatternCoordinatesByVersion { get; } = + new[] + { + Array.Empty(), + Array.Empty(), + new byte[] { 6, 18 }, + new byte[] { 6, 22 }, + new byte[] { 6, 26 }, + new byte[] { 6, 30 }, + new byte[] { 6, 34 }, + new byte[] { 6, 22, 38 }, + new byte[] { 6, 24, 42 }, + new byte[] { 6, 26, 46 }, + new byte[] { 6, 28, 50 }, + new byte[] { 6, 30, 54 }, + new byte[] { 6, 32, 58 }, + new byte[] { 6, 34, 62 }, + new byte[] { 6, 26, 46, 66 }, + new byte[] { 6, 26, 48, 70 }, + new byte[] { 6, 26, 50, 74 }, + new byte[] { 6, 30, 54, 78 }, + new byte[] { 6, 30, 56, 82 }, + new byte[] { 6, 30, 58, 86 }, + new byte[] { 6, 34, 62, 90 }, + new byte[] { 6, 28, 50, 72, 94 }, + new byte[] { 6, 26, 50, 74, 98 }, + new byte[] { 6, 30, 54, 78, 102 }, + new byte[] { 6, 28, 54, 80, 106 }, + new byte[] { 6, 32, 58, 84, 110 }, + new byte[] { 6, 30, 58, 86, 114 }, + new byte[] { 6, 34, 62, 90, 118 }, + new byte[] { 6, 26, 50, 74, 98, 122 }, + new byte[] { 6, 30, 54, 78, 102, 126 }, + new byte[] { 6, 26, 52, 78, 104, 130 }, + new byte[] { 6, 30, 56, 82, 108, 134 }, + new byte[] { 6, 34, 60, 86, 112, 138 }, + new byte[] { 6, 30, 58, 86, 114, 142 }, + new byte[] { 6, 34, 62, 90, 118, 146 }, + new byte[] { 6, 30, 54, 78, 102, 126, 150 }, + new byte[] { 6, 24, 50, 76, 102, 128, 154 }, + new byte[] { 6, 28, 54, 80, 106, 132, 158 }, + new byte[] { 6, 32, 58, 84, 110, 136, 162 }, + new byte[] { 6, 26, 54, 82, 110, 138, 166 }, + new byte[] { 6, 30, 58, 86, 114, 142, 170 } + }; - public override void ApplyTo(TriStateMatrix matrix) - { - foreach (MatrixPoint coordinatePair in GetNonColidingCoordinatePairs(matrix)) - { - CopyTo(matrix, coordinatePair, MatrixStatus.NoMask); - } - } + public override void ApplyTo(TriStateMatrix matrix) + { + foreach (MatrixPoint coordinatePair in GetNonColidingCoordinatePairs(matrix)) + { + CopyTo(matrix, coordinatePair, MatrixStatus.NoMask); + } + } - public IEnumerable GetNonColidingCoordinatePairs(TriStateMatrix matrix) - { - return - GetAllCoordinatePairs() - .Where(point => matrix.MStatus(point.Offset(2, 2)) == MatrixStatus.None); - } + public IEnumerable GetNonColidingCoordinatePairs(TriStateMatrix matrix) + { + return + GetAllCoordinatePairs() + .Where(point => matrix.MStatus(point.Offset(2, 2)) == MatrixStatus.None); + } - private IEnumerable GetAllCoordinatePairs() - { - IEnumerable coordinates = GetPatternCoordinatesByVersion(Version); - foreach (byte centerX in coordinates) - { - foreach (byte centerY in coordinates) - { - MatrixPoint location = new(centerX - 2, centerY - 2); - yield return location; - } - } - } + private IEnumerable GetAllCoordinatePairs() + { + IEnumerable coordinates = GetPatternCoordinatesByVersion(Version); + foreach (byte centerX in coordinates) + { + foreach (byte centerY in coordinates) + { + MatrixPoint location = new(centerX - 2, centerY - 2); + yield return location; + } + } + } - private static IEnumerable GetPatternCoordinatesByVersion(int version) - { - return AlignmentPatternCoordinatesByVersion[version]; - } -} + private static IEnumerable GetPatternCoordinatesByVersion(int version) + { + return AlignmentPatternCoordinatesByVersion[version]; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/DarkDotAtLeftBottom.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/DarkDotAtLeftBottom.cs index 829e3bc..f4747fd 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/DarkDotAtLeftBottom.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/DarkDotAtLeftBottom.cs @@ -1,17 +1,15 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Positioning.Stencils; internal class DarkDotAtLeftBottom : PatternStencilBase { - public DarkDotAtLeftBottom(int version) : base(version) - { - } + public DarkDotAtLeftBottom(int version) : base(version) + { + } - public override bool[,] Stencil => throw new NotImplementedException(); + public override bool[,] Stencil => throw new NotImplementedException(); - public override void ApplyTo(TriStateMatrix matrix) - { - matrix[8, matrix.Width - 8, MatrixStatus.NoMask] = true; - } -} + public override void ApplyTo(TriStateMatrix matrix) + { + matrix[8, matrix.Width - 8, MatrixStatus.NoMask] = true; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PatternStencilBase.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PatternStencilBase.cs index 874042e..a69c6c9 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PatternStencilBase.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PatternStencilBase.cs @@ -1,32 +1,30 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Positioning.Stencils; internal abstract class PatternStencilBase : BitMatrix { - protected const bool O = false; - protected const bool X = true; + protected const bool O = false; + protected const bool X = true; - internal PatternStencilBase(int version) - { - Version = version; - } + internal PatternStencilBase(int version) + { + Version = version; + } - public int Version { get; private set; } + public int Version { get; private set; } - public abstract bool[,] Stencil { get; } + public abstract bool[,] Stencil { get; } - public override int Width => Stencil.GetLength(0); + public override int Width => Stencil.GetLength(0); - public override int Height => Stencil.GetLength(1); + public override int Height => Stencil.GetLength(1); - public override bool[,] InternalArray => throw new NotImplementedException(); + public override bool[,] InternalArray => throw new NotImplementedException(); - public override bool this[int i, int j] - { - get => Stencil[i, j]; - set => throw new NotSupportedException(); - } + public override bool this[int i, int j] + { + get => Stencil[i, j]; + set => throw new NotSupportedException(); + } - public abstract void ApplyTo(TriStateMatrix matrix); -} + public abstract void ApplyTo(TriStateMatrix matrix); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PositionDetectionPattern.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PositionDetectionPattern.cs index 0ebb501..75fc45b 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PositionDetectionPattern.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/PositionDetectionPattern.cs @@ -2,40 +2,40 @@ namespace Gma.QrCodeNet.Encoding.Positioning.Stencils; internal class PositionDetectionPattern : PatternStencilBase { - public PositionDetectionPattern(int version) - : base(version) - { - } + public PositionDetectionPattern(int version) + : base(version) + { + } - private static bool[,] PositionDetection { get; } = - new[,] - { - { O, O, O, O, O, O, O, O, O }, - { O, X, X, X, X, X, X, X, O }, - { O, X, O, O, O, O, O, X, O }, - { O, X, O, X, X, X, O, X, O }, - { O, X, O, X, X, X, O, X, O }, - { O, X, O, X, X, X, O, X, O }, - { O, X, O, O, O, O, O, X, O }, - { O, X, X, X, X, X, X, X, O }, - { O, O, O, O, O, O, O, O, O } - }; + private static bool[,] PositionDetection { get; } = + new[,] + { + { O, O, O, O, O, O, O, O, O }, + { O, X, X, X, X, X, X, X, O }, + { O, X, O, O, O, O, O, X, O }, + { O, X, O, X, X, X, O, X, O }, + { O, X, O, X, X, X, O, X, O }, + { O, X, O, X, X, X, O, X, O }, + { O, X, O, O, O, O, O, X, O }, + { O, X, X, X, X, X, X, X, O }, + { O, O, O, O, O, O, O, O, O } + }; - public override bool[,] Stencil => PositionDetection; + public override bool[,] Stencil => PositionDetection; - public override void ApplyTo(TriStateMatrix matrix) - { - MatrixSize size = GetSizeOfSquareWithSeparators(); + public override void ApplyTo(TriStateMatrix matrix) + { + MatrixSize size = GetSizeOfSquareWithSeparators(); - MatrixPoint leftTopCorner = new(0, 0); - CopyTo(matrix, new MatrixRectangle(new MatrixPoint(1, 1), size), leftTopCorner, MatrixStatus.NoMask); + MatrixPoint leftTopCorner = new(0, 0); + CopyTo(matrix, new MatrixRectangle(new MatrixPoint(1, 1), size), leftTopCorner, MatrixStatus.NoMask); - MatrixPoint rightTopCorner = new(matrix.Width - Width + 1, 0); - CopyTo(matrix, new MatrixRectangle(new MatrixPoint(0, 1), size), rightTopCorner, MatrixStatus.NoMask); + MatrixPoint rightTopCorner = new(matrix.Width - Width + 1, 0); + CopyTo(matrix, new MatrixRectangle(new MatrixPoint(0, 1), size), rightTopCorner, MatrixStatus.NoMask); - MatrixPoint leftBottomCorner = new(0, matrix.Width - Width + 1); - CopyTo(matrix, new MatrixRectangle(new MatrixPoint(1, 0), size), leftBottomCorner, MatrixStatus.NoMask); - } + MatrixPoint leftBottomCorner = new(0, matrix.Width - Width + 1); + CopyTo(matrix, new MatrixRectangle(new MatrixPoint(1, 0), size), leftBottomCorner, MatrixStatus.NoMask); + } - private MatrixSize GetSizeOfSquareWithSeparators() => new(Width - 1, Height - 1); -} + private MatrixSize GetSizeOfSquareWithSeparators() => new(Width - 1, Height - 1); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/TimingPattern.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/TimingPattern.cs index 1cb2dd0..1847fe6 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/TimingPattern.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Positioning/Stencils/TimingPattern.cs @@ -1,35 +1,33 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Positioning.Stencils; internal class TimingPattern : PatternStencilBase { - public TimingPattern(int version) - : base(version) - { - } + public TimingPattern(int version) + : base(version) + { + } - public override bool[,] Stencil => throw new NotImplementedException(); + public override bool[,] Stencil => throw new NotImplementedException(); - public override void ApplyTo(TriStateMatrix matrix) - { - // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical - // separation patterns (size 1). Thus, 8 = 7 + 1. - for (int i = 8; i < matrix.Width - 8; ++i) - { - bool value = (sbyte)((i + 1) % 2) == 1; + public override void ApplyTo(TriStateMatrix matrix) + { + // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical + // separation patterns (size 1). Thus, 8 = 7 + 1. + for (int i = 8; i < matrix.Width - 8; ++i) + { + bool value = (sbyte)((i + 1) % 2) == 1; - // Horizontal line. - if (matrix.MStatus(6, i) == MatrixStatus.None) - { - matrix[6, i, MatrixStatus.NoMask] = value; - } + // Horizontal line. + if (matrix.MStatus(6, i) == MatrixStatus.None) + { + matrix[6, i, MatrixStatus.NoMask] = value; + } - // Vertical line. - if (matrix.MStatus(i, 6) == MatrixStatus.None) - { - matrix[i, 6, MatrixStatus.NoMask] = value; - } - } - } -} + // Vertical line. + if (matrix.MStatus(i, 6) == MatrixStatus.None) + { + matrix[i, 6, MatrixStatus.NoMask] = value; + } + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeConstantVariable.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeConstantVariable.cs index ca1518b..d2932cd 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeConstantVariable.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeConstantVariable.cs @@ -5,48 +5,48 @@ namespace Gma.QrCodeNet.Encoding; /// public static class QRCodeConstantVariable { - public const int MinVersion = 1; - public const int MaxVersion = 40; + public const int MinVersion = 1; + public const int MaxVersion = 40; - public const string DefaultEncoding = "iso-8859-1"; - public const string UTF8Encoding = "utf-8"; + public const string DefaultEncoding = "iso-8859-1"; + public const string UTF8Encoding = "utf-8"; - /// - /// ISO/IEC 18004:2006(E) Page 45 Chapter Generating the error correction codewords - /// Primative Polynomial = Bin 100011101 = Dec 285 - /// - public const int QRCodePrimitive = 285; + /// + /// ISO/IEC 18004:2006(E) Page 45 Chapter Generating the error correction codewords + /// Primative Polynomial = Bin 100011101 = Dec 285 + /// + public const int QRCodePrimitive = 285; - internal const int TerminatorNPaddingBit = 0; + internal const int TerminatorNPaddingBit = 0; - internal const int TerminatorLength = 4; + internal const int TerminatorLength = 4; - /// - /// 0xEC - /// - internal const int PadeCodewordsOdd = 0xec; + /// + /// 0xEC + /// + internal const int PadeCodewordsOdd = 0xec; - /// - /// 0x11 - /// - internal const int PadeCodewordsEven = 0x11; + /// + /// 0x11 + /// + internal const int PadeCodewordsEven = 0x11; - internal const int PositionStencilWidth = 7; + internal const int PositionStencilWidth = 7; - internal static bool[] PadeOdd = new bool[] - { - true, true, true, false, - true, true, false, false - }; + internal static bool[] PadeOdd = new bool[] + { + true, true, true, false, + true, true, false, false + }; - internal static bool[] PadeEven = new bool[] - { - false, false, false, true, - false, false, false, true - }; + internal static bool[] PadeEven = new bool[] + { + false, false, false, true, + false, false, false, true + }; - /// - /// URL:http://en.wikipedia.org/wiki/Byte-order_mark - /// - public static byte[] UTF8ByteOrderMark => new byte[] { 0xEF, 0xBB, 0xBF }; -} + /// + /// URL:http://en.wikipedia.org/wiki/Byte-order_mark + /// + public static byte[] UTF8ByteOrderMark => new byte[] { 0xEF, 0xBB, 0xBF }; +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeEncode.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeEncode.cs index 9ad782c..b353867 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeEncode.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QRCodeEncode.cs @@ -9,24 +9,24 @@ namespace Gma.QrCodeNet.Encoding; internal static class QRCodeEncode { - internal static BitMatrix Encode(string content, ErrorCorrectionLevel errorLevel) - { - EncodationStruct encodeStruct = DataEncode.Encode(content, errorLevel); + internal static BitMatrix Encode(string content, ErrorCorrectionLevel errorLevel) + { + EncodationStruct encodeStruct = DataEncode.Encode(content, errorLevel); - return ProcessEncodationResult(encodeStruct, errorLevel); - } + return ProcessEncodationResult(encodeStruct, errorLevel); + } - private static BitMatrix ProcessEncodationResult(EncodationStruct encodeStruct, ErrorCorrectionLevel errorLevel) - { - BitList codewords = ECGenerator.FillECCodewords(encodeStruct.DataCodewords, encodeStruct.VersionDetail); + private static BitMatrix ProcessEncodationResult(EncodationStruct encodeStruct, ErrorCorrectionLevel errorLevel) + { + BitList codewords = ECGenerator.FillECCodewords(encodeStruct.DataCodewords, encodeStruct.VersionDetail); - TriStateMatrix triMatrix = new(encodeStruct.VersionDetail.MatrixWidth); - PositioningPatternBuilder.EmbedBasicPatterns(encodeStruct.VersionDetail.Version, triMatrix); + TriStateMatrix triMatrix = new(encodeStruct.VersionDetail.MatrixWidth); + PositioningPatternBuilder.EmbedBasicPatterns(encodeStruct.VersionDetail.Version, triMatrix); - triMatrix.EmbedVersionInformation(encodeStruct.VersionDetail.Version); - triMatrix.EmbedFormatInformation(errorLevel, new Pattern0()); - triMatrix.TryEmbedCodewords(codewords); + triMatrix.EmbedVersionInformation(encodeStruct.VersionDetail.Version); + triMatrix.EmbedFormatInformation(errorLevel, new Pattern0()); + triMatrix.TryEmbedCodewords(codewords); - return triMatrix.GetLowestPenaltyMatrix(errorLevel); - } -} + return triMatrix.GetLowestPenaltyMatrix(errorLevel); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrCode.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrCode.cs index de932c6..bcf4e26 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrCode.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrCode.cs @@ -8,21 +8,21 @@ namespace Gma.QrCodeNet.Encoding; /// public class QrCode { - internal QrCode(BitMatrix matrix) - { - Matrix = matrix; - IsContainMatrix = true; - } + internal QrCode(BitMatrix matrix) + { + Matrix = matrix; + IsContainMatrix = true; + } - public bool IsContainMatrix - { - get; - private set; - } + public bool IsContainMatrix + { + get; + private set; + } - public BitMatrix Matrix - { - get; - private set; - } -} + public BitMatrix Matrix + { + get; + private set; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrEncoder.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrEncoder.cs index c40d951..f78c155 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrEncoder.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/QrEncoder.cs @@ -2,38 +2,38 @@ namespace Gma.QrCodeNet.Encoding; public class QrEncoder { - /// - /// Default QrEncoder will set ErrorCorrectionLevel as M - /// - public QrEncoder() - : this(ErrorCorrectionLevel.M) - { - } + /// + /// Default QrEncoder will set ErrorCorrectionLevel as M + /// + public QrEncoder() + : this(ErrorCorrectionLevel.M) + { + } - /// - /// QrEncoder with parameter ErrorCorrectionLevel. - /// - public QrEncoder(ErrorCorrectionLevel errorCorrectionLevel) - { - ErrorCorrectionLevel = errorCorrectionLevel; - } + /// + /// QrEncoder with parameter ErrorCorrectionLevel. + /// + public QrEncoder(ErrorCorrectionLevel errorCorrectionLevel) + { + ErrorCorrectionLevel = errorCorrectionLevel; + } - public ErrorCorrectionLevel ErrorCorrectionLevel { get; set; } + public ErrorCorrectionLevel ErrorCorrectionLevel { get; set; } - /// - /// Encode string content to QrCode matrix - /// - /// - /// This exception for string content is null, empty or too large - public QrCode Encode(string content) - { - if (string.IsNullOrEmpty(content)) - { - throw new InputOutOfBoundaryException("Input cannot be null or empty."); - } - else - { - return new QrCode(QRCodeEncode.Encode(content, ErrorCorrectionLevel)); - } - } -} + /// + /// Encode string content to QrCode matrix + /// + /// + /// This exception for string content is null, empty or too large + public QrCode Encode(string content) + { + if (string.IsNullOrEmpty(content)) + { + throw new InputOutOfBoundaryException("Input cannot be null or empty."); + } + else + { + return new QrCode(QRCodeEncode.Encode(content, ErrorCorrectionLevel)); + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GaloisField256.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GaloisField256.cs index 7ab528f..52324a9 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GaloisField256.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GaloisField256.cs @@ -1,5 +1,3 @@ -using System; - namespace Gma.QrCodeNet.Encoding.ReedSolomon; /// @@ -7,116 +5,116 @@ namespace Gma.QrCodeNet.Encoding.ReedSolomon; /// internal sealed class GaloisField256 { - internal GaloisField256(int primitive) - { - AntiLogTable = new int[256]; - LogTable = new int[256]; + internal GaloisField256(int primitive) + { + AntiLogTable = new int[256]; + LogTable = new int[256]; - Primitive = primitive; + Primitive = primitive; - int gfx = 1; + int gfx = 1; - // Power cycle is from 0 to 254. 2^255 = 1 = 2^0 - // Value cycle is from 1 to 255. Thus there should not have Log(0). - for (int powers = 0; powers < 256; powers++) - { - AntiLogTable[powers] = gfx; - if (powers != 255) - { - LogTable[gfx] = powers; - } + // Power cycle is from 0 to 254. 2^255 = 1 = 2^0 + // Value cycle is from 1 to 255. Thus there should not have Log(0). + for (int powers = 0; powers < 256; powers++) + { + AntiLogTable[powers] = gfx; + if (powers != 255) + { + LogTable[gfx] = powers; + } - gfx <<= 1; // gfx = gfx * 2 where alpha is 2. + gfx <<= 1; // gfx = gfx * 2 where alpha is 2. - if (gfx > 255) - { - gfx ^= primitive; - } - } - } + if (gfx > 255) + { + gfx ^= primitive; + } + } + } - private int[] AntiLogTable { get; } - private int[] LogTable { get; } + private int[] AntiLogTable { get; } + private int[] LogTable { get; } - internal int Primitive { get; } + internal int Primitive { get; } - internal static GaloisField256 QRCodeGaloisField => new(QRCodeConstantVariable.QRCodePrimitive); + internal static GaloisField256 QRCodeGaloisField => new(QRCodeConstantVariable.QRCodePrimitive); - /// - /// Powers of a in GF table. Where a = 2 - /// - internal int Exponent(int powersOfa) => AntiLogTable[powersOfa]; + /// + /// Powers of a in GF table. Where a = 2 + /// + internal int Exponent(int powersOfa) => AntiLogTable[powersOfa]; - /// - /// Log (power of a) in GF table. Where a = 2 - /// - internal int Log(int gfValue) - { - if (gfValue == 0) - { - throw new ArgumentException("GaloisField value will not be equal to 0, Log method."); - } + /// + /// Log (power of a) in GF table. Where a = 2 + /// + internal int Log(int gfValue) + { + if (gfValue == 0) + { + throw new ArgumentException("GaloisField value will not be equal to 0, Log method."); + } - return LogTable[gfValue]; - } + return LogTable[gfValue]; + } - internal int Inverse(int gfValue) - { - if (gfValue == 0) - { - throw new ArgumentException("GaloisField value will not be equal to 0, Inverse method."); - } + internal int Inverse(int gfValue) + { + if (gfValue == 0) + { + throw new ArgumentException("GaloisField value will not be equal to 0, Inverse method."); + } - return Exponent(255 - Log(gfValue)); - } + return Exponent(255 - Log(gfValue)); + } - internal int Addition(int gfValueA, int gfValueB) => gfValueA ^ gfValueB; + internal int Addition(int gfValueA, int gfValueB) => gfValueA ^ gfValueB; - internal int Subtraction(int gfValueA, int gfValueB) => Addition(gfValueA, gfValueB); // Subtraction is same as addition. + internal int Subtraction(int gfValueA, int gfValueB) => Addition(gfValueA, gfValueB); // Subtraction is same as addition. - /// - /// Product of two values. - /// In other words. a multiply b - /// - internal int Product(int gfValueA, int gfValueB) - { - if (gfValueA == 0 || gfValueB == 0) - { - return 0; - } - if (gfValueA == 1) - { - return gfValueB; - } - if (gfValueB == 1) - { - return gfValueA; - } + /// + /// Product of two values. + /// In other words. a multiply b + /// + internal int Product(int gfValueA, int gfValueB) + { + if (gfValueA == 0 || gfValueB == 0) + { + return 0; + } + if (gfValueA == 1) + { + return gfValueB; + } + if (gfValueB == 1) + { + return gfValueA; + } - return Exponent((Log(gfValueA) + Log(gfValueB)) % 255); - } + return Exponent((Log(gfValueA) + Log(gfValueB)) % 255); + } - /// - /// Quotient of two values. - /// In other words. a divided b - /// - internal int Quotient(int gfValueA, int gfValueB) - { - if (gfValueA == 0) - { - return 0; - } + /// + /// Quotient of two values. + /// In other words. a divided b + /// + internal int Quotient(int gfValueA, int gfValueB) + { + if (gfValueA == 0) + { + return 0; + } - if (gfValueB == 0) - { - throw new ArgumentException($"{nameof(gfValueB)} cannot be zero."); - } + if (gfValueB == 0) + { + throw new ArgumentException($"{nameof(gfValueB)} cannot be zero."); + } - if (gfValueB == 1) - { - return gfValueA; - } + if (gfValueB == 1) + { + return gfValueA; + } - return Exponent(Math.Abs(Log(gfValueA) - Log(gfValueB)) % 255); - } -} + return Exponent(Math.Abs(Log(gfValueA) - Log(gfValueB)) % 255); + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GeneratorPolynomial.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GeneratorPolynomial.cs index 94619a8..61036e9 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GeneratorPolynomial.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/GeneratorPolynomial.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Gma.QrCodeNet.Encoding.ReedSolomon; /// @@ -7,56 +5,56 @@ namespace Gma.QrCodeNet.Encoding.ReedSolomon; /// internal sealed class GeneratorPolynomial { - /// - /// After create GeneratorPolynomial. Keep it as long as possible. - /// Unless QRCode encode is done or no more QRCode need to generate. - /// - internal GeneratorPolynomial(GaloisField256 gfield) - { - Gfield = gfield; - CacheGenerator = new List(10) - { - new Polynomial(Gfield, new int[] { 1 }) - }; - } + /// + /// After create GeneratorPolynomial. Keep it as long as possible. + /// Unless QRCode encode is done or no more QRCode need to generate. + /// + internal GeneratorPolynomial(GaloisField256 gfield) + { + Gfield = gfield; + CacheGenerator = new List(10) + { + new Polynomial(Gfield, new int[] { 1 }) + }; + } - private GaloisField256 Gfield { get; } + private GaloisField256 Gfield { get; } - private List CacheGenerator { get; } + private List CacheGenerator { get; } - /// - /// Get generator by degree. (Largest degree for that generator) - /// - /// Generator - internal Polynomial GetGenerator(int degree) - { - if (degree >= CacheGenerator.Count) - { - BuildGenerator(degree); - } + /// + /// Get generator by degree. (Largest degree for that generator) + /// + /// Generator + internal Polynomial GetGenerator(int degree) + { + if (degree >= CacheGenerator.Count) + { + BuildGenerator(degree); + } - return CacheGenerator[degree]; - } + return CacheGenerator[degree]; + } - /// - /// Build Generator if we cannot find specific degree of generator from cache - /// - private void BuildGenerator(int degree) - { - lock (CacheGenerator) - { - int currentCacheLength = CacheGenerator.Count; - if (degree >= currentCacheLength) - { - Polynomial lastGenerator = CacheGenerator[currentCacheLength - 1]; + /// + /// Build Generator if we cannot find specific degree of generator from cache + /// + private void BuildGenerator(int degree) + { + lock (CacheGenerator) + { + int currentCacheLength = CacheGenerator.Count; + if (degree >= currentCacheLength) + { + Polynomial lastGenerator = CacheGenerator[currentCacheLength - 1]; - for (int d = currentCacheLength; d <= degree; d++) - { - Polynomial nextGenerator = lastGenerator.Multiply(new Polynomial(Gfield, new int[] { 1, Gfield.Exponent(d - 1) })); - CacheGenerator.Add(nextGenerator); - lastGenerator = nextGenerator; - } - } - } - } -} + for (int d = currentCacheLength; d <= degree; d++) + { + Polynomial nextGenerator = lastGenerator.Multiply(new Polynomial(Gfield, new int[] { 1, Gfield.Exponent(d - 1) })); + CacheGenerator.Add(nextGenerator); + lastGenerator = nextGenerator; + } + } + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/PolyDivideStruct.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/PolyDivideStruct.cs index 2619030..7b20bbd 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/PolyDivideStruct.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/PolyDivideStruct.cs @@ -2,14 +2,14 @@ namespace Gma.QrCodeNet.Encoding.ReedSolomon; internal struct PolyDivideStruct { - internal PolyDivideStruct(Polynomial quotient, Polynomial remainder) - : this() - { - Quotient = quotient; - Remainder = remainder; - } + internal PolyDivideStruct(Polynomial quotient, Polynomial remainder) + : this() + { + Quotient = quotient; + Remainder = remainder; + } - internal Polynomial Quotient { get; private set; } + internal Polynomial Quotient { get; private set; } - internal Polynomial Remainder { get; private set; } -} + internal Polynomial Remainder { get; private set; } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/Polynomial.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/Polynomial.cs index c0daaa5..ad70fad 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/Polynomial.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/Polynomial.cs @@ -1,242 +1,240 @@ -using System; - namespace Gma.QrCodeNet.Encoding.ReedSolomon; internal sealed class Polynomial { - internal Polynomial(GaloisField256 gfield, int[] coefficients) - { - int coefficientsLength = coefficients.Length; + internal Polynomial(GaloisField256 gfield, int[] coefficients) + { + int coefficientsLength = coefficients.Length; - if (coefficientsLength == 0 || coefficients is null) - { - throw new ArithmeticException($"Cannot create empty {nameof(Polynomial)}."); - } + if (coefficientsLength == 0 || coefficients is null) + { + throw new ArithmeticException($"Cannot create empty {nameof(Polynomial)}."); + } - GField = gfield; + GField = gfield; - Primitive = gfield.Primitive; + Primitive = gfield.Primitive; - if (coefficientsLength > 1 && coefficients[0] == 0) - { - int firstNonZeroIndex = 1; - while (firstNonZeroIndex < coefficientsLength && coefficients[firstNonZeroIndex] == 0) - { - firstNonZeroIndex++; - } + if (coefficientsLength > 1 && coefficients[0] == 0) + { + int firstNonZeroIndex = 1; + while (firstNonZeroIndex < coefficientsLength && coefficients[firstNonZeroIndex] == 0) + { + firstNonZeroIndex++; + } - if (firstNonZeroIndex == coefficientsLength) - { - Coefficients = new int[] { 0 }; - } - else - { - int newLength = coefficientsLength - firstNonZeroIndex; - Coefficients = new int[newLength]; - Array.Copy(coefficients, firstNonZeroIndex, Coefficients, 0, newLength); - } - } - else - { - Coefficients = new int[coefficientsLength]; - Array.Copy(coefficients, Coefficients, coefficientsLength); - } - } + if (firstNonZeroIndex == coefficientsLength) + { + Coefficients = new int[] { 0 }; + } + else + { + int newLength = coefficientsLength - firstNonZeroIndex; + Coefficients = new int[newLength]; + Array.Copy(coefficients, firstNonZeroIndex, Coefficients, 0, newLength); + } + } + else + { + Coefficients = new int[coefficientsLength]; + Array.Copy(coefficients, Coefficients, coefficientsLength); + } + } - internal int[] Coefficients { get; } + internal int[] Coefficients { get; } - internal GaloisField256 GField { get; } + internal GaloisField256 GField { get; } - internal int Degree => Coefficients.Length - 1; + internal int Degree => Coefficients.Length - 1; - internal int Primitive { get; } + internal int Primitive { get; } - internal bool IsMonomialZero => Coefficients[0] == 0; + internal bool IsMonomialZero => Coefficients[0] == 0; - /// - /// Coefficient position. where (coefficient)x^degree - /// - internal int GetCoefficient(int degree) - { - // Eg: x^2 + x + 1. degree 1, reverse position = degree + 1 = 2. - // Pos = 3 - 2 = 1 - return Coefficients[^(degree + 1)]; - } + /// + /// Coefficient position. where (coefficient)x^degree + /// + internal int GetCoefficient(int degree) + { + // Eg: x^2 + x + 1. degree 1, reverse position = degree + 1 = 2. + // Pos = 3 - 2 = 1 + return Coefficients[^(degree + 1)]; + } - /// - /// Add another Polynomial to current one - /// - /// The polynomial need to add or subtract to current one - /// Result polynomial after add or subtract - internal Polynomial AddOrSubtract(Polynomial other) - { - if (Primitive != other.Primitive) - { - throw new ArgumentException($"{nameof(Polynomial)} cannot perform {nameof(AddOrSubtract)} as they do not have the same {nameof(Primitive)}" + - $" for {nameof(GaloisField256)}."); - } - if (IsMonomialZero) - { - return other; - } - else if (other.IsMonomialZero) - { - return this; - } + /// + /// Add another Polynomial to current one + /// + /// The polynomial need to add or subtract to current one + /// Result polynomial after add or subtract + internal Polynomial AddOrSubtract(Polynomial other) + { + if (Primitive != other.Primitive) + { + throw new ArgumentException($"{nameof(Polynomial)} cannot perform {nameof(AddOrSubtract)} as they do not have the same {nameof(Primitive)}" + + $" for {nameof(GaloisField256)}."); + } + if (IsMonomialZero) + { + return other; + } + else if (other.IsMonomialZero) + { + return this; + } - int otherLength = other.Coefficients.Length; - int thisLength = Coefficients.Length; + int otherLength = other.Coefficients.Length; + int thisLength = Coefficients.Length; - if (otherLength > thisLength) - { - return CoefficientXor(Coefficients, other.Coefficients); - } - else - { - return CoefficientXor(other.Coefficients, Coefficients); - } - } + if (otherLength > thisLength) + { + return CoefficientXor(Coefficients, other.Coefficients); + } + else + { + return CoefficientXor(other.Coefficients, Coefficients); + } + } - internal Polynomial CoefficientXor(int[] smallerCoefficients, int[] largerCoefficients) - { - if (smallerCoefficients.Length > largerCoefficients.Length) - { - throw new ArgumentException($"Cannot perform {nameof(CoefficientXor)} method as smaller {nameof(Coefficients)} length is greater than the larger one."); - } + internal Polynomial CoefficientXor(int[] smallerCoefficients, int[] largerCoefficients) + { + if (smallerCoefficients.Length > largerCoefficients.Length) + { + throw new ArgumentException($"Cannot perform {nameof(CoefficientXor)} method as smaller {nameof(Coefficients)} length is greater than the larger one."); + } - int targetLength = largerCoefficients.Length; - int[] xorCoefficient = new int[targetLength]; - int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length; + int targetLength = largerCoefficients.Length; + int[] xorCoefficient = new int[targetLength]; + int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length; - Array.Copy(largerCoefficients, 0, xorCoefficient, 0, lengthDiff); + Array.Copy(largerCoefficients, 0, xorCoefficient, 0, lengthDiff); - for (int index = lengthDiff; index < targetLength; index++) - { - xorCoefficient[index] = GField.Addition(largerCoefficients[index], smallerCoefficients[index - lengthDiff]); - } + for (int index = lengthDiff; index < targetLength; index++) + { + xorCoefficient[index] = GField.Addition(largerCoefficients[index], smallerCoefficients[index - lengthDiff]); + } - return new Polynomial(GField, xorCoefficient); - } + return new Polynomial(GField, xorCoefficient); + } - /// - /// Multiply current Polynomial to another one. - /// - /// Result polynomial after multiply - internal Polynomial Multiply(Polynomial other) - { - if (Primitive != other.Primitive) - { - throw new ArgumentException($"{nameof(Polynomial)} cannot perform {nameof(Multiply)} as they do not have the same {nameof(Primitive)}" + - $" for {nameof(GaloisField256)}."); - } - if (IsMonomialZero || other.IsMonomialZero) - { - return new Polynomial(GField, new int[] { 0 }); - } + /// + /// Multiply current Polynomial to another one. + /// + /// Result polynomial after multiply + internal Polynomial Multiply(Polynomial other) + { + if (Primitive != other.Primitive) + { + throw new ArgumentException($"{nameof(Polynomial)} cannot perform {nameof(Multiply)} as they do not have the same {nameof(Primitive)}" + + $" for {nameof(GaloisField256)}."); + } + if (IsMonomialZero || other.IsMonomialZero) + { + return new Polynomial(GField, new int[] { 0 }); + } - int[] aCoefficients = Coefficients; - int aLength = aCoefficients.Length; - int[] bCoefficient = other.Coefficients; - int bLength = bCoefficient.Length; - int[] rCoefficients = new int[aLength + bLength - 1]; + int[] aCoefficients = Coefficients; + int aLength = aCoefficients.Length; + int[] bCoefficient = other.Coefficients; + int bLength = bCoefficient.Length; + int[] rCoefficients = new int[aLength + bLength - 1]; - for (int aIndex = 0; aIndex < aLength; aIndex++) - { - int aCoeff = aCoefficients[aIndex]; - for (int bIndex = 0; bIndex < bLength; bIndex++) - { - rCoefficients[aIndex + bIndex] = - GField.Addition(rCoefficients[aIndex + bIndex], GField.Product(aCoeff, bCoefficient[bIndex])); - } - } - return new Polynomial(GField, rCoefficients); - } + for (int aIndex = 0; aIndex < aLength; aIndex++) + { + int aCoeff = aCoefficients[aIndex]; + for (int bIndex = 0; bIndex < bLength; bIndex++) + { + rCoefficients[aIndex + bIndex] = + GField.Addition(rCoefficients[aIndex + bIndex], GField.Product(aCoeff, bCoefficient[bIndex])); + } + } + return new Polynomial(GField, rCoefficients); + } - /// - /// Multiplay scalar to current polynomial - /// - /// Result of polynomial after multiply scalar - internal Polynomial MultiplyScalar(int scalar) - { - if (scalar == 0) - { - return new Polynomial(GField, new int[] { 0 }); - } - else if (scalar == 1) - { - return this; - } + /// + /// Multiplay scalar to current polynomial + /// + /// Result of polynomial after multiply scalar + internal Polynomial MultiplyScalar(int scalar) + { + if (scalar == 0) + { + return new Polynomial(GField, new int[] { 0 }); + } + else if (scalar == 1) + { + return this; + } - int length = Coefficients.Length; - int[] rCoefficient = new int[length]; + int length = Coefficients.Length; + int[] rCoefficient = new int[length]; - for (int index = 0; index < length; index++) - { - rCoefficient[index] = GField.Product(Coefficients[index], scalar); - } + for (int index = 0; index < length; index++) + { + rCoefficient[index] = GField.Product(Coefficients[index], scalar); + } - return new Polynomial(GField, rCoefficient); - } + return new Polynomial(GField, rCoefficient); + } - /// - /// Divide current polynomial by "other" - /// - /// Result polynomial after divide - internal PolyDivideStruct Divide(Polynomial other) - { - if (Primitive != other.Primitive) - { - throw new ArgumentException($"{nameof(Polynomial)} cannot perform {nameof(Divide)} as they do not have the same {nameof(Primitive)}" + - $" for {nameof(GaloisField256)}."); - } - if (other.IsMonomialZero) - { - throw new ArgumentException($"Cannot divide by {nameof(Polynomial)} Zero."); - } + /// + /// Divide current polynomial by "other" + /// + /// Result polynomial after divide + internal PolyDivideStruct Divide(Polynomial other) + { + if (Primitive != other.Primitive) + { + throw new ArgumentException($"{nameof(Polynomial)} cannot perform {nameof(Divide)} as they do not have the same {nameof(Primitive)}" + + $" for {nameof(GaloisField256)}."); + } + if (other.IsMonomialZero) + { + throw new ArgumentException($"Cannot divide by {nameof(Polynomial)} Zero."); + } - // This divide by other = a divide by b - int aLength = Coefficients.Length; + // This divide by other = a divide by b + int aLength = Coefficients.Length; - // We will make change to aCoefficient. It will return as remainder - int[] aCoefficients = new int[aLength]; - Array.Copy(Coefficients, 0, aCoefficients, 0, aLength); + // We will make change to aCoefficient. It will return as remainder + int[] aCoefficients = new int[aLength]; + Array.Copy(Coefficients, 0, aCoefficients, 0, aLength); - int bLength = other.Coefficients.Length; + int bLength = other.Coefficients.Length; - if (aLength < bLength) - { - return new PolyDivideStruct(new Polynomial(GField, new int[] { 0 }), this); - } - else - { - // Quotient coefficients - // qLastIndex = alength - blength qlength = qLastIndex + 1 - int[] qCoefficients = new int[(aLength - bLength) + 1]; + if (aLength < bLength) + { + return new PolyDivideStruct(new Polynomial(GField, new int[] { 0 }), this); + } + else + { + // Quotient coefficients + // qLastIndex = alength - blength qlength = qLastIndex + 1 + int[] qCoefficients = new int[(aLength - bLength) + 1]; - // Denominator - int otherLeadingTerm = other.GetCoefficient(other.Degree); - int inverseOtherLeadingTerm = GField.Inverse(otherLeadingTerm); + // Denominator + int otherLeadingTerm = other.GetCoefficient(other.Degree); + int inverseOtherLeadingTerm = GField.Inverse(otherLeadingTerm); - for (int aIndex = 0; aIndex <= aLength - bLength; aIndex++) - { - if (aCoefficients[aIndex] != 0) - { - int aScalar = GField.Product(inverseOtherLeadingTerm, aCoefficients[aIndex]); - Polynomial term = other.MultiplyScalar(aScalar); - qCoefficients[aIndex] = aScalar; + for (int aIndex = 0; aIndex <= aLength - bLength; aIndex++) + { + if (aCoefficients[aIndex] != 0) + { + int aScalar = GField.Product(inverseOtherLeadingTerm, aCoefficients[aIndex]); + Polynomial term = other.MultiplyScalar(aScalar); + qCoefficients[aIndex] = aScalar; - int[] bCoefficient = term.Coefficients; - if (bCoefficient[0] != 0) - { - for (int bIndex = 0; bIndex < bLength; bIndex++) - { - aCoefficients[aIndex + bIndex] = GField.Subtraction(aCoefficients[aIndex + bIndex], bCoefficient[bIndex]); - } - } - } - } + int[] bCoefficient = term.Coefficients; + if (bCoefficient[0] != 0) + { + for (int bIndex = 0; bIndex < bLength; bIndex++) + { + aCoefficients[aIndex + bIndex] = GField.Subtraction(aCoefficients[aIndex + bIndex], bCoefficient[bIndex]); + } + } + } + } - return new PolyDivideStruct(new Polynomial(GField, qCoefficients), new Polynomial(GField, aCoefficients)); - } - } -} + return new PolyDivideStruct(new Polynomial(GField, qCoefficients), new Polynomial(GField, aCoefficients)); + } + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/ReedSolomonEncoder.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/ReedSolomonEncoder.cs index 6bc47de..3aa8136 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/ReedSolomonEncoder.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/ReedSolomon/ReedSolomonEncoder.cs @@ -1,91 +1,89 @@ -using System; - namespace Gma.QrCodeNet.Encoding.ReedSolomon; internal sealed class ReedSolomonEncoder { - /// - /// Encode an array of data codeword with GaloisField 256. - /// - /// Array of data codewords for a single block. - /// Number of error correction codewords for data codewords - /// Cached or newly create GeneratorPolynomial - /// Return error correction codewords array - internal static byte[] Encode(byte[] dataBytes, int numECBytes, GeneratorPolynomial generatorPoly) - { - int dataLength = dataBytes.Length; + /// + /// Encode an array of data codeword with GaloisField 256. + /// + /// Array of data codewords for a single block. + /// Number of error correction codewords for data codewords + /// Cached or newly create GeneratorPolynomial + /// Return error correction codewords array + internal static byte[] Encode(byte[] dataBytes, int numECBytes, GeneratorPolynomial generatorPoly) + { + int dataLength = dataBytes.Length; if (generatorPoly == null) throw new ArgumentNullException(nameof(generatorPoly)); if (dataLength == 0) - { - throw new ArgumentException("There is no data bytes to encode."); - } + { + throw new ArgumentException("There is no data bytes to encode."); + } - if (numECBytes <= 0) - { - throw new ArgumentException("No Error Correction bytes."); - } + if (numECBytes <= 0) + { + throw new ArgumentException("No Error Correction bytes."); + } - int[] toEncode = ConvertToIntArray(dataBytes, dataLength, numECBytes); + int[] toEncode = ConvertToIntArray(dataBytes, dataLength, numECBytes); - Polynomial generator = generatorPoly.GetGenerator(numECBytes); + Polynomial generator = generatorPoly.GetGenerator(numECBytes); - Polynomial dataPoly = new(generator.GField, toEncode); + Polynomial dataPoly = new(generator.GField, toEncode); - PolyDivideStruct divideResult = dataPoly.Divide(generator); + PolyDivideStruct divideResult = dataPoly.Divide(generator); - int[] remainderCoeffs = divideResult.Remainder.Coefficients; + int[] remainderCoeffs = divideResult.Remainder.Coefficients; - return ConvertTosByteArray(remainderCoeffs, numECBytes); - } + return ConvertTosByteArray(remainderCoeffs, numECBytes); + } - /// - /// Convert data codewords to int array. And add error correction space at end of that array - /// - /// Data codewords array - /// Data codewords length - /// Num of error correction bytes - /// Int array for data codewords array follow by error correction space - private static int[] ConvertToIntArray(byte[] dataBytes, int dataLength, int numECBytes) - { - int[] resultArray = new int[dataLength + numECBytes]; + /// + /// Convert data codewords to int array. And add error correction space at end of that array + /// + /// Data codewords array + /// Data codewords length + /// Num of error correction bytes + /// Int array for data codewords array follow by error correction space + private static int[] ConvertToIntArray(byte[] dataBytes, int dataLength, int numECBytes) + { + int[] resultArray = new int[dataLength + numECBytes]; - for (int index = 0; index < dataLength; index++) - { - resultArray[index] = dataBytes[index] & 0xff; - } + for (int index = 0; index < dataLength; index++) + { + resultArray[index] = dataBytes[index] & 0xff; + } - return resultArray; - } + return resultArray; + } - /// - /// Reassembly error correction codewords. As Polynomial class will eliminate zero monomial at front. - /// - /// Remainder byte array after divide. - /// Error correction codewords length - /// Error correction codewords - private static byte[] ConvertTosByteArray(int[] remainder, int numECBytes) - { - int remainderLength = remainder.Length; - if (remainderLength > numECBytes) - { - throw new ArgumentException($"Num of {nameof(remainder)} bytes cannot be larger than {nameof(numECBytes)}."); - } + /// + /// Reassembly error correction codewords. As Polynomial class will eliminate zero monomial at front. + /// + /// Remainder byte array after divide. + /// Error correction codewords length + /// Error correction codewords + private static byte[] ConvertTosByteArray(int[] remainder, int numECBytes) + { + int remainderLength = remainder.Length; + if (remainderLength > numECBytes) + { + throw new ArgumentException($"Num of {nameof(remainder)} bytes cannot be larger than {nameof(numECBytes)}."); + } - int numZeroCoeffs = numECBytes - remainderLength; + int numZeroCoeffs = numECBytes - remainderLength; - byte[] resultArray = new byte[numECBytes]; - for (int index = 0; index < numZeroCoeffs; index++) - { - resultArray[index] = 0; - } + byte[] resultArray = new byte[numECBytes]; + for (int index = 0; index < numZeroCoeffs; index++) + { + resultArray[index] = 0; + } - for (int rIndex = 0; rIndex < remainderLength; rIndex++) - { - resultArray[numZeroCoeffs + rIndex] = (byte)remainder[rIndex]; - } + for (int rIndex = 0; rIndex < remainderLength; rIndex++) + { + resultArray[numZeroCoeffs + rIndex] = (byte)remainder[rIndex]; + } - return resultArray; - } -} + return resultArray; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/StateMatrix.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/StateMatrix.cs index 617e771..6378620 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/StateMatrix.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/StateMatrix.cs @@ -2,27 +2,27 @@ namespace Gma.QrCodeNet.Encoding; public sealed class StateMatrix { - public StateMatrix(int width) - { - Width = width; - MatrixStatus = new MatrixStatus[width, width]; - } + public StateMatrix(int width) + { + Width = width; + MatrixStatus = new MatrixStatus[width, width]; + } - private MatrixStatus[,] MatrixStatus { get; } + private MatrixStatus[,] MatrixStatus { get; } - public MatrixStatus this[int x, int y] - { - get => MatrixStatus[x, y]; - set => MatrixStatus[x, y] = value; - } + public MatrixStatus this[int x, int y] + { + get => MatrixStatus[x, y]; + set => MatrixStatus[x, y] = value; + } - internal MatrixStatus this[MatrixPoint point] - { - get => this[point.X, point.Y]; - set => this[point.X, point.Y] = value; - } + internal MatrixStatus this[MatrixPoint point] + { + get => this[point.X, point.Y]; + set => this[point.X, point.Y] = value; + } - public int Width { get; } + public int Width { get; } - public int Height => Width; -} + public int Height => Width; +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Terminate/Terminator.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Terminate/Terminator.cs index 2e9b9aa..586c8e8 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Terminate/Terminator.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Terminate/Terminator.cs @@ -1,73 +1,71 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Terminate; internal static class Terminator { - private const int NumBitsForByte = 8; + private const int NumBitsForByte = 8; - /// - /// This method will create BitList that contains - /// terminator, padding and pad codewords for given datacodewords. - /// Use it to full fill the data codewords capacity. Thus avoid massive empty bits. - /// - /// ISO/IEC 18004:2006 P. 32 33. - /// Terminator / Bit stream to codeword conversion - /// Method will add terminator bits (Terminator, padding and padcodewords) at end of baseList - /// Num of bits for datacodewords without terminator - /// Total number of datacodewords for specific version. - /// Receive it under Version/VersionTable - internal static void TerminateBites(this BitList baseList, int dataCount, int numTotalDataCodewords) - { - int numTotalDataBits = numTotalDataCodewords << 3; - int numDataBits = dataCount; + /// + /// This method will create BitList that contains + /// terminator, padding and pad codewords for given datacodewords. + /// Use it to full fill the data codewords capacity. Thus avoid massive empty bits. + /// + /// ISO/IEC 18004:2006 P. 32 33. + /// Terminator / Bit stream to codeword conversion + /// Method will add terminator bits (Terminator, padding and padcodewords) at end of baseList + /// Num of bits for datacodewords without terminator + /// Total number of datacodewords for specific version. + /// Receive it under Version/VersionTable + internal static void TerminateBites(this BitList baseList, int dataCount, int numTotalDataCodewords) + { + int numTotalDataBits = numTotalDataCodewords << 3; + int numDataBits = dataCount; - int numFillerBits = numTotalDataBits - numDataBits; - int numBitsNeedForLastByte = numFillerBits & 0x7; - int numFillerBytes = numFillerBits >> 3; + int numFillerBits = numTotalDataBits - numDataBits; + int numBitsNeedForLastByte = numFillerBits & 0x7; + int numFillerBytes = numFillerBits >> 3; - // BitList result = new BitList(); - if (numBitsNeedForLastByte >= QRCodeConstantVariable.TerminatorLength) - { - baseList.TerminatorPadding(numBitsNeedForLastByte); - baseList.PadeCodewords(numFillerBytes); - } - else if (numFillerBytes == 0) - { - baseList.TerminatorPadding(numBitsNeedForLastByte); - } - else if (numFillerBytes > 0) - { - baseList.TerminatorPadding(numBitsNeedForLastByte + NumBitsForByte); - baseList.PadeCodewords(numFillerBytes - 1); - } + // BitList result = new BitList(); + if (numBitsNeedForLastByte >= QRCodeConstantVariable.TerminatorLength) + { + baseList.TerminatorPadding(numBitsNeedForLastByte); + baseList.PadeCodewords(numFillerBytes); + } + else if (numFillerBytes == 0) + { + baseList.TerminatorPadding(numBitsNeedForLastByte); + } + else if (numFillerBytes > 0) + { + baseList.TerminatorPadding(numBitsNeedForLastByte + NumBitsForByte); + baseList.PadeCodewords(numFillerBytes - 1); + } - if (baseList.Count != numTotalDataBits) - { - throw new ArgumentException( - $"Generate terminator and Padding fail. Num of bits need: {numFillerBytes}. Actual length: {baseList.Count - numDataBits}"); - } - } + if (baseList.Count != numTotalDataBits) + { + throw new ArgumentException( + $"Generate terminator and Padding fail. Num of bits need: {numFillerBytes}. Actual length: {baseList.Count - numDataBits}"); + } + } - private static void PadeCodewords(this BitList mainList, int numOfPadeCodewords) - { - if (numOfPadeCodewords < 0) - { - throw new ArgumentException("Num of pade codewords is less than Zero"); - } + private static void PadeCodewords(this BitList mainList, int numOfPadeCodewords) + { + if (numOfPadeCodewords < 0) + { + throw new ArgumentException("Num of pade codewords is less than Zero"); + } - for (int numOfP = 1; numOfP <= numOfPadeCodewords; numOfP++) - { - if (numOfP % 2 == 1) - { - mainList.Add(QRCodeConstantVariable.PadeCodewordsOdd, NumBitsForByte); - } - else - { - mainList.Add(QRCodeConstantVariable.PadeCodewordsEven, NumBitsForByte); - } - } - } + for (int numOfP = 1; numOfP <= numOfPadeCodewords; numOfP++) + { + if (numOfP % 2 == 1) + { + mainList.Add(QRCodeConstantVariable.PadeCodewordsOdd, NumBitsForByte); + } + else + { + mainList.Add(QRCodeConstantVariable.PadeCodewordsEven, NumBitsForByte); + } + } + } - private static void TerminatorPadding(this BitList mainList, int numBits) => mainList.Add(QRCodeConstantVariable.TerminatorNPaddingBit, numBits); -} + private static void TerminatorPadding(this BitList mainList, int numBits) => mainList.Add(QRCodeConstantVariable.TerminatorNPaddingBit, numBits); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/TriStateMatrix.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/TriStateMatrix.cs index 584eb1e..d852c57 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/TriStateMatrix.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/TriStateMatrix.cs @@ -1,48 +1,46 @@ -using System; - namespace Gma.QrCodeNet.Encoding; public class TriStateMatrix : BitMatrixBase { - public TriStateMatrix(int width) : base(width, new bool[width, width]) - { - StateMatrix = new StateMatrix(width); - } + public TriStateMatrix(int width) : base(width, new bool[width, width]) + { + StateMatrix = new StateMatrix(width); + } - internal TriStateMatrix(bool[,] internalArray) : base(internalArray) - { - StateMatrix = new StateMatrix(internalArray.GetLength(0)); - } + internal TriStateMatrix(bool[,] internalArray) : base(internalArray) + { + StateMatrix = new StateMatrix(internalArray.GetLength(0)); + } - private StateMatrix StateMatrix { get; } + private StateMatrix StateMatrix { get; } - public override bool this[int i, int j] - { - get => InternalArray[i, j]; - set - { - if (MStatus(i, j) is MatrixStatus.None or MatrixStatus.NoMask) - { - throw new InvalidOperationException($"The value of cell [{i}, {j}] is not set or is Stencil."); - } - InternalArray[i, j] = value; - } - } + public override bool this[int i, int j] + { + get => InternalArray[i, j]; + set + { + if (MStatus(i, j) is MatrixStatus.None or MatrixStatus.NoMask) + { + throw new InvalidOperationException($"The value of cell [{i}, {j}] is not set or is Stencil."); + } + InternalArray[i, j] = value; + } + } - public bool this[int i, int j, MatrixStatus mstatus] - { - set - { - StateMatrix[i, j] = mstatus; - InternalArray[i, j] = value; - } - } + public bool this[int i, int j, MatrixStatus mstatus] + { + set + { + StateMatrix[i, j] = mstatus; + InternalArray[i, j] = value; + } + } - public override int Height => Width; + public override int Height => Width; - public override int Width => base.Width; + public override int Width => base.Width; - internal MatrixStatus MStatus(int i, int j) => StateMatrix[i, j]; + internal MatrixStatus MStatus(int i, int j) => StateMatrix[i, j]; - internal MatrixStatus MStatus(MatrixPoint point) => MStatus(point.X, point.Y); -} + internal MatrixStatus MStatus(MatrixPoint point) => MStatus(point.X, point.Y); +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/VersionDetail.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/VersionDetail.cs index f7f66e4..efb108a 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/VersionDetail.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/VersionDetail.cs @@ -2,33 +2,33 @@ namespace Gma.QrCodeNet.Encoding; public struct VersionDetail { - internal VersionDetail(int version, int numTotalBytes, int numDataBytes, int numECBlocks) - : this() - { - Version = version; - NumTotalBytes = numTotalBytes; - NumDataBytes = numDataBytes; - NumECBlocks = numECBlocks; - } + internal VersionDetail(int version, int numTotalBytes, int numDataBytes, int numECBlocks) + : this() + { + Version = version; + NumTotalBytes = numTotalBytes; + NumDataBytes = numDataBytes; + NumECBlocks = numECBlocks; + } - internal int Version { get; private set; } - internal int NumTotalBytes { get; private set; } - internal int NumDataBytes { get; private set; } - internal int NumECBlocks { get; private set; } + internal int Version { get; private set; } + internal int NumTotalBytes { get; private set; } + internal int NumDataBytes { get; private set; } + internal int NumECBlocks { get; private set; } - internal int MatrixWidth => Width(Version); + internal int MatrixWidth => Width(Version); - internal int ECBlockGroup1 => NumECBlocks - ECBlockGroup2; + internal int ECBlockGroup1 => NumECBlocks - ECBlockGroup2; - internal int ECBlockGroup2 => NumTotalBytes % NumECBlocks; + internal int ECBlockGroup2 => NumTotalBytes % NumECBlocks; - internal int NumDataBytesGroup1 => NumDataBytes / NumECBlocks; + internal int NumDataBytesGroup1 => NumDataBytes / NumECBlocks; - internal int NumDataBytesGroup2 => NumDataBytesGroup1 + 1; + internal int NumDataBytesGroup2 => NumDataBytesGroup1 + 1; - internal int NumECBytesPerBlock => (NumTotalBytes - NumDataBytes) / NumECBlocks; + internal int NumECBytesPerBlock => (NumTotalBytes - NumDataBytes) / NumECBlocks; - internal static int Width(int version) => 17 + (4 * version); + internal static int Width(int version) => 17 + (4 * version); - public override string ToString() => $"{Version};{NumTotalBytes};{NumDataBytes};{NumECBlocks}"; -} + public override string ToString() => $"{Version};{NumTotalBytes};{NumDataBytes};{NumECBlocks}"; +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlock.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlock.cs index cb796ef..7d900a1 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlock.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlock.cs @@ -2,14 +2,14 @@ namespace Gma.QrCodeNet.Encoding.Versions; internal struct ErrorCorrectionBlock { - internal ErrorCorrectionBlock(int numErrorCorrectionBlock, int numDataCodewards) - : this() - { - NumErrorCorrectionBlock = numErrorCorrectionBlock; - NumDataCodewords = numDataCodewards; - } + internal ErrorCorrectionBlock(int numErrorCorrectionBlock, int numDataCodewards) + : this() + { + NumErrorCorrectionBlock = numErrorCorrectionBlock; + NumDataCodewords = numDataCodewards; + } - internal int NumErrorCorrectionBlock { get; private set; } + internal int NumErrorCorrectionBlock { get; private set; } - internal int NumDataCodewords { get; private set; } -} + internal int NumDataCodewords { get; private set; } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlocks.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlocks.cs index b1fc966..e15f844 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlocks.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/ErrorCorrectionBlocks.cs @@ -1,55 +1,53 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Versions; internal struct ErrorCorrectionBlocks { - internal ErrorCorrectionBlocks(int numErrorCorrectionCodewords, ErrorCorrectionBlock ecBlock) - : this() - { - NumErrorCorrectionCodewards = numErrorCorrectionCodewords; - ECBlock = new ErrorCorrectionBlock[] { ecBlock }; + internal ErrorCorrectionBlocks(int numErrorCorrectionCodewords, ErrorCorrectionBlock ecBlock) + : this() + { + NumErrorCorrectionCodewards = numErrorCorrectionCodewords; + ECBlock = new ErrorCorrectionBlock[] { ecBlock }; - Initialize(); - } + Initialize(); + } - internal ErrorCorrectionBlocks(int numErrorCorrectionCodewords, ErrorCorrectionBlock ecBlock1, ErrorCorrectionBlock ecBlock2) - : this() - { - NumErrorCorrectionCodewards = numErrorCorrectionCodewords; - ECBlock = new ErrorCorrectionBlock[] { ecBlock1, ecBlock2 }; + internal ErrorCorrectionBlocks(int numErrorCorrectionCodewords, ErrorCorrectionBlock ecBlock1, ErrorCorrectionBlock ecBlock2) + : this() + { + NumErrorCorrectionCodewards = numErrorCorrectionCodewords; + ECBlock = new ErrorCorrectionBlock[] { ecBlock1, ecBlock2 }; - Initialize(); - } + Initialize(); + } - internal int NumErrorCorrectionCodewards { get; private set; } + internal int NumErrorCorrectionCodewards { get; private set; } - internal int NumBlocks { get; private set; } + internal int NumBlocks { get; private set; } - internal int ErrorCorrectionCodewordsPerBlock { get; private set; } + internal int ErrorCorrectionCodewordsPerBlock { get; private set; } - private ErrorCorrectionBlock[] ECBlock { get; } + private ErrorCorrectionBlock[] ECBlock { get; } - /// - /// Get Error Correction Blocks - /// - internal ErrorCorrectionBlock[] GetECBlocks() => ECBlock; + /// + /// Get Error Correction Blocks + /// + internal ErrorCorrectionBlock[] GetECBlocks() => ECBlock; - /// - /// Initialize for NumBlocks and ErrorCorrectionCodewordsPerBlock - /// - private void Initialize() + /// + /// Initialize for NumBlocks and ErrorCorrectionCodewordsPerBlock + /// + private void Initialize() { if (ECBlock == null) throw new ArgumentNullException(nameof(ECBlock)); NumBlocks = 0; - int blockLength = ECBlock.Length; - for (int i = 0; i < blockLength; i++) - { - NumBlocks += ECBlock[i].NumErrorCorrectionBlock; - } + int blockLength = ECBlock.Length; + for (int i = 0; i < blockLength; i++) + { + NumBlocks += ECBlock[i].NumErrorCorrectionBlock; + } - ErrorCorrectionCodewordsPerBlock = NumErrorCorrectionCodewards / NumBlocks; - } -} + ErrorCorrectionCodewordsPerBlock = NumErrorCorrectionCodewards / NumBlocks; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/QRCodeVersion.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/QRCodeVersion.cs index cfa160e..30ad44b 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/QRCodeVersion.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/QRCodeVersion.cs @@ -1,35 +1,33 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Versions; internal struct QRCodeVersion { - internal QRCodeVersion(int versionNum, int totalCodewords, ErrorCorrectionBlocks ecblocksL, ErrorCorrectionBlocks ecblocksM, ErrorCorrectionBlocks ecblocksQ, ErrorCorrectionBlocks ecblocksH) - : this() - { - VersionNum = versionNum; - TotalCodewords = totalCodewords; - ECBlocks = new ErrorCorrectionBlocks[] { ecblocksL, ecblocksM, ecblocksQ, ecblocksH }; - DimensionForVersion = 17 + (versionNum * 4); - } + internal QRCodeVersion(int versionNum, int totalCodewords, ErrorCorrectionBlocks ecblocksL, ErrorCorrectionBlocks ecblocksM, ErrorCorrectionBlocks ecblocksQ, ErrorCorrectionBlocks ecblocksH) + : this() + { + VersionNum = versionNum; + TotalCodewords = totalCodewords; + ECBlocks = new ErrorCorrectionBlocks[] { ecblocksL, ecblocksM, ecblocksQ, ecblocksH }; + DimensionForVersion = 17 + (versionNum * 4); + } - internal int VersionNum { get; private set; } + internal int VersionNum { get; private set; } - internal int TotalCodewords { get; private set; } + internal int TotalCodewords { get; private set; } - internal int DimensionForVersion { get; private set; } + internal int DimensionForVersion { get; private set; } - private ErrorCorrectionBlocks[] ECBlocks { get; } + private ErrorCorrectionBlocks[] ECBlocks { get; } - internal ErrorCorrectionBlocks GetECBlocksByLevel(ErrorCorrectionLevel eCLevel) - { - return eCLevel switch - { - ErrorCorrectionLevel.L => ECBlocks[0], - ErrorCorrectionLevel.M => ECBlocks[1], - ErrorCorrectionLevel.Q => ECBlocks[2], - ErrorCorrectionLevel.H => ECBlocks[3], - _ => throw new ArgumentOutOfRangeException(nameof(eCLevel)) - }; - } -} + internal ErrorCorrectionBlocks GetECBlocksByLevel(ErrorCorrectionLevel eCLevel) + { + return eCLevel switch + { + ErrorCorrectionLevel.L => ECBlocks[0], + ErrorCorrectionLevel.M => ECBlocks[1], + ErrorCorrectionLevel.Q => ECBlocks[2], + ErrorCorrectionLevel.H => ECBlocks[3], + _ => throw new ArgumentOutOfRangeException(nameof(eCLevel)) + }; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControl.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControl.cs index 0fdd767..30d5fea 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControl.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControl.cs @@ -1,144 +1,143 @@ -using System; using Gma.QrCodeNet.Encoding.DataEncodation; namespace Gma.QrCodeNet.Encoding.Versions; internal static class VersionControl { - private const int NumBitsModeIndicator = 4; - private const string DefaultEncoding = QRCodeConstantVariable.DefaultEncoding; + private const int NumBitsModeIndicator = 4; + private const string DefaultEncoding = QRCodeConstantVariable.DefaultEncoding; - private static readonly int[] VERSION_GROUP = new int[] { 9, 26, 40 }; + private static readonly int[] VERSION_GROUP = new int[] { 9, 26, 40 }; - /// - /// Determine which version to use - /// - /// Number of bits for encoded content - /// Encoding name for EightBitByte - /// VersionDetail and ECI - internal static VersionControlStruct InitialSetup(int dataBitsLength, ErrorCorrectionLevel level, string encodingName) - { - int totalDataBits = dataBitsLength; + /// + /// Determine which version to use + /// + /// Number of bits for encoded content + /// Encoding name for EightBitByte + /// VersionDetail and ECI + internal static VersionControlStruct InitialSetup(int dataBitsLength, ErrorCorrectionLevel level, string encodingName) + { + int totalDataBits = dataBitsLength; - bool containECI = false; + bool containECI = false; - BitList eciHeader = new(); + BitList eciHeader = new(); - if (encodingName is not DefaultEncoding and not QRCodeConstantVariable.UTF8Encoding) - { - ECISet eciSet = new(ECISet.AppendOption.NameToValue); - int eciValue = eciSet.GetECIValueByName(encodingName); + if (encodingName is not DefaultEncoding and not QRCodeConstantVariable.UTF8Encoding) + { + ECISet eciSet = new(ECISet.AppendOption.NameToValue); + int eciValue = eciSet.GetECIValueByName(encodingName); - totalDataBits += ECISet.NumOfECIHeaderBits(eciValue); - eciHeader = eciSet.GetECIHeader(encodingName); - containECI = true; - } + totalDataBits += ECISet.NumOfECIHeaderBits(eciValue); + eciHeader = eciSet.GetECIHeader(encodingName); + containECI = true; + } - // Determine which version group it belong to - int searchGroup = DynamicSearchIndicator(totalDataBits, level); + // Determine which version group it belong to + int searchGroup = DynamicSearchIndicator(totalDataBits, level); - int[] charCountIndicator = CharCountIndicatorTable.GetCharCountIndicatorSet(); + int[] charCountIndicator = CharCountIndicatorTable.GetCharCountIndicatorSet(); - totalDataBits += (NumBitsModeIndicator + charCountIndicator[searchGroup]); + totalDataBits += (NumBitsModeIndicator + charCountIndicator[searchGroup]); - int lowerSearchBoundary = searchGroup == 0 ? 1 : (VERSION_GROUP[searchGroup - 1] + 1); - int higherSearchBoundary = VERSION_GROUP[searchGroup]; + int lowerSearchBoundary = searchGroup == 0 ? 1 : (VERSION_GROUP[searchGroup - 1] + 1); + int higherSearchBoundary = VERSION_GROUP[searchGroup]; - // Binary search to find proper version - int versionNum = BinarySearch(totalDataBits, level, lowerSearchBoundary, higherSearchBoundary); + // Binary search to find proper version + int versionNum = BinarySearch(totalDataBits, level, lowerSearchBoundary, higherSearchBoundary); - VersionControlStruct vcStruct = FillVCStruct(versionNum, level); + VersionControlStruct vcStruct = FillVCStruct(versionNum, level); - vcStruct.IsContainECI = containECI; + vcStruct.IsContainECI = containECI; - vcStruct.ECIHeader = eciHeader; + vcStruct.ECIHeader = eciHeader; - return vcStruct; - } + return vcStruct; + } - private static VersionControlStruct FillVCStruct(int versionNum, ErrorCorrectionLevel level) - { - if (versionNum is < 1 or > 40) - { - throw new InvalidOperationException($"Unexpected version number: {versionNum}"); - } + private static VersionControlStruct FillVCStruct(int versionNum, ErrorCorrectionLevel level) + { + if (versionNum is < 1 or > 40) + { + throw new InvalidOperationException($"Unexpected version number: {versionNum}"); + } - VersionControlStruct vcStruct = new(); + VersionControlStruct vcStruct = new(); - int version = versionNum; + int version = versionNum; - QRCodeVersion versionData = VersionTable.GetVersionByNum(versionNum); + QRCodeVersion versionData = VersionTable.GetVersionByNum(versionNum); - int numTotalBytes = versionData.TotalCodewords; + int numTotalBytes = versionData.TotalCodewords; - ErrorCorrectionBlocks ecBlocks = versionData.GetECBlocksByLevel(level); - int numDataBytes = numTotalBytes - ecBlocks.NumErrorCorrectionCodewards; - int numECBlocks = ecBlocks.NumBlocks; + ErrorCorrectionBlocks ecBlocks = versionData.GetECBlocksByLevel(level); + int numDataBytes = numTotalBytes - ecBlocks.NumErrorCorrectionCodewards; + int numECBlocks = ecBlocks.NumBlocks; - VersionDetail vcDetail = new(version, numTotalBytes, numDataBytes, numECBlocks); + VersionDetail vcDetail = new(version, numTotalBytes, numDataBytes, numECBlocks); - vcStruct.VersionDetail = vcDetail; - return vcStruct; - } + vcStruct.VersionDetail = vcDetail; + return vcStruct; + } - /// - /// Decide which version group it belong to - /// - /// Number of bits for bitlist where it contain DataBits encode from input content and ECI header - /// Error correction level - /// Version group index for VERSION_GROUP - private static int DynamicSearchIndicator(int numBits, ErrorCorrectionLevel level) - { - int[] charCountIndicator = CharCountIndicatorTable.GetCharCountIndicatorSet(); - int loopLength = VERSION_GROUP.Length; - for (int i = 0; i < loopLength; i++) - { - int totalBits = numBits + NumBitsModeIndicator + charCountIndicator[i]; + /// + /// Decide which version group it belong to + /// + /// Number of bits for bitlist where it contain DataBits encode from input content and ECI header + /// Error correction level + /// Version group index for VERSION_GROUP + private static int DynamicSearchIndicator(int numBits, ErrorCorrectionLevel level) + { + int[] charCountIndicator = CharCountIndicatorTable.GetCharCountIndicatorSet(); + int loopLength = VERSION_GROUP.Length; + for (int i = 0; i < loopLength; i++) + { + int totalBits = numBits + NumBitsModeIndicator + charCountIndicator[i]; - QRCodeVersion version = VersionTable.GetVersionByNum(VERSION_GROUP[i]); - int numECCodewords = version.GetECBlocksByLevel(level).NumErrorCorrectionCodewards; + QRCodeVersion version = VersionTable.GetVersionByNum(VERSION_GROUP[i]); + int numECCodewords = version.GetECBlocksByLevel(level).NumErrorCorrectionCodewards; - int dataCodewords = version.TotalCodewords - numECCodewords; + int dataCodewords = version.TotalCodewords - numECCodewords; - if (totalBits <= dataCodewords * 8) - { - return i; - } - } + if (totalBits <= dataCodewords * 8) + { + return i; + } + } - throw new InputOutOfBoundaryException($"QRCode do not have enough space for {(numBits + NumBitsModeIndicator + charCountIndicator[2])} bits"); - } + throw new InputOutOfBoundaryException($"QRCode do not have enough space for {(numBits + NumBitsModeIndicator + charCountIndicator[2])} bits"); + } - /// - /// Use number of data bits(header + eci header + data bits from EncoderBase) to search for proper version to use - /// between min and max boundary. - /// Boundary define by DynamicSearchIndicator method. - /// - private static int BinarySearch(int numDataBits, ErrorCorrectionLevel level, int lowerVersionNum, int higherVersionNum) - { - int middleVersionNumber; + /// + /// Use number of data bits(header + eci header + data bits from EncoderBase) to search for proper version to use + /// between min and max boundary. + /// Boundary define by DynamicSearchIndicator method. + /// + private static int BinarySearch(int numDataBits, ErrorCorrectionLevel level, int lowerVersionNum, int higherVersionNum) + { + int middleVersionNumber; - while (lowerVersionNum <= higherVersionNum) - { - middleVersionNumber = (lowerVersionNum + higherVersionNum) / 2; - QRCodeVersion version = VersionTable.GetVersionByNum(middleVersionNumber); - int numECCodewords = version.GetECBlocksByLevel(level).NumErrorCorrectionCodewards; - int dataCodewords = version.TotalCodewords - numECCodewords; + while (lowerVersionNum <= higherVersionNum) + { + middleVersionNumber = (lowerVersionNum + higherVersionNum) / 2; + QRCodeVersion version = VersionTable.GetVersionByNum(middleVersionNumber); + int numECCodewords = version.GetECBlocksByLevel(level).NumErrorCorrectionCodewards; + int dataCodewords = version.TotalCodewords - numECCodewords; - if (dataCodewords << 3 == numDataBits) - { - return middleVersionNumber; - } + if (dataCodewords << 3 == numDataBits) + { + return middleVersionNumber; + } - if (dataCodewords << 3 > numDataBits) - { - higherVersionNum = middleVersionNumber - 1; - } - else - { - lowerVersionNum = middleVersionNumber + 1; - } - } - return lowerVersionNum; - } -} + if (dataCodewords << 3 > numDataBits) + { + higherVersionNum = middleVersionNumber - 1; + } + else + { + lowerVersionNum = middleVersionNumber + 1; + } + } + return lowerVersionNum; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControlStruct.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControlStruct.cs index 7979f18..682e478 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControlStruct.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionControlStruct.cs @@ -2,7 +2,7 @@ namespace Gma.QrCodeNet.Encoding.Versions; internal struct VersionControlStruct { - internal VersionDetail VersionDetail { get; set; } - internal bool IsContainECI { get; set; } - internal BitList ECIHeader { get; set; } -} + internal VersionDetail VersionDetail { get; set; } + internal bool IsContainECI { get; set; } + internal BitList ECIHeader { get; set; } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionTable.cs b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionTable.cs index ef30b0b..79f6028 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionTable.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/Encoding/Versions/VersionTable.cs @@ -1,317 +1,315 @@ -using System; - namespace Gma.QrCodeNet.Encoding.Versions; public static class VersionTable { - private static readonly QRCodeVersion[] Version = Initialize(); + private static readonly QRCodeVersion[] Version = Initialize(); - internal static QRCodeVersion GetVersionByNum(int versionNum) - { - if (versionNum is < QRCodeConstantVariable.MinVersion or > QRCodeConstantVariable.MaxVersion) - { - throw new InvalidOperationException($"Unexpected version number: {versionNum}."); - } + internal static QRCodeVersion GetVersionByNum(int versionNum) + { + if (versionNum is < QRCodeConstantVariable.MinVersion or > QRCodeConstantVariable.MaxVersion) + { + throw new InvalidOperationException($"Unexpected version number: {versionNum}."); + } - return Version[versionNum - 1]; - } + return Version[versionNum - 1]; + } - internal static QRCodeVersion GetVersionByWidth(int matrixWidth) - { - if ((matrixWidth - 17) % 4 != 0) - { - throw new ArgumentException("Incorrect matrix width."); - } - else - { - return GetVersionByNum((matrixWidth - 17) / 4); - } - } + internal static QRCodeVersion GetVersionByWidth(int matrixWidth) + { + if ((matrixWidth - 17) % 4 != 0) + { + throw new ArgumentException("Incorrect matrix width."); + } + else + { + return GetVersionByNum((matrixWidth - 17) / 4); + } + } - private static QRCodeVersion[] Initialize() - { - return new QRCodeVersion[] - { - new QRCodeVersion( - 1, - 26, - new ErrorCorrectionBlocks(7, new ErrorCorrectionBlock(1, 19)), - new ErrorCorrectionBlocks(10, new ErrorCorrectionBlock(1, 16)), - new ErrorCorrectionBlocks(13, new ErrorCorrectionBlock(1, 13)), - new ErrorCorrectionBlocks(17, new ErrorCorrectionBlock(1, 9))), - new QRCodeVersion( - 2, - 44, - new ErrorCorrectionBlocks(10, new ErrorCorrectionBlock(1, 34)), - new ErrorCorrectionBlocks(16, new ErrorCorrectionBlock(1, 28)), - new ErrorCorrectionBlocks(22, new ErrorCorrectionBlock(1, 22)), - new ErrorCorrectionBlocks(28, new ErrorCorrectionBlock(1, 16))), - new QRCodeVersion( - 3, - 70, - new ErrorCorrectionBlocks(15, new ErrorCorrectionBlock(1, 55)), - new ErrorCorrectionBlocks(26, new ErrorCorrectionBlock(1, 44)), - new ErrorCorrectionBlocks(36, new ErrorCorrectionBlock(2, 17)), - new ErrorCorrectionBlocks(44, new ErrorCorrectionBlock(2, 13))), - new QRCodeVersion( - 4, - 100, - new ErrorCorrectionBlocks(20, new ErrorCorrectionBlock(1, 80)), - new ErrorCorrectionBlocks(36, new ErrorCorrectionBlock(2, 32)), - new ErrorCorrectionBlocks(52, new ErrorCorrectionBlock(2, 24)), - new ErrorCorrectionBlocks(64, new ErrorCorrectionBlock(4, 9))), - new QRCodeVersion( - 5, - 134, - new ErrorCorrectionBlocks(26, new ErrorCorrectionBlock(1, 108)), - new ErrorCorrectionBlocks(48, new ErrorCorrectionBlock(2, 43)), - new ErrorCorrectionBlocks(72, new ErrorCorrectionBlock(2, 15), new ErrorCorrectionBlock(2, 16)), - new ErrorCorrectionBlocks(88, new ErrorCorrectionBlock(2, 11), new ErrorCorrectionBlock(2, 12))), - new QRCodeVersion( - 6, - 172, - new ErrorCorrectionBlocks(36, new ErrorCorrectionBlock(2, 68)), - new ErrorCorrectionBlocks(64, new ErrorCorrectionBlock(4, 27)), - new ErrorCorrectionBlocks(96, new ErrorCorrectionBlock(4, 19)), - new ErrorCorrectionBlocks(112, new ErrorCorrectionBlock(4, 15))), - new QRCodeVersion( - 7, - 196, - new ErrorCorrectionBlocks(40, new ErrorCorrectionBlock(2, 78)), - new ErrorCorrectionBlocks(72, new ErrorCorrectionBlock(4, 31)), - new ErrorCorrectionBlocks(108, new ErrorCorrectionBlock(2, 14), new ErrorCorrectionBlock(4, 15)), - new ErrorCorrectionBlocks(130, new ErrorCorrectionBlock(4, 13), new ErrorCorrectionBlock(1, 14))), - new QRCodeVersion( - 8, - 242, - new ErrorCorrectionBlocks(48, new ErrorCorrectionBlock(2, 97)), - new ErrorCorrectionBlocks(88, new ErrorCorrectionBlock(2, 38), new ErrorCorrectionBlock(2, 39)), - new ErrorCorrectionBlocks(132, new ErrorCorrectionBlock(4, 18), new ErrorCorrectionBlock(2, 19)), - new ErrorCorrectionBlocks(156, new ErrorCorrectionBlock(4, 14), new ErrorCorrectionBlock(2, 15))), - new QRCodeVersion( - 9, - 292, - new ErrorCorrectionBlocks(60, new ErrorCorrectionBlock(2, 116)), - new ErrorCorrectionBlocks(110, new ErrorCorrectionBlock(3, 36), new ErrorCorrectionBlock(2, 37)), - new ErrorCorrectionBlocks(160, new ErrorCorrectionBlock(4, 16), new ErrorCorrectionBlock(4, 17)), - new ErrorCorrectionBlocks(192, new ErrorCorrectionBlock(4, 12), new ErrorCorrectionBlock(4, 13))), - new QRCodeVersion( - 10, - 346, - new ErrorCorrectionBlocks(72, new ErrorCorrectionBlock(2, 68), new ErrorCorrectionBlock(2, 69)), - new ErrorCorrectionBlocks(130, new ErrorCorrectionBlock(4, 43), new ErrorCorrectionBlock(1, 44)), - new ErrorCorrectionBlocks(192, new ErrorCorrectionBlock(6, 19), new ErrorCorrectionBlock(2, 20)), - new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(6, 15), new ErrorCorrectionBlock(2, 16))), - new QRCodeVersion( - 11, - 404, - new ErrorCorrectionBlocks(80, new ErrorCorrectionBlock(4, 81)), - new ErrorCorrectionBlocks(150, new ErrorCorrectionBlock(1, 50), new ErrorCorrectionBlock(4, 51)), - new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(4, 22), new ErrorCorrectionBlock(4, 23)), - new ErrorCorrectionBlocks(264, new ErrorCorrectionBlock(3, 12), new ErrorCorrectionBlock(8, 13))), - new QRCodeVersion( - 12, - 466, - new ErrorCorrectionBlocks(96, new ErrorCorrectionBlock(2, 92), new ErrorCorrectionBlock(2, 93)), - new ErrorCorrectionBlocks(176, new ErrorCorrectionBlock(6, 36), new ErrorCorrectionBlock(2, 37)), - new ErrorCorrectionBlocks(260, new ErrorCorrectionBlock(4, 20), new ErrorCorrectionBlock(6, 21)), - new ErrorCorrectionBlocks(308, new ErrorCorrectionBlock(7, 14), new ErrorCorrectionBlock(4, 15))), - new QRCodeVersion( - 13, - 532, - new ErrorCorrectionBlocks(104, new ErrorCorrectionBlock(4, 107)), - new ErrorCorrectionBlocks(198, new ErrorCorrectionBlock(8, 37), new ErrorCorrectionBlock(1, 38)), - new ErrorCorrectionBlocks(288, new ErrorCorrectionBlock(8, 20), new ErrorCorrectionBlock(4, 21)), - new ErrorCorrectionBlocks(352, new ErrorCorrectionBlock(12, 11), new ErrorCorrectionBlock(4, 12))), - new QRCodeVersion( - 14, - 581, - new ErrorCorrectionBlocks(120, new ErrorCorrectionBlock(3, 115), new ErrorCorrectionBlock(1, 116)), - new ErrorCorrectionBlocks(216, new ErrorCorrectionBlock(4, 40), new ErrorCorrectionBlock(5, 41)), - new ErrorCorrectionBlocks(320, new ErrorCorrectionBlock(11, 16), new ErrorCorrectionBlock(5, 17)), - new ErrorCorrectionBlocks(384, new ErrorCorrectionBlock(11, 12), new ErrorCorrectionBlock(5, 13))), - new QRCodeVersion( - 15, - 655, - new ErrorCorrectionBlocks(132, new ErrorCorrectionBlock(5, 87), new ErrorCorrectionBlock(1, 88)), - new ErrorCorrectionBlocks(240, new ErrorCorrectionBlock(5, 41), new ErrorCorrectionBlock(5, 42)), - new ErrorCorrectionBlocks(360, new ErrorCorrectionBlock(5, 24), new ErrorCorrectionBlock(7, 25)), - new ErrorCorrectionBlocks(432, new ErrorCorrectionBlock(11, 12), new ErrorCorrectionBlock(7, 13))), - new QRCodeVersion( - 16, - 733, - new ErrorCorrectionBlocks(144, new ErrorCorrectionBlock(5, 98), new ErrorCorrectionBlock(1, 99)), - new ErrorCorrectionBlocks(280, new ErrorCorrectionBlock(7, 45), new ErrorCorrectionBlock(3, 46)), - new ErrorCorrectionBlocks(408, new ErrorCorrectionBlock(15, 19), new ErrorCorrectionBlock(2, 20)), - new ErrorCorrectionBlocks(480, new ErrorCorrectionBlock(3, 15), new ErrorCorrectionBlock(13, 16))), - new QRCodeVersion( - 17, - 815, - new ErrorCorrectionBlocks(168, new ErrorCorrectionBlock(1, 107), new ErrorCorrectionBlock(5, 108)), - new ErrorCorrectionBlocks(308, new ErrorCorrectionBlock(10, 46), new ErrorCorrectionBlock(1, 47)), - new ErrorCorrectionBlocks(448, new ErrorCorrectionBlock(1, 22), new ErrorCorrectionBlock(15, 23)), - new ErrorCorrectionBlocks(532, new ErrorCorrectionBlock(2, 14), new ErrorCorrectionBlock(17, 15))), - new QRCodeVersion( - 18, - 901, - new ErrorCorrectionBlocks(180, new ErrorCorrectionBlock(5, 120), new ErrorCorrectionBlock(1, 121)), - new ErrorCorrectionBlocks(338, new ErrorCorrectionBlock(9, 43), new ErrorCorrectionBlock(4, 44)), - new ErrorCorrectionBlocks(504, new ErrorCorrectionBlock(17, 22), new ErrorCorrectionBlock(1, 23)), - new ErrorCorrectionBlocks(588, new ErrorCorrectionBlock(2, 14), new ErrorCorrectionBlock(19, 15))), - new QRCodeVersion( - 19, - 991, - new ErrorCorrectionBlocks(196, new ErrorCorrectionBlock(3, 113), new ErrorCorrectionBlock(4, 114)), - new ErrorCorrectionBlocks(364, new ErrorCorrectionBlock(3, 44), new ErrorCorrectionBlock(11, 45)), - new ErrorCorrectionBlocks(546, new ErrorCorrectionBlock(17, 21), new ErrorCorrectionBlock(4, 22)), - new ErrorCorrectionBlocks(650, new ErrorCorrectionBlock(9, 13), new ErrorCorrectionBlock(16, 14))), - new QRCodeVersion( - 20, - 1085, - new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(3, 107), new ErrorCorrectionBlock(5, 108)), - new ErrorCorrectionBlocks(416, new ErrorCorrectionBlock(3, 41), new ErrorCorrectionBlock(13, 42)), - new ErrorCorrectionBlocks(600, new ErrorCorrectionBlock(15, 24), new ErrorCorrectionBlock(5, 25)), - new ErrorCorrectionBlocks(700, new ErrorCorrectionBlock(15, 15), new ErrorCorrectionBlock(10, 16))), - new QRCodeVersion( - 21, - 1156, - new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(4, 116), new ErrorCorrectionBlock(4, 117)), - new ErrorCorrectionBlocks(442, new ErrorCorrectionBlock(17, 42)), - new ErrorCorrectionBlocks(644, new ErrorCorrectionBlock(17, 22), new ErrorCorrectionBlock(6, 23)), - new ErrorCorrectionBlocks(750, new ErrorCorrectionBlock(19, 16), new ErrorCorrectionBlock(6, 17))), - new QRCodeVersion( - 22, - 1258, - new ErrorCorrectionBlocks(252, new ErrorCorrectionBlock(2, 111), new ErrorCorrectionBlock(7, 112)), - new ErrorCorrectionBlocks(476, new ErrorCorrectionBlock(17, 46)), - new ErrorCorrectionBlocks(690, new ErrorCorrectionBlock(7, 24), new ErrorCorrectionBlock(16, 25)), - new ErrorCorrectionBlocks(816, new ErrorCorrectionBlock(34, 13))), - new QRCodeVersion( - 23, - 1364, - new ErrorCorrectionBlocks(270, new ErrorCorrectionBlock(4, 121), new ErrorCorrectionBlock(5, 122)), - new ErrorCorrectionBlocks(504, new ErrorCorrectionBlock(4, 47), new ErrorCorrectionBlock(14, 48)), - new ErrorCorrectionBlocks(750, new ErrorCorrectionBlock(11, 24), new ErrorCorrectionBlock(14, 25)), - new ErrorCorrectionBlocks(900, new ErrorCorrectionBlock(16, 15), new ErrorCorrectionBlock(14, 16))), - new QRCodeVersion( - 24, - 1474, - new ErrorCorrectionBlocks(300, new ErrorCorrectionBlock(6, 117), new ErrorCorrectionBlock(4, 118)), - new ErrorCorrectionBlocks(560, new ErrorCorrectionBlock(6, 45), new ErrorCorrectionBlock(14, 46)), - new ErrorCorrectionBlocks(810, new ErrorCorrectionBlock(11, 24), new ErrorCorrectionBlock(16, 25)), - new ErrorCorrectionBlocks(960, new ErrorCorrectionBlock(30, 16), new ErrorCorrectionBlock(2, 17))), - new QRCodeVersion( - 25, - 1588, - new ErrorCorrectionBlocks(312, new ErrorCorrectionBlock(8, 106), new ErrorCorrectionBlock(4, 107)), - new ErrorCorrectionBlocks(588, new ErrorCorrectionBlock(8, 47), new ErrorCorrectionBlock(13, 48)), - new ErrorCorrectionBlocks(870, new ErrorCorrectionBlock(7, 24), new ErrorCorrectionBlock(22, 25)), - new ErrorCorrectionBlocks(1050, new ErrorCorrectionBlock(22, 15), new ErrorCorrectionBlock(13, 16))), - new QRCodeVersion( - 26, - 1706, - new ErrorCorrectionBlocks(336, new ErrorCorrectionBlock(10, 114), new ErrorCorrectionBlock(2, 115)), - new ErrorCorrectionBlocks(644, new ErrorCorrectionBlock(19, 46), new ErrorCorrectionBlock(4, 47)), - new ErrorCorrectionBlocks(952, new ErrorCorrectionBlock(28, 22), new ErrorCorrectionBlock(6, 23)), - new ErrorCorrectionBlocks(1110, new ErrorCorrectionBlock(33, 16), new ErrorCorrectionBlock(4, 17))), - new QRCodeVersion( - 27, - 1828, - new ErrorCorrectionBlocks(360, new ErrorCorrectionBlock(8, 122), new ErrorCorrectionBlock(4, 123)), - new ErrorCorrectionBlocks(700, new ErrorCorrectionBlock(22, 45), new ErrorCorrectionBlock(3, 46)), - new ErrorCorrectionBlocks(1020, new ErrorCorrectionBlock(8, 23), new ErrorCorrectionBlock(26, 24)), - new ErrorCorrectionBlocks(1200, new ErrorCorrectionBlock(12, 15), new ErrorCorrectionBlock(28, 16))), - new QRCodeVersion( - 28, - 1921, - new ErrorCorrectionBlocks(390, new ErrorCorrectionBlock(3, 117), new ErrorCorrectionBlock(10, 118)), - new ErrorCorrectionBlocks(728, new ErrorCorrectionBlock(3, 45), new ErrorCorrectionBlock(23, 46)), - new ErrorCorrectionBlocks(1050, new ErrorCorrectionBlock(4, 24), new ErrorCorrectionBlock(31, 25)), - new ErrorCorrectionBlocks(1260, new ErrorCorrectionBlock(11, 15), new ErrorCorrectionBlock(31, 16))), - new QRCodeVersion( - 29, - 2051, - new ErrorCorrectionBlocks(420, new ErrorCorrectionBlock(7, 116), new ErrorCorrectionBlock(7, 117)), - new ErrorCorrectionBlocks(784, new ErrorCorrectionBlock(21, 45), new ErrorCorrectionBlock(7, 46)), - new ErrorCorrectionBlocks(1140, new ErrorCorrectionBlock(1, 23), new ErrorCorrectionBlock(37, 24)), - new ErrorCorrectionBlocks(1350, new ErrorCorrectionBlock(19, 15), new ErrorCorrectionBlock(26, 16))), - new QRCodeVersion( - 30, - 2185, - new ErrorCorrectionBlocks(450, new ErrorCorrectionBlock(5, 115), new ErrorCorrectionBlock(10, 116)), - new ErrorCorrectionBlocks(812, new ErrorCorrectionBlock(19, 47), new ErrorCorrectionBlock(10, 48)), - new ErrorCorrectionBlocks(1200, new ErrorCorrectionBlock(15, 24), new ErrorCorrectionBlock(25, 25)), - new ErrorCorrectionBlocks(1440, new ErrorCorrectionBlock(23, 15), new ErrorCorrectionBlock(25, 16))), - new QRCodeVersion( - 31, - 2323, - new ErrorCorrectionBlocks(480, new ErrorCorrectionBlock(13, 115), new ErrorCorrectionBlock(3, 116)), - new ErrorCorrectionBlocks(868, new ErrorCorrectionBlock(2, 46), new ErrorCorrectionBlock(29, 47)), - new ErrorCorrectionBlocks(1290, new ErrorCorrectionBlock(42, 24), new ErrorCorrectionBlock(1, 25)), - new ErrorCorrectionBlocks(1530, new ErrorCorrectionBlock(23, 15), new ErrorCorrectionBlock(28, 16))), - new QRCodeVersion( - 32, - 2465, - new ErrorCorrectionBlocks(510, new ErrorCorrectionBlock(17, 115)), - new ErrorCorrectionBlocks(924, new ErrorCorrectionBlock(10, 46), new ErrorCorrectionBlock(23, 47)), - new ErrorCorrectionBlocks(1350, new ErrorCorrectionBlock(10, 24), new ErrorCorrectionBlock(35, 25)), - new ErrorCorrectionBlocks(1620, new ErrorCorrectionBlock(19, 15), new ErrorCorrectionBlock(35, 16))), - new QRCodeVersion( - 33, - 2611, - new ErrorCorrectionBlocks(540, new ErrorCorrectionBlock(17, 115), new ErrorCorrectionBlock(1, 116)), - new ErrorCorrectionBlocks(980, new ErrorCorrectionBlock(14, 46), new ErrorCorrectionBlock(21, 47)), - new ErrorCorrectionBlocks(1440, new ErrorCorrectionBlock(29, 24), new ErrorCorrectionBlock(19, 25)), - new ErrorCorrectionBlocks(1710, new ErrorCorrectionBlock(11, 15), new ErrorCorrectionBlock(46, 16))), - new QRCodeVersion( - 34, - 2761, - new ErrorCorrectionBlocks(570, new ErrorCorrectionBlock(13, 115), new ErrorCorrectionBlock(6, 116)), - new ErrorCorrectionBlocks(1036, new ErrorCorrectionBlock(14, 46), new ErrorCorrectionBlock(23, 47)), - new ErrorCorrectionBlocks(1530, new ErrorCorrectionBlock(44, 24), new ErrorCorrectionBlock(7, 25)), - new ErrorCorrectionBlocks(1800, new ErrorCorrectionBlock(59, 16), new ErrorCorrectionBlock(1, 17))), - new QRCodeVersion( - 35, - 2876, - new ErrorCorrectionBlocks(570, new ErrorCorrectionBlock(12, 121), new ErrorCorrectionBlock(7, 122)), - new ErrorCorrectionBlocks(1064, new ErrorCorrectionBlock(12, 47), new ErrorCorrectionBlock(26, 48)), - new ErrorCorrectionBlocks(1590, new ErrorCorrectionBlock(39, 24), new ErrorCorrectionBlock(14, 25)), - new ErrorCorrectionBlocks(1890, new ErrorCorrectionBlock(22, 15), new ErrorCorrectionBlock(41, 16))), - new QRCodeVersion( - 36, - 3034, - new ErrorCorrectionBlocks(600, new ErrorCorrectionBlock(6, 121), new ErrorCorrectionBlock(14, 122)), - new ErrorCorrectionBlocks(1120, new ErrorCorrectionBlock(6, 47), new ErrorCorrectionBlock(34, 48)), - new ErrorCorrectionBlocks(1680, new ErrorCorrectionBlock(46, 24), new ErrorCorrectionBlock(10, 25)), - new ErrorCorrectionBlocks(1980, new ErrorCorrectionBlock(2, 15), new ErrorCorrectionBlock(64, 16))), - new QRCodeVersion( - 37, - 3196, - new ErrorCorrectionBlocks(630, new ErrorCorrectionBlock(17, 122), new ErrorCorrectionBlock(4, 123)), - new ErrorCorrectionBlocks(1204, new ErrorCorrectionBlock(29, 46), new ErrorCorrectionBlock(14, 47)), - new ErrorCorrectionBlocks(1770, new ErrorCorrectionBlock(49, 24), new ErrorCorrectionBlock(10, 25)), - new ErrorCorrectionBlocks(2100, new ErrorCorrectionBlock(24, 15), new ErrorCorrectionBlock(46, 16))), - new QRCodeVersion( - 38, - 3362, - new ErrorCorrectionBlocks(660, new ErrorCorrectionBlock(4, 122), new ErrorCorrectionBlock(18, 123)), - new ErrorCorrectionBlocks(1260, new ErrorCorrectionBlock(13, 46), new ErrorCorrectionBlock(32, 47)), - new ErrorCorrectionBlocks(1860, new ErrorCorrectionBlock(48, 24), new ErrorCorrectionBlock(14, 25)), - new ErrorCorrectionBlocks(2220, new ErrorCorrectionBlock(42, 15), new ErrorCorrectionBlock(32, 16))), - new QRCodeVersion( - 39, - 3532, - new ErrorCorrectionBlocks(720, new ErrorCorrectionBlock(20, 117), new ErrorCorrectionBlock(4, 118)), - new ErrorCorrectionBlocks(1316, new ErrorCorrectionBlock(40, 47), new ErrorCorrectionBlock(7, 48)), - new ErrorCorrectionBlocks(1950, new ErrorCorrectionBlock(43, 24), new ErrorCorrectionBlock(22, 25)), - new ErrorCorrectionBlocks(2310, new ErrorCorrectionBlock(10, 15), new ErrorCorrectionBlock(67, 16))), - new QRCodeVersion( - 40, - 3706, - new ErrorCorrectionBlocks(750, new ErrorCorrectionBlock(19, 118), new ErrorCorrectionBlock(6, 119)), - new ErrorCorrectionBlocks(1372, new ErrorCorrectionBlock(18, 47), new ErrorCorrectionBlock(31, 48)), - new ErrorCorrectionBlocks(2040, new ErrorCorrectionBlock(34, 24), new ErrorCorrectionBlock(34, 25)), - new ErrorCorrectionBlocks(2430, new ErrorCorrectionBlock(20, 15), new ErrorCorrectionBlock(61, 16))), - }; - } -} + private static QRCodeVersion[] Initialize() + { + return new QRCodeVersion[] + { + new QRCodeVersion( + 1, + 26, + new ErrorCorrectionBlocks(7, new ErrorCorrectionBlock(1, 19)), + new ErrorCorrectionBlocks(10, new ErrorCorrectionBlock(1, 16)), + new ErrorCorrectionBlocks(13, new ErrorCorrectionBlock(1, 13)), + new ErrorCorrectionBlocks(17, new ErrorCorrectionBlock(1, 9))), + new QRCodeVersion( + 2, + 44, + new ErrorCorrectionBlocks(10, new ErrorCorrectionBlock(1, 34)), + new ErrorCorrectionBlocks(16, new ErrorCorrectionBlock(1, 28)), + new ErrorCorrectionBlocks(22, new ErrorCorrectionBlock(1, 22)), + new ErrorCorrectionBlocks(28, new ErrorCorrectionBlock(1, 16))), + new QRCodeVersion( + 3, + 70, + new ErrorCorrectionBlocks(15, new ErrorCorrectionBlock(1, 55)), + new ErrorCorrectionBlocks(26, new ErrorCorrectionBlock(1, 44)), + new ErrorCorrectionBlocks(36, new ErrorCorrectionBlock(2, 17)), + new ErrorCorrectionBlocks(44, new ErrorCorrectionBlock(2, 13))), + new QRCodeVersion( + 4, + 100, + new ErrorCorrectionBlocks(20, new ErrorCorrectionBlock(1, 80)), + new ErrorCorrectionBlocks(36, new ErrorCorrectionBlock(2, 32)), + new ErrorCorrectionBlocks(52, new ErrorCorrectionBlock(2, 24)), + new ErrorCorrectionBlocks(64, new ErrorCorrectionBlock(4, 9))), + new QRCodeVersion( + 5, + 134, + new ErrorCorrectionBlocks(26, new ErrorCorrectionBlock(1, 108)), + new ErrorCorrectionBlocks(48, new ErrorCorrectionBlock(2, 43)), + new ErrorCorrectionBlocks(72, new ErrorCorrectionBlock(2, 15), new ErrorCorrectionBlock(2, 16)), + new ErrorCorrectionBlocks(88, new ErrorCorrectionBlock(2, 11), new ErrorCorrectionBlock(2, 12))), + new QRCodeVersion( + 6, + 172, + new ErrorCorrectionBlocks(36, new ErrorCorrectionBlock(2, 68)), + new ErrorCorrectionBlocks(64, new ErrorCorrectionBlock(4, 27)), + new ErrorCorrectionBlocks(96, new ErrorCorrectionBlock(4, 19)), + new ErrorCorrectionBlocks(112, new ErrorCorrectionBlock(4, 15))), + new QRCodeVersion( + 7, + 196, + new ErrorCorrectionBlocks(40, new ErrorCorrectionBlock(2, 78)), + new ErrorCorrectionBlocks(72, new ErrorCorrectionBlock(4, 31)), + new ErrorCorrectionBlocks(108, new ErrorCorrectionBlock(2, 14), new ErrorCorrectionBlock(4, 15)), + new ErrorCorrectionBlocks(130, new ErrorCorrectionBlock(4, 13), new ErrorCorrectionBlock(1, 14))), + new QRCodeVersion( + 8, + 242, + new ErrorCorrectionBlocks(48, new ErrorCorrectionBlock(2, 97)), + new ErrorCorrectionBlocks(88, new ErrorCorrectionBlock(2, 38), new ErrorCorrectionBlock(2, 39)), + new ErrorCorrectionBlocks(132, new ErrorCorrectionBlock(4, 18), new ErrorCorrectionBlock(2, 19)), + new ErrorCorrectionBlocks(156, new ErrorCorrectionBlock(4, 14), new ErrorCorrectionBlock(2, 15))), + new QRCodeVersion( + 9, + 292, + new ErrorCorrectionBlocks(60, new ErrorCorrectionBlock(2, 116)), + new ErrorCorrectionBlocks(110, new ErrorCorrectionBlock(3, 36), new ErrorCorrectionBlock(2, 37)), + new ErrorCorrectionBlocks(160, new ErrorCorrectionBlock(4, 16), new ErrorCorrectionBlock(4, 17)), + new ErrorCorrectionBlocks(192, new ErrorCorrectionBlock(4, 12), new ErrorCorrectionBlock(4, 13))), + new QRCodeVersion( + 10, + 346, + new ErrorCorrectionBlocks(72, new ErrorCorrectionBlock(2, 68), new ErrorCorrectionBlock(2, 69)), + new ErrorCorrectionBlocks(130, new ErrorCorrectionBlock(4, 43), new ErrorCorrectionBlock(1, 44)), + new ErrorCorrectionBlocks(192, new ErrorCorrectionBlock(6, 19), new ErrorCorrectionBlock(2, 20)), + new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(6, 15), new ErrorCorrectionBlock(2, 16))), + new QRCodeVersion( + 11, + 404, + new ErrorCorrectionBlocks(80, new ErrorCorrectionBlock(4, 81)), + new ErrorCorrectionBlocks(150, new ErrorCorrectionBlock(1, 50), new ErrorCorrectionBlock(4, 51)), + new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(4, 22), new ErrorCorrectionBlock(4, 23)), + new ErrorCorrectionBlocks(264, new ErrorCorrectionBlock(3, 12), new ErrorCorrectionBlock(8, 13))), + new QRCodeVersion( + 12, + 466, + new ErrorCorrectionBlocks(96, new ErrorCorrectionBlock(2, 92), new ErrorCorrectionBlock(2, 93)), + new ErrorCorrectionBlocks(176, new ErrorCorrectionBlock(6, 36), new ErrorCorrectionBlock(2, 37)), + new ErrorCorrectionBlocks(260, new ErrorCorrectionBlock(4, 20), new ErrorCorrectionBlock(6, 21)), + new ErrorCorrectionBlocks(308, new ErrorCorrectionBlock(7, 14), new ErrorCorrectionBlock(4, 15))), + new QRCodeVersion( + 13, + 532, + new ErrorCorrectionBlocks(104, new ErrorCorrectionBlock(4, 107)), + new ErrorCorrectionBlocks(198, new ErrorCorrectionBlock(8, 37), new ErrorCorrectionBlock(1, 38)), + new ErrorCorrectionBlocks(288, new ErrorCorrectionBlock(8, 20), new ErrorCorrectionBlock(4, 21)), + new ErrorCorrectionBlocks(352, new ErrorCorrectionBlock(12, 11), new ErrorCorrectionBlock(4, 12))), + new QRCodeVersion( + 14, + 581, + new ErrorCorrectionBlocks(120, new ErrorCorrectionBlock(3, 115), new ErrorCorrectionBlock(1, 116)), + new ErrorCorrectionBlocks(216, new ErrorCorrectionBlock(4, 40), new ErrorCorrectionBlock(5, 41)), + new ErrorCorrectionBlocks(320, new ErrorCorrectionBlock(11, 16), new ErrorCorrectionBlock(5, 17)), + new ErrorCorrectionBlocks(384, new ErrorCorrectionBlock(11, 12), new ErrorCorrectionBlock(5, 13))), + new QRCodeVersion( + 15, + 655, + new ErrorCorrectionBlocks(132, new ErrorCorrectionBlock(5, 87), new ErrorCorrectionBlock(1, 88)), + new ErrorCorrectionBlocks(240, new ErrorCorrectionBlock(5, 41), new ErrorCorrectionBlock(5, 42)), + new ErrorCorrectionBlocks(360, new ErrorCorrectionBlock(5, 24), new ErrorCorrectionBlock(7, 25)), + new ErrorCorrectionBlocks(432, new ErrorCorrectionBlock(11, 12), new ErrorCorrectionBlock(7, 13))), + new QRCodeVersion( + 16, + 733, + new ErrorCorrectionBlocks(144, new ErrorCorrectionBlock(5, 98), new ErrorCorrectionBlock(1, 99)), + new ErrorCorrectionBlocks(280, new ErrorCorrectionBlock(7, 45), new ErrorCorrectionBlock(3, 46)), + new ErrorCorrectionBlocks(408, new ErrorCorrectionBlock(15, 19), new ErrorCorrectionBlock(2, 20)), + new ErrorCorrectionBlocks(480, new ErrorCorrectionBlock(3, 15), new ErrorCorrectionBlock(13, 16))), + new QRCodeVersion( + 17, + 815, + new ErrorCorrectionBlocks(168, new ErrorCorrectionBlock(1, 107), new ErrorCorrectionBlock(5, 108)), + new ErrorCorrectionBlocks(308, new ErrorCorrectionBlock(10, 46), new ErrorCorrectionBlock(1, 47)), + new ErrorCorrectionBlocks(448, new ErrorCorrectionBlock(1, 22), new ErrorCorrectionBlock(15, 23)), + new ErrorCorrectionBlocks(532, new ErrorCorrectionBlock(2, 14), new ErrorCorrectionBlock(17, 15))), + new QRCodeVersion( + 18, + 901, + new ErrorCorrectionBlocks(180, new ErrorCorrectionBlock(5, 120), new ErrorCorrectionBlock(1, 121)), + new ErrorCorrectionBlocks(338, new ErrorCorrectionBlock(9, 43), new ErrorCorrectionBlock(4, 44)), + new ErrorCorrectionBlocks(504, new ErrorCorrectionBlock(17, 22), new ErrorCorrectionBlock(1, 23)), + new ErrorCorrectionBlocks(588, new ErrorCorrectionBlock(2, 14), new ErrorCorrectionBlock(19, 15))), + new QRCodeVersion( + 19, + 991, + new ErrorCorrectionBlocks(196, new ErrorCorrectionBlock(3, 113), new ErrorCorrectionBlock(4, 114)), + new ErrorCorrectionBlocks(364, new ErrorCorrectionBlock(3, 44), new ErrorCorrectionBlock(11, 45)), + new ErrorCorrectionBlocks(546, new ErrorCorrectionBlock(17, 21), new ErrorCorrectionBlock(4, 22)), + new ErrorCorrectionBlocks(650, new ErrorCorrectionBlock(9, 13), new ErrorCorrectionBlock(16, 14))), + new QRCodeVersion( + 20, + 1085, + new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(3, 107), new ErrorCorrectionBlock(5, 108)), + new ErrorCorrectionBlocks(416, new ErrorCorrectionBlock(3, 41), new ErrorCorrectionBlock(13, 42)), + new ErrorCorrectionBlocks(600, new ErrorCorrectionBlock(15, 24), new ErrorCorrectionBlock(5, 25)), + new ErrorCorrectionBlocks(700, new ErrorCorrectionBlock(15, 15), new ErrorCorrectionBlock(10, 16))), + new QRCodeVersion( + 21, + 1156, + new ErrorCorrectionBlocks(224, new ErrorCorrectionBlock(4, 116), new ErrorCorrectionBlock(4, 117)), + new ErrorCorrectionBlocks(442, new ErrorCorrectionBlock(17, 42)), + new ErrorCorrectionBlocks(644, new ErrorCorrectionBlock(17, 22), new ErrorCorrectionBlock(6, 23)), + new ErrorCorrectionBlocks(750, new ErrorCorrectionBlock(19, 16), new ErrorCorrectionBlock(6, 17))), + new QRCodeVersion( + 22, + 1258, + new ErrorCorrectionBlocks(252, new ErrorCorrectionBlock(2, 111), new ErrorCorrectionBlock(7, 112)), + new ErrorCorrectionBlocks(476, new ErrorCorrectionBlock(17, 46)), + new ErrorCorrectionBlocks(690, new ErrorCorrectionBlock(7, 24), new ErrorCorrectionBlock(16, 25)), + new ErrorCorrectionBlocks(816, new ErrorCorrectionBlock(34, 13))), + new QRCodeVersion( + 23, + 1364, + new ErrorCorrectionBlocks(270, new ErrorCorrectionBlock(4, 121), new ErrorCorrectionBlock(5, 122)), + new ErrorCorrectionBlocks(504, new ErrorCorrectionBlock(4, 47), new ErrorCorrectionBlock(14, 48)), + new ErrorCorrectionBlocks(750, new ErrorCorrectionBlock(11, 24), new ErrorCorrectionBlock(14, 25)), + new ErrorCorrectionBlocks(900, new ErrorCorrectionBlock(16, 15), new ErrorCorrectionBlock(14, 16))), + new QRCodeVersion( + 24, + 1474, + new ErrorCorrectionBlocks(300, new ErrorCorrectionBlock(6, 117), new ErrorCorrectionBlock(4, 118)), + new ErrorCorrectionBlocks(560, new ErrorCorrectionBlock(6, 45), new ErrorCorrectionBlock(14, 46)), + new ErrorCorrectionBlocks(810, new ErrorCorrectionBlock(11, 24), new ErrorCorrectionBlock(16, 25)), + new ErrorCorrectionBlocks(960, new ErrorCorrectionBlock(30, 16), new ErrorCorrectionBlock(2, 17))), + new QRCodeVersion( + 25, + 1588, + new ErrorCorrectionBlocks(312, new ErrorCorrectionBlock(8, 106), new ErrorCorrectionBlock(4, 107)), + new ErrorCorrectionBlocks(588, new ErrorCorrectionBlock(8, 47), new ErrorCorrectionBlock(13, 48)), + new ErrorCorrectionBlocks(870, new ErrorCorrectionBlock(7, 24), new ErrorCorrectionBlock(22, 25)), + new ErrorCorrectionBlocks(1050, new ErrorCorrectionBlock(22, 15), new ErrorCorrectionBlock(13, 16))), + new QRCodeVersion( + 26, + 1706, + new ErrorCorrectionBlocks(336, new ErrorCorrectionBlock(10, 114), new ErrorCorrectionBlock(2, 115)), + new ErrorCorrectionBlocks(644, new ErrorCorrectionBlock(19, 46), new ErrorCorrectionBlock(4, 47)), + new ErrorCorrectionBlocks(952, new ErrorCorrectionBlock(28, 22), new ErrorCorrectionBlock(6, 23)), + new ErrorCorrectionBlocks(1110, new ErrorCorrectionBlock(33, 16), new ErrorCorrectionBlock(4, 17))), + new QRCodeVersion( + 27, + 1828, + new ErrorCorrectionBlocks(360, new ErrorCorrectionBlock(8, 122), new ErrorCorrectionBlock(4, 123)), + new ErrorCorrectionBlocks(700, new ErrorCorrectionBlock(22, 45), new ErrorCorrectionBlock(3, 46)), + new ErrorCorrectionBlocks(1020, new ErrorCorrectionBlock(8, 23), new ErrorCorrectionBlock(26, 24)), + new ErrorCorrectionBlocks(1200, new ErrorCorrectionBlock(12, 15), new ErrorCorrectionBlock(28, 16))), + new QRCodeVersion( + 28, + 1921, + new ErrorCorrectionBlocks(390, new ErrorCorrectionBlock(3, 117), new ErrorCorrectionBlock(10, 118)), + new ErrorCorrectionBlocks(728, new ErrorCorrectionBlock(3, 45), new ErrorCorrectionBlock(23, 46)), + new ErrorCorrectionBlocks(1050, new ErrorCorrectionBlock(4, 24), new ErrorCorrectionBlock(31, 25)), + new ErrorCorrectionBlocks(1260, new ErrorCorrectionBlock(11, 15), new ErrorCorrectionBlock(31, 16))), + new QRCodeVersion( + 29, + 2051, + new ErrorCorrectionBlocks(420, new ErrorCorrectionBlock(7, 116), new ErrorCorrectionBlock(7, 117)), + new ErrorCorrectionBlocks(784, new ErrorCorrectionBlock(21, 45), new ErrorCorrectionBlock(7, 46)), + new ErrorCorrectionBlocks(1140, new ErrorCorrectionBlock(1, 23), new ErrorCorrectionBlock(37, 24)), + new ErrorCorrectionBlocks(1350, new ErrorCorrectionBlock(19, 15), new ErrorCorrectionBlock(26, 16))), + new QRCodeVersion( + 30, + 2185, + new ErrorCorrectionBlocks(450, new ErrorCorrectionBlock(5, 115), new ErrorCorrectionBlock(10, 116)), + new ErrorCorrectionBlocks(812, new ErrorCorrectionBlock(19, 47), new ErrorCorrectionBlock(10, 48)), + new ErrorCorrectionBlocks(1200, new ErrorCorrectionBlock(15, 24), new ErrorCorrectionBlock(25, 25)), + new ErrorCorrectionBlocks(1440, new ErrorCorrectionBlock(23, 15), new ErrorCorrectionBlock(25, 16))), + new QRCodeVersion( + 31, + 2323, + new ErrorCorrectionBlocks(480, new ErrorCorrectionBlock(13, 115), new ErrorCorrectionBlock(3, 116)), + new ErrorCorrectionBlocks(868, new ErrorCorrectionBlock(2, 46), new ErrorCorrectionBlock(29, 47)), + new ErrorCorrectionBlocks(1290, new ErrorCorrectionBlock(42, 24), new ErrorCorrectionBlock(1, 25)), + new ErrorCorrectionBlocks(1530, new ErrorCorrectionBlock(23, 15), new ErrorCorrectionBlock(28, 16))), + new QRCodeVersion( + 32, + 2465, + new ErrorCorrectionBlocks(510, new ErrorCorrectionBlock(17, 115)), + new ErrorCorrectionBlocks(924, new ErrorCorrectionBlock(10, 46), new ErrorCorrectionBlock(23, 47)), + new ErrorCorrectionBlocks(1350, new ErrorCorrectionBlock(10, 24), new ErrorCorrectionBlock(35, 25)), + new ErrorCorrectionBlocks(1620, new ErrorCorrectionBlock(19, 15), new ErrorCorrectionBlock(35, 16))), + new QRCodeVersion( + 33, + 2611, + new ErrorCorrectionBlocks(540, new ErrorCorrectionBlock(17, 115), new ErrorCorrectionBlock(1, 116)), + new ErrorCorrectionBlocks(980, new ErrorCorrectionBlock(14, 46), new ErrorCorrectionBlock(21, 47)), + new ErrorCorrectionBlocks(1440, new ErrorCorrectionBlock(29, 24), new ErrorCorrectionBlock(19, 25)), + new ErrorCorrectionBlocks(1710, new ErrorCorrectionBlock(11, 15), new ErrorCorrectionBlock(46, 16))), + new QRCodeVersion( + 34, + 2761, + new ErrorCorrectionBlocks(570, new ErrorCorrectionBlock(13, 115), new ErrorCorrectionBlock(6, 116)), + new ErrorCorrectionBlocks(1036, new ErrorCorrectionBlock(14, 46), new ErrorCorrectionBlock(23, 47)), + new ErrorCorrectionBlocks(1530, new ErrorCorrectionBlock(44, 24), new ErrorCorrectionBlock(7, 25)), + new ErrorCorrectionBlocks(1800, new ErrorCorrectionBlock(59, 16), new ErrorCorrectionBlock(1, 17))), + new QRCodeVersion( + 35, + 2876, + new ErrorCorrectionBlocks(570, new ErrorCorrectionBlock(12, 121), new ErrorCorrectionBlock(7, 122)), + new ErrorCorrectionBlocks(1064, new ErrorCorrectionBlock(12, 47), new ErrorCorrectionBlock(26, 48)), + new ErrorCorrectionBlocks(1590, new ErrorCorrectionBlock(39, 24), new ErrorCorrectionBlock(14, 25)), + new ErrorCorrectionBlocks(1890, new ErrorCorrectionBlock(22, 15), new ErrorCorrectionBlock(41, 16))), + new QRCodeVersion( + 36, + 3034, + new ErrorCorrectionBlocks(600, new ErrorCorrectionBlock(6, 121), new ErrorCorrectionBlock(14, 122)), + new ErrorCorrectionBlocks(1120, new ErrorCorrectionBlock(6, 47), new ErrorCorrectionBlock(34, 48)), + new ErrorCorrectionBlocks(1680, new ErrorCorrectionBlock(46, 24), new ErrorCorrectionBlock(10, 25)), + new ErrorCorrectionBlocks(1980, new ErrorCorrectionBlock(2, 15), new ErrorCorrectionBlock(64, 16))), + new QRCodeVersion( + 37, + 3196, + new ErrorCorrectionBlocks(630, new ErrorCorrectionBlock(17, 122), new ErrorCorrectionBlock(4, 123)), + new ErrorCorrectionBlocks(1204, new ErrorCorrectionBlock(29, 46), new ErrorCorrectionBlock(14, 47)), + new ErrorCorrectionBlocks(1770, new ErrorCorrectionBlock(49, 24), new ErrorCorrectionBlock(10, 25)), + new ErrorCorrectionBlocks(2100, new ErrorCorrectionBlock(24, 15), new ErrorCorrectionBlock(46, 16))), + new QRCodeVersion( + 38, + 3362, + new ErrorCorrectionBlocks(660, new ErrorCorrectionBlock(4, 122), new ErrorCorrectionBlock(18, 123)), + new ErrorCorrectionBlocks(1260, new ErrorCorrectionBlock(13, 46), new ErrorCorrectionBlock(32, 47)), + new ErrorCorrectionBlocks(1860, new ErrorCorrectionBlock(48, 24), new ErrorCorrectionBlock(14, 25)), + new ErrorCorrectionBlocks(2220, new ErrorCorrectionBlock(42, 15), new ErrorCorrectionBlock(32, 16))), + new QRCodeVersion( + 39, + 3532, + new ErrorCorrectionBlocks(720, new ErrorCorrectionBlock(20, 117), new ErrorCorrectionBlock(4, 118)), + new ErrorCorrectionBlocks(1316, new ErrorCorrectionBlock(40, 47), new ErrorCorrectionBlock(7, 48)), + new ErrorCorrectionBlocks(1950, new ErrorCorrectionBlock(43, 24), new ErrorCorrectionBlock(22, 25)), + new ErrorCorrectionBlocks(2310, new ErrorCorrectionBlock(10, 15), new ErrorCorrectionBlock(67, 16))), + new QRCodeVersion( + 40, + 3706, + new ErrorCorrectionBlocks(750, new ErrorCorrectionBlock(19, 118), new ErrorCorrectionBlock(6, 119)), + new ErrorCorrectionBlocks(1372, new ErrorCorrectionBlock(18, 47), new ErrorCorrectionBlock(31, 48)), + new ErrorCorrectionBlocks(2040, new ErrorCorrectionBlock(34, 24), new ErrorCorrectionBlock(34, 25)), + new ErrorCorrectionBlocks(2430, new ErrorCorrectionBlock(20, 15), new ErrorCorrectionBlock(61, 16))), + }; + } +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/QrCode/QrCode.cs b/Toolkit.UI.Controls.Avalonia/QrCode/QrCode.cs index 7c14ba5..ff5c6ea 100644 --- a/Toolkit.UI.Controls.Avalonia/QrCode/QrCode.cs +++ b/Toolkit.UI.Controls.Avalonia/QrCode/QrCode.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading.Tasks; using Avalonia; using Avalonia.Animation; using Avalonia.Controls; @@ -10,6 +6,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Media; using Avalonia.Threading; using Gma.QrCodeNet.Encoding; +using System.Collections; namespace Toolkit.UI.Controls.Avalonia; @@ -20,41 +17,48 @@ namespace Toolkit.UI.Controls.Avalonia; public class QrCode : Control { #region Properties + /// /// Property for the Background brush (i.e. the area that has no data) /// public static readonly StyledProperty BackgroundProperty = Border.BackgroundProperty.AddOwner(); + /// /// Property for the Foreground brush (i.e. the actual data) /// public static readonly StyledProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner(); + /// /// Property indicating how rounded the corners will be /// public static readonly StyledProperty CornerRadiusProperty = Border.CornerRadiusProperty.AddOwner(); + /// /// Property indicating the Quiet Zone (distance between the edge of the control and where the data actually starts) - /// + /// /// Note: The Quiet Zone (aka Padding) is defined in the QC Code standard (ISO 18004) as the width of 4 modules on all /// sides, but is implemented separately in this control. Official support may wish to remove this property as adjusting /// it will technically make the generated QRCodes "non-standard". This implementation does not currently concern itself /// with this as the code itself it not meant for public consumption. /// public static readonly StyledProperty PaddingProperty = Decorator.PaddingProperty.AddOwner(); + /// /// Property indicating whether the Quiet Zone of 4 modules should be added to the QR Code as additional padding. Default: True /// /// Note: Disabling the Quiet Zone makes the generated QRCodes "non-standard" according to the ISO 18004 standard. /// The padding created by the Quiet Zone depends on the module size and therefore on the amount of data. This can be - /// disabled and a fixed can be set instead to have more control over the layout. + /// disabled and a fixed can be set instead to have more control over the layout. /// public static readonly StyledProperty IsQuietZoneEnabledProperty = AvaloniaProperty.Register(nameof(IsQuietZoneEnabled), true); + /// /// Property indicating the Error Correction Code of the generated data. Default: Medium /// /// Note: See for the specific definitions of each value. /// public static readonly StyledProperty ErrorCorrectionProperty = AvaloniaProperty.Register(nameof(ErrorCorrection), EccLevel.Medium); + /// /// Property for the data represented in the QRCode /// @@ -66,52 +70,61 @@ public class QrCode : Control get => GetValue(BackgroundProperty) ?? Brushes.White; set => SetValue(BackgroundProperty, value); } + /// public IBrush Foreground { get => GetValue(ForegroundProperty) ?? Brushes.Black; set => SetValue(ForegroundProperty, value); } + /// public CornerRadius CornerRadius { get => GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } + /// public Thickness Padding { get => GetValue(PaddingProperty); set => SetValue(PaddingProperty, value); } + /// public bool IsQuietZoneEnabled { get => GetValue(IsQuietZoneEnabledProperty); set => SetValue(IsQuietZoneEnabledProperty, value); } + /// public EccLevel ErrorCorrection { get => GetValue(ErrorCorrectionProperty); set => SetValue(ErrorCorrectionProperty, value); } + /// public string? Data { get => GetValue(DataProperty); set => SetValue(DataProperty, value); } - #endregion + + #endregion Properties /// - /// Engine to actually calculate the bit matrix of the QRCode. Currently a Nuget package, but official support may wish to implement and remove such dependency + /// Engine to actually calculate the bit matrix of the QRCode. Currently a Nuget package, but official support may wish to implement and remove such dependency /// private static readonly QrEncoder QrCodeGenerator = new(); + /// /// A cache of currently set bits in the bit matrix. This is used to potentially speed up processing. /// private readonly Hashtable _setBitsTable = new(); + /// /// A cache of the last encoded QRCode. This is used to reuse the last generated data whenever a style property like Width, Height or Padding was changed. /// @@ -119,6 +132,7 @@ public class QrCode : Control // QRCode specs mandate a standard 4-symbol-sized space on each side of the data. We support custom Padding and will ignore this zone when processing private int QuietZoneCount => IsQuietZoneEnabled ? 4 : 0; + private int QuietMargin => QuietZoneCount * 2; /// @@ -170,7 +184,7 @@ public class QrCode : Control { // Error Correction change requires the data to be reprocessed to recalculate the new bit matrix. This is unavoidable. case nameof(ErrorCorrection): - // A change in data obviously indicates the need to update the bit matrix + // A change in data obviously indicates the need to update the bit matrix case nameof(Data): _encodedQrCode = null; break; @@ -213,7 +227,6 @@ public class QrCode : Control _oldQrCodeGeometry = null; InvalidateVisual(); - }); } @@ -694,7 +707,6 @@ public class QrCode : Control // Render background over the foreground as the geometry has "cut outs" that allow the foreground to show through context.DrawGeometry(Background, null, newGeometry); } - } /// @@ -706,14 +718,17 @@ public class QrCode : Control /// The lowest level of error correction where up to ~7% of data can be be recovered if lost and uses the least amount of symbols to represent the data /// Lowest, + /// /// The standard level of error correction where up to ~15% of data can be be recovered if lost and represents a good compromise between a small size and reliability /// Medium, + /// /// A high readability level of error correction where up to ~25% of data can be be recovered if lost but requires a larger footprint to represent the data /// Quality, + /// /// The maximum level of error correction where up to ~30% of data can be be recovered if lost and represents the maximum achievable reliability /// @@ -722,7 +737,7 @@ public class QrCode : Control /// /// Converts from our EccLevel to the one used by whichever algorithm being used. - /// This exists as an abstraction layer for if/when the package or namespace of the actual QR Generator changes so that breaking changes are not introduced + /// This exists as an abstraction layer for if/when the package or namespace of the actual QR Generator changes so that breaking changes are not introduced /// /// The selected ECC Level to convert /// The appropriate ECC Level type used by the generator @@ -748,4 +763,4 @@ public class QrCode : Control BottomRight = 1 << 2, BottomLeft = 1 << 3 } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/SettingsExpander/SettingsExpander.cs b/Toolkit.UI.Controls.Avalonia/SettingsExpander/SettingsExpander.cs index 90c8807..6fd231f 100644 --- a/Toolkit.UI.Controls.Avalonia/SettingsExpander/SettingsExpander.cs +++ b/Toolkit.UI.Controls.Avalonia/SettingsExpander/SettingsExpander.cs @@ -4,7 +4,7 @@ namespace Toolkit.UI.Controls.Avalonia; public class SettingsExpander : FluentAvalonia.UI.Controls.SettingsExpander { - protected override Type StyleKeyOverride => + protected override Type StyleKeyOverride => typeof(SettingsExpander); public new static readonly StyledProperty DescriptionProperty = @@ -30,4 +30,4 @@ public class SettingsExpanderItem : FluentAvalonia.UI.Controls.SettingsExpanderI get => GetValue(DescriptionProperty); set => SetValue(DescriptionProperty, value); } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/SpacedGrid/ISpacingDefinition.cs b/Toolkit.UI.Controls.Avalonia/SpacedGrid/ISpacingDefinition.cs index bfb9320..1ea1e1e 100644 --- a/Toolkit.UI.Controls.Avalonia/SpacedGrid/ISpacingDefinition.cs +++ b/Toolkit.UI.Controls.Avalonia/SpacedGrid/ISpacingDefinition.cs @@ -3,4 +3,4 @@ public interface ISpacingDefinition { double Spacing { get; set; } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacedGrid.cs b/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacedGrid.cs index df4d52a..7536872 100644 --- a/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacedGrid.cs +++ b/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacedGrid.cs @@ -59,7 +59,7 @@ public class SpacedGrid : Grid } } - private void OnCollectionChanged(object? sender, + private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) { if (args.Action == NotifyCollectionChangedAction.Add || args.Action == NotifyCollectionChangedAction.Replace) diff --git a/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingColumnDefinition.cs b/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingColumnDefinition.cs index 3b213f6..eff3fdc 100644 --- a/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingColumnDefinition.cs +++ b/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingColumnDefinition.cs @@ -11,4 +11,4 @@ public class SpacingColumnDefinition(double width) : get => Width.Value; set => Width = new GridLength(value, GridUnitType.Pixel); } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingRowDefinition.cs b/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingRowDefinition.cs index 6d6bc43..15909c8 100644 --- a/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingRowDefinition.cs +++ b/Toolkit.UI.Controls.Avalonia/SpacedGrid/SpacingRowDefinition.cs @@ -11,4 +11,4 @@ public class SpacingRowDefinition(double height) : get => Height.Value; set => Height = new GridLength(value, GridUnitType.Pixel); } -} +} \ No newline at end of file diff --git a/Toolkit.UI.Controls.Avalonia/Themes/ThemeResources.axaml.cs b/Toolkit.UI.Controls.Avalonia/Themes/ThemeResources.axaml.cs index 6989d3e..2df8fe9 100644 --- a/Toolkit.UI.Controls.Avalonia/Themes/ThemeResources.axaml.cs +++ b/Toolkit.UI.Controls.Avalonia/Themes/ThemeResources.axaml.cs @@ -10,4 +10,4 @@ public class ThemeResources : { AvaloniaXamlLoader.Load(provider, this); } -} +} \ No newline at end of file