fix: full verification against the brief — 137 confirmed findings fixed over six passes #4

Merged
Alby96 merged 169 commits from claude/keen-knuth-uhxv8w into main 2026-10-13 12:10:04 +02:00
9 changed files with 357 additions and 33 deletions
Showing only changes of commit 31dea66270 - Show all commits

No files matched your search

+1
View File
@@ -52,6 +52,7 @@
<data name="Editor.Copy.Same" xml:space="preserve"><value>Nothing to restore</value></data>
<data name="Editor.Copy.Undo" xml:space="preserve"><value>Undo</value></data>
<data name="Editor.Empty" xml:space="preserve"><value>Pick a sequence in the Library</value></data>
<data name="Editor.Error.FramesArriving" xml:space="preserve"><value>Photos are being added to this sequence; wait a moment and try again.</value><comment>long</comment></data>
<data name="Editor.Error.FramesChanged" xml:space="preserve"><value>The frames of this sequence changed on the server; get its proxies again.</value><comment>long</comment></data>
<data name="Editor.Error.Missing" xml:space="preserve"><value>This sequence is no longer in the archive.</value><comment>long</comment></data>
<data name="Editor.Error.NoEngine" xml:space="preserve"><value>Jobs cannot run until the archive index is open.</value><comment>long</comment></data>
+1
View File
@@ -51,6 +51,7 @@
<data name="Editor.Copy.Same" xml:space="preserve"><value>Niente da ripristinare</value></data>
<data name="Editor.Copy.Undo" xml:space="preserve"><value>Annulla</value></data>
<data name="Editor.Empty" xml:space="preserve"><value>Scegli una sequenza in Libreria</value></data>
<data name="Editor.Error.FramesArriving" xml:space="preserve"><value>Si stanno aggiungendo foto a questa sequenza; attendi un momento e riprova.</value></data>
<data name="Editor.Error.FramesChanged" xml:space="preserve"><value>I fotogrammi di questa sequenza sono cambiati sul server; scarica di nuovo i proxy.</value></data>
<data name="Editor.Error.Missing" xml:space="preserve"><value>Questa sequenza non è più nell’archivio.</value></data>
<data name="Editor.Error.NoEngine" xml:space="preserve"><value>I lavori non possono partire finché l’indice dell’archivio non è aperto.</value></data>
+83 -20
View File
@@ -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 (<see cref="ProjectSaver"/>); 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 (<see cref="Conflict"/>). Call from one thread (the UI thread).
/// different values wait for the user's choice (<see cref="Conflict"/>). 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).
/// </summary>
public sealed class EditorSession : IAsyncDisposable
{
public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400);
/// <summary>Times a save reads the frames again when frames keep changing under it.</summary>
private const int FollowAttempts = 3;
/// <summary>Sections "Optimise all" walks through, in panel order.</summary>
public static IReadOnlyList<AdvisorSection> 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;
/// <summary>The sequence being read again (<see cref="ReloadAsync"/>) until its content is taken: saves wait for it.</summary>
private Task _reading = Task.CompletedTask;
public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList<EncoderCapability> codecs, TimeSpan? saveDelay = null)
{
ArgumentNullException.ThrowIfNull(source);
@@ -201,19 +209,31 @@ public sealed class EditorSession : IAsyncDisposable
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken);
/// <summary>Reads the sequence again (an analysis finished): new reports and advice, the stored project merged into the open one.</summary>
/// <summary>
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken.
/// </summary>
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();
}
/// <summary>
/// Takes <paramref name="content"/> 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 (<see cref="ProjectSettings.FollowFrames"/>), so
/// they keep naming the frames the user chose. Returns that move (none when the frames are the same).
/// </summary>
private Func<ProjectSettings, ProjectSettings> 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;
}
/// <summary>Exclusions, a hero, keyframes or frames waiting for their photos: positions that follow frames.</summary>
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<SequencePreset>) Analyse(SequenceContent content,
IReadOnlyList<EncoderCapability> 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;
+50 -13
View File
@@ -23,7 +23,10 @@ namespace Titano.App.Editor;
/// project in <c>.titano/project.json</c> 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 (<see cref="FramesChangedException"/>) until the editor has read them again
/// and moved its own positions the same way (<see cref="EditorSession"/>).
/// </summary>
public sealed class LocalSequenceSource : ISequenceSource
{
@@ -31,6 +34,9 @@ public sealed class LocalSequenceSource : ISequenceSource
private const int SaveAttempts = 3;
private const int JobsListed = 200;
/// <summary>Times the frames are listed again when an insertion lands while they are read.</summary>
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
/// <summary>The JPEG of each GPR frame that an import keeps in another sequence (<see cref="GprCompanions"/>), by position.</summary>
private string?[] _companions = [];
private Guid[] _frameIds = [];
/// <summary>The frames version of the frames last read (<see cref="LoadAsync"/>), whose order the project's positions follow.</summary>
private int _framesVersion = -1;
private ArchivePaths? _paths;
private SequencePaths? _folder;
@@ -74,15 +84,8 @@ public sealed class LocalSequenceSource : ISequenceSource
public async Task<SequenceContent> 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<Frame>();
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;
}
/// <summary>
/// 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.
/// </summary>
/// <exception cref="EditorException">The sequence is gone, or an insertion landed during every attempt.</exception>
private async Task<(Sequence Row, List<Frame> 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<Frame>();
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"));
}
/// <summary>The settings in force: the index copy, else <c>project.json</c>, else defaults.</summary>
/// <exception cref="EditorException">The settings are not a project or come from a newer Titano.</exception>
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"));
}
/// <summary>
/// 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.
/// </summary>
public sealed class FramesChangedException(string message) : EditorException(message);
+19
View File
@@ -78,6 +78,25 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
Changed?.Invoke();
}
/// <summary>
/// Rewrites the project and every undo and redo snapshot with <paramref name="remap"/>, 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.
/// </summary>
public void Remap(Func<ProjectSettings, ProjectSettings> 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<ProjectSettings> steps, ProjectMerge.Rebase rebase)
{
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value);
@@ -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
}
}
/// <summary>
/// A project written against the frames <paramref name="before"/> (frame ids, by index) moved to the frames
/// <paramref name="after"/> (in index order) the way the archive index moves its own copy when it takes them
/// (ProjectPositions in Titano.Data): while every frame of <paramref name="before"/> is still there, its positions
/// move with their frames (<see cref="MoveFramePositions"/>), otherwise they stay; either way pending frames whose
/// photos are now there take their place (<see cref="TranslateFramePositions"/>). An editor that read the frames
/// before frames were inserted saves its edit in the new order this way. Null when nothing changes.
/// </summary>
public static string? FollowFrames(string json, IReadOnlyList<Guid> before, IReadOnlyList<Frame> after)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var now = new Dictionary<Guid, int>(after.Count);
for (var i = 0; i < after.Count; i++) now[after[i].Id] = i;
Dictionary<int, int>? 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<JsonNode> replace, IReadOnlyDictionary<int, int> moves)
{
if (position is not JsonValue value || !value.TryGetValue<int>(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false;
@@ -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);
}
}
/// <summary>A short sequence without its analysis, whose frame ids are all different (the synthetic ids repeat every 64 frames).</summary>
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);
}
/// <summary>Photos captured before the first frame join the source's sequence, as an insertion renumbers it.</summary>
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<Frame> 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()
{
@@ -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()
{
@@ -167,6 +167,47 @@ public sealed class ProjectSettingsTests
Assert.Null(ProjectSettings.MoveFramePositions("""{ "heroFrame": 1, "HeroFrame": 1 }""", new Dictionary<int, int> { [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<Guid> 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<int>().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()
{