feat(editor): edit the crop box on the preview, locked to the output proportions

The Camera step now shows its crop box on the Source picture with its mask on
by default, and the box is moved and resized right there (owner review 1, R5).
A press takes a handle within 6 px, then the wipe divider, then the inside of
the box, then pans; a resize stays anchored at the opposite corner or edge and
locked to the ratio, Alt resizes about the centre. Esc cancels a drag, and once
the box is taken (a press on it or Enter) the arrows, + and - nudge it. Cursors
follow the same priority and screen readers read "x, y, size" from a read-only
value pattern.

Each finished drag goes through CropCommit to CommitCropCommand as one undo
step; a run of key presses merges into one ("Camera.Crop"). The commit writes
the locked box with the offsets at 0, so the render keeps it as drawn. Editing
is gated on the Camera step, the mask on, an editable project, a current
format and frames to show.

PreviewRenderer frames Source through ViewFor, so the turned, mirrored and
straightened view frame is what the box is drawn on; the mask comes from
EditableCrop on the Camera step and FootprintInView elsewhere, and the horizon
overlay is mapped into the view. A straighten grid shows while IsStraightening.
xaml-lint now requires a tooltip on PreviewViewport.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 20:24:10 +01:00
1 parent aaf9c0bba7
commit 6f15717463
13 files changed
+1298 -65

No files matched your search

