diff --git a/src/Titano.Ui/Visuals/PreviewSurface.cs b/src/Titano.Ui/Visuals/PreviewSurface.cs
new file mode 100644
index 00000000..245a2b99
--- /dev/null
+++ b/src/Titano.Ui/Visuals/PreviewSurface.cs
@@ -0,0 +1,195 @@
+using System.Windows;
+using System.Windows.Media;
+
+namespace Titano.Ui.Visuals;
+
+///
+/// Drawing surface of (its PART_Surface). The corrected image, the original
+/// (clipped left of the wipe) and the overlays are retained visuals in image coordinates sharing one
+/// , so panning and zooming only update a matrix; overlays are rebuilt when the zoom
+/// changes (to keep strokes and arrowheads a constant on-screen size) or their data changes. The wipe divider
+/// and its label live in a screen-space layer on top.
+///
+public sealed class PreviewSurface : DrawingElement
+{
+ public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
+ nameof(CornerRadius), typeof(double), typeof(PreviewSurface), new PropertyMetadata(8.0, (d, _) => ((PreviewSurface)d).UpdateClip()));
+
+ private const double LabelSize = 11;
+
+ private readonly VisualCollection _layers;
+ private readonly DrawingVisual _corrected = new();
+ private readonly DrawingVisual _original = new();
+ private readonly ContainerVisual _originalHost = new();
+ private readonly DrawingVisual _overlay = new();
+ private readonly DrawingVisual _chrome = new();
+ private readonly MatrixTransform _view = new();
+ private readonly RectangleGeometry _wipeClip = new();
+ private Size _imageSize = Size.Empty;
+ private double _overlayScale;
+ private double _zoom;
+
+ public PreviewSurface()
+ {
+ _corrected.Transform = _view;
+ _original.Transform = _view;
+ _overlay.Transform = _view;
+ _originalHost.Clip = _wipeClip;
+ _originalHost.Children.Add(_original);
+ _layers = new VisualCollection(this) { _corrected, _originalHost, _overlay, _chrome };
+ }
+
+ /// Radius of the rounded clip of the whole surface.
+ public double CornerRadius { get => (double)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); }
+
+ /// Viewport whose properties drive the layers.
+ internal PreviewViewport? Owner { get; set; }
+
+ protected override int VisualChildrenCount => _layers.Count;
+
+ protected override Visual GetVisualChild(int index) => _layers[index];
+
+ /// Redraws both images over the image rectangle [0, size].
+ internal void SetImages(ImageSource? corrected, ImageSource? original, Size imageSize)
+ {
+ _imageSize = imageSize;
+ var rect = imageSize.IsEmpty ? Rect.Empty : new Rect(imageSize);
+ using (var dc = _corrected.RenderOpen())
+ if (corrected is not null && !rect.IsEmpty) dc.DrawImage(corrected, rect);
+ using (var dc = _original.RenderOpen())
+ if (original is not null && !rect.IsEmpty) dc.DrawImage(original, rect);
+ RefreshOverlay();
+ RefreshChrome();
+ }
+
+ /// Applies the image-to-view transform; is device pixels per image pixel.
+ internal void SetView(ViewTransform view, double zoom)
+ {
+ _view.Matrix = new Matrix(view.Scale, 0, 0, view.Scale, view.OffsetX, view.OffsetY);
+ if (zoom != _zoom)
+ {
+ _zoom = zoom;
+ // Raw pixels from 1:1 up; filtered when shrinking.
+ var mode = zoom >= 1 ? BitmapScalingMode.NearestNeighbor : BitmapScalingMode.HighQuality;
+ RenderOptions.SetBitmapScalingMode(_corrected, mode);
+ RenderOptions.SetBitmapScalingMode(_original, mode);
+ }
+ if (view.Scale != _overlayScale) RefreshOverlay();
+ UpdateWipeClip();
+ }
+
+ /// Rebuilds the overlays (crop mask, region boundary, motion vectors) in image coordinates.
+ internal void RefreshOverlay()
+ {
+ _overlayScale = _view.Matrix.M11;
+ using var dc = _overlay.RenderOpen();
+ if (Owner is not { } owner || _imageSize.IsEmpty || !(_overlayScale > 0)) return;
+ var unit = 1 / _overlayScale;
+ if (owner.ShowCropMask) DrawCropMask(dc, owner, unit);
+ if (owner.ShowRegions && owner.RegionBoundary is { Count: > 1 } boundary) DrawRegion(dc, boundary, unit);
+ if (owner.ShowVectors && owner.MotionVectors is { Count: > 0 } vectors) DrawVectors(dc, vectors, owner.VectorScale, unit);
+ }
+
+ /// Redraws the wipe divider and label.
+ internal void RefreshChrome()
+ {
+ UpdateWipeClip();
+ using var dc = _chrome.RenderOpen();
+ if (Owner is not { } owner || !IsWipeVisible(owner)) return;
+ var scale = PixelScale;
+ var x = PixelGrid.Snap(owner.WipePosition * ActualWidth, scale);
+ dc.DrawRectangle(GetBrush("Brush.Text"), null, new Rect(x - 1, 0, 2, ActualHeight));
+ if (string.IsNullOrEmpty(owner.WipeLabel)) return;
+ var label = CreateText(owner.WipeLabel, LabelSize, GetBrush("Brush.Text"));
+ var pill = new Rect(x - label.Width / 2 - 8, 12, label.Width + 16, label.Height + 6);
+ pill.X = Math.Clamp(pill.X, 4, Math.Max(4, ActualWidth - pill.Width - 4));
+ dc.PushOpacity(0.85);
+ dc.DrawRoundedRectangle(GetBrush("Brush.Chrome"), null, pill, 4, 4);
+ dc.Pop();
+ dc.DrawText(label, new Point(pill.X + 8, pill.Y + 3));
+ }
+
+ protected override void OnRender(DrawingContext dc) => DrawHitArea(dc);
+
+ protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
+ {
+ base.OnRenderSizeChanged(sizeInfo);
+ UpdateClip();
+ RefreshChrome();
+ }
+
+ protected override void OnThemeChanged()
+ {
+ base.OnThemeChanged();
+ RefreshOverlay();
+ RefreshChrome();
+ }
+
+ private static bool IsWipeVisible(PreviewViewport owner) => owner.IsCompareEnabled && owner.OriginalSource is not null;
+
+ private void UpdateClip() => Clip = new RectangleGeometry(new Rect(RenderSize), CornerRadius, CornerRadius);
+
+ private void UpdateWipeClip()
+ {
+ var visible = Owner is { } owner && IsWipeVisible(owner);
+ _wipeClip.Rect = visible ? new Rect(0, 0, Math.Max(0, Owner!.WipePosition * ActualWidth), Math.Max(0, ActualHeight)) : Rect.Empty;
+ }
+
+ /// Everything outside the crop: dimmed with the scrim ("what I lose") or hidden ("how it will look").
+ private void DrawCropMask(DrawingContext dc, PreviewViewport owner, double unit)
+ {
+ var image = new Rect(_imageSize);
+ var n = owner.CropRect;
+ var crop = Rect.Intersect(image, new Rect(n.X * image.Width, n.Y * image.Height, n.Width * image.Width, n.Height * image.Height));
+ if (crop.IsEmpty) crop = new Rect(image.TopLeft, new Size(0, 0));
+ var outside = new CombinedGeometry(GeometryCombineMode.Exclude, new RectangleGeometry(image), new RectangleGeometry(crop));
+ outside.Freeze();
+ var loss = owner.CropMaskMode == CropMaskMode.ShowLoss;
+ dc.DrawGeometry(loss ? GetBrush("Brush.Scrim") : owner.Background ?? GetBrush("Brush.Preview"), null, outside);
+ if (loss && !crop.IsEmpty) dc.DrawRectangle(null, CreatePen("Brush.TextMuted", unit), crop);
+ }
+
+ private void DrawRegion(DrawingContext dc, IReadOnlyList boundary, double unit)
+ {
+ var geometry = new StreamGeometry();
+ using (var ctx = geometry.Open())
+ {
+ ctx.BeginFigure(boundary[0], false, false);
+ for (var i = 1; i < boundary.Count; i++) ctx.LineTo(boundary[i], true, true);
+ }
+ geometry.Freeze();
+ dc.DrawGeometry(null, CreatePen("Brush.Region", 1.5 * unit), geometry);
+ }
+
+ /// Arrows from each sample along its (scaled) displacement; heads stay 5 px on screen.
+ private void DrawVectors(DrawingContext dc, IReadOnlyList vectors, double gain, double unit)
+ {
+ var head = 5 * unit;
+ var geometry = new StreamGeometry();
+ using (var ctx = geometry.Open())
+ {
+ for (var i = 0; i < vectors.Count; i++)
+ {
+ var v = vectors[i];
+ var dx = v.Dx * gain;
+ var dy = v.Dy * gain;
+ var length = Math.Sqrt(dx * dx + dy * dy);
+ if (!(length >= unit)) continue;
+ var start = new Point(v.X, v.Y);
+ var end = new Point(v.X + dx, v.Y + dy);
+ ctx.BeginFigure(start, false, false);
+ ctx.LineTo(end, true, false);
+ // Arrowhead: two strokes at ±25° from the reversed direction.
+ var ux = dx / length;
+ var uy = dy / length;
+ const double cos = 0.906, sin = 0.423;
+ var h = Math.Min(head, length * 0.6);
+ ctx.BeginFigure(new Point(end.X - h * (ux * cos - uy * sin), end.Y - h * (uy * cos + ux * sin)), false, false);
+ ctx.LineTo(end, true, true);
+ ctx.LineTo(new Point(end.X - h * (ux * cos + uy * sin), end.Y - h * (uy * cos - ux * sin)), true, true);
+ }
+ }
+ geometry.Freeze();
+ dc.DrawGeometry(null, CreatePen("Brush.Accent", 1.25 * unit), geometry);
+ }
+}
diff --git a/src/Titano.Ui/Visuals/PreviewViewport.cs b/src/Titano.Ui/Visuals/PreviewViewport.cs
new file mode 100644
index 00000000..bcfc5bb3
--- /dev/null
+++ b/src/Titano.Ui/Visuals/PreviewViewport.cs
@@ -0,0 +1,385 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+
+namespace Titano.Ui.Visuals;
+
+/// How the preview scales the image.
+public enum PreviewZoomMode
+{
+ /// The whole image fits the view, centred; follows resizes.
+ Fit,
+
+ /// One image pixel per device pixel (raw pixels, no interpolation).
+ Actual,
+
+ /// Set by the wheel or by .
+ Custom,
+}
+
+/// What the crop mask shows outside the crop rectangle.
+public enum CropMaskMode
+{
+ /// "What I lose": the outside is dimmed with the scrim.
+ ShowLoss,
+
+ /// "How it will look": the outside is hidden.
+ ShowResult,
+}
+
+/// A motion-field sample in image pixels: origin (X, Y) and displacement (Dx, Dy).
+public readonly record struct MotionVector(float X, float Y, float Dx, float Dy);
+
+///
+/// Editor preview (BRIEF §12.3): the corrected image with an optional original shown left of a draggable wipe
+/// divider (label from ), zoom to fit / 1:1 (raw pixels) / wheel zoom around the cursor,
+/// pan by dragging, and overlays in image coordinates: motion vectors (Accent arrows), region boundary (Region
+/// polyline) and a crop mask (normalised ; dims or hides what the output loses). Tools go
+/// bottom-left (), the shot data pill bottom-right (). Images and
+/// overlays are retained visuals under one shared transform, so panning re-renders nothing. Double-click toggles
+/// Fit and 1:1; Ctrl+0 fits, Ctrl+1 shows 1:1.
+///
+[TemplatePart(Name = PartSurface, Type = typeof(FrameworkElement))]
+public class PreviewViewport : Control
+{
+ public const string PartSurface = "PART_Surface";
+
+ public static readonly RoutedCommand FitCommand = new(nameof(FitCommand), typeof(PreviewViewport), [new KeyGesture(Key.D0, ModifierKeys.Control)]);
+ public static readonly RoutedCommand ActualSizeCommand = new(nameof(ActualSizeCommand), typeof(PreviewViewport), [new KeyGesture(Key.D1, ModifierKeys.Control)]);
+
+ public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
+ nameof(Source), typeof(ImageSource), typeof(PreviewViewport), new PropertyMetadata(null, OnImagesChanged));
+
+ public static readonly DependencyProperty OriginalSourceProperty = DependencyProperty.Register(
+ nameof(OriginalSource), typeof(ImageSource), typeof(PreviewViewport), new PropertyMetadata(null, OnImagesChanged));
+
+ public static readonly DependencyProperty IsCompareEnabledProperty = DependencyProperty.Register(
+ nameof(IsCompareEnabled), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnChromeChanged));
+
+ public static readonly DependencyProperty WipePositionProperty = DependencyProperty.Register(
+ nameof(WipePosition), typeof(double), typeof(PreviewViewport),
+ new FrameworkPropertyMetadata(0.5, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnChromeChanged, CoerceUnit));
+
+ public static readonly DependencyProperty WipeLabelProperty = DependencyProperty.Register(
+ nameof(WipeLabel), typeof(string), typeof(PreviewViewport), new PropertyMetadata(null, OnChromeChanged));
+
+ public static readonly DependencyProperty ZoomModeProperty = DependencyProperty.Register(
+ nameof(ZoomMode), typeof(PreviewZoomMode), typeof(PreviewViewport),
+ new FrameworkPropertyMetadata(PreviewZoomMode.Fit, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnZoomModeChanged));
+
+ public static readonly DependencyProperty ZoomProperty = DependencyProperty.Register(
+ nameof(Zoom), typeof(double), typeof(PreviewViewport),
+ new FrameworkPropertyMetadata(1.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnZoomChanged, CoerceZoom));
+
+ public static readonly DependencyProperty ShowVectorsProperty = DependencyProperty.Register(
+ nameof(ShowVectors), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnOverlayChanged));
+
+ public static readonly DependencyProperty MotionVectorsProperty = DependencyProperty.Register(
+ nameof(MotionVectors), typeof(IReadOnlyList), typeof(PreviewViewport), new PropertyMetadata(null, OnOverlayChanged));
+
+ public static readonly DependencyProperty VectorScaleProperty = DependencyProperty.Register(
+ nameof(VectorScale), typeof(double), typeof(PreviewViewport), new PropertyMetadata(1.0, OnOverlayChanged));
+
+ public static readonly DependencyProperty ShowRegionsProperty = DependencyProperty.Register(
+ nameof(ShowRegions), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnOverlayChanged));
+
+ public static readonly DependencyProperty RegionBoundaryProperty = DependencyProperty.Register(
+ nameof(RegionBoundary), typeof(IReadOnlyList), typeof(PreviewViewport), new PropertyMetadata(null, OnOverlayChanged));
+
+ public static readonly DependencyProperty ShowCropMaskProperty = DependencyProperty.Register(
+ nameof(ShowCropMask), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnOverlayChanged));
+
+ public static readonly DependencyProperty CropRectProperty = DependencyProperty.Register(
+ nameof(CropRect), typeof(Rect), typeof(PreviewViewport), new PropertyMetadata(new Rect(0, 0, 1, 1), OnOverlayChanged));
+
+ public static readonly DependencyProperty CropMaskModeProperty = DependencyProperty.Register(
+ nameof(CropMaskMode), typeof(CropMaskMode), typeof(PreviewViewport), new PropertyMetadata(CropMaskMode.ShowLoss, OnOverlayChanged));
+
+ public static readonly DependencyProperty InfoTextProperty = DependencyProperty.Register(nameof(InfoText), typeof(string), typeof(PreviewViewport));
+
+ public static readonly DependencyProperty ToolsContentProperty = DependencyProperty.Register(nameof(ToolsContent), typeof(object), typeof(PreviewViewport));
+
+ private const double MinZoom = 0.01;
+ private const double MaxZoom = 32;
+ private const double DividerGrip = 6;
+
+ private PreviewSurface? _surface;
+ private ViewTransform _view = new(1, 0, 0);
+ private Size _imageSize = Size.Empty;
+ private bool _syncingZoom;
+ private DragMode _drag;
+ private Point _dragStart;
+ private ViewTransform _dragOrigin;
+
+ static PreviewViewport()
+ {
+ DefaultStyleKeyProperty.OverrideMetadata(typeof(PreviewViewport), new FrameworkPropertyMetadata(typeof(PreviewViewport)));
+ FocusableProperty.OverrideMetadata(typeof(PreviewViewport), new FrameworkPropertyMetadata(true));
+ }
+
+ public PreviewViewport()
+ {
+ CommandBindings.Add(new CommandBinding(FitCommand, (_, _) => SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Fit)));
+ CommandBindings.Add(new CommandBinding(ActualSizeCommand, (_, _) => SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Actual)));
+ }
+
+ private enum DragMode
+ {
+ None,
+ Pan,
+ Wipe,
+ }
+
+ /// Corrected image (the output look).
+ public ImageSource? Source { get => (ImageSource?)GetValue(SourceProperty); set => SetValue(SourceProperty, value); }
+
+ /// Original image for the wipe compare; drawn over the same area as .
+ public ImageSource? OriginalSource { get => (ImageSource?)GetValue(OriginalSourceProperty); set => SetValue(OriginalSourceProperty, value); }
+
+ /// Shows the original left of the wipe divider.
+ public bool IsCompareEnabled { get => (bool)GetValue(IsCompareEnabledProperty); set => SetValue(IsCompareEnabledProperty, value); }
+
+ /// Divider position as a fraction of the view width (two-way).
+ public double WipePosition { get => (double)GetValue(WipePositionProperty); set => SetValue(WipePositionProperty, value); }
+
+ /// Label centred on the divider ("original | corrected").
+ public string? WipeLabel { get => (string?)GetValue(WipeLabelProperty); set => SetValue(WipeLabelProperty, value); }
+
+ public PreviewZoomMode ZoomMode { get => (PreviewZoomMode)GetValue(ZoomModeProperty); set => SetValue(ZoomModeProperty, value); }
+
+ /// Device pixels per image pixel (1 = 1:1). Setting it switches to .
+ public double Zoom { get => (double)GetValue(ZoomProperty); set => SetValue(ZoomProperty, value); }
+
+ public bool ShowVectors { get => (bool)GetValue(ShowVectorsProperty); set => SetValue(ShowVectorsProperty, value); }
+
+ /// Motion field in image pixels.
+ public IReadOnlyList? MotionVectors { get => (IReadOnlyList?)GetValue(MotionVectorsProperty); set => SetValue(MotionVectorsProperty, value); }
+
+ /// Gain applied to vector lengths so sub-pixel motion stays visible.
+ public double VectorScale { get => (double)GetValue(VectorScaleProperty); set => SetValue(VectorScaleProperty, value); }
+
+ public bool ShowRegions { get => (bool)GetValue(ShowRegionsProperty); set => SetValue(ShowRegionsProperty, value); }
+
+ /// Sky/landscape boundary as a polyline in image pixels.
+ public IReadOnlyList? RegionBoundary { get => (IReadOnlyList?)GetValue(RegionBoundaryProperty); set => SetValue(RegionBoundaryProperty, value); }
+
+ public bool ShowCropMask { get => (bool)GetValue(ShowCropMaskProperty); set => SetValue(ShowCropMaskProperty, value); }
+
+ /// Output crop in normalised image coordinates (0…1).
+ public Rect CropRect { get => (Rect)GetValue(CropRectProperty); set => SetValue(CropRectProperty, value); }
+
+ public CropMaskMode CropMaskMode { get => (CropMaskMode)GetValue(CropMaskModeProperty); set => SetValue(CropMaskModeProperty, value); }
+
+ /// Shot data shown in the bottom-right pill.
+ public string? InfoText { get => (string?)GetValue(InfoTextProperty); set => SetValue(InfoTextProperty, value); }
+
+ /// Tool buttons shown bottom-left over the image.
+ public object? ToolsContent { get => GetValue(ToolsContentProperty); set => SetValue(ToolsContentProperty, value); }
+
+ /// Current image-to-view transform in DIPs (for hit testing overlays from outside).
+ public ViewTransform View => _view;
+
+ /// Size of in image pixels.
+ public Size ImageSize => _imageSize;
+
+ private Size ViewSize => _surface?.RenderSize ?? Size.Empty;
+
+ private double PixelScale => VisualTreeHelper.GetDpi(this).DpiScaleX;
+
+ public override void OnApplyTemplate()
+ {
+ if (_surface is not null) _surface.SizeChanged -= OnSurfaceSizeChanged;
+ base.OnApplyTemplate();
+ _surface = GetTemplateChild(PartSurface) as PreviewSurface;
+ if (_surface is null) return;
+ _surface.Owner = this;
+ _surface.SizeChanged += OnSurfaceSizeChanged;
+ _surface.SetImages(Source, OriginalSource, _imageSize);
+ ApplyZoomMode();
+ }
+
+ protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
+ {
+ base.OnMouseLeftButtonDown(e);
+ if (e.Handled || _surface is null) return;
+ Focus();
+ var p = e.GetPosition(_surface);
+ if (e.ClickCount == 2)
+ {
+ ToggleZoom(p);
+ e.Handled = true;
+ return;
+ }
+ _drag = IsNearDivider(p) ? DragMode.Wipe : DragMode.Pan;
+ _dragStart = p;
+ _dragOrigin = _view;
+ if (!CaptureMouse()) _drag = DragMode.None;
+ e.Handled = true;
+ }
+
+ protected override void OnMouseMove(MouseEventArgs e)
+ {
+ base.OnMouseMove(e);
+ if (_drag == DragMode.None || _surface is null) return;
+ var p = e.GetPosition(_surface);
+ if (_drag == DragMode.Wipe)
+ {
+ var width = ViewSize.Width;
+ if (width > 0) SetCurrentValue(WipePositionProperty, p.X / width);
+ return;
+ }
+ UpdateView(ViewportMath.Clamp(ViewportMath.Pan(_dragOrigin, p.X - _dragStart.X, p.Y - _dragStart.Y),
+ _imageSize.Width, _imageSize.Height, ViewSize.Width, ViewSize.Height));
+ }
+
+ protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
+ {
+ base.OnMouseLeftButtonUp(e);
+ if (_drag != DragMode.None) ReleaseMouseCapture();
+ }
+
+ protected override void OnLostMouseCapture(MouseEventArgs e)
+ {
+ base.OnLostMouseCapture(e);
+ _drag = DragMode.None;
+ }
+
+ protected override void OnMouseWheel(MouseWheelEventArgs e)
+ {
+ base.OnMouseWheel(e);
+ if (e.Handled || _surface is null || _imageSize.IsEmpty) return;
+ var p = e.GetPosition(_surface);
+ var dpi = PixelScale;
+ var scale = ViewportMath.WheelZoom(_view.Scale, e.Delta / (double)Mouse.MouseWheelDeltaForOneLine, MinZoom / dpi, MaxZoom / dpi);
+ SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Custom);
+ UpdateView(ViewportMath.Clamp(ViewportMath.ZoomAt(_view, scale, p.X, p.Y), _imageSize.Width, _imageSize.Height, ViewSize.Width, ViewSize.Height));
+ e.Handled = true;
+ }
+
+ protected override void OnQueryCursor(QueryCursorEventArgs e)
+ {
+ base.OnQueryCursor(e);
+ if (e.Handled || _surface is null || !ReferenceEquals(e.OriginalSource, _surface)) return;
+ var p = e.GetPosition(_surface);
+ if (_drag == DragMode.Wipe || IsNearDivider(p)) e.Cursor = Cursors.SizeWE;
+ else if (IsPannable()) e.Cursor = Cursors.SizeAll;
+ else return;
+ e.Handled = true;
+ }
+
+ protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi)
+ {
+ base.OnDpiChanged(oldDpi, newDpi);
+ ApplyZoomMode();
+ }
+
+ private static object CoerceUnit(DependencyObject d, object value) => double.IsNaN((double)value) ? 0.5 : Math.Clamp((double)value, 0, 1);
+
+ private static object CoerceZoom(DependencyObject d, object value) =>
+ double.IsFinite((double)value) ? Math.Clamp((double)value, MinZoom, MaxZoom) : 1.0;
+
+ private static void OnImagesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ var viewport = (PreviewViewport)d;
+ var size = PixelSize(viewport.Source);
+ var resized = size != viewport._imageSize;
+ viewport._imageSize = size;
+ viewport._surface?.SetImages(viewport.Source, viewport.OriginalSource, size);
+ // Same-size frames (scrubbing) keep zoom and pan; a new size refits or re-clamps.
+ if (resized) viewport.ApplyZoomMode();
+ }
+
+ private static void OnChromeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PreviewViewport)d)._surface?.RefreshChrome();
+
+ private static void OnOverlayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PreviewViewport)d)._surface?.RefreshOverlay();
+
+ private static void OnZoomModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PreviewViewport)d).ApplyZoomMode();
+
+ private static void OnZoomChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ var viewport = (PreviewViewport)d;
+ if (viewport._syncingZoom || viewport._imageSize.IsEmpty) return;
+ viewport.SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Custom);
+ var size = viewport.ViewSize;
+ var scale = (double)e.NewValue / viewport.PixelScale;
+ viewport.UpdateView(ViewportMath.Clamp(ViewportMath.ZoomAt(viewport._view, scale, size.Width / 2, size.Height / 2),
+ viewport._imageSize.Width, viewport._imageSize.Height, size.Width, size.Height));
+ }
+
+ private static Size PixelSize(ImageSource? source) => source switch
+ {
+ null => Size.Empty,
+ BitmapSource bitmap => new Size(bitmap.PixelWidth, bitmap.PixelHeight),
+ _ => new Size(source.Width, source.Height),
+ };
+
+ private void OnSurfaceSizeChanged(object sender, SizeChangedEventArgs e)
+ {
+ ApplyZoomMode();
+ _surface?.RefreshChrome();
+ }
+
+ private void ApplyZoomMode()
+ {
+ var view = ViewSize;
+ if (_surface is null || _imageSize.IsEmpty || view.Width <= 0 || view.Height <= 0) return;
+ var (w, h) = (_imageSize.Width, _imageSize.Height);
+ switch (ZoomMode)
+ {
+ case PreviewZoomMode.Fit:
+ UpdateView(ViewportMath.Centered(ViewportMath.FitScale(w, h, view.Width, view.Height), w, h, view.Width, view.Height));
+ break;
+ case PreviewZoomMode.Actual:
+ var actual = 1 / PixelScale;
+ var start = _view.Scale > 0 ? _view : ViewportMath.Centered(actual, w, h, view.Width, view.Height);
+ UpdateView(ViewportMath.Clamp(ViewportMath.ZoomAt(start, actual, view.Width / 2, view.Height / 2), w, h, view.Width, view.Height));
+ break;
+ default:
+ UpdateView(ViewportMath.Clamp(_view, w, h, view.Width, view.Height));
+ break;
+ }
+ }
+
+ private void ToggleZoom(Point at)
+ {
+ if (_imageSize.IsEmpty) return;
+ if (ZoomMode == PreviewZoomMode.Actual)
+ {
+ SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Fit);
+ return;
+ }
+ // 1:1 centred on the double-clicked point.
+ var view = ViewSize;
+ var zoomed = ViewportMath.ZoomAt(_view, 1 / PixelScale, at.X, at.Y);
+ _view = ViewportMath.Pan(zoomed, view.Width / 2 - at.X, view.Height / 2 - at.Y);
+ SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Actual);
+ }
+
+ private void UpdateView(ViewTransform view)
+ {
+ var dpi = PixelScale;
+ if (ZoomMode == PreviewZoomMode.Actual) view = ViewportMath.SnapOffset(view, dpi);
+ _view = view;
+ _surface?.SetView(view, view.Scale * dpi);
+ _syncingZoom = true;
+ try
+ {
+ SetCurrentValue(ZoomProperty, view.Scale * dpi);
+ }
+ finally
+ {
+ _syncingZoom = false;
+ }
+ }
+
+ private bool IsNearDivider(Point p) =>
+ IsCompareEnabled && OriginalSource is not null && Math.Abs(p.X - WipePosition * ViewSize.Width) <= DividerGrip;
+
+ private bool IsPannable()
+ {
+ var view = ViewSize;
+ return !_imageSize.IsEmpty && (_imageSize.Width * _view.Scale > view.Width + 0.5 || _imageSize.Height * _view.Scale > view.Height + 0.5);
+ }
+}