refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,97 @@
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Windows;
|
||||
|
||||
/// <summary>The desktop diagnostics bundle: every entry present, the saved server token and passwords never inside.</summary>
|
||||
[WindowsOnly]
|
||||
public sealed class DiagnosticsBundleTests(TestContext context)
|
||||
{
|
||||
private const string Token = "AQAAANCMnd8BFdERjHoAwE-saved-token";
|
||||
|
||||
[Test]
|
||||
public async Task TheBundleCarriesReportsAndLogsButNoSecrets()
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
var settings = new AppSettings { Language = "en", ServerUrl = "https://nas.local:8443", ServerUsername = "alice", ProtectedToken = Token };
|
||||
var services = new AppServices(environment, settings, () => { }, new NoDialogs()) { Encoders = new OneEncoder() };
|
||||
await File.WriteAllTextAsync(Path.Combine(environment.LogDirectory, "chronos-20261002.log"), $"signed in with password={Token}\n");
|
||||
|
||||
var path = await DiagnosticsBundle.CreateAsync(services, context.CreateTempDirectory(), ["Self-test H.264 Test: passed"]);
|
||||
|
||||
using var zip = ZipFile.OpenRead(path);
|
||||
var texts = zip.Entries.ToDictionary(e => e.FullName, e =>
|
||||
{
|
||||
using var reader = new StreamReader(e.Open());
|
||||
return reader.ReadToEnd();
|
||||
});
|
||||
Assert.SequenceEqual(new[] { "codecs.txt", "environment.txt", "jobs-failed.json", "logs/chronos-20261002.log", "settings.json" },
|
||||
texts.Keys.Order(StringComparer.Ordinal));
|
||||
foreach (var (name, text) in texts) Assert.False(text.Contains(Token, StringComparison.Ordinal), $"{name} leaks the token");
|
||||
Assert.Contains("Self-test H.264 Test: passed", texts["environment.txt"]);
|
||||
Assert.Contains("Test encoder", texts["codecs.txt"]);
|
||||
Assert.Contains("\"ServerUsername\": \"alice\"", texts["settings.json"]);
|
||||
Assert.Contains("\"ProtectedToken\": \"[removed]\"", texts["settings.json"]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task BundlesNeverOverwriteEachOtherAndAFailedOneLeavesNothing()
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs()) { Encoders = new OneEncoder() };
|
||||
await File.WriteAllTextAsync(Path.Combine(environment.LogDirectory, "chronos-20261002.log"), "started\n");
|
||||
var folder = context.CreateTempDirectory();
|
||||
|
||||
var first = await DiagnosticsBundle.CreateAsync(services, folder);
|
||||
var second = await DiagnosticsBundle.CreateAsync(services, folder);
|
||||
Assert.NotEqual(first, second);
|
||||
Assert.SequenceEqual(new[] { first, second }.Order(StringComparer.Ordinal), Directory.GetFiles(folder).Order(StringComparer.Ordinal));
|
||||
|
||||
// The encoder inventory runs after the job query and before the zip is written: cancelling there fails the
|
||||
// bundle half-way, once its temporary file exists.
|
||||
using var cts = new CancellationTokenSource();
|
||||
services.Encoders = new OneEncoder(cts.Cancel);
|
||||
var empty = context.CreateTempDirectory();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => DiagnosticsBundle.CreateAsync(services, empty, ct: cts.Token));
|
||||
Assert.Empty(Directory.GetFiles(empty));
|
||||
}
|
||||
finally
|
||||
{
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class OneEncoder(Action? onDetect = null) : IEncoderInventory
|
||||
{
|
||||
public string? Adapter() => "Test adapter";
|
||||
|
||||
public IReadOnlyList<EncoderRow> Detect()
|
||||
{
|
||||
onDetect?.Invoke();
|
||||
return [new EncoderRow("H.264", "Test encoder", null, EncoderSource.MediaFoundation, true, false, 4096, 2304, VideoCodec.H264)];
|
||||
}
|
||||
|
||||
public Task<SelfTestResult> SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(new SelfTestResult(true, 100, null));
|
||||
}
|
||||
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<SequenceView>("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<TextBox>(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<Grid>(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);
|
||||
});
|
||||
|
||||
/// <summary>Enter typed within the search's 250 ms opens a match of what was typed, not the row selected before.</summary>
|
||||
[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<TextBox>(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}'");
|
||||
});
|
||||
|
||||
/// <summary>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).</summary>
|
||||
[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<ListBox>(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<ListBox>(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);
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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<Toast>().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");
|
||||
});
|
||||
|
||||
/// <summary>The open sequence deleted from the Library: the editor closes, and coming back to Edit shows the picker, not a failed open.</summary>
|
||||
[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<Toast>().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");
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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<ListBox>(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");
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<ListBoxItem>(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<ItemsControl>(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);
|
||||
});
|
||||
|
||||
/// <summary>Types <paramref name="text"/> in the search and waits for the list it reads.</summary>
|
||||
private static async Task SearchAsync(SequenceViewModel section, string text)
|
||||
{
|
||||
var before = section.Picker.Loading;
|
||||
section.Picker.SearchText = text;
|
||||
await DebouncedAsync(section, before);
|
||||
}
|
||||
|
||||
/// <summary>Waits for the search's own read (its 250 ms timer fires), then for the list it reads, whatever the machine's speed.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Waits until a sequence (<paramref name="id"/>, else any) is open and the whole open, Enter included, has ended.</summary>
|
||||
private static async Task<EditorViewModel> 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 });
|
||||
|
||||
/// <summary>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).</summary>
|
||||
private static void DoubleClick(ListBoxItem row)
|
||||
{
|
||||
UIElement target = Find<TextBlock>(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);
|
||||
}
|
||||
|
||||
/// <summary>The row of <paramref name="item"/>, scrolled into view.</summary>
|
||||
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");
|
||||
}
|
||||
|
||||
/// <summary>Runs the dispatcher for <paramref name="time"/> (a modal dialog's loop: timers and saves go on meanwhile).</summary>
|
||||
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<T> Find<T>(DependencyObject root)
|
||||
where T : DependencyObject
|
||||
{
|
||||
var found = new List<T>();
|
||||
var stack = new Stack<DependencyObject>([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;
|
||||
}
|
||||
|
||||
/// <summary>Counts the confirmations asked and answers them as told (true discards the unsaved edit).</summary>
|
||||
private sealed class CountingDialogs : IAppDialogs
|
||||
{
|
||||
public bool Discard { get; set; }
|
||||
|
||||
public int Asked { get; private set; }
|
||||
|
||||
/// <summary>Runs while the question is open (before the answer), as the user reads it.</summary>
|
||||
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<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Automation;
|
||||
using System.Windows.Automation.Peers;
|
||||
using System.Windows.Automation.Provider;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.DesignTime;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Sections;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Theming;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Shows the real main window off screen (section templates, client styles) on the sample data used by
|
||||
/// <c>--capture</c> and renders every screen in both themes: catches XAML, resource, template and view-model wiring
|
||||
/// errors that compile cleanly. Mirrors <see cref="ScreenCapture"/> step by step.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
public sealed class ScreenSmokeTests
|
||||
{
|
||||
[Test]
|
||||
public Task EveryScreenRendersWithSampleDataInBothThemes() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
|
||||
// First run: empty index, the welcome dialog over the empty Library.
|
||||
Assert.True(shell.Library.IsLibraryEmpty, "an empty index shows the empty Library");
|
||||
Assert.False(shell.IsJobActive);
|
||||
shell.ShowWelcome();
|
||||
shell.Welcome!.ShowDiscovered(new DiscoveredServer("Studio NAS", "https://nas.local:8443"));
|
||||
await app.ExpectAsync<WelcomeView>("welcome");
|
||||
Assert.True(shell.Welcome.IsLocal, "a local archive is the default choice");
|
||||
shell.CompleteWelcome();
|
||||
Assert.False(shell.IsWelcomeOpen);
|
||||
await app.ExpectAsync<LibraryView>("library-empty");
|
||||
shell.Navigate(SectionKey.Server);
|
||||
await app.ExpectAsync<ServerView>("server-signedout");
|
||||
Assert.False(shell.Server.IsConnected);
|
||||
|
||||
// A populated archive, jobs in every state, a signed-in server.
|
||||
await app.Sample.FillAsync();
|
||||
await shell.Library.RefreshAsync();
|
||||
await shell.Jobs.ReloadAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
shell.About.SetResult(null);
|
||||
await shell.Settings.DetectEncodersAsync();
|
||||
await shell.Settings.SelfTestAsync();
|
||||
|
||||
shell.Navigate(SectionKey.Library);
|
||||
Assert.Equal(36, shell.Library.Items.Count);
|
||||
Assert.True(shell.Library.IsGrid);
|
||||
await app.ExpectAsync<LibraryView>("library", waitForThumbnails: true);
|
||||
Assert.NotEmpty(app.FindAll<SequenceCard>());
|
||||
// The newest sequence is a RAW: its card shows the embedded preview.
|
||||
Assert.Equal("Harbour sunset", shell.Library.Items[0].Title);
|
||||
Assert.NotNull(shell.Library.Items[0].Thumbnail, "embedded preview of the first card");
|
||||
|
||||
shell.Library.Items[0].IsSelected = true;
|
||||
Assert.True(shell.Library.IsSingleSelection);
|
||||
await app.ExpectAsync<LibraryView>("library-selection", waitForThumbnails: true);
|
||||
shell.Library.LayoutIndex = 1;
|
||||
Assert.True(shell.Library.IsList);
|
||||
await app.ExpectAsync<LibraryView>("library-list", waitForThumbnails: true);
|
||||
shell.Library.LayoutIndex = 0;
|
||||
shell.Library.ClearSelectionCommand.Execute(null);
|
||||
Assert.Equal(0, shell.Library.SelectionCount);
|
||||
|
||||
shell.Navigate(SectionKey.Jobs);
|
||||
Assert.Equal(9, shell.Jobs.Rows.Count);
|
||||
Assert.True(shell.IsJobActive, "running jobs show in the job bar");
|
||||
shell.Jobs.Rows[0].IsExpanded = true;
|
||||
await app.ExpectAsync<JobsView>("jobs");
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
Assert.True(shell.Server.IsConnected, "the saved session is restored");
|
||||
await app.ExpectAsync<ServerView>("server");
|
||||
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
Assert.Equal(3, shell.Settings.PreviewNames.Count);
|
||||
Assert.Equal(6, shell.Settings.Encoders.Count);
|
||||
foreach (var page in Enum.GetValues<SettingsPage>())
|
||||
{
|
||||
shell.Settings.Page = page;
|
||||
await app.ExpectAsync<SettingsView>("settings-" + page.ToString().ToLowerInvariant());
|
||||
}
|
||||
|
||||
shell.Navigate(SectionKey.About);
|
||||
await app.ExpectAsync<AboutView>("about");
|
||||
|
||||
shell.Navigate(SectionKey.Import);
|
||||
await app.ExpectAsync<ImportView>("import");
|
||||
// Edit with no sequence open: the picker lists the sequences (owner review 1, R7).
|
||||
shell.Navigate(SectionKey.Edit);
|
||||
await shell.Sequence.Picker.Loading;
|
||||
await app.ExpectAsync<SequenceView>("edit-picker");
|
||||
Assert.True(shell.Sequence.ShowsPicker);
|
||||
shell.Navigate(SectionKey.Archive);
|
||||
await app.ExpectAsync<ArchiveView>("archive");
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheShellFollowsTheLanguage() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await SampleApp.StartAsync();
|
||||
var english = app.Shell.Library.Title;
|
||||
UiLanguage.Apply("it");
|
||||
try
|
||||
{
|
||||
Assert.NotEqual(english, app.Shell.Library.Title);
|
||||
await app.ExpectAsync<LibraryView>("library-empty-it");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
Assert.Equal(english, app.Shell.Library.Title);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task ArabicMirrorsTheShellFromStartButNotItsPicturesOrLogo() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
// The language is applied before the window exists, as at start-up with Arabic saved in the settings.
|
||||
await using var app = await SampleApp.StartAsync("ar", firstRun: true);
|
||||
try
|
||||
{
|
||||
var window = app.Window;
|
||||
Assert.Equal(FlowDirection.RightToLeft, window.FlowDirection, "the main window opens mirrored");
|
||||
var rail = (FrameworkElement)window.FindName("Rail");
|
||||
Assert.Equal(FlowDirection.RightToLeft, rail.FlowDirection, "the rail mirrors with the window");
|
||||
// The window's content carries the mirror (a capture of it alone reads right to left, as on screen).
|
||||
Assert.Greater(rail.TranslatePoint(new Point(rail.ActualWidth / 2, 0), window).X, window.ActualWidth / 2, "the rail starts on the right");
|
||||
|
||||
// The first-run dialog keeps the shell behind it out of reach.
|
||||
Assert.True(app.Shell.IsWelcomeOpen);
|
||||
Assert.False(rail.IsEnabled, "the rail behind the first-run dialog takes no input");
|
||||
app.Shell.CompleteWelcome();
|
||||
Assert.True(rail.IsEnabled);
|
||||
|
||||
var id = await app.Sample.FillEditorAsync();
|
||||
app.Shell.OpenSequence(id);
|
||||
await app.Shell.Sequence.OpenAsync(id);
|
||||
var editor = Assert.NotNull(app.Shell.Sequence.Editor);
|
||||
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
|
||||
await app.ExpectAsync<SequenceView>("edit-ar");
|
||||
|
||||
// Directional glyphs follow the reading direction; the others, the logo, the picture and the charts do not.
|
||||
var back = Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => b.IsVisible && ReferenceEquals(b.Command, editor.BackCommand)), "the editor's Back button");
|
||||
var arrow = Descendants<Icon>(back).Single();
|
||||
Assert.True(arrow.Glyph!.IsDirectional);
|
||||
Assert.Equal(FlowDirection.RightToLeft, arrow.FlowDirection, "Back points the way Arabic reads");
|
||||
foreach (var icon in app.FindAll<Icon>().Where(i => i.Glyph is { IsDirectional: false } && Bidi.GetIsDirectional(i) is null))
|
||||
Assert.Equal(FlowDirection.LeftToRight, icon.FlowDirection, "a glyph that does not point anywhere keeps its drawing");
|
||||
Assert.True(app.FindAll<BrandMarkIcon>().All(m => m.FlowDirection == FlowDirection.LeftToRight), "the logo never mirrors");
|
||||
var viewport = app.FindAll<PreviewViewport>().Single(v => v.IsVisible);
|
||||
Assert.Equal(FlowDirection.LeftToRight, ((FrameworkElement)viewport.Template.FindName(PreviewViewport.PartSurface, viewport)).FlowDirection, "the photo is not mirrored");
|
||||
Assert.Equal(FlowDirection.RightToLeft, ((FrameworkElement)viewport.Template.FindName(PreviewViewport.PartTools, viewport)).FlowDirection, "the preview tools follow the layout");
|
||||
Assert.True(app.FindAll<DrawingElement>().All(d => d.FlowDirection == FlowDirection.LeftToRight), "charts, filmstrip and curves keep their time axis");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await app.Shell.Sequence.CloseAsync();
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task ToastsDrawSpeakAndCloseAfterTheirAction() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await SampleApp.StartAsync();
|
||||
app.Shell.CompleteWelcome();
|
||||
var ran = false;
|
||||
app.Shell.ShowToast(new Toast { Title = "Harbour sunset rendered", ActionText = "Open", ActionCommand = new RelayCommand(() => ran = true) });
|
||||
await app.ExpectAsync<LibraryView>("library-toast");
|
||||
var host = app.Window.Toasts;
|
||||
Assert.Equal(1, host.Toasts.Count);
|
||||
var toast = Assert.NotNull(host.ItemContainerGenerator.ContainerFromIndex(0) as FrameworkElement, "the toast's container");
|
||||
Assert.Greater(toast.ActualHeight, 0, "the toast is drawn");
|
||||
Assert.Equal("Harbour sunset rendered", AutomationProperties.GetName(toast));
|
||||
var dismiss = Descendants<Button>(toast).Single(b => ReferenceEquals(b.Command, ToastHost.DismissCommand));
|
||||
Assert.Equal(Loc.L("Tooltips.Common.Dismiss"), AutomationProperties.GetName(dismiss));
|
||||
|
||||
var action = Descendants<Button>(toast).Single(b => b.IsVisible && !ReferenceEquals(b.Command, ToastHost.DismissCommand));
|
||||
Assert.True(action.Command!.CanExecute(null));
|
||||
((IInvokeProvider)new ButtonAutomationPeer(action)).Invoke();
|
||||
await app.ExpectAsync<LibraryView>("library-toast-done");
|
||||
Assert.True(ran, "the action ran");
|
||||
Assert.Equal(0, host.Toasts.Count, "the toast closes once its action has run");
|
||||
|
||||
// A failure interrupts the screen reader (assertive); a notice waits its turn.
|
||||
Assert.False(await ArchiveActions.TryAsync(app.Shell, _ => throw new IOException("The archive drive is gone")));
|
||||
Assert.True(host.Toasts.Single().IsError, "a failed archive action is announced at once");
|
||||
app.Shell.Notify("Harbour sunset rendered");
|
||||
Assert.False(host.Toasts[^1].IsError, "a notice is announced in turn");
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheChromeAndTheJobBarHaveNamesAndStates() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await SampleApp.StartAsync();
|
||||
app.Shell.CompleteWelcome();
|
||||
await app.ExpectAsync<LibraryView>("library-empty");
|
||||
var window = app.Window;
|
||||
var captions = Descendants<Button>(window).Where(b => b.Command is RoutedCommand).ToList();
|
||||
Assert.Equal(Loc.L("Tooltips.Window.Minimize"), AutomationProperties.GetName(captions.Single(b => b.Command == SystemCommands.MinimizeWindowCommand)));
|
||||
Assert.Equal(Loc.L("Tooltips.Window.Maximize"), AutomationProperties.GetName(captions.Single(b => b.Command == SystemCommands.MaximizeWindowCommand)));
|
||||
Assert.Equal(Loc.L("Tooltips.Window.Close"), AutomationProperties.GetName(captions.Single(b => b.Command == SystemCommands.CloseWindowCommand)));
|
||||
var railToggle = Descendants<Button>(window).Single(b => ReferenceEquals(b.Command, app.Shell.ToggleRailCommand));
|
||||
Assert.Equal(Loc.L(app.Shell.IsRailCollapsed ? "Shell.Nav.Expand" : "Shell.Nav.Collapse"), AutomationProperties.GetName(railToggle),
|
||||
"the rail button has a short name; the sentence is its tooltip");
|
||||
|
||||
var bar = (JobBar)window.FindName("JobBar");
|
||||
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(bar));
|
||||
Assert.Equal(app.Shell.JobAnnouncement, AutomationProperties.GetName(bar), "screen readers hear the job state, not its progress");
|
||||
Assert.Equal(AutomationControlType.StatusBar, UIElementAutomationPeer.CreatePeerForElement(bar).GetAutomationControlType());
|
||||
var pause = Descendants<Button>(bar).Single();
|
||||
Assert.Equal(Loc.L("Shell.JobBar.Pause"), AutomationProperties.GetName(pause), "a short name; the sentence is the tooltip");
|
||||
|
||||
// A text box hands its padding to the text itself; the template adds none (8 px after a leading icon).
|
||||
app.Shell.Navigate(SectionKey.Settings);
|
||||
app.Shell.Settings.Page = SettingsPage.Archive;
|
||||
await app.ExpectAsync<SettingsView>("settings-archive");
|
||||
var boxes = app.FindAll<TextBox>().Where(t => t.IsVisible).ToList();
|
||||
Assert.Contains(boxes, t => Field.GetGlyph(t) is not null);
|
||||
Assert.Contains(boxes, t => Field.GetGlyph(t) is null);
|
||||
foreach (var box in boxes)
|
||||
{
|
||||
var host = (ScrollViewer)box.Template.FindName("PART_ContentHost", box);
|
||||
Assert.Equal(box.Padding, host.Padding);
|
||||
Assert.Equal(new Thickness(0), ((FrameworkElement)VisualTreeHelper.GetParent(host)).Margin, "no second padding around the text");
|
||||
Assert.Equal(Field.GetGlyph(box) is null ? 0.0 : 22.0, host.Margin.Left);
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>A <see cref="MainWindow"/> on capture services and sample data, shown off screen like <c>--capture</c>.</summary>
|
||||
internal sealed class SampleApp : IAsyncDisposable
|
||||
{
|
||||
private const double Width = 1440;
|
||||
private const double Height = 900;
|
||||
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
|
||||
|
||||
private readonly AppEnvironment _environment;
|
||||
private readonly MainWindow _window;
|
||||
|
||||
private SampleApp(AppEnvironment environment, AppServices services, SampleData sample, ShellViewModel shell, MainWindow window)
|
||||
{
|
||||
_environment = environment;
|
||||
Services = services;
|
||||
Sample = sample;
|
||||
Shell = shell;
|
||||
_window = window;
|
||||
}
|
||||
|
||||
public AppServices Services { get; }
|
||||
public SampleData Sample { get; }
|
||||
public ShellViewModel Shell { get; }
|
||||
public MainWindow Window => _window;
|
||||
|
||||
/// <param name="language">The UI language, applied before the window is created (as at start-up).</param>
|
||||
/// <param name="firstRun">Opens with the first-run dialog, which keeps the shell behind it disabled.</param>
|
||||
/// <param name="saveSettings">Runs where the app writes its settings file (nothing is written by default).</param>
|
||||
/// <param name="dialogs">Answers the app's dialogs (by default every confirmation is declined).</param>
|
||||
public static async Task<SampleApp> StartAsync(string language = "en", bool firstRun = false, Action? saveSettings = null, IAppDialogs? dialogs = null)
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
UiLanguage.Apply(language);
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
var settings = new AppSettings { Language = language, FirstRunCompleted = !firstRun };
|
||||
var services = new AppServices(environment, settings, saveSettings ?? (() => { }), dialogs ?? new NoDialogs());
|
||||
var sample = SampleData.Configure(services);
|
||||
var shell = new ShellViewModel(services);
|
||||
|
||||
// A real window, as in the app: styles and templates apply, and Loaded/IsLoaded drive thumbnail loading.
|
||||
var window = new MainWindow(shell)
|
||||
{
|
||||
WindowStartupLocation = WindowStartupLocation.Manual,
|
||||
Left = -20000,
|
||||
Top = -20000,
|
||||
Width = Width,
|
||||
Height = Height,
|
||||
ShowActivated = false,
|
||||
ShowInTaskbar = false,
|
||||
};
|
||||
window.Show();
|
||||
|
||||
await sample.OpenEmptyAsync();
|
||||
await shell.StartAsync();
|
||||
Assert.Null(services.OpenError);
|
||||
Assert.NotNull(services.Jobs);
|
||||
Assert.NotNull(services.Thumbnails);
|
||||
return new SampleApp(environment, services, sample, shell, window);
|
||||
}
|
||||
|
||||
/// <summary>Renders the current screen in both themes and checks that <typeparamref name="TView"/> is on it.</summary>
|
||||
public async Task ExpectAsync<TView>(string screen, bool waitForThumbnails = false)
|
||||
where TView : FrameworkElement
|
||||
{
|
||||
var luminance = new Dictionary<AppTheme, double>();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
await SettleAsync();
|
||||
if (waitForThumbnails && Services.Thumbnails is { } thumbnails)
|
||||
{
|
||||
for (var i = 0; i < 100 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50);
|
||||
await SettleAsync();
|
||||
}
|
||||
var view = FindAll<TView>().FirstOrDefault(v => v.IsVisible && v.ActualWidth > 0 && v.ActualHeight > 0);
|
||||
Assert.NotNull(view, $"{screen}: no {typeof(TView).Name} on screen in {theme}");
|
||||
var bitmap = Render();
|
||||
luminance[theme] = MeanLuminance(bitmap);
|
||||
Assert.Greater(Distinct(bitmap), 8, $"{screen} drew almost nothing in {theme}");
|
||||
}
|
||||
AssertIconOnlyControlsNamed(screen);
|
||||
Assert.Less(luminance[AppTheme.Dark], luminance[AppTheme.Light], $"{screen}: the light theme is not lighter than the dark one");
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
}
|
||||
|
||||
/// <summary>DESIGN §4: every visible icon-only button or segment has an accessible name and a tooltip.</summary>
|
||||
public void AssertIconOnlyControlsNamed(string screen)
|
||||
{
|
||||
foreach (var control in FindAll<Control>().Where(c => c.IsVisible && IsIconOnly(c)))
|
||||
{
|
||||
var name = AutomationProperties.GetName(control);
|
||||
Assert.False(string.IsNullOrWhiteSpace(name), $"{screen}: an icon-only {control.GetType().Name} bound to {(control as ButtonBase)?.Command} has no name");
|
||||
Assert.True(control.ToolTip is not null, $"{screen}: '{name}' has no tooltip (data context: {control.DataContext?.GetType().Name ?? "none"})");
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> FindAll<T>()
|
||||
where T : DependencyObject
|
||||
{
|
||||
var found = new List<T>();
|
||||
Collect(_window, found);
|
||||
return found;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
_window.Close();
|
||||
Shell.Dispose();
|
||||
await Services.DisposeAsync();
|
||||
_environment.DeleteCaptureData();
|
||||
}
|
||||
|
||||
private async Task SettleAsync()
|
||||
{
|
||||
_window.UpdateLayout();
|
||||
// Bindings, templates, async continuations and deferred work queued on the dispatcher.
|
||||
await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
await Task.Delay(30);
|
||||
await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
_window.UpdateLayout();
|
||||
}
|
||||
|
||||
private RenderTargetBitmap Render()
|
||||
{
|
||||
var root = (FrameworkElement)VisualTreeHelper.GetChild(_window, 0);
|
||||
var dpi = VisualTreeHelper.GetDpi(_window);
|
||||
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
|
||||
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
|
||||
Assert.True(width > 0 && height > 0, "the window has a size");
|
||||
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
|
||||
bitmap.Render(root);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private static bool IsIconOnly(Control control) => control switch
|
||||
{
|
||||
SegmentedItem segment => segment.Content is null && segment.Glyph is not null,
|
||||
ButtonBase button => button.Content is null && ButtonIcon.GetGlyph(button) is not null,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static byte[] Pixels(BitmapSource bitmap)
|
||||
{
|
||||
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
|
||||
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
|
||||
return pixels;
|
||||
}
|
||||
|
||||
private static double MeanLuminance(BitmapSource bitmap)
|
||||
{
|
||||
var pixels = Pixels(bitmap);
|
||||
double sum = 0;
|
||||
for (var i = 0; i < pixels.Length; i += 4) sum += 0.0722 * pixels[i] + 0.7152 * pixels[i + 1] + 0.2126 * pixels[i + 2];
|
||||
return sum / (pixels.Length / 4);
|
||||
}
|
||||
|
||||
private static int Distinct(BitmapSource bitmap)
|
||||
{
|
||||
var pixels = Pixels(bitmap);
|
||||
var colours = new HashSet<int>();
|
||||
for (var i = 0; i < pixels.Length && colours.Count < 1000; i += 4 * 7)
|
||||
colours.Add(BitConverter.ToInt32(pixels, i));
|
||||
return colours.Count;
|
||||
}
|
||||
|
||||
private static void Collect<T>(DependencyObject node, List<T> found)
|
||||
where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(node, i);
|
||||
if (child is T match) found.Add(match);
|
||||
Collect(child, found);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<T> Descendants<T>(DependencyObject root)
|
||||
where T : DependencyObject
|
||||
{
|
||||
var found = new List<T>();
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(root, i);
|
||||
if (child is T match) found.Add(match);
|
||||
found.AddRange(Descendants<T>(child));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dispatcher of the shared WPF <see cref="Application"/> with the client's styles and section templates merged,
|
||||
/// as <c>App.xaml</c> does.
|
||||
/// </summary>
|
||||
internal static class ScreenHost
|
||||
{
|
||||
private static readonly Lazy<Dispatcher> Dispatcher = new(Start, LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
|
||||
public static Task RunAsync(Func<Task> body) => Dispatcher.Value.InvokeAsync(body).Task.Unwrap();
|
||||
|
||||
private static Dispatcher Start()
|
||||
{
|
||||
var dispatcher = WpfApplication.Dispatcher;
|
||||
dispatcher.Invoke(() =>
|
||||
{
|
||||
// pack:// URIs parse only once an Application exists (it registers the scheme), so this one is built here.
|
||||
var sectionTemplates = new Uri("pack://application:,,,/Chronos;component/Shell/SectionTemplates.xaml", UriKind.Absolute);
|
||||
var current = Application.Current;
|
||||
AppResources.Merge(current);
|
||||
if (!current.Resources.MergedDictionaries.Any(d => d.Source == sectionTemplates))
|
||||
current.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = sectionTemplates });
|
||||
});
|
||||
return dispatcher;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Chronos.App.DesignTime;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Theming;
|
||||
|
||||
namespace Chronos.App.Tests.Windows;
|
||||
|
||||
/// <summary>What the shell stops when the app exits (App.OnExit disposes it before the services).</summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(120_000)]
|
||||
public sealed class ShellLifetimeTests
|
||||
{
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
|
||||
/// <summary>DESK-7: the open editor goes with the shell, before the engine and the index under it.</summary>
|
||||
[Test]
|
||||
public Task DisposingTheShellClosesTheOpenEditor() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
UiLanguage.Apply("en");
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
|
||||
try
|
||||
{
|
||||
var sample = SampleData.Configure(services);
|
||||
var shell = new ShellViewModel(services);
|
||||
await sample.OpenEmptyAsync();
|
||||
await shell.StartAsync();
|
||||
var id = await sample.FillEditorAsync();
|
||||
shell.OpenSequence(id);
|
||||
await shell.Sequence.OpenAsync(id);
|
||||
var editor = Assert.NotNull(shell.Sequence.Editor);
|
||||
editor.PlayCommand.Execute(null);
|
||||
Assert.True(editor.IsPlaying, "the editor plays");
|
||||
|
||||
shell.Dispose();
|
||||
Assert.False(editor.IsPlaying, "the editor's player stopped with the shell");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await services.DisposeAsync();
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Automation;
|
||||
using System.Windows.Automation.Peers;
|
||||
using System.Windows.Automation.Provider;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Shell;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Library;
|
||||
using Chronos.App.Sections;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Tests.Editor;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The shell's ways of telling what happens outside the screen in front: the taskbar button (UI-05), Windows
|
||||
/// notifications (UI-06), section shortcuts (UI-07), job toasts (UI-08), rail badges (UI-10), and the General settings
|
||||
/// that drive them; the usage counts consent stays hidden in builds without monetization (RF-3).
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
public sealed class ShellNotificationTests
|
||||
{
|
||||
[Test]
|
||||
public Task TheTaskbarButtonMirrorsTheJobBar() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
await JobsLoadedAsync(shell);
|
||||
var taskbar = Assert.NotNull(app.Window.TaskbarItemInfo);
|
||||
|
||||
shell.SetJob("Render · Harbour sunset", 0.25, name: "Render: Harbour sunset");
|
||||
Assert.Equal(TaskbarItemProgressState.Normal, taskbar.ProgressState);
|
||||
Assert.Approximately(0.25, taskbar.ProgressValue, 1e-9);
|
||||
|
||||
shell.SetJob("Scan · Archive", 0, indeterminate: true);
|
||||
Assert.Equal(TaskbarItemProgressState.Indeterminate, taskbar.ProgressState);
|
||||
|
||||
shell.SetJob(null, 0);
|
||||
Assert.Equal(TaskbarItemProgressState.None, taskbar.ProgressState);
|
||||
|
||||
// A failure nobody has seen on the Jobs screen turns the idle button red.
|
||||
shell.SetUnseenFailures(1);
|
||||
Assert.Equal(TaskbarItemProgressState.Error, taskbar.ProgressState);
|
||||
Assert.Approximately(1, taskbar.ProgressValue, 1e-9);
|
||||
shell.SetJob("Render · Harbour sunset", 0.5);
|
||||
Assert.Equal(TaskbarItemProgressState.Normal, taskbar.ProgressState, "a running job comes first");
|
||||
shell.SetUnseenFailures(0);
|
||||
shell.SetJob(null, 0);
|
||||
Assert.Equal(TaskbarItemProgressState.None, taskbar.ProgressState);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheRailShortcutsOfTheTooltipsNavigate() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(firstRun: true);
|
||||
var shell = app.Shell;
|
||||
var bindings = app.Window.InputBindings.OfType<KeyBinding>().ToList();
|
||||
var expected = new (Key Key, SectionKey Section)[]
|
||||
{
|
||||
(Key.D1, SectionKey.Library), (Key.D2, SectionKey.Import), (Key.D3, SectionKey.Edit), (Key.D4, SectionKey.Archive),
|
||||
(Key.D5, SectionKey.Jobs), (Key.D6, SectionKey.Server), (Key.OemComma, SectionKey.Settings),
|
||||
};
|
||||
|
||||
// The first-run dialog keeps the shell behind it: no shortcut moves it, nor folds its rail.
|
||||
var library = bindings.Single(b => b.Key == Key.D1 && b.Modifiers == ModifierKeys.Control);
|
||||
Assert.False(library.Command.CanExecute(library.CommandParameter), "no navigation behind the first-run dialog");
|
||||
var rail = bindings.Single(b => b.Key == Key.B && b.Modifiers == ModifierKeys.Control);
|
||||
Assert.False(rail.Command.CanExecute(rail.CommandParameter), "Ctrl+B waits for the first-run dialog too");
|
||||
shell.CompleteWelcome();
|
||||
Assert.True(rail.Command.CanExecute(rail.CommandParameter));
|
||||
|
||||
foreach (var (key, section) in expected)
|
||||
{
|
||||
var binding = bindings.Single(b => b.Key == key && b.Modifiers == ModifierKeys.Control);
|
||||
Assert.True(binding.Command.CanExecute(binding.CommandParameter), $"Ctrl+{key}");
|
||||
binding.Command.Execute(binding.CommandParameter);
|
||||
Assert.Equal(section, shell.Current.Key, $"Ctrl+{key}");
|
||||
// The rail tooltip lists the shortcut it answers to.
|
||||
var shortcut = key == Key.OemComma ? "Ctrl+," : "Ctrl+" + (char)('1' + (key - Key.D1));
|
||||
Assert.True(shell.Current.ToolTip.EndsWith(shortcut, StringComparison.Ordinal), $"{section} tooltip ends with {shortcut}");
|
||||
}
|
||||
|
||||
// The editor's 1:1 view no longer takes Ctrl+1 from the Library.
|
||||
var gestures = PreviewViewport.ActualSizeCommand.InputGestures.OfType<KeyGesture>().ToList();
|
||||
Assert.True(gestures.All(g => g is not { Key: Key.D1, Modifiers: ModifierKeys.Control }), "the preview keeps away from Ctrl+1");
|
||||
Assert.Contains(gestures, g => g is { Key: Key.D1, Modifiers: ModifierKeys.Control | ModifierKeys.Shift });
|
||||
Assert.Contains("Ctrl+Shift+1", Loc.L("Tooltips.Editor.Preview.OneToOne"));
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheRailCollapsesToIconsThatNameTheirSectionByCtrlB() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
// Owner review 1: 200 px with names, 48 px of icons whose tooltips name their section, by the button or Ctrl+B.
|
||||
var saves = 0;
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(saveSettings: () => saves++);
|
||||
var shell = app.Shell;
|
||||
var rail = (FrameworkElement)app.Window.FindName("Rail");
|
||||
var toggle = app.Window.InputBindings.OfType<KeyBinding>().Single(b => b.Key == Key.B && b.Modifiers == ModifierKeys.Control);
|
||||
Assert.False(shell.IsRailCollapsed);
|
||||
app.Window.UpdateLayout();
|
||||
Assert.Approximately(200, rail.ActualWidth, 0.5);
|
||||
var buttons = app.FindAll<NavRailButton>().Where(b => b.IsVisible).ToList();
|
||||
Assert.Count(shell.AllSections.Count(), buttons);
|
||||
foreach (var button in buttons) Assert.Equal(((SectionViewModel)button.DataContext).ToolTip, button.ToolTip);
|
||||
|
||||
toggle.Command.Execute(toggle.CommandParameter);
|
||||
app.Window.UpdateLayout();
|
||||
Assert.True(shell.IsRailCollapsed);
|
||||
Assert.True(shell.Services.Settings.RailCollapsed);
|
||||
Assert.Equal(1, saves, "the choice is written at once");
|
||||
Assert.Approximately(48, rail.ActualWidth, 0.5);
|
||||
foreach (var button in buttons)
|
||||
{
|
||||
var section = (SectionViewModel)button.DataContext;
|
||||
// The icon's tooltip names the section; screen readers hear the name once (the name, then what it is for).
|
||||
Assert.Equal($"{section.Label} · {section.ToolTip}", button.ToolTip);
|
||||
Assert.Equal(section.Label, AutomationProperties.GetName(button));
|
||||
Assert.Equal(section.ToolTip, AutomationProperties.GetHelpText(button));
|
||||
}
|
||||
Assert.Contains("Ctrl+B", shell.RailToggleToolTip);
|
||||
|
||||
// The ≡ button does the same, and the choice is written again.
|
||||
var menu = app.FindAll<Button>().Single(b => b.IsVisible && ReferenceEquals(b.Command, shell.ToggleRailCommand));
|
||||
((IInvokeProvider)new ButtonAutomationPeer(menu)).Invoke();
|
||||
await app.Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
app.Window.UpdateLayout();
|
||||
Assert.False(shell.IsRailCollapsed);
|
||||
Assert.Equal(2, saves);
|
||||
Assert.Approximately(200, rail.ActualWidth, 0.5);
|
||||
foreach (var button in buttons) Assert.Equal(((SectionViewModel)button.DataContext).ToolTip, button.ToolTip);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task JobsThatEndRaiseOneToastAndFailuresCountUntilSeen() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
shell.CompleteWelcome();
|
||||
await JobsLoadedAsync(shell);
|
||||
var jobs = shell.Jobs;
|
||||
var raised = new List<Toast>();
|
||||
shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.Cast<Toast>() ?? []);
|
||||
var badge = jobs.Badge;
|
||||
|
||||
// A deep analysis started from the Library ends: one toast whose action opens what it worked on.
|
||||
var analysis = Job(JobKind.DeepAnalyse, JobState.Running, Guid.CreateVersion7());
|
||||
jobs.OnJobChanged(analysis);
|
||||
jobs.Flush();
|
||||
jobs.OnJobChanged(analysis with { State = JobState.Done });
|
||||
jobs.Flush();
|
||||
var done = raised.Single(t => t.Title == Loc.L("Shell.Job.Done"));
|
||||
Assert.Equal(Loc.L("Jobs.Action.Open"), done.ActionText);
|
||||
Assert.False(done.IsError);
|
||||
Assert.True(done.RunsFromNotification, "a click on the Windows notification opens what the job worked on");
|
||||
// The same ending reported again says nothing more.
|
||||
jobs.OnJobChanged(analysis with { State = JobState.Done });
|
||||
jobs.Flush();
|
||||
Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Shell.Job.Done")));
|
||||
|
||||
// A failed verify: an error toast with Retry, a badge on the rail and a red taskbar button until Jobs is opened.
|
||||
var verify = Job(JobKind.Verify, JobState.Running, Guid.CreateVersion7());
|
||||
jobs.OnJobChanged(verify);
|
||||
jobs.Flush();
|
||||
jobs.OnJobChanged(verify with { State = JobState.Failed, Error = "Disk read error" });
|
||||
jobs.Flush();
|
||||
var failed = raised.Single(t => t.Title == Loc.L("Shell.Job.Failed"));
|
||||
Assert.True(failed.IsError);
|
||||
Assert.Equal(Loc.L("Jobs.Action.Retry"), failed.ActionText);
|
||||
Assert.False(failed.RunsFromNotification, "a click on the Windows notification does not retry before the user sees why");
|
||||
Assert.Equal(badge + 1, jobs.Badge);
|
||||
Assert.Equal(TaskbarItemProgressState.Error, shell.TaskbarState);
|
||||
shell.Navigate(SectionKey.Jobs);
|
||||
Assert.Equal(badge, jobs.Badge);
|
||||
Assert.NotEqual(TaskbarItemProgressState.Error, shell.TaskbarState);
|
||||
|
||||
// The editor says the renders it followed to their end, with their output: the shell says nothing then. It says them
|
||||
// also when the sequence cannot be read again (that error is said too), without Show in folder then.
|
||||
var content = EditorFixture.Content(EditorFixture.Sunset);
|
||||
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
|
||||
var editor = new EditorViewModel(shell, new EditorSession(source, content, []), [], EncoderHost.Client);
|
||||
await using (editor)
|
||||
{
|
||||
foreach (var readable in new[] { true, false })
|
||||
{
|
||||
raised.Clear();
|
||||
var render = Job(JobKind.Render, JobState.Running, content.Sequence.Id);
|
||||
source.Report(render);
|
||||
jobs.OnJobChanged(render);
|
||||
await UntilAsync(() => editor.IsBusy);
|
||||
jobs.Flush();
|
||||
if (!readable) source.FailNextLoad = new IOException("The specified network name is no longer available.");
|
||||
source.Report(render with { State = JobState.Done });
|
||||
jobs.OnJobChanged(render with { State = JobState.Done });
|
||||
await UntilAsync(() => raised.Any(t => t.Title == Loc.L("Editor.Render.Done")));
|
||||
jobs.Flush();
|
||||
var finished = Assert.Contains(raised, t => t.Title == Loc.L("Editor.Render.Done"));
|
||||
Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "the editor's own render toast is not doubled");
|
||||
Assert.Equal(readable ? 0 : 1, raised.Count(t => t.IsError), "a failed read is said beside the render's end");
|
||||
if (!readable) Assert.Null(finished.ActionCommand, "without the sequence read again, there is no output to show");
|
||||
}
|
||||
}
|
||||
// A render the editor did not follow (of another sequence) is the shell's to announce.
|
||||
raised.Clear();
|
||||
var other = Job(JobKind.Render, JobState.Running, Guid.CreateVersion7());
|
||||
jobs.OnJobChanged(other);
|
||||
jobs.Flush();
|
||||
jobs.OnJobChanged(other with { State = JobState.Done });
|
||||
jobs.Flush();
|
||||
Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Shell.Job.Done")));
|
||||
|
||||
// Server › Upload all: the batch speaks once, when its last upload ends.
|
||||
raised.Clear();
|
||||
var uploads = Enumerable.Range(0, 3).Select(_ => Job(JobKind.UploadCommit, JobState.Queued, Guid.CreateVersion7())).ToList();
|
||||
foreach (var upload in uploads) jobs.OnJobChanged(upload);
|
||||
jobs.Flush();
|
||||
foreach (var upload in uploads)
|
||||
{
|
||||
Assert.Empty(raised);
|
||||
jobs.OnJobChanged(upload with { State = JobState.Done });
|
||||
jobs.Flush();
|
||||
}
|
||||
var batch = raised.Single();
|
||||
Assert.Equal(Loc.Plural("Shell.Job.DonePlural", 3), batch.Title);
|
||||
Assert.Equal(Loc.L("Jobs.Kind.UploadCommit"), batch.Message);
|
||||
Assert.Equal(Loc.L("Shell.Nav.Jobs"), batch.ActionText);
|
||||
shell.Navigate(SectionKey.Library);
|
||||
batch.ActionCommand!.Execute(null);
|
||||
Assert.Equal(SectionKey.Jobs, shell.Current.Key);
|
||||
|
||||
// Two failures of one update: one error toast that leads to the Jobs screen.
|
||||
raised.Clear();
|
||||
var broken = new[] { Job(JobKind.Move, JobState.Running, Guid.CreateVersion7()), Job(JobKind.Adopt, JobState.Running, Guid.CreateVersion7()) };
|
||||
foreach (var job in broken) jobs.OnJobChanged(job);
|
||||
jobs.Flush();
|
||||
foreach (var job in broken) jobs.OnJobChanged(job with { State = JobState.Failed });
|
||||
jobs.Flush();
|
||||
var failures = raised.Single();
|
||||
Assert.True(failures.IsError);
|
||||
Assert.Equal(Loc.Plural("Shell.Job.FailedPlural", 2), failures.Title);
|
||||
Assert.Null(failures.Message);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task ToastsBecomeWindowsNotificationsOnlyWhileNobodySeesTheWindow() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
Assert.True(OsNotifications.IsUnseen(WindowState.Minimized, isVisible: true, anyWindowActive: true));
|
||||
Assert.True(OsNotifications.IsUnseen(WindowState.Normal, isVisible: true, anyWindowActive: false));
|
||||
Assert.True(OsNotifications.IsUnseen(WindowState.Maximized, isVisible: false, anyWindowActive: true));
|
||||
Assert.False(OsNotifications.IsUnseen(WindowState.Maximized, isVisible: true, anyWindowActive: true));
|
||||
|
||||
// The card prompt of BRIEF §12.4 reads "Card X detected", then its action, which a click runs.
|
||||
var card = new Toast { Title = "EOS R5 card A inserted", Message = "SD 128 GB", ActionText = "Import", RunsFromNotification = true };
|
||||
Assert.Equal("SD 128 GB" + Environment.NewLine + "Import", OsNotifications.BalloonText(card));
|
||||
Assert.Equal("Job finished", OsNotifications.BalloonText(new Toast { Title = "Job finished" }));
|
||||
// An action a click does not run (the auto-import's Cancel) waits in the window.
|
||||
var auto = new Toast { Title = "EOS R5 card A inserted", Message = "Importing into the archive", ActionText = "Cancel" };
|
||||
Assert.Equal("Importing into the archive", OsNotifications.BalloonText(auto));
|
||||
|
||||
Assert.True(MainWindow.StartsMinimized(["Chronos.exe", "--minimized"]));
|
||||
Assert.False(MainWindow.StartsMinimized(["Chronos.exe"]));
|
||||
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
app.Shell.CompleteWelcome();
|
||||
// Minimised: nobody sees the window.
|
||||
app.Window.WindowState = WindowState.Minimized;
|
||||
var enabled = false;
|
||||
using var notifications = new OsNotifications(app.Window, () => enabled, _ => { });
|
||||
Assert.False(notifications.Show(card), "Settings › General › Notifications is off");
|
||||
Assert.False(notifications.HasTrayIcon);
|
||||
enabled = true;
|
||||
Assert.True(notifications.Show(new Toast { Title = "Job finished", Message = "Render · Harbour sunset", ActionCommand = new RelayCommand(() => { }) }));
|
||||
Assert.True(notifications.HasTrayIcon, "the notification area holds the icon while a notification can be clicked");
|
||||
notifications.Dispose();
|
||||
Assert.False(notifications.HasTrayIcon);
|
||||
app.Window.WindowState = WindowState.Normal;
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task AClickOnANotificationBringsTheWindowBackAndRunsOnlyWhatItNames() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
app.Shell.CompleteWelcome();
|
||||
var window = app.Window;
|
||||
var imported = 0;
|
||||
var cancelled = 0;
|
||||
var dismissed = new List<Toast>();
|
||||
Toast Import() => new() { Title = "EOS R5 card A inserted", ActionText = "Import", ActionCommand = new RelayCommand(() => imported++), RunsFromNotification = true };
|
||||
|
||||
// "Card X detected — Import": the click restores the window, opens the card and closes the in-window toast.
|
||||
using (var notifications = new OsNotifications(window, () => true, dismissed.Add))
|
||||
{
|
||||
window.WindowState = WindowState.Minimized;
|
||||
var card = Import();
|
||||
Assert.True(notifications.Show(card));
|
||||
notifications.OnBalloonClicked();
|
||||
await StateAsync(window, WindowState.Normal);
|
||||
Assert.Equal(1, imported);
|
||||
Assert.SequenceEqual([card], dismissed);
|
||||
}
|
||||
|
||||
// The auto-import's toast offers Cancel: the click only brings the window back.
|
||||
using (var notifications = new OsNotifications(window, () => true, dismissed.Add))
|
||||
{
|
||||
window.WindowState = WindowState.Minimized;
|
||||
Assert.True(notifications.Show(new Toast { Title = "EOS R5 card A inserted", ActionText = "Cancel", ActionCommand = new RelayCommand(() => cancelled++) }));
|
||||
notifications.OnBalloonClicked();
|
||||
await StateAsync(window, WindowState.Normal);
|
||||
Assert.Equal(0, cancelled);
|
||||
Assert.Count(1, dismissed);
|
||||
}
|
||||
|
||||
// Two notifications: Windows does not say which one was clicked, so neither action runs.
|
||||
using (var notifications = new OsNotifications(window, () => true, dismissed.Add))
|
||||
{
|
||||
window.WindowState = WindowState.Minimized;
|
||||
Assert.True(notifications.Show(Import()));
|
||||
Assert.True(notifications.Show(Import()));
|
||||
notifications.OnBalloonClicked();
|
||||
await StateAsync(window, WindowState.Normal);
|
||||
Assert.Equal(1, imported);
|
||||
Assert.Count(1, dismissed);
|
||||
}
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task AWindowStartedMinimisedComesBackAsItWasSaved() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
// Closed while still minimised from the start: the saved state stays the one it would have come back to.
|
||||
Assert.True(MainWindow.SavesMaximized(WindowState.Maximized, restoreTo: null));
|
||||
Assert.True(MainWindow.SavesMaximized(WindowState.Minimized, WindowState.Maximized));
|
||||
Assert.False(MainWindow.SavesMaximized(WindowState.Minimized, WindowState.Normal));
|
||||
Assert.False(MainWindow.SavesMaximized(WindowState.Normal, restoreTo: null));
|
||||
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
app.Shell.CompleteWelcome();
|
||||
var window = app.Window;
|
||||
// Started at sign-in with the window saved maximised: it waits on the taskbar.
|
||||
window.WaitMinimized(maximized: true);
|
||||
Assert.Equal(WindowState.Minimized, window.WindowState);
|
||||
// The user opens it from the taskbar: it comes back maximised.
|
||||
window.WindowState = WindowState.Normal;
|
||||
await StateAsync(window, WindowState.Maximized);
|
||||
// Only that first restore: later ones are the user's.
|
||||
window.WindowState = WindowState.Normal;
|
||||
window.WindowState = WindowState.Minimized;
|
||||
window.WindowState = WindowState.Normal;
|
||||
await StateAsync(window, WindowState.Normal);
|
||||
await Task.Delay(100);
|
||||
Assert.Equal(WindowState.Normal, window.WindowState);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task GeneralSettingsHoldStartupAndNotificationsButNoConsent() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
// Monetization (BRIEF §21) ships disabled: the default build offers no usage counts consent.
|
||||
Assert.False(ProductFeatures.AdsEnabled);
|
||||
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(firstRun: true);
|
||||
var shell = app.Shell;
|
||||
await app.ExpectAsync<WelcomeView>("welcome");
|
||||
Assert.False(app.FindAll<CheckBox>().Any(c => c.IsVisible && Equals(c.Content, Loc.L("Settings.General.UsageCounts"))), "no consent on the first-run dialog");
|
||||
shell.CompleteWelcome();
|
||||
|
||||
var settings = shell.Settings;
|
||||
var startup = new MemoryStartWithWindows();
|
||||
settings.Startup = startup;
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
settings.Page = SettingsPage.General;
|
||||
await app.ExpectAsync<SettingsView>("settings-general");
|
||||
var boxes = app.FindAll<CheckBox>().Where(c => c.IsVisible).ToList();
|
||||
Assert.False(boxes.Any(c => Equals(c.Content, Loc.L("Settings.General.UsageCounts"))), "no consent in Settings");
|
||||
var start = boxes.Single(c => Equals(c.Content, Loc.L("Settings.General.StartWithWindows")));
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.StartWithWindows"), start.ToolTip);
|
||||
var notify = boxes.Single(c => Equals(c.Content, Loc.L("Settings.General.OsNotifications")));
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.OsNotifications"), notify.ToolTip);
|
||||
Assert.True(notify.IsChecked == true, "Windows notifications are on by default");
|
||||
|
||||
settings.StartWithWindows = true;
|
||||
Assert.True(startup.IsEnabled);
|
||||
settings.OsNotifications = false;
|
||||
Assert.False(shell.Services.Settings.OsNotifications);
|
||||
settings.ResetSectionCommand.Execute(null);
|
||||
Assert.False(startup.IsEnabled, "Reset section turns Start with Windows off");
|
||||
Assert.True(shell.Services.Settings.OsNotifications, "Reset section turns notifications back on");
|
||||
// Reset section also returned the language to the system's.
|
||||
UiLanguage.Apply("en");
|
||||
|
||||
// The search finds General by its new rows, not by the hidden consent.
|
||||
settings.SearchText = Loc.L("Settings.General.Startup");
|
||||
Assert.Contains(settings.VisiblePages, p => p.Page == SettingsPage.General);
|
||||
settings.SearchText = Loc.L("Settings.General.Usage");
|
||||
Assert.False(settings.VisiblePages.Any(p => p.Page == SettingsPage.General), "the hidden consent does not match");
|
||||
settings.SearchText = string.Empty;
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheServerBadgeCountsConflicts() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
shell.CompleteWelcome();
|
||||
Assert.Equal(0, shell.Server.Badge);
|
||||
await app.Sample.FillAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
Assert.NotNull(await shell.Services.Sync.RefreshAsync());
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
// The sample server holds one sequence whose settings changed on both sides.
|
||||
Assert.Equal(1, shell.Server.Sync.Chips.Single(c => c.Filter == Chronos.App.Server.SyncFilter.Conflicts).Count);
|
||||
Assert.Equal(1, shell.Server.Badge);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheLibraryAndArchiveBadgesCountWarnings() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
shell.CompleteWelcome();
|
||||
await app.Sample.FillAsync();
|
||||
var db = Assert.NotNull(shell.Services.Database);
|
||||
|
||||
// Library: the sequences the Warnings filter shows; an analysis that finds warnings adds one.
|
||||
await shell.Library.RefreshAsync();
|
||||
var warned = await db.Sequences.CountAsync(new SequenceQuery { WithStatus = SequenceStatus.HasWarnings });
|
||||
Assert.Equal(warned, shell.Library.Badge);
|
||||
var clean = (await db.Sequences.ListAsync(new SequenceQuery { WithoutStatus = SequenceStatus.HasWarnings, Limit = 1 })).Items[0];
|
||||
await db.Sequences.RecordAnalysisAsync(clean.Id, SequenceStatus.AnalyzedLight | SequenceStatus.HasWarnings, SequenceStatus.None, 2, null);
|
||||
await shell.Library.RefreshAsync();
|
||||
Assert.Equal(warned + 1, shell.Library.Badge);
|
||||
|
||||
// Archive: the index health lines that need attention (the sample has unverified sequences).
|
||||
shell.Navigate(SectionKey.Archive);
|
||||
await shell.Archive.LoadAsync();
|
||||
Assert.Greater(shell.Archive.Badge, 0);
|
||||
Assert.Equal(shell.Archive.Health.Count(h => !h.IsOk), shell.Archive.Badge);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The Jobs screen's flush can take a render's end before the editor that followed the render has seen it: it leaves
|
||||
/// the toast to the editor, which says it once with its output, and once without it when it closed in between.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task TheEditorSaysTheRenderItFollowedAlsoWhenTheJobsScreenSeesItsEndFirst() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
shell.CompleteWelcome();
|
||||
await JobsLoadedAsync(shell);
|
||||
var jobs = shell.Jobs;
|
||||
var raised = new List<Toast>();
|
||||
shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.Cast<Toast>() ?? []);
|
||||
var content = EditorFixture.Content(EditorFixture.Sunset);
|
||||
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
|
||||
var editor = new EditorViewModel(shell, new EditorSession(source, content, []), [], EncoderHost.Client);
|
||||
shell.Sequence.Attach(editor);
|
||||
|
||||
foreach (var closes in new[] { false, true })
|
||||
{
|
||||
raised.Clear();
|
||||
var render = Job(JobKind.Render, JobState.Running, content.Sequence.Id);
|
||||
source.Report(render);
|
||||
jobs.OnJobChanged(render);
|
||||
await UntilAsync(() => editor.FollowsRender(render.Id));
|
||||
jobs.Flush();
|
||||
|
||||
// The end reaches the Jobs screen first; the editor's own callback runs after its flush.
|
||||
jobs.OnJobChanged(render with { State = JobState.Done });
|
||||
jobs.Flush();
|
||||
Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "the Jobs screen leaves the end of a followed render to the editor");
|
||||
source.Report(render with { State = JobState.Done });
|
||||
if (closes)
|
||||
{
|
||||
await shell.Sequence.CloseAsync();
|
||||
Assert.Null(shell.Sequence.Editor);
|
||||
}
|
||||
await UntilAsync(() => raised.Any(t => t.Title == Loc.L("Editor.Render.Done")));
|
||||
jobs.Flush();
|
||||
var finished = Assert.Contains(raised, t => t.Title == Loc.L("Editor.Render.Done"));
|
||||
Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Editor.Render.Done")), "said once");
|
||||
Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "and never by the Jobs screen as well");
|
||||
if (closes) Assert.Null(finished.ActionCommand, "a closed editor does not read the sequence again for the output");
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Open on a job that worked on several sequences (a deep analysis of a Library selection) shows every one of them
|
||||
/// selected in the Library: also those a search hides, whether it is still pending or applied, and those beyond the
|
||||
/// pages read so far. A job over more sequences than a page leaves the Library as it is; a job on an archive opens
|
||||
/// the Archive screen.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task OpenOnAJobOverSeveralSequencesSelectsThemAllInTheLibrary() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
shell.CompleteWelcome();
|
||||
await app.Sample.FillAsync();
|
||||
var db = Assert.NotNull(shell.Services.Database);
|
||||
var library = shell.Library;
|
||||
await library.RefreshAsync();
|
||||
var ids = (await db.Sequences.ListAsync(new SequenceQuery { Sort = SequenceSort.Oldest, Limit = 3 })).Items.Select(s => s.Id).ToList();
|
||||
Assert.Count(3, ids);
|
||||
bool Listed(Guid id) => library.Items.Any(i => i.Sequence.Id == id);
|
||||
Job Analysis(IReadOnlyList<Guid> targets) =>
|
||||
Job(JobKind.DeepAnalyse, JobState.Done, targets[0]) with { TargetIds = targets, TargetLabel = Loc.Plural("Library.Selection.Count", targets.Count) };
|
||||
|
||||
// A search still waiting to apply.
|
||||
library.SearchText = "no such sequence";
|
||||
await shell.Jobs.OpenTargetAsync(Analysis(ids));
|
||||
Assert.Equal(SectionKey.Library, shell.Current.Key);
|
||||
Assert.Equal(string.Empty, library.SearchText, "the search that hid them is cleared");
|
||||
Assert.Equal(ids.Count, library.SelectionCount, "every sequence the job worked on, not only the first");
|
||||
Assert.SequenceEqual(ids.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order());
|
||||
|
||||
// A search applied: the list no longer holds them.
|
||||
library.SearchText = "no such sequence";
|
||||
await UntilAsync(() => !ids.Any(Listed));
|
||||
Assert.False(ids.Any(Listed), "the search hides them");
|
||||
await shell.Jobs.OpenTargetAsync(Analysis(ids));
|
||||
Assert.Equal(string.Empty, library.SearchText);
|
||||
Assert.SequenceEqual(ids.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order());
|
||||
|
||||
// More sequences than a page: those beyond the first page are read until each is listed.
|
||||
var archiveId = Assert.NotNull(await db.Sequences.GetAsync(ids[0])).ArchiveId;
|
||||
var bulk = new List<Guid>();
|
||||
for (var i = 0; i < LibraryPager.DefaultPageSize + 10; i++)
|
||||
{
|
||||
var sequence = new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = archiveId,
|
||||
Folder = $"2021/2021-03-01 Bulk {i:000}",
|
||||
Title = $"Bulk {i:000}",
|
||||
FirstCapture = new DateTime(2021, 3, 1).AddHours(i),
|
||||
LastCapture = new DateTime(2021, 3, 1).AddHours(i + 1),
|
||||
FrameCount = 10,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await db.Sequences.UpsertAsync(sequence);
|
||||
bulk.Add(sequence.Id);
|
||||
}
|
||||
await library.RefreshAsync();
|
||||
var beyond = bulk.Where(id => !Listed(id)).Take(3).ToList();
|
||||
Assert.Count(3, beyond);
|
||||
await shell.Jobs.OpenTargetAsync(Analysis(beyond));
|
||||
Assert.Greater(library.Items.Count, LibraryPager.DefaultPageSize, "the next pages were read");
|
||||
Assert.SequenceEqual(beyond.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order());
|
||||
|
||||
// A job over more sequences than a page (a maintenance run over the archive) opens the Library as it is.
|
||||
shell.Navigate(SectionKey.Jobs);
|
||||
library.SearchText = "Bulk";
|
||||
await shell.Jobs.OpenTargetAsync(Analysis(bulk));
|
||||
Assert.Equal(SectionKey.Library, shell.Current.Key);
|
||||
Assert.Equal("Bulk", library.SearchText, "its search is not cleared");
|
||||
Assert.SequenceEqual(beyond.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order(), "nor its selection replaced");
|
||||
|
||||
await shell.Jobs.OpenTargetAsync(Job(JobKind.Verify, JobState.Done, Guid.CreateVersion7()));
|
||||
Assert.Equal(SectionKey.Archive, shell.Current.Key);
|
||||
// The Archive screen reads its figures when it opens: let that end before the app closes.
|
||||
await shell.Archive.LoadAsync();
|
||||
});
|
||||
|
||||
/// <summary>Lets the dispatcher run what was posted to it (the editor's job events and reload) until <paramref name="done"/> holds.</summary>
|
||||
private static async Task UntilAsync(Func<bool> done)
|
||||
{
|
||||
for (var i = 0; i < 250 && !done(); i++) await Task.Delay(20);
|
||||
}
|
||||
|
||||
/// <summary>The Jobs screen read its first page (it would set the job bar and the badge again).</summary>
|
||||
private static async Task JobsLoadedAsync(ShellViewModel shell)
|
||||
{
|
||||
for (var i = 0; i < 200 && !shell.Jobs.IsEmpty && !shell.Jobs.HasRows; i++) await Task.Delay(20);
|
||||
Assert.True(shell.Jobs.IsEmpty || shell.Jobs.HasRows, "the job list loaded");
|
||||
}
|
||||
|
||||
/// <summary>The window reached <paramref name="state"/> (a restore from a notification is a posted system command).</summary>
|
||||
private static async Task StateAsync(Window window, WindowState state)
|
||||
{
|
||||
for (var i = 0; i < 250 && window.WindowState != state; i++) await Task.Delay(20);
|
||||
Assert.Equal(state, window.WindowState);
|
||||
}
|
||||
|
||||
private static Job Job(JobKind kind, JobState state, Guid target) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
State = state,
|
||||
Priority = JobPriority.User,
|
||||
TargetIds = [target],
|
||||
TargetLabel = "Harbour sunset",
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
Started = DateTimeOffset.UtcNow,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.IO;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Chronos.App.Library;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Windows;
|
||||
|
||||
/// <summary>WIC decoding of thumbnails: embedded previews read by offset, decode-time scaling and Exif orientation.</summary>
|
||||
[WindowsOnly]
|
||||
public sealed class ThumbnailDecodeTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheEmbeddedPreviewIsDecodedAtTheRequestedWidth()
|
||||
{
|
||||
var (path, frame) = FakeRaw(orientation: 1);
|
||||
var image = ThumbnailService.Decode(path, frame, 160, CancellationToken.None);
|
||||
Assert.NotNull(image);
|
||||
Assert.Equal(160, image!.PixelWidth);
|
||||
Assert.InRange(image.PixelHeight, 89, 91);
|
||||
Assert.True(image.IsFrozen, "thumbnails cross threads");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PortraitFramesAreTurnedAndKeepTheRequestedWidth()
|
||||
{
|
||||
var (path, frame) = FakeRaw(orientation: 6);
|
||||
var image = ThumbnailService.Decode(path, frame, 160, CancellationToken.None);
|
||||
Assert.NotNull(image);
|
||||
Assert.Equal(160, image!.PixelWidth);
|
||||
Assert.InRange(image.PixelHeight, 283, 286);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMissingPreviewFallsBackToTheOriginal()
|
||||
{
|
||||
var folder = context.CreateTempDirectory();
|
||||
var path = Path.Combine(folder, "IMG_0001.JPG");
|
||||
File.WriteAllBytes(path, Jpeg(320, 180));
|
||||
// The index points past the end of the file: the original is decoded instead.
|
||||
var frame = Frame(path) with { PreviewOffset = 1 << 20, PreviewLength = 4096 };
|
||||
var image = ThumbnailService.Decode(path, frame, 64, CancellationToken.None);
|
||||
Assert.Equal(64, image!.PixelWidth);
|
||||
Assert.Null(ThumbnailService.Decode(Path.Combine(folder, "gone.JPG"), frame, 64, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACancelledDecodeStops()
|
||||
{
|
||||
var (path, frame) = FakeRaw(orientation: 1);
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
cancelled.Cancel();
|
||||
Assert.Throws<OperationCanceledException>(() => ThumbnailService.Decode(path, frame, 160, cancelled.Token));
|
||||
}
|
||||
|
||||
/// <summary>A file no decoder reads, with a JPEG preview at a known offset (how cameras store RAW previews).</summary>
|
||||
private (string Path, Frame Frame) FakeRaw(int orientation)
|
||||
{
|
||||
var jpeg = Jpeg(320, 180);
|
||||
var header = new byte[4096];
|
||||
"II*\0"u8.CopyTo(header);
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "IMG_0001.CR2");
|
||||
File.WriteAllBytes(path, [.. header, .. jpeg, .. new byte[2048]]);
|
||||
return (path, Frame(path) with { Orientation = orientation, PreviewOffset = header.Length, PreviewLength = jpeg.Length, Format = ImageFileFormat.Cr2 });
|
||||
}
|
||||
|
||||
private static Frame Frame(string path) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = Guid.CreateVersion7(),
|
||||
Index = 0,
|
||||
RelativePath = Path.GetFileName(path),
|
||||
FileName = Path.GetFileName(path),
|
||||
Width = 320,
|
||||
Height = 180,
|
||||
Format = ImageFileFormat.Jpeg,
|
||||
};
|
||||
|
||||
private static byte[] Jpeg(int width, int height)
|
||||
{
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var i = (y * width + x) * 3;
|
||||
pixels[i] = (byte)(x * 255 / width);
|
||||
pixels[i + 1] = (byte)(y * 255 / height);
|
||||
pixels[i + 2] = 96;
|
||||
}
|
||||
}
|
||||
var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgr24, null, pixels, width * 3);
|
||||
var encoder = new JpegBitmapEncoder { QualityLevel = 85 };
|
||||
encoder.Frames.Add(BitmapFrame.Create(source));
|
||||
using var stream = new MemoryStream();
|
||||
encoder.Save(stream);
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.Ui.Theming;
|
||||
|
||||
namespace Chronos.App.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The process-wide WPF <see cref="Application"/> (only one may ever exist per process) on its own STA thread with
|
||||
/// the Chronos theme. Every WPF test reaches it through here, whichever test happens to run first.
|
||||
/// </summary>
|
||||
internal static class WpfApplication
|
||||
{
|
||||
private static readonly Lazy<(Dispatcher Dispatcher, Thread Thread)> Instance = new(Start, LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
|
||||
public static Dispatcher Dispatcher => Instance.Value.Dispatcher;
|
||||
|
||||
/// <summary>
|
||||
/// Stops the dispatcher in order (its binding engine and windows clean up on their own thread) and waits for it, so the
|
||||
/// process exits without WPF work racing its teardown. Nothing to do when no WPF test ran.
|
||||
/// </summary>
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!Instance.IsValueCreated) return;
|
||||
var (dispatcher, thread) = Instance.Value;
|
||||
if (!dispatcher.HasShutdownStarted) dispatcher.InvokeShutdown();
|
||||
thread.Join(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
|
||||
private static (Dispatcher, Thread) Start()
|
||||
{
|
||||
Dispatcher? dispatcher = null;
|
||||
using var ready = new ManualResetEventSlim();
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
|
||||
ThemeManager.Initialize(app, AppTheme.Dark);
|
||||
dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
|
||||
ready.Set();
|
||||
System.Windows.Threading.Dispatcher.Run();
|
||||
});
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.IsBackground = true;
|
||||
thread.Start();
|
||||
ready.Wait();
|
||||
return (dispatcher!, thread);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user