using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Settings;
///
/// Settings, the first-run dialog and the reading direction on the capture sample: values other screens set, labels and
/// paths that survive long translations and right-to-left text, keyboard focus and the questions before forgetting.
///
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class SettingsScreenSmokeTests
{
[Test]
public Task SettingsShowCurrentValuesAndNeverCutLabelsOrRows() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
await shell.Services.Server.RestoreAsync();
var settings = shell.Settings;
// The open archive and the server connected to were set after Settings was built: it shows them when opened.
shell.Navigate(SectionKey.Settings);
Assert.Equal(@"D:\ChronosArchive", settings.ArchiveRoot.Text);
Assert.Equal("https://nas.local:8443", settings.DefaultServer.Text);
Assert.False(settings.ArchiveRoot.IsDirty || settings.DefaultServer.IsDirty, "values loaded, not edits");
// The section list shows where keyboard focus is.
await app.ExpectAsync("settings-general");
Assert.True(app.FindAll().Where(i => i.DataContext is SettingsPageItem).All(i => i.FocusVisualStyle is not null), "sections have a focus ring");
// At the minimum window width the cache folder row stays one line: Clear beside the path, not under it.
settings.Page = SettingsPage.Storage;
await app.ExpectAsync("settings-storage");
var window = Window.GetWindow(app.FindAll().First(v => v.IsVisible));
var width = window.Width;
window.Width = 1200;
window.UpdateLayout();
var cache = Field(app, Loc.L("Settings.Storage.Folder"));
var clear = app.FindAll().First(b => b.Content as string == Loc.L("Settings.Storage.Clear") && b.IsVisible);
Assert.Approximately(Middle(cache), Middle(clear), 2, "Clear is on the path's line");
Assert.Equal(FlowDirection.LeftToRight, cache.FlowDirection);
// Beside the 200 px rail, Clear stays inside the page in every language (owner review 1, R1).
await InsidePageInEveryLanguageAsync(window, () => app.FindAll().First(b => ReferenceEquals(b.Command, settings.ClearCacheCommand) && b.IsVisible));
window.Width = width;
// Long translations are never cut: German labels show whole (or wrap) in the shared label column.
UiLanguage.Apply("de");
try
{
await app.ExpectAsync("settings-storage-de");
foreach (var label in Labels(app)) Assert.True(IsWhole(label), $"\"{label.Text}\" is shown whole");
}
finally
{
UiLanguage.Apply("en");
}
// Auto values are text with their reason in the tooltip, not buttons that do nothing.
settings.Page = SettingsPage.Rendering;
await app.ExpectAsync("settings-rendering");
Assert.False(app.FindAll().Any(b => b.Content is string text && (text == settings.MemoryAutoText || text == settings.ParallelismAutoText)), "no dead Auto buttons");
// Paths, addresses and fingerprints read left to right; read-only paths show whole in their tooltip.
settings.Page = SettingsPage.Advanced;
await app.ExpectAsync("settings-advanced");
var data = Field(app, Loc.L("Settings.Advanced.DataFolder"));
Assert.Equal(FlowDirection.LeftToRight, data.FlowDirection);
Assert.Equal(settings.DataFolder, data.ToolTip);
// Advanced's Reset section puts its log rows back to their defaults (owner review 2, R11).
Assert.True(settings.CanResetSection);
Assert.True(app.FindAll().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "a Reset section on Advanced");
settings.Logs.SelectedRotation = settings.Logs.Rotations.Single(r => r.Value == Chronos.Core.Diagnostics.LogRotation.Hourly);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Hourly, shell.Services.Settings.LogRotation);
settings.ResetSectionCommand.Execute(null);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Daily, shell.Services.Settings.LogRotation);
// Forgetting a trusted certificate asks first, as on the Server screen; a "no" keeps it and the session.
settings.Page = SettingsPage.Server;
await app.ExpectAsync("settings-server");
Assert.True(settings.CanResetSection);
Assert.Equal(FlowDirection.LeftToRight, Field(app, Loc.L("Settings.Server.Default")).FlowDirection);
var certificate = Assert.Contains(settings.Certificates, _ => true);
Assert.Contains(certificate.Server, certificate.ForgetName);
// Beside the 200 px rail at the minimum width, Forget stays whole inside the page in every language (owner review 1, R1).
window.Width = 1200;
// (A language switch makes the certificate rows again: each round finds Forget in the row it shows.)
await InsidePageInEveryLanguageAsync(window, () => app.FindAll().First(b => b is { DataContext: TrustedCertificateRow, IsVisible: true }));
window.Width = width;
certificate.ForgetCommand.Execute(null);
Assert.Count(1, settings.Certificates);
Assert.True(shell.Server.IsConnected, "the session on the certificate stays");
Assert.True(ServerSession.ForgetRequest(certificate.FullFingerprint).IsDestructive);
});
[Test]
public Task ImportAnalysisAndFormatsAreRealSettings() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
var settings = shell.Settings;
// The open archive's own thumbnail size (archive.json) is what Settings › Archive shows.
var archive = Assert.NotNull(await Chronos.App.Archiving.CurrentArchive.FindAsync(shell.Services.Database!, shell.Services.Settings.LastArchivePath));
// The sample shows a display path as its archive folder; the rows edit only the archive at the archive folder.
shell.Services.Settings.LastArchivePath = archive.RootPath;
var manifestPath = new Chronos.Core.Archiving.ArchivePaths(archive.RootPath).ManifestPath;
var manifest = Chronos.Core.Archiving.ManifestStore.ReadArchive(manifestPath);
Chronos.Core.Archiving.ManifestStore.WriteArchive(manifestPath, manifest with { ThumbnailPolicy = new Chronos.Core.Archiving.ThumbnailPolicy { LongEdge = 240 } });
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Archive;
await WaitAsync(() => settings.SelectedThumbnailSize.Value == 240, "the archive's thumbnail size is shown");
await app.ExpectAsync("settings-archive");
settings.SelectedThumbnailSize = settings.ThumbnailSizes.Single(s => s.Value == 480);
await WaitAsync(() => Chronos.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ThumbnailPolicy.LongEdge == 480, "written into archive.json");
Assert.Equal(480, shell.Services.Settings.ThumbnailLongEdge);
// A proxy size the admin panel set (3840 is none of the presets) is shown as it is, not as 1920.
manifest = Chronos.Core.Archiving.ManifestStore.ReadArchive(manifestPath);
Chronos.Core.Archiving.ManifestStore.WriteArchive(manifestPath, manifest with { ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 3840 } });
shell.Navigate(SectionKey.Library);
shell.Navigate(SectionKey.Settings);
await WaitAsync(() => settings.SelectedProxySize.Value == 3840, "the archive's own proxy size is shown");
Assert.Equal("3840", settings.SelectedProxySize.Label);
Assert.SequenceEqual([1280, 1920, 2560, 3840, Chronos.Core.Archiving.ProxyPolicy.FullSize, Chronos.Core.Archiving.ProxyPolicy.Disabled],
settings.ProxySizes.Select(s => s.Value));
// Reset section on Archive changes the archive everyone shares: it asks first, and a "no" leaves archive.json alone.
settings.ResetSectionCommand.Execute(null);
Assert.Equal((480, 3840), (Chronos.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ThumbnailPolicy.LongEdge,
Chronos.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ProxyPolicy.LongEdge));
Assert.Equal(480, settings.SelectedThumbnailSize.Value);
// Import: the defaults of new cards.
settings.Page = SettingsPage.Import;
await app.ExpectAsync("settings-import");
settings.SessionGap.Text = "90";
Assert.True(settings.SessionGap.Commit());
settings.IsFormatCard = true;
Assert.Equal((90, Chronos.Data.Archiving.AfterImport.FormatCard), (shell.Services.Settings.ImportSessionGapMinutes, shell.Services.Settings.ImportAfter));
Assert.True(settings.CanResetSection);
settings.ResetSectionCommand.Execute(null);
Assert.Equal(("45", true), (settings.SessionGap.Text, settings.IsKeepCard));
// Analysis: thresholds in the language's own decimals, checked against their range.
settings.Page = SettingsPage.Analysis;
await app.ExpectAsync("settings-analysis");
Assert.Equal(6.25.ToString("0.##", System.Globalization.CultureInfo.CurrentCulture), settings.NightBrightness.Text);
settings.NightBrightness.Text = "80";
Assert.True(settings.NightBrightness.HasErrors, "beyond 50 %");
settings.NightBrightness.Revert();
settings.DeepAnalysisAfterScan = true;
Assert.True(shell.Services.Settings.DeepAnalysisAfterScan);
// Formats: the tier of every format and a notice with Install per missing extension.
settings.Page = SettingsPage.Formats;
await WaitAsync(() => settings.Formats.Count > 0 && !settings.IsDetectingFormats, "formats listed");
await app.ExpectAsync("settings-formats");
Assert.Count(3, settings.MissingExtensions);
var installs = app.FindAll().Where(b => b.IsVisible && b.Content as string == Loc.L("Settings.Formats.Install")).ToList();
Assert.Count(3, installs);
Assert.True(installs.All(b => AutomationProperties.GetName(b).StartsWith(Loc.L("Settings.Formats.InstallName", string.Empty), StringComparison.Ordinal)), "named after the extension");
Assert.Contains(settings.Formats, f => f.Row.Tier == Chronos.Core.Imaging.DecodeTier.Native);
Assert.False(settings.CanResetSection, "Formats only shows this PC");
installs[0].Command.Execute(null);
});
[Test]
public Task ArchiveRowsEditOnlyTheArchiveAtTheFolderAndKeepEditsMadeWhileItOpens() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
var settings = shell.Settings;
var db = shell.Services.Database!;
var archive = Assert.NotNull(await Chronos.App.Archiving.CurrentArchive.FindAsync(db, null));
var manifestPath = new Chronos.Core.Archiving.ArchivePaths(archive.RootPath).ManifestPath;
static Chronos.Core.Archiving.ArchiveManifest Read(string path) => Chronos.Core.Archiving.ManifestStore.ReadArchive(path);
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Archive;
// No archive folder: a template edit is this PC's default only, never the first archive of the index. The edit is
// made once the rows follow the empty folder, so it cannot wait for anything that would hide a write.
settings.ArchiveRoot.Text = string.Empty;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
settings.FolderTemplate.Text = "{camera}/{date}";
Assert.True(settings.FolderTemplate.Commit());
Assert.Equal("{camera}/{date}", shell.Services.Settings.FolderTemplate);
// The archive's folder is chosen and a template edited at once, while that archive is still opening: the edit
// reaches its archive.json instead of being undone when it opens, and the row shows it.
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
settings.FileTemplate.Text = "{date}_{n:0000}";
Assert.True(settings.FileTemplate.Commit());
await WaitAsync(() => Read(manifestPath).LayoutTemplates.File == "{date}_{n:0000}", "the edit reached the archive that was opening");
await WaitAsync(() => settings.FileTemplate.Text == "{date}_{n:0000}" && shell.Services.Settings.FileTemplate == "{date}_{n:0000}", "the row shows it");
Assert.NotEqual("{camera}/{date}", Read(manifestPath).LayoutTemplates.Folder);
// An edit made before a second folder change, while the first folder's archive is still opening, goes to that
// archive: never to the archive at the folder chosen after it.
var otherRoot = System.IO.Path.Combine(shell.Services.Environment.DataDirectory, "other-archive");
await shell.Services.Archives!.CreateAsync(otherRoot, "Other");
var otherManifestPath = new Chronos.Core.Archiving.ArchivePaths(otherRoot).ManifestPath;
settings.ArchiveRoot.Text = otherRoot;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
settings.FileTemplate.Text = "{date}-{n:0000}";
Assert.True(settings.FileTemplate.Commit());
settings.ArchiveRoot.Text = otherRoot;
Assert.True(settings.ArchiveRoot.Commit());
await WaitAsync(() => Read(manifestPath).LayoutTemplates.File == "{date}-{n:0000}", "the edit reached the archive of the folder it was made for");
// The folder change is done only once the rows show that folder's archive, also when its read overlapped the
// edit written into the first archive: that read waits for the edit and reads again instead of leaving the rows.
await settings.ArchiveRetarget;
Assert.NotEqual("{date}-{n:0000}", Read(otherManifestPath).LayoutTemplates.File);
Assert.Equal(Read(otherManifestPath).LayoutTemplates.File, settings.FileTemplate.Text);
Assert.Equal(Read(otherManifestPath).LayoutTemplates.File, shell.Services.Settings.FileTemplate);
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
// Offline, only archive.json knows the thumbnail size: this PC's stays instead of becoming the default.
Chronos.Core.Archiving.ManifestStore.WriteArchive(manifestPath, Read(manifestPath) with { ThumbnailPolicy = new Chronos.Core.Archiving.ThumbnailPolicy { LongEdge = 480 } });
shell.Navigate(SectionKey.Library);
shell.Navigate(SectionKey.Settings);
await WaitAsync(() => shell.Services.Settings.ThumbnailLongEdge == 480, "the archive's thumbnail size is shown");
var row = Assert.NotNull(await db.Archives.GetAsync(archive.Id));
await db.Archives.UpsertAsync(row with { ProxyLongEdge = 2560 });
System.IO.File.Move(manifestPath, manifestPath + ".away");
shell.Navigate(SectionKey.Library);
shell.Navigate(SectionKey.Settings);
await WaitAsync(() => shell.Services.Settings.ProxyLongEdge == 2560, "the index's proxy size is shown while offline");
Assert.Equal(480, shell.Services.Settings.ThumbnailLongEdge);
Assert.Equal(480, settings.SelectedThumbnailSize.Value);
});
[Test]
public Task AnArchiveRowEditedWhileSettingsReadsTheArchiveIsNotUndoneByThatRead() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
var settings = shell.Settings;
var archive = Assert.NotNull(await Chronos.App.Archiving.CurrentArchive.FindAsync(shell.Services.Database!, null));
var paths = new Chronos.Core.Archiving.ArchivePaths(archive.RootPath);
static Chronos.Core.Archiving.ArchiveManifest Read(string path) => Chronos.Core.Archiving.ManifestStore.ReadArchive(path);
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Archive;
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
var before = Read(paths.ManifestPath).LayoutTemplates.File;
const string edited = "{camera}_{n:00000}";
Assert.NotEqual(edited, before);
Assert.Equal(before, settings.FileTemplate.Text);
// Another PC holds the archive's settings, so the edit waits to be written. Settings is shown again just before
// the edit is committed: its read of archive.json answers meanwhile, with the file from before the edit.
var lease = Assert.NotNull(Chronos.Core.Archiving.LeaseFile.TryAcquire(paths.LocksDirectory, "archive-settings", "other-pc"));
Task reload;
try
{
shell.Navigate(SectionKey.Library);
shell.Navigate(SectionKey.Settings);
reload = settings.ArchiveReload;
Assert.False(reload.IsCompleted, "the read is in flight");
settings.FileTemplate.Text = edited;
Assert.True(settings.FileTemplate.Commit());
await Task.WhenAny(reload, Task.Delay(1500));
Assert.False(reload.IsCompleted, "the read waits for the edit it overlapped");
Assert.Equal(edited, settings.FileTemplate.Text);
Assert.Equal(edited, shell.Services.Settings.FileTemplate);
Assert.Equal(before, Read(paths.ManifestPath).LayoutTemplates.File);
}
finally
{
lease.Dispose();
}
// Once the edit is written, the read is made again and shows it.
await reload.WaitAsync(TimeSpan.FromSeconds(20));
Assert.Equal(edited, Read(paths.ManifestPath).LayoutTemplates.File);
Assert.Equal(edited, settings.FileTemplate.Text);
Assert.Equal(edited, shell.Services.Settings.FileTemplate);
});
[Test]
public Task TheFirstRunDialogKeepsTheKeyboardInside() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Shell.ShowWelcome();
await app.ExpectAsync("welcome");
var welcome = app.FindAll().First(v => v.IsVisible);
var dialog = (FrameworkElement)welcome.Content;
Assert.Equal(KeyboardNavigationMode.Cycle, KeyboardNavigation.GetTabNavigation(dialog));
Assert.Equal(KeyboardNavigationMode.Cycle, KeyboardNavigation.GetControlTabNavigation(dialog));
Assert.Equal(KeyboardNavigationMode.Contained, KeyboardNavigation.GetDirectionalNavigation(dialog));
// It opens with focus on the chosen card (a local archive by default).
var focused = FocusManager.GetFocusedElement(Window.GetWindow(welcome)) as RadioButton;
Assert.NotNull(focused, "a card has focus");
Assert.True(focused.IsChecked == true && welcome.IsAncestorOf(focused), "the chosen card of the dialog has focus");
// The logo is not mirrored in right-to-left languages.
Assert.True(app.FindAll().Where(b => b.IsVisible).All(b => b.FlowDirection == FlowDirection.LeftToRight));
app.Shell.CompleteWelcome();
});
[Test]
public Task AboutIsTheLastSettingsPageAndOffersNothingTwice() => ScreenHost.RunAsync(async () =>
{
// Owner review 2, R5: About left the rail for the end of Settings; Settings alone docks at the bottom of the rail.
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
var settings = shell.Settings;
Assert.SequenceEqual([SectionKey.Settings], shell.BottomSections.Select(s => s.Key));
Assert.Equal(SettingsPage.About, settings.AllPages[^1].Page);
shell.About.SetResult(null);
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.About;
await app.ExpectAsync("settings-about");
Assert.Equal(Loc.L("Settings.Page.About"), settings.PageTitle);
// This copy's identity: nothing to reset.
Assert.False(settings.CanResetSection);
Assert.False(app.FindAll().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "no Reset section on About");
Assert.True(app.FindAll().Any(t => t.IsVisible && t.Text == shell.About.Build), "the build is shown");
var licence = app.FindAll().Single(b => b.IsVisible && ReferenceEquals(b.Command, shell.About.OpenLicenceCommand));
Assert.Equal(Loc.L("Tooltips.About.Licence"), licence.ToolTip);
// English is the source language: no translation notice.
Assert.False(app.FindAll().Any(b => b.IsVisible && ReferenceEquals(b.Command, shell.About.ReviewTranslationCommand)), "no review link in English");
// One place each in Settings: the update check (Updates), the data folder and the diagnostics bundle (Advanced).
// (Rows build their content when first shown: those pages are shown once.)
foreach (var page in (SettingsPage[])[SettingsPage.Updates, SettingsPage.Advanced, SettingsPage.About])
{
settings.Page = page;
app.Window.UpdateLayout();
}
var buttons = app.FindAll();
Assert.Count(1, buttons.Where(b => ReferenceEquals(b.Command, shell.About.CheckCommand)));
Assert.Count(1, buttons.Where(b => ReferenceEquals(b.Command, settings.OpenDataFolderCommand)));
Assert.Count(1, buttons.Where(b => ReferenceEquals(b.Command, settings.ExportDiagnosticsCommand)));
// The search finds About by its rows and Updates by its releases link.
settings.SearchText = Loc.L("About.Build");
Assert.Contains(settings.VisiblePages, p => p.Page == SettingsPage.About);
settings.SearchText = Loc.L("About.Releases");
Assert.Contains(settings.VisiblePages, p => p.Page == SettingsPage.Updates);
settings.SearchText = Loc.L("About.Translation");
Assert.False(settings.VisiblePages.Any(p => p.Page == SettingsPage.About), "the hidden translation row does not match");
settings.SearchText = string.Empty;
});
[Test]
public Task ARightToLeftLanguageMirrorsEveryWindowAlsoThoseOpenedLater() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var settings = app.Shell.Settings;
app.Shell.About.SetResult(null);
app.Shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.About;
await app.ExpectAsync("settings-about");
var main = Window.GetWindow(app.FindAll().First(v => v.IsVisible));
Assert.Equal(FlowDirection.LeftToRight, main.FlowDirection);
UiLanguage.Apply("ar");
var dialog = new Window
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 320,
Height = 200,
ShowActivated = false,
ShowInTaskbar = false,
};
try
{
Assert.Equal(FlowDirection.RightToLeft, main.FlowDirection);
// Loaded comes with the first render, which can follow an idle tick; class handlers run before this one.
var loaded = new TaskCompletionSource();
dialog.Loaded += (_, _) => loaded.TrySetResult();
dialog.Show();
await loaded.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.Equal(FlowDirection.RightToLeft, dialog.FlowDirection, "a window opened after the switch (a dialog) is mirrored too");
await app.ExpectAsync("settings-about-ar");
// Inside the mirrored window, the logo and the build keep their left-to-right order; the translation notice shows.
var logos = app.FindAll().Where(b => b.IsVisible).ToList();
Assert.NotEmpty(logos);
Assert.True(logos.All(b => b.FlowDirection == FlowDirection.LeftToRight), "the logo is not mirrored");
var build = app.FindAll().First(t => t.IsVisible && t.Text == app.Shell.About.Build);
Assert.Equal(FlowDirection.LeftToRight, build.FlowDirection);
Assert.True(app.FindAll().Any(b => b.IsVisible && ReferenceEquals(b.Command, app.Shell.About.ReviewTranslationCommand)), "Arabic is machine-translated");
// Paths keep their left-to-right order and show whole in their tooltip.
settings.Page = SettingsPage.Advanced;
await app.ExpectAsync("settings-advanced-ar");
var path = Field(app, Loc.L("Settings.Advanced.DataFolder"));
Assert.Equal(FlowDirection.LeftToRight, path.FlowDirection);
Assert.Equal(settings.DataFolder, path.ToolTip);
// The update result is a live region: screen readers hear each new state.
settings.Page = SettingsPage.Updates;
await app.ExpectAsync("settings-updates-ar");
var update = app.FindAll().First(g => g.IsVisible && g.Text == app.Shell.About.UpdateText);
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(update));
Assert.Equal(app.Shell.About.UpdateAnnouncement, AutomationProperties.GetName(update));
}
finally
{
dialog.Close();
UiLanguage.Apply("en");
}
Assert.Equal(FlowDirection.LeftToRight, main.FlowDirection);
});
/// Waits (on the UI thread, letting it run) until holds.
private static async Task WaitAsync(Func condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(20);
while (!condition())
{
Assert.True(DateTime.UtcNow < until, what);
await Task.Delay(50);
}
}
private static TextBox Field(ScreenSmokeTests.SampleApp app, string name) =>
app.FindAll().First(t => t.IsVisible && AutomationProperties.GetName(t) == name);
private static double Middle(FrameworkElement element) =>
element.TranslatePoint(new Point(0, element.ActualHeight / 2), Window.GetWindow(element)).Y;
/// In every shipped language, the button returns lies inside its page's viewport (either reading direction).
private static async Task InsidePageInEveryLanguageAsync(Window window, Func find)
{
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
var button = find();
var page = Ancestor(button);
var (left, right) = Span(page, page.ViewportWidth, window);
var (start, end) = Span(button, button.ActualWidth, window);
Assert.True(start >= left - 0.5 && end <= right + 0.5, $"{language}: '{button.Content}' spans {start:0}–{end:0} px, the page {left:0}–{right:0} px");
}
}
finally
{
UiLanguage.Apply("en");
}
}
/// The left and right edges of the first pixels of an element in window coordinates.
private static (double Left, double Right) Span(FrameworkElement element, double width, Window window)
{
var a = element.TranslatePoint(new Point(0, 0), window).X;
var b = element.TranslatePoint(new Point(width, 0), window).X;
return (Math.Min(a, b), Math.Max(a, b));
}
/// The nearest above .
private static T Ancestor(DependencyObject node)
where T : DependencyObject
{
for (var parent = VisualTreeHelper.GetParent(node); parent is not null; parent = VisualTreeHelper.GetParent(parent))
{
if (parent is T match) return match;
}
throw new InvalidOperationException($"No {typeof(T).Name} above {node}");
}
/// The label of every visible Settings row (the first text of the row template).
private static IEnumerable Labels(ScreenSmokeTests.SampleApp app) =>
app.FindAll().Where(h => h.IsVisible).Select(h => Descendants(h).First());
/// The label's text fits its width on one line, or wraps onto more lines; never trimmed.
private static bool IsWhole(TextBlock label)
{
var probe = new TextBlock { Text = label.Text, FontFamily = label.FontFamily, FontSize = label.FontSize, FontWeight = label.FontWeight };
probe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
return label.TextTrimming == TextTrimming.None || probe.DesiredSize.Width <= label.ActualWidth + 0.5;
}
private static IEnumerable Descendants(DependencyObject node)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) yield return match;
foreach (var nested in Descendants(child)) yield return nested;
}
}
}