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; } // The base constructor sets an inherited property, which may enumerate children before _layers exists. protected override int VisualChildrenCount => _layers is null ? 0 : _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(); } /// 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); } }