diff --git a/src/Titano.App/Editor/EditorSession.cs b/src/Titano.App/Editor/EditorSession.cs index 56b9f2f1..6ee1beea 100644 --- a/src/Titano.App/Editor/EditorSession.cs +++ b/src/Titano.App/Editor/EditorSession.cs @@ -32,7 +32,10 @@ public sealed class EditorSession : IAsyncDisposable private readonly ProjectSaver _saver; private ProjectSettings _basis; - /// The sequence being read again () until its content is taken: saves wait for it. + /// + /// The sequence being read again () until its content is taken: saves and other reads wait + /// for it. + /// private Task _reading = Task.CompletedTask; public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList codecs, TimeSpan? saveDelay = null) @@ -209,15 +212,30 @@ public sealed class EditorSession : IAsyncDisposable public Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken); + /// + /// Makes the project's frame positions name the sequence's frames as they are now, before the project is taken along + /// (a render embeds it): frames inserted since the last read (a sync download, an import of earlier photos, a scan) + /// are read again and the positions follow them (). A server sequence whose frames changed + /// becomes outdated instead (: read-only, its renders refused). + /// + public async Task EnsureFramesAsync(CancellationToken cancellationToken = default) + { + while (!_reading.IsCompleted) await _reading; + var current = await Source.FramesCurrentAsync(cancellationToken); + // A read that began meanwhile (a save that met the new frames) may have taken them already: it ends first. + while (!_reading.IsCompleted) await _reading; + if (!current && !IsRemote) await ReloadAsync(cancellationToken); + } + /// /// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions - /// following them (), the stored project merged into the open one. Saves wait until it is taken. + /// following them (), the stored project merged into the open one. Saves wait until it is taken, + /// and a read waits for the one under way, so each follows the frames the one before it took. /// public async Task ReloadAsync(CancellationToken cancellationToken = default) { await _saver.FlushAsync(); - var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _reading = taken.Task; + var taken = await BeginReadAsync(); try { var content = await Source.LoadAsync(cancellationToken); @@ -257,23 +275,34 @@ public sealed class EditorSession : IAsyncDisposable /// Takes as the sequence. Frames inserted or removed since the last read (a sync download, /// an import of earlier photos, a scan) moved the stored project's frame positions with their frames: the editor's /// project, its undo and redo steps and its basis move the same way (), so - /// they keep naming the frames the user chose. Returns that move (none when the frames are the same). + /// they keep naming the frames the user chose. Call while the read is under way (). /// - private Func Follow(SequenceContent content) + private void Follow(SequenceContent content) { var before = Content.Frames.Select(f => f.Id).ToList(); (Content, Context, Advice, Presets) = Analyse(content, _codecs); - if (before.SequenceEqual(content.Frames.Select(f => f.Id))) return static project => project; + if (before.SequenceEqual(content.Frames.Select(f => f.Id))) return; var after = content.Frames; Log.Info("editor", $"The frames of {content.Sequence.DisplayTitle} changed while it was open; its frame positions follow them"); _basis = Move(_basis); History.Remap(Move); - return Move; ProjectSettings Move(ProjectSettings project) => NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project; } + /// + /// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new + /// one under way until the returned source is completed. + /// + private async Task BeginReadAsync() + { + while (!_reading.IsCompleted) await _reading; + var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _reading = taken.Task; + return taken; + } + /// Exclusions, a hero, keyframes or frames waiting for their photos: positions that follow frames. private static bool NamesFrames(ProjectSettings project) => project.ExcludedFrames.Count > 0 || project.HeroFrame is not null || project.Camera.Keyframes.Count > 0 || project.PendingFrames is { Count: > 0 }; @@ -334,8 +363,18 @@ public sealed class EditorSession : IAsyncDisposable catch (FramesChangedException) when (attempt < FollowAttempts) { // Frames were inserted under the editor and the stored positions moved with them: the frames are read - // again, this edit's positions follow them too, and it is saved in the new order. - project = Follow(await Source.LoadAsync(CancellationToken.None))(project); + // again (after a read under way, whose move this edit's snapshot missed), the project's positions follow + // them, and the project as it is then, which contains this edit, is saved in the new order. + var taken = await BeginReadAsync(); + try + { + Follow(await Source.LoadAsync(CancellationToken.None)); + } + finally + { + taken.SetResult(); + } + project = Project; ContentChanged?.Invoke(); } catch (ProjectConflictException ex) diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs index 2e4ca35a..a3f11ca8 100644 --- a/src/Titano.App/Editor/EditorViewModel.cs +++ b/src/Titano.App/Editor/EditorViewModel.cs @@ -48,6 +48,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable private readonly AsyncRelayCommand _cancelServerJob; private PreviewRenderer _renderer; private int _currentIndex; + + /// The frame on screen: it stays on screen when frames are inserted or removed before it. + private Guid _currentFrameId; private EditorTab _selectedTab; private ImageSource? _previewImage; private ImageSource? _originalImage; @@ -111,6 +114,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable Tabs = [Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)]; _selectedTab = Exposure; _currentIndex = session.Project.HeroFrame is { } hero && (uint)hero < (uint)FrameCount ? hero : 0; + _currentFrameId = FrameId(_currentIndex); // Until the link is read (AttachJobsAsync), a sequence of this PC cannot send its renders. _syncGate = session.IsRemote ? ExportSyncGate.Remote : ExportSyncGate.SignedOut; RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))]; @@ -233,6 +237,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable set { var clamped = FrameCount == 0 ? 0 : int.Clamp(value, 0, FrameCount - 1); + _currentFrameId = FrameId(clamped); if (!Set(ref _currentIndex, clamped)) return; foreach (var tab in Tabs) tab.OnCurrentFrameChanged(); UpdateInfo(); @@ -515,6 +520,10 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable /// public async Task RenderAsync(JobPriority priority, bool batch) { + // The job embeds the project: its frame positions follow frames inserted since the editor read them first. A server + // sequence whose frames changed is outdated instead, and its toast says so and offers fresh proxies. + await Session.EnsureFramesAsync(); + if (IsOutdated) return; var export = batch ? RenderExport : RenderExport with { Batch = [] }; var requests = Session.RenderRequests(export); foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority }); @@ -801,6 +810,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable private void OnContentChanged() { + // The frame on screen stays on screen, wherever frames inserted or removed before it put it (the tabs that reload + // below may seek meanwhile). + var shown = IndexOfFrame(_currentFrameId) ?? int.Min(CurrentIndex, int.Max(0, FrameCount - 1)); _renderer = new PreviewRenderer(Session.Content, Session.Source); Planner = new ExportPlanner(Session.Content, _encoders, _host); if (Thumbnails.Count != FrameCount) Thumbnails = new EditorThumbnails(Session.Source, FrameCount); @@ -808,13 +820,27 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable foreach (var tab in Tabs) tab.OnContentChanged(); OnPropertyChanged(nameof(Summary)); OnPropertyChanged(nameof(FrameCount)); - CurrentIndex = int.Min(CurrentIndex, int.Max(0, FrameCount - 1)); + CurrentIndex = shown; UpdateMarkers(); RequestCorrections(); RequestPlan(); RequestPreview(immediate: true); } + /// The id of frame ; empty when there is none. + private Guid FrameId(int index) => (uint)index < (uint)FrameCount ? Session.Content.Frames[index].Id : Guid.Empty; + + /// Where frame is now; null when the sequence no longer has it. + private int? IndexOfFrame(Guid id) + { + var frames = Session.Content.Frames; + for (var i = 0; i < frames.Count; i++) + { + if (frames[i].Id == id) return i; + } + return null; + } + /// /// The UI language changed: what the tabs keep in objects (chart legends and summaries, the Auto chips of the /// settings), the timeline markers and the preview's info line are made again in the new language. diff --git a/src/Titano.App/Editor/ISequenceSource.cs b/src/Titano.App/Editor/ISequenceSource.cs index 00e089a2..bafab671 100644 --- a/src/Titano.App/Editor/ISequenceSource.cs +++ b/src/Titano.App/Editor/ISequenceSource.cs @@ -44,6 +44,14 @@ public interface ISequenceSource : IAsyncDisposable /// The sequence is gone, or its project cannot be read (corrupt, or written by a newer Titano). Task LoadAsync(CancellationToken cancellationToken); + /// + /// Whether the frames read last are still the sequence's, in the same order: frames inserted + /// or removed since (a sync download, an import of earlier photos, a scan) moved the stored project's positions. A + /// server sequence whose frames changed becomes . + /// + /// The sequence is gone. + Task FramesCurrentAsync(CancellationToken cancellationToken); + /// /// Frame in linear light, oriented, long edge at most ; null /// when the frame cannot be read. The caller owns the buffer. diff --git a/src/Titano.App/Editor/LocalSequenceSource.cs b/src/Titano.App/Editor/LocalSequenceSource.cs index a7d54027..300491ee 100644 --- a/src/Titano.App/Editor/LocalSequenceSource.cs +++ b/src/Titano.App/Editor/LocalSequenceSource.cs @@ -105,6 +105,14 @@ public sealed class LocalSequenceSource : ISequenceSource }, cancellationToken); } + /// An insertion bumps the row's frames version in the transaction that renumbers the frames. + public async Task FramesCurrentAsync(CancellationToken cancellationToken) + { + var framesVersion = _framesVersion; + var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing(); + return row.FramesVersion == framesVersion; + } + public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) { if ((uint)index >= (uint)_files.Length || _files[index] is not { } file) return null; diff --git a/src/Titano.App/Editor/RemoteSequenceSource.cs b/src/Titano.App/Editor/RemoteSequenceSource.cs index 97993e95..1a4bddf8 100644 --- a/src/Titano.App/Editor/RemoteSequenceSource.cs +++ b/src/Titano.App/Editor/RemoteSequenceSource.cs @@ -130,6 +130,13 @@ public sealed class RemoteSequenceSource : ISequenceSource }, cancellationToken); } + /// Read from the server's manifest: a sequence whose frames are not this PC's becomes outdated. + public async Task FramesCurrentAsync(CancellationToken cancellationToken) + { + if (IsOutdated) return false; + return Compare(await Call(() => _api.GetManifestAsync(Id, cancellationToken))); + } + public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) { if ((uint)index >= (uint)_remote.Frames.Count) return null; @@ -305,9 +312,7 @@ public sealed class RemoteSequenceSource : ISequenceSource { try { - var manifest = await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false); - if (SameFrames(manifest)) Volatile.Write(ref _framesVersion, manifest.FramesVersion); - else MarkOutdated(); + Compare(await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false)); } catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or JsonException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) @@ -344,6 +349,21 @@ public sealed class RemoteSequenceSource : ISequenceSource JobChanged?.Invoke(job); } + /// + /// Takes the server's frames as lists them: their frames version when they are this PC's + /// (saves name it), outdated otherwise. Returns whether they are. + /// + private bool Compare(SequenceManifest manifest) + { + if (!SameFrames(manifest)) + { + MarkOutdated(); + return false; + } + Volatile.Write(ref _framesVersion, manifest.FramesVersion); + return true; + } + /// The server's frames are the cached ones, in the same order (frame positions in the project mean the same frames). private bool SameFrames(SequenceManifest manifest) => manifest.Frames.OrderBy(f => f.Index).Select(f => f.Id).SequenceEqual(_remote.Frames.Select(f => f.Id)); diff --git a/tests/Titano.App.Tests/Editor/EditorFixture.cs b/tests/Titano.App.Tests/Editor/EditorFixture.cs index 2099ebd1..3a950da9 100644 --- a/tests/Titano.App.Tests/Editor/EditorFixture.cs +++ b/tests/Titano.App.Tests/Editor/EditorFixture.cs @@ -77,6 +77,9 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon { private readonly SyntheticFrameSource _pixels = new(sequence); + /// The frames the session read last (opened with, or loaded since). + private IReadOnlyList _read = content.Frames; + public ProjectSettings Stored { get; set; } = content.Project; public SequenceContent Content { get; set; } = content; @@ -114,11 +117,36 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon /// Thrown by the next load (the sequence read again after a job). public Exception? FailNextLoad { get; set; } - public Task LoadAsync(CancellationToken cancellationToken) + /// Awaited by the next load once it has read the sequence (a read that is slow to complete). + public Task? NextLoadGate { get; set; } + + /// Times the sequence was read (). + public int Loads { get; private set; } + + public async Task LoadAsync(CancellationToken cancellationToken) { - if (FailNextLoad is not { } failure) return Task.FromResult(Content with { Project = Stored }); - FailNextLoad = null; - return Task.FromException(failure); + if (FailNextLoad is { } failure) + { + FailNextLoad = null; + throw failure; + } + Loads++; + var content = Content with { Project = Stored }; + if (NextLoadGate is { } gate) + { + NextLoadGate = null; + await gate; + } + _read = content.Frames; + return content; + } + + /// Whether holds the frames read last; a server sequence becomes outdated when not. + public Task FramesCurrentAsync(CancellationToken cancellationToken) + { + var current = _read.Select(f => f.Id).SequenceEqual(Content.Frames.Select(f => f.Id)); + if (!current && IsRemote) MarkOutdated(); + return Task.FromResult(current); } public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) diff --git a/tests/Titano.App.Tests/Editor/EditorSessionTests.cs b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs index 9b9a5b44..c4f8e0c2 100644 --- a/tests/Titano.App.Tests/Editor/EditorSessionTests.cs +++ b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs @@ -151,6 +151,89 @@ public sealed class EditorSessionTests } } + [Test] + public async Task ARenderAfterFramesWereInsertedEmbedsThePositionsOfTheFramesTheUserChose() + { + var (session, source) = OpenShort(); + await using (session) + { + Assert.True(session.SetExcluded([3], true)); + Assert.True(session.SetHero(4)); + Assert.True(await session.FlushAsync()); + var frames = session.Content.Frames; + // Two earlier photos are inserted and the index moves the stored positions; the user renders without an edit. + InsertEarlier(source, 2); + source.Stored = source.Stored with { ExcludedFrames = [5], HeroFrame = 6 }; + + await session.EnsureFramesAsync(); + var requests = session.RenderRequests(session.Project.Export); + + Assert.Equal(frames.Count + 2, session.Content.Count, "the frames were read again"); + var parameters = JsonSerializer.Deserialize(requests[0].ParametersJson!, ProtocolJson.Default.RenderJobParameters)!; + var embedded = ProjectSettings.FromJson(parameters.SettingsJson!); + Assert.SequenceEqual([5], embedded.ExcludedFrames); + Assert.Equal(6, embedded.HeroFrame); + Assert.Equal(frames[3].Id, session.Content.Frames[embedded.ExcludedFrames[0]].Id); + Assert.Equal(frames[4].Id, session.Content.Frames[embedded.HeroFrame!.Value].Id); + Assert.True(session.Undo()); + Assert.Null(session.Project.HeroFrame); + Assert.SequenceEqual([5], session.Project.ExcludedFrames, "undo steps name the same frames"); + + // Frames that did not change are not read again. + var loads = source.Loads; + await session.EnsureFramesAsync(); + Assert.Equal(loads, source.Loads); + } + } + + [Test] + public async Task AServerSequenceWhoseFramesChangedIsOutdatedBeforeItsRender() + { + var sequence = EditorFixture.Sequence(12); + var content = EditorFixture.Content(sequence, deep: false); + var source = new FakeSequenceSource(sequence, content) { IsRemote = true }; + var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)); + await using (session) + { + InsertEarlier(source, 1); + + await session.EnsureFramesAsync(); + + Assert.True(source.IsOutdated); + Assert.True(session.IsReadOnly); + Assert.Equal(0, source.Loads, "its proxies are not the server's frames: nothing is read"); + Assert.Equal(12, session.Content.Count); + } + } + + [Test] + public async Task ReadsThatOverlapFollowTheFramesInTheOrderTheyWereRead() + { + var (session, source) = OpenShort(); + await using (session) + { + Assert.True(session.SetExcluded([3], true)); + Assert.True(await session.FlushAsync()); + var frames = session.Content.Frames; + // A job ends after an earlier photo was inserted, and its read of the sequence is slow to complete. + InsertEarlier(source, 1); + source.Stored = source.Stored with { ExcludedFrames = [4] }; + var slow = new TaskCompletionSource(); + source.NextLoadGate = slow.Task; + var first = session.ReloadAsync(); + // Another job ends after two more were inserted: its read waits for the first one and follows its frames. + InsertEarlier(source, 2); + source.Stored = source.Stored with { ExcludedFrames = [6] }; + var second = session.ReloadAsync(); + slow.SetResult(); + await Task.WhenAll(first, second); + + Assert.Equal(frames.Count + 3, session.Content.Count); + Assert.SequenceEqual([6], session.Project.ExcludedFrames); + Assert.Equal(frames[3].Id, session.Content.Frames[6].Id); + } + } + /// A short sequence without its analysis, whose frame ids are all different (the synthetic ids repeat every 64 frames). private static (EditorSession Session, FakeSequenceSource Source) OpenShort() { diff --git a/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs index 70ccf97b..6d7289b6 100644 --- a/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs +++ b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs @@ -14,6 +14,7 @@ using Titano.App.Sections; using Titano.App.Shell; using Titano.App.Tests.Windows; using Titano.Core.Advice; +using Titano.Core.Analysis; using Titano.Core.Export; using Titano.Core.Localization; using Titano.Core.Model; @@ -299,6 +300,36 @@ public sealed class EditorSmokeTests } }); + /// + /// Frames inserted under the editor (a sync download, an import of earlier photos) move the frame on screen with its + /// photo: what the frame actions (Exclude, Set hero, a keyframe) apply to stays the photo the user looks at. + /// + [Test] + public Task TheFrameOnScreenStaysWhenFramesAreInsertedBeforeIt() => ScreenHost.RunAsync(async () => + { + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + var content = EditorFixture.Content(EditorFixture.Sunset, deep: false); + var source = new FakeSequenceSource(EditorFixture.Sunset, content); + var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client); + await using (editor) + { + editor.CurrentIndex = 5; + var shown = content.Frames[5].Id; + // An earlier photo arrives and the last frame goes: as many frames as before, each one place later. + var first = content.Frames[0]; + IReadOnlyList frames = + [.. new[] { first with { Id = Guid.CreateVersion7(), CapturedAt = first.CapturedAt!.Value.AddMinutes(-1) } }.Concat(content.Frames.SkipLast(1)) + .Select((f, i) => f with { Index = i })]; + source.Content = content with { Frames = frames, Light = LightAnalyzer.Analyze(frames) }; + + await editor.Session.ReloadAsync(); + + Assert.Equal(6, editor.CurrentIndex); + Assert.Equal(shown, editor.Session.Content.Frames[editor.CurrentIndex].Id); + Assert.Equal(6, editor.Frames.Selected?.Index); + } + }); + /// The measuring tool of each section has content. private static void ExpectMeasure(SequenceView view, EditorTab tab) { diff --git a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs index 05a9c11c..7b1a6e51 100644 --- a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs +++ b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs @@ -18,6 +18,7 @@ namespace Titano.App.Tests.Editor; internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList frames) : IRemoteSequenceApi { private readonly Lock _gate = new(); + private readonly TaskCompletionSource _subscribed = new(TaskCreationOptions.RunContinuationsAsynchronously); private Channel _events = Channel.CreateUnbounded(); /// The server's frames in order (another list when frames are added or removed on the server). @@ -55,6 +56,9 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyListCompletes once the editor's listener has opened an event stream (the stream open then is the one it reads). + public Task Subscribed => _subscribed.Task; + /// A job of the server, as GET /jobs/{id} returns it. public JobDto Job(Guid id, string kind, string state, Guid? target = null, long done = 0, long total = 0) => new(id, kind, [target ?? sequence.Id], sequence.DisplayTitle, state, "user", done, total, null, null, null, null, 0, null, DateTimeOffset.UtcNow, @@ -168,6 +172,7 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) { var events = Volatile.Read(ref _events).Reader; + _subscribed.TrySetResult(); while (await events.WaitToReadAsync(cancellationToken)) { while (events.TryRead(out var e)) yield return e; diff --git a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs index 4a8d4de5..6fd23079 100644 --- a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs +++ b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs @@ -156,17 +156,7 @@ public sealed class ProjectStoreTests(TestContext context) // Three photos taken before the others are found in the folder (a sync download, an import or a scan // inserts them the same way): the index moves the stored positions with their frames. - var sequence = EditorFixture.Sequence(3); - var first = content.Frames[0].CapturedAt!.Value; - for (var i = 0; i < 3; i++) - { - using var image = sequence.Render(i); - var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i] with { CapturedAt = first.AddMinutes(i - 3) }); - File.WriteAllBytes(Path.Combine(root, "Synthetic", $"EARLY_{i + 1}.JPG"), - JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] })); - } - var archive = (await db.Archives.GetAsync(content.Sequence.ArchiveId, context.Cancellation))!; - await new ArchiveService(db, options).Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation); + await InsertEarlierAsync(db, root, content, options, 3); var moved = ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!); Assert.SequenceEqual([8], moved.ExcludedFrames); Assert.Equal(9, moved.HeroFrame); @@ -195,6 +185,36 @@ public sealed class ProjectStoreTests(TestContext context) } } + [Test] + public async Task ARenderAfterEarlierPhotosArriveEmbedsTheFramesTheUserChose() + { + var (db, sequenceId, root) = await ArchiveAsync(10); + await using (db) + { + var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }; + await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options); + var content = await source.LoadAsync(context.Cancellation); + var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)); + await using (session) + { + Assert.True(session.SetExcluded([5], true)); + Assert.True(await session.FlushAsync()); + Assert.True(await source.FramesCurrentAsync(context.Cancellation)); + + // Earlier photos arrive while the editor is open; the user renders without another edit. + await InsertEarlierAsync(db, root, content, options, 3); + Assert.False(await source.FramesCurrentAsync(context.Cancellation)); + await session.EnsureFramesAsync(context.Cancellation); + var request = session.RenderRequests(session.Project.Export)[0]; + + Assert.True(await source.FramesCurrentAsync(context.Cancellation)); + Assert.Equal(13, session.Content.Count); + var embedded = ProjectSettings.FromJson(ProcessingJobs.ReadRender(request.ParametersJson).Parameters.SettingsJson!); + Assert.SequenceEqual([content.Frames[5].Id], embedded.ExcludedFrames.Select(i => session.Content.Frames[i].Id), "the photo the user excluded"); + } + } + } + [Test] public async Task ASaveThatDoesNotReachTheIndexThrows() { @@ -249,6 +269,25 @@ public sealed class ProjectStoreTests(TestContext context) } } + /// + /// Writes photos taken before the sequence's first frame into its folder and scans the + /// archive: they are inserted in front, and the index moves the stored positions with their frames. + /// + private async Task InsertEarlierAsync(TitanoDatabase db, string root, SequenceContent content, ArchiveServiceOptions options, int count) + { + var sequence = EditorFixture.Sequence(count); + var first = content.Frames[0].CapturedAt!.Value; + for (var i = 0; i < count; i++) + { + using var image = sequence.Render(i); + var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i] with { CapturedAt = first.AddMinutes(i - count) }); + File.WriteAllBytes(Path.Combine(root, "Synthetic", $"EARLY_{i + 1}.JPG"), + JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] })); + } + var archive = (await db.Archives.GetAsync(content.Sequence.ArchiveId, context.Cancellation))!; + await new ArchiveService(db, options).Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation); + } + /// A temporary archive with one adopted folder of synthetic JPEGs, indexed. private async Task<(TitanoDatabase Db, Guid SequenceId, string Root)> ArchiveAsync(int frames) { diff --git a/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs index 9a6c9043..fee4899b 100644 --- a/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs +++ b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs @@ -159,7 +159,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context) Assert.Same(conflict, session.Conflict); Assert.False(await session.FlushAsync(), "the change waits for the choice"); Assert.True(session.ResolveConflict(keepMine: true)); - Assert.True(await session.FlushAsync()); + Assert.True(await FlushAfterChoiceAsync(session)); Assert.Null(session.Conflict); var stored = ProjectSettings.FromJson(api.SettingsJson!); @@ -181,7 +181,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context) await found.Task.WaitAsync(TimeSpan.FromSeconds(10)); Assert.True(session.ResolveConflict(keepMine: false)); - Assert.True(await session.FlushAsync()); + Assert.True(await FlushAfterChoiceAsync(session)); var stored = ProjectSettings.FromJson(api.SettingsJson!); Assert.Equal((0.3, -0.2, (int?)2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY, stored.HeroFrame), "the server's values where both changed; the editor's other change is saved"); @@ -469,6 +469,8 @@ public sealed class RemoteSequenceSourceTests(TestContext context) await using (source) { await source.LoadAsync(context.Cancellation); + // The listener reads the stream open when it subscribes: it must have subscribed for the drop to reach it. + await api.Subscribed.WaitAsync(TimeSpan.FromSeconds(10), context.Cancellation); api.DropEvents(); api.Frames = [.. remote.Frames.Skip(1).Select(f => f.Id)]; api.FramesVersion = 2; @@ -478,6 +480,30 @@ public sealed class RemoteSequenceSourceTests(TestContext context) } } + [Test] + public async Task ARenderIsRefusedOnceTheServersFramesChangedWithoutAnEvent() + { + var (source, api, remote) = Open(); + await using (source) + { + await source.LoadAsync(context.Cancellation); + // A new frames version over the same frames: they are still this PC's. + api.FramesVersion = 2; + Assert.True(await source.FramesCurrentAsync(context.Cancellation)); + Assert.False(source.IsOutdated); + + // A server scan inserts an earlier photo and sends no event: the check before a render finds it. + api.Frames = [Guid.CreateVersion7(), .. remote.Frames.Select(f => f.Id)]; + api.FramesVersion = 3; + Assert.False(await source.FramesCurrentAsync(context.Cancellation)); + Assert.True(source.IsOutdated); + var refused = await Assert.ThrowsAsync(() => + source.SubmitAsync(ProcessingJobs.Render(remote.Sequence, new ExportSettings(), 1920, 1080), context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.FramesChanged"), refused.Message); + Assert.Empty(api.Posted); + } + } + [Test] public async Task AConflictFoundOnOtherFramesIsNotMergedOntoThem() { @@ -591,6 +617,13 @@ public sealed class RemoteSequenceSourceTests(TestContext context) lock (seen) return seen[^1]; } + /// + /// Stores the change after the user settled a conflict. The test's thread is not the saver's: a retry that started + /// before the choice may still be failing on the old basis, and a flush that arrives meanwhile reports it, so one more + /// flush (on the UI thread the choice cannot land inside a retry) is answered by the attempt made after the choice. + /// + private static async Task FlushAfterChoiceAsync(EditorSession session) => await session.FlushAsync() || await session.FlushAsync(); + private static async Task WaitAsync(Func condition) { for (var i = 0; i < 200; i++)