diff --git a/.editorconfig b/.editorconfig index d8419a3..d3eadbc 100644 --- a/.editorconfig +++ b/.editorconfig @@ -63,3 +63,19 @@ dotnet_naming_symbols.private_fields.applicable_kinds = field dotnet_naming_symbols.private_fields.applicable_accessibilities = private dotnet_naming_style.underscore_camel.capitalization = camel_case dotnet_naming_style.underscore_camel.required_prefix = _ + +# Meziantou.Analyzer rules that do not fit this code base. +dotnet_diagnostic.MA0006.severity = none # string == is already ordinal +dotnet_diagnostic.MA0016.severity = none # concrete collection types in signatures are fine here +dotnet_diagnostic.MA0048.severity = none # small related types share a file +dotnet_diagnostic.MA0049.severity = none # HashTool.App.App +dotnet_diagnostic.MA0051.severity = none # method length + +# UI code, tests and benchmarks resume on the caller's context; async void is how UI event handlers are written. +[{src/HashTool.App/**.cs,tests/**.cs,bench/**.cs}] +dotnet_diagnostic.MA0004.severity = none +dotnet_diagnostic.MA0147.severity = none + +[{tests/**.cs,bench/**.cs}] +dotnet_diagnostic.MA0002.severity = none +dotnet_diagnostic.MA0009.severity = none diff --git a/Directory.Build.props b/Directory.Build.props index 2ec7fd3..4699372 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,7 +7,7 @@ disable - 1.1.3 + 1.2.0 poli0981 poli0981 Hash Tool @@ -23,5 +23,17 @@ true all low + + + true + true + + $(NoWarn);CS1591;CS1573 + + + + + + diff --git a/Directory.Packages.props b/Directory.Packages.props index 41dc890..9eeb389 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,6 +17,7 @@ + @@ -24,6 +25,15 @@ + + + + + + + + + diff --git a/src/HashTool.App/Infrastructure/AppCommandLine.cs b/src/HashTool.App/Infrastructure/AppCommandLine.cs index b3c30d1..ac16394 100644 --- a/src/HashTool.App/Infrastructure/AppCommandLine.cs +++ b/src/HashTool.App/Infrastructure/AppCommandLine.cs @@ -57,7 +57,7 @@ public sealed record AppCommandLine( if (Next() is { } list && File.Exists(list)) { paths.AddRange(File.ReadAllLines(list).Where(l => !string.IsNullOrWhiteSpace(l))); - TryDelete(list); + if (IsTemporaryFileList(list)) TryDelete(list); } break; @@ -79,10 +79,26 @@ public sealed record AppCommandLine( } } - var resolved = paths.Select(p => Path.GetFullPath(Path.Combine(workingDirectory, p))).Distinct().ToList(); + var resolved = paths.Select(p => Path.GetFullPath(Path.Combine(workingDirectory, p))) + .Distinct(OperatingSystem.IsLinux() ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase).ToList(); return new AppCommandLine(verb, resolved, smoke, smokeOutput, expected, waitPid); } + /// + /// True only for the list writes (%TEMP%\hashtool-<guid>.txt), so a + /// crafted command line cannot make the app delete any other file. + /// + internal static bool IsTemporaryFileList(string path) + { + var full = Path.GetFullPath(path); + var name = Path.GetFileNameWithoutExtension(full); + return string.Equals(Path.GetDirectoryName(full), Path.GetFullPath(Path.GetTempPath()).TrimEnd(Path.DirectorySeparatorChar), + OperatingSystem.IsLinux() ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) && + Path.GetExtension(full) == ".txt" && + name.StartsWith("hashtool-", StringComparison.Ordinal) && + Guid.TryParseExact(name["hashtool-".Length..], "N", out _); + } + private static void TryDelete(string path) { try diff --git a/src/HashTool.App/Infrastructure/Logging/LogSink.cs b/src/HashTool.App/Infrastructure/Logging/LogSink.cs index 00218b2..481b807 100644 --- a/src/HashTool.App/Infrastructure/Logging/LogSink.cs +++ b/src/HashTool.App/Infrastructure/Logging/LogSink.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Threading; using Microsoft.Extensions.Logging; namespace HashTool.App.Infrastructure.Logging; @@ -22,6 +23,11 @@ public sealed record LogEntry(DateTimeOffset Timestamp, LogLevel Level, string C $"{Timestamp.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)} [{LevelTag}] {Category}: {Message}"; } +public sealed class LogEntryEventArgs(LogEntry entry) : EventArgs +{ + public LogEntry Entry { get; } = entry; +} + /// Keeps the most recent log entries in memory for the Developer console. public sealed class LogSink : ILoggerProvider { @@ -29,12 +35,12 @@ public sealed class LogSink : ILoggerProvider private readonly Queue _entries = new(Capacity); private readonly PathSanitizer _sanitizer; - private readonly object _gate = new(); + private readonly Lock _gate = new(); public LogSink(PathSanitizer sanitizer) => _sanitizer = sanitizer; /// Raised on the logging thread for every entry. - public event EventHandler? EntryAdded; + public event EventHandler? EntryAdded; /// When false, entries are not recorded (the console's pause button). public bool IsRecording { get; set; } = true; @@ -66,7 +72,7 @@ public sealed class LogSink : ILoggerProvider _entries.Enqueue(entry); } - EntryAdded?.Invoke(this, entry); + EntryAdded?.Invoke(this, new LogEntryEventArgs(entry)); } private sealed class SinkLogger(LogSink sink, string category) : ILogger diff --git a/src/HashTool.App/Infrastructure/SmokeTest.cs b/src/HashTool.App/Infrastructure/SmokeTest.cs index 5031226..de60e8e 100644 --- a/src/HashTool.App/Infrastructure/SmokeTest.cs +++ b/src/HashTool.App/Infrastructure/SmokeTest.cs @@ -37,7 +37,7 @@ public static class SmokeTest AppBuilder.Configure().UseHeadless(new AvaloniaHeadlessPlatformOptions()).WithInterFont().SetupWithoutStarting(); using var done = new CancellationTokenSource(); var checks = RunChecksAsync(commandLine, report); - checks.ContinueWith(_ => done.Cancel(), TaskScheduler.Default); + _ = checks.ContinueWith(_ => done.Cancel(), TaskScheduler.Default); Dispatcher.UIThread.MainLoop(done.Token); checks.GetAwaiter().GetResult(); } diff --git a/src/HashTool.App/Services/LocalizationService.cs b/src/HashTool.App/Services/LocalizationService.cs index 4e562eb..9dd423a 100644 --- a/src/HashTool.App/Services/LocalizationService.cs +++ b/src/HashTool.App/Services/LocalizationService.cs @@ -199,6 +199,11 @@ public sealed partial class LocalizationService : ObservableObject codes.Contains("es-419", StringComparer.OrdinalIgnoreCase)) return "es-419"; + // Commonwealth English uses British spelling. + if (language == "en" && name.Split('-')[^1].ToUpperInvariant() is "AU" or "NZ" or "IE" or "ZA" or "MT" or "CY" && + codes.Contains("en-GB", StringComparer.OrdinalIgnoreCase)) + return "en-GB"; + // 3. Same language, preferred variant first, then any variant whose language subtag matches exactly. if (PreferredVariants.TryGetValue(language, out var preferred) && codes.Contains(preferred, StringComparer.OrdinalIgnoreCase)) return preferred; diff --git a/src/HashTool.App/Services/Theme/ThemePalettes.cs b/src/HashTool.App/Services/Theme/ThemePalettes.cs index d280bc9..7d0ca90 100644 --- a/src/HashTool.App/Services/Theme/ThemePalettes.cs +++ b/src/HashTool.App/Services/Theme/ThemePalettes.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using Avalonia.Media; using HashTool.Core.Configuration; @@ -57,7 +58,7 @@ public static class ThemePalettes string? success = null, string? error = null, string? warning = null, string? info = null, string? muted = null, string? secondary = null) { - var p = new Dictionary + var p = new Dictionary(StringComparer.Ordinal) { ["AppBackgroundBrush"] = Brush.Parse(background), ["PaneBackgroundBrush"] = Brush.Parse(pane), diff --git a/src/HashTool.App/Services/UiServices.cs b/src/HashTool.App/Services/UiServices.cs index 54ff890..e4237bb 100644 --- a/src/HashTool.App/Services/UiServices.cs +++ b/src/HashTool.App/Services/UiServices.cs @@ -154,8 +154,8 @@ public sealed class LauncherService(MainWindowAccessor main, ILogger (ExportFormat)t.Tag! == Settings.DefaultExportFormat) ?? types[0]; types.Remove(preferred); diff --git a/src/HashTool.App/ViewModels/DeveloperViewModel.cs b/src/HashTool.App/ViewModels/DeveloperViewModel.cs index d959342..8e8fd86 100644 --- a/src/HashTool.App/ViewModels/DeveloperViewModel.cs +++ b/src/HashTool.App/ViewModels/DeveloperViewModel.cs @@ -41,7 +41,7 @@ public sealed partial class DeveloperViewModel : ObservableObject localization.LanguageChanged += (_, _) => Localization = new LocalizationProxy(localization); Entries.AddRange(sink.Snapshot()); - sink.EntryAdded += (_, entry) => _incoming.Enqueue(entry); + sink.EntryAdded += (_, e) => _incoming.Enqueue(e.Entry); _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Flush()); _timer.Start(); } diff --git a/src/HashTool.App/ViewModels/FileListViewModelBase.cs b/src/HashTool.App/ViewModels/FileListViewModelBase.cs index 74cb26f..d57035b 100644 --- a/src/HashTool.App/ViewModels/FileListViewModelBase.cs +++ b/src/HashTool.App/ViewModels/FileListViewModelBase.cs @@ -521,7 +521,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob { 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 (Elevation.RestartElevated(ElevationVerb, _all.Select(i => SourcePathForRestart(i)).Distinct().ToList())) + 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/UpdateViewModel.cs b/src/HashTool.App/ViewModels/UpdateViewModel.cs index f99318b..4bf3714 100644 --- a/src/HashTool.App/ViewModels/UpdateViewModel.cs +++ b/src/HashTool.App/ViewModels/UpdateViewModel.cs @@ -218,13 +218,40 @@ public sealed partial class UpdateViewModel : ObservableObject internal static string? ToPlainText(string? markdown) { if (string.IsNullOrWhiteSpace(markdown)) return null; - var text = markdown.Replace("\r\n", "\n"); - text = Regex.Replace(text, @"^#{1,6}\s*", "", RegexOptions.Multiline); - text = Regex.Replace(text, @"^\s*[-*+]\s+", "• ", RegexOptions.Multiline); - text = Regex.Replace(text, @"\*\*(.+?)\*\*|__(.+?)__", "$1$2"); - text = Regex.Replace(text, @"`([^`]+)`", "$1"); - text = Regex.Replace(text, @"\[([^\]]+)\]\([^)]+\)", "$1"); - text = Regex.Replace(text, @"\n{3,}", "\n\n"); + var text = markdown.Replace("\r\n", "\n", StringComparison.Ordinal); + try + { + text = Heading().Replace(text, ""); + text = Bullet().Replace(text, "• "); + text = Bold().Replace(text, "${a}${b}"); + text = Code().Replace(text, "${code}"); + text = Link().Replace(text, "${text}"); + text = BlankLines().Replace(text, "\n\n"); + } + catch (RegexMatchTimeoutException) + { + // Notes come from the network; show them unformatted rather than hang on a pathological input. + } + return text.Trim(); } + + // [ \t] rather than \s: \s also matches line breaks, which swallowed the blank line before a list. + [GeneratedRegex(@"^#{1,6}[ \t]*", RegexOptions.Multiline, 1000)] + private static partial Regex Heading(); + + [GeneratedRegex(@"^[ \t]*[-*+][ \t]+", RegexOptions.Multiline, 1000)] + private static partial Regex Bullet(); + + [GeneratedRegex(@"\*\*(?.+?)\*\*|__(?.+?)__", RegexOptions.ExplicitCapture, 1000)] + private static partial Regex Bold(); + + [GeneratedRegex(@"`(?[^`]+)`", RegexOptions.ExplicitCapture, 1000)] + private static partial Regex Code(); + + [GeneratedRegex(@"\[(?[^\]]+)\]\([^)]+\)", RegexOptions.ExplicitCapture, 1000)] + private static partial Regex Link(); + + [GeneratedRegex(@"\n{3,}", RegexOptions.None, 1000)] + private static partial Regex BlankLines(); } diff --git a/src/HashTool.App/Views/CheckHashView.axaml b/src/HashTool.App/Views/CheckHashView.axaml index 2d43614..b3b90c0 100644 --- a/src/HashTool.App/Views/CheckHashView.axaml +++ b/src/HashTool.App/Views/CheckHashView.axaml @@ -174,13 +174,16 @@ + +