Files
Chronos/tests/Chronos.App.Tests/Archive/ArchiveScreenSmokeTests.cs
T
Alby96 a1c1c21ebd feat(app): Convert sequences from the Archive manager and the Library, with Undo after a Replace
Owner review 2, R7 asks for mass conversion after import on the desktop too, with a choice at
every run between Replace and New sequence. The desktop now uses the engine's conversion, the
same plan and job as the web panel.

- Convert... in the Archive manager's mass operations (the set) and the Library's mass bar (the
  selection of one archive; server cards are left out, two archives are refused with their own
  reason). The dialog has the format (JPEG, TIFF 16-bit, Linear DNG, the archival default), a
  JPEG's quality (1-100, 95) and the mode, which starts unchosen at every open: Apply waits for
  it. Each choice has a tooltip that says what becomes of the originals.
- The dry run stays in the dialog and follows the choices: each sequence with its photos and
  sizes before and after, the photos that stay as they are with why, the sequences left as they
  are (busy, offline, unreadable), a summary and the free space line; a volume without the space
  blocks Apply. The mode does not change what converts, so choosing it plans nothing again.
- Apply asks to type the number of photos a Replace replaces, then queues the convert job of
  exactly the plan shown; New sequence leaves the originals as they are and asks nothing.
- When a Replace job ends, its toast offers Undo: for each sequence it converted, the newest
  Replaced trash entry made while it ran goes back (a sequence changed since gets its originals
  as a new sequence). Undo runs once and never from the Windows notification.
- The Library and the Archive screen read the sequences again after a conversion; --capture
  renders archive-convert from a sample plan.
- Strings in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 275469284f895fc92e2569339809e18bf59d1d6a)
(cherry picked from commit 76ba41f58983275ae4b1478edd403efb11da7c79)
2026-10-27 22:02:04 +01:00

