diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs index a2d11016..c8b39f37 100644 --- a/src/Titano.App/Sections/ArchiveViewModel.cs +++ b/src/Titano.App/Sections/ArchiveViewModel.cs @@ -52,6 +52,7 @@ public sealed class ArchiveViewModel : SectionViewModel private int _viewIndex; private bool _loaded; private Task _load = Task.CompletedTask; + private bool _reloadPending; private bool _jobEvents; private string _lastScanText = string.Empty; private ArchiveDialogViewModel? _dialog; @@ -121,9 +122,19 @@ public sealed class ArchiveViewModel : SectionViewModel set { if (value is null || value == _archive) return; + var other = value.Id != _archive?.Id; _archive = value; _duplicates = null; _orphans = null; + if (other) + { + // Until the picked archive is read, nothing of the previous one stays actionable: no tree to take a set + // from, no availability to allow a scan. + _tree = null; + _availability = ArchiveAvailability.Offline; + RebuildRows(); + CommandManager.InvalidateRequerySuggested(); + } _ = LoadAsync(); } } @@ -370,8 +381,30 @@ public sealed class ArchiveViewModel : SectionViewModel _ = LoadAsync(); } - /// Reads archives, figures, tree, health and recent maintenance of the selected archive; joins a read in progress. - public Task LoadAsync() => _load.IsCompleted ? _load = ReadAsync() : _load; + /// + /// Reads archives, figures, tree, health and recent maintenance of the selected archive. A call during a read joins + /// it and reads once more when it ends, so a newly picked archive, a language switch or a finished job is never lost + /// behind the read in progress. + /// + public Task LoadAsync() + { + if (!_load.IsCompleted) + { + _reloadPending = true; + return _load; + } + return _load = ReadUntilCurrentAsync(); + } + + private async Task ReadUntilCurrentAsync() + { + do + { + _reloadPending = false; + await ReadAsync(); + } + while (_reloadPending); + } private async Task ReadAsync() { @@ -384,12 +417,16 @@ public sealed class ArchiveViewModel : SectionViewModel _archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath); if (_archive is not { } archive) return; var root = archive.RootPath; - _availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root))); - _stats = await db.Sequences.GetStatsAsync(archive.Id); + var availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root))); + var stats = await db.Sequences.GetStatsAsync(archive.Id); var sequences = await ListSequencesAsync(db, archive.Id); var withoutProxies = await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt }); - ShowFigures(_stats, withoutProxies); - ShowTree(ArchiveTree.Build(archive, _availability, sequences)); + // Another archive was picked meanwhile: the read its pick queued shows it, never this one's tree. + if (!IsShowing(archive)) return; + _availability = availability; + _stats = stats; + ShowFigures(stats, withoutProxies); + ShowTree(ArchiveTree.Build(archive, availability, sequences)); await LoadRecentAsync(db, archive); } catch (DatabaseException ex) @@ -572,6 +609,7 @@ public sealed class ArchiveViewModel : SectionViewModel var jobs = new List(); foreach (var kind in MaintenanceReports.MaintenanceKinds) jobs.AddRange((await db.Jobs.ListAsync(null, kind, RecentCount)).Items.Where(j => j.TargetIds.Contains(archive.Id))); + if (!IsShowing(archive)) return; Recent = MaintenanceReports.Recent(jobs, RecentCount); var scan = jobs.Where(j => j.Kind == JobKind.Scan && j is { State: JobState.Done, Finished: not null, Started: not null }) .MaxBy(j => j.Finished); @@ -613,6 +651,9 @@ public sealed class ArchiveViewModel : SectionViewModel private bool IsOnline() => _archive is not null && _availability == ArchiveAvailability.Online; + /// The archive a read started with is still the one picked. + private bool IsShowing(Core.Model.Archive archive) => _archive?.Id == archive.Id; + /// A command's tooltip, or why it is disabled: these commands write to the archive or read all of it. private string WhenOnline(string key) => _archive is null || IsOnline() ? Loc.L(key) : Loc.L("Archive.Blocked.NotOnline"); diff --git a/src/Titano.App/Sections/ImportViewModel.cs b/src/Titano.App/Sections/ImportViewModel.cs index 763091c5..7395f117 100644 --- a/src/Titano.App/Sections/ImportViewModel.cs +++ b/src/Titano.App/Sections/ImportViewModel.cs @@ -547,7 +547,10 @@ public sealed class ImportViewModel : SectionViewModel get => _result; private set { + var replaced = _result; if (!Set(ref _result, value)) return; + // A replaced result stops listening to language switches, which would otherwise keep it and its plan alive. + replaced?.Dispose(); if (value is null && _phase == ImportPhase.Done) Phase = ImportPhase.Ready; } } @@ -1228,6 +1231,13 @@ public sealed class ImportViewModel : SectionViewModel _jobCardId = cardId; // Cancel pressed while the job was being queued. if (cancelled.IsCancellationRequested && Services.Jobs is { } jobs) await jobs.CancelAsync(job.Id); + // A worker may have run the job to its end before its id was recorded here (a destination gone offline fails at + // once): those events went unseen, so the job's state is read back once. + if (Services.Database is { } db && await db.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended) + { + await OnImportJobChangedAsync(ended); + return; + } Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); } @@ -1339,7 +1349,6 @@ public sealed class ImportViewModel : SectionViewModel private void Finish(ImportPlan plan, ImportOutcome outcome) { _runCts = null; - _result?.Dispose(); var device = _selected?.Device is { } d && Services.Devices.Devices.Any(x => x.Identity == d.Identity) ? d : null; var card = _selected?.Card ?? _cards.FirstOrDefault(c => c.Identity == _selected?.Key); Result = new ImportResultViewModel(Shell, plan, outcome, _choices, _choices.Destination == ImportDestinationKind.Archive ? _archive : null, card, device); diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs index 9b680bdc..44832fc2 100644 --- a/src/Titano.App/Sections/LibraryViewModel.cs +++ b/src/Titano.App/Sections/LibraryViewModel.cs @@ -1191,6 +1191,8 @@ public sealed class LibraryViewModel : SectionViewModel _year = _year.IsAny ? Years[0] : _year; _camera = _camera.IsAny ? Cameras[0] : _camera; _tag = _tag.IsAny ? Tags[0] : _tag; + // The timeline's month readouts are sentences made with the figures: made again in the new language. + ApplyFacets(); foreach (var item in Items) { item.Update(item.Sequence); diff --git a/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs b/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs index 5376d444..9230c40b 100644 --- a/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs @@ -170,6 +170,34 @@ public sealed class ArchiveScreenSmokeTests static DialogFact Fact(RebuildDialogViewModel dialog, string label) => dialog.FactRows.Single(f => f.Label == Loc.L(label)); } + /// + /// Picking another archive while one is being read shows the picked one: the read in progress is followed by one of + /// the new archive, and meanwhile nothing of the previous archive's tree can be acted on. + /// + [Test] + public Task PickingAnotherArchiveDuringAReadShowsThePickedOne() => ScreenHost.RunAsync(async () => + { + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + await app.Sample.FillAsync(); + var archive = app.Shell.Archive; + await ArchiveScenes.ShowAsync(app.Shell, "overview"); + Assert.Contains(archive.TreeRows, r => r.Node.Kind == TreeNodeKind.Sequence); + var second = await app.Services.Archives!.CreateAsync(Path.Combine(app.Services.Environment.DataDirectory, "second-archive"), "Second"); + + var reading = archive.LoadAsync(); + archive.SelectedArchive = second; + Assert.Empty(archive.TreeRows); + Assert.False(archive.AnalyseSetCommand.CanExecute(null), "nothing of the first archive can be acted on while the picked one is read"); + Assert.False(archive.ScanCommand.CanExecute(null), "the picked archive is not known to be online yet"); + await reading; + + Assert.Equal(second.Id, archive.SelectedArchive!.Id); + Assert.Contains(archive.Archives, a => a.Id == second.Id); + Assert.True(archive.TreeRows[0].IsArchive); + Assert.False(archive.TreeRows.Any(r => r.Node.Kind == TreeNodeKind.Sequence), "the tree is the picked, empty archive's"); + Assert.True(archive.ScanCommand.CanExecute(null), "the picked archive was probed: it is online"); + }); + [Test] public void TheArrowTowardsTheIndentOpensAYearInEitherDirection() { diff --git a/tests/Titano.App.Tests/Import/ImportScreenSmokeTests.cs b/tests/Titano.App.Tests/Import/ImportScreenSmokeTests.cs index aa795e8e..8f2b96a5 100644 --- a/tests/Titano.App.Tests/Import/ImportScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Import/ImportScreenSmokeTests.cs @@ -166,6 +166,62 @@ public sealed class ImportScreenSmokeTests } }); + /// + /// An archive import whose job ends before the screen records its id (here cancelled inside the engine's own "queued" + /// event, so the screen sees none of its events) still ends the screen's run instead of leaving it copying forever. + /// + [Test] + public Task AnImportJobThatEndsBeforeItIsRecordedStillEndsTheRun() => ScreenHost.RunAsync(async () => + { + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + await app.Sample.FillAsync(); + var import = app.Shell.Import; + await ShowAsync(app, "plan"); + var engine = Assert.NotNull(app.Services.Engine); + void CancelAtOnce(Core.Model.Job job) + { + if (job is { Kind: Core.Model.JobKind.Import, State: Core.Model.JobState.Queued }) engine.CancelAsync(job.Id).GetAwaiter().GetResult(); + } + engine.JobChanged += CancelAtOnce; + try + { + Assert.True(import.StartCommand.CanExecute(null), "the plan can be imported"); + import.StartCommand.Execute(null); + for (var i = 0; i < 300 && !import.IsFailed; i++) await Task.Delay(50); + } + finally + { + engine.JobChanged -= CancelAtOnce; + } + Assert.True(import.IsFailed, "the screen left Running though no event of the job reached it"); + Assert.Equal(Loc.L("Import.Status.Cancelled"), import.ErrorText); + }); + + /// A result replaced by New import stops following the language: nothing keeps it, or its plan, alive. + [Test] + public Task AReplacedResultStopsFollowingTheLanguage() => ScreenHost.RunAsync(async () => + { + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + await app.Sample.FillAsync(); + var import = app.Shell.Import; + await ShowAsync(app, "done"); + var replaced = Assert.NotNull(import.Result); + var refreshed = 0; + replaced.PropertyChanged += (_, _) => refreshed++; + import.NewImportCommand.Execute(null); + Assert.Null(import.Result); + try + { + UiLanguage.Apply("it"); + } + finally + { + UiLanguage.Apply("en"); + } + Assert.Equal(0, refreshed, "the replaced result was disposed"); + await import.WaitForPlanAsync(); + }); + /// As --capture does: toasts of the previous state go, those of an insertion state stay. private static async Task ShowAsync(ScreenSmokeTests.SampleApp app, string state) { diff --git a/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs b/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs index c9b0f30a..56bc15f1 100644 --- a/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs @@ -3,6 +3,7 @@ using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Titano.App.Archiving; +using Titano.App.Infrastructure; using Titano.App.Library; using Titano.App.Sections; using Titano.App.Shell; @@ -153,6 +154,32 @@ public sealed class LibraryScreenSmokeTests trash.CloseCommand.Execute(null); }); + /// A language switch makes the timeline's month readouts again, as it does the filters (BRIEF ยง16). + [Test] + public Task TheTimelineReadoutsFollowALanguageSwitch() => 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(); + var library = app.Shell.Library; + await LibraryScenes.ShowAsync(app.Shell, "timeline"); + var english = Readout(library); + try + { + UiLanguage.Apply("it"); + var italian = Readout(library); + Assert.NotEqual(english, italian, "the month readouts follow the language"); + } + finally + { + UiLanguage.Apply("en"); + } + Assert.Equal(english, Readout(library), "and come back with it"); + + static string Readout(LibraryViewModel library) => library.TimelineBands[0].ToolTips!.First(t => !string.IsNullOrEmpty(t))!; + }); + private static void Press(UIElement target, Key key) => target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent });