From 31dea66270988f03e345b1e0c3cb20eef2577a26 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 19:13:55 +0000 Subject: [PATCH] fix(editor): move a local editor's positions with frames inserted under it An editor open on a sequence of this PC while earlier photos arrived (a sync download, an import, a scan) kept its frames and positions in the old order, while the index moved the stored positions with their frames. The next edit of exclusions, the hero or keyframes was merged as the editor's own value and stored in the old order, so other photos were excluded and the Library's hero and the project's named different frames. LocalSequenceSource records the frames version it read the frames at (row and frames read as one state) and refuses a save under the sequence lease when the row's frames version moved (FramesChangedException); the index edit also names that version. EditorSession then reads the sequence again and moves its project, its basis and every undo and redo step the way the index moved the stored copy (ProjectSettings.FollowFrames: by frame id when frames were only inserted, otherwise unchanged; waiting photos placed), and saves in the new order. A read after a job follows the frames the same way, and saves wait for a read under way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Editor.resx | 1 + i18n/it/Editor.it.resx | 1 + src/Titano.App/Editor/EditorSession.cs | 103 ++++++++++++++---- src/Titano.App/Editor/LocalSequenceSource.cs | 63 ++++++++--- src/Titano.App/Editor/ProjectHistory.cs | 19 ++++ src/Titano.Core/Project/ProjectSettings.cs | 34 ++++++ .../Editor/EditorSessionTests.cs | 71 ++++++++++++ .../Editor/ProjectStoreTests.cs | 57 ++++++++++ .../Project/ProjectSettingsTests.cs | 41 +++++++ 9 files changed, 357 insertions(+), 33 deletions(-) diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx index f6a59fbb..402b1f0c 100644 --- a/i18n/en/Editor.resx +++ b/i18n/en/Editor.resx @@ -52,6 +52,7 @@ Nothing to restore Undo Pick a sequence in the Library + Photos are being added to this sequence; wait a moment and try again.long The frames of this sequence changed on the server; get its proxies again.long This sequence is no longer in the archive.long Jobs cannot run until the archive index is open.long diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx index 1e8570ad..bfc1a2d8 100644 --- a/i18n/it/Editor.it.resx +++ b/i18n/it/Editor.it.resx @@ -51,6 +51,7 @@ Niente da ripristinare Annulla Scegli una sequenza in Libreria + Si stanno aggiungendo foto a questa sequenza; attendi un momento e riprova. I fotogrammi di questa sequenza sono cambiati sul server; scarica di nuovo i proxy. Questa sequenza non è più nell’archivio. I lavori non possono partire finché l’indice dell’archivio non è aperto. diff --git a/src/Titano.App/Editor/EditorSession.cs b/src/Titano.App/Editor/EditorSession.cs index 9b7f63a6..56b9f2f1 100644 --- a/src/Titano.App/Editor/EditorSession.cs +++ b/src/Titano.App/Editor/EditorSession.cs @@ -13,12 +13,17 @@ namespace Titano.App.Editor; /// and redo, and the actions of every section — edit, Optimise (§10.4), Reset, exclusions and hero, analysis and render /// jobs. Every change is saved shortly after it is made (); a change stored meanwhile by /// someone else (an analysis job, another client) is merged in. On a server sequence, settings both sides changed to -/// different values wait for the user's choice (). Call from one thread (the UI thread). +/// different values wait for the user's choice (). Frames inserted under the editor (a sync +/// download, an import of earlier photos, a scan) are read again before the next save, and the project's frame positions, +/// its undo steps included, move with their frames as the stored ones did. Call from one thread (the UI thread). /// public sealed class EditorSession : IAsyncDisposable { public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400); + /// Times a save reads the frames again when frames keep changing under it. + private const int FollowAttempts = 3; + /// Sections "Optimise all" walks through, in panel order. public static IReadOnlyList OptimisedSections { get; } = [AdvisorSection.Frames, AdvisorSection.Timing, AdvisorSection.Exposure, AdvisorSection.Motion, AdvisorSection.Camera, AdvisorSection.Export]; @@ -27,6 +32,9 @@ 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. + private Task _reading = Task.CompletedTask; + public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList codecs, TimeSpan? saveDelay = null) { ArgumentNullException.ThrowIfNull(source); @@ -201,19 +209,31 @@ public sealed class EditorSession : IAsyncDisposable public Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken); - /// Reads the sequence again (an analysis finished): new reports and advice, the stored project merged into the open one. + /// + /// 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. + /// public async Task ReloadAsync(CancellationToken cancellationToken = default) { await _saver.FlushAsync(); - var content = await Source.LoadAsync(cancellationToken); - (Content, Context, Advice, Presets) = Analyse(content, _codecs); - // A server's settings that conflict with the editor's waiting change are not merged over it: that change's - // retry meets them and asks (Conflict). - if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0)) + var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _reading = taken.Task; + try { - var merged = ProjectMerge.Merge(_basis, Project, content.Project); - _basis = content.Project; - History.Replace(merged); + var content = await Source.LoadAsync(cancellationToken); + Follow(content); + // A server's settings that conflict with the editor's waiting change are not merged over it: that change's + // retry meets them and asks (Conflict). + if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0)) + { + var merged = ProjectMerge.Merge(_basis, Project, content.Project); + _basis = content.Project; + History.Replace(merged); + } + } + finally + { + taken.SetResult(); } ContentChanged?.Invoke(); } @@ -233,6 +253,31 @@ public sealed class EditorSession : IAsyncDisposable await Source.DisposeAsync(); } + /// + /// 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). + /// + private Func 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; + 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; + } + + /// 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 }; + private static (SequenceContent, SequenceContext, AdvisorResult, IReadOnlyList) Analyse(SequenceContent content, IReadOnlyList codecs) { @@ -271,21 +316,39 @@ public sealed class EditorSession : IAsyncDisposable private async Task SaveAsync(ProjectSettings project) { - ProjectSettings stored; - try + if (!_reading.IsCompleted) { - stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None); + // A read under way decides the frames the project's positions name. Once it is taken, the project as it is + // then contains this change (projects are whole snapshots), with its positions on those frames. + while (!_reading.IsCompleted) await _reading; + project = Project; } - catch (ProjectConflictException ex) + ProjectSettings stored; + for (var attempt = 1; ; attempt++) { - var found = Conflict is null; - Conflict = ex; - if (found) + try { - Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}"); - ConflictFound?.Invoke(ex); + stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None); + break; + } + 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); + ContentChanged?.Invoke(); + } + catch (ProjectConflictException ex) + { + var found = Conflict is null; + Conflict = ex; + if (found) + { + Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}"); + ConflictFound?.Invoke(ex); + } + throw; } - throw; } Conflict = null; _basis = stored; diff --git a/src/Titano.App/Editor/LocalSequenceSource.cs b/src/Titano.App/Editor/LocalSequenceSource.cs index 2105978f..a7d54027 100644 --- a/src/Titano.App/Editor/LocalSequenceSource.cs +++ b/src/Titano.App/Editor/LocalSequenceSource.cs @@ -23,7 +23,10 @@ namespace Titano.App.Editor; /// project in .titano/project.json mirrored in the index's settings column (with its hero frame, which the /// Library shows), jobs on this PC's engine. Project writes follow the archive engine's protocol: under the sequence's /// lease file (so the server and the job engine wait for it), file first (atomically), then the index with its settings -/// version as an optimistic check. +/// version as an optimistic check. Project settings name frames by position, and frames inserted while the sequence is +/// open (a sync download, an import of earlier photos, a scan) move the stored positions with their frames: a save made +/// against the frames read earlier is refused () until the editor has read them again +/// and moved its own positions the same way (). /// public sealed class LocalSequenceSource : ISequenceSource { @@ -31,6 +34,9 @@ public sealed class LocalSequenceSource : ISequenceSource private const int SaveAttempts = 3; private const int JobsListed = 200; + /// Times the frames are listed again when an insertion lands while they are read. + private const int ReadAttempts = 3; + private readonly TitanoDatabase _db; private readonly Guid _sequenceId; private readonly ImageDecoder _decoder; @@ -41,6 +47,10 @@ public sealed class LocalSequenceSource : ISequenceSource /// The JPEG of each GPR frame that an import keeps in another sequence (), by position. private string?[] _companions = []; private Guid[] _frameIds = []; + + /// The frames version of the frames last read (), whose order the project's positions follow. + private int _framesVersion = -1; + private ArchivePaths? _paths; private SequencePaths? _folder; @@ -74,15 +84,8 @@ public sealed class LocalSequenceSource : ISequenceSource public async Task LoadAsync(CancellationToken cancellationToken) { - var sequence = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing(); + var (sequence, frames) = await ReadFramesAsync(cancellationToken); var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken) ?? throw Missing(); - var frames = new List(); - while (true) - { - var page = await _db.Frames.ListBySequenceAsync(_sequenceId, frames.Count > 0 ? frames[^1].Index : -1, PageSize, cancellationToken); - frames.AddRange(page); - if (page.Count < PageSize) break; - } var renders = await _db.Renders.ListBySequenceAsync(_sequenceId, cancellationToken); var companions = await GprCompanions.FindAsync(_db, archive, frames, cancellationToken); return await Task.Run(() => @@ -95,7 +98,7 @@ public sealed class LocalSequenceSource : ISequenceSource if ((frames[i].Flags & FrameFlags.Missing) == 0) files[i] = paths.FromRelative(frames[i].RelativePath); } _companions = [.. frames.Select(f => companions.GetValueOrDefault(f.Id))]; - (_paths, _folder, _files, _frameIds) = (paths, folder, files, [.. frames.Select(f => f.Id)]); + (_paths, _folder, _files, _frameIds, _framesVersion) = (paths, folder, files, [.. frames.Select(f => f.Id)], sequence.FramesVersion); var context = SequenceContext.FromFrames(frames); return new SequenceContent(sequence, frames, ReadProject(sequence, folder), LightAnalyzer.Analyze(frames), ReadReport(folder, frames.Count), context.SourceWidth, context.SourceHeight, folder.Exports, [.. renders.OrderByDescending(r => r.Created)], SavedCopies.List(folder.MetaDirectory)); @@ -127,7 +130,7 @@ public sealed class LocalSequenceSource : ISequenceSource { ArgumentNullException.ThrowIfNull(project); ArgumentNullException.ThrowIfNull(basis); - var (paths, folder, frameIds) = (_paths, _folder, _frameIds); + var (paths, folder, frameIds, framesVersion) = (_paths, _folder, _frameIds, _framesVersion); if (paths is null || folder is null) throw new InvalidOperationException("LoadAsync first."); return Task.Run(async () => { @@ -137,13 +140,16 @@ public sealed class LocalSequenceSource : ISequenceSource for (var attempt = 1; ; attempt++) { var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing(); + // Frames were inserted or removed since the editor read them, so its positions name the old order. Insertions + // hold this lease, so the frames do not change again before this save ends. + if (row.FramesVersion != framesVersion) throw new FramesChangedException(Loc.L("Editor.Error.FramesArriving")); var stored = ReadProject(row, folder); var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored); var json = merged.ToJson(); if (json == stored.ToJson()) return merged; AtomicFile.WriteAllText(folder.ProjectPath, json); var edit = new SequenceEdit { SettingsJson = json, HeroFrameId = merged.HeroFrame == stored.HeroFrame ? null : HeroFrameId(merged, frameIds) }; - var result = await _db.Sequences.EditAsync(_sequenceId, edit, row.SettingsVersion, cancellationToken); + var result = await _db.Sequences.EditAsync(_sequenceId, edit, row.SettingsVersion, framesVersion, cancellationToken); switch (result.Outcome) { case SequenceEditOutcome.Updated: @@ -151,7 +157,8 @@ public sealed class LocalSequenceSource : ISequenceSource return merged; case SequenceEditOutcome.NotFound: throw Missing(); - // The settings moved in the index meanwhile (server API): merge again on top of them; the file follows the next write. + // The settings moved in the index meanwhile (server API): merge again on top of them, or find the frames that + // moved; the file follows the next write. case SequenceEditOutcome.Conflict when attempt == SaveAttempts: throw new EditorException(Loc.L("Editor.Error.SaveConflict")); } @@ -181,6 +188,30 @@ public sealed class LocalSequenceSource : ISequenceSource return ValueTask.CompletedTask; } + /// + /// The sequence row with its frames as one state: the frames are listed between two reads of the row that find the + /// same frames version (an insertion renumbers the frames and moves the row's positions in one transaction, and + /// bumps the version), so the project's positions name these frames. + /// + /// The sequence is gone, or an insertion landed during every attempt. + private async Task<(Sequence Row, List Frames)> ReadFramesAsync(CancellationToken cancellationToken) + { + for (var attempt = 0; attempt < ReadAttempts; attempt++) + { + var before = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing(); + var frames = new List(); + while (true) + { + var page = await _db.Frames.ListBySequenceAsync(_sequenceId, frames.Count > 0 ? frames[^1].Index : -1, PageSize, cancellationToken); + frames.AddRange(page); + if (page.Count < PageSize) break; + } + var after = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing(); + if (after.FramesVersion == before.FramesVersion) return (after, frames); + } + throw new EditorException(Loc.L("Editor.Error.FramesArriving")); + } + /// The settings in force: the index copy, else project.json, else defaults. /// The settings are not a project or come from a newer Titano. internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder) @@ -221,3 +252,9 @@ public sealed class LocalSequenceSource : ISequenceSource private static EditorException Missing() => new(Loc.L("Editor.Error.Missing")); } + +/// +/// The frames of a sequence of this PC changed since the editor read them (frames inserted or removed): nothing was +/// saved. The editor reads them again, moves its positions as the index moved the stored ones, and saves again. +/// +public sealed class FramesChangedException(string message) : EditorException(message); diff --git a/src/Titano.App/Editor/ProjectHistory.cs b/src/Titano.App/Editor/ProjectHistory.cs index 3622b17c..c90b1a95 100644 --- a/src/Titano.App/Editor/ProjectHistory.cs +++ b/src/Titano.App/Editor/ProjectHistory.cs @@ -78,6 +78,25 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200) Changed?.Invoke(); } + /// + /// Rewrites the project and every undo and redo snapshot with , without an undo step: a change + /// of what the values mean rather than of the values (frame positions following frames inserted under the editor), so + /// undo and redo keep naming the same frames. + /// + public void Remap(Func remap) + { + ArgumentNullException.ThrowIfNull(remap); + foreach (var steps in new[] { _undo, _redo }) + { + for (var node = steps.First; node is not null; node = node.Next) node.Value = remap(node.Value); + } + var current = remap(Current); + if (ProjectMerge.SameValues(current, Current)) return; + _runKey = null; + Current = current; + Changed?.Invoke(); + } + private static void Rebase(LinkedList steps, ProjectMerge.Rebase rebase) { for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value); diff --git a/src/Titano.Core/Project/ProjectSettings.cs b/src/Titano.Core/Project/ProjectSettings.cs index 1494e670..60fc2eae 100644 --- a/src/Titano.Core/Project/ProjectSettings.cs +++ b/src/Titano.Core/Project/ProjectSettings.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; +using Titano.Core.Model; namespace Titano.Core.Project; @@ -324,6 +325,39 @@ public sealed record ProjectSettings } } + /// + /// A project written against the frames (frame ids, by index) moved to the frames + /// (in index order) the way the archive index moves its own copy when it takes them + /// (ProjectPositions in Titano.Data): while every frame of is still there, its positions + /// move with their frames (), otherwise they stay; either way pending frames whose + /// photos are now there take their place (). An editor that read the frames + /// before frames were inserted saves its edit in the new order this way. Null when nothing changes. + /// + public static string? FollowFrames(string json, IReadOnlyList before, IReadOnlyList after) + { + ArgumentNullException.ThrowIfNull(before); + ArgumentNullException.ThrowIfNull(after); + var now = new Dictionary(after.Count); + for (var i = 0; i < after.Count; i++) now[after[i].Id] = i; + Dictionary? moves = []; + for (var i = 0; i < before.Count; i++) + { + if (!now.TryGetValue(before[i], out var index)) + { + moves = null; + break; + } + if (index != i) moves[i] = index; + } + var moved = moves is null ? null : MoveFramePositions(json, moves); + var current = moved ?? json; + // Most projects wait for no photo: the frames' photos are gathered only for those that do. + var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase) + ? TranslateFramePositions(current, null, new FramePhotos(after.Select((f, i) => (i, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))))) + : null; + return placed ?? moved; + } + private static bool Move(JsonNode? position, Action replace, IReadOnlyDictionary moves) { if (position is not JsonValue value || !value.TryGetValue(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false; diff --git a/tests/Titano.App.Tests/Editor/EditorSessionTests.cs b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs index 7015300d..9b9a5b44 100644 --- a/tests/Titano.App.Tests/Editor/EditorSessionTests.cs +++ b/tests/Titano.App.Tests/Editor/EditorSessionTests.cs @@ -98,6 +98,77 @@ public sealed class EditorSessionTests } } + [Test] + public async Task AnEditMadeBeforeInsertedFramesWereReadIsSavedOnTheFramesItNamed() + { + var (session, source) = OpenShort(); + await using (session) + { + Assert.True(session.SetExcluded([3], true)); + Assert.True(await session.FlushAsync()); + // Two earlier photos are inserted (a download, an import, a scan): the stored exclusion moved with its frame. + var frames = session.Content.Frames; + InsertEarlier(source, 2); + source.Stored = source.Stored with { ExcludedFrames = [5] }; + source.FailNextSave = new FramesChangedException("frames changed"); + + // The editor still shows the frames it read when the user excludes another one. + Assert.True(session.SetExcluded([6], true)); + Assert.True(await session.FlushAsync()); + + Assert.Equal(frames.Count + 2, session.Content.Count, "the frames were read again"); + Assert.SequenceEqual([5, 8], source.Stored.ExcludedFrames); + Assert.SequenceEqual([frames[3].Id, frames[6].Id], session.Project.ExcludedFrames.Select(i => session.Content.Frames[i].Id)); + Assert.True(session.Undo()); + Assert.SequenceEqual([5], session.Project.ExcludedFrames, "undo steps name the same frames"); + Assert.True(session.Undo()); + Assert.Empty(session.Project.ExcludedFrames); + } + } + + [Test] + public async Task AReadAfterFramesWereInsertedMovesTheOpenProjectWithThem() + { + var (session, source) = OpenShort(); + await using (session) + { + Assert.True(session.SetExcluded([3], true)); + Assert.True(session.SetHero(4)); + Assert.True(await session.FlushAsync()); + InsertEarlier(source, 2); + source.Stored = source.Stored with { ExcludedFrames = [5], HeroFrame = 6 }; + + await session.ReloadAsync(); + + Assert.SequenceEqual([5], session.Project.ExcludedFrames); + Assert.Equal(6, session.Project.HeroFrame); + Assert.True(session.Undo()); + Assert.Null(session.Project.HeroFrame); + Assert.SequenceEqual([5], session.Project.ExcludedFrames, "the step before Set hero names the same frame"); + Assert.True(await session.FlushAsync()); + Assert.SequenceEqual([5], source.Stored.ExcludedFrames); + Assert.Null(source.Stored.HeroFrame); + } + } + + /// 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() + { + var sequence = EditorFixture.Sequence(12); + var content = EditorFixture.Content(sequence, deep: false); + var source = new FakeSequenceSource(sequence, content); + return (new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)), source); + } + + /// Photos captured before the first frame join the source's sequence, as an insertion renumbers it. + private static void InsertEarlier(FakeSequenceSource source, int count) + { + var first = source.Content.Frames[0]; + var early = Enumerable.Range(0, count).Select(i => first with { Id = Guid.CreateVersion7(), CapturedAt = first.CapturedAt!.Value.AddMinutes(i - count) }); + IReadOnlyList frames = [.. early.Concat(source.Content.Frames).Select((f, i) => f with { Index = i })]; + source.Content = source.Content with { Frames = frames, Light = LightAnalyzer.Analyze(frames) }; + } + [Test] public async Task AFailedSaveStaysPendingUntilItIsStored() { diff --git a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs index ab55c4a9..4a8d4de5 100644 --- a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs +++ b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs @@ -138,6 +138,63 @@ public sealed class ProjectStoreTests(TestContext context) } } + [Test] + public async Task AnEditorOpenWhileEarlierPhotosArriveSavesOnTheFramesTheUserChose() + { + 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(session.SetHero(6)); + Assert.True(await session.FlushAsync()); + + // 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); + var moved = ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!); + Assert.SequenceEqual([8], moved.ExcludedFrames); + Assert.Equal(9, moved.HeroFrame); + + // The editor still shows the ten frames it read; the user excludes the eighth of them. + Assert.Equal(10, session.Content.Count); + Assert.True(session.SetExcluded([7], true)); + Assert.True(await session.FlushAsync()); + + Assert.Equal(13, session.Content.Count, "the frames were read again before the save"); + Assert.SequenceEqual([8, 10], session.Project.ExcludedFrames); + Assert.Equal(9, session.Project.HeroFrame); + var row = (await db.Sequences.GetAsync(sequenceId))!; + var stored = ProjectSettings.FromJson(row.SettingsJson!); + var frames = session.Content.Frames; + Assert.SequenceEqual([content.Frames[5].Id, content.Frames[7].Id], stored.ExcludedFrames.Select(i => frames[i].Id), "the photos the user chose"); + Assert.Equal(content.Frames[6].Id, frames[stored.HeroFrame!.Value].Id); + Assert.Equal(content.Frames[6].Id, row.HeroFrameId); + Assert.Equal(row.SettingsJson, File.ReadAllText(Path.Combine(root, "Synthetic", ".titano", "project.json"))); + + // Undo takes back the user's last step on the new frames too. + Assert.True(session.Undo()); + Assert.True(await session.FlushAsync()); + Assert.SequenceEqual([8], ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!).ExcludedFrames); + } + } + } + [Test] public async Task ASaveThatDoesNotReachTheIndexThrows() { diff --git a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs index 33e3c525..60978fa2 100644 --- a/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs +++ b/tests/Titano.Core.Tests/Project/ProjectSettingsTests.cs @@ -167,6 +167,47 @@ public sealed class ProjectSettingsTests Assert.Null(ProjectSettings.MoveFramePositions("""{ "heroFrame": 1, "HeroFrame": 1 }""", new Dictionary { [1] = 2 })); } + [Test] + public void AnEditorsPositionsFollowFramesInsertedUnderItAsTheIndexMovedTheStoredOnes() + { + // An editor read four frames; a download then inserted two earlier photos, one of which an exclusion waited for. + var photos = Enumerable.Range(0, 6).Select(Photo).ToList(); + var ids = Enumerable.Range(0, 6).Select(_ => Guid.CreateVersion7()).ToList(); + IReadOnlyList before = ids[2..]; + var after = ids.Select((id, i) => new Titano.Core.Model.Frame + { + Id = id, + SequenceId = Guid.Empty, + Index = i, + RelativePath = $"s/IMG_{i}.JPG", + FileName = $"IMG_{i}.JPG", + Sha256 = photos[i].Sha256, + Size = photos[i].Size, + CapturedAt = photos[i].CapturedAt, + }).ToList(); + var project = new ProjectSettings + { + ExcludedFrames = [1, 3], + HeroFrame = 0, + Camera = new CameraSettings { Keyframes = [new CameraKey(2, 0.5, 0.5, 1, 0)] }, + Exposure = new ExposureSettings { DeflickerWindow = new Auto().WithManual(41) }, + PendingFrames = [new PendingFrame { Sha256 = photos[1].Sha256, Size = photos[1].Size, Excluded = true }], + }; + + var followed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.FollowFrames(project.ToJson(), before, after))); + + Assert.SequenceEqual([1, 3, 5], followed.ExcludedFrames); + Assert.Equal(2, followed.HeroFrame); + Assert.SequenceEqual([4], followed.Camera.Keyframes.Select(k => k.Frame)); + Assert.Equal(41, followed.Exposure.DeflickerWindow.Manual); + Assert.Null(followed.PendingFrames); + + // The same frames: nothing moves. A frame the editor read that is gone: positions stay, as the index leaves them. + Assert.Null(ProjectSettings.FollowFrames(new ProjectSettings { ExcludedFrames = [1] }.ToJson(), ids, after)); + var removed = after.Where(f => f.Id != ids[3]).Select((f, i) => f with { Index = i }).ToList(); + Assert.Null(ProjectSettings.FollowFrames(new ProjectSettings { ExcludedFrames = [1, 3] }.ToJson(), before, removed)); + } + [Test] public void PositionsCrossToAnotherCopyByPhotoAndWaitForPhotosItLacks() {