merge: sequence editor with Export tab (preview through the render pipeline, section tabs, autosave with undo/redo)

Keeps the sync captures and sample server next to the editor's sample sunset;
the editor's capture runs last since it leaves an analysis running.

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:58:34 +00:00
commit 8feea5da10
53 files changed
+8622 -18

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,265 @@
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;
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)
{
Assert.False(session.HasPendingSave);
for (var i = 1; i <= 20; i++) session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = i / 20.0 } }, "offset");
Assert.True(session.HasPendingSave, "closing the window waits for this save");
await session.FlushAsync();
Assert.False(session.HasPendingSave);
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 });
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 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)
{
var reported = 0;
session.SaveFailed += _ => reported++;
source.FailNextSave = new IOException("share offline");
session.Edit(p => p with { HeroFrame = 1 });
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);
}
}
[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 ASequencePresetKeepsTheUsersFramesAndNaming()
{
var (session, _) = Open();
await using (session)
{
session.SetExcluded([1, 2], excluded: true);
session.SetHero(9);
session.Edit(p => p with { Export = p.Export with { NameTemplate = "{title}", Overrides = new ExportOverrides { Width = 640 } } });
var preset = session.Presets.First(p => p.Id == "social-vertical");
Assert.True(session.ApplyPreset(preset));
Assert.Equal("9:16", session.Project.Camera.Aspect.Manual);
Assert.Equal("vertical-1080x1920", session.Project.Export.Preset.Manual);
Assert.Null(session.Project.Export.Overrides.Width, "the preset's own values");
Assert.SequenceEqual([1, 2], session.Project.ExcludedFrames);
Assert.Equal(9, session.Project.HeroFrame);
Assert.Equal("{title}", session.Project.Export.NameTemplate);
Assert.True(session.Undo());
Assert.Equal(640, session.Project.Export.Overrides.Width);
}
}
[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,215 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Project;
using Titano.Testing;
using Titano.Ui.Theming;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Editor;
/// <summary>
/// The sequence editor in the real main window, off screen at the minimum capture size, on the synthetic sunset of
/// <c>--capture</c> (real JPEG frames, deep analysis, advised project): every section shows its measuring tool, its
/// settings and preview pixels in both themes, and an edit goes through undo and redo.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class EditorSmokeTests
{
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
[Test]
public Task EverySectionOfTheEditorRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
var environment = AppEnvironment.ForCapture();
UiLanguage.Apply("en");
ThemeManager.Apply(AppTheme.Dark);
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
var sample = SampleData.Configure(services);
var shell = new ShellViewModel(services);
var window = new MainWindow(shell)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 1200,
Height = 788,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
await sample.OpenEmptyAsync();
await shell.StartAsync();
var id = await sample.FillEditorAsync();
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(shell.Sequence.Editor);
Assert.Equal(96, editor.FrameCount);
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)
{
ThemeManager.Apply(theme);
foreach (var tab in editor.Tabs)
{
editor.SelectedTab = tab;
await SettleAsync(window);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), $"{tab.Key}: still busy");
await SettleAsync(window);
var view = Find<SequenceView>(window).Single(v => v.IsVisible);
Assert.NotNull(editor.PreviewImage, $"{tab.Key}: the preview shows pixels");
ExpectMeasure(view, tab);
Assert.True(Find<ContentPresenter>(view).Any(p => ReferenceEquals(p.Content, tab) && p.ActualHeight > 100), $"{tab.Key}: settings column");
Assert.Greater(Distinct(Render(window)), 40, $"{tab.Key} drew almost nothing in {theme}");
}
}
// 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;
editor.Session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } });
editor.UndoCommand.Execute(null);
Assert.Equal(before, editor.Session.Project.Exposure.ExposureOffsetEv);
editor.RedoCommand.Execute(null);
Assert.Equal(0.5, editor.Session.Project.Exposure.ExposureOffsetEv);
await editor.Session.FlushAsync();
Assert.NotNull(editor.Plan, "the export is planned");
}
finally
{
ThemeManager.Apply(AppTheme.Dark);
window.Close();
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
environment.DeleteCaptureData();
}
});
/// <summary>The measuring tool of each section has content.</summary>
private static void ExpectMeasure(SequenceView view, EditorTab tab)
{
switch (tab)
{
case FramesTab frames:
Assert.Equal(96, frames.Frames.Count);
Assert.NotEmpty(Find<ListBoxItem>(view).Where(i => i.DataContext is FrameRow && i.IsVisible));
break;
case CameraTab or TimeTab:
Assert.NotEmpty(Find<CurveEditor>(view).Where(c => c.IsVisible && c.ActualHeight > 50));
break;
case ExportTab export:
Assert.NotEmpty(export.Cards);
Assert.NotEmpty(Find<Button>(view).Where(b => b.DataContext is PresetCard && b.IsVisible));
Assert.True(export.Cards.Any(c => c.Estimate is not null), "estimates on the cards");
break;
default:
var chart = Find<SeriesChart>(view).Single(c => c.IsVisible);
Assert.True(chart.ActualHeight > 50, $"{tab.Key}: chart height");
Assert.NotEmpty(chart.Series!);
break;
}
}
private static async Task SettleAsync(Window window)
{
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
private static RenderTargetBitmap Render(Window window)
{
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
var dpi = VisualTreeHelper.GetDpi(window);
var bitmap = new RenderTargetBitmap((int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX), (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY),
dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
bitmap.Render(root);
return bitmap;
}
private static int Distinct(BitmapSource bitmap)
{
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
var colours = new HashSet<int>();
for (var i = 0; i < pixels.Length && colours.Count < 2000; i += 4 * 5) colours.Add(BitConverter.ToInt32(pixels, i));
return colours.Count;
}
private static List<T> Find<T>(DependencyObject root)
where T : DependencyObject
{
var found = new List<T>();
var stack = new Stack<DependencyObject>([root]);
while (stack.TryPop(out var node))
{
if (node is T match) found.Add(match);
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) stack.Push(VisualTreeHelper.GetChild(node, i));
}
return found;
}
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}
@@ -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");
}
}
@@ -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,217 @@
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);
}
[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 WithoutAnalysisNothingIsMeasuredUntilAModuleNeedsIt()
{
var content = EditorFixture.Content(EditorFixture.Sunset, deep: false);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
var renderer = new PreviewRenderer(content, source);
await renderer.PrepareAsync(new ProjectSettings(), CancellationToken.None);
Assert.Equal(0, source.Decodes, "no module on, nothing to measure");
var project = Deflickered();
await renderer.PrepareAsync(project, CancellationToken.None);
var decodes = source.Decodes;
Assert.GreaterOrEqual(decodes, EditorFixture.Sunset.Count, "deflicker measures the luminance once");
await renderer.PrepareAsync(project with { Exposure = project.Exposure with { DeflickerStrength = project.Exposure.DeflickerStrength.WithManual(0.4) } },
CancellationToken.None);
Assert.Equal(decodes, source.Decodes);
}
[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;
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,141 @@
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.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]
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,171 @@
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 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()
{
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,203 @@
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 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()
{
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);
}
}