refactor: fix analyzer findings and add header comments

Fixes every finding the new quality gate reports, without changing behavior:

- One type per file (MA0048): AppBrand, Attribution, NullActivityLog,
  LogSnapshot, ISanitizable, AppTheme, UpdateCheckResult, UpdateText,
  IUpdateBackend, ContentDialogPrompter, WindowExtensions, MessageBoxPrompter,
  and the samples' SampleSettings/SampleSettingsContext get their own files
  (the samples now link samples/Shared/*.cs).
- Regex match timeouts on the two generated regexes (MA0009).
- AppInfo.Id reports nameof(value) as the parameter (MA0015); test updated.
- Splash dismissal is a named DismissAfterAsync started through the
  dispatcher (MA0147, MA0134), and the WinUI splash constructor is split into
  builders (MA0051). The WPF countdown must go through the dispatcher: the
  sample builds its window before Application.Run, when no synchronization
  context exists.
- The WinUI sample's startup update check is a named method (MA0147).
- CA1859 in BrandTool and the version tests; private static readonly fields
  renamed to s_camelCase (IDE1006).
- A header comment on every type and method (K22-CODE-09/CS-04): hand-written
  for library, sample, and tool code; test methods summarize their
  Subject_Behavior names.

Verified: zero-warning x64 build, 115 unit tests with 100% line coverage of
KofTwentyTwo.AppKit and KofTwentyTwo.AppKit.Updates, 12 UI tests, and
dotnet format --verify-no-changes --severity warn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: James Maes <james@kof22.com>
This commit is contained in:
james.maesandClaude Opus 5.5 committed 2026-10-09 10:23:40 -05:00
1 parent 44fe822201
commit 20c95cffaa
53 files changed
+763 -434

No files matched your search

+3
View File
@@ -10,6 +10,7 @@ using Microsoft.UI.Xaml;
namespace AppKit.Sample.WinUI;
/// <summary>The WinUI sample application: installs AppKit&apos;s crash net and the saved theme, then opens the main window.</summary>
public partial class App : Application
{
private Window? _window;
@@ -19,6 +20,7 @@ public partial class App : Application
/// <summary>Installs the crash net and applies the saved theme; WinUI allows setting the application theme only here, before any window exists.</summary>
public App()
{
InitializeComponent();
@@ -29,6 +31,7 @@ public partial class App : Application
/// <summary>Logs the start and opens the main window.</summary>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
Log.Info($"{SampleApp.Info.DisplayName} started.");
@@ -20,7 +20,7 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="..\Shared\SampleApp.cs" Link="SampleApp.cs" />
<Compile Include="..\Shared\*.cs" Link="Shared\%(Filename)%(Extension)" />
<Content Include="..\Shared\Brand\app-icon.svg" Link="Assets\Brand\app-icon.svg" CopyToOutputDirectory="PreserveNewest" />
<Content Include="..\Shared\Brand\app.ico" Link="Assets\Brand\app.ico" CopyToOutputDirectory="PreserveNewest" />
<Manifest Include="$(ApplicationManifest)" />
+26 -5
View File
@@ -11,6 +11,7 @@ using Microsoft.UI.Xaml;
namespace AppKit.Sample.WinUI;
/// <summary>The sample&apos;s main window: each control exercises one AppKit service.</summary>
public sealed partial class MainWindow : Window
{
private readonly SampleSettings _settings = SampleApp.SettingsStore.Load();
@@ -18,6 +19,7 @@ public sealed partial class MainWindow : Window
/// <summary>Sizes and brands the window, wires the update coordinator, restores the saved settings, shows the splash, and schedules the quiet startup update check.</summary>
public MainWindow()
{
InitializeComponent();
@@ -41,20 +43,31 @@ public sealed partial class MainWindow : Window
if(_settings.CheckForUpdatesOnStartup)
{
DispatcherQueue.TryEnqueue(async () =>
{
await Task.Delay(_settings.ShowSplashScreen ? _settings.SplashMilliseconds + 500 : 1000);
await _updates.CheckQuietlyAsync();
});
// The constructor runs on the UI thread, so the check resumes there to show dialogs.
_ = CheckForUpdatesAfterStartupAsync();
}
}
/// <summary>
/// Waits for the splash to clear (dialogs need the window's XamlRoot), then runs the
/// quiet startup update check, which only speaks up when an update exists.
/// </summary>
private async Task CheckForUpdatesAfterStartupAsync()
{
await Task.Delay(_settings.ShowSplashScreen ? _settings.SplashMilliseconds + 500 : 1000);
await _updates.CheckQuietlyAsync();
}
/// <summary>File, Exit.</summary>
private void Exit_Click(object sender, RoutedEventArgs e) => Close();
/// <summary>View, theme: applies the chosen theme to the window and saves it.</summary>
private void Theme_Click(object sender, RoutedEventArgs e)
{
_settings.Theme = (string)((FrameworkElement)sender).Tag;
@@ -64,6 +77,7 @@ public sealed partial class MainWindow : Window
/// <summary>View, Show splash at startup: saves the preference.</summary>
private void Splash_Click(object sender, RoutedEventArgs e)
{
_settings.ShowSplashScreen = SplashToggle.IsChecked;
@@ -72,18 +86,22 @@ public sealed partial class MainWindow : Window
/// <summary>Help, Check for updates: runs the interactive update flow.</summary>
private async void CheckForUpdates_Click(object sender, RoutedEventArgs e) => await _updates.CheckInteractivelyAsync();
/// <summary>Help, Activity log: opens the live log window, or brings the open one forward.</summary>
private void ActivityLog_Click(object sender, RoutedEventArgs e) => LogWindow.ShowSingle(App.Log, SampleApp.Info);
/// <summary>Help, About: shows the About dialog.</summary>
private async void About_Click(object sender, RoutedEventArgs e) => await AboutDialog.ShowAsync(SampleApp.Info, Content.XamlRoot);
/// <summary>Writes an INFO entry, to show logging.</summary>
private void LogInfo_Click(object sender, RoutedEventArgs e)
{
App.Log.Info("The user pressed 'Write a log entry'.");
@@ -92,6 +110,7 @@ public sealed partial class MainWindow : Window
/// <summary>Logs a handled exception with its stack trace, to show error logging.</summary>
private void LogError_Click(object sender, RoutedEventArgs e)
{
try
@@ -107,6 +126,7 @@ public sealed partial class MainWindow : Window
/// <summary>Throws on purpose, to show that the crash net logs the exception and the app keeps running.</summary>
private void Throw_Click(object sender, RoutedEventArgs e)
{
StatusText.Text = "Threw; the crash net logged it and the app kept running.";
@@ -115,6 +135,7 @@ public sealed partial class MainWindow : Window
/// <summary>Saves the settings and reports a failed save in the status line.</summary>
private void Save()
{
if(!SampleApp.SettingsStore.Save(_settings))
+1
View File
@@ -15,6 +15,7 @@ namespace AppKit.Sample.WinUI;
/// </summary>
public static class Program
{
/// <summary>Runs Velopack&apos;s install and update hooks first, then starts the WinUI application (the XAML-generated Main is disabled for this).</summary>
[STAThread]
private static void Main()
{
@@ -15,7 +15,7 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="..\Shared\SampleApp.cs" Link="SampleApp.cs" />
<Compile Include="..\Shared\*.cs" Link="Shared\%(Filename)%(Extension)" />
<Content Include="..\Shared\Brand\app.ico" Link="Assets\Brand\app.ico" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
@@ -11,6 +11,7 @@ using KofTwentyTwo.AppKit.Wpf;
namespace AppKit.Sample.Wpf;
/// <summary>The sample&apos;s main window: each control exercises one AppKit service.</summary>
public partial class MainWindow : Window
{
private readonly SampleSettings _settings = SampleApp.SettingsStore.Load();
@@ -18,6 +19,7 @@ public partial class MainWindow : Window
/// <summary>Brands the window, wires the update coordinator, restores the saved settings, shows the splash, and schedules the quiet startup update check.</summary>
public MainWindow()
{
InitializeComponent();
@@ -49,10 +51,12 @@ public partial class MainWindow : Window
/// <summary>File, Exit.</summary>
private void Exit_Click(object sender, RoutedEventArgs e) => Close();
/// <summary>View, theme: applies the chosen Fluent theme to the application and saves it.</summary>
private void Theme_Click(object sender, RoutedEventArgs e)
{
_settings.Theme = (string)((FrameworkElement)sender).Tag;
@@ -63,6 +67,7 @@ public partial class MainWindow : Window
/// <summary>View, Show splash at startup: saves the preference.</summary>
private void Splash_Click(object sender, RoutedEventArgs e)
{
_settings.ShowSplashScreen = SplashToggle.IsChecked;
@@ -71,18 +76,22 @@ public partial class MainWindow : Window
/// <summary>Help, Check for updates: runs the interactive update flow.</summary>
private async void CheckForUpdates_Click(object sender, RoutedEventArgs e) => await _updates.CheckInteractivelyAsync();
/// <summary>Help, Activity log: opens the live log window, or brings the open one forward.</summary>
private void ActivityLog_Click(object sender, RoutedEventArgs e) => LogWindow.ShowSingle(Program.Log, SampleApp.Info);
/// <summary>Help, About: shows the About window.</summary>
private void About_Click(object sender, RoutedEventArgs e) => AboutWindow.Show(SampleApp.Info, this);
/// <summary>Writes an INFO entry, to show logging.</summary>
private void LogInfo_Click(object sender, RoutedEventArgs e)
{
Program.Log.Info("The user pressed 'Write a log entry'.");
@@ -91,6 +100,7 @@ public partial class MainWindow : Window
/// <summary>Logs a handled exception with its stack trace, to show error logging.</summary>
private void LogError_Click(object sender, RoutedEventArgs e)
{
try
@@ -106,6 +116,7 @@ public partial class MainWindow : Window
/// <summary>Throws on purpose, to show that the crash net logs the exception and the app keeps running.</summary>
private void Throw_Click(object sender, RoutedEventArgs e)
{
StatusText.Text = "Threw; the crash net logged it and the app kept running.";
@@ -114,6 +125,7 @@ public partial class MainWindow : Window
/// <summary>Checks the View menu item that matches the saved theme and clears the others.</summary>
private void CheckTheme()
{
foreach(MenuItem item in new[] { ThemeSystem, ThemeLight, ThemeDark })
@@ -124,6 +136,7 @@ public partial class MainWindow : Window
/// <summary>Saves the settings and reports a failed save in the status line.</summary>
private void Save()
{
if(!SampleApp.SettingsStore.Save(_settings))
+1
View File
@@ -19,6 +19,7 @@ public static class Program
/// <summary>Runs Velopack&apos;s install and update hooks first, then creates the WPF application with AppKit&apos;s crash net and theme and shows the main window.</summary>
[STAThread]
private static void Main()
{
+5 -30
View File
@@ -3,7 +3,6 @@
* SPDX-License-Identifier: MIT
*/
using System.Text.Json.Serialization;
using KofTwentyTwo.AppKit;
using KofTwentyTwo.AppKit.Settings;
@@ -26,11 +25,11 @@ internal static class SampleApp
Copyright = "Copyright (c) 2026 James Maes",
Brand = new AppBrand { IconSvgPath = "Assets/Brand/app-icon.svg", IconIcoPath = "Assets/Brand/app.ico" },
Attributions =
[
new("KofTwentyTwo.AppKit", "MIT License"),
new("Velopack", "MIT License"),
new(".NET Runtime", "MIT License"),
],
[
new("KofTwentyTwo.AppKit", "MIT License"),
new("Velopack", "MIT License"),
new(".NET Runtime", "MIT License"),
],
};
@@ -39,27 +38,3 @@ internal static class SampleApp
public static SettingsStore<SampleSettings> SettingsStore { get; } = new(Paths.SettingsFile, SampleSettingsContext.Default.SampleSettings);
}
/// <summary>The sample's preferences: the shared shell settings plus one of its own.</summary>
internal sealed class SampleSettings : ShellSettings
{
public string Greeting { get; set; } = "Hello from AppKit";
public override void Sanitize()
{
base.Sanitize();
Greeting ??= "Hello from AppKit";
}
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(SampleSettings))]
internal sealed partial class SampleSettingsContext : JsonSerializerContext
{
}
+24
View File
@@ -0,0 +1,24 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
using KofTwentyTwo.AppKit.Settings;
namespace AppKit.Sample;
/// <summary>The sample's preferences: the shared shell settings plus one of its own.</summary>
internal sealed class SampleSettings : ShellSettings
{
public string Greeting { get; set; } = "Hello from AppKit";
/// <summary>Repairs the shared shell settings, then restores a missing greeting.</summary>
public override void Sanitize()
{
base.Sanitize();
Greeting ??= "Hello from AppKit";
}
}
+16
View File
@@ -0,0 +1,16 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
using System.Text.Json.Serialization;
namespace AppKit.Sample;
/// <summary>Source-generated JSON serializer for the sample&apos;s settings, so trimmed builds need no reflection.</summary>
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(SampleSettings))]
internal sealed partial class SampleSettingsContext : JsonSerializerContext
{
}
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit.Updates;
/// <summary>
/// The narrow slice of Velopack the update service uses, so the guarding and state
/// logic is testable without an installed app or the network.
/// </summary>
internal interface IUpdateBackend
{
bool IsInstalled { get; }
string? CurrentVersion { get; }
/// <summary>The newer version found (and remembered for download), or null.</summary>
Task<string?> CheckAsync();
/// <summary>Downloads the remembered update.</summary>
Task DownloadAsync(Action<int>? progress, CancellationToken cancellationToken);
/// <summary>Applies the downloaded update and restarts; exits the process on success.</summary>
void ApplyAndRestart();
}
@@ -5,32 +5,6 @@
namespace KofTwentyTwo.AppKit.Updates;
/// <summary>
/// Result of an update check. <see cref="AvailableVersion"/> is the newer version
/// found, or null when already up to date; <see cref="Error"/> is non-null when the
/// check itself failed.
/// </summary>
public sealed record UpdateCheckResult(string? AvailableVersion, string? Error)
{
/// <summary>No newer version exists.</summary>
public static UpdateCheckResult UpToDate { get; } = new(null, null);
/// <summary>True when a newer version was found.</summary>
public bool IsUpdateAvailable => Error is null && AvailableVersion is not null;
/// <summary>A newer version was found.</summary>
public static UpdateCheckResult Available(string version) => new(version, null);
/// <summary>The check failed.</summary>
public static UpdateCheckResult Failed(string error) => new(null, error);
}
/// <summary>
/// Checks for and installs app updates. Every member is guarded: failures come back as
/// values, never exceptions, because nothing as optional as an update may crash the app.
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit.Updates;
/// <summary>
/// Result of an update check. <see cref="AvailableVersion"/> is the newer version
/// found, or null when already up to date; <see cref="Error"/> is non-null when the
/// check itself failed.
/// </summary>
public sealed record UpdateCheckResult(string? AvailableVersion, string? Error)
{
/// <summary>No newer version exists.</summary>
public static UpdateCheckResult UpToDate { get; } = new(null, null);
/// <summary>True when a newer version was found.</summary>
public bool IsUpdateAvailable => Error is null && AvailableVersion is not null;
/// <summary>A newer version was found.</summary>
public static UpdateCheckResult Available(string version) => new(version, null);
/// <summary>The check failed.</summary>
public static UpdateCheckResult Failed(string error) => new(null, error);
}
@@ -9,47 +9,6 @@ using KofTwentyTwo.AppKit.Logging;
namespace KofTwentyTwo.AppKit.Updates;
/// <summary>User-facing text of the update flow, shared by every UI package.</summary>
public static class UpdateText
{
/// <summary>Title of the check dialogs.</summary>
public const string CheckTitle = "Check for updates";
/// <summary>Title of the confirmation dialog.</summary>
public const string AvailableTitle = "Update available";
/// <summary>Title shown when installing failed.</summary>
public const string FailedTitle = "Update failed";
/// <summary>Shown in builds that cannot self-update.</summary>
public const string NotSupported = "Updates are only available in installed builds.";
/// <summary>Confirm button.</summary>
public const string Confirm = "Update and restart";
/// <summary>Decline button.</summary>
public const string Decline = "Not now";
/// <summary>"You are up to date (v1.2.3)."</summary>
public static string UpToDate(string? currentVersion)
=> currentVersion is null ? "You are up to date." : $"You are up to date (v{currentVersion}).";
/// <summary>Explains a failed check.</summary>
public static string CheckFailed(string error) => $"Could not check for updates.\n{error}";
/// <summary>Offers the update.</summary>
public static string Available(string appName, string version)
=> $"{appName} v{version} is available. The app will restart to finish installing the update.";
}
/// <summary>
/// The "check for updates" flows, written once against <see cref="IUpdateService"/> and
/// <see cref="IUserPrompter"/> so WinUI and WPF apps behave identically and the logic is
@@ -140,6 +99,7 @@ public sealed class UpdateCoordinator
/// <summary>Offers the update and, when accepted, downloads it, applies it, and restarts. A failed install is logged and shown, because reaching the end means the restart did not happen.</summary>
private async Task OfferAsync(string version, CancellationToken cancellationToken)
{
bool accepted = await _prompter.ConfirmAsync(
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit.Updates;
/// <summary>User-facing text of the update flow, shared by every UI package.</summary>
public static class UpdateText
{
/// <summary>Title of the check dialogs.</summary>
public const string CheckTitle = "Check for updates";
/// <summary>Title of the confirmation dialog.</summary>
public const string AvailableTitle = "Update available";
/// <summary>Title shown when installing failed.</summary>
public const string FailedTitle = "Update failed";
/// <summary>Shown in builds that cannot self-update.</summary>
public const string NotSupported = "Updates are only available in installed builds.";
/// <summary>Confirm button.</summary>
public const string Confirm = "Update and restart";
/// <summary>Decline button.</summary>
public const string Decline = "Not now";
/// <summary>"You are up to date (v1.2.3)."</summary>
public static string UpToDate(string? currentVersion)
=> currentVersion is null ? "You are up to date." : $"You are up to date (v{currentVersion}).";
/// <summary>Explains a failed check.</summary>
public static string CheckFailed(string error) => $"Could not check for updates.\n{error}";
/// <summary>Offers the update.</summary>
public static string Available(string appName, string version)
=> $"{appName} v{version} is available. The app will restart to finish installing the update.";
}
@@ -24,6 +24,7 @@ internal sealed class VelopackGithubBackend : IUpdateBackend
/// <summary>Creates a Velopack UpdateManager over the repository&apos;s GitHub Releases, looking at prereleases only when asked.</summary>
public VelopackGithubBackend(Uri repositoryUrl, bool includePrereleases)
{
_manager = new UpdateManager(new GithubSource(repositoryUrl.ToString(), accessToken: null, prerelease: includePrereleases));
@@ -37,6 +38,7 @@ internal sealed class VelopackGithubBackend : IUpdateBackend
/// <summary>Asks Velopack for a newer release and remembers it for the download.</summary>
public async Task<string?> CheckAsync()
{
_pending = await _manager.CheckForUpdatesAsync().ConfigureAwait(false);
@@ -45,6 +47,7 @@ internal sealed class VelopackGithubBackend : IUpdateBackend
/// <summary>Downloads the remembered update with progress; fails when no update was found.</summary>
public Task DownloadAsync(Action<int>? progress, CancellationToken cancellationToken)
=> _pending is null
? Task.FromException(new InvalidOperationException("No update was found to download."))
@@ -52,6 +55,7 @@ internal sealed class VelopackGithubBackend : IUpdateBackend
/// <summary>Applies the downloaded update and restarts the app; Velopack exits the process on success.</summary>
public void ApplyAndRestart()
{
if(_pending is null)
@@ -8,34 +8,6 @@ using System.Reflection;
namespace KofTwentyTwo.AppKit.Updates;
/// <summary>
/// The narrow slice of Velopack the update service uses, so the guarding and state
/// logic is testable without an installed app or the network.
/// </summary>
internal interface IUpdateBackend
{
bool IsInstalled { get; }
string? CurrentVersion { get; }
/// <summary>The newer version found (and remembered for download), or null.</summary>
Task<string?> CheckAsync();
/// <summary>Downloads the remembered update.</summary>
Task DownloadAsync(Action<int>? progress, CancellationToken cancellationToken);
/// <summary>Applies the downloaded update and restarts; exits the process on success.</summary>
void ApplyAndRestart();
}
/// <summary>
/// Self-update via Velopack with releases hosted on the app's public GitHub repository.
/// A prerelease build (a '-' in its version) follows the dev channel, whose packages
@@ -102,6 +102,7 @@ public sealed partial class AboutDialog : ContentDialog
/// <summary>A titled section of the dialog body: a bold heading the caller adds content lines under.</summary>
private static StackPanel Section(string heading)
{
var section = new StackPanel { Spacing = 4 };
@@ -111,6 +112,7 @@ public sealed partial class AboutDialog : ContentDialog
/// <summary>Looks up a theme style by key; null when the app&apos;s resources lack it, so the text falls back to default styling instead of failing.</summary>
private static Style? ThemeStyle(string key)
=> Application.Current.Resources.TryGetValue(key, out object? style) ? style as Style : null;
}
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
using KofTwentyTwo.AppKit.Interaction;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace KofTwentyTwo.AppKit.WinUI;
/// <summary>
/// <see cref="IUserPrompter"/> over guarded ContentDialogs, for shared flows such as
/// <see cref="Updates.UpdateCoordinator"/>.
/// </summary>
/// <param name="xamlRoot">Supplies the XamlRoot to host dialogs, usually <c>() =&gt; window.Content.XamlRoot</c>.</param>
public sealed class ContentDialogPrompter(Func<XamlRoot> xamlRoot) : IUserPrompter
{
/// <inheritdoc/>
public async Task ShowMessageAsync(string title, string message)
{
await DialogGuard.ShowAsync(new ContentDialog
{
Title = title,
Content = new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
CloseButtonText = "OK",
DefaultButton = ContentDialogButton.Close,
XamlRoot = xamlRoot(),
});
}
/// <inheritdoc/>
public async Task<bool> ConfirmAsync(string title, string message, string confirmText, string cancelText)
{
ContentDialogResult? result = await DialogGuard.ShowAsync(new ContentDialog
{
Title = title,
Content = new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
PrimaryButtonText = confirmText,
CloseButtonText = cancelText,
DefaultButton = ContentDialogButton.Primary,
XamlRoot = xamlRoot(),
});
return result == ContentDialogResult.Primary;
}
}
@@ -3,8 +3,6 @@
* SPDX-License-Identifier: MIT
*/
using KofTwentyTwo.AppKit.Interaction;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
@@ -52,43 +50,3 @@ public static class DialogGuard
}
}
}
/// <summary>
/// <see cref="IUserPrompter"/> over guarded ContentDialogs, for shared flows such as
/// <see cref="Updates.UpdateCoordinator"/>.
/// </summary>
/// <param name="xamlRoot">Supplies the XamlRoot to host dialogs, usually <c>() =&gt; window.Content.XamlRoot</c>.</param>
public sealed class ContentDialogPrompter(Func<XamlRoot> xamlRoot) : IUserPrompter
{
/// <inheritdoc/>
public async Task ShowMessageAsync(string title, string message)
{
await DialogGuard.ShowAsync(new ContentDialog
{
Title = title,
Content = new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
CloseButtonText = "OK",
DefaultButton = ContentDialogButton.Close,
XamlRoot = xamlRoot(),
});
}
/// <inheritdoc/>
public async Task<bool> ConfirmAsync(string title, string message, string confirmText, string cancelText)
{
ContentDialogResult? result = await DialogGuard.ShowAsync(new ContentDialog
{
Title = title,
Content = new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
PrimaryButtonText = confirmText,
CloseButtonText = cancelText,
DefaultButton = ContentDialogButton.Primary,
XamlRoot = xamlRoot(),
});
return result == ContentDialogResult.Primary;
}
}
+4 -2
View File
@@ -20,11 +20,11 @@ namespace KofTwentyTwo.AppKit.WinUI;
/// </summary>
public sealed partial class LogWindow : Window
{
private static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(1);
private static readonly TimeSpan s_refreshInterval = TimeSpan.FromSeconds(1);
private static LogWindow? s_current;
private readonly IActivityLog _log;
private readonly DispatcherTimer _refresh = new() { Interval = RefreshInterval };
private readonly DispatcherTimer _refresh = new() { Interval = s_refreshInterval };
private readonly TextBlock _pathText = new() { VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis, Opacity = 0.7 };
private readonly TextBlock _logText = new() { FontFamily = new FontFamily("Cascadia Mono, Consolas"), FontSize = 12, IsTextSelectionEnabled = true, TextWrapping = TextWrapping.NoWrap };
private readonly ScrollViewer _scroll = new() { HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Padding = new Thickness(12) };
@@ -105,6 +105,7 @@ public sealed partial class LogWindow : Window
/// <summary>Copies the visible log text to the clipboard.</summary>
private void CopyToClipboard()
{
var package = new Windows.ApplicationModel.DataTransfer.DataPackage();
@@ -139,6 +140,7 @@ public sealed partial class LogWindow : Window
/// <summary>Rereads the log tail, applies the errors-only filter, and scrolls to the newest entry.</summary>
private void Reload()
{
_pathText.Text = _log.CurrentLogFilePath; // the day can roll over while the window is open
+78 -33
View File
@@ -40,6 +40,29 @@ public sealed partial class SplashOverlay : UserControl
AutomationProperties.SetName(root, $"{app.DisplayName} is starting");
AutomationProperties.SetAutomationId(root, "AppKitSplash");
root.Children.Add(BuildCenter(app, versionAssembly ?? Assembly.GetEntryAssembly()));
if(BuildCredit(app) is { } credit)
{
root.Children.Add(credit);
}
root.Children.Add(BuildActivityStrip());
var fade = new DoubleAnimation { To = 0, Duration = new Duration(TimeSpan.FromMilliseconds(250)) };
Storyboard.SetTarget(fade, root);
Storyboard.SetTargetProperty(fade, "Opacity");
_fadeOut.Children.Add(fade);
Content = root;
}
/// <summary>
/// The centered brand block: the vector mark, the name, the tagline, and the build
/// identity of <paramref name="assembly"/> when there is one.
/// </summary>
private static StackPanel BuildCenter(AppInfo app, Assembly? assembly)
{
var center = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
center.Children.Add(new Image
{
@@ -58,37 +81,55 @@ public sealed partial class SplashOverlay : UserControl
tagline.Margin = new Thickness(0, 4, 0, 0);
AddCentered(center, tagline);
}
Assembly? assembly = versionAssembly ?? Assembly.GetEntryAssembly();
if(assembly is not null)
{
TextBlock version = Brand.Text(BuildVersion.Describe(assembly), 12, 0.6);
version.Margin = new Thickness(0, 8, 0, 0);
AddCentered(center, version);
}
root.Children.Add(center);
return center;
}
/// <summary>
/// The author credit anchored above the activity strip, or null when the app declares
/// neither an author nor any contact details.
/// </summary>
private static StackPanel? BuildCredit(AppInfo app)
{
string contact = Credits.ContactLine(app);
if(app.Author.Length > 0 || contact.Length > 0)
if(app.Author.Length == 0 && contact.Length == 0)
{
var credit = new StackPanel
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Bottom,
Margin = new Thickness(0, 0, 0, 44),
Spacing = 3,
};
if(app.Author.Length > 0)
{
AddCentered(credit, Brand.Text("Created by " + app.Author, 13, 0.85, strong: true));
}
if(contact.Length > 0)
{
AddCentered(credit, Brand.Text(contact, 12, 0.6));
}
root.Children.Add(credit);
return null;
}
// Thin activity strip: white bar over a 20% white track.
var credit = new StackPanel
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Bottom,
Margin = new Thickness(0, 0, 0, 44),
Spacing = 3,
};
if(app.Author.Length > 0)
{
AddCentered(credit, Brand.Text("Created by " + app.Author, 13, 0.85, strong: true));
}
if(contact.Length > 0)
{
AddCentered(credit, Brand.Text(contact, 12, 0.6));
}
return credit;
}
/// <summary>
/// The thin activity strip at the bottom: a white bar over a 20% white track, with the
/// track height resource overridden so the track matches the 3px bar.
/// </summary>
private static ProgressBar BuildActivityStrip()
{
var progress = new ProgressBar
{
IsIndeterminate = true,
@@ -100,14 +141,7 @@ public sealed partial class SplashOverlay : UserControl
Margin = new Thickness(0, 0, 0, 20),
};
progress.Resources["ProgressBarTrackHeight"] = 3.0;
root.Children.Add(progress);
var fade = new DoubleAnimation { To = 0, Duration = new Duration(TimeSpan.FromMilliseconds(250)) };
Storyboard.SetTarget(fade, root);
Storyboard.SetTargetProperty(fade, "Opacity");
_fadeOut.Children.Add(fade);
Content = root;
return progress;
}
@@ -133,16 +167,26 @@ public sealed partial class SplashOverlay : UserControl
Grid.SetColumnSpan(overlay, Math.Max(grid.ColumnDefinitions.Count, 1));
}
host.Children.Add(overlay);
overlay.DispatcherQueue.TryEnqueue(async () =>
{
await Task.Delay(settings.SplashMilliseconds);
await overlay.DismissAsync();
});
///////////////////////////////////////////////////////////////////////////////
// start the countdown through the dispatcher queue, not directly: the queue //
// runs it on the UI thread with its synchronization context in place, so //
// the fade after the delay also runs on the UI thread //
///////////////////////////////////////////////////////////////////////////////
overlay.DispatcherQueue.TryEnqueue(() => _ = overlay.DismissAfterAsync(settings.SplashMilliseconds));
return overlay;
}
/// <summary>Waits <paramref name="milliseconds"/>, then fades the overlay out.</summary>
private async Task DismissAfterAsync(int milliseconds)
{
await Task.Delay(milliseconds);
await DismissAsync();
}
/// <summary>
/// Fades the overlay out and removes it from its parent panel. Safe to call more
/// than once; only the first call does anything.
@@ -168,6 +212,7 @@ public sealed partial class SplashOverlay : UserControl
/// <summary>Centers an element horizontally and adds it to the panel.</summary>
private static void AddCentered(Panel panel, FrameworkElement element)
{
element.HorizontalAlignment = HorizontalAlignment.Center;
@@ -3,10 +3,8 @@
* SPDX-License-Identifier: MIT
*/
using System.Runtime.InteropServices;
using KofTwentyTwo.AppKit.Logging;
using KofTwentyTwo.AppKit.Settings;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
@@ -75,65 +73,3 @@ public static class WinUIShell
};
}
}
/// <summary>DPI-aware sizing and branding for WinUI windows.</summary>
public static partial class WindowExtensions
{
/// <summary>The window's display scale (1.0 at 100%, 1.5 at 150%).</summary>
public static double DpiScale(this Window window)
{
ArgumentNullException.ThrowIfNull(window);
IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
uint dpi = GetDpiForWindow(hwnd);
return dpi == 0 ? 1.0 : dpi / 96.0;
}
/// <summary>
/// Resizes to <paramref name="width"/> x <paramref name="height"/> effective pixels.
/// AppWindow.Resize takes physical pixels, so this scales by the monitor DPI.
/// </summary>
public static void ResizeForDpi(this Window window, int width, int height)
{
double scale = window.DpiScale();
window.AppWindow.Resize(new Windows.Graphics.SizeInt32((int)(width * scale), (int)(height * scale)));
}
/// <summary>Keeps the window from shrinking below a usable size, in effective pixels.</summary>
public static void SetMinimumSize(this Window window, int width, int height)
{
double scale = window.DpiScale();
if(window.AppWindow.Presenter is OverlappedPresenter presenter)
{
presenter.PreferredMinimumWidth = (int)(width * scale);
presenter.PreferredMinimumHeight = (int)(height * scale);
}
}
/// <summary>
/// Sets the brand icon on the title bar (and taskbar / Alt-Tab for unpackaged runs).
/// The .ico must be copied to the output directory. A missing file is ignored.
/// </summary>
public static void SetAppIcon(this Window window, AppInfo app)
{
ArgumentNullException.ThrowIfNull(window);
ArgumentNullException.ThrowIfNull(app);
string path = Path.Combine(AppContext.BaseDirectory, app.Brand.IconIcoPath);
if(File.Exists(path))
{
window.AppWindow.SetIcon(path);
}
}
[LibraryImport("user32.dll")]
private static partial uint GetDpiForWindow(IntPtr hwnd);
}
@@ -0,0 +1,72 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
using System.Runtime.InteropServices;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
namespace KofTwentyTwo.AppKit.WinUI;
/// <summary>DPI-aware sizing and branding for WinUI windows.</summary>
public static partial class WindowExtensions
{
/// <summary>The window's display scale (1.0 at 100%, 1.5 at 150%).</summary>
public static double DpiScale(this Window window)
{
ArgumentNullException.ThrowIfNull(window);
IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
uint dpi = GetDpiForWindow(hwnd);
return dpi == 0 ? 1.0 : dpi / 96.0;
}
/// <summary>
/// Resizes to <paramref name="width"/> x <paramref name="height"/> effective pixels.
/// AppWindow.Resize takes physical pixels, so this scales by the monitor DPI.
/// </summary>
public static void ResizeForDpi(this Window window, int width, int height)
{
double scale = window.DpiScale();
window.AppWindow.Resize(new Windows.Graphics.SizeInt32((int)(width * scale), (int)(height * scale)));
}
/// <summary>Keeps the window from shrinking below a usable size, in effective pixels.</summary>
public static void SetMinimumSize(this Window window, int width, int height)
{
double scale = window.DpiScale();
if(window.AppWindow.Presenter is OverlappedPresenter presenter)
{
presenter.PreferredMinimumWidth = (int)(width * scale);
presenter.PreferredMinimumHeight = (int)(height * scale);
}
}
/// <summary>
/// Sets the brand icon on the title bar (and taskbar / Alt-Tab for unpackaged runs).
/// The .ico must be copied to the output directory. A missing file is ignored.
/// </summary>
public static void SetAppIcon(this Window window, AppInfo app)
{
ArgumentNullException.ThrowIfNull(window);
ArgumentNullException.ThrowIfNull(app);
string path = Path.Combine(AppContext.BaseDirectory, app.Brand.IconIcoPath);
if(File.Exists(path))
{
window.AppWindow.SetIcon(path);
}
}
/// <summary>Win32 GetDpiForWindow: the effective DPI of the monitor the window is on.</summary>
[LibraryImport("user32.dll")]
private static partial uint GetDpiForWindow(IntPtr hwnd);
}
@@ -83,6 +83,7 @@ public sealed class AboutWindow : Window
/// <summary>The brand header: the splash look in miniature, with the name, tagline, and build version.</summary>
private static Border Header(AppInfo app, Assembly? assembly)
{
var title = new StackPanel { Orientation = Orientation.Horizontal };
@@ -116,11 +117,13 @@ public sealed class AboutWindow : Window
/// <summary>A bold section heading.</summary>
private static TextBlock Heading(string text)
=> new() { Text = text, FontWeight = FontWeights.SemiBold, Margin = new Thickness(0, 16, 0, 0) };
/// <summary>A wrapped paragraph with the given space above it.</summary>
private static TextBlock Paragraph(string text, double top = 12)
=> new() { Text = text, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, top, 0, 0) };
}
+2
View File
@@ -103,6 +103,7 @@ public sealed class LogWindow : Window
/// <summary>Timer tick: reloads only when Follow is on and the log file grew or rolled over to a new day.</summary>
private void RefreshIfChanged()
{
if(_follow.IsChecked != true)
@@ -127,6 +128,7 @@ public sealed class LogWindow : Window
/// <summary>Rereads the log tail, applies the errors-only filter, and scrolls to the newest entry.</summary>
private void Reload()
{
_pathText.Text = _log.CurrentLogFilePath;
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
using System.Windows;
using KofTwentyTwo.AppKit.Interaction;
namespace KofTwentyTwo.AppKit.Wpf;
/// <summary>
/// <see cref="IUserPrompter"/> over WPF message boxes, for shared flows such as
/// <see cref="Updates.UpdateCoordinator"/>. Message boxes cannot relabel their buttons,
/// so confirmations show Yes/No with the confirm text folded into the question.
/// </summary>
/// <param name="owner">Supplies the owning window, usually the main window.</param>
public sealed class MessageBoxPrompter(Func<Window?> owner) : IUserPrompter
{
/// <inheritdoc/>
public Task ShowMessageAsync(string title, string message)
{
Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
return Task.CompletedTask;
}
/// <inheritdoc/>
public Task<bool> ConfirmAsync(string title, string message, string confirmText, string cancelText)
{
MessageBoxResult result = Show($"{message}\n\n{confirmText}?", title, MessageBoxButton.YesNo, MessageBoxImage.Question);
return Task.FromResult(result == MessageBoxResult.Yes);
}
/// <summary>Shows a message box owned by the app&apos;s window when there is one, so it stays in front of the app.</summary>
private MessageBoxResult Show(string message, string title, MessageBoxButton buttons, MessageBoxImage image)
=> owner() is Window window
? MessageBox.Show(window, message, title, buttons, image)
: MessageBox.Show(message, title, buttons, image);
}
+15 -5
View File
@@ -111,16 +111,26 @@ public sealed class SplashOverlay : UserControl
Grid.SetColumnSpan(overlay, Math.Max(grid.ColumnDefinitions.Count, 1));
}
host.Children.Add(overlay);
overlay.Dispatcher.InvokeAsync(async () =>
{
await Task.Delay(settings.SplashMilliseconds);
await overlay.DismissAsync();
});
///////////////////////////////////////////////////////////////////////////////
// start the countdown through the dispatcher, not directly: an app may call //
// this before Application.Run, when no synchronization context exists yet, //
// and the fade must run on the UI thread //
///////////////////////////////////////////////////////////////////////////////
_ = overlay.Dispatcher.InvokeAsync(() => overlay.DismissAfterAsync(settings.SplashMilliseconds));
return overlay;
}
/// <summary>Waits <paramref name="milliseconds"/>, then fades the overlay out.</summary>
private async Task DismissAfterAsync(int milliseconds)
{
await Task.Delay(milliseconds);
await DismissAsync();
}
/// <summary>
/// Fades the overlay out and removes it from its parent panel. Safe to call more
/// than once; only the first call does anything.
+1 -35
View File
@@ -6,7 +6,6 @@
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using KofTwentyTwo.AppKit.Interaction;
using KofTwentyTwo.AppKit.Logging;
using KofTwentyTwo.AppKit.Settings;
@@ -71,6 +70,7 @@ public static class WpfShell
/// <summary>Records an exception caught by the crash net; a failure of the logger itself is swallowed so logging can never make an error fatal.</summary>
private static void SafeLog(Func<IActivityLog?> log, string message, Exception exception)
{
try
@@ -83,37 +83,3 @@ public static class WpfShell
}
}
}
/// <summary>
/// <see cref="IUserPrompter"/> over WPF message boxes, for shared flows such as
/// <see cref="Updates.UpdateCoordinator"/>. Message boxes cannot relabel their buttons,
/// so confirmations show Yes/No with the confirm text folded into the question.
/// </summary>
/// <param name="owner">Supplies the owning window, usually the main window.</param>
public sealed class MessageBoxPrompter(Func<Window?> owner) : IUserPrompter
{
/// <inheritdoc/>
public Task ShowMessageAsync(string title, string message)
{
Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
return Task.CompletedTask;
}
/// <inheritdoc/>
public Task<bool> ConfirmAsync(string title, string message, string confirmText, string cancelText)
{
MessageBoxResult result = Show($"{message}\n\n{confirmText}?", title, MessageBoxButton.YesNo, MessageBoxImage.Question);
return Task.FromResult(result == MessageBoxResult.Yes);
}
private MessageBoxResult Show(string message, string title, MessageBoxButton buttons, MessageBoxImage image)
=> owner() is Window window
? MessageBox.Show(window, message, title, buttons, image)
: MessageBox.Show(message, title, buttons, image);
}
+25
View File
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit;
/// <summary>
/// Brand look for the splash and About header: a diagonal two-stop gradient behind
/// white type, plus the app-relative paths of the vector mark and window icon.
/// </summary>
public sealed record AppBrand
{
/// <summary>Top-left gradient color, "#RRGGBB" or "#AARRGGBB".</summary>
public string GradientStart { get; init; } = "#3B4CCA";
/// <summary>Bottom-right gradient color, "#RRGGBB" or "#AARRGGBB".</summary>
public string GradientEnd { get; init; } = "#2A2F8F";
/// <summary>Vector mark, relative to the app directory.</summary>
public string IconSvgPath { get; init; } = "Assets/Brand/app-icon.svg";
/// <summary>Window and taskbar icon, relative to the app directory.</summary>
public string IconIcoPath { get; init; } = "Assets/Brand/app.ico";
}
+3 -30
View File
@@ -34,7 +34,7 @@ public sealed partial record AppInfo
{
throw new ArgumentException(
$"App id '{value}' is invalid: use lowercase letters, digits, and dashes, starting with a letter or digit.",
nameof(Id));
nameof(value));
}
_id = value;
}
@@ -87,34 +87,7 @@ public sealed partial record AppInfo
[GeneratedRegex("^[a-z0-9][a-z0-9-]*$")]
/// <summary>The app id grammar: lowercase letters, digits, and dashes, starting with a letter or digit. Source-generated, with a match timeout as a guard.</summary>
[GeneratedRegex("^[a-z0-9][a-z0-9-]*$", RegexOptions.None, matchTimeoutMilliseconds: 1000)]
private static partial Regex IdPattern();
}
/// <summary>A third-party component credited in the About screen.</summary>
/// <param name="Name">Component name, e.g. "Velopack".</param>
/// <param name="License">License name, e.g. "MIT License".</param>
public sealed record Attribution(string Name, string License);
/// <summary>
/// Brand look for the splash and About header: a diagonal two-stop gradient behind
/// white type, plus the app-relative paths of the vector mark and window icon.
/// </summary>
public sealed record AppBrand
{
/// <summary>Top-left gradient color, "#RRGGBB" or "#AARRGGBB".</summary>
public string GradientStart { get; init; } = "#3B4CCA";
/// <summary>Bottom-right gradient color, "#RRGGBB" or "#AARRGGBB".</summary>
public string GradientEnd { get; init; } = "#2A2F8F";
/// <summary>Vector mark, relative to the app directory.</summary>
public string IconSvgPath { get; init; } = "Assets/Brand/app-icon.svg";
/// <summary>Window and taskbar icon, relative to the app directory.</summary>
public string IconIcoPath { get; init; } = "Assets/Brand/app.ico";
}
+11
View File
@@ -0,0 +1,11 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit;
/// <summary>A third-party component credited in the About screen.</summary>
/// <param name="Name">Component name, e.g. "Velopack".</param>
/// <param name="License">License name, e.g. "MIT License".</param>
public sealed record Attribution(string Name, string License);
+1
View File
@@ -88,6 +88,7 @@ public static class BuildVersion
/// <summary>The informational version the build stamped (tag version plus the SourceLink commit), falling back to the assembly version.</summary>
private static string? InformationalVersion(Assembly assembly)
=> assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion
?? assembly.GetName().Version?.ToString();
@@ -86,11 +86,13 @@ public sealed class FileActivityLog : IActivityLog
/// <summary>The log file for one day.</summary>
private string FilePathFor(DateOnly day)
=> Path.Combine(LogDirectory, $"{_filePrefix}-{day.ToString(DateFormat, CultureInfo.InvariantCulture)}.log");
/// <summary>Appends one entry under the lock, pruning old files on the first write of a day. Never throws: a logging failure must not take down the operation it describes.</summary>
private void Write(string level, string message, Exception? exception)
{
try
@@ -33,39 +33,3 @@ public interface IActivityLog
/// <summary>Full path of the file new entries are currently appended to.</summary>
string CurrentLogFilePath { get; }
}
/// <summary>An <see cref="IActivityLog"/> that discards everything.</summary>
public sealed class NullActivityLog : IActivityLog
{
/// <summary>The shared instance.</summary>
public static NullActivityLog Instance { get; } = new();
/// <inheritdoc/>
public string LogDirectory => "";
/// <inheritdoc/>
public string CurrentLogFilePath => "";
/// <inheritdoc/>
public void Info(string message)
{
}
/// <inheritdoc/>
public void Warning(string message)
{
}
/// <inheritdoc/>
public void Error(string message, Exception? exception = null)
{
}
}
@@ -0,0 +1,11 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit.Logging;
/// <summary>The last lines of a log file and the file length they were read at.</summary>
/// <param name="Lines">The tail, oldest first.</param>
/// <param name="Length">File length in bytes when read; 0 when the file is absent.</param>
public sealed record LogSnapshot(IReadOnlyList<string> Lines, long Length);
+2 -9
View File
@@ -7,14 +7,6 @@ using System.Text.RegularExpressions;
namespace KofTwentyTwo.AppKit.Logging;
/// <summary>The last lines of a log file and the file length they were read at.</summary>
/// <param name="Lines">The tail, oldest first.</param>
/// <param name="Length">File length in bytes when read; 0 when the file is absent.</param>
public sealed record LogSnapshot(IReadOnlyList<string> Lines, long Length);
/// <summary>
/// Reads and filters <see cref="FileActivityLog"/> files for the log viewer windows.
/// Never throws: this is diagnostics UI, and an unreadable file becomes a readable
@@ -100,6 +92,7 @@ public static partial class LogTail
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}")]
/// <summary>Matches the timestamp that starts every log entry, so continuation lines (exception text) can be told apart.</summary>
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", RegexOptions.None, matchTimeoutMilliseconds: 1000)]
private static partial Regex EntryStart();
}
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit.Logging;
/// <summary>An <see cref="IActivityLog"/> that discards everything.</summary>
public sealed class NullActivityLog : IActivityLog
{
/// <summary>The shared instance.</summary>
public static NullActivityLog Instance { get; } = new();
/// <inheritdoc/>
public string LogDirectory => "";
/// <inheritdoc/>
public string CurrentLogFilePath => "";
/// <inheritdoc/>
public void Info(string message)
{
}
/// <inheritdoc/>
public void Warning(string message)
{
}
/// <inheritdoc/>
public void Error(string message, Exception? exception = null)
{
}
}
@@ -176,24 +176,28 @@ public sealed class CredentialManagerVault : ISecretVault
/// <summary>advapi32 CredWriteW: creates or replaces a credential.</summary>
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CredWriteW(ref CredentialW credential, uint flags);
/// <summary>advapi32 CredReadW: reads a credential into a buffer that must be released with CredFree.</summary>
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CredReadW(string targetName, uint type, uint flags, out IntPtr credential);
/// <summary>advapi32 CredDeleteW: deletes a credential.</summary>
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CredDeleteW(string targetName, uint type, uint flags);
/// <summary>advapi32 CredFree: releases a buffer returned by CredReadW.</summary>
[DllImport("advapi32.dll", ExactSpelling = true)]
private static extern void CredFree(IntPtr buffer);
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit.Settings;
/// <summary>The app's color theme.</summary>
public enum AppTheme
{
/// <summary>Follow the Windows setting.</summary>
System,
/// <summary>Always light.</summary>
Light,
/// <summary>Always dark.</summary>
Dark,
}
@@ -0,0 +1,13 @@
/*
* Copyright (c) 2026 James Maes (KofTwentyTwo)
* SPDX-License-Identifier: MIT
*/
namespace KofTwentyTwo.AppKit.Settings;
/// <summary>Settings that repair out-of-range or missing values after loading.</summary>
public interface ISanitizable
{
/// <summary>Clamps, defaults, and validates every value in place.</summary>
void Sanitize();
}
@@ -8,16 +8,6 @@ using System.Text.Json.Serialization.Metadata;
namespace KofTwentyTwo.AppKit.Settings;
/// <summary>Settings that repair out-of-range or missing values after loading.</summary>
public interface ISanitizable
{
/// <summary>Clamps, defaults, and validates every value in place.</summary>
void Sanitize();
}
/// <summary>
/// Loads and saves a settings object as indented JSON. Takes a source-generated
/// <see cref="JsonTypeInfo{T}"/> so trimmed Release publishes need no reflection.
@@ -105,6 +95,7 @@ public sealed class SettingsStore<T>
/// <summary>Deletes a file if it can; used to clean up the temporary file after a failed save.</summary>
private static void TryDelete(string path)
{
try
@@ -7,22 +7,6 @@ using System.Text.Json.Serialization;
namespace KofTwentyTwo.AppKit.Settings;
/// <summary>The app's color theme.</summary>
public enum AppTheme
{
/// <summary>Follow the Windows setting.</summary>
System,
/// <summary>Always light.</summary>
Light,
/// <summary>Always dark.</summary>
Dark,
}
/// <summary>
/// Preferences every AppKit app shares: theme, startup splash, and automatic update
/// checks. Apps derive their own settings class from this one and register the derived
@@ -5,8 +5,10 @@
namespace KofTwentyTwo.AppKit.Tests;
/// <summary>Tests for the splash and About credit text.</summary>
public class CreditsTests
{
/// <summary>ContactLine: joins what is set.</summary>
[Fact]
public void ContactLine_JoinsWhatIsSet()
{
@@ -23,6 +25,7 @@ public class CreditsTests
/// <summary>ContactLine: empty when nothing is set.</summary>
[Fact]
public void ContactLine_EmptyWhenNothingIsSet()
{
@@ -32,6 +35,7 @@ public class CreditsTests
/// <summary>The owner profile is host/owner for any repository URL, or just the host when the path is empty.</summary>
[Theory]
[InlineData(null, null)]
[InlineData("https://github.com/", "github.com")]
+14
View File
@@ -13,6 +13,7 @@ namespace KofTwentyTwo.AppKit.Tests;
/// <summary>A per-test temporary directory, deleted on dispose.</summary>
internal sealed class TempDirectory : IDisposable
{
/// <summary>Creates a unique folder under the system temp directory.</summary>
public TempDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "appkit-tests", Guid.NewGuid().ToString("N"));
@@ -25,10 +26,12 @@ internal sealed class TempDirectory : IDisposable
/// <summary>A path inside the folder.</summary>
public string File(string name) => System.IO.Path.Combine(Path, name);
/// <summary>Deletes the folder; a handle a failing test left open is left for the OS temp cleaner.</summary>
public void Dispose()
{
try
@@ -51,6 +54,7 @@ internal sealed class ManualTimeProvider(DateTimeOffset now) : TimeProvider
/// <summary>The settable current time.</summary>
public override DateTimeOffset GetUtcNow() => Now;
@@ -71,14 +75,17 @@ internal sealed class RecordingLog : IActivityLog
/// <summary>Records an INFO entry.</summary>
public void Info(string message) => Entries.Add("INFO " + message);
/// <summary>Records a WARN entry.</summary>
public void Warning(string message) => Entries.Add("WARN " + message);
/// <summary>Records an ERROR entry (the exception is not needed by the tests).</summary>
public void Error(string message, Exception? exception = null) => Entries.Add("ERROR " + message);
}
@@ -93,6 +100,7 @@ internal sealed class RecordingPrompter(bool confirm = false) : IUserPrompter
/// <summary>Records the message.</summary>
public Task ShowMessageAsync(string title, string message)
{
Messages.Add((title, message));
@@ -101,6 +109,7 @@ internal sealed class RecordingPrompter(bool confirm = false) : IUserPrompter
/// <summary>Records the question and answers with the scripted choice.</summary>
public Task<bool> ConfirmAsync(string title, string message, string confirmText, string cancelText)
{
Confirmations.Add((title, message, confirmText, cancelText));
@@ -125,10 +134,12 @@ internal sealed class FakeUpdateService : IUpdateService
/// <summary>Returns the scripted check result.</summary>
public Task<UpdateCheckResult> CheckAsync(CancellationToken cancellationToken = default) => Task.FromResult(NextCheck);
/// <summary>Counts the call and returns the scripted error, or null for success.</summary>
public Task<string?> DownloadAndApplyAsync(IProgress<int>? progress = null, CancellationToken cancellationToken = default)
{
ApplyCalls++;
@@ -157,11 +168,13 @@ internal sealed class FakeBackend : IUpdateBackend
/// <summary>Returns the scripted available version, or fails with the scripted exception.</summary>
public Task<string?> CheckAsync()
=> CheckFailure is null ? Task.FromResult(Available) : Task.FromException<string?>(CheckFailure);
/// <summary>Counts the download and reports 100% progress, or fails with the scripted exception.</summary>
public Task DownloadAsync(Action<int>? progress, CancellationToken cancellationToken)
{
if(DownloadFailure is not null)
@@ -175,5 +188,6 @@ internal sealed class FakeBackend : IUpdateBackend
/// <summary>Counts the apply; the real backend would exit the process here.</summary>
public void ApplyAndRestart() => Applies++;
}
@@ -9,8 +9,10 @@ using System.Reflection.Emit;
namespace KofTwentyTwo.AppKit.Tests;
/// <summary>Tests for app identity: id validation, defaults, and derived names.</summary>
public class AppInfoTests
{
/// <summary>Id: accepts valid ids.</summary>
[Theory]
[InlineData("gclo")]
[InlineData("my-app-2")]
@@ -23,6 +25,7 @@ public class AppInfoTests
/// <summary>Id: rejects invalid ids.</summary>
[Theory]
[InlineData("")]
[InlineData("Gclo")]
@@ -33,11 +36,12 @@ public class AppInfoTests
public void Id_RejectsInvalidIds(string? id)
{
ArgumentException ex = Assert.Throws<ArgumentException>(() => new AppInfo { Id = id!, DisplayName = "X" });
Assert.Equal("Id", ex.ParamName);
Assert.Equal("value", ex.ParamName);
}
/// <summary>DataDirectoryVariable: is upper snake case of id.</summary>
[Fact]
public void DataDirectoryVariable_IsUpperSnakeCaseOfId()
{
@@ -46,6 +50,7 @@ public class AppInfoTests
/// <summary>Defaults: are empty and brand is set.</summary>
[Fact]
public void Defaults_AreEmptyAndBrandIsSet()
{
@@ -67,6 +72,7 @@ public class AppInfoTests
/// <summary>AllProperties: round trip.</summary>
[Fact]
public void AllProperties_RoundTrip()
{
@@ -94,8 +100,10 @@ public class AppInfoTests
/// <summary>Tests for parsing brand colors.</summary>
public class ArgbColorTests
{
/// <summary>Parse: six digits is opaque.</summary>
[Fact]
public void Parse_SixDigits_IsOpaque()
{
@@ -104,6 +112,7 @@ public class ArgbColorTests
/// <summary>Parse: eight digits keeps alpha.</summary>
[Fact]
public void Parse_EightDigits_KeepsAlpha()
{
@@ -112,6 +121,7 @@ public class ArgbColorTests
/// <summary>Components: are exposed.</summary>
[Fact]
public void Components_AreExposed()
{
@@ -121,6 +131,7 @@ public class ArgbColorTests
/// <summary>TryParse: rejects malformed.</summary>
[Theory]
[InlineData(null)]
[InlineData("")]
@@ -135,6 +146,7 @@ public class ArgbColorTests
/// <summary>Parse: malformed throws.</summary>
[Fact]
public void Parse_Malformed_Throws()
{
@@ -144,36 +156,40 @@ public class ArgbColorTests
/// <summary>Tests for the per-user data paths and the data-directory override.</summary>
public class AppPathsTests
{
private static readonly AppInfo App = new() { Id = "my-app", DisplayName = "My App" };
private static readonly AppInfo s_app = new() { Id = "my-app", DisplayName = "My App" };
/// <summary>DataRoot: defaults to local app data.</summary>
[Fact]
public void DataRoot_DefaultsToLocalAppData()
{
var paths = new AppPaths(App, _ => null);
var paths = new AppPaths(s_app, _ => null);
string expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "my-app");
Assert.Equal(expected, paths.DataRoot);
}
/// <summary>DataRoot: empty override uses default.</summary>
[Fact]
public void DataRoot_EmptyOverride_UsesDefault()
{
var paths = new AppPaths(App, _ => "");
var paths = new AppPaths(s_app, _ => "");
Assert.EndsWith("my-app", paths.DataRoot, StringComparison.Ordinal);
}
/// <summary>DataRoot: honors override variable.</summary>
[Fact]
public void DataRoot_HonorsOverrideVariable()
{
string? asked = null;
var paths = new AppPaths(App, name =>
var paths = new AppPaths(s_app, name =>
{
asked = name;
return @"D:\portable";
@@ -187,6 +203,7 @@ public class AppPathsTests
/// <summary>PublicConstructor: reads the real environment.</summary>
[Fact]
public void PublicConstructor_ReadsTheRealEnvironment()
{
@@ -196,6 +213,7 @@ public class AppPathsTests
/// <summary>Constructor: null app throws.</summary>
[Fact]
public void Constructor_NullApp_Throws()
{
@@ -205,8 +223,10 @@ public class AppPathsTests
/// <summary>Tests for the build identity text and prerelease detection.</summary>
public class BuildVersionTests
{
/// <summary>Format: shortens commit metadata.</summary>
[Theory]
[InlineData(null, "unknown")]
[InlineData(" ", "unknown")]
@@ -222,6 +242,7 @@ public class BuildVersionTests
/// <summary>IsPrerelease: looks only at the version part.</summary>
[Theory]
[InlineData(null, false)]
[InlineData("1.2.3", false)]
@@ -235,6 +256,7 @@ public class BuildVersionTests
/// <summary>Describe: reads informational version.</summary>
[Fact]
public void Describe_ReadsInformationalVersion()
{
@@ -245,6 +267,7 @@ public class BuildVersionTests
/// <summary>Describe: falls back to assembly version.</summary>
[Fact]
public void Describe_FallsBackToAssemblyVersion()
{
@@ -255,6 +278,7 @@ public class BuildVersionTests
/// <summary>Describe: no version attributes is zero version.</summary>
[Fact]
public void Describe_NoVersionAttributes_IsZeroVersion()
{
@@ -265,6 +289,7 @@ public class BuildVersionTests
/// <summary>NullAssembly: throws.</summary>
[Fact]
public void NullAssembly_Throws()
{
@@ -274,7 +299,8 @@ public class BuildVersionTests
private static Assembly Emit(string? informationalVersion, Version? version)
/// <summary>Emits an in-memory assembly with the given informational and assembly versions, so every fallback branch can be tested.</summary>
private static AssemblyBuilder Emit(string? informationalVersion, Version? version)
{
var name = new AssemblyName("Emitted" + Guid.NewGuid().ToString("N")) { Version = version };
var builder = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
@@ -8,6 +8,7 @@ using KofTwentyTwo.AppKit.Logging;
namespace KofTwentyTwo.AppKit.Tests;
/// <summary>Tests for the daily file log: entry format, rollover, retention, and failure handling.</summary>
public sealed class FileActivityLogTests : IDisposable
{
private readonly TempDirectory _temp = new();
@@ -15,10 +16,12 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>Deletes the test&apos;s temporary folder.</summary>
public void Dispose() => _temp.Dispose();
/// <summary>Writes: timestamped levels to todays file.</summary>
[Fact]
public void Writes_TimestampedLevels_ToTodaysFile()
{
@@ -39,6 +42,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>RollsOver: at midnight.</summary>
[Fact]
public void RollsOver_AtMidnight()
{
@@ -52,6 +56,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>Prunes: files outside retention once per day.</summary>
[Fact]
public void Prunes_FilesOutsideRetention_OncePerDay()
{
@@ -80,6 +85,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>Prune: skips files it cannot delete.</summary>
[Fact]
public void Prune_SkipsFilesItCannotDelete()
{
@@ -96,6 +102,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>ZeroRetention: keeps everything.</summary>
[Fact]
public void ZeroRetention_KeepsEverything()
{
@@ -108,6 +115,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>WriteFailures: are swallowed.</summary>
[Fact]
public void WriteFailures_AreSwallowed()
{
@@ -121,6 +129,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>ForApp: uses the apps logs folder and id.</summary>
[Fact]
public void ForApp_UsesTheAppsLogsFolderAndId()
{
@@ -136,6 +145,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>Constructor: validates arguments.</summary>
[Fact]
public void Constructor_ValidatesArguments()
{
@@ -146,6 +156,7 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>NullLog: discards everything.</summary>
[Fact]
public void NullLog_DiscardsEverything()
{
@@ -160,16 +171,19 @@ public sealed class FileActivityLogTests : IDisposable
/// <summary>Tests for reading and filtering log tails.</summary>
public sealed class LogTailTests : IDisposable
{
private readonly TempDirectory _temp = new();
/// <summary>Deletes the test&apos;s temporary folder.</summary>
public void Dispose() => _temp.Dispose();
/// <summary>Read: missing file is empty.</summary>
[Theory]
[InlineData(null)]
[InlineData("")]
@@ -183,6 +197,7 @@ public sealed class LogTailTests : IDisposable
/// <summary>Read: keeps only the tail.</summary>
[Fact]
public void Read_KeepsOnlyTheTail()
{
@@ -195,6 +210,7 @@ public sealed class LogTailTests : IDisposable
/// <summary>Read: locked file returns an explanation.</summary>
[Fact]
public void Read_LockedFile_ReturnsAnExplanation()
{
@@ -208,6 +224,7 @@ public sealed class LogTailTests : IDisposable
/// <summary>Read: rejects non positive line counts.</summary>
[Fact]
public void Read_RejectsNonPositiveLineCounts()
{
@@ -216,6 +233,7 @@ public sealed class LogTailTests : IDisposable
/// <summary>ErrorsOnly: keeps error entries with continuation lines.</summary>
[Fact]
public void ErrorsOnly_KeepsErrorEntriesWithContinuationLines()
{
@@ -235,6 +253,7 @@ public sealed class LogTailTests : IDisposable
/// <summary>ToDisplayText: has friendly empty states.</summary>
[Fact]
public void ToDisplayText_HasFriendlyEmptyStates()
{
@@ -245,6 +264,7 @@ public sealed class LogTailTests : IDisposable
/// <summary>NullArguments: throw.</summary>
[Fact]
public void NullArguments_Throw()
{
@@ -9,8 +9,10 @@ using KofTwentyTwo.AppKit.Secrets;
namespace KofTwentyTwo.AppKit.Tests;
/// <summary>Tests for the in-memory secret vault.</summary>
public class InMemorySecretVaultTests
{
/// <summary>Store, overwrite, retrieve, and delete behave like a dictionary, and deleting twice is harmless.</summary>
[Fact]
public void StoreRetrieveDelete()
{
@@ -26,6 +28,7 @@ public class InMemorySecretVaultTests
/// <summary>Empty keys and null secrets are rejected.</summary>
[Fact]
public void ValidatesArguments()
{
@@ -46,6 +49,7 @@ public sealed class CredentialManagerVaultTests : IDisposable
/// <summary>Removes the credentials the test may have created.</summary>
public void Dispose()
{
_vault.Delete("token");
@@ -54,6 +58,7 @@ public sealed class CredentialManagerVaultTests : IDisposable
/// <summary>A secret round-trips through the Credential Manager, overwrites in place, and deletes cleanly.</summary>
[Fact]
public void StoreRetrieveOverwriteDelete()
{
@@ -68,6 +73,7 @@ public sealed class CredentialManagerVaultTests : IDisposable
/// <summary>EmptySecret: round trips.</summary>
[Fact]
public void EmptySecret_RoundTrips()
{
@@ -77,6 +83,7 @@ public sealed class CredentialManagerVaultTests : IDisposable
/// <summary>TargetName: is prefix colon key.</summary>
[Fact]
public void TargetName_IsPrefixColonKey()
{
@@ -87,6 +94,7 @@ public sealed class CredentialManagerVaultTests : IDisposable
/// <summary>OversizedSecret: fails loudly.</summary>
[Fact]
public void OversizedSecret_FailsLoudly()
{
@@ -98,6 +106,7 @@ public sealed class CredentialManagerVaultTests : IDisposable
/// <summary>InvalidTargets: surface native errors.</summary>
[Fact]
public void InvalidTargets_SurfaceNativeErrors()
{
@@ -107,6 +116,7 @@ public sealed class CredentialManagerVaultTests : IDisposable
/// <summary>Constructor: validates platform and prefix.</summary>
[Fact]
public void Constructor_ValidatesPlatformAndPrefix()
{
@@ -16,6 +16,7 @@ public sealed class SampleSettings : ShellSettings
/// <summary>Repairs the shell settings, then clamps the app&apos;s own value.</summary>
public override void Sanitize()
{
base.Sanitize();
@@ -33,6 +34,7 @@ public sealed class PlainSettings
/// <summary>Source-generated serializer for the test settings types.</summary>
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(SampleSettings))]
[JsonSerializable(typeof(PlainSettings))]
@@ -42,21 +44,25 @@ internal sealed partial class TestSettingsContext : JsonSerializerContext
/// <summary>Tests for loading and saving settings, including corrupt files and failed writes.</summary>
public sealed class SettingsStoreTests : IDisposable
{
private readonly TempDirectory _temp = new();
/// <summary>Deletes the test&apos;s temporary folder.</summary>
public void Dispose() => _temp.Dispose();
/// <summary>A store for the sample settings, by default in a nested folder that does not exist yet.</summary>
private SettingsStore<SampleSettings> Store(string? path = null)
=> new(path ?? _temp.File(Path.Combine("nested", "settings.json")), TestSettingsContext.Default.SampleSettings);
/// <summary>Load: missing file returns defaults.</summary>
[Fact]
public void Load_MissingFile_ReturnsDefaults()
{
@@ -67,6 +73,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>SaveThenLoad: round trips.</summary>
[Fact]
public void SaveThenLoad_RoundTrips()
{
@@ -86,6 +93,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Load: corrupt or null file returns defaults.</summary>
[Theory]
[InlineData("{ not json")]
[InlineData("null")]
@@ -99,6 +107,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Load: sanitizes out of range values.</summary>
[Fact]
public void Load_SanitizesOutOfRangeValues()
{
@@ -113,6 +122,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Save: failure returns false.</summary>
[Fact]
public void Save_FailureReturnsFalse()
{
@@ -123,6 +133,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Save: swap fails cleans up the temporary file.</summary>
[Fact]
public void Save_SwapFails_CleansUpTheTemporaryFile()
{
@@ -134,6 +145,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Save: temporary path blocked returns false and leaves original.</summary>
[Fact]
public void Save_TemporaryPathBlocked_ReturnsFalseAndLeavesOriginal()
{
@@ -156,6 +168,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Save: bare file name writes relative to current directory.</summary>
[Fact]
public void Save_BareFileName_WritesRelativeToCurrentDirectory()
{
@@ -173,6 +186,7 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Constructor: and save validate arguments.</summary>
[Fact]
public void Constructor_And_Save_ValidateArguments()
{
@@ -184,8 +198,10 @@ public sealed class SettingsStoreTests : IDisposable
/// <summary>Tests for the shared shell settings and their repair rules.</summary>
public class ShellSettingsTests
{
/// <summary>ThemeKind: tolerates bad stored values.</summary>
[Theory]
[InlineData("Light", AppTheme.Light)]
[InlineData("Dark", AppTheme.Dark)]
@@ -200,6 +216,7 @@ public class ShellSettingsTests
/// <summary>Sanitize: clamps splash.</summary>
[Theory]
[InlineData(0, ShellSettings.DefaultSplashMilliseconds)]
[InlineData(1, ShellSettings.MinSplashMilliseconds)]
@@ -215,6 +232,7 @@ public class ShellSettingsTests
/// <summary>Fresh settings show the splash, check for updates, and use the default splash time.</summary>
[Fact]
public void Defaults()
{
@@ -8,8 +8,10 @@ using KofTwentyTwo.AppKit.Updates;
namespace KofTwentyTwo.AppKit.Tests;
/// <summary>Tests for update check results.</summary>
public class UpdateCheckResultTests
{
/// <summary>Only a result with a version and no error counts as an available update.</summary>
[Fact]
public void Factories()
{
@@ -22,8 +24,10 @@ public class UpdateCheckResultTests
/// <summary>Tests for the update service&apos;s guarding and state, over a fake Velopack backend.</summary>
public class VelopackUpdateServiceTests
{
/// <summary>NotInstalled: is unsupported.</summary>
[Fact]
public async Task NotInstalled_IsUnsupported()
{
@@ -36,6 +40,7 @@ public class VelopackUpdateServiceTests
/// <summary>BackendThatCannotBeCreated: is unsupported and never throws.</summary>
[Fact]
public async Task BackendThatCannotBeCreated_IsUnsupportedAndNeverThrows()
{
@@ -48,6 +53,7 @@ public class VelopackUpdateServiceTests
/// <summary>Check: finds update then downloads applies with progress.</summary>
[Fact]
public async Task Check_FindsUpdate_ThenDownloadsAppliesWithProgress()
{
@@ -69,6 +75,7 @@ public class VelopackUpdateServiceTests
/// <summary>Check: up to date leaves nothing to install.</summary>
[Fact]
public async Task Check_UpToDate_LeavesNothingToInstall()
{
@@ -79,6 +86,7 @@ public class VelopackUpdateServiceTests
/// <summary>Check: failure is reported and clears pending update.</summary>
[Fact]
public async Task Check_Failure_IsReportedAndClearsPendingUpdate()
{
@@ -93,6 +101,7 @@ public class VelopackUpdateServiceTests
/// <summary>DownloadFailure: is returned.</summary>
[Fact]
public async Task DownloadFailure_IsReturned()
{
@@ -105,6 +114,7 @@ public class VelopackUpdateServiceTests
/// <summary>RealVelopack: outside an install is unsupported.</summary>
[Fact]
public async Task RealVelopack_OutsideAnInstall_IsUnsupported()
{
@@ -117,6 +127,7 @@ public class VelopackUpdateServiceTests
/// <summary>NullRepository: throws.</summary>
[Fact]
public void NullRepository_Throws()
{
@@ -125,14 +136,17 @@ public class VelopackUpdateServiceTests
/// <summary>An IProgress that reports immediately on the calling thread, so assertions see the values.</summary>
private sealed class SynchronousProgress(Action<int> report) : IProgress<int>
{
/// <summary>Forwards the value to the callback.</summary>
public void Report(int value) => report(value);
}
}
/// <summary>Tests for the interactive and quiet update flows.</summary>
public class UpdateCoordinatorTests
{
private readonly FakeUpdateService _updates = new();
@@ -140,10 +154,12 @@ public class UpdateCoordinatorTests
/// <summary>A coordinator over the fake service and the given prompter, logging to the recording log.</summary>
private UpdateCoordinator Coordinator(RecordingPrompter prompter) => new(_updates, prompter, "Sample", _log);
/// <summary>Interactive: unsupported says so.</summary>
[Fact]
public async Task Interactive_Unsupported_SaysSo()
{
@@ -155,6 +171,7 @@ public class UpdateCoordinatorTests
/// <summary>Interactive: failure explains and logs.</summary>
[Fact]
public async Task Interactive_Failure_ExplainsAndLogs()
{
@@ -167,6 +184,7 @@ public class UpdateCoordinatorTests
/// <summary>Interactive: up to date shows current version.</summary>
[Theory]
[InlineData("1.0.0", "You are up to date (v1.0.0).")]
[InlineData(null, "You are up to date.")]
@@ -180,6 +198,7 @@ public class UpdateCoordinatorTests
/// <summary>Interactive: available declined does not install.</summary>
[Fact]
public async Task Interactive_Available_Declined_DoesNotInstall()
{
@@ -196,6 +215,7 @@ public class UpdateCoordinatorTests
/// <summary>Interactive: available accepted installs.</summary>
[Fact]
public async Task Interactive_Available_Accepted_Installs()
{
@@ -209,6 +229,7 @@ public class UpdateCoordinatorTests
/// <summary>Install: failure is shown and logged.</summary>
[Fact]
public async Task Install_Failure_IsShownAndLogged()
{
@@ -222,6 +243,7 @@ public class UpdateCoordinatorTests
/// <summary>Quiet: unsupported up to date and failure stay silent.</summary>
[Fact]
public async Task Quiet_Unsupported_UpToDate_AndFailure_StaySilent()
{
@@ -242,6 +264,7 @@ public class UpdateCoordinatorTests
/// <summary>Quiet: available offers the update.</summary>
[Fact]
public async Task Quiet_Available_OffersTheUpdate()
{
@@ -255,6 +278,7 @@ public class UpdateCoordinatorTests
/// <summary>NullLog: is allowed.</summary>
[Fact]
public async Task NullLog_IsAllowed()
{
@@ -264,6 +288,7 @@ public class UpdateCoordinatorTests
/// <summary>Constructor: validates arguments.</summary>
[Fact]
public void Constructor_ValidatesArguments()
{
+20 -11
View File
@@ -33,12 +33,13 @@ public enum SampleKind
/// </summary>
public sealed class AppSession : IDisposable
{
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(10);
private static readonly TimeSpan LaunchTimeout = TimeSpan.FromSeconds(30);
private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(250);
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(10);
private static readonly TimeSpan s_launchTimeout = TimeSpan.FromSeconds(30);
private static readonly TimeSpan s_pollInterval = TimeSpan.FromMilliseconds(250);
/// <summary>Launches the sample against a fresh temporary data folder and waits for its main window.</summary>
public AppSession(SampleKind kind, bool showSplash = false)
{
ExePath = ResolveExePath(kind);
@@ -110,20 +111,22 @@ public sealed class AppSession : IDisposable
/// <summary>Retries the lookup until it returns an element, or fails naming what was awaited.</summary>
public AutomationElement WaitFor(Func<AutomationElement?> lookup, string description, TimeSpan? timeout = null)
{
TimeSpan effective = timeout ?? DefaultTimeout;
RetryResult<AutomationElement?> result = Retry.WhileNull(lookup, timeout: effective, interval: PollInterval, ignoreException: true);
TimeSpan effective = timeout ?? s_defaultTimeout;
RetryResult<AutomationElement?> result = Retry.WhileNull(lookup, timeout: effective, interval: s_pollInterval, ignoreException: true);
return result.Result
?? throw new TimeoutException($"Timed out after {effective.TotalSeconds:0}s waiting for {description}. (app exited: {App.HasExited})");
}
/// <summary>Retries until the lookup returns nothing, or fails naming what was expected to disappear.</summary>
public static void WaitUntilGone(Func<AutomationElement?> lookup, string description, TimeSpan? timeout = null)
{
TimeSpan effective = timeout ?? DefaultTimeout;
if(!Retry.WhileTrue(() => lookup() is not null, timeout: effective, interval: PollInterval, ignoreException: true).Success)
TimeSpan effective = timeout ?? s_defaultTimeout;
if(!Retry.WhileTrue(() => lookup() is not null, timeout: effective, interval: s_pollInterval, ignoreException: true).Success)
{
throw new TimeoutException($"Timed out after {effective.TotalSeconds:0}s waiting for {description} to go away.");
}
@@ -131,11 +134,13 @@ public sealed class AppSession : IDisposable
/// <summary>Waits for the element with the given automation id in any of the app&apos;s windows.</summary>
public AutomationElement WaitForElement(string automationId, TimeSpan? timeout = null)
=> WaitFor(() => FindInApp(cf => cf.ByAutomationId(automationId)), $"element '{automationId}'", timeout);
/// <summary>Waits until no element with the given automation id remains.</summary>
public void WaitForElementGone(string automationId, TimeSpan? timeout = null)
=> WaitUntilGone(() => FindInApp(cf => cf.ByAutomationId(automationId)), $"element '{automationId}'", timeout);
@@ -164,7 +169,7 @@ public sealed class AppSession : IDisposable
Invoke(menu);
}
Wait.UntilInputIsProcessed();
item = Retry.WhileNull(() => FindInApp(cf => cf.ByAutomationId(itemAutomationId)), timeout: TimeSpan.FromSeconds(3), interval: PollInterval, ignoreException: true).Result;
item = Retry.WhileNull(() => FindInApp(cf => cf.ByAutomationId(itemAutomationId)), timeout: TimeSpan.FromSeconds(3), interval: s_pollInterval, ignoreException: true).Result;
}
Invoke(item ?? throw new TimeoutException($"Menu item '{itemAutomationId}' never appeared under '{menuName}'. (app exited: {App.HasExited})"));
}
@@ -194,6 +199,7 @@ public sealed class AppSession : IDisposable
/// <summary>Invokes an element through UI Automation, falling back to a mouse click.</summary>
private static void Invoke(AutomationElement element)
{
if(element.Patterns.Invoke.TryGetPattern(out IInvokePattern? invoke))
@@ -209,6 +215,7 @@ public sealed class AppSession : IDisposable
/// <summary>Waits for the app&apos;s main window, failing fast if the process exits.</summary>
private Window WaitForMainWindow()
{
RetryResult<Window?> result = Retry.WhileNull(
@@ -227,13 +234,14 @@ public sealed class AppSession : IDisposable
return null;
}
},
timeout: LaunchTimeout,
interval: PollInterval);
return result.Result ?? throw new TimeoutException($"The main window did not appear within {LaunchTimeout.TotalSeconds:0}s. Exe: {ExePath}");
timeout: s_launchTimeout,
interval: s_pollInterval);
return result.Result ?? throw new TimeoutException($"The main window did not appear within {s_launchTimeout.TotalSeconds:0}s. Exe: {ExePath}");
}
/// <summary>Reads a file the app may still be writing, without locking it.</summary>
private static string ReadShared(string path)
{
if(!File.Exists(path))
@@ -280,6 +288,7 @@ public sealed class AppSession : IDisposable
/// <summary>Closes the app (killing it if needed), then disposes the automation and deletes the data folder.</summary>
public void Dispose()
{
try
@@ -15,6 +15,7 @@ namespace KofTwentyTwo.AppKit.UiTests;
[Collection("Desktop")]
public class SampleAppTests
{
/// <summary>Splash: shows then dismisses itself.</summary>
[Theory]
[InlineData(SampleKind.WinUI)]
[InlineData(SampleKind.Wpf)]
@@ -27,6 +28,7 @@ public class SampleAppTests
/// <summary>About: shows the build version.</summary>
[Theory]
[InlineData(SampleKind.WinUI)]
[InlineData(SampleKind.Wpf)]
@@ -42,6 +44,7 @@ public class SampleAppTests
/// <summary>UnhandledException: is logged and the app survives.</summary>
[Theory]
[InlineData(SampleKind.WinUI)]
[InlineData(SampleKind.Wpf)]
@@ -58,6 +61,7 @@ public class SampleAppTests
/// <summary>ActivityLog: opens a window showing the log.</summary>
[Theory]
[InlineData(SampleKind.WinUI)]
[InlineData(SampleKind.Wpf)]
@@ -72,6 +76,7 @@ public class SampleAppTests
/// <summary>ThemeChoice: is saved.</summary>
[Theory]
[InlineData(SampleKind.WinUI)]
[InlineData(SampleKind.Wpf)]
@@ -86,6 +91,7 @@ public class SampleAppTests
/// <summary>CheckForUpdates: in a loose build says updates need an install.</summary>
[Theory]
[InlineData(SampleKind.WinUI)]
[InlineData(SampleKind.Wpf)]
@@ -102,6 +108,7 @@ public class SampleAppTests
/// <summary>UI tests share one desktop, so the collection never runs in parallel.</summary>
[CollectionDefinition("Desktop", DisableParallelization = true)]
public class DesktopCollectionDefinition
{
+9 -3
View File
@@ -22,10 +22,11 @@ internal static class Program
private const double Box = 512;
private const double TileInset = 48;
private const double TileRadius = 104;
private static readonly int[] IconSizes = [16, 20, 24, 32, 40, 48, 64, 128, 256];
private static readonly int[] s_iconSizes = [16, 20, 24, 32, 40, 48, 64, 128, 256];
/// <summary>Entry point: reads the options, then writes app-icon.svg and a multi-size app.ico to the output folder.</summary>
[STAThread]
private static int Main(string[] args)
{
@@ -44,13 +45,14 @@ internal static class Program
Directory.CreateDirectory(outDir);
File.WriteAllText(Path.Combine(outDir, "app-icon.svg"), Svg(spec));
WriteIco(Path.Combine(outDir, "app.ico"), IconSizes.Select(size => Png(spec, size)).ToList(), IconSizes);
WriteIco(Path.Combine(outDir, "app.ico"), s_iconSizes.Select(size => Png(spec, size)).ToList(), s_iconSizes);
Console.WriteLine($"Wrote app-icon.svg and app.ico to {Path.GetFullPath(outDir)}");
return 0;
}
/// <summary>Parses --name value pairs into a case-insensitive dictionary.</summary>
private static Dictionary<string, string> Parse(string[] args)
{
var options = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
@@ -63,6 +65,7 @@ internal static class Program
/// <summary>The mark as SVG text: the rounded gradient tile and the white stroked glyph.</summary>
private static string Svg(MarkSpec spec)
=> $"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
@@ -81,6 +84,7 @@ internal static class Program
/// <summary>Renders the mark with WPF as a PNG of the given pixel size.</summary>
private static byte[] Png(MarkSpec spec, int size)
{
var visual = new DrawingVisual();
@@ -106,7 +110,7 @@ internal static class Program
/// <summary>Writes an .ico whose frames are embedded PNGs (supported since Windows Vista).</summary>
private static void WriteIco(string path, IReadOnlyList<byte[]> pngs, IReadOnlyList<int> sizes)
private static void WriteIco(string path, List<byte[]> pngs, int[] sizes)
{
using var writer = new BinaryWriter(File.Create(path));
writer.Write((ushort)0); // reserved
@@ -133,6 +137,7 @@ internal static class Program
/// <summary>Parses a #RRGGBB or #AARRGGBB string into a WPF color.</summary>
private static Color ToColor(string hex)
{
var color = ArgbColor.Parse(hex);
@@ -141,5 +146,6 @@ internal static class Program
/// <summary>The mark definition: gradient colors, the glyph's SVG path data, and its stroke width.</summary>
private sealed record MarkSpec(string Start, string End, string Glyph, double Stroke);
}