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 AnEditMadeBeforeInsertedFramesWereReadIsSavedOnTheFramesItNamed() { var (session, source) = OpenShort(); await using (session) { Assert.True(session.SetExcluded([3], true)); Assert.True(await session.FlushAsync()); // Two earlier photos are inserted (a download, an import, a scan): the stored exclusion moved with its frame. var frames = session.Content.Frames; InsertEarlier(source, 2); source.Stored = source.Stored with { ExcludedFrames = [5] }; source.FailNextSave = new FramesChangedException("frames changed"); // The editor still shows the frames it read when the user excludes another one. Assert.True(session.SetExcluded([6], true)); Assert.True(await session.FlushAsync()); Assert.Equal(frames.Count + 2, session.Content.Count, "the frames were read again"); Assert.SequenceEqual([5, 8], source.Stored.ExcludedFrames); Assert.SequenceEqual([frames[3].Id, frames[6].Id], session.Project.ExcludedFrames.Select(i => session.Content.Frames[i].Id)); Assert.True(session.Undo()); Assert.SequenceEqual([5], session.Project.ExcludedFrames, "undo steps name the same frames"); Assert.True(session.Undo()); Assert.Empty(session.Project.ExcludedFrames); } } [Test] public async Task AReadAfterFramesWereInsertedMovesTheOpenProjectWithThem() { var (session, source) = OpenShort(); await using (session) { Assert.True(session.SetExcluded([3], true)); Assert.True(session.SetHero(4)); Assert.True(await session.FlushAsync()); InsertEarlier(source, 2); source.Stored = source.Stored with { ExcludedFrames = [5], HeroFrame = 6 }; await session.ReloadAsync(); Assert.SequenceEqual([5], session.Project.ExcludedFrames); Assert.Equal(6, session.Project.HeroFrame); Assert.True(session.Undo()); Assert.Null(session.Project.HeroFrame); Assert.SequenceEqual([5], session.Project.ExcludedFrames, "the step before Set hero names the same frame"); Assert.True(await session.FlushAsync()); Assert.SequenceEqual([5], source.Stored.ExcludedFrames); Assert.Null(source.Stored.HeroFrame); } } [Test] public async Task ARenderAfterFramesWereInsertedEmbedsThePositionsOfTheFramesTheUserChose() { var (session, source) = OpenShort(); await using (session) { Assert.True(session.SetExcluded([3], true)); Assert.True(session.SetHero(4)); Assert.True(await session.FlushAsync()); var frames = session.Content.Frames; // Two earlier photos are inserted and the index moves the stored positions; the user renders without an edit. InsertEarlier(source, 2); source.Stored = source.Stored with { ExcludedFrames = [5], HeroFrame = 6 }; await session.EnsureFramesAsync(); var requests = session.RenderRequests(session.Project.Export); Assert.Equal(frames.Count + 2, session.Content.Count, "the frames were read again"); var parameters = JsonSerializer.Deserialize(requests[0].ParametersJson!, ProtocolJson.Default.RenderJobParameters)!; var embedded = ProjectSettings.FromJson(parameters.SettingsJson!); Assert.SequenceEqual([5], embedded.ExcludedFrames); Assert.Equal(6, embedded.HeroFrame); Assert.Equal(frames[3].Id, session.Content.Frames[embedded.ExcludedFrames[0]].Id); Assert.Equal(frames[4].Id, session.Content.Frames[embedded.HeroFrame!.Value].Id); Assert.True(session.Undo()); Assert.Null(session.Project.HeroFrame); Assert.SequenceEqual([5], session.Project.ExcludedFrames, "undo steps name the same frames"); // Frames that did not change are not read again. var loads = source.Loads; await session.EnsureFramesAsync(); Assert.Equal(loads, source.Loads); } } [Test] public async Task AServerSequenceWhoseFramesChangedIsOutdatedBeforeItsRender() { var sequence = EditorFixture.Sequence(12); var content = EditorFixture.Content(sequence, deep: false); var source = new FakeSequenceSource(sequence, content) { IsRemote = true }; var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)); await using (session) { InsertEarlier(source, 1); await session.EnsureFramesAsync(); Assert.True(source.IsOutdated); Assert.True(session.IsReadOnly); Assert.Equal(0, source.Loads, "its proxies are not the server's frames: nothing is read"); Assert.Equal(12, session.Content.Count); } } [Test] public async Task ReadsThatOverlapFollowTheFramesInTheOrderTheyWereRead() { var (session, source) = OpenShort(); await using (session) { Assert.True(session.SetExcluded([3], true)); Assert.True(await session.FlushAsync()); var frames = session.Content.Frames; // A job ends after an earlier photo was inserted, and its read of the sequence is slow to complete. InsertEarlier(source, 1); source.Stored = source.Stored with { ExcludedFrames = [4] }; var slow = new TaskCompletionSource(); source.NextLoadGate = slow.Task; var first = session.ReloadAsync(); // Another job ends after two more were inserted: its read waits for the first one and follows its frames. InsertEarlier(source, 2); source.Stored = source.Stored with { ExcludedFrames = [6] }; var second = session.ReloadAsync(); slow.SetResult(); await Task.WhenAll(first, second); Assert.Equal(frames.Count + 3, session.Content.Count); Assert.SequenceEqual([6], session.Project.ExcludedFrames); Assert.Equal(frames[3].Id, session.Content.Frames[6].Id); } } /// A short sequence without its analysis, whose frame ids are all different (the synthetic ids repeat every 64 frames). private static (EditorSession Session, FakeSequenceSource Source) OpenShort() { var sequence = EditorFixture.Sequence(12); var content = EditorFixture.Content(sequence, deep: false); var source = new FakeSequenceSource(sequence, content); return (new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)), source); } /// Photos captured before the first frame join the source's sequence, as an insertion renumbers it. private static void InsertEarlier(FakeSequenceSource source, int count) { var first = source.Content.Frames[0]; var early = Enumerable.Range(0, count).Select(i => first with { Id = Guid.CreateVersion7(), CapturedAt = first.CapturedAt!.Value.AddMinutes(i - count) }); IReadOnlyList frames = [.. early.Concat(source.Content.Frames).Select((f, i) => f with { Index = i })]; source.Content = source.Content with { Frames = frames, Light = LightAnalyzer.Analyze(frames) }; } [Test] public async Task AFailedSaveStaysPendingUntilItIsStored() { 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); } } }