diff --git a/qodana.yaml b/qodana.yaml index 2084d2f..5505d1b 100644 --- a/qodana.yaml +++ b/qodana.yaml @@ -5,14 +5,61 @@ version: "1.0" linter: qodana-dotnet withinDocker: false -profile: - name: qodana.recommended - dotnet: solution: HashTool.slnx +# The shipped code. Tests and benchmarks are checked by the compiler, the analyzers and SonarCloud; the legacy client is +# pinned to Velopack 0.0.1298 on purpose (the release upgrade gate runs it like a Hash Tool 1.1.x client). exclude: - name: All paths: - # Pinned to Velopack 0.0.1298 on purpose: the release upgrade gate runs it like a Hash Tool 1.1.x client. - - tests/Compat + - tests + - bench + +profile: + base: + name: qodana.recommended + groups: + - groupId: RoslynAnalyzers + groups: + - "category:C#/Roslyn Analyzers" + inspections: + # Roslyn analyzers (Meziantou, .NET, CommunityToolkit.Mvvm) already run in every build, where their warnings fail + # CI; their suggestions are not repeated here (SonarCloud ignores them too). + - group: RoslynAnalyzers + enabled: false + # Translations may equal the English text: en-GB/en-IN/en-SG, product and technical names. + - inspection: OverriddenWithSameValue + ignore: + - "src/HashTool.App/Lang/**" + # Compiled bindings such as $parent[Window].((vm:MainWindowViewModel)DataContext).X: the data context is set by the + # view that hosts the control. + - inspection: Xaml.PossibleNullReferenceException + enabled: false + # "accent" comes from the Fluent theme; "hashInput" marks the expected-hash box for code-behind. + - inspection: Xaml.StyleClassNotFound + enabled: false + # OnXChanged(value) partial methods are declared by CommunityToolkit.Mvvm's generator. + - inspection: UnusedParameterInPartialMethod + enabled: false + # Drag and drop handlers must be async void; their exceptions reach Dispatcher.UIThread.UnhandledException. + - inspection: AsyncVoidLambda + ignore: + - "src/HashTool.App/Views/**" + # The application manifest uses the Windows side-by-side schema, which the XML checker does not know. + - inspection: XmlHighlighting + ignore: + - "src/HashTool.App/app.manifest" + # Avalonia's application class, completed by the XAML compiler. + - inspection: PartialTypeWithSinglePart + ignore: + - "src/HashTool.App/App.axaml.cs" + # The smoke test cancels the token from a continuation that runs before the dispatcher loop returns. + - inspection: AccessToDisposedClosure + ignore: + - "src/HashTool.App/Infrastructure/SmokeTest.cs" + +failureConditions: + severityThresholds: + critical: 0 + high: 0 diff --git a/src/HashTool.App/App.axaml.cs b/src/HashTool.App/App.axaml.cs index 2cddf82..9d2789d 100644 --- a/src/HashTool.App/App.axaml.cs +++ b/src/HashTool.App/App.axaml.cs @@ -36,7 +36,7 @@ public partial class App : Application }; } - Dispatcher.UIThread.UnhandledException += (_, e) => + Dispatcher.UIThread.UnhandledException += (sender, e) => { logger.LogError(e.Exception, "Unhandled UI exception"); e.Handled = true; diff --git a/src/HashTool.App/AppHost.cs b/src/HashTool.App/AppHost.cs index fa8d041..47729ff 100644 --- a/src/HashTool.App/AppHost.cs +++ b/src/HashTool.App/AppHost.cs @@ -4,8 +4,6 @@ using HashTool.App.Infrastructure.Logging; using HashTool.App.Services; using HashTool.App.Services.Theme; using HashTool.App.ViewModels; -using HashTool.Core.Configuration; -using HashTool.Core.Hashing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; diff --git a/src/HashTool.App/Converters/FontNameConverter.cs b/src/HashTool.App/Converters/FontNameConverter.cs index 13e62e4..20cd9d5 100644 --- a/src/HashTool.App/Converters/FontNameConverter.cs +++ b/src/HashTool.App/Converters/FontNameConverter.cs @@ -17,6 +17,6 @@ public sealed class FontNameConverter : IValueConverter _ => value }; - public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException(); } diff --git a/src/HashTool.App/Converters/HashMaskConverter.cs b/src/HashTool.App/Converters/HashMaskConverter.cs index ed66916..5ad675a 100644 --- a/src/HashTool.App/Converters/HashMaskConverter.cs +++ b/src/HashTool.App/Converters/HashMaskConverter.cs @@ -7,9 +7,9 @@ namespace HashTool.App.Converters; public class HashMaskConverter : IMultiValueConverter { - public object? Convert(IList values, Type targetType, object? parameter, CultureInfo culture) + public object Convert(IList values, Type targetType, object? parameter, CultureInfo culture) { - if (values == null || values.Count < 3) return ""; + if (values.Count < 3) return ""; var hash = values[0] as string ?? ""; var isMaskingEnabled = values[1] as bool? ?? false; diff --git a/src/HashTool.App/Converters/LabelConverters.cs b/src/HashTool.App/Converters/LabelConverters.cs index 49aa1c4..5779a8e 100644 --- a/src/HashTool.App/Converters/LabelConverters.cs +++ b/src/HashTool.App/Converters/LabelConverters.cs @@ -5,7 +5,6 @@ using Avalonia.Data.Converters; using HashTool.App.Models; using HashTool.App.Services; using HashTool.App.ViewModels; -using HashTool.Core.Configuration; namespace HashTool.App.Converters; diff --git a/src/HashTool.App/Infrastructure/AppPaths.cs b/src/HashTool.App/Infrastructure/AppPaths.cs index 02b4e82..687d3b4 100644 --- a/src/HashTool.App/Infrastructure/AppPaths.cs +++ b/src/HashTool.App/Infrastructure/AppPaths.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using HashTool.Core.Configuration; namespace HashTool.App.Infrastructure; diff --git a/src/HashTool.App/Infrastructure/SingleInstance.cs b/src/HashTool.App/Infrastructure/SingleInstance.cs index 5fbd216..c78474d 100644 --- a/src/HashTool.App/Infrastructure/SingleInstance.cs +++ b/src/HashTool.App/Infrastructure/SingleInstance.cs @@ -67,6 +67,7 @@ public sealed partial class SingleInstance : IDisposable request ??= new ActivationRequest(ActivationVerb.Auto, []); var deadline = DateTime.UtcNow + timeout; var delay = 50; + Span header = stackalloc byte[4]; while (DateTime.UtcNow < deadline) { try @@ -75,7 +76,6 @@ public sealed partial class SingleInstance : IDisposable client.Connect(Math.Max(100, (int)(deadline - DateTime.UtcNow).TotalMilliseconds)); if (OperatingSystem.IsWindows()) AllowSetForegroundWindow(-1); var payload = JsonSerializer.SerializeToUtf8Bytes(new PipeMessage(request.Verb, [.. request.Paths]), PipeJsonContext.Default.PipeMessage); - Span header = stackalloc byte[4]; BinaryPrimitives.WriteInt32LittleEndian(header, payload.Length); client.Write(header); client.Write(payload); @@ -180,9 +180,9 @@ public sealed partial class SingleInstance : IDisposable _stop.Dispose(); } + // Returns whether it worked; there is nothing to do when it did not. [LibraryImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool AllowSetForegroundWindow(int processId); + private static partial void AllowSetForegroundWindow(int processId); /// Wire format; a single constructor so the source-generated serializer can create it. internal sealed record PipeMessage(ActivationVerb Verb, string[] Paths); diff --git a/src/HashTool.App/Infrastructure/SmokeTest.cs b/src/HashTool.App/Infrastructure/SmokeTest.cs index 673ad54..b02bad5 100644 --- a/src/HashTool.App/Infrastructure/SmokeTest.cs +++ b/src/HashTool.App/Infrastructure/SmokeTest.cs @@ -82,7 +82,7 @@ public static class SmokeTest // Hash a text. main.Text.Text = "123456789"; await main.Text.Pending; - var textHash = main.Text.Results.Single(r => r.Algorithm == Core.Hashing.HashType.SHA256).Hash; + var textHash = main.Text.Results.Single(r => r.Algorithm == HashType.SHA256).Hash; if (!string.Equals(textHash, Sha256Of123456789, StringComparison.OrdinalIgnoreCase)) report.Errors.Add($"Text: unexpected hash {textHash}"); @@ -110,7 +110,7 @@ public static class SmokeTest { var file = Path.Combine(folder.FullName, "check.txt"); await File.WriteAllTextAsync(file, "123456789"); - main.Create.SelectedAlgorithm = Core.Hashing.HashType.SHA256; + main.Create.SelectedAlgorithm = HashType.SHA256; await main.Create.AddPathsAsync([file]); await main.Create.RunAllCommand.ExecuteAsync(null); var created = main.Create.Items.Single(); diff --git a/src/HashTool.App/Services/LocalizationService.cs b/src/HashTool.App/Services/LocalizationService.cs index 9dd423a..a7ae3f2 100644 --- a/src/HashTool.App/Services/LocalizationService.cs +++ b/src/HashTool.App/Services/LocalizationService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; @@ -42,6 +43,9 @@ internal sealed record LanguageEntry(string Name, string Code); /// public sealed partial class LocalizationService : ObservableObject { + /// Raised for Localization[Key] bindings: every translated string may have changed. + private static readonly PropertyChangedEventArgs IndexerChanged = new("Item[]"); + private static readonly Dictionary PreferredVariants = new(StringComparer.OrdinalIgnoreCase) { ["zh"] = "zh-Hans-CN", @@ -153,7 +157,7 @@ public sealed partial class LocalizationService : ObservableObject Culture = ApplyCulture(code); _cache.Clear(); RefreshAutoName(); - OnPropertyChanged("Item[]"); + OnPropertyChanged(IndexerChanged); LanguageChanged?.Invoke(this, EventArgs.Empty); } diff --git a/src/HashTool.App/Services/SettingsService.cs b/src/HashTool.App/Services/SettingsService.cs index d2683f9..03a2968 100644 --- a/src/HashTool.App/Services/SettingsService.cs +++ b/src/HashTool.App/Services/SettingsService.cs @@ -1,7 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; -using HashTool.Core.Configuration; using Microsoft.Extensions.Logging; namespace HashTool.App.Services; @@ -26,7 +25,7 @@ public sealed class SettingsService : IDisposable _logger = logger; LoadResult = store.Load(out var settings); Current = settings; - _saveTimer = new Timer(_ => _ = SaveNowAsync(), null, Timeout.Infinite, Timeout.Infinite); + _saveTimer = new Timer(state => _ = SaveNowAsync(), null, Timeout.Infinite, Timeout.Infinite); _logger.LogInformation("Settings {Result} from {Path}", LoadResult, store.FilePath); } diff --git a/src/HashTool.App/Services/Theme/ThemePalettes.cs b/src/HashTool.App/Services/Theme/ThemePalettes.cs index ef52d4c..9ef2d0a 100644 --- a/src/HashTool.App/Services/Theme/ThemePalettes.cs +++ b/src/HashTool.App/Services/Theme/ThemePalettes.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using Avalonia.Media; -using HashTool.Core.Configuration; namespace HashTool.App.Services.Theme; diff --git a/src/HashTool.App/Services/Theme/ThemeService.cs b/src/HashTool.App/Services/Theme/ThemeService.cs index baada50..ec7c3ef 100644 --- a/src/HashTool.App/Services/Theme/ThemeService.cs +++ b/src/HashTool.App/Services/Theme/ThemeService.cs @@ -4,7 +4,6 @@ using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; using CommunityToolkit.Mvvm.ComponentModel; -using HashTool.Core.Configuration; namespace HashTool.App.Services.Theme; diff --git a/src/HashTool.App/ViewModels/AboutViewModel.cs b/src/HashTool.App/ViewModels/AboutViewModel.cs index c5b91e1..59a5a43 100644 --- a/src/HashTool.App/ViewModels/AboutViewModel.cs +++ b/src/HashTool.App/ViewModels/AboutViewModel.cs @@ -67,7 +67,7 @@ public sealed partial class AboutViewModel : ObservableObject Library("Avalonia UI", typeof(Avalonia.Application), "MIT", "https://avaloniaui.net/"), Library("Inter font", typeof(Avalonia.Fonts.Inter.InterFontCollection), "SIL OFL 1.1", "https://rsms.me/inter/"), Library("Blake3.NET", typeof(Blake3.Hasher), "BSD-2-Clause", "https://github.com/xoofx/Blake3.NET"), - Library("CommunityToolkit.Mvvm", typeof(CommunityToolkit.Mvvm.ComponentModel.ObservableObject), "MIT", "https://github.com/CommunityToolkit/dotnet"), + Library("CommunityToolkit.Mvvm", typeof(ObservableObject), "MIT", "https://github.com/CommunityToolkit/dotnet"), Library("Material.Icons.Avalonia", typeof(Material.Icons.Avalonia.MaterialIcon), "MIT", "https://github.com/SKProCH/Material.Icons"), Library("Microsoft.Extensions.*", typeof(Microsoft.Extensions.Logging.ILogger), "MIT", "https://github.com/dotnet/runtime"), Library("System.IO.Hashing", typeof(System.IO.Hashing.XxHash3), "MIT", "https://github.com/dotnet/runtime"), diff --git a/src/HashTool.App/ViewModels/CheckHashViewModel.cs b/src/HashTool.App/ViewModels/CheckHashViewModel.cs index cffcd08..e642090 100644 --- a/src/HashTool.App/ViewModels/CheckHashViewModel.cs +++ b/src/HashTool.App/ViewModels/CheckHashViewModel.cs @@ -10,7 +10,6 @@ using HashTool.App.Models; using HashTool.App.Services; using HashTool.Core.Checksums; using HashTool.Core.Files; -using HashTool.Core.Hashing; using HashTool.Core.Processing; using Microsoft.Extensions.Logging; diff --git a/src/HashTool.App/ViewModels/CreateHashViewModel.cs b/src/HashTool.App/ViewModels/CreateHashViewModel.cs index 5c0135d..bfdcf32 100644 --- a/src/HashTool.App/ViewModels/CreateHashViewModel.cs +++ b/src/HashTool.App/ViewModels/CreateHashViewModel.cs @@ -12,7 +12,6 @@ using HashTool.App.Models; using HashTool.App.Services; using HashTool.Core.Checksums; using HashTool.Core.Files; -using HashTool.Core.Hashing; using HashTool.Core.Processing; using Microsoft.Extensions.Logging; @@ -89,7 +88,7 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase var items = ItemsWithResults(); if (items.Count == 0) { - await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"], DialogIcon.Information); + await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"]); return; } @@ -104,7 +103,7 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase types.Add(new FileTypeChoice(L["FileType_Json"], "*.json", ExportFormat.Json)); types.Add(new FileTypeChoice(L["FileType_Csv"], "*.csv", ExportFormat.Csv)); - var preferred = types.FirstOrDefault(t => (ExportFormat)t.Tag! == Settings.DefaultExportFormat) ?? types[0]; + var preferred = types.FirstOrDefault(type => (ExportFormat)type.Tag! == Settings.DefaultExportFormat) ?? types[0]; types.Remove(preferred); types.Insert(0, preferred); var format = (ExportFormat)preferred.Tag!; @@ -135,7 +134,7 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase var items = ItemsWithResults(); if (items.Count == 0) { - await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"], DialogIcon.Information); + await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"]); return; } diff --git a/src/HashTool.App/ViewModels/DeveloperViewModel.cs b/src/HashTool.App/ViewModels/DeveloperViewModel.cs index 8e8fd86..51989ed 100644 --- a/src/HashTool.App/ViewModels/DeveloperViewModel.cs +++ b/src/HashTool.App/ViewModels/DeveloperViewModel.cs @@ -24,7 +24,6 @@ public sealed partial class DeveloperViewModel : ObservableObject private readonly IStorageService _storage; private readonly ILauncherService _launcher; private readonly ConcurrentQueue _incoming = new(); - private readonly DispatcherTimer _timer; [ObservableProperty] private LocalizationProxy _localization; [ObservableProperty] private LogLevel _minimumLevel = LogLevel.Debug; @@ -42,8 +41,8 @@ public sealed partial class DeveloperViewModel : ObservableObject Entries.AddRange(sink.Snapshot()); sink.EntryAdded += (_, e) => _incoming.Enqueue(e.Entry); - _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Flush()); - _timer.Start(); + // The dispatcher keeps a running timer alive. + new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Flush()).Start(); } /// Entries at or above , newest last. diff --git a/src/HashTool.App/ViewModels/FileItem.cs b/src/HashTool.App/ViewModels/FileItem.cs index 521a9f7..94879ff 100644 --- a/src/HashTool.App/ViewModels/FileItem.cs +++ b/src/HashTool.App/ViewModels/FileItem.cs @@ -3,7 +3,6 @@ using System.IO; using System.Threading; using CommunityToolkit.Mvvm.ComponentModel; using HashTool.App.Models; -using HashTool.Core.Hashing; namespace HashTool.App.ViewModels; @@ -58,7 +57,7 @@ public sealed partial class FileItem : ObservableObject public long Size { get; } - public string SizeText => Core.ByteSize.Format(Size); + public string SizeText => ByteSize.Format(Size); [ObservableProperty] private HashType _algorithm; diff --git a/src/HashTool.App/ViewModels/FileListViewModelBase.cs b/src/HashTool.App/ViewModels/FileListViewModelBase.cs index 213e0b9..e744292 100644 --- a/src/HashTool.App/ViewModels/FileListViewModelBase.cs +++ b/src/HashTool.App/ViewModels/FileListViewModelBase.cs @@ -14,7 +14,6 @@ using HashTool.App.Infrastructure; using HashTool.App.Models; using HashTool.App.Services; using HashTool.Core.Files; -using HashTool.Core.Hashing; using HashTool.Core.Processing; using Microsoft.Extensions.Logging; @@ -113,7 +112,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob protected LocalizationService L => Services.Localization; - protected Core.Configuration.AppSettings Settings => Services.Settings.Current; + protected AppSettings Settings => Services.Settings.Current; /// Visible (filtered) items. public AvaloniaList Items { get; } = []; @@ -527,7 +526,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob protected async Task OfferElevationAsync(IReadOnlyList items) { if (!Elevation.CanRestartElevated || !items.Any(i => i.Status == ItemStatus.AccessDenied)) return; - if (!await Services.Dialogs.ConfirmAsync(L["Btn_RestartAdmin"], L["Msg_AccessDeniedRestart"], DialogIcon.Question)) return; + if (!await Services.Dialogs.ConfirmAsync(L["Btn_RestartAdmin"], L["Msg_AccessDeniedRestart"])) return; if (Elevation.RestartElevated(ElevationVerb, _all.Select(i => SourcePathForRestart(i)).Distinct(_byPath.Comparer).ToList())) RequestShutdown?.Invoke(this, EventArgs.Empty); } diff --git a/src/HashTool.App/ViewModels/MainWindowViewModel.cs b/src/HashTool.App/ViewModels/MainWindowViewModel.cs index 5a287d3..9326d71 100644 --- a/src/HashTool.App/ViewModels/MainWindowViewModel.cs +++ b/src/HashTool.App/ViewModels/MainWindowViewModel.cs @@ -8,7 +8,6 @@ using HashTool.App.Infrastructure; using HashTool.App.Services; using HashTool.App.Services.Theme; using HashTool.Core.Checksums; -using HashTool.Core.Configuration; namespace HashTool.App.ViewModels; diff --git a/src/HashTool.App/ViewModels/SettingsViewModel.cs b/src/HashTool.App/ViewModels/SettingsViewModel.cs index 1e2380e..a227aba 100644 --- a/src/HashTool.App/ViewModels/SettingsViewModel.cs +++ b/src/HashTool.App/ViewModels/SettingsViewModel.cs @@ -4,16 +4,12 @@ using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; -using Avalonia.Media; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using HashTool.App.Infrastructure; -using HashTool.App.Infrastructure.Logging; using HashTool.App.Services; using HashTool.App.Services.Theme; using HashTool.Core.Checksums; -using HashTool.Core.Configuration; -using HashTool.Core.Hashing; using Microsoft.Extensions.Logging; namespace HashTool.App.ViewModels; @@ -111,7 +107,7 @@ public sealed partial class SettingsViewModel : ObservableObject // ------------------------------------------------------------------ language & appearance - public LanguageItem SelectedLanguage + public LanguageItem? SelectedLanguage { get => Loc.SelectedLanguage; set diff --git a/src/HashTool.App/Views/FocusHandOff.cs b/src/HashTool.App/Views/Controls/FocusHandOff.cs similarity index 96% rename from src/HashTool.App/Views/FocusHandOff.cs rename to src/HashTool.App/Views/Controls/FocusHandOff.cs index 484fc87..207268e 100644 --- a/src/HashTool.App/Views/FocusHandOff.cs +++ b/src/HashTool.App/Views/Controls/FocusHandOff.cs @@ -36,7 +36,7 @@ public static class FocusHandOff // The target usually becomes visible in the same update, possibly after this control was hidden. Dispatcher.UIThread.Post(() => { - var focused = topLevel.FocusManager?.GetFocusedElement(); + var focused = topLevel.FocusManager.GetFocusedElement(); if ((focused is null || ReferenceEquals(focused, topLevel)) && ReferenceEquals(TopLevel.GetTopLevel(target), topLevel) && target.IsEffectivelyVisible && target.IsEffectivelyEnabled) target.Focus(NavigationMethod.Tab); diff --git a/src/HashTool.App/Views/HighlightTextBlock.axaml b/src/HashTool.App/Views/Controls/HighlightTextBlock.axaml similarity index 100% rename from src/HashTool.App/Views/HighlightTextBlock.axaml rename to src/HashTool.App/Views/Controls/HighlightTextBlock.axaml diff --git a/src/HashTool.App/Views/HighlightTextBlock.axaml.cs b/src/HashTool.App/Views/Controls/HighlightTextBlock.axaml.cs similarity index 100% rename from src/HashTool.App/Views/HighlightTextBlock.axaml.cs rename to src/HashTool.App/Views/Controls/HighlightTextBlock.axaml.cs diff --git a/src/HashTool.App/Views/RowTabNavigation.cs b/src/HashTool.App/Views/Controls/RowTabNavigation.cs similarity index 98% rename from src/HashTool.App/Views/RowTabNavigation.cs rename to src/HashTool.App/Views/Controls/RowTabNavigation.cs index 6ac98f3..89076e2 100644 --- a/src/HashTool.App/Views/RowTabNavigation.cs +++ b/src/HashTool.App/Views/Controls/RowTabNavigation.cs @@ -33,7 +33,7 @@ public static class RowTabNavigation private static void OnKeyDown(object? sender, KeyEventArgs e) { if (e.Handled || e.Key != Key.Tab || (e.KeyModifiers & ~KeyModifiers.Shift) != KeyModifiers.None) return; - if (TopLevel.GetTopLevel(sender as Visual)?.FocusManager?.GetFocusedElement() is not Control focused) return; + if (TopLevel.GetTopLevel(sender as Visual)?.FocusManager.GetFocusedElement() is not Control focused) return; var row = focused as ListBoxItem ?? focused.FindAncestorOfType(); if (row is null) return; diff --git a/src/HashTool.App/Views/MainWindow.axaml.cs b/src/HashTool.App/Views/MainWindow.axaml.cs index c7dcf7a..79fc79b 100644 --- a/src/HashTool.App/Views/MainWindow.axaml.cs +++ b/src/HashTool.App/Views/MainWindow.axaml.cs @@ -3,7 +3,6 @@ using Avalonia; using Avalonia.Controls; using HashTool.App.Services; using HashTool.App.ViewModels; -using HashTool.Core.Configuration; namespace HashTool.App.Views; diff --git a/src/HashTool.Cli/HashToolCommand.cs b/src/HashTool.Cli/HashToolCommand.cs index e01ba52..4084f1a 100644 --- a/src/HashTool.Cli/HashToolCommand.cs +++ b/src/HashTool.Cli/HashToolCommand.cs @@ -7,7 +7,6 @@ using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; -using HashTool.Core.Checksums; using HashTool.Core.Hashing; namespace HashTool.Cli; diff --git a/src/HashTool.Cli/VerifyCommand.cs b/src/HashTool.Cli/VerifyCommand.cs index b708e3c..2010549 100644 --- a/src/HashTool.Cli/VerifyCommand.cs +++ b/src/HashTool.Cli/VerifyCommand.cs @@ -132,7 +132,7 @@ internal static class VerifyCommand private static string Count(int count, string singular, string plural) => $"{count} {(count == 1 ? singular : plural)}"; - internal readonly record struct Outcome(HashMatch Match, HashType? Algorithm, Exception? Error) + internal readonly record struct Outcome(HashMatch Match, Exception? Error) { public bool IsOk => Error is null && Match is HashMatch.Match or HashMatch.LegacyByteOrderMatch; @@ -151,7 +151,7 @@ internal static class VerifyCommand internal static async Task CheckAsync(HashEngine engine, string path, string expected, IReadOnlyList candidates, CancellationToken cancellationToken) { - if (candidates.Count == 0) return new Outcome(HashMatch.LengthMismatch, null, null); + if (candidates.Count == 0) return new Outcome(HashMatch.LengthMismatch, null); HashResult[] results; try { @@ -159,13 +159,13 @@ internal static class VerifyCommand } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - return new Outcome(HashMatch.Mismatch, null, ex); + return new Outcome(HashMatch.Mismatch, ex); } var matches = results.Select(r => (Result: r, Match: HashMatcher.Compare(expected, r))).ToList(); var best = matches.FirstOrDefault(m => m.Match == HashMatch.Match); if (best.Result is null) best = matches.FirstOrDefault(m => m.Match == HashMatch.LegacyByteOrderMatch); if (best.Result is null) best = matches[0]; - return new Outcome(best.Match, best.Result.Algorithm, null); + return new Outcome(best.Match, null); } } diff --git a/src/HashTool.Core/Checksums/ChecksumParser.cs b/src/HashTool.Core/Checksums/ChecksumParser.cs index f25d651..94101ab 100644 --- a/src/HashTool.Core/Checksums/ChecksumParser.cs +++ b/src/HashTool.Core/Checksums/ChecksumParser.cs @@ -196,7 +196,7 @@ public static partial class ChecksumParser hash = HashMatcher.Normalize(hash); if (!HashMatcher.IsHex(hash)) return false; - HashType? algorithm = null; + HashType algorithm; var guessed = false; if (explicitType is { } e && HashAlgorithms.HexLength(e) == hash.Length) algorithm = e; else if (explicitType is not null) return false; diff --git a/src/HashTool.Core/Checksums/ChecksumWriter.cs b/src/HashTool.Core/Checksums/ChecksumWriter.cs index 241bbab..f9b408d 100644 --- a/src/HashTool.Core/Checksums/ChecksumWriter.cs +++ b/src/HashTool.Core/Checksums/ChecksumWriter.cs @@ -29,7 +29,8 @@ public static class ChecksumWriter { public static string Write(IEnumerable lines, ExportFormat format, HexCase letterCase = HexCase.Lower) { - using var writer = new StringWriter(CultureInfo.InvariantCulture) { NewLine = "\n" }; + using var writer = new StringWriter(CultureInfo.InvariantCulture); + writer.NewLine = "\n"; Write(writer, lines, format, letterCase); return writer.ToString(); } diff --git a/src/HashTool.Core/Files/FileEnumerator.cs b/src/HashTool.Core/Files/FileEnumerator.cs index bc8f8ea..12bf86e 100644 --- a/src/HashTool.Core/Files/FileEnumerator.cs +++ b/src/HashTool.Core/Files/FileEnumerator.cs @@ -72,10 +72,10 @@ public static class FileEnumerator try { enumerator = new FileSystemEnumerable(Path.GetFullPath(directory), - static (ref FileSystemEntry entry) => new FileEntry(entry.ToFullPath(), entry.Length), enumerationOptions) + static (ref entry) => new FileEntry(entry.ToFullPath(), entry.Length), enumerationOptions) { - ShouldIncludePredicate = static (ref FileSystemEntry entry) => !entry.IsDirectory, - ShouldRecursePredicate = static (ref FileSystemEntry entry) => !IsLink(ref entry) + ShouldIncludePredicate = static (ref entry) => !entry.IsDirectory, + ShouldRecursePredicate = static (ref entry) => !IsLink(ref entry) } .GetEnumerator(); } diff --git a/src/HashTool.Core/Hashing/HashEngine.cs b/src/HashTool.Core/Hashing/HashEngine.cs index beb4440..2d81133 100644 --- a/src/HashTool.Core/Hashing/HashEngine.cs +++ b/src/HashTool.Core/Hashing/HashEngine.cs @@ -74,15 +74,16 @@ public sealed class HashEngine(HashEngineOptions? options = null) ArgumentNullException.ThrowIfNull(algorithms); if (algorithms.Count == 0) throw new ArgumentException("At least one algorithm is required.", nameof(algorithms)); - var functions = new HashFunction[algorithms.Count]; + // Only the functions created so far are disposed if creating one of them fails. + var functions = new List(algorithms.Count); var current = ArrayPool.Shared.Rent(bufferSize); var next = ArrayPool.Shared.Rent(bufferSize); ValueTask pendingRead = default; var readInFlight = false; try { - for (var i = 0; i < functions.Length; i++) - functions[i] = HashFunction.Create(algorithms[i], _options.Blake3ParallelThreshold); + foreach (var algorithm in algorithms) + functions.Add(HashFunction.Create(algorithm, _options.Blake3ParallelThreshold)); pendingRead = stream.ReadAsync(current.AsMemory(0, bufferSize), cancellationToken); readInFlight = true; @@ -101,8 +102,8 @@ public sealed class HashEngine(HashEngineOptions? options = null) (current, next) = (next, current); } - var results = new HashResult[functions.Length]; - for (var i = 0; i < functions.Length; i++) + var results = new HashResult[functions.Count]; + for (var i = 0; i < functions.Count; i++) results[i] = new HashResult(algorithms[i], functions[i].GetHash()); return results; } @@ -121,20 +122,20 @@ public sealed class HashEngine(HashEngineOptions? options = null) } } - foreach (var function in functions) function?.Dispose(); + foreach (var function in functions) function.Dispose(); ArrayPool.Shared.Return(current); ArrayPool.Shared.Return(next); } } - private static void Append(HashFunction[] functions, byte[] buffer, int count) + private static void Append(List functions, byte[] buffer, int count) { - if (functions.Length == 1) + if (functions.Count == 1) { functions[0].Append(buffer.AsSpan(0, count)); return; } - Parallel.For(0, functions.Length, i => functions[i].Append(buffer.AsSpan(0, count))); + Parallel.For(0, functions.Count, i => functions[i].Append(buffer.AsSpan(0, count))); } }