feat(app): editor session, project history, local source, preview renderer and export planner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 17:00:26 +00:00
1 parent 7d95536096
commit e6d1317aab
19 files changed
+2146

No files matched your search

@@ -0,0 +1,132 @@
using System.Globalization;
using Titano.App.Editor;
using Titano.Core.Analysis;
using Titano.Core.Analysis.Deep;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Render.Diagnostics;
using Titano.Data.Archiving.Jobs;
namespace Titano.App.Tests.Editor;
/// <summary>A synthetic sunset with flicker and two exposure steps, as the editor tests open it.</summary>
internal static class EditorFixture
{
private static readonly Lazy<SyntheticSequence> Shared = new(() => Sequence());
static EditorFixture() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
public static SyntheticSequence Sunset => Shared.Value;
public static SyntheticSequence Sequence(int frames = 72) => SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 96,
Height = 64,
FrameCount = frames,
StartEv = 0,
EndEv = -2,
FlickerEv = 0.25,
ExposureSteps = [new SyntheticExposureStep(24, -1), new SyntheticExposureStep(48, -1)],
StartKelvin = 5200,
EndKelvin = 3400,
});
/// <summary>The sequence as <see cref="ISequenceSource.LoadAsync"/> returns it, with a deep analysis when asked.</summary>
public static SequenceContent Content(SyntheticSequence sequence, ProjectSettings? project = null, bool deep = true)
{
var id = Guid.CreateVersion7();
var frames = sequence.Frames.Select(f => f with { SequenceId = id }).ToList();
var row = new Sequence
{
Id = id,
ArchiveId = Guid.CreateVersion7(),
Title = "Harbour sunset",
Folder = "2026/2026-09-28 Synthetic",
CameraMake = sequence.Options.CameraMake,
CameraModel = sequence.Options.CameraModel,
FirstCapture = frames[0].CapturedAt,
LastCapture = frames[^1].CapturedAt,
FrameCount = frames.Count,
MedianInterval = sequence.Options.IntervalSeconds,
};
var report = deep ? DeepAnalyzer.AnalyzeAsync(new Frames(sequence)).GetAwaiter().GetResult() : null;
return new SequenceContent(row, frames, project ?? new ProjectSettings(), LightAnalyzer.Analyze(frames), report, sequence.Options.Width,
sequence.Options.Height, null, []);
}
/// <summary>Synthetic frames as the deep analysis reads them.</summary>
private sealed class Frames(SyntheticSequence sequence) : IFrameSource
{
public int Count => sequence.Count;
public LightFrame Metadata(int index) => LightFrame.From(sequence.Metadata[index], index);
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) =>
ValueTask.FromResult<ImageBuffer?>(sequence.Render(index));
}
}
/// <summary>
/// An in-memory <see cref="ISequenceSource"/>: synthetic pixels, a stored project with the same merge rule as the
/// archive, recorded jobs. <see cref="ExternalEdit"/> simulates someone else changing the stored project before a save.
/// </summary>
internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceContent content) : ISequenceSource
{
private readonly SyntheticFrameSource _pixels = new(sequence);
public ProjectSettings Stored { get; set; } = content.Project;
public SequenceContent Content { get; set; } = content;
public List<ArchiveJobRequest> Submitted { get; } = [];
public int Saves { get; private set; }
public int Decodes { get; private set; }
/// <summary>Applied to the stored project before the next save reads it.</summary>
public Func<ProjectSettings, ProjectSettings>? ExternalEdit { get; set; }
/// <summary>Thrown by the next save.</summary>
public Exception? FailNextSave { get; set; }
/// <summary>Awaited by every decode (tests of cancellation).</summary>
public Task DecodeGate { get; set; } = Task.CompletedTask;
public Task<SequenceContent> LoadAsync(CancellationToken cancellationToken) => Task.FromResult(Content with { Project = Stored });
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
await DecodeGate.WaitAsync(cancellationToken);
Decodes++;
return await _pixels.GetFrameAsync(index, maxLongEdge, purpose, cancellationToken);
}
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
{
if (FailNextSave is { } failure)
{
FailNextSave = null;
return Task.FromException<ProjectSettings>(failure);
}
if (ExternalEdit is { } edit)
{
Stored = edit(Stored);
ExternalEdit = null;
}
Stored = ProjectMerge.SameValues(Stored, basis) ? project : ProjectMerge.Merge(basis, project, Stored);
Saves++;
return Task.FromResult(Stored);
}
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
Submitted.Add(request);
return Task.FromResult(Guid.CreateVersion7());
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
@@ -0,0 +1,206 @@
using System.IO;
using System.Text.Json;
using Titano.App.Editor;
using Titano.Core.Advice;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Protocol;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
public sealed class EditorSessionTests
{
private static (EditorSession Session, FakeSequenceSource Source) Open(ProjectSettings? project = null, bool deep = true)
{
var content = EditorFixture.Content(EditorFixture.Sunset, project, deep);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
return (new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)), source);
}
[Test]
public async Task EditsAreSavedAndUndoable()
{
var (session, source) = Open();
await using (session)
{
Assert.True(session.Edit(p => EditorSettings.Deflicker.WithManual(p, true)));
await session.FlushAsync();
Assert.True(source.Stored.Exposure.Deflicker is { IsAuto: false, Manual: true });
Assert.True(session.Undo());
await session.FlushAsync();
Assert.True(source.Stored.Exposure.Deflicker.IsAuto, "undo is saved too");
Assert.True(session.Redo());
await session.FlushAsync();
Assert.False(source.Stored.Exposure.Deflicker.IsAuto);
}
}
[Test]
public async Task RapidEditsSaveOnce()
{
var (session, source) = Open();
await using (session)
{
for (var i = 1; i <= 20; i++) session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = i / 20.0 } }, "offset");
await session.FlushAsync();
Assert.Equal(1, source.Saves);
Assert.Equal(1.0, source.Stored.Exposure.ExposureOffsetEv);
}
}
[Test]
public async Task AChangeStoredMeanwhileIsMergedIntoTheEditor()
{
var (session, source) = Open();
await using (session)
{
source.ExternalEdit = p => p with { Camera = p.Camera with { OffsetY = -0.2 } };
session.Edit(p => p with { HeroFrame = 5 });
await session.FlushAsync();
Assert.Equal(5, session.Project.HeroFrame);
Assert.Equal(-0.2, session.Project.Camera.OffsetY, "their change shows up in the editor");
Assert.True(session.Undo());
Assert.Null(session.Project.HeroFrame);
}
}
[Test]
public async Task AFailedSaveIsReportedAndRetriedByTheNextChange()
{
var (session, source) = Open();
await using (session)
{
Exception? reported = null;
session.SaveFailed += ex => reported = ex;
source.FailNextSave = new IOException("share offline");
session.Edit(p => p with { HeroFrame = 1 });
await session.FlushAsync();
Assert.NotNull(reported);
session.Edit(p => p with { HeroFrame = 2 });
await session.FlushAsync();
Assert.Equal(2, source.Stored.HeroFrame);
}
}
[Test]
public async Task OptimiseSectionTakesTheHeavierDecisionsAsOneStep()
{
// The user turned deflicker off by hand; the analysis measured flicker, so Optimise returns it to Auto (on).
var start = new ProjectSettings();
start = start with { Exposure = start.Exposure with { Deflicker = start.Exposure.Deflicker.WithManual(false) } };
var (session, _) = Open(start);
await using (session)
{
var advice = session.Advice.Find(AdvisorParameters.Deflicker);
Assert.NotNull(advice);
Assert.Equal(true, advice!.Value);
session.Edit(p => Advisor.Apply(p, session.Advice));
Assert.False(EditorSettings.Deflicker.Effective(session.Project, null), "advice never overrides a manual value");
var changes = session.Optimise(AdvisorSection.Exposure);
Assert.True(EditorSettings.Deflicker.Effective(session.Project, null));
Assert.True(session.Project.Exposure.Deflicker.IsAuto);
var change = Assert.Contains(changes, c => c.Parameter == AdvisorParameters.Deflicker);
Assert.Equal(false, change.Before);
Assert.Equal(true, change.After);
Assert.True(session.Undo());
Assert.False(session.Project.Exposure.Deflicker.IsAuto, "one undo restores the manual choice");
}
}
[Test]
public async Task WithoutAnalysisOptimiseChangesNothingItCannotMeasure()
{
var (session, _) = Open(deep: false);
await using (session)
{
Assert.True(session.Advice.Find(AdvisorParameters.Deflicker)!.IsMissingData);
var changes = session.Optimise(AdvisorSection.Exposure);
Assert.DoesNotContain(AdvisorParameters.Deflicker, changes.Select(c => c.Parameter));
Assert.False(session.Project.Exposure.Deflicker.HasAdvice);
}
}
[Test]
public async Task ResetReturnsTheSectionToAuto()
{
var (session, _) = Open();
await using (session)
{
session.Edit(p => EditorSettings.Stabilize.WithManual(p, true));
session.Edit(p => EditorSettings.ShutterAngle.WithManual(p, 90.0));
session.Edit(p => EditorSettings.Deflicker.WithManual(p, true));
Assert.False(EditorSettings.IsSectionAuto(session.Project, AdvisorSection.Motion));
Assert.True(session.ResetSection(AdvisorSection.Motion));
Assert.True(EditorSettings.IsSectionAuto(session.Project, AdvisorSection.Motion));
Assert.False(session.Project.Exposure.Deflicker.IsAuto, "other sections keep their values");
}
}
[Test]
public async Task ExclusionsAndHeroAreFrameIndices()
{
var (session, _) = Open();
await using (session)
{
Assert.True(session.SetExcluded([5, 3, 400], excluded: true));
Assert.SequenceEqual([3, 5], session.Project.ExcludedFrames);
Assert.True(session.SetExcluded([3], excluded: false));
Assert.SequenceEqual([5], session.Project.ExcludedFrames);
Assert.False(session.SetHero(999));
Assert.True(session.SetHero(10));
Assert.Equal(10, session.Project.HeroFrame);
}
}
[Test]
public async Task RenderRequestsEmbedTheProjectAndTheExport()
{
var (session, source) = Open();
await using (session)
{
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.7 } });
var export = session.ExportFor("4k-hevc");
Assert.Empty(export.Batch);
var request = session.RenderRequest(export with { Batch = ["1080p-h264"] });
Assert.Equal(JobKind.Render, request.Kind);
Assert.SequenceEqual([session.Content.Sequence.Id], request.Targets);
Assert.Equal(JobPriority.User, request.Priority);
var parameters = JsonSerializer.Deserialize(request.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
Assert.Equal("hevc", parameters.Codec);
Assert.Equal(3840, parameters.Width);
Assert.Contains("1080p-h264", parameters.PresetJson);
var embedded = ProjectSettings.FromJson(parameters.SettingsJson!);
Assert.Equal(0.7, embedded.Exposure.ExposureOffsetEv);
Assert.Equal("4k-hevc", embedded.Export.Preset.Manual);
await session.SubmitAsync(request);
await session.SubmitAsync(session.AnalysisRequest());
Assert.Equal(2, source.Submitted.Count);
Assert.Equal(JobKind.DeepAnalyse, source.Submitted[1].Kind);
}
}
[Test]
public async Task ReloadBringsNewAnalysisAndKeepsUserValues()
{
var (session, source) = Open(deep: false);
await using (session)
{
Assert.Null(session.Content.Deep);
session.Edit(p => p with { HeroFrame = 2 });
source.Content = EditorFixture.Content(EditorFixture.Sunset, deep: true) with { Sequence = session.Content.Sequence };
source.Stored = Advisor.Apply(source.Stored, session.Advice);
var changed = 0;
session.ContentChanged += () => changed++;
await session.ReloadAsync();
Assert.Equal(1, changed);
Assert.NotNull(session.Content.Deep);
Assert.False(session.Advice.Find(AdvisorParameters.Deflicker)!.IsMissingData, "advice from the new analysis");
Assert.Equal(2, session.Project.HeroFrame);
}
}
}
@@ -0,0 +1,93 @@
using Titano.App.Editor;
using Titano.Core.Advice;
using Titano.Core.Export;
using Titano.Core.Project;
using Titano.Core.Video;
using Titano.Core.Video.Managed;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
public sealed class ExportPlannerTests
{
private static readonly SequenceContent Content = EditorFixture.Content(EditorFixture.Sunset);
private static ExportPlanner Planner(EncoderHost host = EncoderHost.Client) => new(Content, [new ManagedEncoderProvider()], host);
[Test]
public void TheListHasSequencePresetsFirstThenEveryBuiltInPreset()
{
var context = SequenceContext.FromFrames(Content.Frames);
var advice = Advisor.Recommend(Content.Light, Content.Deep, context);
var presets = SequencePresets.Generate(Content.Light, Content.Deep, context);
var choices = ExportPlanner.Choices(presets, advice);
Assert.Equal(presets.Count + ExportPresets.BuiltIn.Count, choices.Count);
Assert.True(choices.Take(presets.Count).All(c => c.Sequence is not null));
Assert.SequenceEqual(ExportPresets.BuiltIn.Select(p => p.Id), choices.Skip(presets.Count).Select(c => c.Id));
var recommended = Assert.Contains(choices, c => c.IsRecommended);
Assert.Equal(advice.Find(AdvisorParameters.ExportPreset)!.Value, recommended.ExportPresetId);
Assert.NotNull(recommended.Reason);
Assert.True(choices.All(c => c.Name.Length > 0 && !c.Name.StartsWith("Export.", StringComparison.Ordinal)), "names are localised");
}
[Test]
public void AnImageSequenceIsEstimatedAndNamedAsAFolder()
{
var project = new ProjectSettings();
project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("png-sequence"), NameTemplate = "{title} {width}x{height} {codec}" } };
var plan = Planner().Plan(project);
Assert.NotNull(plan);
Assert.True(plan!.Setup.Encoder.IsReady);
Assert.Equal(96, plan.Setup.Encoder.Settings.Width);
Assert.Equal("Harbour sunset 96x64 PNG", plan.FileName, "no extension: a folder of frames");
Assert.Null(plan.NameError);
var workload = plan.Setup.Workload();
Assert.Equal(ExportEstimator.EstimateBytes(plan.Export with { Codec = VideoCodec.PngSequence }, workload), plan.Estimate.Bytes);
Assert.Greater(plan.Estimate.Bytes, 0);
Assert.Greater(plan.Estimate.Time.TotalSeconds, 0);
}
[Test]
public void ExcludedFramesShortenTheEstimate()
{
var project = new ProjectSettings();
project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("jpeg-sequence") } };
var all = Planner().Plan(project)!;
var fewer = Planner().Plan(project with { ExcludedFrames = [.. Enumerable.Range(0, 36)] })!;
Assert.Equal(Content.Count, all.Setup.Plan.Frames.Count);
Assert.Less(fewer.Estimate.Bytes, all.Estimate.Bytes);
}
[Test]
public void VideoWithoutAnEncoderExplainsWhy()
{
var plan = Planner().Plan(new ProjectSettings())!;
Assert.False(plan.Setup.Encoder.IsReady, "only managed encoders here; H.264 needs Media Foundation or a render node");
Assert.Contains(plan.Setup.Encoder.Notices, n => n.Key == EncoderNotices.NoEncoder);
var server = Planner(EncoderHost.Server).Plan(new ProjectSettings())!;
Assert.Equal(EncoderSelectionStatus.NeedsRenderNode, server.Setup.Encoder.Status);
}
[Test]
public void ABrokenTemplateIsExplainedAndStillNamesTheFile()
{
var project = new ProjectSettings();
project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("gif-preview"), NameTemplate = "{title} {nope}" } };
var plan = Planner().Plan(project)!;
Assert.Equal("Unknown token “nope” at position 9.", plan.NameError);
Assert.Equal("Harbour sunset.gif", plan.FileName);
}
[Test]
public void EditingAValueMakesThePresetCustom()
{
var project = new ProjectSettings();
project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("png-sequence"), Overrides = new ExportOverrides { Width = 48 } } };
var plan = Planner().Plan(project)!;
Assert.True(plan.Export.IsCustom);
Assert.Equal("Custom", plan.PresetName);
Assert.Equal(48, plan.Setup.Encoder.Settings.Width);
}
}
@@ -0,0 +1,121 @@
using Titano.App.Editor;
using Titano.Core.Imaging;
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>The corrected-frame preview through the render pipeline at preview size.</summary>
public sealed class PreviewRendererTests
{
private static (PreviewRenderer Renderer, FakeSequenceSource Source) Create()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
return (new PreviewRenderer(content, source), source);
}
private static ProjectSettings Deflickered()
{
var p = new ProjectSettings();
return p with { Exposure = p.Exposure with { Deflicker = p.Exposure.Deflicker.WithManual(true), HighlightKnee = null } };
}
[Test]
public async Task DeflickerFlattensThePreviewedLuminance()
{
var (renderer, _) = Create();
var project = Deflickered();
var corrections = await renderer.PrepareAsync(project, CancellationToken.None);
Assert.Same(corrections, renderer.Cached(project));
Assert.Null(renderer.Cached(new ProjectSettings()), "other exposure settings need their own preparation");
var corrected = new List<double>();
var original = new List<double>();
for (var i = 4; i < 20; i++)
{
using var frame = await renderer.RenderAsync(new PreviewRequest(i, project, 64, PreviewFraming.Output), corrections, CancellationToken.None);
Assert.NotNull(frame);
corrected.Add(LogMean(frame!.Corrected));
original.Add(LogMean(frame.Original));
}
Assert.Less(Spread(corrected), Spread(original) * 0.6, "flicker removed between the steps");
}
[Test]
public async Task OutputFramingFollowsTheExportAspect()
{
var (renderer, _) = Create();
var project = new ProjectSettings();
project = project with { Export = project.Export with { Preset = project.Export.Preset.WithManual("square-1440") } };
using var output = await renderer.RenderAsync(new PreviewRequest(0, project, 80, PreviewFraming.Output), null, CancellationToken.None);
Assert.Equal(80, output!.Corrected.Width, "the square output at the preview's long edge");
Assert.Equal(80, output.Corrected.Height);
Assert.Equal(output.Corrected.Width, output.Original.Width);
using var source = await renderer.RenderAsync(new PreviewRequest(0, project, 80, PreviewFraming.Source), null, CancellationToken.None);
Assert.Equal(80, source!.Corrected.Width);
Assert.Approximately(64.0 / 96, source.Crop.Width, 0.02, "the square crop keeps two thirds of the 3:2 frame");
Assert.Approximately(1, source.Crop.Height, 0.02);
Assert.Approximately((1 - 64.0 / 96) / 2, source.Crop.X, 0.02, "centred");
}
[Test]
public async Task VectorsDescribeTheMotionToTheNextFrame()
{
var (renderer, _) = Create();
using var frame = await renderer.RenderAsync(new PreviewRequest(10, new ProjectSettings(), 96, PreviewFraming.Source, Vectors: true), null,
CancellationToken.None);
Assert.NotEmpty(frame!.Vectors);
Assert.True(frame.Vectors.All(v => v.X >= 0 && v.X < 96 && v.Y >= 0 && v.Y < 64));
using var last = await renderer.RenderAsync(new PreviewRequest(EditorFixture.Sunset.Count - 1, new ProjectSettings(), 96, PreviewFraming.Source, true),
null, CancellationToken.None);
Assert.Empty(last!.Vectors);
}
[Test]
public async Task ACancelledPreviewStopsWhileDecoding()
{
var (renderer, source) = Create();
source.DecodeGate = new TaskCompletionSource().Task;
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await Assert.ThrowsAsync<OperationCanceledException>(() => renderer.RenderAsync(new PreviewRequest(0, new ProjectSettings(), 64, PreviewFraming.Output), null, cts.Token));
}
[Test]
public async Task AnUnknownFrameHasNoPreview()
{
var (renderer, _) = Create();
Assert.Null(await renderer.RenderAsync(new PreviewRequest(-1, new ProjectSettings(), 64, PreviewFraming.Output), null, CancellationToken.None));
Assert.Null(await renderer.RenderAsync(new PreviewRequest(10_000, new ProjectSettings(), 64, PreviewFraming.Output), null, CancellationToken.None));
}
[Test]
public async Task PreparedDecodesAreReused()
{
var (renderer, source) = Create();
var project = new ProjectSettings();
project = project with { Exposure = project.Exposure with { WhiteBalanceSmoothing = project.Exposure.WhiteBalanceSmoothing.WithManual(true) } };
await renderer.PrepareAsync(project, CancellationToken.None);
var decodes = source.Decodes;
Assert.GreaterOrEqual(decodes, EditorFixture.Sunset.Count, "white balance is measured on every frame");
await renderer.PrepareAsync(project with { Exposure = project.Exposure with { ExposureOffsetEv = 0.5 } }, CancellationToken.None);
Assert.Equal(decodes, source.Decodes);
}
private static double LogMean(ImageBuffer image)
{
double sum = 0;
var n = image.PlaneLength;
for (var i = 0; i < n; i++) sum += 0.2126 * image.Plane(0)[i] + 0.7152 * image.Plane(1)[i] + 0.0722 * image.Plane(2)[i];
return Math.Log2(sum / n);
}
/// <summary>Standard deviation of the frame-to-frame differences (flicker, not the slow ramp).</summary>
private static double Spread(List<double> values)
{
var diffs = values.Zip(values.Skip(1), (a, b) => b - a).ToList();
var mean = diffs.Average();
return Math.Sqrt(diffs.Sum(d => (d - mean) * (d - mean)) / diffs.Count);
}
}
@@ -0,0 +1,90 @@
using Titano.App.Editor;
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
public sealed class ProjectHistoryTests
{
private static ProjectSettings WithOffset(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } };
[Test]
public void UndoAndRedoWalkTheSnapshots()
{
var start = new ProjectSettings();
var history = new ProjectHistory(start);
var changes = 0;
history.Changed += () => changes++;
Assert.True(history.Apply(WithOffset(start, 0.5)));
Assert.True(history.Apply(WithOffset(history.Current, 1.0)));
Assert.Equal(1.0, history.Current.Exposure.ExposureOffsetEv);
Assert.True(history.Undo());
Assert.Equal(0.5, history.Current.Exposure.ExposureOffsetEv);
Assert.True(history.Undo());
Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv);
Assert.False(history.Undo(), "nothing left to undo");
Assert.True(history.CanRedo);
Assert.True(history.Redo());
Assert.Equal(0.5, history.Current.Exposure.ExposureOffsetEv);
Assert.Equal(5, changes);
}
[Test]
public void ANewEditClearsRedo()
{
var history = new ProjectHistory(new ProjectSettings());
history.Apply(WithOffset(history.Current, 0.5));
history.Undo();
history.Apply(WithOffset(history.Current, -0.5));
Assert.False(history.CanRedo);
Assert.False(history.Redo());
}
[Test]
public void EditsWithTheSameKeyAreOneStep()
{
var history = new ProjectHistory(new ProjectSettings());
for (var i = 1; i <= 10; i++) history.Apply(WithOffset(history.Current, i / 10.0), "Exposure.Offset");
history.Apply(history.Current with { HeroFrame = 3 }, "Frames.Hero");
Assert.True(history.Undo());
Assert.Equal(1.0, history.Current.Exposure.ExposureOffsetEv, "the hero step undone");
Assert.True(history.Undo());
Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv, "the whole drag undone in one step");
Assert.False(history.CanUndo);
}
[Test]
public void AnEditThatChangesNothingIsNotAStep()
{
var history = new ProjectHistory(new ProjectSettings());
Assert.False(history.Apply(new ProjectSettings()), "equal values, even as a new instance");
Assert.False(history.CanUndo);
}
[Test]
public void ReplaceAdoptsWithoutAnUndoStep()
{
var history = new ProjectHistory(new ProjectSettings());
history.Apply(WithOffset(history.Current, 0.5));
history.Replace(history.Current with { HeroFrame = 7 });
Assert.Equal(7, history.Current.HeroFrame);
Assert.True(history.Undo());
Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv);
Assert.False(history.CanUndo);
}
[Test]
public void TheOldestStepsAreDroppedBeyondCapacity()
{
var history = new ProjectHistory(new ProjectSettings(), capacity: 3);
for (var i = 1; i <= 5; i++) history.Apply(history.Current with { HeroFrame = i });
var undone = 0;
while (history.Undo()) undone++;
Assert.Equal(3, undone);
Assert.Equal(2, history.Current.HeroFrame);
}
}
@@ -0,0 +1,157 @@
using System.IO;
using Titano.App.Editor;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Data.Repositories;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>Project merges, and the local source over a real SQLite index and archive folder.</summary>
public sealed class ProjectStoreTests(TestContext context)
{
[Test]
public void AMemberOnlyTheyChangedIsKept()
{
var basis = new ProjectSettings();
var ours = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.5 } };
var theirs = basis with { HeroFrame = 12 };
var merged = ProjectMerge.Merge(basis, ours, theirs);
Assert.Equal(0.5, merged.Exposure.ExposureOffsetEv);
Assert.Equal(12, merged.HeroFrame);
}
[Test]
public void AdviceMergesIntoAManualValueOfTheSameSetting()
{
var basis = new ProjectSettings();
var ours = basis with { Exposure = basis.Exposure with { Deflicker = basis.Exposure.Deflicker.WithManual(true) } };
var theirs = basis with { Exposure = basis.Exposure with { Deflicker = basis.Exposure.Deflicker.WithAdvice(false, "Advisor.Reason.Deflicker.Off") } };
var merged = ProjectMerge.Merge(basis, ours, theirs).Exposure.Deflicker;
Assert.False(merged.IsAuto, "the user's manual choice stays");
Assert.True(merged.Manual);
Assert.True(merged.HasAdvice, "the new advice is stored next to it");
Assert.Equal("Advisor.Reason.Deflicker.Off", merged.ReasonKey);
}
[Test]
public void WhenBothChangedAValueTheEditorWins()
{
var basis = new ProjectSettings();
var merged = ProjectMerge.Merge(basis, basis with { HeroFrame = 3 }, basis with { HeroFrame = 9 });
Assert.Equal(3, merged.HeroFrame);
}
[Test]
public async Task TheLocalSourceReadsDecodesSavesAndQueues()
{
var (db, sequenceId, root) = await ArchiveAsync(12);
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);
Assert.Equal(12, content.Count);
Assert.Equal(96, content.SourceWidth);
Assert.Equal(64, content.SourceHeight);
Assert.Null(content.Deep, "not analysed yet");
Assert.NotNull(content.ExportsFolder);
Assert.Contains("exports", content.ExportsFolder!);
using (var frame = await source.DecodeAsync(3, 32, DecodePurpose.Thumbnail, context.Cancellation))
{
Assert.NotNull(frame);
Assert.LessOrEqual(Math.Max(frame!.Width, frame.Height), 32);
}
Assert.Null(await source.DecodeAsync(99, 32, DecodePurpose.Thumbnail, context.Cancellation));
// A save writes project.json and the index row together.
var edited = content.Project with { HeroFrame = 4, Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.3 } };
var stored = await source.SaveProjectAsync(edited, content.Project, context.Cancellation);
Assert.True(ProjectMerge.SameValues(edited, stored));
var projectPath = Path.Combine(root, "Synthetic", ".titano", "project.json");
Assert.FileExists(projectPath);
Assert.Equal(edited.ToJson(), File.ReadAllText(projectPath));
var row = await db.Sequences.GetAsync(sequenceId);
Assert.Equal(edited.ToJson(), row!.SettingsJson);
// Someone else changes the settings meanwhile (the server API): both edits survive the next save.
var theirs = stored with { Camera = stored.Camera with { OffsetY = 0.25 } };
await db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = theirs.ToJson() }, row.SettingsVersion);
var mine = stored with { HeroFrame = 7 };
var merged = await source.SaveProjectAsync(mine, stored, context.Cancellation);
Assert.Equal(7, merged.HeroFrame);
Assert.Equal(0.25, merged.Camera.OffsetY);
Assert.Equal(merged.ToJson(), File.ReadAllText(projectPath));
Assert.Equal(merged.ToJson(), (await db.Sequences.GetAsync(sequenceId))!.SettingsJson);
var reloaded = await source.LoadAsync(context.Cancellation);
Assert.True(ProjectMerge.SameValues(merged, reloaded.Project), "the index copy is read back");
await Assert.ThrowsAsync<InvalidOperationException>(() => source.SubmitAsync(ProcessingJobs.DeepAnalysis([sequenceId]), context.Cancellation));
}
}
[Test]
public async Task JobsGoToTheEngine()
{
var (db, sequenceId, _) = await ArchiveAsync(4);
await using (db)
{
await using var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "test" });
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), engine);
var content = await source.LoadAsync(context.Cancellation);
var session = new EditorSession(source, content, []);
var id = await session.SubmitAsync(session.AnalysisRequest(), context.Cancellation);
var job = await db.Jobs.GetAsync(id);
Assert.Equal(JobKind.DeepAnalyse, job!.Kind);
Assert.Equal(JobState.Queued, job.State);
Assert.SequenceEqual([sequenceId], job.TargetIds);
}
}
[Test]
public async Task AnUnreadableProjectIsReportedNotReplaced()
{
var (db, sequenceId, root) = await ArchiveAsync(4);
await using (db)
{
var path = Path.Combine(root, "Synthetic", ".titano", "project.json");
File.WriteAllText(path, "{ not json");
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null);
await Assert.ThrowsAsync<InvalidDataException>(() => source.LoadAsync(context.Cancellation));
Assert.Equal("{ not json", File.ReadAllText(path));
}
}
/// <summary>A temporary archive with one adopted folder of synthetic JPEGs, indexed.</summary>
private async Task<(TitanoDatabase Db, Guid SequenceId, string Root)> ArchiveAsync(int frames)
{
var directory = context.CreateTempDirectory("editor");
var root = Path.Combine(directory, "archive");
var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
var service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
var archive = await service.CreateAsync(root, "Test");
var sequence = EditorFixture.Sequence(frames);
var folder = Path.Combine(root, "Synthetic");
Directory.CreateDirectory(folder);
for (var i = 0; i < sequence.Count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
await service.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
var location = (await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single();
return (db, location.Id, root);
}
}
@@ -0,0 +1,133 @@
using System.Collections.Concurrent;
using Titano.App.Editor;
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>Debouncing and cancellation of preview work, and the coalescing project writer.</summary>
public sealed class SchedulingTests
{
[Test]
public async Task OnlyTheLastOfRapidRequestsRuns()
{
using var runner = new LatestRunner(TimeSpan.FromMilliseconds(80));
var ran = new ConcurrentQueue<int>();
var tasks = Enumerable.Range(0, 10).Select(i => runner.Schedule(_ =>
{
ran.Enqueue(i);
return Task.CompletedTask;
})).ToList();
await Task.WhenAll(tasks);
Assert.SequenceEqual([9], ran);
}
[Test]
public async Task ANewRequestCancelsTheRunningOne()
{
using var runner = new LatestRunner(TimeSpan.Zero);
var started = new TaskCompletionSource();
var cancelled = false;
var first = runner.Schedule(async token =>
{
started.SetResult();
try
{
await Task.Delay(Timeout.Infinite, token);
}
catch (OperationCanceledException)
{
cancelled = true;
throw;
}
});
await started.Task;
var second = runner.Schedule(_ => Task.CompletedTask);
await Task.WhenAll(first, second);
Assert.True(cancelled, "the superseded run saw its token cancelled");
Assert.True(first.IsCompletedSuccessfully, "a superseded run ends quietly");
}
[Test]
public async Task ImmediateRequestsSkipTheDelay()
{
using var runner = new LatestRunner(TimeSpan.FromSeconds(30));
var ran = false;
await runner.Schedule(_ =>
{
ran = true;
return Task.CompletedTask;
}, immediate: true).WaitAsync(TimeSpan.FromSeconds(10));
Assert.True(ran);
}
[Test]
public async Task FailuresSurfaceFromTheRun()
{
using var runner = new LatestRunner(TimeSpan.Zero);
await Assert.ThrowsAsync<InvalidOperationException>(() => runner.Schedule(_ => throw new InvalidOperationException("broken")));
}
[Test]
public async Task CancelStopsThePendingRequest()
{
using var runner = new LatestRunner(TimeSpan.FromMilliseconds(200));
var ran = false;
var run = runner.Schedule(_ =>
{
ran = true;
return Task.CompletedTask;
});
runner.Cancel();
await run;
Assert.False(ran);
}
[Test]
public async Task TheSaverWritesTheNewestProjectOnce()
{
var saved = new List<int?>();
var saver = new ProjectSaver(p =>
{
saved.Add(p.HeroFrame);
return Task.CompletedTask;
}, TimeSpan.FromMilliseconds(50));
for (var i = 0; i < 5; i++) saver.Schedule(new ProjectSettings { HeroFrame = i });
await saver.FlushAsync();
Assert.SequenceEqual([(int?)4], saved);
Assert.False(saver.HasPendingChanges);
}
[Test]
public async Task FlushSkipsTheDelay()
{
var saved = 0;
var saver = new ProjectSaver(_ =>
{
saved++;
return Task.CompletedTask;
}, TimeSpan.FromMinutes(5));
saver.Schedule(new ProjectSettings());
await saver.FlushAsync().WaitAsync(TimeSpan.FromSeconds(10));
Assert.Equal(1, saved);
}
[Test]
public async Task AChangeDuringAWriteIsWrittenAfterIt()
{
var gate = new TaskCompletionSource();
var saved = new List<int?>();
var saver = new ProjectSaver(async p =>
{
saved.Add(p.HeroFrame);
if (saved.Count == 1) await gate.Task;
}, TimeSpan.Zero);
saver.Schedule(new ProjectSettings { HeroFrame = 1 });
while (saved.Count == 0) await Task.Delay(5);
saver.Schedule(new ProjectSettings { HeroFrame = 2 });
saver.Schedule(new ProjectSettings { HeroFrame = 3 });
gate.SetResult();
await saver.FlushAsync();
Assert.SequenceEqual([(int?)1, 3], saved);
}
}