test(app): editor history, saver retry, merge, preview re-solve and capture scenes

- Tests for undo after adopted changes, run ending, saver retries and stop,
  the local source refusing unsaved writes, re-solves without decoding and equal
  to a fresh preparation, 1:1 pictures, waveform, crop margins and the values of
  the Optimise toast; the Windows smoke test checks Render, Batch, the waveform,
  1:1, the window title and the hidden idle job bar.
- The capture sample has a manual value and camera keyframes; the capture adds
  the overlays, the waveform, the Optimise toast and Export.html's tool state.
- Crop margins live in a WPF-free class; a discarded change stops retrying.

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-03 10:44:21 +00:00
1 parent 25e85aee57
commit fa5699e6f3
15 files changed
+462 -53

No files matched your search

@@ -2,6 +2,7 @@ using System.IO;
using System.Text.Json;
using Titano.App.Editor;
using Titano.Core.Advice;
using Titano.Core.Analysis;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Protocol;
@@ -61,29 +62,62 @@ public sealed class EditorSessionTests
{
source.ExternalEdit = p => p with { Camera = p.Camera with { OffsetY = -0.2 } };
session.Edit(p => p with { HeroFrame = 5 });
await session.FlushAsync();
Assert.True(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);
Assert.Equal(-0.2, session.Project.Camera.OffsetY, "undo keeps their change");
Assert.True(await session.FlushAsync());
Assert.Equal(-0.2, source.Stored.Camera.OffsetY, "and the undone project stored over it keeps it too");
Assert.True(session.Redo());
Assert.Equal(-0.2, session.Project.Camera.OffsetY);
}
}
[Test]
public async Task AFailedSaveIsReportedAndRetriedByTheNextChange()
public async Task AdviceFromAReloadSurvivesUndo()
{
var (session, source) = Open(deep: false);
await using (session)
{
session.Edit(p => p with { HeroFrame = 2 });
Assert.True(await session.FlushAsync());
// The deep analysis finished: its advice is stored, the editor reads it back.
source.Content = EditorFixture.Content(EditorFixture.Sunset, deep: true) with { Sequence = session.Content.Sequence };
var advice = Advisor.Recommend(source.Content.Light, source.Content.Deep, SequenceContext.FromFrames(source.Content.Frames));
source.Stored = Advisor.Apply(source.Stored, advice);
await session.ReloadAsync();
Assert.True(session.Project.Exposure.Deflicker.HasAdvice);
Assert.True(session.Undo());
Assert.Null(session.Project.HeroFrame);
Assert.True(session.Project.Exposure.Deflicker.HasAdvice, "undo does not wipe the advice");
Assert.True(await session.FlushAsync());
Assert.True(source.Stored.Exposure.Deflicker.HasAdvice, "nor does the save that follows");
}
}
[Test]
public async Task AFailedSaveStaysPendingUntilItIsStored()
{
var (session, source) = Open();
await using (session)
{
Exception? reported = null;
session.SaveFailed += ex => reported = ex;
var reported = 0;
session.SaveFailed += _ => reported++;
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);
Assert.False(await session.FlushAsync(), "the flush reports the failure");
Assert.Equal(1, reported);
Assert.True(session.HasPendingSave, "closing the window must not drop the edit");
Assert.NotNull(session.LastSaveError);
Assert.Null(source.Stored.HeroFrame);
Assert.True(await session.FlushAsync(), "the retry stores it without another edit");
Assert.Equal(1, source.Stored.HeroFrame);
Assert.False(session.HasPendingSave);
Assert.Null(session.LastSaveError);
}
}
@@ -60,6 +60,15 @@ public sealed class EditorSmokeTests
Assert.NotNull(editor.Session.Content.Deep, "the sample is analysed");
Assert.True(editor.Session.Project.Exposure.Deflicker.HasAdvice, "the advice is in the project");
Assert.Equal("Harbour sunset", editor.Title);
Assert.Equal("Titano — Harbour sunset", shell.WindowTitle, "the window title follows the open sequence");
Assert.False(shell.IsJobBarVisible, "the idle job bar gives its height to the editor");
// The Render split button can be clicked once the plan exists (its command re-reads its state).
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await SettleAsync(window);
Assert.True(editor.CanRender, editor.RenderBlockedReason ?? "renderable");
var render = Find<SplitButton>(window).Single(b => b.IsVisible);
Assert.True(Find<Button>(render).First().IsEnabled, "Render is enabled");
foreach (var theme in Themes)
{
@@ -78,6 +87,35 @@ public sealed class EditorSmokeTests
}
}
// The Export tab: Add to queue and Batch follow the plan and the ticked presets.
ThemeManager.Apply(AppTheme.Dark);
var export = editor.Tabs.OfType<ExportTab>().Single();
editor.ShowVectors = true;
editor.SelectedTab = export;
await SettleAsync(window);
Assert.False(Find<PreviewViewport>(window).Single(p => p.IsVisible).ShowVectors, "a tool without a button on the Export tab draws nothing");
Assert.True(export.AddToQueueCommand.CanExecute(null));
Assert.False(export.BatchCommand.CanExecute(null), "nothing ticked");
var batchButton = Find<Button>(window).Single(b => ReferenceEquals(b.Command, export.BatchCommand));
Assert.False(batchButton.IsEnabled);
export.Cards.First(c => c.CanBatch).IsInBatch = true;
await SettleAsync(window);
Assert.True(batchButton.IsEnabled, "ticking a card enables Batch…");
editor.ShowVectors = false;
// The waveform of the Exposure tab is measured from the preview.
editor.SelectedTab = editor.Exposure;
editor.Exposure.ChartMode = ExposureChart.Waveform;
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.NotNull(editor.WaveformImage, "the waveform shows the frame on screen");
editor.Exposure.ChartMode = ExposureChart.Luminance;
// 1:1 renders the source's own pixels; Fit returns to the view's size.
editor.ZoomMode = PreviewZoomMode.Actual;
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.Equal(editor.Session.Content.SourceWidth, ((BitmapSource)editor.PreviewImage!).PixelWidth, "1:1 shows source pixels");
editor.ZoomMode = PreviewZoomMode.Fit;
// An edit through the session is undone and redone (Ctrl+Z / Ctrl+Y run the same commands).
ThemeManager.Apply(AppTheme.Dark);
var before = editor.Session.Project.Exposure.ExposureOffsetEv;
@@ -0,0 +1,62 @@
using Titano.App.Editor;
using Titano.Core.Advice;
using Titano.Core.Imaging;
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>Composed texts of the editor, crop margins and the waveform monitor.</summary>
public sealed class EditorTextTests
{
static EditorTextTests() => _ = EditorFixture.Sunset;
[Test]
public void OptimiseReportsValuesAsTheControlsShowThem()
{
Assert.Equal("Frame 0413", EditorText.Value(AdvisorParameters.Hero, 412), "1-based, four digits, like the Frames tab");
Assert.Equal("Source", EditorText.Value(AdvisorParameters.Aspect, "source"));
Assert.Equal("16:9", EditorText.Value(AdvisorParameters.Aspect, "16:9"));
Assert.Equal("24 fps", EditorText.Value(AdvisorParameters.FrameRate, "24"));
Assert.Equal("41 frames", EditorText.Value(AdvisorParameters.DeflickerWindow, 41));
Assert.Equal("0.80", EditorText.Value(AdvisorParameters.DeflickerStrength, 0.8));
Assert.Equal("Centred", EditorText.Value(AdvisorParameters.OffsetY, 0.0));
Assert.Equal("On", EditorText.Value(AdvisorParameters.Deflicker, true));
Assert.Equal("Horizon", EditorText.Value(AdvisorParameters.Regions, RegionMode.Horizon));
Assert.Equal("None", EditorText.Value(AdvisorParameters.Hero, null));
Assert.Equal("3 frames", EditorText.Value(AdvisorParameters.Excluded, new[] { 1, 2, 3 }));
}
[Test]
public void CropMarginsKeepAtLeastATenthOfTheFrame()
{
Assert.SequenceEqual([0.0, 0, 0, 0], CropMargins.Of(null));
var crop = CropMargins.With(null, CropSide.Left, 0.2);
Assert.SequenceEqual([0.2, 0, 0.8, 1], crop!);
crop = CropMargins.With(crop, CropSide.Top, 0.6);
Assert.Approximately(CropMargins.MaxMargin, crop![1], 1e-12, "no margin beyond the maximum");
crop = CropMargins.With(crop, CropSide.Left, 0.45);
crop = CropMargins.With(crop, CropSide.Right, 0.45);
Assert.Approximately(CropMargins.MinSize, crop![2], 1e-12, "opposite margins leave a tenth of the width");
var margins = CropMargins.Of(crop);
Assert.Approximately(0.45, margins[0], 1e-12);
Assert.Approximately(0.45, margins[1], 1e-12);
Assert.Null(CropMargins.With(CropMargins.With(CropMargins.With(crop, CropSide.Left, 0), CropSide.Right, 0), CropSide.Top, 0),
"no margin left is the whole frame");
Assert.SequenceEqual([0.0, 0, 0, 0], CropMargins.Of([double.NaN, 0, 1, 1]), "an invalid crop is ignored, as the render does");
}
[Test]
public void AFlatGreyPictureIsOneLineOfTheWaveform()
{
using var grey = new ImageBuffer(40, 10);
grey.Data.Fill((float)ColorSpace.SrgbToLinear(0.5));
var waveform = LumaWaveform.Measure(grey);
Assert.Equal(40, waveform.Columns);
Assert.Equal(LumaWaveform.Levels, waveform.Rows);
var lit = Enumerable.Range(0, waveform.Rows).Where(r => waveform.Density[r * waveform.Columns] > 0).ToList();
Assert.Equal(1, lit.Count, "one level");
Assert.LessOrEqual(Math.Abs(lit[0] - (LumaWaveform.Levels - 1) / 2.0), 1.0, "half grey sits halfway up");
Assert.Equal(255, waveform.Density[lit[0] * waveform.Columns], "every pixel of the column there");
}
}
@@ -103,6 +103,84 @@ public sealed class PreviewRendererTests
Assert.Equal(decodes, source.Decodes);
}
[Test]
public async Task SolveSettingsReuseTheMeasurementsWithoutDecoding()
{
var (renderer, source) = Create();
var project = Sunset();
await renderer.PrepareAsync(project, CancellationToken.None);
var decodes = source.Decodes;
Assert.Greater(decodes, 0, "stabilisation and colour are measured once");
foreach (var strength in new[] { 0.3, 0.6, 0.9 })
{
var changed = project with { Exposure = project.Exposure with { DeflickerStrength = project.Exposure.DeflickerStrength.WithManual(strength), TransitionLength = project.Exposure.TransitionLength.WithManual(6) } };
await renderer.PrepareAsync(changed, CancellationToken.None);
}
Assert.Equal(decodes, source.Decodes, "a strength or transition change re-solves from the measured series");
}
[Test]
public async Task AReSolveMatchesAFreshPreparation()
{
var (warm, _) = Create();
var project = Sunset();
await warm.PrepareAsync(project, CancellationToken.None);
var changed = project with { Exposure = project.Exposure with { DeflickerStrength = project.Exposure.DeflickerStrength.WithManual(0.5), ExposureOffsetEv = 0.3 } };
var resolved = await warm.PrepareAsync(changed, CancellationToken.None);
var (cold, _) = Create();
var fresh = await cold.PrepareAsync(changed, CancellationToken.None);
Assert.Equal(fresh.ExposureEv.Length, resolved.ExposureEv.Length);
for (var i = 0; i < fresh.ExposureEv.Length; i++) Assert.Approximately(fresh.ExposureEv[i], resolved.ExposureEv[i], 1e-9, $"frame {i}");
Assert.NotNull(resolved.WhiteBalance);
for (var i = 0; i < fresh.WhiteBalance!.Length; i++) Assert.Equal(fresh.WhiteBalance[i], resolved.WhiteBalance![i]);
Assert.Equal(fresh.StabilizationZoom, resolved.StabilizationZoom);
Assert.NotNull(resolved.Stabilization);
Assert.SequenceEqual(fresh.Stabilization!, resolved.Stabilization!);
}
[Test]
public async Task ActualSizeRendersTheSourcePixels()
{
var (renderer, _) = Create();
var edge = int.Max(EditorFixture.Sunset.Options.Width, EditorFixture.Sunset.Options.Height);
using var frame = await renderer.RenderAsync(new PreviewRequest(3, new ProjectSettings(), edge, PreviewFraming.Source, Vectors: true), null,
CancellationToken.None);
Assert.Equal(EditorFixture.Sunset.Options.Width, frame!.Corrected.Width, "one picture pixel per source pixel");
Assert.Equal(EditorFixture.Sunset.Options.Height, frame.Corrected.Height);
Assert.NotEmpty(frame.Vectors);
Assert.True(frame.Vectors.All(v => v.X < frame.Corrected.Width && v.Y < frame.Corrected.Height), "vectors in picture pixels");
}
[Test]
public async Task TheWaveformIsMeasuredOnRequest()
{
var (renderer, _) = Create();
using var plain = await renderer.RenderAsync(new PreviewRequest(3, new ProjectSettings(), 64, PreviewFraming.Output), null, CancellationToken.None);
Assert.Null(plain!.Waveform);
using var frame = await renderer.RenderAsync(new PreviewRequest(3, new ProjectSettings(), 64, PreviewFraming.Output, Waveform: true), null,
CancellationToken.None);
var waveform = Assert.NotNull(frame!.Waveform);
Assert.Equal(frame.Corrected.Width, waveform.Columns);
Assert.True(waveform.Density.Any(d => d > 0));
}
/// <summary>A sunset project as the advisor leaves it: deflicker, holy grail, white balance and stabilisation on.</summary>
private static ProjectSettings Sunset()
{
var p = new ProjectSettings();
return p with
{
Exposure = p.Exposure with
{
Deflicker = p.Exposure.Deflicker.WithManual(true),
HolyGrail = p.Exposure.HolyGrail.WithManual(true),
WhiteBalanceSmoothing = p.Exposure.WhiteBalanceSmoothing.WithManual(true),
},
Motion = p.Motion with { Stabilize = p.Motion.Stabilize.WithManual(true) },
};
}
private static double LogMean(ImageBuffer image)
{
double sum = 0;
@@ -74,7 +74,58 @@ public sealed class ProjectHistoryTests
Assert.Equal(7, history.Current.HeroFrame);
Assert.True(history.Undo());
Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv);
Assert.Equal(7, history.Current.HeroFrame, "undo reverts the user's step, not the adopted change");
Assert.False(history.CanUndo);
Assert.True(history.Redo());
Assert.Equal(0.5, history.Current.Exposure.ExposureOffsetEv);
Assert.Equal(7, history.Current.HeroFrame);
}
[Test]
public void AdviceAdoptedLaterSurvivesUndoAndRedo()
{
var start = new ProjectSettings();
var history = new ProjectHistory(start);
history.Apply(start with { Camera = start.Camera with { OffsetY = 0.1 } });
history.Apply(history.Current with { HeroFrame = 4 });
history.Undo();
// An analysis fills the advice of a setting the user never touched; the redo step and the undo step both take it.
var advised = history.Current with { Exposure = history.Current.Exposure with { Deflicker = history.Current.Exposure.Deflicker.WithAdvice(true, "Advisor.Reason.Deflicker.On") } };
history.Replace(advised);
Assert.True(history.Undo());
Assert.Equal(0.0, history.Current.Camera.OffsetY);
Assert.True(history.Current.Exposure.Deflicker.HasAdvice, "the advice is not undone");
Assert.True(history.Redo());
Assert.True(history.Redo());
Assert.Equal(4, history.Current.HeroFrame);
Assert.True(history.Current.Exposure.Deflicker is { HasAdvice: true, IsAuto: true });
}
[Test]
public void AValueBothChangedUndoesToTheUsersOwnStep()
{
var start = new ProjectSettings();
var history = new ProjectHistory(start);
history.Apply(start with { HeroFrame = 3 });
history.Replace(history.Current with { HeroFrame = 9 });
Assert.True(history.Undo());
Assert.Null(history.Current.HeroFrame, "the user's step reverts the value it set");
}
[Test]
public void EndingARunMakesTheNextEditANewStep()
{
var history = new ProjectHistory(new ProjectSettings());
history.Apply(WithOffset(history.Current, 0.2), "Exposure.Offset");
history.Apply(WithOffset(history.Current, 0.4), "Exposure.Offset");
history.EndRun();
history.Apply(WithOffset(history.Current, 0.6), "Exposure.Offset");
Assert.True(history.Undo());
Assert.Equal(0.4, history.Current.Exposure.ExposureOffsetEv, "the second drag is its own step");
Assert.True(history.Undo());
Assert.Equal(0.0, history.Current.Exposure.ExposureOffsetEv);
}
[Test]
@@ -101,6 +101,20 @@ public sealed class ProjectStoreTests(TestContext context)
}
}
[Test]
public async Task ASaveThatDoesNotReachTheIndexThrows()
{
var (db, sequenceId, _) = await ArchiveAsync(4);
await using (db)
{
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null,
new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
var content = await source.LoadAsync(context.Cancellation);
Assert.True(await db.Sequences.DeleteAsync(sequenceId));
await Assert.ThrowsAsync<InvalidOperationException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
}
}
[Test]
public async Task JobsGoToTheEngine()
{
@@ -112,6 +112,76 @@ public sealed class SchedulingTests
Assert.Equal(1, saved);
}
[Test]
public async Task AFailedWriteIsRetriedUntilStored()
{
var attempts = 0;
var stored = new List<int?>();
var failures = new List<int>();
var saver = new ProjectSaver(p =>
{
if (++attempts <= 2) throw new System.IO.IOException("offline");
stored.Add(p.HeroFrame);
return Task.CompletedTask;
}, TimeSpan.Zero);
saver.Failed += (_, count) => failures.Add(count);
// Without a delay the first write happens at once and fails; the flush retries at once and fails again.
saver.Schedule(new ProjectSettings { HeroFrame = 7 });
Assert.False(await saver.FlushAsync());
Assert.True(saver.HasPendingChanges, "kept pending after a failure");
Assert.NotNull(saver.LastError);
Assert.True(await saver.FlushAsync().WaitAsync(TimeSpan.FromSeconds(10)), "a flush skips the retry delay");
Assert.SequenceEqual([(int?)7], stored);
Assert.SequenceEqual([1, 2], failures, "failures in a row are counted");
Assert.False(saver.HasPendingChanges);
Assert.Null(saver.LastError);
}
[Test]
public async Task ARetryWritesTheNewestChange()
{
var fail = true;
var stored = new List<int?>();
var saver = new ProjectSaver(p =>
{
if (fail) throw new System.IO.IOException("offline");
stored.Add(p.HeroFrame);
return Task.CompletedTask;
}, TimeSpan.Zero);
saver.Schedule(new ProjectSettings { HeroFrame = 1 });
Assert.False(await saver.FlushAsync());
saver.Schedule(new ProjectSettings { HeroFrame = 2 });
fail = false;
Assert.True(await saver.FlushAsync());
Assert.SequenceEqual([(int?)2], stored, "the newer project contains the failed one");
}
[Test]
public async Task StopDropsThePendingChange()
{
var saved = 0;
var saver = new ProjectSaver(_ =>
{
saved++;
throw new System.IO.IOException("offline");
}, TimeSpan.Zero);
saver.Schedule(new ProjectSettings { HeroFrame = 1 });
Assert.False(await saver.FlushAsync());
var attempts = saved;
saver.Stop();
Assert.True(await saver.FlushAsync().WaitAsync(TimeSpan.FromSeconds(10)), "nothing pending after a stop");
saver.Schedule(new ProjectSettings { HeroFrame = 2 });
Assert.False(saver.HasPendingChanges, "a stopped saver takes no new change");
Assert.Equal(attempts, saved);
}
[Test]
public async Task FlushWithNothingPendingIsStored()
{
var saver = new ProjectSaver(_ => Task.CompletedTask, TimeSpan.FromMinutes(5));
Assert.True(await saver.FlushAsync().WaitAsync(TimeSpan.FromSeconds(10)));
}
[Test]
public async Task AChangeDuringAWriteIsWrittenAfterIt()
{