merge: integration branch claude/keen-knuth-uhxv8w into the Library workstream

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-06 07:49:48 +00:00
commit 992834988d
289 files changed
+18046 -731

No files matched your search

@@ -125,6 +125,7 @@ public sealed class EditorSmokeTests
editor.RedoCommand.Execute(null);
Assert.Equal(0.5, editor.Session.Project.Exposure.ExposureOffsetEv);
await editor.Session.FlushAsync();
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.NotNull(editor.Plan, "the export is planned");
}
finally
@@ -53,6 +53,49 @@ public sealed class CardPoolTests
Assert.Equal(@"D:\Shoots\2026", pool[4].Root);
}
[Test]
public void ARememberedCardStaysNewUntilItHasANickname()
{
var unnamed = Known(GoPro, "GoPro 12", DateTimeOffset.UtcNow) with { Nickname = null };
var source = CardPool.Build([GoPro], [unnamed], null).Single();
Assert.NotNull(source.Card, "the first plan remembered it");
Assert.False(source.IsKnown);
Assert.Equal("New card", source.StateText);
Assert.Equal("GOPRO", source.Title);
var named = CardPool.Build([GoPro], [unnamed with { Nickname = "GoPro 12" }], null).Single();
Assert.True(named.IsKnown);
Assert.Equal("Known card", named.StateText);
}
[Test]
public void TheEntryTooltipCarriesTheStateAndTheWholeSubtitle()
{
var pool = CardPool.Build([CardA, Usb], [Known(CardA, "EOS R5 · card A", DateTimeOffset.UtcNow)], @"D:\Shoots\2026");
Assert.Equal("Known card · 128 GB · 96.2 GB used", pool[0].ToolTip);
Assert.Equal("no DCIM · 1.8 TB free", pool[1].ToolTip);
Assert.Equal(@"Folder · D:\Shoots\2026", pool[2].ToolTip);
}
[Test]
public void PathsAndSerialsStayLeftToRightInARightToLeftLanguage()
{
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
var pool = CardPool.Build([Usb with { Label = string.Empty }, CardA], [], @"D:\Shoots\");
Assert.Equal("\u202AG:\\\u202C", pool[1].Title, "a drive root keeps its separator at its end");
Assert.Equal("\u202AD:\\Shoots\\\u202C", pool[2].Title);
Assert.Equal("\u202AD:\\Shoots\\\u202C", pool[2].Subtitle);
Assert.Contains("\u202A3F2A-9C11\u202C", pool[0].IdentityText);
Assert.Equal("EOS_DIGITAL", pool[0].Title, "a label is left to bidi");
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[Test]
public void AKnownCardWithoutDcimIsStillACard()
{
@@ -66,6 +66,10 @@ public sealed class ImportChoicesTests
Assert.True((a with { FileTemplate = "{name}" }).NeedsNewPlan(a));
Assert.True((a with { Destination = ImportDestinationKind.Folder }).NeedsNewPlan(a));
Assert.True((a with { IncludeSubfolders = false }).NeedsNewPlan(a));
Assert.False((a with { FolderPath = @"D:\Shoots" }).NeedsNewPlan(a), "the folder path is not used for the archive");
var folder = a with { Destination = ImportDestinationKind.Folder, FolderPath = @"D:\Shoots" };
Assert.True((folder with { FolderPath = @"E:\Backup" }).NeedsNewPlan(folder));
Assert.False((folder with { FolderPath = @"d:\shoots" }).NeedsNewPlan(folder), "paths compare without case");
Assert.False(a.TitlesChangeNames);
Assert.True((a with { FolderTemplate = "{year}/{Title:upper}" }).TitlesChangeNames);
}
@@ -0,0 +1,41 @@
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using Titano.App.Import;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Protocol;
using Titano.Protocol.Client;
using Titano.Testing;
namespace Titano.App.Tests.Import;
/// <summary>A stopped import or plan says what happened in one localized sentence, never the exception's raw text.</summary>
public sealed class ImportFailuresTests
{
public ImportFailuresTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void AnImportFailureIsOneSentenceByCause()
{
const string Card = "EOS R5 · card A";
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Import(new ImportSourceUnavailableException(@"C:\Users\me\AppData\Local\Temp\card\"), Card));
Assert.Equal("The destination is full.", ImportFailures.Import(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), Card));
Assert.Equal("Titano may not write to the destination.", ImportFailures.Import(new UnauthorizedAccessException(@"Access to D:\Shoots is denied."), Card));
Assert.Equal("The server did not accept the photos.", ImportFailures.Import(new HttpRequestException("No such host is known."), Card));
Assert.Equal("The server did not accept the photos.",
ImportFailures.Import(new TitanoApiException(HttpStatusCode.InsufficientStorage, new ApiError("quota", "Quota exceeded", null)), Card));
Assert.Equal("The import stopped before the end.", ImportFailures.Import(new InvalidDataException("Bad sidecar. Second sentence."), Card));
}
[Test]
public void APlanningFailureNamesTheSource()
{
const string Folder = @"D:\Shoots";
Assert.Equal(@"D:\Shoots is no longer available.", ImportFailures.Plan(new DirectoryNotFoundException(@"Could not find a part of the path 'D:\Shoots\DCIM'."), Folder));
Assert.Equal(@"D:\Shoots could not be read.", ImportFailures.Plan(new UnauthorizedAccessException("Access denied."), Folder));
Assert.Equal(@"D:\Shoots could not be read.", ImportFailures.Plan(new IOException("The device is not ready."), Folder));
Assert.Equal("The import could not be planned.", ImportFailures.Plan(new InvalidOperationException("Sequence contains no elements"), Folder));
}
}
@@ -35,6 +35,7 @@ public sealed class ImportPlansTests
Assert.True(totals.HasEnoughSpace);
Assert.Equal(TimeSpan.FromSeconds(3), totals.Estimate);
Assert.Equal("3 sessions · 7 photos · 120 MB · about 3 s", totals.Text);
Assert.Equal("3 sessions · 7 photos · 120 MB", totals.SummaryText);
Assert.Equal("1 duplicate", totals.DuplicatesText);
Assert.Equal("Import 5 photos", totals.ImportText);
Assert.Equal("80 MB free after import", totals.SpaceText);
@@ -124,6 +125,39 @@ public sealed class ImportPlansTests
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, folder.Rows[1].Destination);
}
[Test]
public void ShowPlanShowsNamesUnderTheirSessionFolder()
{
var plan = ThreeSessions();
var details = ImportPlans.Details(plan, ImportDestinationKind.Archive, verify: true);
var session = details.Rows[0];
Assert.True(session.SourceText.StartsWith("Session 1 · ", StringComparison.Ordinal), session.SourceText);
Assert.Equal("2026/2026-09-28 Canon EOS R5/originals", session.DestinationText);
var file = details.Rows[2];
Assert.Equal("IMG_0002.CR2", file.SourceText);
Assert.Equal(plan.Sessions[0].Items[1].FileName, file.DestinationText);
Assert.Equal("DCIM/100CANON/IMG_0002.CR2", file.Source, "the full path stays for the tooltip");
Assert.Equal("Split at IMG_0002.CR2", file.SplitName);
}
[Test]
public void ARightToLeftLanguageReadsTheSessionTimesWithItsOwnArrow()
{
var plan = ThreeSessions();
Assert.Contains("→", ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText);
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
var time = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText;
Assert.Contains("←", time);
Assert.False(time.Contains('→'), "a right-to-left reader would see the arrow point back to the start");
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[Test]
public void TheNamePreviewShowsTheFirstThreeCopiedFiles()
{
@@ -1,8 +1,15 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using Titano.App.Import;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Testing;
using Titano.Ui.Controls;
@@ -10,8 +17,9 @@ namespace Titano.App.Tests.Import;
/// <summary>
/// Every Import state of <c>--capture</c> (<see cref="ImportScenes"/>) on the simulated cards, rendered in both themes
/// in the real main window, with the figures and gates each state must show — and the buttons really enabled, not
/// only their commands.
/// in the real main window at the 1200 × 788 capture size, with the figures and gates each state must show — and the
/// buttons really enabled, named for screen readers, nothing that matters cut off, and paths, numbers and times
/// readable in a right-to-left language.
/// </summary>
[WindowsOnly]
[Serial]
@@ -26,7 +34,9 @@ public sealed class ImportScreenSmokeTests
var import = app.Shell.Import;
await ShowAsync(app, "inserted");
await UseCaptureSizeAsync(app);
Assert.NotEmpty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts), "the insertion toast");
Assert.False(import.FolderPath.HasErrors, "the folder path is not checked while Archive is the destination");
await app.ExpectAsync<ImportView>("import-inserted");
await ShowAsync(app, "plan");
@@ -40,11 +50,29 @@ public sealed class ImportScreenSmokeTests
await app.ExpectAsync<ImportView>("import-plan");
Assert.True(ButtonFor(app, import.StartCommand).IsEnabled, "the Import button is enabled once the plan is ready");
Assert.True(ButtonFor(app, import.Sessions[1].MergeCommand).IsEnabled, "a session can merge into the one before");
Assert.False(Validation.GetHasError(Named<TextBox>(app, "FolderPathBox")), "the folder path is not checked while Archive is the destination");
foreach (var session in import.Sessions)
Assert.True(Fits(TextFor(app, session.Row.TimeText)), $"the session time '{session.Row.TimeText}' is cut at 1200 px");
foreach (var item in DeviceItems(app))
{
Assert.NotNull(item.FocusVisualStyle, "a device shows keyboard focus");
Assert.Equal(((ImportSource)item.DataContext).ToolTip, item.ToolTip as string);
}
AssertEveryButtonIsNamed(app);
await AssertFourDigitsFitAsync(app, import);
await AssertFolderPathIsCheckedOnlyForFolderAsync(app, import);
await ShowAsync(app, "showplan");
Assert.True(import.IsDetailsOpen);
Assert.Equal(50 + 3, import.Details!.Rows.Count);
await app.ExpectAsync<ImportView>("import-showplan");
var file = import.Details.Rows[2];
Assert.True(Fits(TextFor(app, file.SourceText)), "a file's name on the card is shown whole");
Assert.True(Fits(TextFor(app, file.DestinationText)), "a file's new name is shown whole");
Assert.True(Fits(TextFor(app, import.Details.Rows[0].SourceText)), "a session heading is shown whole");
Assert.Within(Left(app, TextFor(app, Loc.L("Import.Details.Column.Action"))), 0, Left(app, TextFor(app, file.ActionText)), 0, 2,
"the Action header lines up with its cells");
AssertEveryButtonIsNamed(app);
await ShowAsync(app, "running");
Assert.True(import.IsRunning);
@@ -52,11 +80,27 @@ public sealed class ImportScreenSmokeTests
Assert.False(import.Sessions[0].IsEditable, "titles lock while copying");
await app.ExpectAsync<ImportView>("import-running");
Assert.True(ButtonFor(app, import.CancelCommand).IsEnabled, "Cancel is enabled while copying");
foreach (var item in DeviceItems(app))
{
Assert.False(item.IsEnabled, "the source of a running import stays selected");
Assert.Equal(Loc.L("Import.Blocked.Copying"), item.ToolTip as string);
}
Assert.Equal(0.4, TextFor(app, Loc.L("Import.Scan.Frames")).Opacity, "unit words dim with their field");
var progress = Named<TextBlock>(app, "ProgressLine");
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(progress));
Assert.Same(progress, AutomationProperties.GetLabeledBy(app.FindAll<ProgressBar>().First(p => p.IsVisible && IsInImport(p))));
await ShowAsync(app, "failed");
Assert.True(import.IsFailed);
Assert.Equal("EOS R5 · card A is no longer available.", import.ErrorText);
Assert.Contains(SampleCards.Card(app.Services.Environment.DataDirectory).Root, import.FailureToolTip);
await app.ExpectAsync<ImportView>("import-failed");
Assert.True(ButtonFor(app, import.RetryCommand).IsEnabled, "Retry is enabled after a failure");
var failure = Named<TextBlock>(app, "FailureLine");
Assert.Equal(AutomationLiveSetting.Assertive, AutomationProperties.GetLiveSetting(failure));
Assert.True(Fits(failure), "the failure sentence is shown whole");
Assert.Null(app.FindAll<Button>().FirstOrDefault(b => b.IsVisible && ReferenceEquals(b.Command, app.Shell.NavigateCommand) && IsInImport(b)),
"an error offers one action");
await ShowAsync(app, "done");
Assert.True(import.IsDone);
@@ -67,14 +111,55 @@ public sealed class ImportScreenSmokeTests
Assert.Equal(49, result.Actions.DeleteCount);
Assert.False(result.Actions.CanFormat, "a photo touched since the import keeps the card from being formatted");
Assert.Empty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
Assert.False(import.IsFormEnabled, "a finished import keeps its form until New import");
Assert.False(import.TotalsText.Contains(Loc.L("Import.Plan.About", string.Empty).Trim(), StringComparison.Ordinal), "no estimate after the import");
Assert.Equal(string.Empty, import.SpaceText);
await app.ExpectAsync<ImportView>("import-done");
Assert.True(ButtonFor(app, result.DeleteCommand).IsEnabled, "the Delete button follows the dry run");
AssertEveryButtonIsNamed(app);
await ShowAsync(app, "newcard");
Assert.True(import.IsNicknameOpen, "a new card asks for its nickname");
Assert.Equal("SONY", import.SourceTitle);
Assert.False(import.SelectedSource!.IsKnown, "a card without a nickname is still new, though its plan remembered it");
Assert.NotEmpty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
await app.ExpectAsync<ImportView>("import-newcard");
AssertEveryButtonIsNamed(app);
});
[Test]
public Task PathsNumbersAndTimesStayReadableRightToLeft() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
UiLanguage.Apply("ar");
try
{
var import = app.Shell.Import;
await ShowAsync(app, "plan");
Assert.Equal(ImportPhase.Ready, import.Phase);
Assert.Equal(FlowDirection.RightToLeft, WindowOf(app).FlowDirection);
Assert.Equal(FlowDirection.LeftToRight, Named<TextBox>(app, "FolderPathBox").FlowDirection);
Assert.Equal(FlowDirection.LeftToRight, Named<TextBox>(app, "GapBox").FlowDirection);
foreach (var template in app.FindAll<TextBox>().Where(t => EditBehavior.GetField(t) is { } f && (f == import.FolderTemplate || f == import.FileTemplate)))
Assert.Equal(FlowDirection.LeftToRight, template.FlowDirection, "name templates read left to right");
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, import.NamePreview).FlowDirection, "the name preview reads left to right");
var size = TextFor(app, import.Sessions[0].Row.SizeText);
Assert.Equal(FlowDirection.LeftToRight, size.FlowDirection);
Assert.Equal(TextAlignment.Right, size.TextAlignment, "numbers stay right-aligned");
Assert.Contains("←", import.Sessions[0].Row.TimeText);
await app.ExpectAsync<ImportView>("import-plan-ar");
await ShowAsync(app, "showplan");
var file = import.Details!.Rows[2];
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, file.SourceText).FlowDirection);
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, file.DestinationText).FlowDirection);
await app.ExpectAsync<ImportView>("import-showplan-ar");
}
finally
{
UiLanguage.Apply("en");
}
});
/// <summary>As <c>--capture</c> does: toasts of the previous state go, those of an insertion state stay.</summary>
@@ -83,6 +168,7 @@ public sealed class ImportScreenSmokeTests
DismissToasts(app);
await ImportScenes.ShowAsync(app.Shell, state);
if (!ImportScenes.ShowsToast(state)) DismissToasts(app);
await SettleAsync(app);
}
private static void DismissToasts(ScreenSmokeTests.SampleApp app)
@@ -93,6 +179,135 @@ public sealed class ImportScreenSmokeTests
}
}
/// <summary>The size CI captures at (and the window's minimum width): nothing may be cut there.</summary>
private static async Task UseCaptureSizeAsync(ScreenSmokeTests.SampleApp app)
{
var window = WindowOf(app);
window.Width = 1200;
window.Height = 788;
await SettleAsync(app);
}
private static async Task SettleAsync(ScreenSmokeTests.SampleApp app)
{
var window = WindowOf(app);
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
private static async Task WaitUntilAsync(ScreenSmokeTests.SampleApp app, Func<bool> condition, string what)
{
for (var i = 0; i < 200 && !condition(); i++) await Task.Delay(25);
Assert.True(condition(), what);
await SettleAsync(app);
}
/// <summary>The empty folder path is fine for the archive; choosing Folder makes it invalid and offers "Choose folder".</summary>
private static async Task AssertFolderPathIsCheckedOnlyForFolderAsync(ScreenSmokeTests.SampleApp app, ImportViewModel import)
{
var box = Named<TextBox>(app, "FolderPathBox");
import.IsFolderDestination = true;
await WaitUntilAsync(app, () => import.Phase == ImportPhase.NoSource, "the plan stops without a folder");
Assert.True(Validation.GetHasError(box), "an empty path is an error once Folder is chosen");
Assert.True(import.HasStatusAction);
Assert.Equal(Loc.L("Import.Destination.Choose"), import.StatusActionText);
Assert.True(Named<Button>(app, "StatusActionButton").IsVisible, "the status sentence comes with its action");
import.IsArchiveDestination = true;
await WaitUntilAsync(app, () => import.Phase == ImportPhase.Ready, "the archive plan is back");
Assert.False(Validation.GetHasError(box));
Assert.Equal("Harbour sunset", import.Plan!.Sessions[^1].Title, "typed titles survive the round trip");
}
/// <summary>The 56 px gap box shows its largest value, 1440, whole.</summary>
private static async Task AssertFourDigitsFitAsync(ScreenSmokeTests.SampleApp app, ImportViewModel import)
{
import.GapMinutes.Text = "1440";
await SettleAsync(app);
var host = Descendants(Named<TextBox>(app, "GapBox")).OfType<ScrollViewer>().First();
Assert.LessOrEqual(host.ExtentWidth, host.ViewportWidth + 1, "1440 fits the gap box");
import.GapMinutes.Revert();
}
/// <summary>Every button, check box and radio button of the screen has a name screen readers can announce.</summary>
private static void AssertEveryButtonIsNamed(ScreenSmokeTests.SampleApp app)
{
foreach (var button in app.FindAll<ButtonBase>().Where(b => b.IsVisible && b.Focusable && IsInImport(b)))
{
var name = AutomationProperties.GetName(button);
if (string.IsNullOrEmpty(name)) name = button.Content as string;
Assert.False(string.IsNullOrWhiteSpace(name), $"{button.GetType().Name} '{button.Name}' bound to {button.Command} has no accessible name");
}
}
private static Window WindowOf(ScreenSmokeTests.SampleApp app) => Window.GetWindow(app.FindAll<FrameworkElement>().First())!;
private static ImportView View(ScreenSmokeTests.SampleApp app) => app.FindAll<ImportView>().First(v => v.IsVisible);
private static bool IsInImport(DependencyObject element) => FindAncestor<ImportView>(element) is not null;
private static T? FindAncestor<T>(DependencyObject element)
where T : DependencyObject
{
for (var node = VisualTreeHelper.GetParent(element); node is not null; node = VisualTreeHelper.GetParent(node))
{
if (node is T match) return match;
}
return null;
}
private static IEnumerable<DependencyObject> Descendants(DependencyObject root)
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
yield return child;
foreach (var below in Descendants(child)) yield return below;
}
}
private static T Named<T>(ScreenSmokeTests.SampleApp app, string name)
where T : FrameworkElement =>
Assert.NotNull(app.FindAll<T>().FirstOrDefault(e => e.Name == name), $"{typeof(T).Name} {name}");
private static TextBlock TextFor(ScreenSmokeTests.SampleApp app, string text) =>
Assert.NotNull(app.FindAll<TextBlock>().FirstOrDefault(t => t.IsVisible && t.Text == text && IsInImport(t)), $"a visible text '{text}'");
private static IEnumerable<ListBoxItem> DeviceItems(ScreenSmokeTests.SampleApp app) =>
app.FindAll<ListBoxItem>().Where(i => i.IsVisible && i.DataContext is ImportSource);
/// <summary>
/// The text is shown whole: a copy with the same font, numerals and padding, measured by the same layout engine,
/// needs no more room than the layout gave the shown one (a formatted-text estimate differs by a few pixels).
/// </summary>
private static bool Fits(TextBlock text)
{
var probe = new TextBlock
{
Text = text.Text,
FontFamily = text.FontFamily,
FontSize = text.FontSize,
FontStyle = text.FontStyle,
FontWeight = text.FontWeight,
FontStretch = text.FontStretch,
FlowDirection = text.FlowDirection,
Language = text.Language,
Padding = text.Padding,
TextWrapping = text.TextWrapping,
};
System.Windows.Documents.Typography.SetNumeralAlignment(probe, System.Windows.Documents.Typography.GetNumeralAlignment(text));
TextOptions.SetTextFormattingMode(probe, TextOptions.GetTextFormattingMode(text));
if (text.TextWrapping != TextWrapping.NoWrap)
{
probe.Measure(new Size(text.ActualWidth, double.PositiveInfinity));
return probe.DesiredSize.Height <= text.ActualHeight + 0.5;
}
probe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
return probe.DesiredSize.Width <= text.ActualWidth + 1;
}
private static double Left(ScreenSmokeTests.SampleApp app, FrameworkElement element) => element.TranslatePoint(new Point(0, 0), View(app)).X;
private static Button ButtonFor(ScreenSmokeTests.SampleApp app, ICommand command) =>
Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => ReferenceEquals(b.Command, command) && b.IsVisible), "a visible button bound to the command");
}
@@ -167,6 +167,31 @@ public sealed class JobListModelTests
Assert.Equal("done · 3:00", JobText.State(done));
}
[Test]
public void TheWorkersReadoutCountsOnlyJobsOfThisPc()
{
var model = new JobListModel();
model.Apply(Job(JobState.Running, started: -1) with { NodeId = "STUDIO#0" });
model.Apply(Job(JobState.Running, started: -2) with { NodeId = "studio#3" });
model.Apply(Job(JobState.Running, started: -3) with { NodeId = "render-box#0" });
model.Apply(Job(JobState.Running, started: -4));
model.Apply(Job(JobState.Done, started: -9, finished: -8) with { NodeId = "studio#1" });
Assert.Equal(4, model.RunningCount);
Assert.Equal(2, model.RunningOn("studio"));
Assert.True(JobText.IsLocal("studio#2", "STUDIO"));
Assert.False(JobText.IsLocal("studio-2", "studio"));
Assert.False(JobText.IsLocal(null, "studio"));
}
[Test]
public void RowsAreNamedByKindAndTarget()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Equal("Render · Harbour sunset", JobText.Name(Job(JobState.Running, kind: JobKind.Render, label: "Harbour sunset")));
Assert.Equal("Proxies", JobText.Name(Job(JobState.Queued)));
}
private static Job Job(JobState state, int created = 0, int? started = null, int? finished = null, JobPriority priority = JobPriority.Normal,
JobKind kind = JobKind.Proxies, string? label = null, long done = 0, long total = 0) => new()
{
@@ -0,0 +1,90 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Titano.App.Jobs;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Testing;
using Titano.Ui.Controls;
namespace Titano.App.Tests.Jobs;
/// <summary>The Jobs screen on the capture sample: keyboard reach, names for screen readers, counts and the table's columns.</summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class JobsScreenSmokeTests
{
[Test]
public Task RowsAreReachableNamedAndLinedUpWithTheHeader() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
await shell.Jobs.ReloadAsync();
shell.Navigate(SectionKey.Jobs);
await app.ExpectAsync<JobsView>("jobs");
var jobs = shell.Jobs;
// The rail badge, the status strip and the Running chip count the same jobs.
var running = jobs.Chips.Single(c => c.Filter == JobFilter.Running).Count;
Assert.Greater(running, 0);
Assert.Equal(running, jobs.Badge);
Assert.Equal(Loc.Plural("Shell.Status.Jobs", running), shell.JobsText);
// The capture engine starts no workers: there is no "Workers n / 0" to show.
Assert.False(jobs.HasWorkers);
// Tab reaches every row button: the rows take no focus, the list passes Tab on to their content.
var list = app.FindAll<ListBox>().Single(l => l.Name == "JobList");
Assert.Equal(KeyboardNavigationMode.Continue, KeyboardNavigation.GetTabNavigation(list));
var items = app.FindAll<ListBoxItem>().Where(i => i.DataContext is JobRowViewModel && i.IsVisible).ToList();
Assert.True(items.Count > 3, "several rows are on screen");
foreach (var item in items)
{
var row = (JobRowViewModel)item.DataContext;
// A row reads as its job and state; its buttons and its log toggle name the job.
Assert.Equal(row.AccessibleName, AutomationProperties.GetName(item));
Assert.Equal(row.StateText, AutomationProperties.GetItemStatus(item));
var buttons = Descendants<Button>(item).Where(b => b.IsVisible).ToList();
Assert.True(buttons.All(b => b.Focusable && b.IsTabStop), "every row button is a tab stop");
Assert.True(buttons.All(b => AutomationProperties.GetName(b).Contains(row.AccessibleName, StringComparison.Ordinal)), $"buttons of {row.AccessibleName} name it");
var state = Descendants<StatusGlyph>(item).Single();
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(state));
// Right to left: numbers stay right-aligned in both reading directions.
var percent = Descendants<TextBlock>(item).First(t => t.Text == row.PercentText);
Assert.True(percent.FlowDirection == FlowDirection.LeftToRight && percent.TextAlignment == TextAlignment.Right, "the percentage stays right-aligned");
}
// Header and rows share their columns: same padding, one actions column for all, the scroll-bar gutter kept.
var rows = items.Select(i => (Row: (JobRowViewModel)i.DataContext, Item: i)).ToList();
var kindHeader = Text(app, Loc.L("Jobs.Column.Kind"));
var stateHeader = Text(app, Loc.L("Jobs.Column.State"));
foreach (var (row, item) in rows)
{
Assert.Approximately(Left(kindHeader), Left(Descendants<TextBlock>(item).First(t => t.Text == row.Kind)), 1.5, $"Kind of {row.AccessibleName}");
Assert.Approximately(Left(stateHeader), Left(Descendants<StatusGlyph>(item).Single()), 1.5, $"State of {row.AccessibleName}");
}
var actionColumns = rows.Select(r => Left(Descendants<ItemsControl>(r.Item).Last())).ToList();
Assert.True(actionColumns.Max() - actionColumns.Min() < 1, "the actions column starts at the same x in every row");
});
private static TextBlock Text(ScreenSmokeTests.SampleApp app, string text) => app.FindAll<TextBlock>().First(t => t.Text == text && t.IsVisible);
/// <summary>The left edge of an element in window coordinates.</summary>
private static double Left(FrameworkElement element) => element.TranslatePoint(new Point(0, 0), Window.GetWindow(element)).X;
private static IEnumerable<T> Descendants<T>(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<T>(child)) yield return nested;
}
}
}
@@ -1,3 +1,5 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using Titano.App.Infrastructure;
@@ -82,6 +84,36 @@ public sealed class ServerScreenSmokeTests
Assert.True(rowButtons.Select(b => b.DataContext).OfType<SyncRowAction>().Count() > 3, "buttons of several rows are on screen");
Assert.True(rowButtons.All(b => b.Focusable && b.IsTabStop), "every row button is a tab stop");
// Screen readers: a row reads as its sequence and state, each of the many "Upload" buttons names its sequence.
foreach (var item in app.FindAll<ListBoxItem>().Where(i => i.DataContext is SyncRow && i.IsVisible))
{
var row = (SyncRow)item.DataContext;
Assert.Equal(row.Title, AutomationProperties.GetName(item));
Assert.Equal(row.StateText, AutomationProperties.GetItemStatus(item));
}
Assert.True(rowButtons.All(b => AutomationProperties.GetName(b) == ((SyncRowAction)b.DataContext).AccessibleName), "row buttons carry their row's name");
Assert.Equal(Loc.L("Server.Sync.ActionFor", Loc.L("Server.Sync.Action.Upload"), "Clouds over the Langhe"),
Row(table, "Clouds over the Langhe").Actions.Single().AccessibleName);
// The filters are a radio group: the chosen one is checked, so its state reaches screen readers.
var chips = app.FindAll<RadioButton>().Where(r => r.DataContext is SyncFilterChip).ToList();
Assert.Count(Enum.GetValues<SyncFilter>().Length, chips);
Assert.True(chips.All(c => c.IsChecked == ((SyncFilterChip)c.DataContext).IsSelected), "the checked chip is the chosen filter");
// While connected the address is read-only text (selectable, not dimmed), kept left to right; status changes are announced.
var address = app.FindAll<TextBox>().Single(t => t.Name == "AddressBox");
Assert.True(address.IsEnabled && address.IsReadOnly, "the connected address is read-only, not disabled");
Assert.Equal(FlowDirection.LeftToRight, address.FlowDirection);
var known = app.FindAll<Button>().Single(b => b.Name == "KnownButton");
Assert.False(string.IsNullOrEmpty(AutomationProperties.GetName(known)), "the icon-only button has a name");
Assert.True(ToolTipService.GetShowOnDisabled(known), "a disabled ▾ still says why");
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(
app.FindAll<StatusGlyph>().First(g => g.IsVisible && g.Text == shell.Server.StatusText)));
// The web admin admits administrators only: the sample user is an editor.
Assert.False(table.CanOpenAdmin);
Assert.False(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Server.Sync.OpenAdmin") && b.IsVisible), "no admin link for an editor");
// Transfers in every state: the rows show what moves and offer Pause or Resume.
await app.Sample.FillSyncAsync();
await table.ReloadAsync();
@@ -104,9 +136,22 @@ public sealed class ServerScreenSmokeTests
Assert.Equal("Holy grail · Monviso", Assert.Contains(table.Rows, _ => true).Title);
Assert.Count(1, table.Rows);
await app.ExpectAsync<ServerView>("server-conflict");
// One row, no scrolling: the header still lines up with the cells (same padding, constant scroll-bar gutter).
var only = table.Rows[0];
Assert.Approximately(Left(Text(app, Loc.L("Server.Sync.Column.Local"))), Left(Text(app, only.LocalText)), 1.5, "This PC column");
Assert.Approximately(Left(Text(app, Loc.L("Server.Sync.Column.State"))),
Left(app.FindAll<StatusGlyph>().First(g => g.DataContext == only && g.IsVisible)), 1.5, "State column");
// No match: one sentence and its one action, which shows every sequence again.
table.SearchText = "nothing like this";
Assert.False(table.HasRows);
Assert.NotNull(table.EmptyText);
Assert.Equal(SyncEmpty.NoMatch, table.Empty);
table.ClearFiltersCommand.Execute(null);
Assert.Equal(string.Empty, table.SearchText);
Assert.True(Chip(table, SyncFilter.All).IsSelected);
Assert.Equal(Chip(table, SyncFilter.All).Count, table.Rows.Count);
// Another language relabels chips and rows at once.
UiLanguage.Apply("it");
@@ -137,12 +182,23 @@ public sealed class ServerScreenSmokeTests
Assert.False(shell.Server.Sync.IsActive);
Assert.False(shell.Server.Sync.HasRows);
Assert.Equal(SyncEmpty.SignedOut, shell.Server.Sync.Empty);
Assert.False(shell.Server.Sync.UploadAllCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected"), shell.Server.Sync.UploadAllToolTip);
shell.Navigate(SectionKey.Server);
await app.ExpectAsync<ServerView>("server-signedout-table");
// Nothing to filter while signed out: chips and search give way to the one action, Connect.
Assert.False(app.FindAll<RadioButton>().Any(r => r.DataContext is SyncFilterChip && r.IsVisible), "no filter chips while signed out");
Assert.False(app.FindAll<TextBox>().Any(t => AutomationProperties.GetName(t) == Loc.L("Server.Sync.Search") && t.IsVisible), "no search while signed out");
Assert.True(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Server.Connect") && b.IsVisible), "the empty table offers Connect");
});
private static TextBlock Text(ScreenSmokeTests.SampleApp app, string text) => app.FindAll<TextBlock>().First(t => t.Text == text && t.IsVisible);
/// <summary>The left edge of an element in window coordinates.</summary>
private static double Left(FrameworkElement element) => element.TranslatePoint(new Point(0, 0), Window.GetWindow(element)).X;
private static SyncFilterChip Chip(SyncTableViewModel table, SyncFilter filter) => table.Chips.Single(c => c.Filter == filter);
private static SyncRow Row(SyncTableViewModel table, string title) => table.Rows.Single(r => r.Title == title);
@@ -153,6 +153,24 @@ public sealed class SyncTextTests
Assert.Equal(0, rows.Count(r => SyncText.Matches(r, SyncFilter.Conflicts, "comet")));
}
[Test]
public void ATransferCountsWhereItsOriginalsAre()
{
var uploadNotOnServer = Entry(SyncStatus.Transferring, transfer: Upload(JobState.Queued)) with { Link = null };
var download = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Download, State = JobState.Running };
var downloadNotHere = Entry(SyncStatus.Transferring, transfer: download) with { Local = null };
var uploadOnBoth = Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running));
Assert.True(SyncText.Matches(uploadNotOnServer, SyncFilter.LocalOnly, string.Empty));
Assert.False(SyncText.Matches(uploadNotOnServer, SyncFilter.Remote, string.Empty));
Assert.True(SyncText.Matches(downloadNotHere, SyncFilter.Remote, string.Empty));
Assert.False(SyncText.Matches(downloadNotHere, SyncFilter.LocalOnly, string.Empty));
// Partly on both sides: neither "only here" nor "only on the server".
Assert.False(SyncText.Matches(uploadOnBoth, SyncFilter.LocalOnly, string.Empty));
Assert.False(SyncText.Matches(uploadOnBoth, SyncFilter.Remote, string.Empty));
Assert.True(SyncText.Matches(uploadOnBoth, SyncFilter.All, string.Empty));
}
private static (StatusKind, string) Kind(SyncEntry entry)
{
var (kind, text, _) = SyncText.State(entry);
@@ -4,6 +4,7 @@ using System.IO;
using Titano.App.Settings;
using Titano.Core.Localization;
using Titano.Core.Naming;
using Titano.Core.Video;
using Titano.Testing;
namespace Titano.App.Tests.Settings;
@@ -132,6 +133,37 @@ public sealed class SettingsLogicTests
Assert.Equal("en", LanguageCatalog.Match(CultureInfo.GetCultureInfo("sw")).Code);
}
[Test]
public void EachEncoderNamesThePresetsItServes()
{
var hevc = new EncoderRow("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc);
var av1 = hevc with { Codec = "AV1", Name = "NVIDIA AV1 Encoder MFT", VideoCodec = VideoCodec.Av1 };
var h264 = new EncoderRow("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264);
var animation = new EncoderRow("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null);
Assert.SequenceEqual(["8K archive", "4K archive", "4K HEVC", "DCI 4K", "Cinema 21:9", "4K 60 fps"], EncoderUse.Presets(hevc));
Assert.Equal("Animated GIF · Animated PNG", EncoderUse.Text(animation));
Assert.Contains("Share 1080p", EncoderUse.Presets(h264));
Assert.Equal("4K AV1", EncoderUse.Text(av1));
}
[Test]
public void ARenderNodeOffersHardwareEncodersOnlyWhenRendersMayUseThem()
{
EncoderRow[] rows =
[
new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc),
new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264),
new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264),
new("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
];
Assert.Equal("HEVC · H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: true)));
Assert.Equal(3, EncoderUse.Node(rows, allowsHardware: true).Count);
Assert.Equal("H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: false)));
Assert.Null(EncoderUse.Codecs([]));
}
[Test]
public void EnumDrivenKeysExistInEveryRequiredLanguage()
{
@@ -0,0 +1,195 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Testing;
namespace Titano.App.Tests.Settings;
/// <summary>
/// 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.
/// </summary>
[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:\TitanoArchive", 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<SettingsView>("settings-general");
Assert.True(app.FindAll<ListBoxItem>().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<SettingsView>("settings-storage");
var window = Window.GetWindow(app.FindAll<SettingsView>().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<Button>().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);
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<SettingsView>("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<SettingsView>("settings-rendering");
Assert.False(app.FindAll<Button>().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<SettingsView>("settings-advanced");
var data = Field(app, Loc.L("Settings.Advanced.DataFolder"));
Assert.Equal(FlowDirection.LeftToRight, data.FlowDirection);
Assert.Equal(settings.DataFolder, data.ToolTip);
// Advanced has nothing to reset: no Reset section there.
Assert.False(settings.CanResetSection);
Assert.False(settings.ResetSectionCommand.CanExecute(null));
Assert.False(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "no Reset section on Advanced");
// 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<SettingsView>("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);
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 TheFirstRunDialogKeepsTheKeyboardInside() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Shell.ShowWelcome();
await app.ExpectAsync<WelcomeView>("welcome");
var welcome = app.FindAll<WelcomeView>().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<Titano.Ui.Controls.BrandMarkIcon>().Where(b => b.IsVisible).All(b => b.FlowDirection == FlowDirection.LeftToRight));
app.Shell.CompleteWelcome();
});
[Test]
public Task ARightToLeftLanguageMirrorsEveryWindowAlsoThoseOpenedLater() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Shell.About.SetResult(null);
app.Shell.Navigate(SectionKey.About);
await app.ExpectAsync<AboutView>("about");
var main = Window.GetWindow(app.FindAll<AboutView>().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);
dialog.Show();
await dialog.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
Assert.Equal(FlowDirection.RightToLeft, dialog.FlowDirection, "a window opened after the switch (a dialog) is mirrored too");
await app.ExpectAsync<AboutView>("about-ar");
// Inside the mirrored window, paths and the logo keep their left-to-right order.
var path = app.FindAll<TextBlock>().First(t => t.IsVisible && t.Text == app.Shell.About.DataFolder);
Assert.Equal(FlowDirection.LeftToRight, path.FlowDirection);
Assert.Equal(app.Shell.About.DataFolder, path.ToolTip);
// The update result is a live region: screen readers hear each new state.
var update = app.FindAll<Titano.Ui.Controls.StatusGlyph>().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);
});
private static TextBox Field(ScreenSmokeTests.SampleApp app, string name) =>
app.FindAll<TextBox>().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;
/// <summary>The label of every visible Settings row (the first text of the row template).</summary>
private static IEnumerable<TextBlock> Labels(ScreenSmokeTests.SampleApp app) =>
app.FindAll<HeaderedContentControl>().Where(h => h.IsVisible).Select(h => Descendants<TextBlock>(h).First());
/// <summary>The label's text fits its width on one line, or wraps onto more lines; never trimmed.</summary>
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<T> Descendants<T>(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<T>(child)) yield return nested;
}
}
}
@@ -0,0 +1,203 @@
using System.ComponentModel;
using Titano.Core.Localization;
using Titano.Protocol;
using Titano.Testing;
using Titano.Uploader.Server;
using Titano.Uploader.Shell;
using Titano.Uploader.Uploads;
namespace Titano.App.Tests.Uploader;
/// <summary>
/// The sign-in form puts each failure where DESIGN §4 wants it: a refused address or password marks that field
/// (message in its tooltip), other failures are one sentence, with Retry only where trying again can help.
/// </summary>
public sealed class ConnectViewModelTests
{
private const string Fingerprint = "AB:CD";
[Test]
public void NoFieldShowsAnErrorBeforeSigningIn()
{
var form = Form(new FakeSession());
Assert.False(form.HasErrors);
Assert.Empty(form.GetErrors(nameof(ConnectViewModel.Address)));
Assert.Null(form.PasswordError);
Assert.Null(form.ErrorText);
Assert.False(form.CanRetry);
Assert.Equal(Loc.L("Tooltips.Uploader.ServerAddress"), form.AddressToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Password"), form.PasswordToolTip);
}
[Test]
public void AnInvalidAddressMarksTheServerFieldUntilItChanges()
{
var form = Form(new FakeSession(SignInResult.InvalidAddress));
var changed = new List<string?>();
form.ErrorsChanged += (_, e) => changed.Add(e.PropertyName);
form.SignInCommand.Execute(null);
var message = Loc.L("Uploader.Connect.Error.InvalidAddress");
Assert.True(form.HasErrors);
Assert.SequenceEqual([message], form.GetErrors(nameof(ConnectViewModel.Address)).Cast<string>());
Assert.Equal(message, form.AddressToolTip);
Assert.Contains(nameof(ConnectViewModel.Address), changed);
Assert.Null(form.ErrorText, "a field error is not repeated under the form");
Assert.False(form.CanRetry);
form.Address = "https://nas.local:9443";
Assert.False(form.HasErrors);
Assert.Equal(Loc.L("Tooltips.Uploader.ServerAddress"), form.AddressToolTip);
}
[Test]
public void AServerThatIsNotTitanoMarksTheServerField()
{
var form = Form(new FakeSession(SignInResult.NotTitano));
form.SignInCommand.Execute(null);
Assert.Equal(Loc.L("Uploader.Connect.Error.NotTitano"), form.AddressError);
Assert.Null(form.ErrorText);
}
[Test]
public void AWrongPasswordMarksThePasswordFieldUntilTheUserTypes()
{
var form = Form(new FakeSession(SignInResult.BadCredentials));
form.SignInCommand.Execute(null);
var message = Loc.L("Uploader.Connect.Error.BadCredentials");
Assert.Equal(message, form.PasswordError);
Assert.Equal(message, form.PasswordToolTip);
Assert.False(form.HasErrors, "the address is not in question");
Assert.Null(form.ErrorText);
Assert.False(form.CanRetry, "the same password would fail again");
form.Password = "another";
Assert.Null(form.PasswordError);
}
[Theory]
[Case(SignInResult.Unreachable, "Uploader.Connect.Error.Unreachable")]
[Case(SignInResult.Failed, "Uploader.Connect.Error.Failed")]
public void FailuresThatMayPassOfferRetry(SignInResult result, string key)
{
var form = Form(new FakeSession(result));
form.SignInCommand.Execute(null);
Assert.Equal(Loc.L(key), form.ErrorText);
Assert.True(form.CanRetry);
Assert.False(form.HasErrors);
Assert.Null(form.PasswordError);
}
[Test]
public void ADeclinedCertificateIsReportedWithoutRetry()
{
var session = new FakeSession(SignInResult.Untrusted);
var form = Form(session, trust: false);
form.SignInCommand.Execute(null);
Assert.Equal(Loc.L("Uploader.Connect.Error.Untrusted"), form.ErrorText);
Assert.False(form.CanRetry);
Assert.Equal(1, session.Attempts);
Assert.Null(session.Trusted);
}
[Test]
public void ATrustedCertificateSignsInAgainAndClearsEveryError()
{
var session = new FakeSession(SignInResult.BadCredentials, SignInResult.Untrusted, SignInResult.Success);
var form = Form(session, trust: true);
form.SignInCommand.Execute(null);
Assert.NotNull(form.PasswordError);
form.SignInCommand.Execute(null);
Assert.Equal(Fingerprint, session.Trusted);
Assert.Equal(3, session.Attempts);
Assert.Null(form.PasswordError);
Assert.Null(form.ErrorText);
Assert.False(form.HasErrors);
}
[Test]
public void TheFormSaysWhileItsOwnSignInRuns()
{
var session = new FakeSession(SignInResult.Unreachable);
var form = Form(session);
session.During = () => Assert.True(form.IsSigningIn, "signing in while the request runs");
form.SignInCommand.Execute(null);
Assert.Equal(1, session.Attempts);
Assert.False(form.IsSigningIn);
}
private static ConnectViewModel Form(FakeSession session, bool trust = false) =>
new(session, new FakeDialogs(trust), "https://nas.local:8443/", "alberto") { Password = "secret" };
/// <summary>Answers each sign-in with the next scripted result, moving through SigningIn as the real session does.</summary>
private sealed class FakeSession(params SignInResult[] results) : IServerSession
{
private ConnectionState _state = ConnectionState.SignedOut;
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler<ServerProblem>? SessionEnded
{
add { }
remove { }
}
public int Attempts { get; private set; }
public string? Trusted { get; private set; }
public Action? During { get; set; }
public ConnectionState State => _state;
public string? Address => "https://nas.local:8443/";
public string? Username => "alberto";
public long QuotaBytes => 0;
public long UsedBytes => 0;
public int BandwidthLimit { get; set; }
public Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct)
{
var result = results[Math.Min(Attempts, results.Length - 1)];
Attempts++;
SetState(ConnectionState.SigningIn);
During?.Invoke();
SetState(result == SignInResult.Success ? ConnectionState.Connected : ConnectionState.SignedOut);
return Task.FromResult<(SignInResult, string?)>((result, result == SignInResult.Untrusted ? Fingerprint : null));
}
public void Trust(string fingerprint) => Trusted = fingerprint;
public Task SignOutAsync() => Task.CompletedTask;
public Task RefreshAsync() => Task.CompletedTask;
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<SequenceDto>>([]);
private void SetState(ConnectionState state)
{
_state = state;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(State)));
}
}
private sealed class FakeDialogs(bool trust) : IUploaderDialogs
{
public IReadOnlyList<string> PickFiles() => [];
public string? PickFolder() => null;
public string? PickWatchFolder() => null;
public bool ConfirmTrust(string address, string fingerprint) => trust;
public bool ConfirmDeleteAfterUpload() => false;
}
}
@@ -0,0 +1,200 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Uploader.DesignTime;
using Titano.Uploader.Shell;
using Titano.Uploader.Uploads;
namespace Titano.App.Tests.Uploader;
/// <summary>
/// The uploader window on the <c>--capture</c> sample data, shown off screen: icon-only buttons and queue rows are
/// named for screen readers, rows take keyboard focus, no field shows an error before use, disabled controls say
/// why, and in a right-to-left language the window mirrors while paths, file names and the media glyph do not.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(120_000)]
public sealed class UploaderScreenSmokeTests
{
[Test]
public Task EveryScreenIsNamedFocusableAndCalm() => ScreenHost.RunAsync(async () =>
{
UiLanguage.Apply("en");
using var screen = await UploaderScreen.OpenAsync();
var vm = screen.ViewModel;
screen.Sample.ShowConnect();
await screen.SettleAsync();
Assert.Equal(FlowDirection.LeftToRight, screen.Window.FlowDirection);
Assert.False(vm.Connect.HasErrors, "the address is not marked before a sign-in");
Assert.Null(vm.Connect.PasswordError);
Assert.Null(vm.Connect.ErrorText);
foreach (var box in screen.Visible<TextBox>())
Assert.False(Validation.GetHasError(box), $"{AutomationProperties.GetName(box)} shows an error before use");
Assert.False(screen.Named<Border>("PasswordErrorRing").IsVisible, "the password box shows no error before use");
screen.AssertIconButtonsNamed("connect");
// Enter signs in from the form, not from the settings panel drawn over it.
var signIn = screen.Visible<Button>().Single(b => Equals(b.Content, Loc.L("Uploader.Connect.SignIn")));
Assert.True(signIn.IsDefault, "Enter signs in");
vm.IsSettingsOpen = true;
await screen.SettleAsync();
Assert.False(signIn.IsDefault, "Enter in the settings panel does not sign in");
vm.IsSettingsOpen = false;
await screen.SettleAsync();
screen.Sample.ShowQueue();
await screen.SettleAsync();
screen.AssertIconButtonsNamed("queue");
Assert.Equal(Loc.L("Uploader.Queue.List"), AutomationProperties.GetName(screen.Named<ListBox>("ItemList")));
var rows = screen.Visible<ListBoxItem>();
Assert.NotEmpty(rows);
foreach (var row in rows)
{
Assert.True(row.Focusable, "queue rows take keyboard focus");
var item = (UploadItem)row.DataContext;
var name = UIElementAutomationPeer.CreatePeerForElement(row)?.GetName();
Assert.Contains(item.FileName, name);
Assert.Contains(UploadStateTextConverter.Text(item.State), name);
}
Assert.Contains(rows, r => r.DataContext == vm.CurrentItem);
Assert.NotNull(vm.FirstFailed());
Assert.NotNull(vm.FailedText);
Assert.True(screen.Named<Button>("FailedLink").IsVisible, "the failure count is a link to the failed file");
// Disabled controls say why; the settings panel keeps Tab inside it.
Assert.Equal(Loc.L("Tooltips.Uploader.SequenceDisabled"), vm.SequenceToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Pause"), vm.PauseToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Stop"), vm.StopToolTip);
Assert.Equal(KeyboardNavigationMode.Cycle, KeyboardNavigation.GetTabNavigation(screen.Named<Border>("SettingsPanel")));
vm.IsSettingsOpen = true;
await screen.SettleAsync();
screen.AssertIconButtonsNamed("settings");
vm.IsSettingsOpen = false;
});
[Test]
public Task TheWindowMirrorsForRightToLeftLanguages() => ScreenHost.RunAsync(async () =>
{
UiLanguage.Apply("ar");
try
{
using var screen = await UploaderScreen.OpenAsync();
screen.Sample.ShowQueue();
await screen.SettleAsync();
Assert.Equal(FlowDirection.RightToLeft, screen.Window.FlowDirection);
// File names, paths and addresses read left to right in every language.
var fileNames = screen.Visible<ListBoxItem>().Select(r => ((UploadItem)r.DataContext).FileName).ToHashSet();
var islands = screen.Visible<TextBlock>()
.Where(t => fileNames.Contains(t.Text) || t.Text.Contains('\\') || t.Text.StartsWith("https://", StringComparison.Ordinal))
.ToList();
Assert.NotEmpty(islands);
foreach (var text in islands) Assert.Equal(FlowDirection.LeftToRight, text.FlowDirection, text.Text);
// Media glyphs (pause, play) are not mirrored.
var pause = screen.Visible<Button>().Single(b => AutomationProperties.GetName(b) == screen.ViewModel.PauseLabel);
Assert.Equal(FlowDirection.LeftToRight, pause.FlowDirection);
screen.Sample.ShowConnect();
await screen.SettleAsync();
Assert.Equal(FlowDirection.LeftToRight, screen.Named<TextBox>("AddressBox").FlowDirection);
var mark = screen.Visible<BrandMarkIcon>().Single(m => m.ActualWidth >= 48);
Assert.Equal(FlowDirection.LeftToRight, mark.FlowDirection);
}
finally
{
UiLanguage.Apply("en");
}
});
/// <summary>A <see cref="MainWindow"/> on <see cref="SampleData"/>, shown off screen like <c>--capture</c>.</summary>
private sealed class UploaderScreen : IDisposable
{
private UploaderScreen(SampleData sample, MainViewModel viewModel, MainWindow window)
{
Sample = sample;
ViewModel = viewModel;
Window = window;
}
public SampleData Sample { get; }
public MainViewModel ViewModel { get; }
public MainWindow Window { get; }
public static async Task<UploaderScreen> OpenAsync()
{
ThemeManager.Apply(AppTheme.Dark);
var sample = new SampleData();
var vm = sample.CreateViewModel();
var window = new MainWindow(vm, sample.Settings)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 760,
Height = 700,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
var screen = new UploaderScreen(sample, vm, window);
await screen.SettleAsync();
return screen;
}
public async Task SettleAsync()
{
Window.UpdateLayout();
// Bindings, templates and the work the window defers to the dispatcher (scrolling, focus).
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
Window.UpdateLayout();
}
public List<T> Visible<T>()
where T : FrameworkElement => [.. All<T>(Window).Where(e => e.IsVisible)];
public T Named<T>(string name)
where T : FrameworkElement => All<T>(Window).Single(e => e.Name == name);
/// <summary>DESIGN §4: an icon-only button carries an accessible name (and a tooltip).</summary>
public void AssertIconButtonsNamed(string screen)
{
foreach (var button in Visible<Button>().Where(b => b.Content is null))
{
Assert.False(string.IsNullOrWhiteSpace(AutomationProperties.GetName(button)), $"{screen}: an icon-only button has no name");
Assert.True(button.ToolTip is not null, $"{screen}: {AutomationProperties.GetName(button)} has no tooltip");
}
}
public void Dispose()
{
Window.Close();
ViewModel.Dispose();
}
private static IEnumerable<T> All<T>(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 All<T>(child)) yield return nested;
}
}
}
}
@@ -47,7 +47,23 @@ public sealed class UploaderTextTests
public void ProgressLineMatchesTheMockup()
{
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 0 retries", UploaderText.ProgressLine(Mockup, En));
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 1 retry · 3 failed", UploaderText.ProgressLine(Mockup with { Retries = 1, Failed = 3 }, En));
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 1 retry", UploaderText.ProgressLine(Mockup with { Retries = 1, Failed = 3 }, En));
}
[Test]
public void FailuresHaveTheirOwnTextOnlyWhenThereAreAny()
{
Assert.Null(UploaderText.Failed(Mockup, En));
Assert.Equal("1,203 failed", UploaderText.Failed(Mockup with { Failed = 1_203 }, En));
Assert.Equal("3 non riusciti", UploaderText.Failed(Mockup with { Failed = 3 }, It));
}
[Test]
public void SizeUnitsFollowTheLanguage()
{
Assert.Equal("999 byte", UploaderText.Bytes(999, It));
Assert.Equal("1,5 KB", UploaderText.Bytes(1_536, It));
Assert.Equal("4,2 MB/s", UploaderText.Rate(4_240_000, It));
}
[Theory]
@@ -0,0 +1,52 @@
using Titano.Core.Localization;
using Titano.Testing;
using Titano.Uploader.Shell;
using Titano.Uploader.Text;
namespace Titano.App.Tests.Uploader;
/// <summary>A watch-folder chip shows the path (which it may shorten) and the interval apart; the tooltip carries the whole path.</summary>
public sealed class WatchFolderViewModelTests
{
private const string Path = @"\\garage-pi\cam";
[Test]
public void TheChipNamesThePathAndTheInterval()
{
var chip = Chip(isNetwork: false);
var interval = UploaderText.Duration(TimeSpan.FromMinutes(5), Loc.Culture);
Assert.Equal(Loc.L("Uploader.Watch.Interval", interval), chip.IntervalText);
Assert.Equal(Loc.L("Uploader.Watch.Chip", Path, interval), chip.Text);
}
[Test]
public void TheTooltipStartsWithTheWholePathKeptLeftToRight()
{
var interval = UploaderText.Duration(TimeSpan.FromMinutes(5), Loc.Culture);
var embedded = "\u202A" + Path + "\u202C · ";
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolder", interval), Chip(isNetwork: false).ToolTip);
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolderNetwork", interval), Chip(isNetwork: true).ToolTip);
var missing = Chip(isNetwork: true);
missing.IsAvailable = false;
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolderMissing", interval), missing.ToolTip);
}
[Test]
public void ANewIntervalRefreshesTheChip()
{
var chip = Chip(isNetwork: false);
var changed = new List<string?>();
chip.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
chip.IntervalSeconds = 60;
Assert.Contains(nameof(WatchFolderViewModel.IntervalText), changed);
Assert.Contains(nameof(WatchFolderViewModel.Text), changed);
Assert.Contains(nameof(WatchFolderViewModel.ToolTip), changed);
Assert.Equal(Loc.L("Uploader.Watch.Interval", UploaderText.Duration(TimeSpan.FromMinutes(1), Loc.Culture)), chip.IntervalText);
}
private static WatchFolderViewModel Chip(bool isNetwork) => new(Path, 300, isNetwork, (_, _) => { }, _ => { });
}