From 8d4b00aceb3478cda7bbcac0be4af886ab321db2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 12:40:57 +0000 Subject: [PATCH] test(app): screen smoke tests and thumbnail decoding on Windows Every screen is rendered from the --capture sample data in an off-screen main window in both themes; thumbnails are decoded from embedded previews with orientation. The sign-in flow now stores the login token on every IServerApi, and thumbnail pending loads include index lookups so capture waits for them. A cancelled-load test no longer depends on scheduling. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.App/Library/ThumbnailService.cs | 29 +- src/Titano.App/Server/ConnectFlow.cs | 2 + .../About/UpdateCheckTests.cs | 2 +- .../Library/ThumbnailCacheTests.cs | 9 +- .../Windows/ScreenSmokeTests.cs | 327 ++++++++++++++++++ .../Windows/ThumbnailDecodeTests.cs | 101 ++++++ 6 files changed, 461 insertions(+), 9 deletions(-) create mode 100644 tests/Titano.App.Tests/Windows/ScreenSmokeTests.cs create mode 100644 tests/Titano.App.Tests/Windows/ThumbnailDecodeTests.cs diff --git a/src/Titano.App/Library/ThumbnailService.cs b/src/Titano.App/Library/ThumbnailService.cs index 439650c9..50630c90 100644 --- a/src/Titano.App/Library/ThumbnailService.cs +++ b/src/Titano.App/Library/ThumbnailService.cs @@ -28,6 +28,7 @@ public sealed class ThumbnailService : IDisposable private readonly ThumbnailCache _cache; private readonly ConcurrentDictionary _archiveRoots = new(); private readonly ConcurrentDictionary _firstFrames = new(); + private int _requests; public ThumbnailService(TitanoDatabase db, int capacity) { @@ -37,8 +38,8 @@ public sealed class ThumbnailService : IDisposable public int Count => _cache.Count; - /// Decodes in flight (capture waits for them). - public int PendingLoads => _cache.PendingLoads; + /// Thumbnail requests in flight, index lookups included (capture and tests wait for them). + public int PendingLoads => Math.Max(Volatile.Read(ref _requests), _cache.PendingLoads); /// Maximum thumbnails kept in memory (Settings › Storage). public int Capacity @@ -50,15 +51,31 @@ public sealed class ThumbnailService : IDisposable /// The hero thumbnail of a sequence: its hero frame, or the first frame. public async Task HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct) { - var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false); - return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null; + Interlocked.Increment(ref _requests); + try + { + var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false); + return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null; + } + finally + { + Interlocked.Decrement(ref _requests); + } } /// A frame of a sequence by index (hover scrubbing). public async Task FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct) { - var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false); - return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false); + Interlocked.Increment(ref _requests); + try + { + var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false); + return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false); + } + finally + { + Interlocked.Decrement(ref _requests); + } } /// Hover-scrub frames of a sequence, sampled to at most positions. diff --git a/src/Titano.App/Server/ConnectFlow.cs b/src/Titano.App/Server/ConnectFlow.cs index e79d845f..d024edfa 100644 --- a/src/Titano.App/Server/ConnectFlow.cs +++ b/src/Titano.App/Server/ConnectFlow.cs @@ -141,6 +141,8 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) : { var login = await _api.LoginAsync(username.Trim(), password, ct); if (login.Token is null) return Retry(ConnectError.BadCredentials); + // TitanoClient keeps the token itself; set it explicitly so every IServerApi behaves the same. + _api.Token = login.Token; User = login.User; return Set(ConnectStep.Connected, ConnectError.None); } diff --git a/tests/Titano.App.Tests/About/UpdateCheckTests.cs b/tests/Titano.App.Tests/About/UpdateCheckTests.cs index 372190de..997a89e3 100644 --- a/tests/Titano.App.Tests/About/UpdateCheckTests.cs +++ b/tests/Titano.App.Tests/About/UpdateCheckTests.cs @@ -17,7 +17,7 @@ public sealed class UpdateCheckTests Assert.Equal(Version.Parse(expected), UpdateCheck.ParseVersion(tag)); [Theory] - [Case(null)] + [Case(new object?[] { null })] [Case("")] [Case("latest")] [Case("v-one")] diff --git a/tests/Titano.App.Tests/Library/ThumbnailCacheTests.cs b/tests/Titano.App.Tests/Library/ThumbnailCacheTests.cs index 98d05c38..789c9eef 100644 --- a/tests/Titano.App.Tests/Library/ThumbnailCacheTests.cs +++ b/tests/Titano.App.Tests/Library/ThumbnailCacheTests.cs @@ -118,17 +118,22 @@ public sealed class ThumbnailCacheTests public async Task ALoadAfterACancelledOneStartsFresh() { var attempts = 0; + var blocked = true; using var cache = new ThumbnailCache(8, async (k, ct) => { - if (Interlocked.Increment(ref attempts) == 1) await Task.Delay(Timeout.Infinite, ct); + Interlocked.Increment(ref attempts); + if (Volatile.Read(ref blocked)) await Task.Delay(Timeout.Infinite, ct); return "img" + k; }); using var scrolledAway = new CancellationTokenSource(); var first = cache.GetAsync(9, scrolledAway.Token); scrolledAway.Cancel(); await Assert.ThrowsAsync(() => first); + Volatile.Write(ref blocked, false); Assert.Equal("img9", await cache.GetAsync(9, CancellationToken.None).WaitAsync(Wait)); - Assert.Equal(2, attempts); + // The cancelled load may have stopped before it reached the decoder. + Assert.InRange(Volatile.Read(ref attempts), 1, 2); + Assert.Equal(0, cache.PendingLoads); } [Test] diff --git a/tests/Titano.App.Tests/Windows/ScreenSmokeTests.cs b/tests/Titano.App.Tests/Windows/ScreenSmokeTests.cs new file mode 100644 index 00000000..fd589fa2 --- /dev/null +++ b/tests/Titano.App.Tests/Windows/ScreenSmokeTests.cs @@ -0,0 +1,327 @@ +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using Titano.App.DesignTime; +using Titano.App.Infrastructure; +using Titano.App.Sections; +using Titano.App.Server; +using Titano.App.Settings; +using Titano.App.Shell; +using Titano.Testing; +using Titano.Ui.Controls; +using Titano.Ui.Theming; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Windows; + +/// +/// Shows the real main window off screen (section templates, client styles) on the sample data used by +/// --capture and renders every screen in both themes: catches XAML, resource, template and view-model wiring +/// errors that compile cleanly. Mirrors step by step. +/// +[WindowsOnly] +[Serial] +[Timeout(300_000)] +public sealed class ScreenSmokeTests +{ + [Test] + public Task EveryScreenRendersWithSampleDataInBothThemes() => ScreenHost.RunAsync(async () => + { + await using var app = await SampleApp.StartAsync(); + var shell = app.Shell; + + // First run: empty index, the welcome dialog over the empty Library. + Assert.True(shell.Library.IsLibraryEmpty, "an empty index shows the empty Library"); + Assert.False(shell.IsJobActive); + shell.ShowWelcome(); + shell.Welcome!.ShowDiscovered(new DiscoveredServer("Studio NAS", "https://nas.local:8443")); + await app.ExpectAsync("welcome"); + Assert.True(shell.Welcome.IsLocal, "a local archive is the default choice"); + shell.CompleteWelcome(); + Assert.False(shell.IsWelcomeOpen); + await app.ExpectAsync("library-empty"); + shell.Navigate(SectionKey.Server); + await app.ExpectAsync("server-signedout"); + Assert.False(shell.Server.IsConnected); + + // A populated archive, jobs in every state, a signed-in server. + await app.Sample.FillAsync(); + await shell.Library.RefreshAsync(); + await shell.Jobs.ReloadAsync(); + await shell.Services.Server.RestoreAsync(); + shell.About.SetResult(null); + await shell.Settings.DetectEncodersAsync(); + await shell.Settings.SelfTestAsync(); + + shell.Navigate(SectionKey.Library); + Assert.Equal(36, shell.Library.Items.Count); + Assert.True(shell.Library.IsGrid); + await app.ExpectAsync("library", waitForThumbnails: true); + Assert.NotEmpty(app.FindAll()); + // The newest sequence is a RAW: its card shows the embedded preview. + Assert.Equal("Harbour sunset", shell.Library.Items[0].Title); + Assert.NotNull(shell.Library.Items[0].Thumbnail, "embedded preview of the first card"); + + shell.Library.Items[0].IsSelected = true; + Assert.True(shell.Library.IsSingleSelection); + await app.ExpectAsync("library-selection", waitForThumbnails: true); + shell.Library.LayoutIndex = 1; + Assert.True(shell.Library.IsList); + await app.ExpectAsync("library-list", waitForThumbnails: true); + shell.Library.LayoutIndex = 0; + shell.Library.ClearSelectionCommand.Execute(null); + Assert.Equal(0, shell.Library.SelectionCount); + + shell.Navigate(SectionKey.Jobs); + Assert.Equal(9, shell.Jobs.Rows.Count); + Assert.True(shell.IsJobActive, "running jobs show in the job bar"); + shell.Jobs.Rows[0].IsExpanded = true; + await app.ExpectAsync("jobs"); + + shell.Navigate(SectionKey.Server); + Assert.True(shell.Server.IsConnected, "the saved session is restored"); + await app.ExpectAsync("server"); + + shell.Navigate(SectionKey.Settings); + Assert.Equal(3, shell.Settings.PreviewNames.Count); + Assert.Equal(6, shell.Settings.Encoders.Count); + foreach (var page in Enum.GetValues()) + { + shell.Settings.Page = page; + await app.ExpectAsync("settings-" + page.ToString().ToLowerInvariant()); + } + + shell.Navigate(SectionKey.About); + await app.ExpectAsync("about"); + + shell.Navigate(SectionKey.Import); + await app.ExpectAsync("import"); + shell.Navigate(SectionKey.Sequence); + await app.ExpectAsync("sequence"); + shell.Navigate(SectionKey.Archive); + await app.ExpectAsync("archive"); + }); + + [Test] + public Task TheShellFollowsTheLanguage() => ScreenHost.RunAsync(async () => + { + await using var app = await SampleApp.StartAsync(); + var english = app.Shell.Library.Title; + UiLanguage.Apply("it"); + try + { + Assert.NotEqual(english, app.Shell.Library.Title); + await app.ExpectAsync("library-empty-it"); + } + finally + { + UiLanguage.Apply("en"); + } + Assert.Equal(english, app.Shell.Library.Title); + }); + + /// A on capture services and sample data, shown off screen like --capture. + private sealed class SampleApp : IAsyncDisposable + { + private const double Width = 1440; + private const double Height = 900; + private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light]; + + private readonly AppEnvironment _environment; + private readonly MainWindow _window; + + private SampleApp(AppEnvironment environment, AppServices services, SampleData sample, ShellViewModel shell, MainWindow window) + { + _environment = environment; + Services = services; + Sample = sample; + Shell = shell; + _window = window; + } + + public AppServices Services { get; } + public SampleData Sample { get; } + public ShellViewModel Shell { get; } + + public static async Task StartAsync() + { + var environment = AppEnvironment.ForCapture(); + UiLanguage.Apply("en"); + ThemeManager.Apply(AppTheme.Dark); + var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs()); + var sample = SampleData.Configure(services); + var shell = new ShellViewModel(services); + + // A real window, as in the app: styles and templates apply, and Loaded/IsLoaded drive thumbnail loading. + var window = new MainWindow(shell) + { + WindowStartupLocation = WindowStartupLocation.Manual, + Left = -20000, + Top = -20000, + Width = Width, + Height = Height, + ShowActivated = false, + ShowInTaskbar = false, + }; + window.Show(); + + await sample.OpenEmptyAsync(); + await shell.StartAsync(); + Assert.Null(services.OpenError); + Assert.NotNull(services.Jobs); + Assert.NotNull(services.Thumbnails); + return new SampleApp(environment, services, sample, shell, window); + } + + /// Renders the current screen in both themes and checks that is on it. + public async Task ExpectAsync(string screen, bool waitForThumbnails = false) + where TView : FrameworkElement + { + var luminance = new Dictionary(); + foreach (var theme in Themes) + { + ThemeManager.Apply(theme); + await SettleAsync(); + if (waitForThumbnails && Services.Thumbnails is { } thumbnails) + { + for (var i = 0; i < 100 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50); + await SettleAsync(); + } + var view = FindAll().FirstOrDefault(v => v.IsVisible && v.ActualWidth > 0 && v.ActualHeight > 0); + Assert.NotNull(view, $"{screen}: no {typeof(TView).Name} on screen in {theme}"); + var bitmap = Render(); + luminance[theme] = MeanLuminance(bitmap); + Assert.Greater(Distinct(bitmap), 8, $"{screen} drew almost nothing in {theme}"); + } + Assert.Less(luminance[AppTheme.Dark], luminance[AppTheme.Light], $"{screen}: the light theme is not lighter than the dark one"); + ThemeManager.Apply(AppTheme.Dark); + } + + public List FindAll() + where T : DependencyObject + { + var found = new List(); + Collect(_window, found); + return found; + } + + public async ValueTask DisposeAsync() + { + ThemeManager.Apply(AppTheme.Dark); + _window.Close(); + Shell.Dispose(); + await Services.DisposeAsync(); + _environment.DeleteCaptureData(); + } + + private async Task SettleAsync() + { + _window.UpdateLayout(); + // Bindings, templates, async continuations and deferred work queued on the dispatcher. + await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle); + await Task.Delay(30); + await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle); + _window.UpdateLayout(); + } + + private RenderTargetBitmap Render() + { + var root = (FrameworkElement)VisualTreeHelper.GetChild(_window, 0); + var dpi = VisualTreeHelper.GetDpi(_window); + var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX); + var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY); + Assert.True(width > 0 && height > 0, "the window has a size"); + var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32); + bitmap.Render(root); + return bitmap; + } + + private static byte[] Pixels(BitmapSource bitmap) + { + var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4]; + bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0); + return pixels; + } + + private static double MeanLuminance(BitmapSource bitmap) + { + var pixels = Pixels(bitmap); + double sum = 0; + for (var i = 0; i < pixels.Length; i += 4) sum += 0.0722 * pixels[i] + 0.7152 * pixels[i + 1] + 0.2126 * pixels[i + 2]; + return sum / (pixels.Length / 4); + } + + private static int Distinct(BitmapSource bitmap) + { + var pixels = Pixels(bitmap); + var colours = new HashSet(); + for (var i = 0; i < pixels.Length && colours.Count < 1000; i += 4 * 7) + colours.Add(BitConverter.ToInt32(pixels, i)); + return colours.Count; + } + + private static void Collect(DependencyObject node, List found) + where T : DependencyObject + { + for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) + { + var child = VisualTreeHelper.GetChild(node, i); + if (child is T match) found.Add(match); + Collect(child, found); + } + } + } + + /// Dialogs that answer like a user who cancels everything. + private sealed class NoDialogs : IAppDialogs + { + public string? PickFolder(string title, string? initialFolder = null) => null; + public string? PickJsonFile(string title) => null; + public bool Confirm(ConfirmRequest request) => false; + public bool SignIn(string server, string? username, Func> signIn) => false; + } +} + +/// +/// The STA dispatcher of the process-wide WPF (only one may exist per process): reuses the +/// one an earlier WPF test created, otherwise starts it with the Titano theme; then merges the client's styles and +/// section templates, as App.xaml does. +/// +internal static class ScreenHost +{ + private static readonly Uri SectionTemplates = new("pack://application:,,,/Titano;component/Shell/SectionTemplates.xaml", UriKind.Absolute); + private static readonly Lazy Dispatcher = new(Start, LazyThreadSafetyMode.ExecutionAndPublication); + + public static Task RunAsync(Func body) => Dispatcher.Value.InvokeAsync(body).Task.Unwrap(); + + private static Dispatcher Start() + { + var app = Application.Current; + Dispatcher? dispatcher = app?.Dispatcher; + if (dispatcher is null) + { + using var ready = new ManualResetEventSlim(); + var thread = new Thread(() => + { + var created = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; + ThemeManager.Initialize(created, AppTheme.Dark); + dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; + ready.Set(); + System.Windows.Threading.Dispatcher.Run(); + }); + thread.SetApartmentState(ApartmentState.STA); + thread.IsBackground = true; + thread.Start(); + ready.Wait(); + } + dispatcher!.Invoke(() => + { + var current = Application.Current; + AppResources.Merge(current); + if (!current.Resources.MergedDictionaries.Any(d => d.Source == SectionTemplates)) + current.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = SectionTemplates }); + }); + return dispatcher; + } +} diff --git a/tests/Titano.App.Tests/Windows/ThumbnailDecodeTests.cs b/tests/Titano.App.Tests/Windows/ThumbnailDecodeTests.cs new file mode 100644 index 00000000..0db0f533 --- /dev/null +++ b/tests/Titano.App.Tests/Windows/ThumbnailDecodeTests.cs @@ -0,0 +1,101 @@ +using System.IO; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Titano.App.Library; +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Testing; + +namespace Titano.App.Tests.Windows; + +/// WIC decoding of thumbnails: embedded previews read by offset, decode-time scaling and Exif orientation. +[WindowsOnly] +public sealed class ThumbnailDecodeTests(TestContext context) +{ + [Test] + public void TheEmbeddedPreviewIsDecodedAtTheRequestedWidth() + { + var (path, frame) = FakeRaw(orientation: 1); + var image = ThumbnailService.Decode(path, frame, 160, CancellationToken.None); + Assert.NotNull(image); + Assert.Equal(160, image!.PixelWidth); + Assert.InRange(image.PixelHeight, 89, 91); + Assert.True(image.IsFrozen, "thumbnails cross threads"); + } + + [Test] + public void PortraitFramesAreTurnedAndKeepTheRequestedWidth() + { + var (path, frame) = FakeRaw(orientation: 6); + var image = ThumbnailService.Decode(path, frame, 160, CancellationToken.None); + Assert.NotNull(image); + Assert.Equal(160, image!.PixelWidth); + Assert.InRange(image.PixelHeight, 283, 286); + } + + [Test] + public void AMissingPreviewFallsBackToTheOriginal() + { + var folder = context.CreateTempDirectory(); + var path = Path.Combine(folder, "IMG_0001.JPG"); + File.WriteAllBytes(path, Jpeg(320, 180)); + // The index points past the end of the file: the original is decoded instead. + var frame = Frame(path) with { PreviewOffset = 1 << 20, PreviewLength = 4096 }; + var image = ThumbnailService.Decode(path, frame, 64, CancellationToken.None); + Assert.Equal(64, image!.PixelWidth); + Assert.Null(ThumbnailService.Decode(Path.Combine(folder, "gone.JPG"), frame, 64, CancellationToken.None)); + } + + [Test] + public void ACancelledDecodeStops() + { + var (path, frame) = FakeRaw(orientation: 1); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + Assert.Throws(() => ThumbnailService.Decode(path, frame, 160, cancelled.Token)); + } + + /// A file no decoder reads, with a JPEG preview at a known offset (how cameras store RAW previews). + private (string Path, Frame Frame) FakeRaw(int orientation) + { + var jpeg = Jpeg(320, 180); + var header = new byte[4096]; + "II*\0"u8.CopyTo(header); + var path = Path.Combine(context.CreateTempDirectory(), "IMG_0001.CR2"); + File.WriteAllBytes(path, [.. header, .. jpeg, .. new byte[2048]]); + return (path, Frame(path) with { Orientation = orientation, PreviewOffset = header.Length, PreviewLength = jpeg.Length, Format = ImageFileFormat.Cr2 }); + } + + private static Frame Frame(string path) => new() + { + Id = Guid.CreateVersion7(), + SequenceId = Guid.CreateVersion7(), + Index = 0, + RelativePath = Path.GetFileName(path), + FileName = Path.GetFileName(path), + Width = 320, + Height = 180, + Format = ImageFileFormat.Jpeg, + }; + + private static byte[] Jpeg(int width, int height) + { + var pixels = new byte[width * height * 3]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var i = (y * width + x) * 3; + pixels[i] = (byte)(x * 255 / width); + pixels[i + 1] = (byte)(y * 255 / height); + pixels[i + 2] = 96; + } + } + var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgr24, null, pixels, width * 3); + var encoder = new JpegBitmapEncoder { QualityLevel = 85 }; + encoder.Frames.Add(BitmapFrame.Create(source)); + using var stream = new MemoryStream(); + encoder.Save(stream); + return stream.ToArray(); + } +}