feat(editor): visual crop, rotate/mirror/flip/straighten, colour looks (owner review 1 phase 4) (#26)
CI / Build and test (push) Successful in 8m19s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 12m9s
CI / PostgreSQL 16 integration (push) Successful in 7m49s
CI / PostgreSQL 17 integration (push) Successful in 7m19s
CI / Docker image (push) Successful in 46s
Release / Server image (push) Successful in 1m14s

Owner review 1 R5 + R6. Camera rotation, mirror, flip, straighten and crop handles locked to the output; an Exposure Look group; Export output size ("proportions win"); settings format 2 with older-node gates. Also fixes project text and hashes differing between Windows and Linux.

Closes #19
Closes #20

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #26.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 01:09:09 +01:00
1 parent db389a54f2
commit 188b2c2e55
355 files changed
+10549 -1061

No files matched your search

@@ -0,0 +1,311 @@
using System.Globalization;
using Chronos.App.Editor;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
/// <summary>
/// The Camera step's rows (owner review 1, R5/R6) and the Exposure step's Look group on an open session of the 96 × 64
/// synthetic sunset: the crop box locked to the aspect through Crop size, X and Y, the orientation controls, Straighten,
/// the look written only when it is not the identity, and every row's label and tooltip in English and Italian.
/// </summary>
[Serial]
public sealed class CameraTabTests
{
private static (EditorSession Session, FakeSequenceSource Source) Open(ProjectSettings? project = null)
{
var content = EditorFixture.Content(EditorFixture.Sunset, project);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
return (new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)), source);
}
private static ProjectSettings WithAspect(string aspect, string? preset = null)
{
var project = new ProjectSettings();
project = project with { Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual(aspect) } };
return preset is null ? project : project with { Export = project.Export with { Preset = project.Export.Preset.WithManual(preset) } };
}
private static T Row<T>(IReadOnlyList<SettingRow> rows, string headerKey)
where T : SettingRow => (T)rows.Single(r => r.Header == Loc.L(headerKey));
private static void Refresh(IReadOnlyList<SettingRow> rows)
{
foreach (var row in rows) row.Refresh();
}
[Test]
public void TheRotationRowCountsTheTurnsAsShown()
{
var camera = new CameraSettings();
foreach (var op in new[] { OrientationOp.Mirror, OrientationOp.RotateRight, OrientationOp.RotateRight, OrientationOp.Flip, OrientationOp.RotateRight })
{
var before = CameraTab.ShownTurns(camera);
camera = OrientationEdit.Apply(camera, op);
var expected = op == OrientationOp.RotateRight ? (before + 1) % 4 : (4 - before) % 4;
Assert.Equal(expected, CameraTab.ShownTurns(camera), $"after {op}");
}
Assert.Equal(3, CameraTab.ShownTurns(new CameraSettings { Rotate = 90, Mirror = true }));
Assert.Equal(1, CameraTab.ShownTurns(new CameraSettings { Rotate = 90, Mirror = true, Flip = true }));
}
[Test]
public async Task CropSizeAndPlaceMoveTheBoxLockedToTheAspect()
{
var (session, _) = Open(WithAspect("9:16"));
await using (session)
{
var rows = CameraTab.FramingRows(session);
var size = Row<NumberRow>(rows, "Editor.Camera.CropSize");
var x = Row<NumberRow>(rows, "Editor.Camera.CropX");
var y = Row<NumberRow>(rows, "Editor.Camera.CropY");
Assert.Equal(1.0, size.Value, "no crop: the largest box");
Assert.Equal(0.0, x.Value);
Assert.True(x.IsApplicable, "a 9:16 box can move across a 3:2 frame");
Assert.False(y.IsApplicable, "but not up or down");
Assert.Equal(Loc.L("Tooltips.Editor.NotApplicable.NoSlack"), y.NotApplicableReason);
var ratio = session.CropLockRatio(session.Project);
x.Value = 1;
var box = CropFrame.Of(session.Project.Camera.Crop);
Assert.Approximately(1, box.Right, 1e-9, "Crop X +1 puts the box at the right edge");
Assert.Approximately(ratio, box.Width / box.Height, 1e-9, "locked to the aspect");
Refresh(rows);
size.Value = 0.5;
box = CropFrame.Of(session.Project.Camera.Crop);
Assert.Approximately(0.5, box.Height, 1e-9, "half the largest box");
Assert.Approximately(1, box.Right, 1e-9, "still at the right edge");
Assert.Approximately(ratio, box.Width / box.Height, 1e-9);
Refresh(rows);
Assert.True(y.IsApplicable, "a smaller box can move up and down");
Assert.Equal(1.0, x.Value);
Assert.Equal("+1.00", x.DisplayValue);
Assert.Equal("50 %", size.DisplayValue);
y.Value = -1;
Assert.Approximately(0, CropFrame.Of(session.Project.Camera.Crop).Y, 1e-9, "Crop Y −1 is the top");
Refresh(rows);
size.Value = 0.02;
Assert.Approximately(CropFrame.MinimumShare, CropFrame.Of(session.Project.Camera.Crop).Height, 1e-9, "never below a tenth of the largest box");
Assert.True(session.Project.Camera is { OffsetX: 0, OffsetY: 0 });
}
}
[Test]
public async Task TheWholeFrameAtItsOwnProportionsIsNoCrop()
{
var (session, _) = Open(WithAspect("source", "png-sequence"));
await using (session)
{
var rows = CameraTab.FramingRows(session);
var size = Row<NumberRow>(rows, "Editor.Camera.CropSize");
size.Value = 0.6;
Assert.NotNull(session.Project.Camera.Crop);
Refresh(rows);
size.Value = 1;
Assert.Null(session.Project.Camera.Crop, "the largest box is the whole view: nothing is stored");
Assert.Equal(ProjectSettings.BaseVersion, session.Project.RequiredFormat);
}
}
[Test]
public async Task ALegacyCropPlacedByOffsetsIsBakedInAtItsFirstEdit()
{
var legacy = WithAspect("1:1");
legacy = legacy with { Camera = legacy.Camera with { OffsetX = 1 } };
var (session, _) = Open(legacy);
await using (session)
{
var rows = CameraTab.FramingRows(session);
var before = CameraTab.LockedBox(session, session.Project);
Assert.Approximately(1, before.Right, 1e-9, "the render puts the square at the right");
Assert.Equal(1.0, Row<NumberRow>(rows, "Editor.Camera.CropX").Value, "the rows show it where it renders");
Row<NumberRow>(rows, "Editor.Camera.CropSize").Value = 0.8;
var after = CropFrame.Of(session.Project.Camera.Crop);
Assert.True(session.Project.Camera is { OffsetX: 0, OffsetY: 0 }, "the offsets are baked into the box");
Assert.Approximately(1, after.Right, 1e-9);
Assert.Approximately(0.8 * before.Height, after.Height, 1e-9);
}
}
[Test]
public async Task TheRotationButtonsTurnAndTheRowShowsTheStoredAngle()
{
var (session, _) = Open(WithAspect("16:9"));
await using (session)
{
var rows = CameraTab.FramingRows(session);
var rotation = Row<IconActionsRow>(rows, "Editor.Camera.Rotation");
Assert.Equal("0°", rotation.Value);
Assert.SequenceEqual([Loc.L("Editor.Camera.RotateLeft"), Loc.L("Editor.Camera.RotateRight")], rotation.Actions.Select(a => a.Name));
Assert.SequenceEqual(["Icon.RotateLeft", "Icon.RotateRight"], rotation.Actions.Select(a => a.GlyphKey));
rotation.Actions[1].Command.Execute(null);
Refresh(rows);
Assert.Equal("90°", rotation.Value);
rotation.Actions[0].Command.Execute(null);
rotation.Actions[0].Command.Execute(null);
Refresh(rows);
Assert.Equal("270°", rotation.Value);
Assert.Equal("9:16", session.Project.Camera.Aspect.Manual, "three quarter turns: portrait");
}
}
[Test]
public async Task MirrorAndFlipAreSwitchesThatMoveTheCropWithThePicture()
{
var project = WithAspect("16:9");
project = project with { Camera = project.Camera with { Crop = [0.1, 0.2, 0.3, 0.4] } };
var (session, _) = Open(project);
await using (session)
{
var rows = CameraTab.FramingRows(session);
var mirror = Row<SwitchRow>(rows, "Editor.Camera.Mirror");
var flip = Row<SwitchRow>(rows, "Editor.Camera.Flip");
Assert.False(mirror.IsOn);
mirror.IsOn = true;
Assert.True(session.Project.Camera.Mirror);
Assert.SequenceEqual([0.6, 0.2, 0.3, 0.4], session.Project.Camera.Crop!, "x becomes 1 − x − w");
flip.IsOn = true;
Assert.True(session.Project.Camera.Flip);
Assert.SequenceEqual([0.6, 0.4, 0.3, 0.4], session.Project.Camera.Crop!, "y becomes 1 − y − h");
Assert.True(session.Undo());
Refresh(rows);
Assert.False(flip.IsOn, "the switch follows undo");
Assert.True(mirror.IsOn);
}
}
[Test]
public async Task ASwitchTheProjectDoesNotTakeSpringsBack()
{
var (session, source) = Open();
await using (session)
{
var mirror = Row<SwitchRow>(CameraTab.FramingRows(session), "Editor.Camera.Mirror");
source.IsReadOnly = true;
mirror.IsOn = true;
Assert.False(mirror.IsOn);
Assert.False(session.Project.Camera.Mirror);
}
}
[Test]
public async Task StraightenStoresTenthsOfADegreeAndShowsTheGrid()
{
var (session, _) = Open();
await using (session)
{
var straighten = Row<NumberRow>(CameraTab.FramingRows(session), "Editor.Camera.Straighten");
Assert.True(straighten.ShowsGrid, "using it shows the preview's grid");
Assert.Equal((-15.0, 15.0), (straighten.Minimum, straighten.Maximum));
straighten.Value = -1.23;
Assert.Equal(-1.2, session.Project.Camera.Straighten);
Assert.Equal("−1.2°", straighten.DisplayValue);
Assert.Equal(ProjectSettings.CurrentVersion, session.Project.RequiredFormat, "a straighten needs format 2");
straighten.Value = 0.02;
Assert.Equal(0.0, session.Project.Camera.Straighten);
Assert.False(double.IsNegative(session.Project.Camera.Straighten), "never −0");
Assert.Equal(ProjectSettings.BaseVersion, session.Project.RequiredFormat, "level again: format 1");
Assert.True(CameraTab.FramingRows(session).OfType<NumberRow>().Count(r => r.ShowsGrid) == 1, "only Straighten");
}
}
[Test]
public async Task TheLookIsWrittenOnlyWhenAFilterIsChosen()
{
var (session, _) = Open();
await using (session)
{
var before = session.Project.ToJson();
var rows = ExposureTab.LookRows(session);
Assert.True(rows[0] is GroupRow, "the group starts with its name");
var filter = Row<ChoiceRow>(rows, "Editor.Look.Filter");
var strength = Row<NumberRow>(rows, "Editor.Look.Strength");
Assert.Equal("none", filter.Selected?.Value);
Assert.False(strength.IsApplicable, "no filter: Strength is n/a");
Assert.Equal(Loc.L("Tooltips.Editor.NotApplicable.NoLook"), strength.NotApplicableReason);
Assert.SequenceEqual(["None", "Mono", "Sepia", "Warm", "Cool", "Vivid", "Muted", "Fade"], filter.Options.Select(o => o.Label));
filter.Selected = filter.Options.Single(o => Equals(o.Value, "sepia"));
Assert.Equal(new LookSettings { Filter = "sepia" }.Filter, session.Project.Look?.Filter);
Assert.Null(session.Project.Look!.Strength, "100 % is the default");
Assert.Equal(ProjectSettings.CurrentVersion, session.Project.RequiredFormat);
Refresh(rows);
Assert.True(strength.IsApplicable);
Assert.Equal(1.0, strength.Value);
strength.Value = 0.6;
Assert.Equal(0.6, session.Project.Look!.Strength);
Assert.Equal("60 %", strength.DisplayValue);
strength.Value = 1;
Assert.Null(session.Project.Look!.Strength);
// 0 % would be a look that changes nothing yet changes the text: None is the one way there.
Assert.Equal(ExposureTab.MinimumStrength, strength.Minimum);
Assert.Null(ExposureTab.WithLook(session.Project, "sepia", 0).Look, "the identity is written as no look");
Refresh(rows);
filter.Selected = filter.Options.Single(o => Equals(o.Value, "none"));
Assert.Null(session.Project.Look, "the identity is no look");
Assert.Equal(ProjectSettings.BaseVersion, session.Project.RequiredFormat);
Assert.Equal(before, session.Project.ToJson(), "and the text is the one before the look");
}
}
[Test]
public void ALookOfANewerChronosKeepsWhatItDoesNotKnow()
{
var extra = ProjectSettings.FromJson("""{"look":{"filter":"warm","strength":0.4,"grain":0.2}}""");
var changed = ExposureTab.WithLook(extra, "cool", 0.4);
Assert.Equal("cool", changed.Look?.Filter);
Assert.Contains("\"grain\":0.2", changed.ToJson().Replace(" ", string.Empty, StringComparison.Ordinal));
}
[Test]
public async Task EveryRowHasATooltipAndALabelOfAtMostThreeWordsInEnglishAndItalian()
{
var (session, _) = Open(WithAspect("9:16"));
await using (session)
{
var missing = new List<string>();
void OnMissing(string key) => missing.Add(key);
Loc.MissingKey += OnMissing;
try
{
foreach (var culture in new[] { "en", "it" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
var rows = CameraTab.FramingRows(session).Concat(ExposureTab.LookRows(session)).ToList();
var labels = new List<string>();
foreach (var row in rows)
{
labels.Add(row.Header);
Assert.False(string.IsNullOrWhiteSpace(row.ToolTip), $"{culture}: {row.Header} has a tooltip");
Assert.NotEqual(row.Header, row.ToolTip, $"{culture}: the tooltip explains, it does not repeat the label");
if (row is IconActionsRow icons)
{
foreach (var action in icons.Actions)
{
labels.Add(action.Name);
Assert.False(string.IsNullOrWhiteSpace(action.ToolTip), $"{culture}: {action.Name} has a tooltip");
}
}
if (row is ChoiceRow choices) labels.AddRange(choices.Options.Select(o => o.Label));
}
labels.AddRange(new[] { "Editor.Camera.ResetFraming", "Editor.Export.OutputSize" }.Select(k => Loc.L(k)));
foreach (var key in new[] { "Tooltips.Editor.Camera.ResetFraming", "Tooltips.Editor.Camera.ResetFramingNone", "Tooltips.Editor.Export.OutputSize" })
Assert.False(string.IsNullOrWhiteSpace(Loc.L(key)), key);
foreach (var label in labels)
Assert.LessOrEqual(label.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"{culture}: \"{label}\" is at most three words");
}
}
finally
{
Loc.MissingKey -= OnMissing;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
Assert.Empty(missing);
}
}
}
@@ -206,6 +206,26 @@ public sealed class EditPathTests
"a crop of the whole frame is no crop");
}
[Test]
public void TheOrientationAndTheLookReadEdited()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var project = new ProjectSettings();
foreach (var (camera, what) in new[]
{
(new CameraSettings { Rotate = 90 }, "a quarter turn"), (new CameraSettings { Mirror = true }, "a mirror"),
(new CameraSettings { Flip = true }, "a flip"), (new CameraSettings { Straighten = -1.2 }, "a straighten"),
})
Assert.Equal(Loc.L("Editor.Step.Edited"), State(EditPath.Camera, content, project: project with { Camera = camera }).Text, what);
Assert.Equal(Loc.L("Editor.Step.Edited"), State(EditPath.Exposure, content, project: project with { Look = new LookSettings { Filter = "sepia" } }).Text,
"a look");
Assert.Equal(Loc.L("Common.Auto"), State(EditPath.Exposure, content, project: project with { Look = null }).Text, "no look");
Assert.Equal(Loc.L("Common.Auto"), State(EditPath.Exposure, content, project: project with { Look = new LookSettings { Filter = "sepia", Strength = 0 } }).Text,
"a look at 0 % changes no pixel");
Assert.Equal(Loc.L("Common.Auto"), State(EditPath.Exposure, content, project: project with { Look = new LookSettings { Filter = "grain" } }).Text,
"a filter this Chronos does not know renders as none");
}
[Test]
public void AMissingValueOfASettingThatDoesNotApplyAsksNothing()
{
@@ -3,6 +3,7 @@ using System.Text.Json;
using Chronos.App.Editor;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Protocol;
@@ -416,4 +417,196 @@ public sealed class EditorSessionTests
Assert.Equal(2, session.Project.HeroFrame);
}
}
// ---- Orientation and framing (owner review 1, R5/R6) ----
/// <summary>A project with a manual aspect (the advice never decides it) and a crop.</summary>
private static ProjectSettings WithAspect(string aspect, double[]? crop = null)
{
var project = new ProjectSettings();
return project with { Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual(aspect), Crop = crop } };
}
[Test]
public async Task EachOrientationPressIsOneUndoStepAndTurnsTheCropWithThePicture()
{
var (session, _) = Open(WithAspect("16:9", [0.1, 0.2, 0.4, 0.3]));
await using (session)
{
Assert.True(session.Orient(OrientationOp.RotateRight));
Assert.Equal(90, session.Project.Camera.Rotate);
Assert.Equal("9:16", session.Project.Camera.Aspect.Manual, "the proportions turn with the picture");
Assert.SequenceEqual([0.5, 0.1, 0.3, 0.4], session.Project.Camera.Crop!, "the crop keeps the content");
Assert.True(session.Orient(OrientationOp.Mirror));
Assert.True(session.Project.Camera.Mirror);
Assert.SequenceEqual([0.2, 0.1, 0.3, 0.4], session.Project.Camera.Crop!, "mirror maps x to 1 − x − w");
Assert.True(session.Undo());
Assert.False(session.Project.Camera.Mirror, "one press, one step");
Assert.Equal(90, session.Project.Camera.Rotate);
Assert.True(session.Undo());
Assert.Equal(0, session.Project.Camera.Rotate);
Assert.SequenceEqual([0.1, 0.2, 0.4, 0.3], session.Project.Camera.Crop!);
}
}
[Test]
public async Task OptimiseAfterATurnAdvisesTheAspectOfTheTurnedView()
{
var (session, _) = Open();
await using (session)
{
session.Edit(p => Advisor.Apply(p, session.Advice));
var advised = EditorSettings.Aspect.Effective(session.Project, null);
Assert.True(advised is "16:9" or "9:16", "the analysis advises a video aspect");
Assert.True(session.Orient(OrientationOp.RotateRight));
var turned = EditorSettings.Aspect.Effective(session.Project, null);
Assert.NotEqual(advised, turned, "the turn transposes the advised aspect");
session.Optimise(AdvisorSection.Camera);
Assert.Equal(turned, EditorSettings.Aspect.Effective(session.Project, null), "the advice is worked out on the turned view");
}
}
[Test]
public async Task ATurnSeenThroughAMirrorTurnsThePictureTheWayTheUserPressed()
{
var (session, _) = Open(WithAspect("16:9"));
await using (session)
{
session.Orient(OrientationOp.RotateRight);
Assert.Equal(90, session.Project.Camera.Rotate, "clockwise as stored");
session.Orient(OrientationOp.Mirror);
session.Orient(OrientationOp.RotateRight);
Assert.Equal(0, session.Project.Camera.Rotate, "through one mirror, a clockwise press is an anticlockwise stored turn");
session.Orient(OrientationOp.Flip);
session.Orient(OrientationOp.RotateRight);
Assert.Equal(90, session.Project.Camera.Rotate, "mirror and flip together are a half turn: the sense is kept");
Assert.True(session.Project.Camera is { Mirror: true, Flip: true });
}
}
[Test]
public async Task FourRightTurnsGiveBackTheSameCanonicalText()
{
var keyed = WithAspect("16:9", [0.1, 0.2, 0.4, 0.3]);
keyed = keyed with { Camera = keyed.Camera with { Keyframes = [new CameraKey(4, 0.3, 0.6, 1.5, 2)], Straighten = 1.5 } };
var (session, _) = Open(keyed);
await using (session)
{
var before = session.Project.ToJson();
for (var i = 0; i < 4; i++) Assert.True(session.Orient(OrientationOp.RotateRight));
Assert.Equal(before, session.Project.ToJson());
Assert.Equal(ProjectSettings.CurrentVersion, session.Project.RequiredFormat, "a straighten needs format 2");
}
}
[Test]
public async Task AnAspectChangeRefitsALockedCropAroundItsCentre()
{
var (session, _) = Open(WithAspect("16:9"));
await using (session)
{
var ratio = session.CropLockRatio(session.Project);
var box = CropFrame.Clamp(new RectD(0.2, 0.2, 0.5, 0.5 / ratio), ratio);
Assert.True(session.Edit(p => p with { Camera = p.Camera with { Crop = CropFrame.ToCrop(box) } }));
Assert.True(session.Edit(p => EditorSettings.Aspect.WithManual(p, "9:16")));
var refitted = CropFrame.Of(session.Project.Camera.Crop);
Assert.Approximately(session.CropLockRatio(session.Project), refitted.Width / refitted.Height, 1e-9, "locked to the new proportions");
Assert.Approximately(box.CenterX, refitted.CenterX, 1e-9, "the same centre");
Assert.Approximately(box.CenterY, refitted.CenterY, 1e-9);
Assert.Approximately(box.Width * box.Height, refitted.Width * refitted.Height, 1e-9, "the same area");
Assert.True(session.Undo());
Assert.SequenceEqual(CropFrame.ToCrop(box)!, session.Project.Camera.Crop!, "the aspect and the refit are one step");
}
}
[Test]
public async Task ALegacyCropPlacedByOffsetsIsLeftForTheRenderToFit()
{
var legacy = WithAspect("16:9", [0, 0, 1, 0.8]);
legacy = legacy with { Camera = legacy.Camera with { OffsetX = 0.5 } };
var (session, _) = Open(legacy);
await using (session)
{
Assert.True(session.Edit(p => EditorSettings.Aspect.WithManual(p, "1:1")));
Assert.SequenceEqual([0.0, 0, 1, 0.8], session.Project.Camera.Crop!);
Assert.Equal(0.5, session.Project.Camera.OffsetX);
}
}
[Test]
public async Task ResetFramingClearsTheCropAndTheOrientationAndKeepsTheKeyframesOnTheirContent()
{
var framed = WithAspect("9:16", [0.2, 0, 0.3, 1]);
var key = new CameraKey(3, 0.4, 0.5, 2, 0);
framed = framed with
{
Camera = framed.Camera with { OffsetX = 0.2, OffsetY = -0.1, Rotate = 270, Mirror = true, Flip = true, Straighten = -3.5, Keyframes = [key] },
Look = new LookSettings { Filter = "sepia" },
};
var (session, _) = Open(framed);
await using (session)
{
Assert.True(EditorSession.HasFraming(session.Project.Camera));
Assert.True(session.ResetFraming());
var camera = session.Project.Camera;
Assert.Null(camera.Crop);
Assert.True(camera is { OffsetX: 0, OffsetY: 0, Rotate: 0, Mirror: false, Flip: false, Straighten: 0 });
var back = OrientationEdit.Apply(OrientationEdit.Apply(OrientationEdit.Apply(OrientationEdit.Apply(OrientationEdit.Apply(framed,
OrientationOp.Flip), OrientationOp.Mirror), OrientationOp.RotateLeft), OrientationOp.RotateLeft), OrientationOp.RotateLeft);
Assert.SequenceEqual(back.Camera.Keyframes, camera.Keyframes, "keyframes stay on the content they framed");
Assert.Equal(1, camera.Keyframes.Count);
Assert.Equal("16:9", camera.Aspect.Manual, "the aspect turns back with the picture");
Assert.Equal("sepia", session.Project.Look?.Filter, "nor the look");
Assert.False(EditorSession.HasFraming(camera));
Assert.False(session.ResetFraming(), "nothing left to clear");
Assert.True(session.Undo());
Assert.Equal(270, session.Project.Camera.Rotate, "one step");
}
}
[Test]
public void ResetFramingTurnsAKeyframeBackWithThePicture()
{
var turned = new ProjectSettings();
turned = turned with { Camera = turned.Camera with { Rotate = 90, Aspect = turned.Camera.Aspect.WithManual("9:16"), Keyframes = [new CameraKey(2, 0.2, 0.3, 1.5, 0)] } };
var reset = EditorSession.WithoutFraming(turned);
var (x, y) = OrientationEdit.MapPoint(0.2, 0.3, OrientationOp.RotateLeft);
Assert.True(reset.Camera.Keyframes[0] is { CenterX: var cx, CenterY: var cy } && cx == x && cy == y, "moved as the picture turns back");
Assert.True((x, y) != (0.2, 0.3));
Assert.Equal("16:9", reset.Camera.Aspect.Manual);
var again = OrientationEdit.Apply(reset, OrientationOp.RotateRight);
Assert.True(again.Camera is { Rotate: 90 } && again.Camera.Keyframes[0] is { CenterX: 0.2, CenterY: 0.3 }, "turning again puts it where it was");
Assert.Equal("9:16", again.Camera.Aspect.Manual);
}
[Test]
public async Task ASequencePresetKeepsTheOrientationAndTheLook()
{
var turned = new ProjectSettings() with { Look = new LookSettings { Filter = "mono", Strength = 0.5 } };
turned = turned with { Camera = turned.Camera with { Rotate = 90, Mirror = true, Straighten = 2 } };
var (session, _) = Open(turned);
await using (session)
{
Assert.True(session.ApplyPreset(session.Presets.First(p => p.Id == "social-vertical")));
Assert.True(session.Project.Camera is { Rotate: 90, Mirror: true, Straighten: 2 });
Assert.Equal("mono", session.Project.Look?.Filter);
Assert.Equal(0.5, session.Project.Look?.Strength);
}
}
[Test]
public async Task AReadOnlyProjectIsNeitherTurnedNorReset()
{
var (session, source) = Open(WithAspect("16:9", [0.1, 0.2, 0.4, 0.3]));
await using (session)
{
source.IsReadOnly = true;
Assert.False(session.Orient(OrientationOp.RotateLeft));
Assert.False(session.ResetFraming());
Assert.Equal(0, session.Project.Camera.Rotate);
Assert.NotNull(session.Project.Camera.Crop);
}
}
}
@@ -4,6 +4,7 @@ using System.IO;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
@@ -19,6 +20,7 @@ using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Testing;
using Chronos.Ui.Controls;
using Chronos.Ui.Theming;
@@ -424,6 +426,129 @@ public sealed class EditorSmokeTests
}
});
/// <summary>
/// The Camera step edits the crop box on the preview (owner review 1, R5): its mask is on by default and shows the box the
/// render fits, a drag on the picture is one undo step, a run of key presses another, the box is locked to the output
/// proportions with the offsets at 0, and a quarter turn shows the turned view frame.
/// </summary>
[Test]
public Task TheCameraStepEditsTheCropBoxOnThePreview() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
var id = await app.Sample.FillEditorAsync();
app.Shell.OpenSequence(id);
await app.Shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(app.Shell.Sequence.Editor);
try
{
editor.SelectedTab = editor.Exposure;
Assert.False(editor.ShowCropMask, "the other steps keep their mask off");
Assert.False(editor.CropEditable);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.View"), editor.PreviewToolTip);
editor.SelectedTab = editor.Tabs.OfType<CameraTab>().Single();
Assert.True(editor.ShowCropMask, "on by default on the Camera step");
Assert.True(editor.CropEditable);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.CropEdit"), editor.PreviewToolTip);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
await SettleAsync(app.Window);
var (width, height) = (editor.Session.Content.SourceWidth, editor.Session.Content.SourceHeight);
RenderGeometry Geometry() => RenderGeometry.Create(editor.Session.Project.Camera, ExportResolver.Resolve(editor.Session.Project.Export), width, height);
static Rect RectOf(Chronos.Core.Imaging.Geometry.RectD r) => new(r.X, r.Y, r.Width, r.Height);
Assert.Equal(RectOf(Geometry().EditableCrop), editor.EditCrop, "the mask is the box the render fits");
Assert.Equal(editor.EditCrop, editor.CropRect);
var viewport = Find<PreviewViewport>(app.Window).Single(v => v.IsVisible);
Assert.True(viewport.CropEditable);
Assert.Equal(editor.EditCrop, viewport.EditCrop);
Assert.Equal(editor.CropLockRatio, viewport.CropLockRatio);
Assert.Equal(editor.PreviewToolTip, viewport.ToolTip);
// The bottom-right handle dragged in: one undo step, the box locked, the offsets at 0.
Point At(double nx, double ny)
{
var (x, y) = viewport.View.ToView(nx * viewport.ImageSize.Width, ny * viewport.ImageSize.Height);
return new Point(x, y);
}
var before = editor.Session.Project.Camera;
var box = viewport.EditCrop;
viewport.Press(At(box.Right, box.Bottom));
viewport.DragTo(At(box.X + box.Width * 0.7, box.Y + box.Height * 0.7), aboutCentre: false);
Assert.Same(before, editor.Session.Project.Camera, "nothing changes while dragging");
viewport.EndDrag(commit: true);
var cropped = editor.Session.Project.Camera;
var crop = Assert.NotNull(cropped.Crop);
Assert.Approximately(0, cropped.OffsetX, 0);
Assert.Approximately(0, cropped.OffsetY, 0);
Assert.Approximately(editor.CropLockRatio, crop[2] / crop[3], 1e-9, "locked to the proportions");
Assert.Less(crop[3], box.Height);
Assert.Approximately(box.X, crop[0], 1e-9, "anchored at the opposite corner");
Assert.Equal(new Rect(crop[0], crop[1], crop[2], crop[3]), editor.EditCrop);
// Two nudges are one more step.
Assert.True(viewport.IsCropSelected, "the press took the box");
Assert.True(viewport.Nudge(Key.Right, ModifierKeys.None));
Assert.True(viewport.Nudge(Key.Down, ModifierKeys.None));
editor.Session.EndEditRun();
var nudged = Assert.NotNull(editor.Session.Project.Camera.Crop);
Assert.Approximately(crop[0] + 0.01, nudged[0], 1e-9);
Assert.Approximately(crop[1] + 0.01, nudged[1], 1e-9);
editor.UndoCommand.Execute(null);
Assert.SequenceEqual(crop, editor.Session.Project.Camera.Crop!, "one undo takes both nudges back");
editor.UndoCommand.Execute(null);
Assert.SequenceEqual(before.Crop ?? [], editor.Session.Project.Camera.Crop ?? [], "and one more the drag");
editor.RedoCommand.Execute(null);
Assert.SequenceEqual(crop, editor.Session.Project.Camera.Crop!);
// The straighten grid shows while the slider is used, on the Camera step only.
editor.IsStraightening = true;
await SettleAsync(app.Window);
Assert.True(viewport.ShowGrid);
editor.IsStraightening = false;
Assert.False(viewport.ShowGrid);
// A quarter turn: the box waits for the turned picture, then maps onto it.
var ratio = editor.CropLockRatio;
editor.Session.Edit(p => p with { Camera = p.Camera with { Rotate = 90, Crop = null } });
Assert.Equal(ratio, editor.CropLockRatio, "the box of the picture on screen until the turned one comes");
Assert.False(editor.CropEditable, "and it cannot be dragged meanwhile: it would land in the turned frame");
Assert.False(editor.CommitCropCommand.CanExecute(editor.EditCrop));
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.True(editor.CropEditable, "the turned picture is on screen");
var picture = (System.Windows.Media.Imaging.BitmapSource)editor.PreviewImage!;
Assert.Less(picture.PixelWidth, picture.PixelHeight, "the landscape source shows turned");
Assert.Equal(Geometry().LockRatio, editor.CropLockRatio);
Assert.Equal(RectOf(Geometry().EditableCrop), editor.EditCrop);
editor.UndoCommand.Execute(null);
await editor.Session.FlushAsync();
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
// Read-only and newer-format projects are drawn, never edited.
var content = EditorFixture.Content(EditorFixture.Sunset);
foreach (var (source, reason) in new[]
{
(new FakeSequenceSource(EditorFixture.Sunset, content) { IsReadOnly = true }, "read-only"),
(new FakeSequenceSource(EditorFixture.Sunset, content with { Project = content.Project with { Version = ProjectSettings.CurrentVersion + 1 } }), "newer format"),
})
{
var locked = new EditorViewModel(app.Shell, new EditorSession(source, source.Content, []), [], EncoderHost.Client);
await using (locked)
{
locked.SelectedTab = locked.Tabs.OfType<CameraTab>().Single();
Assert.True(locked.ShowCropMask, reason);
Assert.False(locked.CropEditable, reason);
Assert.False(locked.CommitCropCommand.CanExecute(new Rect(0.1, 0.1, 0.5, 0.5)), reason);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.View"), locked.PreviewToolTip);
}
}
}
finally
{
await app.Shell.Sequence.CloseAsync();
}
});
/// <summary>
/// At the 1200 px minimum beside the 200 px rail (owner review 1, R1), a server sequence's job keeps its Cancel whole in every
/// language, also read-only (the longest place line): the title and the summary give way first (BRIEF §11.5, cancel always stays).
@@ -8,7 +8,7 @@ using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
/// <summary>Composed texts of the editor (the conflict prompt among them), crop margins and the waveform monitor.</summary>
/// <summary>Composed texts of the editor (the conflict prompt among them, the Camera step's values) and the waveform monitor.</summary>
public sealed class EditorTextTests
{
static EditorTextTests() => _ = EditorFixture.Sunset;
@@ -38,22 +38,15 @@ public sealed class EditorTextTests
}
[Test]
public void CropMarginsKeepAtLeastATenthOfTheFrame()
public void TheCameraRowsShowAnglesAndPlacementsAsTheMockupDoes()
{
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");
Assert.Equal("−1.2°", CameraTab.Degrees(-1.2), "a minus sign, one decimal");
Assert.Equal("15.0°", CameraTab.Degrees(15));
Assert.Equal("0°", CameraTab.Degrees(0), "level reads as a whole number");
Assert.Equal("0°", CameraTab.Degrees(-0.0), "never a negative zero");
Assert.Equal("+0.40", EditorText.Placement(0.4));
Assert.Equal("−0.60", EditorText.Placement(-0.6));
Assert.Equal("Centred", EditorText.Placement(0));
}
[Test]
@@ -1,6 +1,7 @@
using Chronos.App.Editor;
using Chronos.Core.Advice;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
@@ -90,4 +91,57 @@ public sealed class ExportPlannerTests
Assert.Equal("Custom", plan.PresetName);
Assert.Equal(48, plan.Setup.Encoder.Settings.Width);
}
/// <summary>An H.264 encoder that takes at most <paramref name="maxWidth"/>×<paramref name="maxHeight"/> (either way round).</summary>
private sealed class H264Provider(int maxWidth, int maxHeight) : IVideoEncoderProvider
{
public string Name => "h264";
public IReadOnlyList<EncoderCapability> Capabilities { get; } = [new(VideoCodec.H264, "Test H.264", false, maxWidth, maxHeight, false)];
public bool CanEncode(EncodeSettings settings) => settings.Codec == VideoCodec.H264;
public IVideoEncoderSession Open(EncodeSettings settings) => throw new NotSupportedException("Planning never encodes.");
}
private static ProjectSettings FourKAt(string aspect)
{
var project = new ProjectSettings();
return project with
{
Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual(aspect) },
Export = project.Export with { Preset = project.Export.Preset.WithManual("4k-h264") },
};
}
[Test]
public void TheChosenProportionsWinAndThePresetKeepsItsName()
{
var planner = new ExportPlanner(Content, [new H264Provider(4096, 2304)], EncoderHost.Client);
var plan = planner.Plan(FourKAt("9:16"))!;
Assert.Equal((2160, 3840), plan.OutputSize, "4K at 9:16");
Assert.Equal((2160, 3840), plan.EncodedSize, "the encoder takes it turned");
Assert.False(plan.IsCapped);
Assert.Equal("2160 × 3840", ExportTab.OutputSizeOf(plan));
Assert.Equal(Loc.L("Tooltips.Editor.Export.OutputSize"), ExportTab.OutputSizeToolTipOf(plan));
Assert.Equal(Loc.L("Export.Preset.4kH264"), plan.PresetName, "the preset is not made Custom");
Assert.False(plan.Export.IsCustom);
Assert.Equal((3840, 2160), (plan.Export.Width, plan.Export.Height), "Width × Height stay the preset's box");
var workload = plan.Setup.Workload();
Assert.Equal((2160, 3840), (workload.Width, workload.Height), "the estimate is of the adapted size");
var source = planner.Plan(FourKAt("source"))!;
Assert.Equal((3840, 2160), source.OutputSize, "source keeps the preset's ratio");
}
[Test]
public void AnOutputTheEncoderShrinksIsMarkedCapped()
{
var plan = new ExportPlanner(Content, [new H264Provider(1920, 1080)], EncoderHost.Client).Plan(FourKAt("9:16"))!;
Assert.Equal((2160, 3840), plan.OutputSize);
Assert.Equal((1080, 1920), plan.EncodedSize);
Assert.True(plan.IsCapped);
Assert.Equal(Loc.L("Editor.Export.Capped", "1080 × 1920"), ExportTab.OutputSizeOf(plan));
Assert.Equal(Loc.L("Tooltips.Editor.Export.OutputCapped", "1080 × 1920"), ExportTab.OutputSizeToolTipOf(plan), "the largest size it takes, turned");
}
}
@@ -1,6 +1,12 @@
using System.IO;
using Chronos.App.Editor;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Render.Diagnostics;
using Chronos.Core.Video;
using Chronos.Core.Video.Managed;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
@@ -71,6 +77,11 @@ public sealed class PreviewRendererTests
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);
// The flow sees the frames as the render's does, before the look (owner review 1, phase 4): the same vectors with Vivid.
var vivid = new ProjectSettings { Look = new LookSettings { Filter = "vivid" } };
using var looked = await renderer.RenderAsync(new PreviewRequest(10, vivid, 96, PreviewFraming.Source, Vectors: true), null, CancellationToken.None);
Assert.SequenceEqual(frame.Vectors, looked!.Vectors);
}
[Test]
@@ -183,6 +194,133 @@ public sealed class PreviewRendererTests
Assert.True(waveform.Density.Any(d => d > 0));
}
[Test]
public async Task OutputFramingFollowsChosenPortraitProportions()
{
// The chosen proportions win (owner review 1, R5): the square preset's box takes a 9:16 picture.
var (renderer, _) = Create();
var project = new ProjectSettings();
project = project with
{
Export = project.Export with { Preset = project.Export.Preset.WithManual("square-1440") },
Camera = project.Camera with { Aspect = project.Camera.Aspect.WithManual("9:16") },
};
using var output = await renderer.RenderAsync(new PreviewRequest(0, project, 80, PreviewFraming.Output), null, CancellationToken.None);
Assert.Equal(45, output!.Corrected.Width, "810 × 1440 at the preview's long edge");
Assert.Equal(80, output.Corrected.Height);
using var source = await renderer.RenderAsync(new PreviewRequest(0, project, 96, PreviewFraming.Source), null, CancellationToken.None);
Assert.Equal(96, source!.Corrected.Width, "the whole frame");
Assert.Approximately(9.0 / 16 * 64 / 96, source.LockRatio, 1e-12, "the box's ratio in normalised units");
Assert.Approximately(1, source.EditCrop.Height, 1e-9, "the largest 9:16 box of the 3:2 frame");
Assert.Approximately(source.LockRatio, source.EditCrop.Width, 1e-9);
Assert.Approximately(source.EditCrop.Width, source.Crop.Width, 0.02, "the output's footprint is the box");
Assert.Approximately(source.EditCrop.X, source.Crop.X, 0.02);
}
[Test]
public async Task SourceFramingShowsTheTurnedViewFrame()
{
var (renderer, _) = Create();
var plain = new ProjectSettings();
var turned = plain with { Camera = plain.Camera with { Rotate = 90 } };
using var frame = await renderer.RenderAsync(new PreviewRequest(5, plain, 96, PreviewFraming.Source), null, CancellationToken.None);
using var view = await renderer.RenderAsync(new PreviewRequest(5, turned, 96, PreviewFraming.Source), null, CancellationToken.None);
Assert.Equal((96, 64), (frame!.Corrected.Width, frame.Corrected.Height));
Assert.Equal((64, 96), (view!.Corrected.Width, view.Corrected.Height), "a quarter turn swaps the size");
Assert.Equal((64, 96), (view.Original.Width, view.Original.Height));
Assert.Equal((64, 96), view.ViewSize);
Assert.Equal((96, 64), frame.ViewSize);
// Turned a quarter clockwise, exactly: the view's (x, y) is the frame's (y, H − 1 − x).
for (var c = 0; c < 3; c++)
{
var a = frame.Original.Plane(c);
var b = view.Original.Plane(c);
for (var y = 0; y < 96; y += 7)
{
for (var x = 0; x < 64; x += 5) Assert.Approximately(a[(63 - x) * 96 + y], b[y * 64 + x], 1e-6, $"channel {c} at ({x}, {y})");
}
}
}
[Test]
public async Task TheMaskIsTheEditableCropOfTheViewFrame()
{
var (renderer, _) = Create();
var project = new ProjectSettings();
project = project with
{
Camera = project.Camera with
{
Aspect = project.Camera.Aspect.WithManual("1:1"),
Crop = [0.1, 0.05, 0.6, 0.8],
OffsetX = 0.5,
Rotate = 270,
Straighten = 4,
},
};
using var frame = await renderer.RenderAsync(new PreviewRequest(2, project, 96, PreviewFraming.Source), null, CancellationToken.None);
var geometry = RenderGeometry.Create(project.Camera, ExportResolver.Resolve(project.Export), EditorFixture.Sunset.Options.Width, EditorFixture.Sunset.Options.Height);
Assert.Equal(geometry.EditableCrop, frame!.EditCrop, "the box the render fits, the same on every frame");
Assert.Equal(geometry.LockRatio, frame.LockRatio);
Assert.Approximately(frame.EditCrop.Width / frame.EditCrop.Height * frame.Corrected.Width / frame.Corrected.Height, 1, 0.03, "square on the picture");
Assert.Approximately(frame.EditCrop.X, frame.Crop.X, 0.02, "without stabilisation or pose, the output's footprint is the box");
Assert.Approximately(frame.EditCrop.Width, frame.Crop.Width, 0.02);
Assert.Approximately(frame.EditCrop.Height, frame.Crop.Height, 0.02);
Assert.Equal((64, 96), (frame.Corrected.Width, frame.Corrected.Height));
}
[Test]
public async Task ALookChangesOnlyTheCorrectedPicture()
{
var (renderer, _) = Create();
var plain = Deflickered() with { Exposure = new ProjectSettings().Exposure with { HighlightKnee = null } };
var look = new LookSettings { Filter = "sepia", Strength = 0.6 };
foreach (var framing in new[] { PreviewFraming.Output, PreviewFraming.Source })
{
using var before = await renderer.RenderAsync(new PreviewRequest(4, plain, 64, framing), null, CancellationToken.None);
using var after = await renderer.RenderAsync(new PreviewRequest(4, plain with { Look = look }, 64, framing), null, CancellationToken.None);
Assert.True(before!.Original.Data.SequenceEqual(after!.Original.Data), $"{framing}: the original side has no look");
Assert.False(before.Corrected.Data.SequenceEqual(after.Corrected.Data), $"{framing}: the corrected side has it");
FrameFinish.Apply(before.Corrected, look, null);
Assert.True(before.Corrected.Data.SequenceEqual(after.Corrected.Data), $"{framing}: the render's finish");
}
}
[Test]
public async Task OutputFramingMatchesTheRenderTurnedStraightenedAndWithALook()
{
var project = new ProjectSettings();
project = project with
{
Exposure = project.Exposure with { HighlightKnee = null },
Export = project.Export with { Preset = project.Export.Preset.WithManual("png-sequence") },
Camera = project.Camera with { Rotate = 90, Straighten = 3 },
Look = new LookSettings { Filter = "sepia", Strength = 0.6 },
};
var (renderer, _) = Create();
using var preview = await renderer.RenderAsync(new PreviewRequest(0, project, 96, PreviewFraming.Output), null, CancellationToken.None);
Assert.Equal((64, 96), (preview!.Corrected.Width, preview.Corrected.Height), "the turned frame at the source's size");
var capture = new CapturingEncoder();
var pixels = new SyntheticFrameSource(EditorFixture.Sunset);
var folder = Path.Combine(Path.GetTempPath(), "chronos-preview-" + Guid.NewGuid().ToString("N"));
try
{
var input = new RenderInput { Source = pixels, Frames = pixels.Metadata(), Project = project };
await new RenderPipeline([capture, new ManagedEncoderProvider()]).RenderAsync(input, new RenderTarget(ExportResolver.Resolve(project.Export), folder));
}
finally
{
if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true);
}
var rendered = capture.Frames[0];
Assert.Equal((preview.Corrected.Width, preview.Corrected.Height), (rendered.Width, rendered.Height));
Assert.Greater(Psnr(rendered, preview.Corrected), 40, "the preview is the render's frame");
foreach (var frame in capture.Frames) frame.Dispose();
}
/// <summary>A sunset project as the advisor leaves it: deflicker, holy grail, white balance and stabilisation on.</summary>
private static ProjectSettings Sunset()
{
@@ -207,6 +345,49 @@ public sealed class PreviewRendererTests
return Math.Log2(sum / n);
}
/// <summary>Peak signal-to-noise ratio of the 8-bit sRGB encodings.</summary>
private static double Psnr(ImageBuffer expected, ImageBuffer actual)
{
var a = PixelConvert.ToInterleaved8(expected, 3);
var b = PixelConvert.ToInterleaved8(actual, 3);
double sum = 0;
for (var i = 0; i < a.Length; i++) sum += (a[i] - b[i]) * (a[i] - b[i]);
return sum == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255 / (sum / a.Length));
}
/// <summary>A PNG-sequence encoder that keeps a copy of every frame instead of writing it.</summary>
private sealed class CapturingEncoder : IVideoEncoderProvider
{
private static readonly EncoderCapability Capability = new(VideoCodec.PngSequence, "Capture", false, 8192, 8192, true);
public string Name => "capture";
public IReadOnlyList<EncoderCapability> Capabilities { get; } = [Capability];
public List<ImageBuffer> Frames { get; } = [];
public bool CanEncode(EncodeSettings settings) => settings.Codec == VideoCodec.PngSequence;
public IVideoEncoderSession Open(EncodeSettings settings) => new Session(this);
private sealed class Session(CapturingEncoder owner) : IVideoEncoderSession
{
public string EncoderName => Capability.Name;
public bool IsHardware => false;
public void WriteFrame(ImageBuffer frame, long duration90k) => owner.Frames.Add(frame.Clone());
public void Complete()
{
}
public void Dispose()
{
}
}
}
/// <summary>Standard deviation of the frame-to-frame differences (flicker, not the slow ramp).</summary>
private static double Spread(List<double> values)
{
@@ -117,7 +117,7 @@ public sealed class ProjectHistoryTests
[Test]
public void SettingsOfANewerChronosAdoptedDropTheStepsInsteadOfMergingThem()
{
var newer = ProjectSettings.FromJson("""{ "version": 2, "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""", allowNewer: true);
var newer = ProjectSettings.FromJson("""{ "version": 3, "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""", allowNewer: true);
// The workspace's merge throws as ProjectMerge does where both sides changed and one is a newer Chronos's.
foreach (var merge in new Func<ProjectSettings, ProjectSettings, ProjectSettings, ProjectSettings>?[]
{ null, (basis, ours, theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs).Merged })
@@ -65,6 +65,30 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
}
/// <summary>
/// Owner review 1, phase 4: an older server (format 1) stores whatever settings it is sent and then fails every render of
/// them, so a turn or a look is never sent to it; an edit of the base format still is.
/// </summary>
[Test]
public async Task SettingsAnOlderServerCannotReadAreNotSent()
{
var (source, api, _) = Open(serverFormat: ProjectSettings.BaseVersion);
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
var turned = content.Project with { Camera = content.Project.Camera with { Rotate = 90 } };
var refused = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(turned, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), refused.Message);
var look = content.Project with { Look = new LookSettings { Filter = "sepia" } };
await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(look, content.Project, context.Cancellation));
Assert.Empty(api.Edits);
var brighter = content.Project with { Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.5 } };
await source.SaveProjectAsync(brighter, content.Project, context.Cancellation);
Assert.Count(1, api.Edits);
}
}
[Test]
public async Task SavesSendTheVersionTheyWereMadeFrom()
{
@@ -574,12 +598,12 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(int frames = 6, int cached = int.MaxValue,
bool readOnly = false) =>
Open(EditorFixture.Sequence(frames), cached, readOnly);
bool readOnly = false, int serverFormat = ProjectSettings.CurrentVersion) =>
Open(EditorFixture.Sequence(frames), cached, readOnly, serverFormat);
/// <summary>A server sequence whose first <paramref name="cached"/> proxies are on this PC (synthetic JPEGs).</summary>
private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(SyntheticSequence sunset, int cached = int.MaxValue,
bool readOnly = false)
bool readOnly = false, int serverFormat = ProjectSettings.CurrentVersion)
{
var folder = context.CreateTempDirectory("proxies");
var sequence = new Sequence
@@ -603,7 +627,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
var remote = new RemoteSequence(Server, sequence, frames, files);
var api = new FakeRemoteSequenceApi(sequence, [.. frames.Select(f => f.Id)]) { SettingsJson = new ProjectSettings().ToJson() };
return (new RemoteSequenceSource(remote, api, DecoderFactory.CreateClient(null), readOnly), api, remote);
return (new RemoteSequenceSource(remote, api, DecoderFactory.CreateClient(null), readOnly, serverFormat), api, remote);
}
/// <summary>Someone on the server sets the exposure offset to 0.3 and moves the framing.</summary>
@@ -0,0 +1,81 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Chronos.App.Editor;
using Chronos.App.Shell;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
/// <summary>
/// The Camera step's Straighten slider reports its use to the editor (owner review 1, R6): the NumberRow template of
/// <c>Editor/EditorPanels.xaml</c> turns <see cref="SliderActivity"/> on for the row that shows the grid, and binds its
/// <see cref="SliderActivity.IsActiveProperty"/> one way to the source <c>Editor.IsStraightening</c> of the step. Built off
/// screen on the test dispatcher (no window): the slider's activity is set as <see cref="SliderActivity"/> sets it when the
/// slider takes the focus or the mouse capture.
/// </summary>
[WindowsOnly]
[Serial]
public sealed class StraightenGridBindingTests
{
[Test]
public async Task UsingTheStraightenSliderTellsTheEditor()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var session = new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content), content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
var rows = CameraTab.FramingRows(session);
Windows.WpfApplication.Dispatcher.Invoke(() =>
{
AppResources.Merge(Application.Current);
var step = new FakeStep();
var items = new ItemsControl { ItemsSource = rows, DataContext = step };
items.Resources.MergedDictionaries.Add(new ResourceDictionary
{
Source = new Uri("pack://application:,,,/Chronos;component/Editor/EditorPanels.xaml", UriKind.Absolute),
});
var host = new Border { Child = items };
host.Measure(new Size(320, 2000));
host.Arrange(new Rect(0, 0, 320, 2000));
host.UpdateLayout();
var sliders = Descendants<Slider>(host).ToList();
Assert.Equal(rows.OfType<NumberRow>().Count(), sliders.Count);
var straighten = Assert.NotNull(sliders.SingleOrDefault(s => s.DataContext is NumberRow { ShowsGrid: true }));
Assert.Equal(Loc.L("Editor.Camera.Straighten"), ((NumberRow)straighten.DataContext).Header);
Assert.True(SliderActivity.GetTracks(straighten), "the Straighten slider is tracked");
Assert.False(sliders.Where(s => !ReferenceEquals(s, straighten)).Any(SliderActivity.GetTracks), "no other slider is");
Assert.False(step.Editor.IsStraightening);
straighten.SetCurrentValue(SliderActivity.IsActiveProperty, true);
Assert.True(step.Editor.IsStraightening, "focused or dragged: the editor shows the grid");
straighten.SetCurrentValue(SliderActivity.IsActiveProperty, false);
Assert.False(step.Editor.IsStraightening, "let go: the grid goes");
});
}
}
private static IEnumerable<T> Descendants<T>(DependencyObject root)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child is T match) yield return match;
foreach (var nested in Descendants<T>(child)) yield return nested;
}
}
/// <summary>The step's data context as the template reads it: <c>Editor.IsStraightening</c>.</summary>
public sealed class FakeStep
{
public FakeEditor Editor { get; } = new();
}
public sealed class FakeEditor
{
public bool IsStraightening { get; set; }
}
}