386 lines
22 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
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.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Archiving;
using Chronos.Core.Conversion;
using Chronos.Core.Localization;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Archiving;
/// <summary>
/// Every Archive view of <c>--capture</c> (<see cref="ArchiveScenes"/>) on the sample archive, rendered in both themes
/// in the real main window, with what each view must show — the buttons really enabled and named for screen readers,
/// keyboard focus visible, no error or busy state left over — and paths and templates readable in a right-to-left
/// language.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ArchiveScreenSmokeTests
{
[Test]
public Task EveryArchiveViewRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var archive = app.Shell.Archive;
await ArchiveScenes.ShowAsync(app.Shell, "overview");
Assert.True(archive.IsOverview);
Assert.True(archive.TreeRows[0].IsArchive);
Assert.Equal(StatusKind.Online, archive.TreeRows[0].AvailabilityKind);
Assert.True(archive.TreeRows[1].IsYear);
Assert.True(archive.TreeRows[1].IsExpanded, "the newest year opens with the screen");
Assert.Equal(5, archive.Tiles.Count);
Assert.Equal(2, archive.MonthRows.Count, "one heatmap row per year, 2025 and 2026");
Assert.NotEmpty(archive.StorageBars);
Assert.NotEmpty(archive.CameraBars);
Assert.NotEmpty(archive.FormatBars);
Assert.True(archive.HasMonthScale, "the heatmap's scale sits in its header");
Assert.Contains(archive.CameraBars[0].ToolTip!, archive.CamerasDescription);
Assert.True(archive.ScanCommand.CanExecute(null), "an online archive can be scanned");
await app.ExpectAsync<ArchiveView>("archive-overview");
Assert.True(ButtonFor(app, archive.ScanCommand).IsEnabled, "the Scan button is enabled once the archive is read");
Assert.True(ButtonFor(app, archive.AnalyseSetCommand).IsEnabled, "mass operations are enabled on the whole archive");
AssertEveryButtonIsNamed(app);
Assert.Contains(archive.SetText, AutomationProperties.GetName(SetButton(app)));
foreach (var row in TreeItems(app)) Assert.NotNull(row.FocusVisualStyle, "a tree row shows keyboard focus");
Assert.Equal(Loc.L("Archive.Tree.Collapse"), AutomationProperties.GetName(ButtonFor(app, archive.TreeRows[1].ToggleCommand)),
"the open year's expander has a short name; the sentence is its tooltip");
var sequence = archive.TreeRows.First(r => r.Node.Kind == TreeNodeKind.Sequence);
Assert.Contains(sequence.Title, sequence.RowToolTip);
// Expanding another year keeps the selection: the set stays what the user chose.
var year = archive.TreeRows[1];
var tree = Tree(app);
tree.SelectedItems.Add(year);
var chosen = archive.SetText;
archive.Toggle(archive.TreeRows.Last(r => r.IsYear));
Assert.Equal(chosen, archive.SetText, "opening a year does not change the set");
Assert.True(tree.SelectedItems.Cast<ArchiveTreeRowViewModel>().Any(r => r.Node.Key == year.Node.Key), "the list shows the same selection");
tree.SelectedItems.Clear();
await ArchiveScenes.ShowAsync(app.Shell, "maintenance");
Assert.True(archive.IsMaintenance);
Assert.Equal(5, archive.Health.Count);
Assert.Equal(1, archive.Duplicates!.Count);
Assert.Equal(3, archive.Orphans!.Count, "unlisted photos, a row without sidecar, a folder not indexed");
var duplicatesLine = archive.Health[4].Line;
Assert.False(duplicatesLine.IsOk, "index health agrees with the duplicate groups listed beside it");
Assert.Equal(HealthAction.MarkDuplicates, duplicatesLine.Action);
await app.ExpectAsync<ArchiveView>("archive-maintenance");
Assert.False(app.FindAll<Button>().Any(b => b.IsVisible && ReferenceEquals(b.Command, archive.CancelSearchCommand)), "no Cancel without a search");
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(TextFor(app, archive.DuplicatesText)), "search results are announced");
AssertEveryButtonIsNamed(app);
await ArchiveScenes.ShowAsync(app.Shell, "rebuild");
var rebuild = Assert.NotNull(archive.Dialog as RebuildDialogViewModel);
Assert.True(rebuild.RebuildCommand.CanExecute(null));
Assert.False(archive.IsContentEnabled, "the screen behind a dialog takes no input");
Assert.False(rebuild.FactRows.Any(f => f.Value == Loc.L("Archive.Rebuild.Counting")), "counted, the facts no longer say Counting…");
await app.ExpectAsync<ArchiveView>("archive-rebuild");
Assert.False(tree.IsEnabled);
var frame = Assert.NotNull(VisualTreeHelper.GetChild(tree, 0) as Border);
Assert.Equal(0, ((SolidColorBrush)frame.Background).Color.A, "the disabled tree keeps its panel's fill instead of the system's white");
AssertNoErrorShown(app);
await ArchiveScenes.ShowAsync(app.Shell, "reorganize");
var reorganize = Assert.NotNull(archive.Dialog as ReorganizeDialogViewModel);
Assert.NotEmpty(reorganize.Rows, "the dry run lists the sequences that change");
Assert.Null(reorganize.ErrorText);
await app.ExpectAsync<ArchiveView>("archive-reorganize");
Assert.True(ButtonFor(app, reorganize.ApplyCommand).IsEnabled, "Apply follows the dry run");
Assert.True(ButtonFor(app, reorganize.CloseCommand).IsDefault, "Enter takes the safe way out");
foreach (var box in app.FindAll<CheckBox>().Where(c => c.IsVisible)) Assert.NotNull(box.ToolTip, "every template switch says what it does");
AssertNoErrorShown(app);
AssertEveryButtonIsNamed(app);
reorganize.CloseCommand.Execute(null);
await ArchiveScenes.ShowAsync(app.Shell, "convert");
var convert = Assert.NotNull(archive.Dialog as ConvertDialogViewModel);
Assert.Equal(ConvertMode.NewSequence, convert.Mode);
Assert.Count(6, convert.Rows, "the dry run lists the sequences, each with what converts or why it does not");
Assert.True(convert.IsSpaceFine);
Assert.Null(convert.ErrorText);
await app.ExpectAsync<ArchiveView>("archive-convert");
Assert.True(ButtonFor(app, convert.ApplyCommand).IsEnabled, "Apply follows the dry run and the mode chosen");
Assert.True(ButtonFor(app, convert.CloseCommand).IsDefault, "Enter takes the safe way out");
Assert.True(TextFor(app, convert.SpaceText!).IsVisible, "the free space line shows");
foreach (var choice in app.FindAll<RadioButton>().Where(r => r.IsVisible && IsInArchive(r))) Assert.NotNull(choice.ToolTip, "every choice says what it does");
AssertNoErrorShown(app);
AssertEveryButtonIsNamed(app);
convert.CloseCommand.Execute(null);
archive.RetagSetCommand.Execute(null);
var retag = Assert.NotNull(archive.Dialog as RetagDialogViewModel);
retag.Add.Text = "sunset";
await app.ExpectAsync<ArchiveView>("archive-retag");
Assert.True(ButtonFor(app, retag.ApplyCommand).IsEnabled, "Apply follows the typed tags");
AssertNoErrorShown(app);
retag.CloseCommand.Execute(null);
});
[Test]
public Task PathsTemplatesAndMonthsStayReadableRightToLeft() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
UiLanguage.Apply("ar");
try
{
var archive = app.Shell.Archive;
await ArchiveScenes.ShowAsync(app.Shell, "overview");
Assert.Equal(12.ToString("N0", Loc.Culture), archive.MonthLabels[^1], "Arabic month names have no initials: the columns are numbered");
var year = archive.TreeRows[1];
Assert.Equal(Loc.L("Tooltips.Archive.YearRowRtl", year.Title + Loc.Separator + year.Detail), year.RowToolTip, "the tooltip names the mirrored arrow keys");
await app.ExpectAsync<ArchiveView>("archive-overview-ar");
// The dialogs' templates exist once they are laid out: render first, then look inside.
await ArchiveScenes.ShowAsync(app.Shell, "rebuild");
await app.ExpectAsync<ArchiveView>("archive-rebuild-ar");
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, archive.SelectedArchive!.RootPath).FlowDirection, "the archive folder reads left to right");
await ArchiveScenes.ShowAsync(app.Shell, "reorganize");
var reorganize = Assert.NotNull(archive.Dialog as ReorganizeDialogViewModel);
await app.ExpectAsync<ArchiveView>("archive-reorganize-ar");
var template = Assert.NotNull(app.FindAll<TextBox>().FirstOrDefault(t => t.IsVisible && EditBehavior.GetField(t) == reorganize.Folders.Field));
Assert.Equal(FlowDirection.LeftToRight, template.FlowDirection, "the naming template reads left to right");
var folder = reorganize.Rows.SelectMany(r => r.Lines).First(l => l.IsPath);
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, folder.From).FlowDirection, "a folder before the move reads left to right");
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, folder.To).FlowDirection, "a folder after the move reads left to right");
reorganize.CloseCommand.Execute(null);
await ArchiveScenes.ShowAsync(app.Shell, "convert");
var convert = Assert.NotNull(archive.Dialog as ConvertDialogViewModel);
await app.ExpectAsync<ArchiveView>("archive-convert-ar");
var untitled = Assert.NotNull(convert.Rows.FirstOrDefault(r => r.IsNamePath), "a sequence without a title is named by its folder");
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, untitled.Name).FlowDirection, "its folder reads left to right");
convert.CloseCommand.Execute(null);
}
finally
{
UiLanguage.Apply("en");
}
});
[Test]
public async Task RebuildCountsSayWhyInsteadOfCountingForever()
{
var offline = new RebuildDialogViewModel(Archive("/nowhere"), ArchiveAvailability.Offline, 3, () => Task.CompletedTask, _ => { });
await offline.CountAsync();
var sidecars = Fact(offline, "Archive.Rebuild.Sidecars");
Assert.Equal("—", sidecars.Value);
Assert.Equal(Loc.L("Archive.Error.Offline", Formatting.LeftToRight("/nowhere")), sidecars.ToolTip);
Assert.True(Fact(offline, "Archive.Rebuild.Root").IsPath, "the archive folder is shown left to right");
var missing = Path.Combine(Path.GetTempPath(), "chronos-missing-" + Guid.NewGuid().ToString("N"));
var unreadable = new RebuildDialogViewModel(Archive(missing), ArchiveAvailability.Online, 3, () => Task.CompletedTask, _ => { });
await unreadable.CountAsync();
Assert.Equal("—", Fact(unreadable, "Archive.Rebuild.Metadata").Value);
Assert.Equal(Loc.L("Archive.Failed.Files"), Fact(unreadable, "Archive.Rebuild.Metadata").ToolTip);
Assert.Null(unreadable.BusyText, "nothing is counting any more");
static Core.Model.Archive Archive(string root) => new() { Id = Guid.CreateVersion7(), Name = "ChronosArchive", RootPath = root };
static DialogFact Fact(RebuildDialogViewModel dialog, string label) => dialog.FactRows.Single(f => f.Label == Loc.L(label));
}
/// <summary>
/// Picking another archive while one is being read shows the picked one: the read in progress is followed by one of
/// the new archive, and meanwhile nothing of the previous archive's tree can be acted on.
/// </summary>
[Test]
public Task PickingAnotherArchiveDuringAReadShowsThePickedOne() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var archive = app.Shell.Archive;
await ArchiveScenes.ShowAsync(app.Shell, "overview");
Assert.Contains(archive.TreeRows, r => r.Node.Kind == TreeNodeKind.Sequence);
Assert.NotEmpty(archive.Tiles);
Assert.NotEmpty(archive.CameraBars);
var first = archive.SelectedArchive!;
var second = await app.Services.Archives!.CreateAsync(Path.Combine(app.Services.Environment.DataDirectory, "second-archive"), "Second");
var reading = archive.LoadAsync();
archive.SelectedArchive = second;
Assert.Empty(archive.TreeRows);
// None of the first archive's figures stays on screen under the picked one's name while it is read (or if its read fails).
Assert.Empty(archive.Tiles);
Assert.Empty(archive.MonthRows);
Assert.Empty(archive.StorageBars);
Assert.Empty(archive.CameraBars);
Assert.Empty(archive.FormatBars);
Assert.Empty(archive.Recent);
Assert.False(archive.HasRecent);
Assert.Equal(string.Empty, archive.LastScanText);
Assert.Equal(0, archive.Badge, "the rail badge counts the picked archive's health, which is not read yet");
Assert.False(archive.AnalyseSetCommand.CanExecute(null), "nothing of the first archive can be acted on while the picked one is read");
Assert.False(archive.ScanCommand.CanExecute(null), "the picked archive is not known to be online yet");
Assert.Equal(Loc.L("Archive.Blocked.Reading"), archive.ScanToolTip, "not yet read is not offline");
Assert.False(archive.RebuildCommand.CanExecute(null), "the rebuild dialog waits for the picked archive's own state and figures");
Assert.Null(await archive.OpenRebuildDialogAsync());
Assert.Empty(archive.Health);
// Back to the first archive before the picked one is read: it was read before, but none of its figures is left.
archive.SelectedArchive = first;
Assert.Empty(archive.TreeRows);
Assert.False(archive.RebuildCommand.CanExecute(null), "the first archive is not read again yet");
Assert.False(archive.ScanCommand.CanExecute(null));
Assert.Equal(Loc.L("Archive.Blocked.Reading"), archive.ScanToolTip);
Assert.Null(await archive.OpenRebuildDialogAsync());
archive.SelectedArchive = second;
await reading;
Assert.Equal(second.Id, archive.SelectedArchive!.Id);
Assert.Contains(archive.Archives, a => a.Id == second.Id);
Assert.True(archive.TreeRows[0].IsArchive);
Assert.False(archive.TreeRows.Any(r => r.Node.Kind == TreeNodeKind.Sequence), "the tree is the picked, empty archive's");
Assert.True(archive.ScanCommand.CanExecute(null), "the picked archive was probed: it is online");
Assert.Equal(Loc.L("Tooltips.Archive.Scan"), archive.ScanToolTip);
Assert.True(archive.RebuildCommand.CanExecute(null));
var rebuild = Assert.NotNull(await archive.OpenRebuildDialogAsync());
Assert.Equal(second.Id, rebuild.Archive.Id);
Assert.Equal(ArchiveAvailability.Online, rebuild.Availability, "the dialog shows the picked archive's availability");
Assert.Equal(0, rebuild.Indexed, "and its own index, not the first archive's");
rebuild.CloseCommand.Execute(null);
});
[Test]
public void TheArrowTowardsTheIndentOpensAYearInEitherDirection()
{
Assert.True(ArchiveView.Toggles(Key.Right, FlowDirection.LeftToRight, isExpanded: false));
Assert.False(ArchiveView.Toggles(Key.Right, FlowDirection.LeftToRight, isExpanded: true));
Assert.True(ArchiveView.Toggles(Key.Left, FlowDirection.LeftToRight, isExpanded: true));
Assert.True(ArchiveView.Toggles(Key.Left, FlowDirection.RightToLeft, isExpanded: false), "a mirrored tree opens with Left");
Assert.True(ArchiveView.Toggles(Key.Right, FlowDirection.RightToLeft, isExpanded: true), "and closes with Right");
Assert.False(ArchiveView.Toggles(Key.Right, FlowDirection.RightToLeft, isExpanded: false));
Assert.True(ArchiveView.Toggles(Key.Enter, FlowDirection.RightToLeft, isExpanded: true));
Assert.False(ArchiveView.Toggles(Key.Down, FlowDirection.LeftToRight, isExpanded: false));
}
/// <summary>Every button of the screen has a name screen readers can announce, menu buttons with drawn chevrons included.</summary>
private static void AssertEveryButtonIsNamed(ScreenSmokeTests.SampleApp app)
{
foreach (var button in app.FindAll<ButtonBase>().Where(b => b.IsVisible && b.Focusable && IsInArchive(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");
}
}
/// <summary>
/// Beside the 200 px rail at the 1200 px minimum (owner review 1, R1), in every shipped language: a year row shows its year
/// whole (its figures give way, and stay inside the row).
/// </summary>
[Test]
public Task YearRowsKeepTheirYearAtTheMinimumWidthInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
await ArchiveScenes.ShowAsync(app.Shell, "overview");
var window = app.Window;
window.Width = 1200;
window.Height = 788;
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
var years = TreeItems(app).Where(i => ((ArchiveTreeRowViewModel)i.DataContext).IsYear).ToList();
Assert.True(years.Count > 0, $"{language}: year rows show");
foreach (var item in years)
{
var row = (ArchiveTreeRowViewModel)item.DataContext;
var texts = Descendants<TextBlock>(item).Where(t => t.IsVisible).ToList();
var title = texts.Single(t => t.Text == row.Title);
// A copy with the same font, measured by the same layout engine, needs no more room than the year got (layout
// rounding aside: a cut year keeps barely half of it).
var probe = new TextBlock
{
Text = title.Text,
FontFamily = title.FontFamily,
FontSize = title.FontSize,
FontStyle = title.FontStyle,
FontWeight = title.FontWeight,
FontStretch = title.FontStretch,
FlowDirection = title.FlowDirection,
Language = title.Language,
};
TextOptions.SetTextFormattingMode(probe, TextOptions.GetTextFormattingMode(title));
probe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
Assert.True(probe.DesiredSize.Width <= title.ActualWidth + 1, $"{language}: the year '{row.Title}' is cut ({title.ActualWidth:0} of {probe.DesiredSize.Width:0} px)");
var (left, right) = Span(item, window);
foreach (var text in texts)
{
var (start, end) = Span(text, window);
Assert.True(start >= left - 0.5 && end <= right + 0.5, $"{language}: '{text.Text}' spans {start:0}–{end:0} px, its row {left:0}–{right:0} px");
}
}
}
}
finally
{
UiLanguage.Apply("en");
}
});
/// <summary>The left and right edges of an element in window coordinates, whichever way the window reads.</summary>
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 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;
}
}
/// <summary>A dialog that has not failed shows no error line.</summary>
private static void AssertNoErrorShown(ScreenSmokeTests.SampleApp app) =>
Assert.False(app.FindAll<StatusGlyph>().Any(g => g.IsVisible && g.Kind == StatusKind.Error && IsInArchive(g)), "no error state before anything failed");
private static ListBox Tree(ScreenSmokeTests.SampleApp app) => app.FindAll<ListBox>().Single(l => l.Name == "Tree");
private static IEnumerable<ListBoxItem> TreeItems(ScreenSmokeTests.SampleApp app) =>
app.FindAll<ListBoxItem>().Where(i => i.IsVisible && i.DataContext is ArchiveTreeRowViewModel);
private static Button SetButton(ScreenSmokeTests.SampleApp app) =>
Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => b.IsVisible && b.ToolTip as string == Loc.L("Tooltips.Archive.Set")), "the set filter button");
private static bool IsInArchive(DependencyObject element)
{
for (var node = VisualTreeHelper.GetParent(element); node is not null; node = VisualTreeHelper.GetParent(node))
{
if (node is ArchiveView) return true;
}
return false;
}
private static TextBlock TextFor(ScreenSmokeTests.SampleApp app, string text) =>
Assert.NotNull(app.FindAll<TextBlock>().FirstOrDefault(t => t.IsVisible && t.Text == text && IsInArchive(t)), $"a visible text '{text}'");
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");
}