using System.IO;
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 Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Editor;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Data.Archiving;
using Chronos.Testing;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Tests.Windows;
///
/// The Edit section's picker (owner review 1, R7) on the capture sample: one list of this PC's and the server's
/// sequences, the search, the empty states, opening with Enter or a double-click, Change sequence and Esc, a sequence
/// that cannot open, the open sequence deleted, and the open sequence's unsaved edit, kept or discarded, asked about once.
///
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class EditSectionTests
{
[Test]
public Task ThePickerListsThisPcAndTheServerNewestFirstAndSearches() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
await app.Shell.Services.Server.RestoreAsync();
await app.Shell.Services.Sync.RefreshAsync();
await app.Shell.Library.RefreshAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await app.ExpectAsync("edit-picker");
Assert.True(section.ShowsPicker, "no sequence open: the picker shows");
Assert.Equal(Text("Shell.Nav.Edit"), section.Title);
var items = section.Picker.Items.ToList();
Assert.True(items.Count > 10, "the sample's sequences");
var captures = items.Select(i => i.Sequence.FirstCapture).ToList();
for (var i = 1; i < captures.Count; i++)
Assert.True(captures[i] is not { } after || (captures[i - 1] is { } before && before >= after), $"newest first at row {i}");
Assert.Contains(items, i => i.IsRemote && i.Title == "Sunrise over Superga");
Assert.Same(items[0], section.Picker.Selected, "nothing edited yet: the first row is selected");
// The search narrows the list a moment after the last key; no match offers Clear search.
await SearchAsync(section, "harbour");
Assert.True(section.Picker.Items.Count is > 0 and < 5, "only the harbour sequence");
Assert.True(section.Picker.Items.All(i => i.Title.Contains("Harbour", StringComparison.OrdinalIgnoreCase)));
await SearchAsync(section, "no such sequence");
Assert.True(section.Picker.IsNoMatch);
Assert.False(section.Picker.IsEmptyLibrary);
var shown = section.Picker.Loading;
section.Picker.ClearCommand.Execute(null);
await DebouncedAsync(section, shown);
Assert.Equal(items.Count, section.Picker.Items.Count);
});
[Test]
public Task AnEmptyLibraryOffersImport() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
Assert.True(section.Picker.IsEmptyLibrary);
Assert.False(section.Picker.OpenCommand.CanExecute(null));
section.OpenImportCommand.Execute(null);
Assert.Equal(SectionKey.Import, app.Shell.Current.Key);
});
[Test]
public Task EnterOpensTheSequenceAndChangeSequenceComesBackToTheSameEditor() => ScreenHost.RunAsync(async () =>
{
var saves = 0;
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(saveSettings: () => saves++);
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
// The search box has the keyboard; Enter there opens the selected row (the first).
var first = section.Picker.Items[0];
var search = Find(app.Window).Single(t => t.Name == "Search");
Assert.Same(search, FocusManager.GetFocusedElement(app.Window), "the search box has the keyboard when the picker shows");
Press(search, Key.Enter);
var editor = await OpenedAsync(section);
Assert.Equal(first.Id, editor.Session.Content.Sequence.Id);
Assert.False(section.ShowsPicker);
Assert.Equal(first.Id, app.Shell.Services.Settings.LastEditedSequence);
Assert.True(saves > 0, "the sequence edited last is written");
await SettleAsync(app.Window);
// Change sequence: the picker covers the editor, which stays open and laid out; the open sequence is selected.
Assert.True(section.ChangeSequenceCommand.CanExecute(null), "the open has ended");
section.ChangeSequenceCommand.Execute(null);
await section.Picker.Loading;
await SettleAsync(app.Window);
Assert.True(section.ShowsPicker && section.IsPicking);
Assert.Same(search, FocusManager.GetFocusedElement(app.Window), "the search box has the keyboard again");
Assert.Equal(first.Id, section.Picker.Selected?.Id);
Assert.Equal(Text("Shell.Nav.Edit"), section.Title, "the window title names the section while choosing");
var root = Find(app.Window).Single(g => g.Name == "EditorRoot");
Assert.Greater(root.ActualWidth, 0, "the editor stays laid out behind the picker");
// Esc with an empty search goes back to the same editor.
Press(search, Key.Escape);
Assert.False(section.IsPicking);
Assert.Same(editor, section.Editor);
// Coming back to Edit leaves a choice on screen; asking for the open sequence (the Library's Open) ends it.
Assert.True(section.ChangeSequenceCommand.CanExecute(null));
section.ChangeSequenceCommand.Execute(null);
app.Shell.Navigate(SectionKey.Library);
app.Shell.Navigate(SectionKey.Edit);
Assert.True(section.IsPicking, "coming back to Edit leaves the choice on screen");
app.Shell.Navigate(SectionKey.Library);
app.Shell.OpenSequence(first.Id);
Assert.Equal(SectionKey.Edit, app.Shell.Current.Key);
Assert.False(section.IsPicking, "opening the open sequence shows it");
Assert.Same(editor, section.Editor);
// Also while Edit is on screen (a toast's Open, a project file of the open sequence).
section.ChangeSequenceCommand.Execute(null);
app.Shell.OpenSequence(first.Id);
Assert.False(section.IsPicking);
Assert.Same(editor, section.Editor);
});
/// Enter typed within the search's 250 ms opens a match of what was typed, not the row selected before.
[Test]
public Task EnterRightAfterTypingOpensAMatch() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
Assert.False(section.Picker.Selected!.Title.Contains("Langhe", StringComparison.OrdinalIgnoreCase), "another sequence is selected first");
var search = Find(app.Window).Single(t => t.Name == "Search");
section.Picker.SearchText = "langhe";
Press(search, Key.Enter);
var editor = await OpenedAsync(section);
Assert.True(editor.Title.Contains("Langhe", StringComparison.OrdinalIgnoreCase), $"opened '{editor.Title}'");
});
/// A double-click on a row opens it, in the picker and in the Library's list and grid (the row takes the mouse-down).
[Test]
public Task ADoubleClickOnARowOpensIt() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
var list = Find(app.Window).Single(l => l.Name == "List" && l.IsVisible);
var item = section.Picker.Items.Skip(1).First(i => !i.IsRemote);
DoubleClick(Cell(list, item));
var editor = await OpenedAsync(section);
Assert.Equal(item.Id, editor.Session.Content.Sequence.Id, "the row double-clicked opened, not the one selected");
// The Library's list and grid: a double-click opens the sequence in Edit.
foreach (var grid in new[] { false, true })
{
app.Shell.Navigate(SectionKey.Library);
await app.Shell.Library.RefreshAsync();
app.Shell.Library.LayoutIndex = grid ? 0 : 1;
await SettleAsync(app.Window);
var name = grid ? "CardGrid" : "RowList";
var library = Find(app.Window).Single(l => l.Name == name && l.IsVisible);
var target = app.Shell.Library.Items.First(i => !i.IsRemote && i.Id != app.Shell.CurrentSequenceId);
DoubleClick(Cell(library, target));
Assert.Equal(SectionKey.Edit, app.Shell.Current.Key, grid ? "a card" : "a row");
Assert.Equal(target.Id, app.Shell.CurrentSequenceId);
await OpenedAsync(section, target.Id);
}
});
///
/// A sequence that cannot open (gone from the index, no server to ask) leaves the open one open behind the picker, with
/// Cancel still there, and the open one again the sequence asked for (owner review 1, R7 review).
///
[Test]
public Task ASequenceThatCannotOpenLeavesTheOpenOneOpen() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
var first = section.Picker.Items.First(i => !i.IsRemote);
await section.PickAsync(first);
var editor = await OpenedAsync(section);
section.ChangeSequenceCommand.Execute(null);
await section.Picker.Loading;
// The window shows and clears the toasts: they are counted as they come.
var errors = 0;
app.Shell.PendingToasts.CollectionChanged += (_, e) => errors += e.NewItems?.OfType().Count(t => t.IsError) ?? 0;
var gone = new SequenceItem(first.Sequence with { Id = Guid.CreateVersion7() }, null);
await section.PickAsync(gone);
Assert.Same(editor, section.Editor, "the open sequence stayed open");
Assert.True(section.IsPicking && section.CanCancelPick, "the choice goes on, and Cancel goes back");
Assert.Equal(first.Id, app.Shell.CurrentSequenceId, "the open sequence is again the one asked for");
Assert.Equal(1, errors, "the failure is reported once");
section.CancelPickCommand.Execute(null);
app.Shell.Navigate(SectionKey.Library);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
Assert.Same(editor, section.Editor);
Assert.Equal(1, errors, "coming back neither tries again nor reports it again");
});
/// The open sequence deleted from the Library: the editor closes, and coming back to Edit shows the picker, not a failed open.
[Test]
public Task DeletingTheOpenSequenceLeavesThePicker() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
var first = section.Picker.Items.First(i => !i.IsRemote);
await section.PickAsync(first);
await OpenedAsync(section);
var row = Assert.NotNull(await app.Shell.Services.Database!.Sequences.GetAsync(first.Id));
app.Shell.Navigate(SectionKey.Library);
Assert.True(await SequenceDeletion.CloseEditorAsync(app.Shell, new DeletePlan([new DeleteStep(row, null, 0, 0)], [])));
Assert.Null(section.Editor, "the editor closed");
Assert.Null(app.Shell.CurrentSequenceId, "the deleted sequence is no longer asked for");
var errors = 0;
app.Shell.PendingToasts.CollectionChanged += (_, e) => errors += e.NewItems?.OfType().Count(t => t.IsError) ?? 0;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
Assert.True(section.ShowsPicker);
Assert.False(section.IsLoading);
Assert.Equal(0, errors, "no failed open");
});
///
/// The sequence edited last is selected and in view even when it is older than the first page (read on until it comes),
/// and with a sequence open the open one is (owner review 1, R7 review).
///
[Test]
public Task TheSequenceEditedLastIsSelectedAndShownBeyondTheFirstPage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
var oldest = section.Picker.Items.Last(i => !i.IsRemote);
Assert.True(section.Picker.Items.IndexOf(oldest) > 20, "an old sequence, far down the list");
app.Shell.Services.Settings.LastEditedSequence = oldest.Id;
section.Picker.PageSize = 5;
await section.Picker.ReloadAsync();
await SettleAsync(app.Window);
Assert.Equal(oldest.Id, section.Picker.Selected?.Id, "read on until the sequence edited last is listed");
var list = Find(app.Window).Single(l => l.Name == "List" && l.IsVisible);
var row = Assert.NotNull(list.ItemContainerGenerator.ContainerFromItem(section.Picker.Selected!) as ListBoxItem, "its row is realised");
var top = row.TranslatePoint(new Point(0, 0), list).Y;
Assert.True(top >= -0.5 && top + row.ActualHeight <= list.ActualHeight + 0.5, "and scrolled into view");
});
///
/// At 1200 px in every language each picker row reads as its title to screen readers, and its states (Analysed,
/// Proxies, Remote) are whole inside the row.
///
[Test]
public Task PickerRowsReadAsTheirTitleAndKeepTheirStatesWholeInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
await app.Sample.FillAsync();
await app.Shell.Services.Server.RestoreAsync();
await app.Shell.Services.Sync.RefreshAsync();
await app.Shell.Library.RefreshAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await section.Picker.ReloadAsync();
await SettleAsync(app.Window);
var rows = Find(app.Window).Where(r => r.IsVisible && r.DataContext is SequenceItem).ToList();
Assert.True(rows.Count > 5, $"{language}: rows show");
Assert.True(rows.Any(r => ((SequenceItem)r.DataContext).IsRemote), $"{language}: a server row shows");
foreach (var row in rows)
{
var item = (SequenceItem)row.DataContext;
Assert.Equal(item.Title, UIElementAutomationPeer.CreatePeerForElement(row).GetName(), $"{language}: the row reads as its title");
var states = Find(row).Single(c => c.ItemsSource is not null && !ReferenceEquals(c, row));
var a = states.TranslatePoint(new Point(0, 0), row).X;
var b = states.TranslatePoint(new Point(states.ActualWidth, 0), row).X;
Assert.True(double.Min(a, b) >= row.Padding.Left - 0.5 && double.Max(a, b) <= row.ActualWidth - row.Padding.Right + 0.5,
$"{language}: the states of '{item.Title}' span {double.Min(a, b):0}–{double.Max(a, b):0} px in a {row.ActualWidth:0} px row");
}
}
}
finally
{
UiLanguage.Apply("en");
}
});
[Test]
public Task AnUnsavedEditIsAskedAboutOnceAndKeptOrDiscarded() => ScreenHost.RunAsync(async () =>
{
var dialogs = new CountingDialogs { Discard = false };
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(dialogs: dialogs);
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
var content = EditorFixture.Content(EditorFixture.Sunset);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client);
section.Attach(editor);
app.Shell.KeepSequence(content.Sequence.Id);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
section.ChangeSequenceCommand.Execute(null);
await section.Picker.Loading;
var other = section.Picker.Items.First(i => !i.IsRemote);
// The archive stays offline: Keep editing keeps the open sequence, which stays the one asked for.
editor.Session.Edit(p => p with { HeroFrame = 2 });
source.FailSaves = new IOException("The archive drive is gone");
await section.PickAsync(other);
Assert.Equal(1, dialogs.Asked);
Assert.Same(editor, section.Editor);
Assert.False(section.IsPicking);
Assert.Equal(content.Sequence.Id, app.Shell.CurrentSequenceId);
app.Shell.Navigate(SectionKey.Library);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
Assert.Equal(1, dialogs.Asked, "coming back to Edit does not ask again");
Assert.Same(editor, section.Editor, "nor opens the other sequence");
Assert.Equal(content.Sequence.Id, app.Shell.CurrentSequenceId);
// Discard: the archive answers again while the question is open (retries would write the edit then), yet the edit is
// dropped unwritten and the other sequence opens.
dialogs.Discard = true;
dialogs.WhileAsked = () =>
{
source.FailSaves = null;
PumpFor(TimeSpan.FromSeconds(2.5));
};
editor.Session.Edit(p => p with { HeroFrame = 3 });
var saves = source.Saves;
await section.PickAsync(other);
Assert.Equal(2, dialogs.Asked);
Assert.Equal(other.Id, section.Editor?.Session.Content.Sequence.Id);
Assert.Equal(saves, source.Saves, "nothing was written once the user chose to discard");
Assert.NotEqual(3, source.Stored.HeroFrame);
});
/// Types in the search and waits for the list it reads.
private static async Task SearchAsync(SequenceViewModel section, string text)
{
var before = section.Picker.Loading;
section.Picker.SearchText = text;
await DebouncedAsync(section, before);
}
/// Waits for the search's own read (its 250 ms timer fires), then for the list it reads, whatever the machine's speed.
private static async Task DebouncedAsync(SequenceViewModel section, Task before)
{
for (var i = 0; i < 250 && ReferenceEquals(section.Picker.Loading, before); i++) await Task.Delay(20);
Assert.False(ReferenceEquals(section.Picker.Loading, before), "the search read the list again");
await section.Picker.Loading;
}
/// Waits until a sequence (, else any) is open and the whole open, Enter included, has ended.
private static async Task OpenedAsync(SequenceViewModel section, Guid? id = null)
{
bool Busy() => section.Editor is not { } editor || (id is { } wanted && editor.Session.Content.Sequence.Id != wanted) || section.IsLoading
|| ((AsyncRelayCommand)section.Picker.SearchOpenCommand).IsRunning || ((AsyncRelayCommand)section.Picker.OpenItemCommand).IsRunning;
for (var i = 0; i < 400 && Busy(); i++) await Task.Delay(50);
Assert.False(Busy(), "the sequence opened");
await section.Editor!.WhenIdleAsync(TimeSpan.FromSeconds(30));
return section.Editor;
}
private static void Press(UIElement target, Key key) =>
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.PreviewKeyDownEvent });
/// A left double-click as the mouse raises it: a mouse-down with a click count of 2 on a text of the row (else on the row).
private static void DoubleClick(ListBoxItem row)
{
UIElement target = Find(row).FirstOrDefault(t => t.IsVisible && t.ActualWidth > 0) as UIElement ?? row;
var down = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left) { RoutedEvent = Mouse.MouseDownEvent };
typeof(MouseButtonEventArgs).GetProperty(nameof(MouseButtonEventArgs.ClickCount))!.SetValue(down, 2);
target.RaiseEvent(down);
}
/// The row of , scrolled into view.
private static ListBoxItem Cell(ListBox list, object item)
{
list.ScrollIntoView(item);
list.UpdateLayout();
return Assert.NotNull(list.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem, "the row is realised");
}
/// Runs the dispatcher for (a modal dialog's loop: timers and saves go on meanwhile).
private static void PumpFor(TimeSpan time)
{
var frame = new DispatcherFrame();
var timer = new DispatcherTimer(time, DispatcherPriority.Normal, (_, _) => frame.Continue = false, Dispatcher.CurrentDispatcher);
timer.Start();
Dispatcher.PushFrame(frame);
timer.Stop();
}
private static string Text(string key) => Loc.L(key);
private static async Task SettleAsync(Window window)
{
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
private static List Find(DependencyObject root)
where T : DependencyObject
{
var found = new List();
var stack = new Stack([root]);
while (stack.TryPop(out var node))
{
if (node is T match) found.Add(match);
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) stack.Push(VisualTreeHelper.GetChild(node, i));
}
return found;
}
/// Counts the confirmations asked and answers them as told (true discards the unsaved edit).
private sealed class CountingDialogs : IAppDialogs
{
public bool Discard { get; set; }
public int Asked { get; private set; }
/// Runs while the question is open (before the answer), as the user reads it.
public Action? WhileAsked { get; set; }
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request)
{
Asked++;
WhileAsked?.Invoke();
return Discard;
}
public bool SignIn(string server, string? username, Func> signIn) => false;
}
}