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. internal 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 dispatcher of the shared WPF with the client's styles and section templates merged, /// as App.xaml does. /// internal static class ScreenHost { 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 dispatcher = WpfApplication.Dispatcher; dispatcher.Invoke(() => { // pack:// URIs parse only once an Application exists (it registers the scheme), so this one is built here. var sectionTemplates = new Uri("pack://application:,,,/Titano;component/Shell/SectionTemplates.xaml", UriKind.Absolute); 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; } }