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 Chronos.App.Import;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Import;
using Chronos.Core.Localization;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Import;
///
/// Every Import state of --capture ( ) on the simulated cards, rendered in both themes
/// 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.
///
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ImportScreenSmokeTests
{
[Test]
public Task EveryImportStateRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var import = app.Shell.Import;
await ShowAsync(app, "inserted");
await UseCaptureSizeAsync(app);
Assert.NotEmpty(app.FindAll().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("import-inserted");
await ShowAsync(app, "plan");
Assert.Equal(ImportPhase.Ready, import.Phase);
Assert.Equal("EOS R5 · card A", import.SourceTitle);
Assert.Equal(3, import.Sessions.Count, "night, dawn and sunset");
Assert.Equal(50, import.Plan!.CopyCount);
Assert.Equal("Harbour sunset", import.Plan.Sessions[^1].Title);
Assert.Null(import.StartBlocker);
Assert.Empty(app.FindAll().SelectMany(host => host.Toasts));
await app.ExpectAsync("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(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("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);
Assert.False(import.IsFormEnabled);
Assert.False(import.Sessions[0].IsEditable, "titles lock while copying");
await app.ExpectAsync("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(app, "ProgressLine");
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(progress));
Assert.Same(progress, AutomationProperties.GetLabeledBy(app.FindAll().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("import-failed");
Assert.True(ButtonFor(app, import.RetryCommand).IsEnabled, "Retry is enabled after a failure");
var failure = Named(app, "FailureLine");
Assert.Equal(AutomationLiveSetting.Assertive, AutomationProperties.GetLiveSetting(failure));
Assert.True(Fits(failure), "the failure sentence is shown whole");
Assert.Null(app.FindAll().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);
var result = import.Result!;
Assert.True(result.IsComplete);
Assert.True(result.OffersDelete);
Assert.True(result.Actions.CanDelete, "a verified import and its dry run allow deleting");
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().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("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().SelectMany(host => host.Toasts));
await app.ExpectAsync("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(app, "FolderPathBox").FlowDirection);
Assert.Equal(FlowDirection.LeftToRight, Named(app, "GapBox").FlowDirection);
foreach (var template in app.FindAll().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");
// A size carries the language's unit, so it reads in the language's direction, whole, at the end of its cell.
var size = TextFor(app, import.Sessions[0].Row.SizeText);
Assert.Equal(FlowDirection.RightToLeft, size.FlowDirection);
Assert.Equal(TextAlignment.Right, size.TextAlignment);
var shown = size.ActualWidth + size.Margin.Left + size.Margin.Right;
size.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
Assert.True(shown >= size.DesiredSize.Width - 0.5, $"the size column fits the whole size ({shown:0.#} < {size.DesiredSize.Width:0.#})");
Assert.Contains("←", import.Sessions[0].Row.TimeText);
await app.ExpectAsync("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("import-showplan-ar");
}
finally
{
UiLanguage.Apply("en");
}
});
///
/// An archive import whose job ends before the screen records its id (here cancelled inside the engine's own "queued"
/// event, so the screen sees none of its events) still ends the screen's run instead of leaving it copying forever.
///
[Test]
public Task AnImportJobThatEndsBeforeItIsRecordedStillEndsTheRun() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var import = app.Shell.Import;
await ShowAsync(app, "plan");
var engine = Assert.NotNull(app.Services.Engine);
void CancelAtOnce(Core.Model.Job job)
{
if (job is { Kind: Core.Model.JobKind.Import, State: Core.Model.JobState.Queued }) engine.CancelAsync(job.Id).GetAwaiter().GetResult();
}
engine.JobChanged += CancelAtOnce;
try
{
Assert.True(import.StartCommand.CanExecute(null), "the plan can be imported");
import.StartCommand.Execute(null);
for (var i = 0; i < 300 && !import.IsFailed; i++) await Task.Delay(50);
}
finally
{
engine.JobChanged -= CancelAtOnce;
}
Assert.True(import.IsFailed, "the screen left Running though no event of the job reached it");
Assert.Equal(Loc.L("Import.Status.Cancelled"), import.ErrorText);
});
/// A result replaced by New import stops following the language: nothing keeps it, or its plan, alive.
[Test]
public Task AReplacedResultStopsFollowingTheLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var import = app.Shell.Import;
await ShowAsync(app, "done");
var replaced = Assert.NotNull(import.Result);
var refreshed = 0;
replaced.PropertyChanged += (_, _) => refreshed++;
import.NewImportCommand.Execute(null);
Assert.Null(import.Result);
try
{
UiLanguage.Apply("it");
}
finally
{
UiLanguage.Apply("en");
}
Assert.Equal(0, refreshed, "the replaced result was disposed");
await import.WaitForPlanAsync();
});
///
/// "Group" (BRIEF §12.4) is offered for a picked folder only, and a card is always planned by sessions. Switching the
/// grouping drops the splits made on the other grouping's sessions, and the session controls it turns off say why.
///
[Test]
public Task AWholeFolderIsOfferedForAFolderOnlyAndDropsTheSplitsMadeBefore() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var import = app.Shell.Import;
var card = SampleCards.Card(app.Services.Environment.DataDirectory);
// A card: no Group choice, and asking for a whole folder changes nothing.
await ShowAsync(app, "plan");
Assert.False(import.CanGroupFolder);
import.GroupWholeFolder = true;
Assert.True(import.GroupBySessions);
Assert.Equal(ImportGrouping.Sessions, import.Choices.Grouping);
Assert.True(import.SessionsApply);
// The card's photos picked as a folder start by sessions: night, dawn and sunset.
await import.ImportFolderAsync(card.Root);
await import.WaitForPlanAsync();
Assert.True(import.CanGroupFolder);
Assert.True(import.GroupBySessions);
Assert.Equal((ImportGrouping.Sessions, 3), (import.Plan!.Grouping, import.Plan.Sessions.Count));
// The sunset split in two halves of twelve photos.
import.ShowPlanCommand.Execute(null);
import.SplitCommand.Execute(import.Details!.Rows.Where(r => r.Kind == PlanRowKind.File).ToList()[^12]);
await import.WaitForPlanAsync();
Assert.Equal(4, import.Plan!.Sessions.Count, "the split starts a session");
// The whole folder is one sequence for its one format, not cut where the sessions were split.
import.GroupWholeFolder = true;
await WaitUntilAsync(app, () => import.Plan is { Grouping: ImportGrouping.WholeFolder } && import.Phase == ImportPhase.Ready, "the whole folder is planned");
Assert.Equal(ImportGrouping.WholeFolder, import.Choices.Grouping);
Assert.Equal(1, import.Plan!.Sessions.Count);
Assert.False(import.SessionsApply);
Assert.False(import.GapApplies);
var why = Loc.L("Import.Blocked.WholeFolder");
Assert.Equal((why, why, why), (import.SessionsToolTip, import.GapMinutes.ToolTip, import.MinimumFrames.ToolTip));
var boxes = app.FindAll().Where(t => IsInImport(t) && EditBehavior.GetField(t) is { } f && (f == import.GapMinutes || f == import.MinimumFrames)).ToList();
Assert.Equal(2, boxes.Count);
foreach (var box in boxes)
{
Assert.False(box.IsEnabled);
Assert.True(ToolTipService.GetShowOnDisabled(box), "a disabled session box still shows why");
Assert.Equal(why, box.ToolTip as string);
}
// Back to sessions: the split made before stays gone.
import.GroupBySessions = true;
await WaitUntilAsync(app, () => import.Plan is { Grouping: ImportGrouping.Sessions } && import.Phase == ImportPhase.Ready, "the sessions are planned again");
Assert.Equal(3, import.Plan!.Sessions.Count);
Assert.True(import.SessionsApply);
Assert.Equal(Loc.L("Tooltips.Import.Gap"), import.GapMinutes.ToolTip);
// Choosing the card again leaves the folder's whole-folder choice behind.
import.GroupWholeFolder = true;
await WaitUntilAsync(app, () => import.Plan is { Grouping: ImportGrouping.WholeFolder } && import.Phase == ImportPhase.Ready, "the whole folder is planned");
import.SelectSource(card.Identity);
await import.WaitForPlanAsync();
Assert.False(import.CanGroupFolder);
Assert.True(import.GroupBySessions);
Assert.Equal(ImportGrouping.Sessions, import.Choices.Grouping);
Assert.Equal((ImportGrouping.Sessions, 3), (import.Plan!.Grouping, import.Plan.Sessions.Count));
});
/// As --capture does: toasts of the previous state go, those of an insertion state stay.
private static async Task ShowAsync(ScreenSmokeTests.SampleApp app, string state)
{
DismissToasts(app);
await ImportScenes.ShowAsync(app.Shell, state);
if (!ImportScenes.ShowsToast(state)) DismissToasts(app);
await SettleAsync(app);
}
private static void DismissToasts(ScreenSmokeTests.SampleApp app)
{
foreach (var host in app.FindAll())
{
foreach (var toast in host.Toasts.ToList()) host.Dismiss(toast);
}
}
/// The size CI captures at (and the window's minimum width): nothing may be cut there.
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 condition, string what)
{
for (var i = 0; i < 200 && !condition(); i++) await Task.Delay(25);
Assert.True(condition(), what);
await SettleAsync(app);
}
/// The empty folder path is fine for the archive; choosing Folder makes it invalid and offers "Choose folder".
private static async Task AssertFolderPathIsCheckedOnlyForFolderAsync(ScreenSmokeTests.SampleApp app, ImportViewModel import)
{
var box = Named(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(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");
}
/// The 56 px gap box shows its largest value, 1440, whole.
private static async Task AssertFourDigitsFitAsync(ScreenSmokeTests.SampleApp app, ImportViewModel import)
{
import.GapMinutes.Text = "1440";
await SettleAsync(app);
var host = Descendants(Named(app, "GapBox")).OfType().First();
Assert.LessOrEqual(host.ExtentWidth, host.ViewportWidth + 1, "1440 fits the gap box");
import.GapMinutes.Revert();
}
/// Every button, check box and radio button of the screen has a name screen readers can announce.
private static void AssertEveryButtonIsNamed(ScreenSmokeTests.SampleApp app)
{
foreach (var button in app.FindAll().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");
}
}
///
/// Beside the 200 px rail at the 1200 px minimum (owner review 1, R1), in every shipped language: the session rows' Merge and the
/// plan rows' Split stay inside their rows (shown or not yet revealed), and the result line inside its card.
///
[Test]
public Task RowButtonsAndTheResultFitAtTheMinimumWidthInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
foreach (var (state, list) in new[] { ("plan", "SessionRows"), ("showplan", "PlanRows") })
{
await ShowAsync(app, state);
await UseCaptureSizeAsync(app);
await InEveryLanguageAsync(app, language =>
{
var rows = Named(app, list);
var viewport = Descendants(rows).OfType().First();
var (left, right) = Span(viewport, WindowOf(app));
foreach (var button in Descendants(rows).OfType().Where(b => b.Visibility != Visibility.Collapsed && b.ActualWidth > 0))
{
var (start, end) = Span(button, WindowOf(app));
Assert.True(start >= left - 0.5 && end <= right + 0.5, $"{language} {state}: '{button.Content}' spans {start:0}–{end:0} px, its rows {left:0}–{right:0} px");
}
});
}
await ShowAsync(app, "done");
await UseCaptureSizeAsync(app);
await InEveryLanguageAsync(app, language =>
{
var result = app.FindAll().First(g => g.IsVisible && g.DataContext is ImportResultViewModel && IsInImport(g));
var line = (FrameworkElement)VisualTreeHelper.GetParent(result);
var card = (FrameworkElement)VisualTreeHelper.GetParent(line);
var (left, right) = Span(card, WindowOf(app));
foreach (var text in Descendants(line).OfType().Where(t => t.IsVisible))
{
var (start, end) = Span(text, WindowOf(app));
Assert.True(start >= left - 0.5 && end <= right + 0.5, $"{language}: '{text.Text}' spans {start:0}–{end:0} px, its card {left:0}–{right:0} px");
}
});
});
private static async Task InEveryLanguageAsync(ScreenSmokeTests.SampleApp app, Action check)
{
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await SettleAsync(app);
check(language);
}
}
finally
{
UiLanguage.Apply("en");
}
}
/// The left and right edges of an element in window coordinates, whichever way the window reads.
private static (double Left, double Right) Span(FrameworkElement element, Window window)
{
var a = element.TranslatePoint(new Point(0, 0), window).X;
var b = element.TranslatePoint(new Point(element.ActualWidth, 0), window).X;
return (Math.Min(a, b), Math.Max(a, b));
}
private static Window WindowOf(ScreenSmokeTests.SampleApp app) => Window.GetWindow(app.FindAll().First())!;
private static ImportView View(ScreenSmokeTests.SampleApp app) => app.FindAll().First(v => v.IsVisible);
private static bool IsInImport(DependencyObject element) => FindAncestor(element) is not null;
private static T? FindAncestor(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 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(ScreenSmokeTests.SampleApp app, string name)
where T : FrameworkElement =>
Assert.NotNull(app.FindAll().FirstOrDefault(e => e.Name == name), $"{typeof(T).Name} {name}");
private static TextBlock TextFor(ScreenSmokeTests.SampleApp app, string text) =>
Assert.NotNull(app.FindAll().FirstOrDefault(t => t.IsVisible && t.Text == text && IsInImport(t)), $"a visible text '{text}'");
private static IEnumerable DeviceItems(ScreenSmokeTests.SampleApp app) =>
app.FindAll().Where(i => i.IsVisible && i.DataContext is ImportSource);
///
/// 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).
///
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().FirstOrDefault(b => ReferenceEquals(b.Command, command) && b.IsVisible), "a visible button bound to the command");
}