@@ -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,126 @@ 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.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
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).
@@ -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;
@@ -183,6 +189,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 +340,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)
{
@@ -1,3 +1,4 @@
using Chronos.Core.Imaging.Geometry;
using Chronos.Testing;
using Chronos.Ui.Visuals;
@@ -69,4 +70,75 @@ public sealed class ViewportMathTests
Assert.Approximately(Math.Round(10.4 * 1.5), t.OffsetX * 1.5, 1e-9);
Assert.Approximately(Math.Round(-3.1 * 1.5), t.OffsetY * 1.5, 1e-9);
}
[Test]
public void ACropPressTakesAHandleWithinTheGripThenTheInsideAtEveryZoom()
{
// A 400×300 image with the box [0.25, 0.2, 0.5, 0.6]: the grip is 6 view units whatever the zoom.
var crop = new RectD(0.25, 0.2, 0.5, 0.6);
foreach (var view in new[] { new ViewTransform(0.25, 40, 10), new ViewTransform(1, -30, 5), new ViewTransform(4, -500, -300) })
{
CropHandle Hit(double nx, double ny, double dx, double dy)
{
var (x, y) = view.ToView(nx * 400, ny * 300);
return ViewportMath.HitCrop(view, 400, 300, crop, x + dx, y + dy, 6);
}
var zoom = $"scale {view.Scale}";
Assert.Equal(CropHandle.TopLeft, Hit(0.25, 0.2, -5, 4), zoom);
Assert.Equal(CropHandle.BottomRight, Hit(0.75, 0.8, 6, -6), zoom);
Assert.Equal(CropHandle.Top, Hit(0.5, 0.2, 3, -2), zoom);
Assert.Equal(CropHandle.Left, Hit(0.25, 0.5, 2, 0), zoom);
Assert.Equal(CropHandle.Inside, Hit(0.25, 0.5, 0, 7), "beside a handle, inside the box: a move");
Assert.Equal(CropHandle.None, Hit(0.25, 0.5, -7, 0), "outside the box and the grip: a pan");
Assert.Equal(CropHandle.Inside, Hit(0.5, 0.5, 0, 0), zoom);
Assert.Equal(CropHandle.None, Hit(0.1, 0.1, 0, 0), zoom);
}
Assert.Equal(CropHandle.None, ViewportMath.HitCrop(new ViewTransform(0, 0, 0), 400, 300, crop, 0, 0, 6), "no view yet");
}
[Test]
public void TheNearestHandleWinsOnATinyBox()
{
// At 1/4 zoom a box of 40×30 image pixels is 10×7.5 view units: every handle is within the grip of the centre.
var view = new ViewTransform(0.25, 0, 0);
var crop = new RectD(0.45, 0.45, 0.1, 0.1);
var (x, y) = view.ToView(0.55 * 400, 0.55 * 300);
Assert.Equal(CropHandle.BottomRight, ViewportMath.HitCrop(view, 400, 300, crop, x - 1, y - 1, 6));
var (cx, cy) = view.ToView(0.5 * 400, 0.45 * 300);
Assert.Equal(CropHandle.Top, ViewportMath.HitCrop(view, 400, 300, crop, cx, cy + 0.5, 6));
}
[Test]
public void TheHandlesSitOnTheCornersAndTheEdgeMidpoints()
{
var crop = new RectD(0.1, 0.2, 0.4, 0.6);
Assert.Count(8, ViewportMath.CropHandles);
Assert.Within(0.1, 0.2, ViewportMath.HandleAt(crop, CropHandle.TopLeft).X, ViewportMath.HandleAt(crop, CropHandle.TopLeft).Y, 1e-12);
Assert.Within(0.3, 0.8, ViewportMath.HandleAt(crop, CropHandle.Bottom).X, ViewportMath.HandleAt(crop, CropHandle.Bottom).Y, 1e-12);
Assert.Within(0.5, 0.5, ViewportMath.HandleAt(crop, CropHandle.Right).X, ViewportMath.HandleAt(crop, CropHandle.Right).Y, 1e-12);
Assert.Within(0.3, 0.5, ViewportMath.HandleAt(crop, CropHandle.Inside).X, ViewportMath.HandleAt(crop, CropHandle.Inside).Y, 1e-12);
}
[Test]
public void PlusAndMinusResizeAboutTheCentreLockedAndWithinTheLimits()
{
const double ratio = 0.5;
var largest = CropFrame.Largest(ratio);
var box = CropFrame.FromRows(0.5, 0, 0, ratio);
var grown = ViewportMath.ResizeCrop(box, 0.02, ratio);
Assert.Approximately(box.Height + 0.02 * largest.Height, grown.Height, 1e-12);
Assert.Approximately(ratio, grown.Width / grown.Height, 1e-12);
Assert.Within(box.CenterX, box.CenterY, grown.CenterX, grown.CenterY, 1e-12);
var smallest = CropFrame.FromRows(CropFrame.MinimumShare, 0, 0, ratio);
Assert.Approximately(smallest.Height, ViewportMath.ResizeCrop(smallest, -0.02, ratio).Height, 1e-12, "not below the minimum");
var whole = ViewportMath.ResizeCrop(largest, 0.02, ratio);
Assert.Approximately(largest.Height, whole.Height, 1e-12, "not beyond the largest box");
// At an edge the grown box moves back inside the view.
var corner = CropFrame.FromRows(0.9, 1, 1, ratio);
var pushed = ViewportMath.ResizeCrop(corner, 0.08, ratio);
Assert.LessOrEqual(pushed.Right, 1 + 1e-12);
Assert.LessOrEqual(pushed.Bottom, 1 + 1e-12);
}
}
@@ -278,6 +278,217 @@ public sealed class VisualsSmokeTests
}
});
[Test]
public void ACropDragMovesThenResizesLockedAndIsReportedOncePerDrag() => WpfHost.Run(() =>
{
var preview = CropPreview(new Rect(0.3, 0.2, 0.3, 0.6), ratio: 0.5);
Render(preview, 800, 450);
var edits = new List<CropEditEventArgs>();
preview.CropEditCompleted += (_, e) => edits.Add(e);
// Inside the box: a move; only the overlay follows the pointer until the button is released.
preview.Press(At(preview, 0.45, 0.5));
Assert.Equal(PreviewViewport.DragMode.MoveCrop, preview.Dragging);
preview.DragTo(At(preview, 0.55, 0.55), aboutCentre: false);
Assert.Empty(edits, "nothing is reported while dragging");
Assert.Approximately(0.4, preview.ShownCrop.X, 1e-6, "the overlay follows");
Assert.Approximately(0.3, preview.EditCrop.X, 0, "the box itself waits for the release");
preview.EndDrag(commit: true);
var moved = Assert.Contains(edits, _ => true).Crop;
Assert.Within(0.4, 0.25, moved.X, moved.Y, 1e-6);
Assert.False(edits[0].IsNudge);
Assert.Equal(moved, preview.EditCrop, "the finished box is the edited one");
// The bottom-right handle, dragged far outside: anchored at the top-left corner, locked, clamped to the view.
preview.Press(At(preview, 0.7, 0.85));
Assert.Equal(PreviewViewport.DragMode.ResizeCrop, preview.Dragging);
preview.DragTo(At(preview, 1.5, 1.5), aboutCentre: false);
preview.EndDrag(commit: true);
Assert.Count(2, edits);
var resized = edits[1].Crop;
Assert.Within(0.4, 0.25, resized.X, resized.Y, 1e-9, "anchored at the opposite corner");
Assert.Approximately(0.5, resized.Width / resized.Height, 1e-9, "the ratio stays locked");
Assert.Approximately(1, resized.Bottom, 1e-9, "as large as the view lets it be");
Assert.LessOrEqual(resized.Right, 1);
// Alt resizes about the centre.
preview.Press(At(preview, resized.Right, resized.Bottom));
preview.DragTo(At(preview, resized.Right - 0.05, resized.Bottom - 0.1), aboutCentre: true);
preview.EndDrag(commit: true);
var centred = edits[2].Crop;
Assert.Within(resized.X + resized.Width / 2, resized.Y + resized.Height / 2, centred.X + centred.Width / 2, centred.Y + centred.Height / 2, 1e-9);
Assert.Approximately(0.5, centred.Width / centred.Height, 1e-9);
// A press released where it started, and a pan outside the box, report nothing.
preview.Press(At(preview, centred.X + centred.Width / 2, centred.Y + centred.Height / 2));
preview.EndDrag(commit: true);
preview.Press(At(preview, 0.05, 0.05));
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging);
preview.DragTo(At(preview, 0.1, 0.1), aboutCentre: false);
preview.EndDrag(commit: true);
Assert.Count(3, edits);
});
[Test]
public void APressTakesAHandleThenTheDividerThenTheBoxThenPansAtEveryZoom() => WpfHost.Run(() =>
{
var preview = CropPreview(new Rect(0.4, 0.4, 0.2, 0.2), ratio: 1);
preview.OriginalSource = Bitmap(2000, 1500);
preview.IsCompareEnabled = true;
preview.WipePosition = 0.5;
Render(preview, 800, 450);
var surface = Assert.NotNull(FindChild<PreviewSurface>(preview));
foreach (var zoom in new double?[] { null, 1, 2 })
{
if (zoom is { } z) preview.Zoom = z;
var label = zoom is null ? "fit" : $"zoom {zoom}";
// The image column under the divider, and a box of 0.06 × 0.12 around it (corner handles well away).
var divider = surface.ActualWidth / 2;
var nx = preview.View.ToImage(divider, 0).X / 2000;
var y = At(preview, 0, 0.5).Y;
PreviewViewport.DragMode Take(Rect box, double x)
{
preview.EditCrop = box;
preview.Press(new Point(x, y));
var mode = preview.Dragging;
preview.EndDrag(commit: false);
return mode;
}
Assert.Equal(PreviewViewport.DragMode.ResizeCrop, Take(new Rect(nx, 0.44, 0.06, 0.12), divider), $"{label}: a handle on the divider");
Assert.Equal(PreviewViewport.DragMode.Wipe, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), divider), $"{label}: the divider inside the box");
Assert.Equal(PreviewViewport.DragMode.MoveCrop, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), At(preview, nx + 0.012, 0.5).X), $"{label}: inside");
Assert.Equal(PreviewViewport.DragMode.Pan, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), At(preview, nx + 0.06, 0.5).X), $"{label}: outside");
}
// Not editable: no handle and no box to take, the divider and pan only.
preview.CropEditable = false;
preview.EditCrop = new Rect(0.4, 0.4, 0.2, 0.2);
preview.Press(At(preview, 0.4, 0.4));
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging);
preview.EndDrag(commit: false);
});
[Test]
public void EscCancelsADragAndTheKeysNudgeTheBoxOnceItIsTaken() => WpfHost.Run(() =>
{
var preview = CropPreview(new Rect(0.3, 0.2, 0.3, 0.6), ratio: 0.5);
var window = OffScreen(preview, 800, 450);
try
{
var edits = new List<CropEditEventArgs>();
preview.CropEditCompleted += (_, e) => edits.Add(e);
Assert.False(Press(preview, Key.Right), "until the box is taken, the arrows step frames");
// Esc cancels a drag: the box stays, nothing is reported.
preview.Press(At(preview, 0.45, 0.5));
preview.DragTo(At(preview, 0.6, 0.6), aboutCentre: false);
Assert.True(Press(preview, Key.Escape));
Assert.Equal(PreviewViewport.DragMode.None, preview.Dragging);
Assert.Equal(new Rect(0.3, 0.2, 0.3, 0.6), preview.EditCrop);
Assert.Equal(new Rect(0.3, 0.2, 0.3, 0.6), preview.ShownCrop);
Assert.Empty(edits);
// The press took the box: the arrows move it 1 %, + and − resize it about its centre, each reported as a nudge.
Assert.True(preview.IsCropSelected);
Assert.True(Press(preview, Key.Right));
Assert.Count(1, edits);
Assert.True(edits[0].IsNudge);
Assert.Approximately(0.31, preview.EditCrop.X, 1e-9);
Assert.True(preview.Nudge(Key.Down, ModifierKeys.Shift), "Shift moves 10 %");
Assert.Approximately(0.3, preview.EditCrop.Y, 1e-9);
var before = preview.EditCrop;
Assert.True(Press(preview, Key.OemMinus));
var shrunk = preview.EditCrop;
Assert.Less(shrunk.Height, before.Height);
Assert.Approximately(0.5, shrunk.Width / shrunk.Height, 1e-9);
Assert.Within(before.X + before.Width / 2, before.Y + before.Height / 2, shrunk.X + shrunk.Width / 2, shrunk.Y + shrunk.Height / 2, 1e-9);
Assert.Count(3, edits);
// Esc gives the arrows back; Enter takes the box from the keyboard.
Assert.True(Press(preview, Key.Escape));
Assert.False(preview.IsCropSelected);
Assert.False(Press(preview, Key.Left));
Assert.True(Press(preview, Key.Enter));
Assert.True(Press(preview, Key.Left));
Assert.Count(4, edits);
// A box that can no longer change gives the keys back.
preview.CropEditable = false;
Assert.False(preview.IsCropSelected);
Assert.False(Press(preview, Key.Right));
}
finally
{
window.Close();
}
});
[Test]
public void TheEditableBoxDrawsItsHandlesAndScreenReadersReadIt() => WpfHost.Run(() =>
{
var card = ColorOf("Brush.Card");
var preview = CropPreview(new Rect(0.25, 0.2, 0.5, 0.6), ratio: 0.5 / 0.6);
Render(preview, 800, 450);
var surface = Assert.NotNull(FindChild<PreviewSurface>(preview));
Color HandlePixel(double nx, double ny)
{
var bitmap = Render(preview, 800, 450);
var (x, y) = preview.View.ToView(nx * 2000, ny * 1500);
var p = surface.TranslatePoint(new Point(x, y), preview);
return PixelAt(bitmap, (int)Math.Round(p.X), (int)Math.Round(p.Y));
}
foreach (var (nx, ny) in new[] { (0.25, 0.2), (0.75, 0.8), (0.5, 0.2), (0.75, 0.5) })
Assert.True(Near(HandlePixel(nx, ny), card, 8), $"a Card handle at ({nx}, {ny})");
preview.CropMaskMode = CropMaskMode.ShowResult;
Assert.True(Near(HandlePixel(0.25, 0.8), card, 8), "the handles draw in either mask mode");
var peer = UIElementAutomationPeer.CreatePeerForElement(preview);
var value = Assert.NotNull(peer.GetPattern(PatternInterface.Value) as System.Windows.Automation.Provider.IValueProvider);
Assert.Equal(Loc.L("Editor.Preview.CropValue", Loc.L("Common.Percent", 25), Loc.L("Common.Percent", 20), Loc.L("Common.Percent", 60)), value.Value);
Assert.True(value.IsReadOnly);
preview.CropMaskMode = CropMaskMode.ShowLoss;
preview.CropEditable = false;
Assert.False(Near(HandlePixel(0.25, 0.2), card, 8), "no handles while the box cannot change");
Assert.Null(peer.GetPattern(PatternInterface.Value), "and no value to read");
});
private static PreviewViewport CropPreview(Rect crop, double ratio) => new()
{
Source = Bitmap(2000, 1500),
ShowCropMask = true,
CropEditable = true,
CropLockRatio = ratio,
EditCrop = crop,
};
/// <summary>The surface point of the normalised image point (<paramref name="nx"/>, <paramref name="ny"/>) of a 2000 × 1500 preview.</summary>
private static Point At(PreviewViewport preview, double nx, double ny)
{
var (x, y) = preview.View.ToView(nx * 2000, ny * 1500);
return new Point(x, y);
}
/// <summary>A window off screen around <paramref name="element"/>, so it has a presentation source for key events.</summary>
private static Window OffScreen(FrameworkElement element, double width, double height)
{
var window = new Window
{
Content = new Border { Child = element },
Width = width,
Height = height,
WindowStyle = WindowStyle.None,
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
window.UpdateLayout();
return window;
}
private static IEnumerable<(string Name, FrameworkElement Element, double Width, double Height)> Samples()
{
var n = 120_000;
@@ -342,6 +553,15 @@ public sealed class VisualsSmokeTests
ShowCropMask = true,
CropRect = new Rect(0.1, 0.1, 0.8, 0.8),
}, 800, 450);
yield return ("PreviewViewport.CropEdit", new PreviewViewport
{
Source = Bitmap(2000, 1500),
ShowCropMask = true,
CropEditable = true,
CropLockRatio = 0.5,
EditCrop = new Rect(0.3, 0.2, 0.3, 0.6),
ShowGrid = true,
}, 800, 450);
yield return ("SequenceCard", SampleCard(), 236, 208);
yield return ("SegmentedControl", SampleSegments(), 120, 32);
@@ -438,8 +658,13 @@ public sealed class VisualsSmokeTests
return false;
}
private static void Press(UIElement target, Key key) =>
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent });
/// <summary>Raises a key press on <paramref name="target"/>; true when something handled it.</summary>
private static bool Press(UIElement target, Key key)
{
var args = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent };
target.RaiseEvent(args);
return args.Handled;
}
private static RenderTargetBitmap Render(FrameworkElement element, double width, double height)
{