using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using Titano.Core.Localization; 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. Screen readers see an image (named by AutomationProperties.Name) /// whose status is the zoom and whose help text is the shot data, holding the tools. /// [TemplatePart(Name = PartSurface, Type = typeof(FrameworkElement))] [TemplatePart(Name = PartTools, Type = typeof(FrameworkElement))] [TemplatePart(Name = PartInfo, Type = typeof(FrameworkElement))] public class PreviewViewport : Control { public const string PartSurface = "PART_Surface"; public const string PartTools = "PART_Tools"; public const string PartInfo = "PART_Info"; 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 FrameworkElement? _tools; private FrameworkElement? _info; private Thickness _infoMargin; 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(); _tools = GetTemplateChild(PartTools) as FrameworkElement; _info = GetTemplateChild(PartInfo) as FrameworkElement; if (_info is not null) _infoMargin = _info.Margin; _surface = GetTemplateChild(PartSurface) as PreviewSurface; if (_surface is null) return; _surface.Owner = this; _surface.SizeChanged += OnSurfaceSizeChanged; _surface.SetImages(Source, OriginalSource, _imageSize); ApplyZoomMode(); } /// The shot data pill sits beside the tools at the bottom, and just above them when both do not fit in one row. protected override Size ArrangeOverride(Size arrangeBounds) { var size = base.ArrangeOverride(arrangeBounds); if (_tools is not null && _info is not null) { var lifted = _tools.DesiredSize.Width + _info.DesiredSize.Width > arrangeBounds.Width; var margin = lifted ? _infoMargin with { Bottom = _tools.DesiredSize.Height - _tools.Margin.Top + 6 } : _infoMargin; if (_info.Margin != margin) _info.Margin = margin; } return size; } 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(); } protected override AutomationPeer OnCreateAutomationPeer() => new PreviewViewportAutomationPeer(this); 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; // The same picture at another resolution (a 1:1 render replacing the fitted one) keeps what is on screen. if (resized && !size.IsEmpty && !viewport._imageSize.IsEmpty && viewport._view.Scale > 0) viewport._view = viewport._view with { Scale = viewport._view.Scale * viewport._imageSize.Width / size.Width }; 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); var zoom = view.Scale * dpi; if (zoom == Zoom) return; _syncingZoom = true; try { SetCurrentValue(ZoomProperty, zoom); } 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); } } /// The preview seen by UI Automation: an image whose status gives the zoom ("50 %") and whose help text is the shot data. public sealed class PreviewViewportAutomationPeer(PreviewViewport owner) : FrameworkElementAutomationPeer(owner) { protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Image; protected override string GetClassNameCore() => nameof(PreviewViewport); protected override string GetItemStatusCore() { var viewport = (PreviewViewport)Owner; return viewport.ImageSize.IsEmpty ? string.Empty : Loc.L("Common.Percent", Math.Round(viewport.Zoom * 100)); } protected override string GetHelpTextCore() { var help = base.GetHelpTextCore(); return string.IsNullOrEmpty(help) ? ((PreviewViewport)Owner).InfoText ?? string.Empty : help; } }