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

+11 -2
View File
@@ -15,6 +15,7 @@ using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Video;
using Titano.Data;
using Titano.Data.Archiving;
@@ -91,7 +92,8 @@ public sealed class SampleData
/// <summary>
/// The sequence editor's sample: a second archive holding a synthetic harbour sunset of real JPEG frames with Exif
/// (flicker, two received exposure steps, white-balance drift, a horizon), indexed by a scan, analysed (light and
/// deep, saved as <c>analysis.json</c>), advised into <c>project.json</c> and given two past renders.
/// deep, saved as <c>analysis.json</c>), advised into <c>project.json</c> with one manual value and three camera
/// keyframes, and given two past renders.
/// </summary>
/// <returns>The sequence id to open in the editor.</returns>
public async Task<Guid> FillEditorAsync()
@@ -119,7 +121,14 @@ public sealed class SampleData
var sequence = content.Sequence;
deep.Save(new ArchivePaths(root).Sequence(sequence.Folder).AnalysisPath);
var advice = Advisor.Recommend(content.Light, deep, SequenceContext.FromFrames(content.Frames));
await source.SaveProjectAsync(Advisor.Apply(content.Project, advice), content.Project, CancellationToken.None);
// As a user leaves it: the advice applied, one value taken over by hand (Sun track) and a slow push-in.
var advised = Advisor.Apply(content.Project, advice);
var project = advised with
{
Exposure = advised.Exposure with { DeflickerStrength = advised.Exposure.DeflickerStrength.WithManual(0.8) },
Camera = advised.Camera with { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(48, 0.6, 0.46, 1.4, 0), new CameraKey(95, 0.64, 0.4, 1.9, 0)] },
};
await source.SaveProjectAsync(project, content.Project, CancellationToken.None);
await db.Sequences.RecordAnalysisAsync(id, SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.HasWarnings, SequenceStatus.None,
advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning), AnalysisSummary.From(deep).ToJson());
foreach (var (preset, codec, width, height, daysAgo, bytes) in new[] { ("4K archive", "hevc", 3840, 2160, 7, 2_210_000_000L), ("1080p share", "h264", 1920, 1080, 3, 412_000_000L) })
+3 -32
View File
@@ -12,15 +12,6 @@ using Titano.Ui.Visuals;
namespace Titano.App.Editor;
/// <summary>Margins of the free crop, in the order of <c>CameraTab.Margins</c> (opposites differ in the lowest bit).</summary>
public enum CropSide
{
Left,
Right,
Top,
Bottom,
}
/// <summary>
/// Camera (BRIEF §12.3): the free crop of the frame (margins), the output aspect and its placement inside the crop, and
/// virtual-camera keyframes edited as a zoom curve over the sequence (X = frame, Y = zoom) with the selected keyframe's
@@ -31,11 +22,6 @@ public sealed class CameraTab : EditorTab
/// <summary>Zoom at the top of the curve editor.</summary>
public const double MaxZoom = 4;
/// <summary>Largest crop margin; opposite margins together leave at least <see cref="MinCropSize"/> of the frame.</summary>
public const double MaxCropMargin = 0.45;
public const double MinCropSize = 0.1;
private int _selectedKey = -1;
public CameraTab(EditorViewModel editor)
@@ -169,25 +155,10 @@ public sealed class CameraTab : EditorTab
OnPropertyChanged(nameof(RemoveKeyToolTip));
}
/// <summary>A margin of the free crop (<see cref="CameraSettings.Crop"/>, normalised x, y, width, height); all zero = the whole frame.</summary>
/// <summary>A margin of the free crop (<see cref="CropMargins"/>); all zero = the whole frame.</summary>
private static NumberRow CropRow(EditorSession session, CropSide side, string headerKey) => new(session, headerKey, "Tooltips.Editor.Camera.Crop", 0,
MaxCropMargin, 0.01, p => Margins(p.Camera.Crop)[(int)side], (p, v) => p with { Camera = p.Camera with { Crop = WithMargin(p.Camera.Crop, side, v) } },
v => Formatting.Percent(v));
/// <summary>Left, right, top and bottom margins of a crop rectangle.</summary>
private static double[] Margins(double[]? crop) => crop is [var x, var y, var w, var h] && new[] { x, y, w, h }.All(double.IsFinite)
? [double.Clamp(x, 0, 1), double.Clamp(1 - x - w, 0, 1), double.Clamp(y, 0, 1), double.Clamp(1 - y - h, 0, 1)]
: [0, 0, 0, 0];
private static double[]? WithMargin(double[]? crop, CropSide side, double value)
{
var margins = Margins(crop);
var opposite = (int)side ^ 1;
margins[(int)side] = double.Clamp(value, 0, double.Min(MaxCropMargin, 1 - MinCropSize - margins[opposite]));
if (margins.All(m => m == 0)) return null;
var (left, right, top, bottom) = (margins[0], margins[1], margins[2], margins[3]);
return [left, top, 1 - left - right, 1 - top - bottom];
}
CropMargins.MaxMargin, 0.01, p => CropMargins.Of(p.Camera.Crop)[(int)side],
(p, v) => p with { Camera = p.Camera with { Crop = CropMargins.With(p.Camera.Crop, side, v) } }, v => Formatting.Percent(v));
private Point ToPoint(CameraKey key) => new(Editor.FrameCount > 1 ? (double)key.Frame / (Editor.FrameCount - 1) : 0, (key.Zoom - 1) / (MaxZoom - 1));
+37
View File
@@ -0,0 +1,37 @@
namespace Titano.App.Editor;
/// <summary>Margins of the free crop, in the order of <see cref="CropMargins.Of"/> (opposites differ in the lowest bit).</summary>
public enum CropSide
{
Left,
Right,
Top,
Bottom,
}
/// <summary>
/// The Camera tab's crop margins over <c>CameraSettings.Crop</c> (a normalised x, y, width, height rectangle, null for the
/// whole frame): each margin at most <see cref="MaxMargin"/>, opposite margins leaving at least <see cref="MinSize"/>.
/// </summary>
public static class CropMargins
{
public const double MaxMargin = 0.45;
public const double MinSize = 0.1;
/// <summary>Left, right, top and bottom margins of <paramref name="crop"/> (zeros for none or an invalid one, which the render ignores too).</summary>
public static double[] Of(double[]? crop) => crop is [var x, var y, var w, var h] && double.IsFinite(x + y + w + h)
? [double.Clamp(x, 0, 1), double.Clamp(1 - x - w, 0, 1), double.Clamp(y, 0, 1), double.Clamp(1 - y - h, 0, 1)]
: [0, 0, 0, 0];
/// <summary><paramref name="crop"/> with one margin changed; null when no margin is left (the whole frame).</summary>
public static double[]? With(double[]? crop, CropSide side, double value)
{
var margins = Of(crop);
var opposite = (int)side ^ 1;
margins[(int)side] = double.Clamp(value, 0, double.Min(MaxMargin, 1 - MinSize - margins[opposite]));
if (margins.All(m => m == 0)) return null;
var (left, right, top, bottom) = (margins[0], margins[1], margins[2], margins[3]);
return [left, top, 1 - left - right, 1 - top - bottom];
}
}
+5 -1
View File
@@ -156,11 +156,15 @@ public sealed class EditorSession : IAsyncDisposable
/// <summary>Stores pending changes now; false when the save failed (the change stays pending and is retried).</summary>
public Task<bool> FlushAsync() => _saver.FlushAsync();
/// <summary>Stores what is pending one last time and releases the source; callers that must not lose an edit flush and ask first.</summary>
/// <summary>
/// Stores what is pending one last time, stops retrying and releases the source; callers that must not lose an edit
/// flush and ask first (<c>SequenceViewModel.ConfirmCloseAsync</c>).
/// </summary>
public async ValueTask DisposeAsync()
{
History.Changed -= OnProjectChanged;
if (!await _saver.FlushAsync()) Log.Warning("editor", $"The last change of {Content.Sequence.DisplayTitle} was not saved", _saver.LastError);
_saver.Stop();
await Source.DisposeAsync();
}
+1 -1
View File
@@ -152,7 +152,7 @@ public sealed class ExposureTab : EditorTab
if (content.Deep is { Regions: not null } withSky && withSky.Frames.SkyLogLuminance.Any(v => v is not null))
{
series.Add(new ChartSeries(Loc.L("Editor.Chart.Sky"), withSky.Frames.SkyLogLuminance.Select(v => v ?? double.NaN).ToArray(), "Brush.Region")
{ Dash = LineDash.Dashed });
{ Dash = LineDash.Dashed });
legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Sky"), "Brush.Region", LegendSwatch.DashedLine));
}
}
+3
View File
@@ -113,9 +113,12 @@ public sealed class PreviewRenderer(SequenceContent content, ISequenceSource sou
if (Cached(project) is { } cached) return cached;
var key = Key(project);
var measured = await MeasureAsync(project, cancellationToken).ConfigureAwait(false);
// Nothing is measured again: white balance comes from the measuring preparation, and a stabilisation it could
// not solve (its warning is kept) is not tried again.
var solveProject = project with
{
Exposure = project.Exposure with { WhiteBalanceSmoothing = project.Exposure.WhiteBalanceSmoothing.WithManual(false) },
Motion = measured.Stabilization is null ? project.Motion with { Stabilize = project.Motion.Stabilize.WithManual(false) } : project.Motion,
};
var solved = await RenderPreparation.PrepareAsync(Input(solveProject, Reuse(measured, project)), Options, null, cancellationToken).ConfigureAwait(false);
var corrections = solved with
+16 -2
View File
@@ -18,6 +18,7 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
private ProjectSettings? _pending;
private bool _running;
private bool _flushRequested;
private bool _stopped;
private int _failures;
private CancellationTokenSource? _wait;
@@ -42,6 +43,7 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
TaskCompletionSource start;
lock (_gate)
{
if (_stopped) return;
_pending = project;
if (_running) return;
_running = true;
@@ -67,6 +69,17 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
}
}
/// <summary>Drops what is pending and stops retrying (the editor closed and the user chose to discard the change).</summary>
public void Stop()
{
lock (_gate)
{
_stopped = true;
_pending = null;
_wait?.Cancel();
}
}
private async Task LoopAsync(Task started)
{
await started;
@@ -118,13 +131,14 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
lock (_gate)
{
// A newer change contains this one (projects are whole snapshots); otherwise this one waits for the retry.
_pending ??= next;
if (!_stopped) _pending ??= next;
failures = ++_failures;
Complete(false);
}
LastError = ex;
wait = TimeSpan.FromSeconds(double.Min(MaxRetryDelay.TotalSeconds, double.Pow(2, failures)));
Failed?.Invoke(ex, failures);
// Flushes learn the outcome after the failure was reported.
lock (_gate) Complete(false);
}
}
}
+30 -6
View File
@@ -114,8 +114,12 @@ public static class ScreenCapture
}
}
/// <summary>The sequence editor on the synthetic sunset: every section in both themes (<c>sequence-&lt;tab&gt;-&lt;theme&gt;.png</c>).</summary>
private static async Task<int> CaptureEditorAsync(Window window, ShellViewModel shell, SampleData sample, string directory)
/// <summary>
/// The sequence editor on the synthetic sunset: every section in both themes (<c>sequence-&lt;tab&gt;-&lt;theme&gt;.png</c>,
/// the Camera tab with a keyframe selected, the Export tab as Export.html with the crop mask and no compare), then
/// the preview overlays, the waveform and the "what changed" toast of Optimise all.
/// </summary>
private static async Task<int> CaptureEditorAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
{
var written = 0;
var id = await sample.FillEditorAsync();
@@ -126,22 +130,42 @@ public static class ScreenCapture
Log.Warning("capture", "The editor sample did not open");
return 0;
}
foreach (var camera in editor.Tabs.OfType<CameraTab>()) camera.SelectedKey = 1;
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
foreach (var tab in editor.Tabs)
{
editor.SelectedTab = tab;
editor.IsCompare = tab is not ExportTab;
editor.CurrentIndex = tab is ExportTab ? 40 : 45;
await Settle(window);
if (!await editor.WhenIdleAsync(TimeSpan.FromSeconds(30))) Log.Warning("capture", $"The {tab.Key} section was still busy");
written += await SaveAsync(window, directory, "sequence-" + tab.Key.ToLowerInvariant(), theme);
written += await SaveEditorAsync(window, editor, directory, "sequence-" + tab.Key.ToLowerInvariant(), theme);
}
editor.SelectedTab = editor.Exposure;
editor.IsCompare = true;
editor.ShowVectors = editor.ShowRegions = true;
written += await SaveEditorAsync(window, editor, directory, "sequence-exposure-overlays", theme);
editor.ShowVectors = editor.ShowRegions = false;
editor.Exposure.ChartMode = ExposureChart.Waveform;
written += await SaveEditorAsync(window, editor, directory, "sequence-exposure-waveform", theme);
editor.Exposure.ChartMode = ExposureChart.Luminance;
editor.OptimiseAllCommand.Execute(null);
written += await SaveEditorAsync(window, editor, directory, "sequence-optimise", theme);
editor.Session.Undo();
foreach (var toast in window.Toasts.Toasts.ToList()) window.Toasts.Dismiss(toast);
}
editor.SelectedTab = editor.Exposure;
return written;
}
private static async Task<int> SaveEditorAsync(Window window, EditorViewModel editor, string directory, string screen, AppTheme theme)
{
await Settle(window);
if (!await editor.WhenIdleAsync(TimeSpan.FromSeconds(30))) Log.Warning("capture", $"{screen} was still busy");
return await SaveAsync(window, directory, screen, theme);
}
private static async Task<int> SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
{
await Settle(window);
@@ -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()
{