Files
Chronos/tests/Titano.App.Tests/Windows/ScreenSmokeTests.cs
T
Claude 77e07bf000 fix(ui): the viewport's tools are its logical children; remote editor tests read a shared job table safely
The preview tools are a property value of the viewport, presented by its template
with no logical parent, so neither an element-name nor an ancestor binding gave
them the editor reliably: the crop result toggle then showed with no tooltip.
As logical children they inherit the viewport's data context like any content.

The remote editor tests changed the fake server's job table while the source's
event loop read it, which could hand the loop a null job; it is now a concurrent
dictionary. The read-only test waits for the event, which is raised after the
flag is set, instead of the flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-11 23:20:51 +00:00

471 lines
23 KiB
C#

using System.IO;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
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.Core.Localization;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
using Titano.Ui.Theming;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Windows;
/// <summary>
/// Shows the real main window off screen (section templates, client styles) on the sample data used by
/// <c>--capture</c> and renders every screen in both themes: catches XAML, resource, template and view-model wiring
/// errors that compile cleanly. Mirrors <see cref="ScreenCapture"/> step by step.
/// </summary>
[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<WelcomeView>("welcome");
Assert.True(shell.Welcome.IsLocal, "a local archive is the default choice");
shell.CompleteWelcome();
Assert.False(shell.IsWelcomeOpen);
await app.ExpectAsync<LibraryView>("library-empty");
shell.Navigate(SectionKey.Server);
await app.ExpectAsync<ServerView>("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<LibraryView>("library", waitForThumbnails: true);
Assert.NotEmpty(app.FindAll<SequenceCard>());
// 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<LibraryView>("library-selection", waitForThumbnails: true);
shell.Library.LayoutIndex = 1;
Assert.True(shell.Library.IsList);
await app.ExpectAsync<LibraryView>("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<JobsView>("jobs");
shell.Navigate(SectionKey.Server);
Assert.True(shell.Server.IsConnected, "the saved session is restored");
await app.ExpectAsync<ServerView>("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<SettingsPage>())
{
shell.Settings.Page = page;
await app.ExpectAsync<SettingsView>("settings-" + page.ToString().ToLowerInvariant());
}
shell.Navigate(SectionKey.About);
await app.ExpectAsync<AboutView>("about");
shell.Navigate(SectionKey.Import);
await app.ExpectAsync<ImportView>("import");
shell.Navigate(SectionKey.Sequence);
await app.ExpectAsync<SequenceView>("sequence");
shell.Navigate(SectionKey.Archive);
await app.ExpectAsync<ArchiveView>("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<LibraryView>("library-empty-it");
}
finally
{
UiLanguage.Apply("en");
}
Assert.Equal(english, app.Shell.Library.Title);
});
[Test]
public Task ArabicMirrorsTheShellFromStartButNotItsPicturesOrLogo() => ScreenHost.RunAsync(async () =>
{
// The language is applied before the window exists, as at start-up with Arabic saved in the settings.
await using var app = await SampleApp.StartAsync("ar", firstRun: true);
try
{
var window = app.Window;
Assert.Equal(FlowDirection.RightToLeft, window.FlowDirection, "the main window opens mirrored");
var rail = (FrameworkElement)window.FindName("Rail");
Assert.Equal(FlowDirection.RightToLeft, rail.FlowDirection, "the rail mirrors with the window");
// The window's content carries the mirror (a capture of it alone reads right to left, as on screen).
Assert.Greater(rail.TranslatePoint(new Point(rail.ActualWidth / 2, 0), window).X, window.ActualWidth / 2, "the rail starts on the right");
// The first-run dialog keeps the shell behind it out of reach.
Assert.True(app.Shell.IsWelcomeOpen);
Assert.False(rail.IsEnabled, "the rail behind the first-run dialog takes no input");
app.Shell.CompleteWelcome();
Assert.True(rail.IsEnabled);
var id = await app.Sample.FillEditorAsync();
app.Shell.OpenSequence(id);
await app.Shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(app.Shell.Sequence.Editor);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await app.ExpectAsync<SequenceView>("sequence-ar");
// Directional glyphs follow the reading direction; the others, the logo, the picture and the charts do not.
var back = Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => b.IsVisible && ReferenceEquals(b.Command, editor.BackCommand)), "the editor's Back button");
var arrow = Descendants<Icon>(back).Single();
Assert.True(arrow.Glyph!.IsDirectional);
Assert.Equal(FlowDirection.RightToLeft, arrow.FlowDirection, "Back points the way Arabic reads");
foreach (var icon in app.FindAll<Icon>().Where(i => i.Glyph is { IsDirectional: false } && Bidi.GetIsDirectional(i) is null))
Assert.Equal(FlowDirection.LeftToRight, icon.FlowDirection, "a glyph that does not point anywhere keeps its drawing");
Assert.True(app.FindAll<BrandMarkIcon>().All(m => m.FlowDirection == FlowDirection.LeftToRight), "the logo never mirrors");
var viewport = app.FindAll<PreviewViewport>().Single(v => v.IsVisible);
Assert.Equal(FlowDirection.LeftToRight, ((FrameworkElement)viewport.Template.FindName(PreviewViewport.PartSurface, viewport)).FlowDirection, "the photo is not mirrored");
Assert.Equal(FlowDirection.RightToLeft, ((FrameworkElement)viewport.Template.FindName(PreviewViewport.PartTools, viewport)).FlowDirection, "the preview tools follow the layout");
Assert.True(app.FindAll<DrawingElement>().All(d => d.FlowDirection == FlowDirection.LeftToRight), "charts, filmstrip and curves keep their time axis");
}
finally
{
await app.Shell.Sequence.CloseAsync();
UiLanguage.Apply("en");
}
});
[Test]
public Task ToastsDrawSpeakAndCloseAfterTheirAction() => ScreenHost.RunAsync(async () =>
{
await using var app = await SampleApp.StartAsync();
app.Shell.CompleteWelcome();
var ran = false;
app.Shell.ShowToast(new Toast { Title = "Harbour sunset rendered", ActionText = "Open", ActionCommand = new RelayCommand(() => ran = true) });
await app.ExpectAsync<LibraryView>("library-toast");
var host = app.Window.Toasts;
Assert.Equal(1, host.Toasts.Count);
var toast = Assert.NotNull(host.ItemContainerGenerator.ContainerFromIndex(0) as FrameworkElement, "the toast's container");
Assert.Greater(toast.ActualHeight, 0, "the toast is drawn");
Assert.Equal("Harbour sunset rendered", AutomationProperties.GetName(toast));
var dismiss = Descendants<Button>(toast).Single(b => ReferenceEquals(b.Command, ToastHost.DismissCommand));
Assert.Equal(Loc.L("Tooltips.Common.Dismiss"), AutomationProperties.GetName(dismiss));
var action = Descendants<Button>(toast).Single(b => b.IsVisible && !ReferenceEquals(b.Command, ToastHost.DismissCommand));
Assert.True(action.Command!.CanExecute(null));
((IInvokeProvider)new ButtonAutomationPeer(action)).Invoke();
await app.ExpectAsync<LibraryView>("library-toast-done");
Assert.True(ran, "the action ran");
Assert.Equal(0, host.Toasts.Count, "the toast closes once its action has run");
// A failure interrupts the screen reader (assertive); a notice waits its turn.
Assert.False(await ArchiveActions.TryAsync(app.Shell, _ => throw new IOException("The archive drive is gone")));
Assert.True(host.Toasts.Single().IsError, "a failed archive action is announced at once");
app.Shell.Notify("Harbour sunset rendered");
Assert.False(host.Toasts[^1].IsError, "a notice is announced in turn");
});
[Test]
public Task TheChromeAndTheJobBarHaveNamesAndStates() => ScreenHost.RunAsync(async () =>
{
await using var app = await SampleApp.StartAsync();
app.Shell.CompleteWelcome();
await app.ExpectAsync<LibraryView>("library-empty");
var window = app.Window;
var captions = Descendants<Button>(window).Where(b => b.Command is RoutedCommand).ToList();
Assert.Equal(Loc.L("Tooltips.Window.Minimize"), AutomationProperties.GetName(captions.Single(b => b.Command == SystemCommands.MinimizeWindowCommand)));
Assert.Equal(Loc.L("Tooltips.Window.Maximize"), AutomationProperties.GetName(captions.Single(b => b.Command == SystemCommands.MaximizeWindowCommand)));
Assert.Equal(Loc.L("Tooltips.Window.Close"), AutomationProperties.GetName(captions.Single(b => b.Command == SystemCommands.CloseWindowCommand)));
var railToggle = Descendants<Button>(window).Single(b => ReferenceEquals(b.Command, app.Shell.ToggleRailCommand));
Assert.Equal(Loc.L(app.Shell.IsRailCollapsed ? "Shell.Nav.Expand" : "Shell.Nav.Collapse"), AutomationProperties.GetName(railToggle),
"the rail button has a short name; the sentence is its tooltip");
var bar = (JobBar)window.FindName("JobBar");
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(bar));
Assert.Equal(app.Shell.JobAnnouncement, AutomationProperties.GetName(bar), "screen readers hear the job state, not its progress");
Assert.Equal(AutomationControlType.StatusBar, UIElementAutomationPeer.CreatePeerForElement(bar).GetAutomationControlType());
var pause = Descendants<Button>(bar).Single();
Assert.Equal(Loc.L("Shell.JobBar.Pause"), AutomationProperties.GetName(pause), "a short name; the sentence is the tooltip");
// A text box hands its padding to the text itself; the template adds none (8 px after a leading icon).
app.Shell.Navigate(SectionKey.Settings);
app.Shell.Settings.Page = SettingsPage.Archive;
await app.ExpectAsync<SettingsView>("settings-archive");
var boxes = app.FindAll<TextBox>().Where(t => t.IsVisible).ToList();
Assert.Contains(boxes, t => Field.GetGlyph(t) is not null);
Assert.Contains(boxes, t => Field.GetGlyph(t) is null);
foreach (var box in boxes)
{
var host = (ScrollViewer)box.Template.FindName("PART_ContentHost", box);
Assert.Equal(box.Padding, host.Padding);
Assert.Equal(new Thickness(0), ((FrameworkElement)VisualTreeHelper.GetParent(host)).Margin, "no second padding around the text");
Assert.Equal(Field.GetGlyph(box) is null ? 0.0 : 22.0, host.Margin.Left);
}
});
/// <summary>A <see cref="MainWindow"/> on capture services and sample data, shown off screen like <c>--capture</c>.</summary>
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 MainWindow Window => _window;
/// <param name="language">The UI language, applied before the window is created (as at start-up).</param>
/// <param name="firstRun">Opens with the first-run dialog, which keeps the shell behind it disabled.</param>
public static async Task<SampleApp> StartAsync(string language = "en", bool firstRun = false)
{
var environment = AppEnvironment.ForCapture();
UiLanguage.Apply(language);
ThemeManager.Apply(AppTheme.Dark);
var settings = new AppSettings { Language = language, FirstRunCompleted = !firstRun };
var services = new AppServices(environment, settings, () => { }, 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);
}
/// <summary>Renders the current screen in both themes and checks that <typeparamref name="TView"/> is on it.</summary>
public async Task ExpectAsync<TView>(string screen, bool waitForThumbnails = false)
where TView : FrameworkElement
{
var luminance = new Dictionary<AppTheme, double>();
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<TView>().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}");
}
AssertIconOnlyControlsNamed(screen);
Assert.Less(luminance[AppTheme.Dark], luminance[AppTheme.Light], $"{screen}: the light theme is not lighter than the dark one");
ThemeManager.Apply(AppTheme.Dark);
}
/// <summary>DESIGN §4: every visible icon-only button or segment has an accessible name and a tooltip.</summary>
public void AssertIconOnlyControlsNamed(string screen)
{
foreach (var control in FindAll<Control>().Where(c => c.IsVisible && IsIconOnly(c)))
{
var name = AutomationProperties.GetName(control);
Assert.False(string.IsNullOrWhiteSpace(name), $"{screen}: an icon-only {control.GetType().Name} bound to {(control as ButtonBase)?.Command} has no name");
Assert.True(control.ToolTip is not null, $"{screen}: '{name}' has no tooltip (data context: {control.DataContext?.GetType().Name ?? "none"})");
}
}
public List<T> FindAll<T>()
where T : DependencyObject
{
var found = new List<T>();
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 bool IsIconOnly(Control control) => control switch
{
SegmentedItem segment => segment.Content is null && segment.Glyph is not null,
ButtonBase button => button.Content is null && ButtonIcon.GetGlyph(button) is not null,
_ => false,
};
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<int>();
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<T>(DependencyObject node, List<T> 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);
}
}
}
private static List<T> Descendants<T>(DependencyObject root)
where T : DependencyObject
{
var found = new List<T>();
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child is T match) found.Add(match);
found.AddRange(Descendants<T>(child));
}
return found;
}
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
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<string, string, Task<string?>> signIn) => false;
}
}
/// <summary>
/// The dispatcher of the shared WPF <see cref="Application"/> with the client's styles and section templates merged,
/// as <c>App.xaml</c> does.
/// </summary>
internal static class ScreenHost
{
private static readonly Lazy<Dispatcher> Dispatcher = new(Start, LazyThreadSafetyMode.ExecutionAndPublication);
public static Task RunAsync(Func<Task> 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;
}
}