diff --git a/api/Avalonia.nupkg.xml b/api/Avalonia.nupkg.xml index cf7ef0deca..5c720c9413 100644 --- a/api/Avalonia.nupkg.xml +++ b/api/Avalonia.nupkg.xml @@ -151,6 +151,18 @@ baseline/Avalonia/lib/net10.0/Avalonia.Base.dll current/Avalonia/lib/net10.0/Avalonia.Base.dll + + CP0006 + M:Avalonia.Platform.IGeometryImpl.FillContains(Avalonia.Platform.IGeometryImpl) + baseline/Avalonia/lib/net10.0/Avalonia.Base.dll + current/Avalonia/lib/net10.0/Avalonia.Base.dll + + + CP0006 + M:Avalonia.Platform.IGeometryImpl.GetFillIntersectionResult(Avalonia.Platform.IGeometryImpl) + baseline/Avalonia/lib/net10.0/Avalonia.Base.dll + current/Avalonia/lib/net10.0/Avalonia.Base.dll + CP0006 M:Avalonia.Platform.Storage.IStorageProvider.OpenFilePickerWithResultAsync(Avalonia.Platform.Storage.FilePickerOpenOptions) @@ -187,6 +199,18 @@ baseline/Avalonia/lib/net8.0/Avalonia.Base.dll current/Avalonia/lib/net8.0/Avalonia.Base.dll + + CP0006 + M:Avalonia.Platform.IGeometryImpl.FillContains(Avalonia.Platform.IGeometryImpl) + baseline/Avalonia/lib/net8.0/Avalonia.Base.dll + current/Avalonia/lib/net8.0/Avalonia.Base.dll + + + CP0006 + M:Avalonia.Platform.IGeometryImpl.GetFillIntersectionResult(Avalonia.Platform.IGeometryImpl) + baseline/Avalonia/lib/net8.0/Avalonia.Base.dll + current/Avalonia/lib/net8.0/Avalonia.Base.dll + CP0006 M:Avalonia.Platform.Storage.IStorageProvider.OpenFilePickerWithResultAsync(Avalonia.Platform.Storage.FilePickerOpenOptions) diff --git a/samples/RenderDemo/MainWindow.xaml b/samples/RenderDemo/MainWindow.xaml index aedd9f95cf..e463578709 100644 --- a/samples/RenderDemo/MainWindow.xaml +++ b/samples/RenderDemo/MainWindow.xaml @@ -72,6 +72,9 @@ + + + diff --git a/samples/RenderDemo/Pages/GeometryHitTestingPage.axaml b/samples/RenderDemo/Pages/GeometryHitTestingPage.axaml new file mode 100644 index 0000000000..f5c7c2cf23 --- /dev/null +++ b/samples/RenderDemo/Pages/GeometryHitTestingPage.axaml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/RenderDemo/Pages/GeometryHitTestingPage.axaml.cs b/samples/RenderDemo/Pages/GeometryHitTestingPage.axaml.cs new file mode 100644 index 0000000000..854a5957a4 --- /dev/null +++ b/samples/RenderDemo/Pages/GeometryHitTestingPage.axaml.cs @@ -0,0 +1,109 @@ +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Shapes; +using Avalonia.Input; +using Avalonia.Markup.Xaml; +using Avalonia.Media; + +namespace RenderDemo.Pages; + +public class GeometryHitTestingPage : UserControl +{ + private readonly IBrush _hitStroke = Brushes.Yellow; + private readonly TranslateTransform _probePosition = new(); + private readonly Dictionary _strokes = new(); + private readonly List<(Shape Shape, IntersectionResult Intersection)> _hits = new(); + private readonly Geometry _probeGeometry; + private readonly Panel _scene; + private readonly Path _probe; + private readonly TextBlock _status; + + public GeometryHitTestingPage() + { + InitializeComponent(); + + _scene = this.Get("Scene"); + _probe = this.Get("Probe"); + _status = this.Get("Status"); + + _probeGeometry = CreateProbeGeometry(); + _probeGeometry.Transform = _probePosition; + _probe.Data = _probeGeometry; + + foreach (var shape in _scene.Children.OfType()) + { + if (shape != _probe) + _strokes.Add(shape, shape.Stroke); + } + + _scene.PointerEntered += SceneOnPointerMoved; + _scene.PointerMoved += SceneOnPointerMoved; + _scene.PointerExited += SceneOnPointerExited; + + UpdateStatus(); + } + + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + } + + private Geometry CreateProbeGeometry() + => new PolylineGeometry([new(0, -42), new(38, 26), new(-38, 26)], true); + + private void SceneOnPointerMoved(object? sender, PointerEventArgs e) + { + _probe.IsVisible = true; + MoveProbe(e.GetPosition(_scene)); + } + + private void MoveProbe(Point position) + { + _probePosition.X = position.X; + _probePosition.Y = position.Y; + + ClearHits(); + + foreach (var result in _scene.GetInputElementsAt(_probeGeometry)) + { + if (result?.VisualHit is Shape shape && _strokes.ContainsKey(shape)) + { + shape.Stroke = _hitStroke; + _hits.Add((shape, result.IntersectionResult)); + } + } + + UpdateStatus(); + } + + private void SceneOnPointerExited(object? sender, PointerEventArgs e) + { + _probe.IsVisible = false; + ClearHits(); + UpdateStatus(); + } + + private void ClearHits() + { + foreach (var hit in _hits) + { + hit.Shape.Stroke = _strokes[hit.Shape]; + } + + _hits.Clear(); + } + + private void UpdateStatus() + { + if (_hits.Count == 0) + { + _status.Text = "No intersection"; + return; + } + + _status.Text = "Intersecting, " + string.Join(", ", _hits.Select(hit => $"{hit.Shape.Name} ({hit.Intersection})")); + } +} + diff --git a/samples/RenderDemo/Pages/HitTestingPage.cs b/samples/RenderDemo/Pages/HitTestingPage.cs index f7b2e454b2..621b4dbf1c 100644 --- a/samples/RenderDemo/Pages/HitTestingPage.cs +++ b/samples/RenderDemo/Pages/HitTestingPage.cs @@ -1,10 +1,13 @@ using System; +using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Numerics; using Avalonia; using Avalonia.Animation; using Avalonia.Animation.Easings; using Avalonia.Controls; +using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Media; using Avalonia.Rendering.Composition; @@ -15,6 +18,7 @@ namespace RenderDemo.Pages { public class HitTestingPage : UserControl { + private const int RegionSize = 80; private const int GroupColumns = 8; private const int GroupRows = 5; private const int CellsPerGroupSide = 10; @@ -44,6 +48,9 @@ namespace RenderDemo.Pages private bool _animationsStarted; private Cell? _lastHitCell; private Cell? _lastClickedCell; + private bool _regionSelection; + private Ellipse _region; + private List _regionHits = new List(); public HitTestingPage() { @@ -54,6 +61,9 @@ namespace RenderDemo.Pages Background = Brushes.Transparent }; + _scene.PointerMoved += Scene_PointerMoved; + _scene.PointerPressed += Scene_PointerPressed; + _stats = new TextBlock { HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, @@ -65,6 +75,31 @@ namespace RenderDemo.Pages IsHitTestVisible = false }; + var regionSelection = new CheckBox() + { + Content = "Region Selection" + }; + + _region = new Ellipse() + { + Width = RegionSize * 2, + Height = RegionSize, + Fill = Brushes.Transparent, + StrokeThickness = 2, + Stroke = Brushes.Green, + IsVisible = false, + IsHitTestVisible = false + }; + + regionSelection.IsCheckedChanged += (s, e) => + { + _regionSelection = !_regionSelection; + + _region.IsVisible = _regionSelection; + + ClearRegionHighlights(); + }; + var numberOfHitTests = new NumericUpDown { Minimum = 0, @@ -92,7 +127,8 @@ namespace RenderDemo.Pages Children = { new TextBlock { Text = "Hit tests per update:" }, - numberOfHitTests + numberOfHitTests, + regionSelection } }; @@ -119,6 +155,57 @@ namespace RenderDemo.Pages ResetState(); } + private void ClearRegionHighlights() + { + _lastClickedCell?.ClearHighlight(); + _lastClickedCell = null; + foreach (var cell in _regionHits) + { + cell.ClearHighlight(); + } + _regionHits.Clear(); + } + + private void Scene_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if(_regionSelection) + { + var bounds = _region.Bounds; + + ClearRegionHighlights(); + + var geometry = new EllipseGeometry(bounds); + + var cells = _scene.GetVisualsAt(geometry); + + if (cells == null) + return; + + foreach (var cell in cells) + { + if(cell?.VisualHit is Cell c) + { + c.IsLatestClick = true; + c.UpdateHighlight(); + _regionHits.Add(c); + } + } + } + } + + private void Scene_PointerMoved(object? sender, PointerEventArgs e) + { + if(_regionSelection) + { + var point = e.GetPosition(_scene); + + var rect = new Rect(point, new Size()).Inflate(new Thickness(_region.Bounds.Width / 2, _region.Bounds.Height / 2)); + + Canvas.SetLeft(_region, rect.X); + Canvas.SetTop(_region, rect.Y); + } + } + protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); @@ -177,6 +264,8 @@ namespace RenderDemo.Pages } } } + + _scene.Children.Add(_region); } private void OnCompositionUpdate() @@ -337,7 +426,7 @@ namespace RenderDemo.Pages private void OnCellPointerPressed(object? sender, PointerPressedEventArgs e) { - if (sender is not Cell cell) + if (sender is not Cell cell || _regionSelection) return; SetLastClickedCell(cell); diff --git a/src/Avalonia.Base/Input/InputExtensions.cs b/src/Avalonia.Base/Input/InputExtensions.cs index a5107588c9..2533a174a4 100644 --- a/src/Avalonia.Base/Input/InputExtensions.cs +++ b/src/Avalonia.Base/Input/InputExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Avalonia.Media; using Avalonia.VisualTree; #nullable enable @@ -31,10 +32,29 @@ namespace Avalonia.Input return (element as Visual)?.GetVisualsAt(p, enabledElementsOnly ? s_hitTestEnabledOnlyDelegate : s_hitTestDelegate).Cast() ?? Enumerable.Empty(); } - + /// public static IEnumerable GetInputElementsAt(this IInputElement element, Point p) => GetInputElementsAt(element, p, true); + /// + /// Returns the active input elements intersecting a geometry on an . + /// + /// The element to test. + /// The geometry on . + /// Whether to only return elements for which is true. + /// + /// The active input elements found intersecting the geometry, with intersection details, ordered topmost first. + /// + public static IEnumerable GetInputElementsAt(this IInputElement element, Geometry geometry, bool enabledElementsOnly = true) + { + element = element ?? throw new ArgumentNullException(nameof(element)); + + return (element as Visual)?.GetVisualsAt(geometry, enabledElementsOnly ? s_hitTestEnabledOnlyDelegate : s_hitTestDelegate) + .Where(x => x.VisualHit is IInputElement) + .Select(x => new GeometryHitTestResult(x.VisualHit, x.IntersectionResult)) ?? + Enumerable.Empty(); + } + /// /// Returns the topmost active input element at a point on an . /// @@ -52,6 +72,22 @@ namespace Avalonia.Input /// public static IInputElement? InputHitTest(this IInputElement element, Point p) => InputHitTest(element, p, true); + /// + /// Returns the topmost active input element intersecting a geometry on an . + /// + /// The element to test. + /// The geometry on . + /// Whether to only return elements for which is true. + /// A containing the topmost intersecting the specified geometry and intersection details, or null if no element intersects. + public static GeometryHitTestResult? InputHitTest(this IInputElement element, Geometry geometry, bool enabledElementsOnly = true) + { + element = element ?? throw new ArgumentNullException(nameof(element)); + + var hitTest = (element as Visual)?.GetVisualAt(geometry, enabledElementsOnly ? s_hitTestEnabledOnlyDelegate : s_hitTestDelegate); + + return hitTest?.VisualHit is IInputElement inputElement ? hitTest : null; + } + /// /// Returns the topmost active input element at a point on an . /// @@ -79,6 +115,30 @@ namespace Avalonia.Input /// public static IInputElement? InputHitTest(this IInputElement element, Point p, Func filter) => InputHitTest(element, p, filter, true); + /// + /// Returns the topmost active input element intersecting a geometry on an . + /// + /// The element to test. + /// The geometry on . + /// + /// A filter predicate. If the predicate returns false then the visual and all its + /// children will be excluded from the results. + /// + /// Whether to only return elements for which is true. + /// A containing the topmost intersecting the specified geometry and intersection details, or null if no element intersects. + public static IInputElement? InputHitTest( + this IInputElement element, + Geometry geometry, + Func filter, + bool enabledElementsOnly = true) + { + element = element ?? throw new ArgumentNullException(nameof(element)); + filter = filter ?? throw new ArgumentNullException(nameof(filter)); + var hitTestDelegate = enabledElementsOnly ? s_hitTestEnabledOnlyDelegate : s_hitTestDelegate; + + return (element as Visual)?.GetVisualAt(geometry, x => hitTestDelegate(x) && filter(x)) as IInputElement; + } + private static bool IsHitTestVisible(Visual visual) => visual is { IsVisible: true, IsAttachedToVisualTree: true } and IInputElement { IsHitTestVisible: true }; private static bool IsHitTestVisible_EnabledOnly(Visual visual) => IsHitTestVisible(visual) && visual is IInputElement { IsEffectivelyEnabled: true }; diff --git a/src/Avalonia.Base/Media/Geometry.cs b/src/Avalonia.Base/Media/Geometry.cs index 8082c2e71a..1499816122 100644 --- a/src/Avalonia.Base/Media/Geometry.cs +++ b/src/Avalonia.Base/Media/Geometry.cs @@ -1,8 +1,8 @@ using System; -using Avalonia.Platform; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using Avalonia.Platform; using Avalonia.Reactive; using Avalonia.Rendering.Composition; using Avalonia.Rendering.Composition.Drawing; @@ -120,6 +120,16 @@ namespace Avalonia.Media return PlatformImpl?.FillContains(point) == true; } + /// + /// Returns a value that describes the intersection between the current geometry and the specified geometry + /// + /// The geometry to test for containment. + /// The describing the intersection between the geometries + public IntersectionResult? GetFillIntersectionResult(Geometry geometry) + { + return geometry.PlatformImpl == null ? IntersectionResult.Empty : PlatformImpl?.GetFillIntersectionResult(geometry.PlatformImpl); + } + /// /// Indicates whether the geometry's stroke contains the specified point. /// diff --git a/src/Avalonia.Base/Media/GeometryHitTestResult.cs b/src/Avalonia.Base/Media/GeometryHitTestResult.cs new file mode 100644 index 0000000000..c43574a385 --- /dev/null +++ b/src/Avalonia.Base/Media/GeometryHitTestResult.cs @@ -0,0 +1,9 @@ +namespace Avalonia.Media +{ + /// + /// Returns the results of a hit test that uses a as a hit test parameter. + /// + /// Gets the that is returned from a hit test result. + /// Gets the value of the hit test. + public record class GeometryHitTestResult(Visual VisualHit, IntersectionResult IntersectionResult); +} diff --git a/src/Avalonia.Base/Media/IntersectionResult.cs b/src/Avalonia.Base/Media/IntersectionResult.cs new file mode 100644 index 0000000000..cab4c70d0d --- /dev/null +++ b/src/Avalonia.Base/Media/IntersectionResult.cs @@ -0,0 +1,33 @@ +namespace Avalonia.Media +{ + /// + /// Provides information about the intersection between a hit geometry and a target geometry or visual. + /// + public enum IntersectionResult + { + /// + /// The IntersectionDetail value is not calculated. + /// + NotCalculated = 0, + + /// + /// The hit test parameter and the target visual, or geometry, do not intersect. + /// + Empty = 1, + + /// + /// The target geometry or visual is fully inside the hit test . + /// + FullyInside = 2, + + /// + /// The hit test parameter is fully contained within the boundary of the target visual or geometry. + /// + FullyContains = 3, + + /// + /// The hit test parameter and the target visual, or geometry, intersect. This means that the two elements overlap, but neither element contains the other. + /// + Intersects = 4 + } +} diff --git a/src/Avalonia.Base/Platform/IGeometryImpl.cs b/src/Avalonia.Base/Platform/IGeometryImpl.cs index 0e74f1e4c5..ae8eb6d765 100644 --- a/src/Avalonia.Base/Platform/IGeometryImpl.cs +++ b/src/Avalonia.Base/Platform/IGeometryImpl.cs @@ -46,6 +46,13 @@ namespace Avalonia.Platform /// true if the geometry contains the point; otherwise, false. bool FillContains(Point point); + /// + /// Returns a value that describes the intersection between the current geometry and the specified geometry + /// + /// The geometry to test for containment. + /// The describing the intersection between the geometries + IntersectionResult GetFillIntersectionResult(IGeometryImpl geometry); + /// /// Intersects the geometry with another geometry. /// diff --git a/src/Avalonia.Base/Platform/LtrbRect.cs b/src/Avalonia.Base/Platform/LtrbRect.cs index 97cbec0ab2..37615b8205 100644 --- a/src/Avalonia.Base/Platform/LtrbRect.cs +++ b/src/Avalonia.Base/Platform/LtrbRect.cs @@ -301,4 +301,4 @@ public struct LtrbPixelRect internal static LtrbPixelRect FromRectUnscaled(LtrbRect rect) => new((int)rect.Left, (int)rect.Top, (int)Math.Ceiling(rect.Right), (int)Math.Ceiling(rect.Bottom)); -} \ No newline at end of file +} diff --git a/src/Avalonia.Base/Rendering/Composition/CompositingRenderer.cs b/src/Avalonia.Base/Rendering/Composition/CompositingRenderer.cs index cef5eb62de..6cb4021713 100644 --- a/src/Avalonia.Base/Rendering/Composition/CompositingRenderer.cs +++ b/src/Avalonia.Base/Rendering/Composition/CompositingRenderer.cs @@ -4,9 +4,10 @@ using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Avalonia.Diagnostics; -using Avalonia.Platform.Surfaces; using Avalonia.Media; +using Avalonia.Platform.Surfaces; using Avalonia.Rendering.Composition.Drawing; +using Avalonia.Rendering.Composition.HitTesting; using Avalonia.Threading; namespace Avalonia.Rendering.Composition; @@ -92,6 +93,14 @@ internal class CompositingRenderer : IRendererWithCompositor, IHitTester /// public IEnumerable HitTest(Point p, Visual? root, Func? filter) + => HitTest(p, root, filter, (visual, _) => visual); + + public IEnumerable HitTest(Geometry geometry, Visual? root, Func? filter) + => HitTest(geometry, root, filter, (visual, intersection) => new GeometryHitTestResult(visual, intersection)); + + private IEnumerable HitTest(T input, Visual? root, Func? filter, Func resultSelector) + where THitTester : struct, ICompositionHitTester + where TResult : class { using var _ = Diagnostic.PerformingHitTest(); @@ -102,7 +111,7 @@ internal class CompositingRenderer : IRendererWithCompositor, IHitTester yield break; rootVisual = root.CompositionVisual; } - + Func? f = null; if (filter != null) f = v => @@ -112,22 +121,37 @@ internal class CompositingRenderer : IRendererWithCompositor, IHitTester return true; }; - using var res = CompositionTarget.TryHitTest(p, rootVisual, f); - if(res == null) + using var res = CompositionTarget.TryHitTest(input, rootVisual, f); + if (res == null) yield break; - foreach(var v in res) + + foreach (var v in res) { - if (v is CompositionDrawListVisual dv) + if (v.Item2 is CompositionDrawListVisual dv) { if (filter == null || filter(dv.Visual)) - yield return dv.Visual; + yield return resultSelector(dv.Visual, v.Item1); } } } /// public Visual? HitTestFirst(Point p, Visual root, Func? filter) + => HitTestFirst(p, root, filter, out _); + + /// + public GeometryHitTestResult? HitTestFirst(Geometry geometry, Visual root, Func? filter) { + var visual = HitTestFirst(geometry, root, filter, out var intersectionResult); + + return visual != null ? new GeometryHitTestResult(visual, intersectionResult) : null; + } + + private Visual? HitTestFirst(T input, Visual root, Func? filter, out IntersectionResult intersectionResult) + where THitTester : struct, ICompositionHitTester + { + intersectionResult = IntersectionResult.NotCalculated; + using var _ = Diagnostic.PerformingHitTest(); if (root.CompositionVisual == null) @@ -137,7 +161,8 @@ internal class CompositingRenderer : IRendererWithCompositor, IHitTester ? null : v => v is not CompositionDrawListVisual dlv || filter(dlv.Visual); - return CompositionTarget.TryHitTestFirst(p, root.CompositionVisual, f, static v => v is CompositionDrawListVisual) is CompositionDrawListVisual dv ? dv.Visual : null; + return CompositionTarget.TryHitTestFirst(input, root.CompositionVisual, f, static v => v is CompositionDrawListVisual, out intersectionResult) + is CompositionDrawListVisual dv ? dv.Visual : null; } /// diff --git a/src/Avalonia.Base/Rendering/Composition/CompositionDrawListVisual.cs b/src/Avalonia.Base/Rendering/Composition/CompositionDrawListVisual.cs index 6f4bb3b882..c7bf13e6ff 100644 --- a/src/Avalonia.Base/Rendering/Composition/CompositionDrawListVisual.cs +++ b/src/Avalonia.Base/Rendering/Composition/CompositionDrawListVisual.cs @@ -1,3 +1,4 @@ +using Avalonia.Media; using Avalonia.Rendering.Composition.Drawing; using Avalonia.Rendering.Composition.Server; using Avalonia.Rendering.Composition.Transport; @@ -65,4 +66,17 @@ internal class CompositionDrawListVisual : CompositionContainerVisual return DrawList?.HitTest(pt) ?? false; } + + internal override IntersectionResult HitTest(Geometry geometry) + { + var custom = Visual as ICustomHitTest; + if (DrawList == null && custom == null) + return IntersectionResult.Empty; + if (custom != null) + { + return custom.HitTest(geometry); + } + + return DrawList?.HitTest(geometry) ?? IntersectionResult.Empty; + } } diff --git a/src/Avalonia.Base/Rendering/Composition/CompositionTarget.cs b/src/Avalonia.Base/Rendering/Composition/CompositionTarget.cs index 8b418211b8..0e9607dafa 100644 --- a/src/Avalonia.Base/Rendering/Composition/CompositionTarget.cs +++ b/src/Avalonia.Base/Rendering/Composition/CompositionTarget.cs @@ -1,7 +1,9 @@ using System; -using System.Numerics; +using System.Diagnostics.CodeAnalysis; using Avalonia.Collections.Pooled; -using Avalonia.VisualTree; +using Avalonia.Media; +using Avalonia.Platform; +using Avalonia.Rendering.Composition.HitTesting; namespace Avalonia.Rendering.Composition { @@ -24,12 +26,16 @@ namespace Avalonia.Rendering.Composition if (Root != null) Root.Root = null; } - + /// - /// Attempts to perform a hit-tst + /// Attempts to perform a hit-test. /// - /// - public PooledList? TryHitTest(Point point, CompositionVisual? root, Func? filter) + /// A list of visuals hit during the test. + public PooledList<(IntersectionResult, CompositionVisual)>? TryHitTest( + T input, + CompositionVisual? root, + Func? filter) + where THitTester : struct, ICompositionHitTester { Server.Compositor.Readback.NextRead(); @@ -43,10 +49,11 @@ namespace Avalonia.Rendering.Composition var readback = root.TryGetValidReadback(); if (readback == null) return null; - point = point.Transform(readback.Matrix); - var res = new PooledList(); - HitTestCore(root, point, res, filter); + var parentInput = THitTester.Transform(input, in readback.Matrix); + + var res = new PooledList<(IntersectionResult, CompositionVisual)>(); + HitTestCore(root, parentInput, res, filter); return res; } @@ -77,31 +84,37 @@ namespace Avalonia.Rendering.Composition } } - private void HitTestCore(CompositionVisual visual, Point parentPoint, PooledList result, Func? filter) + private void HitTestCore( + CompositionVisual visual, + T parentInput, + PooledList<(IntersectionResult, CompositionVisual)> result, + Func? filter) + where THitTester : struct, ICompositionHitTester { - if (!HitTestVisual(visual, parentPoint, filter, out var point)) + if (!HitTestVisual(visual, parentInput, filter, out var input)) return; // Inspect children if (visual is CompositionContainerVisual cv) - HitTestChildren(cv, point, result, filter); - + HitTestChildren(cv, input, result, filter); + // Hit-test the current node - if (visual.HitTest(point)) - result.Add(visual); + if (THitTester.HitTest(visual, input) is IntersectionResult intersectionResult && intersectionResult > IntersectionResult.Empty) + result.Add((intersectionResult, visual)); } - private void HitTestChildren(CompositionContainerVisual visual, Point point, PooledList result, Func? filter) + private void HitTestChildren(CompositionContainerVisual visual, T input, PooledList<(IntersectionResult, CompositionVisual)> result, Func? filter) + where THitTester : struct, ICompositionHitTester { if (visual.Children.Count >= CompositionContainerVisual.HitTestAabbTreeThreshold) { var candidates = RentHitTestChildCandidates(out var releaseToField); try { - if (visual.TryQueryHitTestChildren(point, candidates)) + if (visual.TryQueryHitTestChildren(input, candidates)) { foreach (var child in candidates) - HitTestCore(child, point, result, filter); + HitTestCore(child, input, result, filter); return; } } @@ -112,47 +125,58 @@ namespace Avalonia.Rendering.Composition } for (var c = visual.Children.Count - 1; c >= 0; c--) - HitTestCore(visual.Children[c], point, result, filter); + HitTestCore(visual.Children[c], input, result, filter); } - private static bool HitTestVisual(CompositionVisual visual, Point parentPoint, Func? filter, out Point point) + private static bool HitTestVisual( + CompositionVisual visual, + T parentInput, + Func? filter, + [MaybeNullWhen(false)] out T input) + where THitTester : struct, ICompositionHitTester { - point = default; + input = default; - if (visual.Visible == false) + if (!visual.Visible) return false; if (filter != null && !filter(visual)) return false; var readback = visual.TryGetValidReadback(); - if(readback == null) + if (readback == null) return false; if (!visual.DisableSubTreeBoundsHitTestOptimization && - (readback.TransformedSubtreeBounds == null || - !readback.TransformedSubtreeBounds.Value.Contains(parentPoint))) + (readback.TransformedSubtreeBounds is not { } transformedSubtreeBounds || + !THitTester.TransformedSubTreeBoundsMatch(transformedSubtreeBounds, parentInput))) return false; - if(!readback.Matrix.TryInvert(out var invMatrix)) + if (!readback.Matrix.TryInvert(out var invMatrix)) return false; - point = parentPoint.Transform(invMatrix); + input = THitTester.Transform(parentInput, in invMatrix); - if (visual.ClipToBounds - && (point.X < 0 || point.Y < 0 || point.X > visual.Size.X || point.Y > visual.Size.Y)) + if (visual.ClipToBounds && !THitTester.ClippedBoundsMatch(visual, input)) return false; - if (visual.Clip?.FillContains(point) == false) + if (visual.Clip is { } clip && !THitTester.ClipMatches(clip, input)) return false; return true; } - public CompositionVisual? TryHitTestFirst(Point point, CompositionVisual? root, Func? filter, Func? resultFilter) + public CompositionVisual? TryHitTestFirst( + T input, + CompositionVisual? root, + Func? filter, + Func? resultFilter, out IntersectionResult intersectionResult) + where THitTester : struct, ICompositionHitTester { Server.Compositor.Readback.NextRead(); + intersectionResult = IntersectionResult.NotCalculated; + root ??= Root; if (root == null) return null; @@ -164,12 +188,21 @@ namespace Avalonia.Rendering.Composition if (readback == null) return null; - return HitTestFirstCore(root, point.Transform(readback.Matrix), filter, resultFilter); + var parentInput = THitTester.Transform(input, in readback.Matrix); + + return HitTestFirstCore(root, parentInput, filter, resultFilter, out intersectionResult); } - internal CompositionVisual? HitTestFirstCore(CompositionVisual visual, Point parentPoint, Func? filter, Func? resultFilter) + internal CompositionVisual? HitTestFirstCore( + CompositionVisual visual, + T parentInput, + Func? filter, + Func? resultFilter, out IntersectionResult intersectionResult) + where THitTester : struct, ICompositionHitTester { - if (!HitTestVisual(visual, parentPoint, filter, out var point)) + intersectionResult = IntersectionResult.NotCalculated; + + if (!HitTestVisual(visual, parentInput, filter, out var input)) return null; if (visual is CompositionContainerVisual cv) @@ -177,7 +210,7 @@ namespace Avalonia.Rendering.Composition var queriedIndexedChildren = false; if (cv.Children.Count >= CompositionContainerVisual.HitTestAabbTreeThreshold) { - if (cv.TryQueryFirstHitTestChild(this, point, filter, resultFilter, out var hit)) + if (cv.TryQueryFirstHitTestChild(this, input, filter, resultFilter, out var hit, out intersectionResult)) { queriedIndexedChildren = true; if (hit != null) @@ -189,14 +222,16 @@ namespace Avalonia.Rendering.Composition { for (var c = cv.Children.Count - 1; c >= 0; c--) { - var hit = HitTestFirstCore(cv.Children[c], point, filter, resultFilter); + var hit = HitTestFirstCore(cv.Children[c], input, filter, resultFilter, out intersectionResult); if (hit != null) return hit; } } } - return visual.HitTest(point) && (resultFilter == null || resultFilter(visual)) ? visual : null; + intersectionResult = THitTester.HitTest(visual, input); + + return intersectionResult > IntersectionResult.Empty && (resultFilter == null || resultFilter(visual)) ? visual : null; } /// diff --git a/src/Avalonia.Base/Rendering/Composition/ContainerVisual.cs b/src/Avalonia.Base/Rendering/Composition/ContainerVisual.cs index ceaf18ee0c..04dedb041d 100644 --- a/src/Avalonia.Base/Rendering/Composition/ContainerVisual.cs +++ b/src/Avalonia.Base/Rendering/Composition/ContainerVisual.cs @@ -1,6 +1,7 @@ using System; using Avalonia.Collections.Pooled; -using Avalonia.Rendering.Composition.Server; +using Avalonia.Media; +using Avalonia.Rendering.Composition.HitTesting; namespace Avalonia.Rendering.Composition { @@ -53,7 +54,8 @@ namespace Avalonia.Rendering.Composition _hitTestChildren?.Clear(); } - internal bool TryQueryHitTestChildren(Point point, PooledList results) + internal bool TryQueryHitTestChildren(T input, PooledList results) + where THitTester : struct, ICompositionHitTester { if (Children.Count < HitTestAabbTreeThreshold) { @@ -63,22 +65,30 @@ namespace Avalonia.Rendering.Composition _hitTestChildren ??= new CompositionHitTestAabbTree(Children); - _hitTestChildren.Query(point, results, Server.Compositor.Readback.ReadRevision); + _hitTestChildren.Query(input, results, Server.Compositor.Readback.ReadRevision); return true; } - internal bool TryQueryFirstHitTestChild(CompositionTarget target, Point point, Func? filter, Func? resultFilter, out CompositionVisual? hit) + internal bool TryQueryFirstHitTestChild( + CompositionTarget target, + T input, + Func? filter, + Func? resultFilter, + out CompositionVisual? hit, + out IntersectionResult intersectionResult) + where THitTester : struct, ICompositionHitTester { if (Children.Count < HitTestAabbTreeThreshold) { _hitTestChildren = null; hit = null; + intersectionResult = IntersectionResult.Empty; return false; } _hitTestChildren ??= new CompositionHitTestAabbTree(Children); - hit = _hitTestChildren.QueryFirst(target, point, filter, resultFilter, Server.Compositor.Readback.ReadRevision); + hit = _hitTestChildren.QueryFirst(target, input, filter, resultFilter, Server.Compositor.Readback.ReadRevision, out intersectionResult); return true; } diff --git a/src/Avalonia.Base/Rendering/Composition/Drawing/CompositionRenderData.cs b/src/Avalonia.Base/Rendering/Composition/Drawing/CompositionRenderData.cs index feb0a93f61..79a41f6452 100644 --- a/src/Avalonia.Base/Rendering/Composition/Drawing/CompositionRenderData.cs +++ b/src/Avalonia.Base/Rendering/Composition/Drawing/CompositionRenderData.cs @@ -1,4 +1,5 @@ using System; +using Avalonia.Media; using Avalonia.Rendering.Composition.Server; using Avalonia.Rendering.Composition.Transport; using Avalonia.Utilities; @@ -47,4 +48,6 @@ internal class CompositionRenderData : ICompositorSerializable, IDisposable } public bool HitTest(Point pt) => _stream.HitTest(pt); + + public IntersectionResult HitTest(Geometry geometry) => _stream.HitTest(geometry); } diff --git a/src/Avalonia.Base/Rendering/Composition/Drawing/RenderDataStream.HitTest.cs b/src/Avalonia.Base/Rendering/Composition/Drawing/RenderDataStream.HitTest.cs index 38b39053f9..289fc831fd 100644 --- a/src/Avalonia.Base/Rendering/Composition/Drawing/RenderDataStream.HitTest.cs +++ b/src/Avalonia.Base/Rendering/Composition/Drawing/RenderDataStream.HitTest.cs @@ -1,6 +1,6 @@ using System; +using System.Collections.Generic; using Avalonia.Media; -using Avalonia.Media.Imaging; using Avalonia.Platform; using Avalonia.Rendering.SceneGraph; using Avalonia.Utilities; @@ -13,88 +13,189 @@ internal partial class RenderDataStream { public bool SavedLive; public bool RestorePoint; - public Point SavedPoint; + public Point? SavedPoint; } internal struct HitTestVisitor : IRenderDataVisitor { public bool StopVisiting { get; private set; } + public Geometry? CurrentGeometry + { + get => _currentGeometry; + set + { + _currentGeometry = value; + _renderedGeometry = GetRenderedGeometry(value, s_defaultStokePen); + } + } + public bool HitFound; - public Point Current; + public IntersectionResult HitResult; + private Geometry? _currentGeometry; + private Geometry? _renderedGeometry; + public Point? CurrentPoint; public bool Live; - public HitTestVisitor(Point point) + private Stack? _savedGeometries = null; + + public HitTestVisitor() { StopVisiting = false; - HitFound = false; - Current = point; Live = true; } + public HitTestVisitor(Geometry geometry) : this() + { + HitResult = IntersectionResult.NotCalculated; + CurrentGeometry = geometry; + _savedGeometries = new Stack(); + } + + public HitTestVisitor(Point point) : this() + { + HitResult = IntersectionResult.NotCalculated; + CurrentPoint = point; + } + private void Hit() { HitFound = true; StopVisiting = true; } + private void Hit(IntersectionResult result) + { + HitResult = result; + StopVisiting = true; + } + public void OnDrawLine(IPen? serverPen, IPen? clientPen, Point p1, Point p2) { - if (Live && HitTestLine(clientPen, p1, p2, Current)) + if (!Live) + return; + + if (CurrentPoint is { } point && HitTestLine(clientPen, p1, p2, point)) Hit(); + + else if (_renderedGeometry is { } geometry && HitTestLine(clientPen, p1, p2, geometry) is { } intersectionDetail) + Hit(intersectionDetail); } public void OnDrawRectangle(IBrush? serverBrush, IPen? serverPen, IPen? clientPen, RoundedRect rect, BoxShadows boxShadows) { - if (Live && HitTestRectangle(serverBrush, clientPen, rect, Current)) + if (!Live) + return; + + if (CurrentPoint is { } point && HitTestRectangle(serverBrush, clientPen, rect, point)) Hit(); + + else if (_renderedGeometry is { } geometry && HitTestRectangle(serverBrush, clientPen, rect, geometry) is { } intersectionDetail) + Hit(intersectionDetail); } public void OnDrawEllipse(IBrush? serverBrush, IPen? serverPen, IPen? clientPen, Rect rect) { - if (Live && HitTestEllipse(serverBrush, clientPen, rect, Current)) + if (!Live) + return; + + if (CurrentPoint is { } point && HitTestEllipse(serverBrush, clientPen, rect, point)) Hit(); + + else if (_renderedGeometry is { } geometry && HitTestEllipse(serverBrush, clientPen, rect, geometry) is { } intersectionDetail) + Hit(intersectionDetail); } public void OnDrawGeometry(IBrush? serverBrush, IPen? serverPen, IPen? clientPen, IGeometryImpl? geometry) { - if (Live && geometry != null && - ((serverBrush != null && geometry.FillContains(Current)) || - (clientPen != null && geometry.StrokeContains(clientPen, Current)))) + if (!Live || geometry == null) + return; + + if (CurrentPoint is { } point && + ((serverBrush != null && geometry.FillContains(point)) || + (clientPen != null && geometry.StrokeContains(clientPen, point)))) Hit(); + + else if (_renderedGeometry is { } currentGeometry && + serverBrush != null && currentGeometry.PlatformImpl != null && + GetRenderedGeometry(geometry, clientPen) is { } renderedGeometry && + renderedGeometry.GetFillIntersectionResult(currentGeometry.PlatformImpl) is { } intersectionDetail) + Hit(intersectionDetail); } public void OnDrawGlyphRun(IBrush? serverBrush, IRef? glyphRun) { - if (Live && glyphRun != null && glyphRun.Item.Bounds.ContainsExclusive(Current)) + if (!Live || glyphRun == null) + return; + + if (CurrentPoint is { } point && glyphRun.Item.Bounds.ContainsExclusive(point)) Hit(); + + else if (_renderedGeometry is { } geometry && GetIntersectionDetail(glyphRun.Item.Bounds, geometry.Bounds) is { } intersectionDetail) + Hit(intersectionDetail); } public void OnDrawBitmap(IRef? bitmap, double opacity, Rect sourceRect, Rect destRect) { - if (Live && destRect.Contains(Current)) + if (!Live) + return; + + if (CurrentPoint is { } point && destRect.Contains(point)) Hit(); + + else if (_renderedGeometry is { } geometry && GetIntersectionDetail(destRect, geometry.Bounds) is { } intersectionDetail) + Hit(intersectionDetail); } public void OnDrawCustom(ICustomDrawOperation? operation) { - if (Live && operation != null && operation.HitTest(Current)) + if (!Live) + return; + + if (CurrentPoint is { } point && operation != null && operation.HitTest(point)) Hit(); + + else if (_renderedGeometry is { } geometry && operation != null && operation.HitTest(geometry) is { } intersectionDetail) + Hit(intersectionDetail); + } + + private IntersectionResult GetIntersectionDetail(Rect firstRect, Rect secondRect) + { + if (firstRect.Contains(secondRect)) + return IntersectionResult.FullyContains; + + if (secondRect.Contains(secondRect)) + return IntersectionResult.FullyInside; + + if (firstRect.Intersects(secondRect)) + return IntersectionResult.Intersects; + + return IntersectionResult.Empty; } public HitTestScope OnPushClip(RoundedRect clip) { var scope = new HitTestScope { SavedLive = Live }; - if (Live && !clip.Rect.Contains(Current)) - Live = false; + + if (Live) + { + if ((CurrentPoint is { } point && !clip.Rect.Contains(point)) || + (_renderedGeometry is { } geometry && !clip.Rect.Contains(geometry.Bounds))) + Live = false; + } + return scope; } public HitTestScope OnPushGeometryClip(IGeometryImpl? geometry) { var scope = new HitTestScope { SavedLive = Live }; - if (Live && geometry != null && !geometry.FillContains(Current)) - Live = false; + if (Live && geometry != null) + { + if ((CurrentPoint is { } point && !geometry.FillContains(point)) || (_renderedGeometry is { } currentGeometry && currentGeometry.PlatformImpl != null && + geometry.GetFillIntersectionResult(currentGeometry.PlatformImpl) > IntersectionResult.Empty)) + Live = false; + } return scope; } @@ -112,8 +213,18 @@ internal partial class RenderDataStream if (matrix.TryInvert(out var inverted)) { scope.RestorePoint = true; - scope.SavedPoint = Current; - Current = Current.Transform(inverted); + if (CurrentPoint is { } point) + { + scope.SavedPoint = point; + CurrentPoint = point.Transform(inverted); + } + else if (CurrentGeometry != null) + { + _savedGeometries?.Push(CurrentGeometry); + CurrentGeometry = CurrentGeometry.Clone(); + CurrentGeometry.Transform = new MatrixTransform((CurrentGeometry.Transform?.Value ?? Matrix.Identity) * inverted); + _renderedGeometry?.Transform = CurrentGeometry.Transform; + } } else Live = false; @@ -134,7 +245,10 @@ internal partial class RenderDataStream { Live = scope.SavedLive; if (scope.RestorePoint) - Current = scope.SavedPoint; + { + CurrentPoint = scope.SavedPoint; + CurrentGeometry = _savedGeometries?.Pop(); + } } } @@ -145,6 +259,13 @@ internal partial class RenderDataStream return visitor.HitFound; } + public IntersectionResult HitTest(Geometry geometry) + { + var visitor = new HitTestVisitor(geometry); + Visit(ref visitor); + return visitor.HitResult; + } + private static bool HitTestLine(IPen? clientPen, Point p1, Point p2, Point p) { if (clientPen == null) @@ -176,6 +297,14 @@ internal partial class RenderDataStream return Math.Abs(distance) <= halfThickness; } + private static IntersectionResult? HitTestLine(IPen? clientPen, Point p1, Point p2, Geometry geometry) + { + if (clientPen == null) + return IntersectionResult.NotCalculated; + + return geometry.GetFillIntersectionResult(new LineGeometry(p1, p2)); + } + private static bool HitTestRectangle(IBrush? serverBrush, IPen? clientPen, RoundedRect rect, Point p) { var strokeThicknessAdjustment = (clientPen?.Thickness / 2) ?? 0; @@ -208,6 +337,35 @@ internal partial class RenderDataStream return false; } + private static IntersectionResult? HitTestRectangle(IBrush? serverBrush, IPen? clientPen, RoundedRect rect, Geometry geometry) + { + var strokeThicknessAdjustment = (clientPen?.Thickness / 2) ?? 0; + + if (rect.IsRounded) + { + var outer = rect.Inflate(strokeThicknessAdjustment, strokeThicknessAdjustment); + return new RectangleGeometry(outer.Rect, outer.RadiiTopLeft.X, outer.RadiiTopLeft.Y).GetFillIntersectionResult(geometry); + } + else + { + var outer = rect.Rect.Inflate(strokeThicknessAdjustment); + return new RectangleGeometry(outer).GetFillIntersectionResult(geometry); + } + } + + private static readonly IPen s_defaultStokePen = new Pen(); + + private static Geometry? GetRenderedGeometry(Geometry? geometry, IPen? pen) + { + return geometry == null ? null : new CombinedGeometry(geometry.GetWidenedGeometry(pen ?? s_defaultStokePen), geometry); + } + + private static IGeometryImpl? GetRenderedGeometry(IGeometryImpl? geometry, IPen? pen) + { + return geometry == null ? null : new CombinedGeometry(new ImmutableGeometry(geometry.GetWidenedGeometry(pen ?? s_defaultStokePen)), + new ImmutableGeometry(geometry)).PlatformImpl; + } + private static bool HitTestEllipse(IBrush? serverBrush, IPen? clientPen, Rect rect, Point p) { var center = rect.Center; @@ -240,6 +398,19 @@ internal partial class RenderDataStream return false; } + private static IntersectionResult? HitTestEllipse(IBrush? serverBrush, IPen? clientPen, Rect rect, Geometry geometry) + { + var center = rect.Center; + var strokeThickness = clientPen?.Thickness ?? 0; + + var rx = rect.Width / 2 + strokeThickness / 2; + var ry = rect.Height / 2 + strokeThickness / 2; + + var ellipse = new EllipseGeometry(rect); + + return ellipse.GetFillIntersectionResult(geometry); + } + private static bool EllipseContains(double dx, double dy, double radiusX, double radiusY) { var rx2 = radiusX * radiusX; diff --git a/src/Avalonia.Base/Rendering/Composition/CompositionHitTestAabbTree.cs b/src/Avalonia.Base/Rendering/Composition/HitTesting/CompositionHitTestAabbTree.cs similarity index 95% rename from src/Avalonia.Base/Rendering/Composition/CompositionHitTestAabbTree.cs rename to src/Avalonia.Base/Rendering/Composition/HitTesting/CompositionHitTestAabbTree.cs index f42c46a4a7..2cf6ff6e02 100644 --- a/src/Avalonia.Base/Rendering/Composition/CompositionHitTestAabbTree.cs +++ b/src/Avalonia.Base/Rendering/Composition/HitTesting/CompositionHitTestAabbTree.cs @@ -4,9 +4,10 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Avalonia.Collections.Pooled; +using Avalonia.Media; using Avalonia.Platform; -namespace Avalonia.Rendering.Composition; +namespace Avalonia.Rendering.Composition.HitTesting; internal sealed class CompositionHitTestAabbTree { @@ -104,7 +105,8 @@ internal sealed class CompositionHitTestAabbTree RemoveBucketIfEmpty(oldBucket); } - public void Query(Point point, PooledList results, ulong readbackRevision) + public void Query(T input, PooledList results, ulong readbackRevision) + where THitTester : struct, ICompositionHitTester { var candidates = ArrayPool.Shared.Rent(OrderBucketSize); var stack = ArrayPool.Shared.Rent(16); @@ -122,7 +124,7 @@ internal sealed class CompositionHitTestAabbTree candidateCount = 0; var stackCount = 0; - QueryBucket(bucket, point, ref candidates, ref candidateCount, ref stack, ref stackCount); + QueryBucket(bucket, input, ref candidates, ref candidateCount, ref stack, ref stackCount); candidates.AsSpan(0, candidateCount).Sort(s_candidateComparer); for (var j = 0; j < candidateCount; j++) @@ -139,8 +141,16 @@ internal sealed class CompositionHitTestAabbTree } } - public CompositionVisual? QueryFirst(CompositionTarget target, Point point, Func? filter, Func? resultFilter, ulong readbackRevision) + public CompositionVisual? QueryFirst( + CompositionTarget target, + T input, + Func? filter, + Func? resultFilter, + ulong readbackRevision, + out IntersectionResult intersectionResult) + where THitTester : struct, ICompositionHitTester { + intersectionResult = IntersectionResult.NotCalculated; var candidates = ArrayPool.Shared.Rent(OrderBucketSize); var stack = ArrayPool.Shared.Rent(16); var candidateCount = 0; @@ -157,12 +167,12 @@ internal sealed class CompositionHitTestAabbTree candidateCount = 0; var stackCount = 0; - QueryBucket(bucket, point, ref candidates, ref candidateCount, ref stack, ref stackCount); + QueryBucket(bucket, input, ref candidates, ref candidateCount, ref stack, ref stackCount); candidates.AsSpan(0, candidateCount).Sort(s_candidateComparer); for (var j = 0; j < candidateCount; j++) { - var hit = target.HitTestFirstCore(candidates[j].Visual, point, filter, resultFilter); + var hit = target.HitTestFirstCore(candidates[j].Visual, input, filter, resultFilter, out intersectionResult); if (hit != null) return hit; } @@ -241,7 +251,14 @@ internal sealed class CompositionHitTestAabbTree AddUnbounded(visual, entry.Order, ref entry); } - private void QueryBucket(Bucket bucket, Point point, ref Candidate[] candidates, ref int candidateCount, ref int[] stack, ref int stackCount) + private void QueryBucket( + Bucket bucket, + T input, + ref Candidate[] candidates, + ref int candidateCount, + ref int[] stack, + ref int stackCount) + where THitTester : struct, ICompositionHitTester { PushQueryNode(ref stack, ref stackCount, bucket.Root); @@ -250,7 +267,7 @@ internal sealed class CompositionHitTestAabbTree var nodeIndex = stack[--stackCount]; var node = _nodes[nodeIndex]; - if (!node.Bounds.Contains(point)) + if (!THitTester.TransformedSubTreeBoundsMatch(node.Bounds, input)) continue; if (node.IsLeaf) diff --git a/src/Avalonia.Base/Rendering/Composition/HitTesting/GeometryCompositionHitTester.cs b/src/Avalonia.Base/Rendering/Composition/HitTesting/GeometryCompositionHitTester.cs new file mode 100644 index 0000000000..a851c06fe6 --- /dev/null +++ b/src/Avalonia.Base/Rendering/Composition/HitTesting/GeometryCompositionHitTester.cs @@ -0,0 +1,33 @@ +using Avalonia.Media; +using Avalonia.Platform; + +namespace Avalonia.Rendering.Composition.HitTesting; + +internal struct GeometryCompositionHitTester : ICompositionHitTester +{ + public static Geometry Transform(Geometry input, in Matrix matrix) + { + var result = input.Clone(); + result.Transform = new MatrixTransform((input.Transform?.Value ?? Matrix.Identity) * matrix); + return result; + } + + public static IntersectionResult HitTest(CompositionVisual visual, Geometry input) + => visual.HitTest(input); + + public static bool TransformedSubTreeBoundsMatch(LtrbRect bounds, Geometry input) + { + var geometryRenderBounds = input.Bounds; + return bounds.Intersects(new LtrbRect(geometryRenderBounds)); + } + + public static bool ClippedBoundsMatch(CompositionVisual visual, Geometry input) + { + var bounds = input.Bounds; + return bounds.Width > 0 && bounds.Height > 0 && bounds.Intersects(new Rect(new Size(visual.Size.X, visual.Size.Y))); + } + + public static bool ClipMatches(IGeometryImpl clip, Geometry input) + => input.PlatformImpl is { } geometryImpl && + clip.GetFillIntersectionResult(geometryImpl) > IntersectionResult.Empty; +} diff --git a/src/Avalonia.Base/Rendering/Composition/HitTesting/ICompositionHitTester.cs b/src/Avalonia.Base/Rendering/Composition/HitTesting/ICompositionHitTester.cs new file mode 100644 index 0000000000..91818923ea --- /dev/null +++ b/src/Avalonia.Base/Rendering/Composition/HitTesting/ICompositionHitTester.cs @@ -0,0 +1,17 @@ +using Avalonia.Media; +using Avalonia.Platform; + +namespace Avalonia.Rendering.Composition.HitTesting; + +internal interface ICompositionHitTester +{ + static abstract T Transform(T input, in Matrix matrix); + + static abstract IntersectionResult HitTest(CompositionVisual visual, T input); + + static abstract bool TransformedSubTreeBoundsMatch(LtrbRect bounds, T input); + + static abstract bool ClippedBoundsMatch(CompositionVisual visual, T input); + + static abstract bool ClipMatches(IGeometryImpl clip, T input); +} diff --git a/src/Avalonia.Base/Rendering/Composition/HitTesting/PointCompositionHitTester.cs b/src/Avalonia.Base/Rendering/Composition/HitTesting/PointCompositionHitTester.cs new file mode 100644 index 0000000000..7a4be96419 --- /dev/null +++ b/src/Avalonia.Base/Rendering/Composition/HitTesting/PointCompositionHitTester.cs @@ -0,0 +1,22 @@ +using Avalonia.Media; +using Avalonia.Platform; + +namespace Avalonia.Rendering.Composition.HitTesting; + +internal struct PointCompositionHitTester : ICompositionHitTester +{ + public static Point Transform(Point input, in Matrix matrix) + => input.Transform(matrix); + + public static IntersectionResult HitTest(CompositionVisual visual, Point input) + => visual.HitTest(input) ? IntersectionResult.FullyContains : IntersectionResult.Empty; + + public static bool TransformedSubTreeBoundsMatch(LtrbRect bounds, Point input) + => bounds.Contains(input); + + public static bool ClippedBoundsMatch(CompositionVisual visual, Point input) + => input.X >= 0 && input.Y >= 0 && input.X <= visual.Size.X && input.Y <= visual.Size.Y; + + public static bool ClipMatches(IGeometryImpl clip, Point input) + => clip.FillContains(input); +} diff --git a/src/Avalonia.Base/Rendering/Composition/Visual.cs b/src/Avalonia.Base/Rendering/Composition/Visual.cs index 6134d48220..b67adcc800 100644 --- a/src/Avalonia.Base/Rendering/Composition/Visual.cs +++ b/src/Avalonia.Base/Rendering/Composition/Visual.cs @@ -1,9 +1,6 @@ -using System; -using System.Numerics; using Avalonia.Media; using Avalonia.Rendering.Composition.Drawing; using Avalonia.Rendering.Composition.Server; -using Avalonia.VisualTree; namespace Avalonia.Rendering.Composition { @@ -102,5 +99,6 @@ namespace Avalonia.Rendering.Composition internal object? Tag { get; set; } internal virtual bool HitTest(Point point) => true; + internal virtual IntersectionResult HitTest(Geometry geometry) => IntersectionResult.Intersects; } } diff --git a/src/Avalonia.Base/Rendering/ICustomHitTest.cs b/src/Avalonia.Base/Rendering/ICustomHitTest.cs index 65bb24b4b3..003576606a 100644 --- a/src/Avalonia.Base/Rendering/ICustomHitTest.cs +++ b/src/Avalonia.Base/Rendering/ICustomHitTest.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using System.Linq; -using Avalonia.VisualTree; +using Avalonia.Media; namespace Avalonia.Rendering { @@ -12,5 +10,19 @@ namespace Avalonia.Rendering { /// The point to hit test in global coordinate space. bool HitTest(Point point); + + /// + /// Hit test the geometry in this node. + /// + /// The geometry in global coordinates. + /// The describing the intersecting between the hit geometry and the node's geometry. + /// + /// This method does not recurse to childs, if you want + /// to hit test children they must be hit tested manually. + /// + IntersectionResult HitTest(Geometry geometry) + { + return IntersectionResult.Empty; + } } } diff --git a/src/Avalonia.Base/Rendering/IRenderer.cs b/src/Avalonia.Base/Rendering/IRenderer.cs index bc69f90aa5..4948e06f5a 100644 --- a/src/Avalonia.Base/Rendering/IRenderer.cs +++ b/src/Avalonia.Base/Rendering/IRenderer.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Avalonia.Media; using Avalonia.Metadata; using Avalonia.Rendering.Composition; @@ -93,11 +94,34 @@ namespace Avalonia.Rendering /// The visuals at the specified point, topmost first. IEnumerable HitTest(Point p, Visual root, Func? filter); + /// + /// Hit tests a geometry to find the visuals intersecting a region. + /// + /// + /// ⚠️ This method is low-level and DOES NOT respect . + /// Use to perform input hit testing, or provide your own function. + /// + /// The geometry, in coordinates relative to + /// The root of the subtree to search. + /// + /// A filter predicate. If the predicate returns false then the visual and all its + /// children will be excluded from the results. + /// + /// The visuals intersecting the specified geometry, topmost first. + IEnumerable HitTest(Geometry geometry, Visual root, Func filter); + /// /// Hit tests a location to find first visual at the specified point. /// /// /// The visual at the specified point, topmost first. Visual? HitTestFirst(Point p, Visual root, Func? filter); + + /// + /// Hit tests a geometry to find the visuals intersecting a region. + /// + /// + /// The visuals intersecting the specified geometry, topmost first. + GeometryHitTestResult? HitTestFirst(Geometry geometry, Visual root, Func? filter); } } diff --git a/src/Avalonia.Base/Rendering/SceneGraph/CustomDrawOperation.cs b/src/Avalonia.Base/Rendering/SceneGraph/CustomDrawOperation.cs index a3ee957bbe..60714bdcc8 100644 --- a/src/Avalonia.Base/Rendering/SceneGraph/CustomDrawOperation.cs +++ b/src/Avalonia.Base/Rendering/SceneGraph/CustomDrawOperation.cs @@ -1,7 +1,5 @@ using System; -using Avalonia.Logging; using Avalonia.Media; -using Avalonia.Platform; namespace Avalonia.Rendering.SceneGraph { @@ -23,6 +21,20 @@ namespace Avalonia.Rendering.SceneGraph /// bool HitTest(Point p); + /// + /// Hit test the geometry in this node. + /// + /// The geometry in global coordinates. + /// The describing the intersecting between the hit geometry and the node's geometry. + /// + /// This method does not recurse to childs, if you want + /// to hit test children they must be hit tested manually. + /// + IntersectionResult HitTest(Geometry geometry) + { + return IntersectionResult.Empty; + } + /// /// Renders the node to a drawing context. /// diff --git a/src/Avalonia.Base/VisualTree/VisualExtensions.cs b/src/Avalonia.Base/VisualTree/VisualExtensions.cs index 2007d39f7d..9cc1d9e673 100644 --- a/src/Avalonia.Base/VisualTree/VisualExtensions.cs +++ b/src/Avalonia.Base/VisualTree/VisualExtensions.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Runtime.CompilerServices; using Avalonia.Layout; +using Avalonia.Media; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Utilities; @@ -319,6 +318,19 @@ namespace Avalonia.VisualTree return visual.GetVisualAt(p, x => x.IsVisible); } + /// + /// Gets the first visual in the visual tree whose bounds intersects a geometry. + /// + /// The root visual to test. + /// The geometry. + /// A containing the visual intersecting the requested geometry and intersection details, or null if no intersection. + public static GeometryHitTestResult? GetVisualAt(this Visual visual, Geometry geometry) + { + ThrowHelper.ThrowIfNull(visual, nameof(visual)); + + return visual.GetVisualAt(geometry, x => x.IsVisible); + } + /// /// Gets the first visual in the visual tree whose bounds contain a point. /// @@ -342,6 +354,29 @@ namespace Avalonia.VisualTree return source.HitTester.HitTestFirst(p, visual, filter); } + /// + /// Gets the first visual in the visual tree whose bounds intersects a geometry. + /// + /// The root visual to test. + /// The geometry. + /// + /// A filter predicate. If the predicate returns false then the visual and all its + /// children will be excluded from the results. + /// + /// A containing the visual intersecting the requested geometry and intersection details, or null if no intersection. + public static GeometryHitTestResult? GetVisualAt(this Visual visual, Geometry geometry, Func filter) + { + ThrowHelper.ThrowIfNull(visual, nameof(visual)); + + var source = visual.GetPresentationSource(); + if (source is null) + { + return null; + } + + return source.HitTester.HitTestFirst(geometry, visual, filter); + } + /// /// Enumerates the visible visuals in the visual tree whose bounds contain a point. /// @@ -357,6 +392,21 @@ namespace Avalonia.VisualTree return visual.GetVisualsAt(p, x => x.IsVisible); } + /// + /// Enumerates the visible visuals in the visual tree whose bounds intersects a geometry. + /// + /// The root visual to test. + /// The geometry. + /// The visuals intersecting the requested geometry with intersection details. + public static IEnumerable GetVisualsAt( + this Visual visual, + Geometry geometry) + { + ThrowHelper.ThrowIfNull(visual, nameof(visual)); + + return visual.GetVisualsAt(geometry, x => x.IsVisible); + } + /// /// Enumerates the visuals in the visual tree whose bounds contain a point. /// @@ -384,6 +434,33 @@ namespace Avalonia.VisualTree return source.HitTester.HitTest(p, visual, filter); } + /// + /// Enumerates the visible visuals in the visual tree whose bounds intersects a geometry. + /// + /// The root visual to test. + /// The geometry. + /// + /// A filter predicate. If the predicate returns false then the visual and all its + /// children will be excluded from the results. + /// + /// The visuals intersecting the requested geometry with intersection details. + public static IEnumerable GetVisualsAt( + this Visual visual, + Geometry geometry, + Func filter) + { + ThrowHelper.ThrowIfNull(visual, nameof(visual)); + + var source = visual.GetPresentationSource(); + + if (source is null) + { + return Array.Empty(); + } + + return source.HitTester.HitTest(geometry, visual, filter); + } + /// /// Enumerates the children of an in the visual tree. /// diff --git a/src/Headless/Avalonia.Headless/HeadlessPlatformRenderInterface.cs b/src/Headless/Avalonia.Headless/HeadlessPlatformRenderInterface.cs index 0d8114f7f5..9ea479d48d 100644 --- a/src/Headless/Avalonia.Headless/HeadlessPlatformRenderInterface.cs +++ b/src/Headless/Avalonia.Headless/HeadlessPlatformRenderInterface.cs @@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.InteropServices; +using Avalonia.Layout; using Avalonia.Media; using Avalonia.Media.Imaging; using Avalonia.Media.TextFormatting; @@ -43,7 +44,7 @@ namespace Avalonia.Headless public IGeometryImpl CreateRectangleGeometry(Rect rect) { - return new HeadlessGeometryStub(rect); + return new HeadlessRectangleGeometryContextStub(rect); } public IStreamGeometryImpl CreateStreamGeometry() => new HeadlessStreamingGeometryStub(); @@ -224,10 +225,32 @@ namespace Avalonia.Headless segmentGeometry = null; return false; } + + public virtual IntersectionResult GetFillIntersectionResult(IGeometryImpl geometry) + { + var intersection = Intersect(geometry); + + if (intersection?.Bounds.Size != new Size()) + { + var bounds = GetRenderBounds(null); + var otherBounds = geometry.GetRenderBounds(null); + + if (bounds.Contains(otherBounds)) + return IntersectionResult.FullyContains; + + if (otherBounds.Contains(bounds)) + return IntersectionResult.FullyInside; + + return IntersectionResult.Intersects; + } + + return IntersectionResult.Empty; + } } - private class HeadlessTransformedGeometryStub : HeadlessGeometryStub, ITransformedGeometryImpl + private class HeadlessTransformedGeometryStub : HeadlessGeometryStub, ITransformedGeometryImpl, IHeadlessGeometryWithEdges { + private List? _points; public HeadlessTransformedGeometryStub(IGeometryImpl b, Matrix transform) : this(Fix(b, transform)) { @@ -253,12 +276,103 @@ namespace Avalonia.Headless public IGeometryImpl SourceGeometry { get; } public Matrix Transform { get; } + + public List Points + { + get + { + if (SourceGeometry is IHeadlessGeometryWithEdges geometryWithEdges) + { + return _points ??= geometryWithEdges.Points.Select(x => x.Transform(Transform)).ToList(); + } + + return []; + } + } + } + + private class HeadlessRectangleGeometryContextStub : HeadlessGeometryStub, IHeadlessGeometryWithEdges + { + private List _points = new List(); + public HeadlessRectangleGeometryContextStub(Rect bounds) : base(bounds) + { + _points.Add(bounds.TopLeft); + _points.Add(bounds.TopRight); + _points.Add(bounds.BottomLeft); + _points.Add(bounds.BottomRight); + } + + public List Points => _points; + + public override IntersectionResult GetFillIntersectionResult(IGeometryImpl geometry) + { + if (geometry is IHeadlessGeometryWithEdges stub) + { + var axes = (this as IHeadlessGeometryWithEdges).GetAxes(); + axes.AddRange(stub.GetAxes()); + + foreach (var axis in axes) + { + var (min, max) = (this as IHeadlessGeometryWithEdges).ProjectionOnAxis(axis); + var projection2 = stub.ProjectionOnAxis(axis); + + if (max < projection2.min || projection2.max < min) + return IntersectionResult.Empty; + } + + return IntersectionResult.Intersects; + } + + return base.GetFillIntersectionResult(geometry); + } + } + + internal interface IHeadlessGeometryWithEdges + { + List Points { get; } + + public (double min, double max) ProjectionOnAxis(Vector axis) + { + double min = double.PositiveInfinity, max = double.NegativeInfinity; + + foreach (var point in Points) + { + var p = Vector.Dot(axis, new Vector(point.X, point.Y)); + + if (p < min) + { + min = p; + } + + if (p > max) + { + max = p; + } + } + + return (min, max); + } + + public List GetAxes() + { + List axes = new List(); + + for (var i = 0; i < Points.Count; i++) + { + var point = Points[i]; + var otherPoint = Points[(i + i) % Points.Count]; + var edge = new Vector(point.X - otherPoint.X, point.Y - otherPoint.Y); + axes.Add(new Vector(-edge.Y, edge.X)); + } + + return axes; + } } private class HeadlessStreamingGeometryStub : HeadlessGeometryStub, IStreamGeometryImpl { private HeadlessStreamingGeometryContextStub _context; - + public HeadlessStreamingGeometryStub() : base(default) { _context = new HeadlessStreamingGeometryContextStub(this); @@ -279,10 +393,21 @@ namespace Avalonia.Headless return _context.FillContains(point); } - private class HeadlessStreamingGeometryContextStub : IStreamGeometryContextImpl + public override IntersectionResult GetFillIntersectionResult(IGeometryImpl geometry) + { + if (geometry is IHeadlessGeometryWithEdges stub) + return _context.FillContains(stub); + + return base.GetFillIntersectionResult(geometry); + } + + private class HeadlessStreamingGeometryContextStub : IStreamGeometryContextImpl, IHeadlessGeometryWithEdges { private readonly HeadlessStreamingGeometryStub _parent; - private List points = new List(); + private List _points = new List(); + + public List Points => _points; + public HeadlessStreamingGeometryContextStub(HeadlessStreamingGeometryStub parent) { _parent = parent; @@ -290,7 +415,7 @@ namespace Avalonia.Headless private void Track(Point pt) { - points.Add(pt); + _points.Add(pt); } public Rect CalculateBounds() @@ -300,7 +425,7 @@ namespace Avalonia.Headless var top = double.MaxValue; var bottom = double.MinValue; - foreach (var p in points) + foreach (var p in _points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); @@ -310,7 +435,7 @@ namespace Avalonia.Headless return new Rect(new Point(left, top), new Point(right, bottom)); } - + public void Dispose() { _parent.Bounds = CalculateBounds(); @@ -345,16 +470,16 @@ namespace Avalonia.Headless { } - + public bool FillContains(Point point) { // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) - for (int i = 0; i < points.Count; i++) + for (int i = 0; i < _points.Count; i++) { - var a = points[i]; - var b = points[(i + 1) % points.Count]; - var c = points[(i + 2) % points.Count]; + var a = _points[i]; + var b = _points[(i + 1) % _points.Count]; + var c = _points[(i + 2) % _points.Count]; Vector v0 = c - a; Vector v1 = b - a; @@ -370,10 +495,28 @@ namespace Avalonia.Headless var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; - if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; + if ((u >= 0) && (v >= 0) && (u + v < 1)) + return true; } return false; } + + public IntersectionResult FillContains(IHeadlessGeometryWithEdges geometry) + { + var axes = (this as IHeadlessGeometryWithEdges).GetAxes(); + axes.AddRange(geometry.GetAxes()); + + foreach (var axis in axes) + { + var (min, max) = (this as IHeadlessGeometryWithEdges).ProjectionOnAxis(axis); + var projection2 = geometry.ProjectionOnAxis(axis); + + if (max < projection2.min || projection2.max < min) + return IntersectionResult.Empty; + } + + return IntersectionResult.Intersects; + } } } diff --git a/src/Skia/Avalonia.Skia/GeometryImpl.cs b/src/Skia/Avalonia.Skia/GeometryImpl.cs index 7412ed72a7..c7c971911c 100644 --- a/src/Skia/Avalonia.Skia/GeometryImpl.cs +++ b/src/Skia/Avalonia.Skia/GeometryImpl.cs @@ -3,7 +3,6 @@ using System.Diagnostics.CodeAnalysis; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Skia.Helpers; -using Avalonia.Utilities; using SkiaSharp; namespace Avalonia.Skia @@ -171,6 +170,28 @@ namespace Avalonia.Skia } } + /// + public IntersectionResult GetFillIntersectionResult(IGeometryImpl geometry) + { + var other = geometry as GeometryImpl; + if (other == null || FillPath == null || other.FillPath == null) + return IntersectionResult.Empty; + + var region = new SKRegion(FillPath); + var otherRegion = new SKRegion(other.FillPath); + + if(region.Contains(otherRegion)) + return IntersectionResult.FullyInside; + + if (otherRegion.Contains(region)) + return IntersectionResult.FullyContains; + + if (region.Intersects(otherRegion)) + return IntersectionResult.Intersects; + + return IntersectionResult.Empty; + } + private struct PathCache : IDisposable { private int _penHash; diff --git a/tests/Avalonia.Base.UnitTests/Rendering/CompositorHitTestingTests.cs b/tests/Avalonia.Base.UnitTests/Rendering/CompositorHitTestingTests.cs index 9dbb446bdc..99827bbce3 100644 --- a/tests/Avalonia.Base.UnitTests/Rendering/CompositorHitTestingTests.cs +++ b/tests/Avalonia.Base.UnitTests/Rendering/CompositorHitTestingTests.cs @@ -1,24 +1,18 @@ using System; using System.Linq; -using Avalonia.Base.UnitTests.VisualTree; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Shapes; using Avalonia.Layout; using Avalonia.Media; -using Avalonia.Platform; -using Avalonia.Rendering; using Avalonia.Rendering.Composition; using Avalonia.UnitTests; -using Avalonia.VisualTree; -using Moq; using Xunit; namespace Avalonia.Base.UnitTests.Rendering; public class CompositorHitTestingTests : CompositorTestsBase { - [Fact] public void HitTest_Should_Find_Controls_At_Point() { @@ -34,11 +28,31 @@ public class CompositorHitTestingTests : CompositorTestsBase }; s.TopLevel.Content = border; - + s.AssertHitTest(new Point(100, 100), null, border); } } + [Fact] + public void HitTest_Should_Find_Controls_At_Geometry() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + var border = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + s.TopLevel.Content = border; + + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 50, 50)), null, new GeometryHitTestResult(border, IntersectionResult.FullyContains)); + } + } + [Fact] public void HitTest_Should_Not_Find_Empty_Controls_At_Point() { @@ -58,6 +72,25 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Should_Not_Find_Empty_Controls_At_Geometry() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + var border = new Border + { + Width = 100, + Height = 100, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + s.TopLevel.Content = border; + + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 50, 50)), null); + } + } + [Fact] public void HitTest_Should_Not_Find_Invisible_Controls_At_Point() { @@ -83,7 +116,33 @@ public class CompositorHitTestingTests : CompositorTestsBase s.AssertHitTest(new Point(100, 100), null); } } - + + [Fact] + public void HitTest_Should_Not_Find_Invisible_Controls_At_Geometry() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border visible, border; + s.TopLevel.Content = border = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + IsVisible = false, + Child = visible = new Border + { + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Stretch, + } + }; + + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 50, 50)), null); + } + } + [Theory, InlineData(false, false), InlineData(true, false), @@ -92,7 +151,7 @@ public class CompositorHitTestingTests : CompositorTestsBase ] public void HitTest_Should_Find_Zero_Opacity_Controls_At_Point(bool parent, bool child) { - + using (var s = new CompositorTestServices(new Size(200, 200))) { Border visible, border; @@ -116,7 +175,42 @@ public class CompositorHitTestingTests : CompositorTestsBase s.AssertHitTest(new Point(100, 100), null, visible, border); } } - + + [Theory, + InlineData(false, false), + InlineData(true, false), + InlineData(false, true), + InlineData(true, true), + ] + public void HitTest_Should_Find_Zero_Opacity_Controls_At_Geometry(bool parent, bool child) + { + + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border visible, border; + s.TopLevel.Content = border = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Opacity = parent ? 0 : 1, + Child = visible = new Border + { + Opacity = child ? 0 : 1, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Stretch, + } + }; + + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 50, 50)), null, + new GeometryHitTestResult(visible, IntersectionResult.FullyContains), + new GeometryHitTestResult(border, IntersectionResult.FullyContains)); + } + } + [Fact] public void HitTest_Should_Not_Find_Control_Outside_Point() { @@ -137,6 +231,26 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Should_Not_Find_Control_Outside_Geometry() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + var border = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + + }; + s.TopLevel.Content = border; + + s.AssertHitTest(new RectangleGeometry(new Rect(10, 10, 10, 10)), null); + } + } + [Fact] public void HitTest_Should_Return_Top_Controls_First() { @@ -172,6 +286,43 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Should_Return_Top_Controls_First() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Panel container = new Panel + { + Width = 200, + Height = 200, + Children = + { + new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }, + new Border + { + Width = 50, + Height = 50, + Background = Brushes.Blue, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + } + } + }; + s.TopLevel.Content = container; + + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 50, 50)), null, + new GeometryHitTestResult(container.Children[1], IntersectionResult.Intersects), + new GeometryHitTestResult(container.Children[0], IntersectionResult.FullyContains)); + } + } + [Fact] public void HitTest_Should_Return_Top_Controls_First_With_ZIndex() { @@ -218,6 +369,54 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Should_Return_Top_Controls_First_With_ZIndex() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Panel container = new Panel + { + Width = 200, + Height = 200, + Children = + { + new Border + { + Width = 100, + Height = 100, + ZIndex = 1, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }, + new Border + { + Width = 50, + Height = 50, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }, + new Border + { + Width = 75, + Height = 75, + ZIndex = 2, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + } + } + + }; + s.TopLevel.Content = container; + + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 50, 50)), null, new GeometryHitTestResult(container.Children[2], IntersectionResult.Intersects), + new GeometryHitTestResult(container.Children[0], IntersectionResult.FullyContains), + new GeometryHitTestResult(container.Children[1], IntersectionResult.Intersects)); + } + } + [Fact] public void HitTest_Should_Find_Control_Translated_Outside_Parent_Bounds() { @@ -258,6 +457,47 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Find_Control_Translated_Outside_Parent_Bounds() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border target; + Panel container = new Panel + { + Width = 200, + Height = 200, + Background = Brushes.Red, + ClipToBounds = false, + Children = + { + new Border + { + Width = 100, + Height = 100, + ZIndex = 1, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Top, + Child = target = new Border + { + Width = 50, + Height = 50, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Top, + RenderTransform = new TranslateTransform(110, 110), + } + }, + } + }; + s.TopLevel.Content = container; + + s.AssertHitTest(new RectangleGeometry(new Rect(120, 120, 50, 50)), null, new GeometryHitTestResult(target, IntersectionResult.Intersects), + new GeometryHitTestResult(container, IntersectionResult.FullyContains)); + } + } + [Fact] public void HitTest_Should_Not_Find_Control_Outside_Parent_Bounds_When_Clipped() { @@ -299,14 +539,11 @@ public class CompositorHitTestingTests : CompositorTestsBase } [Fact] - public void HitTest_Should_Not_Find_Control_Outside_Scroll_Viewport() + public void HitTest_Geometry_Should_Not_Find_Control_Outside_Parent_Bounds_When_Clipped() { - using (var s = new CompositorTestServices(new Size(100, 200))) + using (var s = new CompositorTestServices(new Size(200, 200))) { Border target; - Border item1; - Border item2; - ScrollContentPresenter scroll; Panel container = new Panel { Width = 100, @@ -314,30 +551,73 @@ public class CompositorHitTestingTests : CompositorTestsBase Background = Brushes.Red, Children = { - (target = new Border() - { - Name = "b1", - Width = 100, - Height = 100, - Background = Brushes.Red, - }), - new Border() + new Panel() { - Name = "b2", Width = 100, Height = 100, Background = Brushes.Red, Margin = new Thickness(0, 100, 0, 0), - Child = scroll = new ScrollContentPresenter() + ClipToBounds = true, + Children = { - CanHorizontallyScroll = true, - CanVerticallyScroll = true, - Content = new StackPanel() + (target = new Border() { - Children = - { - (item1 = new Border() - { + Width = 100, + Height = 100, + Background = Brushes.Red, + Margin = new Thickness(0, -100, 0, 0) + }) + } + } + } + + }; + s.TopLevel.Content = container; + + s.AssertHitTest(new RectangleGeometry(new Rect(50, 50, 50, 50)), null, new GeometryHitTestResult(container, IntersectionResult.FullyContains)); + } + } + + [Fact] + public void HitTest_Should_Not_Find_Control_Outside_Scroll_Viewport() + { + using (var s = new CompositorTestServices(new Size(100, 200))) + { + Border target; + Border item1; + Border item2; + ScrollContentPresenter scroll; + Panel container = new Panel + { + Width = 100, + Height = 200, + Background = Brushes.Red, + Children = + { + (target = new Border() + { + Name = "b1", + Width = 100, + Height = 100, + Background = Brushes.Red, + }), + new Border() + { + Name = "b2", + Width = 100, + Height = 100, + Background = Brushes.Red, + Margin = new Thickness(0, 100, 0, 0), + Child = scroll = new ScrollContentPresenter() + { + CanHorizontallyScroll = true, + CanVerticallyScroll = true, + Content = new StackPanel() + { + Children = + { + (item1 = new Border() + { Name = "b3", Width = 100, Height = 100, @@ -359,16 +639,90 @@ public class CompositorHitTestingTests : CompositorTestsBase s.TopLevel.Content = container; scroll.UpdateChild(); - + s.AssertHitTestFirst(new Point(50, 150), null, item1); - s.AssertHitTestFirst(new Point(50,50), null, target); - + s.AssertHitTestFirst(new Point(50, 50), null, target); + scroll.Offset = new Vector(0, 100); s.AssertHitTestFirst(new Point(50, 150), null, item2); - - s.AssertHitTestFirst(new Point(50,50), null, target); + + s.AssertHitTestFirst(new Point(50, 50), null, target); + } + } + + [Fact] + public void HitTest_Geometry_Should_Not_Find_Control_Outside_Scroll_Viewport() + { + using (var s = new CompositorTestServices(new Size(100, 200))) + { + Border target; + Border item1; + Border item2; + ScrollContentPresenter scroll; + Panel container = new Panel + { + Width = 100, + Height = 200, + Background = Brushes.Red, + Children = + { + (target = new Border() + { + Name = "b1", + Width = 100, + Height = 100, + Background = Brushes.Red, + }), + new Border() + { + Name = "b2", + Width = 100, + Height = 100, + Background = Brushes.Red, + Margin = new Thickness(0, 100, 0, 0), + Child = scroll = new ScrollContentPresenter() + { + CanHorizontallyScroll = true, + CanVerticallyScroll = true, + Content = new StackPanel() + { + Children = + { + (item1 = new Border() + { + Name = "b3", + Width = 100, + Height = 100, + Background = Brushes.Red, + }), + (item2 = new Border() + { + Name = "b4", + Width = 100, + Height = 100, + Background = Brushes.Red, + }), + } + } + } + } + } + }; + s.TopLevel.Content = container; + + scroll.UpdateChild(); + + s.AssertHitTestFirst(new RectangleGeometry(new Rect(50, 150, 50, 50)), null, item1); + + s.AssertHitTestFirst(new RectangleGeometry(new Rect(50, 50, 50, 50)), null, target); + + scroll.Offset = new Vector(0, 100); + + s.AssertHitTestFirst(new RectangleGeometry(new Rect(50, 150, 50, 50)), null, item2); + + s.AssertHitTestFirst(new RectangleGeometry(new Rect(50, 50, 50, 50)), null, target); } } @@ -391,6 +745,25 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Should_Not_Find_Path_When_Outside_Fill() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Path path = new Path + { + Width = 200, + Height = 200, + Fill = Brushes.Red, + Data = new RectangleGeometry(new Rect(50, 50, 100, 100)) + }; + s.TopLevel.Content = path; + + s.AssertHitTest(new RectangleGeometry(new Rect(95, 95, 50, 50)), null, new GeometryHitTestResult(path, IntersectionResult.FullyContains)); + s.AssertHitTest(new RectangleGeometry(new Rect(0, 0, 10, 10)), null); + } + } + [Fact] public void HitTest_Should_Respect_Geometry_Clip() { @@ -415,12 +788,43 @@ public class CompositorHitTestingTests : CompositorTestsBase s.RunJobs(); Assert.Equal(new Rect(100, 100, 200, 200), border.Bounds); - s.AssertHitTest(new Point(200,200), null, canvas, border); + s.AssertHitTest(new Point(200, 200), null, canvas, border); s.AssertHitTest(new Point(110, 110), null); } } + [Fact] + public void HitTest_Geometry_Should_Respect_Geometry_Clip() + { + using (var s = new CompositorTestServices(new Size(400, 400))) + { + Canvas canvas; + Border border = new Border + { + Background = Brushes.Red, + Clip = StreamGeometry.Parse("M100,0 L0,100 100,100"), + Width = 200, + Height = 200, + Child = canvas = new Canvas + { + Background = Brushes.Yellow, + Margin = new Thickness(10), + } + + }; + s.TopLevel.Content = border; + + s.RunJobs(); + Assert.Equal(new Rect(100, 100, 200, 200), border.Bounds); + + s.AssertHitTest(new RectangleGeometry(new Rect(195, 195, 10, 10)), null, new GeometryHitTestResult(canvas, IntersectionResult.FullyContains), + new GeometryHitTestResult(border, IntersectionResult.FullyContains)); + + s.AssertHitTest(new RectangleGeometry(new Rect(110, 110, 10, 10)), null); + } + } + [Fact] public void HitTest_Should_Accommodate_ICustomHitTest() { @@ -437,13 +841,36 @@ public class CompositorHitTestingTests : CompositorTestsBase }; s.TopLevel.Content = border; - + s.AssertHitTest(75, 100, null, border); s.AssertHitTest(125, 100, null, border); s.AssertHitTest(175, 100, null); } } - + + [Fact] + public void HitTest_Geometry_Should_Accommodate_ICustomHitTest() + { + using (var s = new CompositorTestServices(new Size(300, 200))) + { + Border border = new CustomHitTestBorder + { + ClipToBounds = false, + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + s.TopLevel.Content = border; + + s.AssertHitTest(new RectangleGeometry(new Rect(75, 100, 10, 10)), null, new GeometryHitTestResult(border, IntersectionResult.Intersects)); + s.AssertHitTest(new RectangleGeometry(new Rect(125, 100, 10, 10)), null, new GeometryHitTestResult(border, IntersectionResult.Intersects)); + s.AssertHitTest(new RectangleGeometry(new Rect(175, 100, 10, 10)), null); + } + } + [Fact] public void Removing_ICustomHitTest_Child_Should_Restore_SubTree_Bounds_Optimization() { @@ -499,12 +926,35 @@ public class CompositorHitTestingTests : CompositorTestsBase }; s.TopLevel.Content = stackPanel; - + s.AssertHitTest(new Point(5, 10), null, targetRectangle); } } - - + + [Fact] + public void HitTest_Geometry_Should_Not_Hit_Controls_Next_Pixel() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border targetRectangle; + + var stackPanel = new StackPanel + { + Orientation = Orientation.Vertical, + HorizontalAlignment = HorizontalAlignment.Left, + Children = + { + new Border { Width = 10, Height = 10, Background= Brushes.Red}, + { targetRectangle = new Border { Width = 10, Height = 10, Background = Brushes.Green, Name = "Target"} } + } + }; + + s.TopLevel.Content = stackPanel; + + s.AssertHitTest(new RectangleGeometry(new Rect(5, 10, 10, 10)), null, new GeometryHitTestResult(targetRectangle, IntersectionResult.Intersects)); + } + } + [Fact] public void HitTest_Filter_Should_Filter_Out_Children() { @@ -531,6 +981,33 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Filter_Should_Filter_Out_Children() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border child, parent; + s.TopLevel.Content = parent = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Child = child = new Border + { + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Stretch, + } + }; + + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 10, 10)), null, new GeometryHitTestResult(child, IntersectionResult.FullyContains), + new GeometryHitTestResult(parent, IntersectionResult.FullyContains)); + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 10, 10)), v => v != parent); + } + } + [Fact] public void HitTestFirst_Should_Skip_Element_Child_Composition_Visual() { @@ -556,18 +1033,42 @@ public class CompositorHitTestingTests : CompositorTestsBase } [Fact] - public void HitTest_Should_Find_Control_With_Many_Siblings() + public void HitTestFirst_Geometry_Should_Skip_Element_Child_Composition_Visual() { - using (var s = new CompositorTestServices(new Size(1000, 200))) + using (var s = new CompositorTestServices(new Size(200, 200))) { - Border target = null!; - var canvas = new Canvas { Width = 1000, Height = 200 }; - - for (var i = 0; i < 70; i++) + var target = new Border { - var child = new Border { Width = 8, Height = 8, Background = Brushes.Red }; - Canvas.SetLeft(child, i * 12); - canvas.Children.Add(child); + Width = 200, + Height = 200, + Background = Brushes.Red + }; + + s.TopLevel.Content = target; + s.RunJobs(); + + var childVisual = s.Compositor.CreateSolidColorVisual(); + childVisual.Size = new Vector(200, 200); + childVisual.Color = Colors.Blue; + ElementComposition.SetElementChildVisual(target, childVisual); + + s.AssertHitTestFirst(new RectangleGeometry(new Rect(100, 100, 10, 10)), null, target); + } + } + + [Fact] + public void HitTest_Should_Find_Control_With_Many_Siblings() + { + using (var s = new CompositorTestServices(new Size(1000, 200))) + { + Border target = null!; + var canvas = new Canvas { Width = 1000, Height = 200 }; + + for (var i = 0; i < 70; i++) + { + var child = new Border { Width = 8, Height = 8, Background = Brushes.Red }; + Canvas.SetLeft(child, i * 12); + canvas.Children.Add(child); if (i == 0) target = child; @@ -578,6 +1079,29 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Should_Find_Control_With_Many_Siblings() + { + using (var s = new CompositorTestServices(new Size(1000, 200))) + { + Border target = null!; + var canvas = new Canvas { Width = 1000, Height = 200 }; + + for (var i = 0; i < 70; i++) + { + var child = new Border { Width = 8, Height = 8, Background = Brushes.Red, Name = $"{i}" }; + Canvas.SetLeft(child, i * 12); + canvas.Children.Add(child); + + if (i == 0) + target = child; + } + + s.TopLevel.Content = canvas; + s.AssertHitTestFirst(new RectangleGeometry(new Rect(4, 4, 2, 2)), null, target); + } + } + [Fact] public void HitTest_Should_Return_Top_Controls_First_With_Many_Overlapping_Siblings() { @@ -603,6 +1127,31 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Should_Return_Top_Controls_First_With_Many_Overlapping_Siblings() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border top = null!; + var canvas = new Canvas { Width = 200, Height = 200 }; + + for (var i = 0; i < 70; i++) + { + var child = new Border { Width = 100, Height = 100, Background = Brushes.Red }; + Canvas.SetLeft(child, 50); + Canvas.SetTop(child, 50); + canvas.Children.Add(child); + + if (i == 69) + top = child; + } + + s.TopLevel.Content = canvas; + s.AssertHitTestFirst(new RectangleGeometry(new Rect(100, 100, 10, 10)), null, top); + s.AssertHitTest(new RectangleGeometry(new Rect(100, 100, 10, 10)), null, canvas.Children.Cast().Reverse().Select(x => new GeometryHitTestResult(x, IntersectionResult.FullyContains)).ToArray()); + } + } + [Fact] public void HitTest_Should_Update_Many_Sibling_Index_When_Child_Moves() { @@ -630,6 +1179,33 @@ public class CompositorHitTestingTests : CompositorTestsBase } } + [Fact] + public void HitTest_Geometry_Should_Update_Many_Sibling_Index_When_Child_Moves() + { + using (var s = new CompositorTestServices(new Size(1000, 200))) + { + Border moving = null!; + var canvas = new Canvas { Width = 1000, Height = 200 }; + + for (var i = 0; i < 70; i++) + { + var child = new Border { Width = 8, Height = 8, Background = Brushes.Red }; + Canvas.SetLeft(child, i * 12); + canvas.Children.Add(child); + + if (i == 69) + moving = child; + } + + s.TopLevel.Content = canvas; + s.AssertHitTestFirst(new RectangleGeometry(new Rect(69 * 12 + 4, 4, 2, 2)), null, moving); + + Canvas.SetLeft(moving, 10); + Canvas.SetTop(moving, 100); + s.AssertHitTestFirst(new RectangleGeometry(new Rect(14, 104, 2, 2)), null, moving); + } + } + [Fact] public void HitTest_Should_Update_Many_Sibling_Index_When_Child_Is_Added_And_Removed() { @@ -664,9 +1240,258 @@ public class CompositorHitTestingTests : CompositorTestsBase } } - private static IDisposable TestApplication() + [Fact] + public void HitTest_Geometry_Should_Update_Many_Sibling_Index_When_Child_Is_Added_And_Removed() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border top = null!; + var canvas = new Canvas { Width = 200, Height = 200 }; + + for (var i = 0; i < 70; i++) + { + var child = new Border { Width = 100, Height = 100, Background = Brushes.Red }; + Canvas.SetLeft(child, 50); + Canvas.SetTop(child, 50); + canvas.Children.Add(child); + + if (i == 69) + top = child; + } + + s.TopLevel.Content = canvas; + s.AssertHitTestFirst(new RectangleGeometry(new Rect(100, 100, 10, 10)), null, top); + + var added = new Border { Width = 100, Height = 100, Background = Brushes.Blue }; + Canvas.SetLeft(added, 50); + Canvas.SetTop(added, 50); + canvas.Children.Add(added); + + s.AssertHitTestFirst(new RectangleGeometry(new Rect(100, 100, 10, 10)), null, added); + + canvas.Children.Remove(added); + s.AssertHitTestFirst(new RectangleGeometry(new Rect(100, 100, 10, 10)), null, top); + } + } + + [Fact] + public void HitTest_Geometry_Should_Find_Control_Within_Geometry_Bounds() { - return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface); + using (var s = new CompositorTestServices(new Size(200, 200))) + { + var border = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + s.TopLevel.Content = border; + s.RunJobs(); + + var geometry = new RectangleGeometry { Rect = new Rect(80, 80, 40, 40) }; + s.AssertHitTestFirst(geometry, null, border); + } } + [Fact] + public void HitTest_Geometry_Should_Not_Find_Control_Outside_Geometry_Bounds() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + var border = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + s.TopLevel.Content = border; + s.RunJobs(); + + var geometry = new RectangleGeometry { Rect = new Rect(10, 10, 30, 30) }; + s.AssertHitTestFirst(geometry, null, null); + } + } + + [Fact] + public void HitTest_Geometry_Should_Find_Multiple_Controls_Within_Bounds() + { + using (var s = new CompositorTestServices(new Size(300, 200))) + { + Panel container = new Panel + { + Width = 300, + Height = 200, + Children = + { + new Border + { + Name = "border1", + Width = 50, + Height = 50, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Top, + }, + new Border + { + Name = "border2", + Width = 50, + Height = 50, + Background = Brushes.Blue, + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Center, + } + } + }; + s.TopLevel.Content = container; + s.RunJobs(); + + var geometry = new RectangleGeometry { Rect = new Rect(0, 0, 100, 200) }; + s.AssertHitTestFirst(geometry, null, container.Children[1]); + } + } + + [Fact] + public void HitTest_Geometry_Should_Respect_Control_Visibility() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + var border = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Child = new Border + { + Background = Brushes.Blue, + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Stretch, + IsVisible = false + } + }; + s.TopLevel.Content = border; + + s.RunJobs(); + + var geometry = new RectangleGeometry { Rect = new Rect(50, 50, 100, 100) }; + s.AssertHitTestFirst(geometry, null, border); + } + } + + [Fact] + public void HitTest_Geometry_Should_Find_Top_Control_With_ZIndex() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Panel container = new Panel + { + Width = 200, + Height = 200, + Children = + { + new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + ZIndex = 1, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }, + new Border + { + Width = 100, + Height = 100, + Background = Brushes.Blue, + ZIndex = 2, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(10) + } + } + }; + s.TopLevel.Content = container; + s.RunJobs(); + + var geometry = new RectangleGeometry { Rect = new Rect(50, 50, 100, 100) }; + s.AssertHitTestFirst(geometry, null, container.Children[1]); + } + } + + [Fact] + public void HitTest_Geometry_Should_Filter_Results() + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + Border parent, child; + s.TopLevel.Content = parent = new Border + { + Width = 100, + Height = 100, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Child = child = new Border + { + Background = Brushes.Blue, + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Stretch, + } + }; + s.RunJobs(); + + var geometry = new RectangleGeometry { Rect = new Rect(50, 50, 100, 100) }; + + s.AssertHitTestFirst(geometry, null, child); + s.AssertHitTestFirst(geometry, v => v != parent, null); + s.AssertHitTestFirst(geometry, v => v != child, parent); + } + } + + [Theory] + [InlineData(50, 50, 100, 100, 50, 50, IntersectionResult.FullyInside)] + [InlineData(80, 80, 100, 100, 50, 50, IntersectionResult.Intersects)] + [InlineData(95, 95, 40, 40, 80, 80, IntersectionResult.FullyContains)] + [InlineData(0, 0, 10, 10, 50, 50, IntersectionResult.Empty)] + public void HitTest_Geometry_Should_Return_Correct_IntersectionResult( + double geomX, double geomY, double geomWidth, double geomHeight, + double elemWidth, double elemHeight, IntersectionResult expectedResult) + { + using (var s = new CompositorTestServices(new Size(200, 200))) + { + var border = new Border + { + Width = elemWidth, + Height = elemHeight, + Background = Brushes.Red, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + s.TopLevel.Content = border; + s.RunJobs(); + + var geometry = new RectangleGeometry(new Rect(geomX, geomY, geomWidth, geomHeight)); + + if (expectedResult == IntersectionResult.Empty) + { + // Geometry doesn't intersect element + s.AssertHitTest(geometry, null); + } + else + { + // Geometry intersects element + s.AssertHitTest(geometry, null, + new GeometryHitTestResult(border, expectedResult)); + } + } + } } diff --git a/tests/Avalonia.Base.UnitTests/Rendering/CustomHitTestBorder.cs b/tests/Avalonia.Base.UnitTests/Rendering/CustomHitTestBorder.cs index d65df992be..1998a9c661 100644 --- a/tests/Avalonia.Base.UnitTests/Rendering/CustomHitTestBorder.cs +++ b/tests/Avalonia.Base.UnitTests/Rendering/CustomHitTestBorder.cs @@ -1,4 +1,5 @@ using Avalonia.Controls; +using Avalonia.Media; using Avalonia.Rendering; namespace Avalonia.Base.UnitTests.Rendering @@ -11,5 +12,10 @@ namespace Avalonia.Base.UnitTests.Rendering return new Rect( -Bounds.Width / 2,0, Bounds.Width, Bounds.Height) .Contains(point); } + + public IntersectionResult HitTest(Geometry geometry) + { + return new RectangleGeometry(new Rect(-Bounds.Width / 2, 0, Bounds.Width, Bounds.Height)).GetFillIntersectionResult(geometry) ?? IntersectionResult.Empty; + } } } diff --git a/tests/Avalonia.Base.UnitTests/Rendering/SceneGraph/DrawOperationTests.cs b/tests/Avalonia.Base.UnitTests/Rendering/SceneGraph/DrawOperationTests.cs index a0ff9f2134..bcd4fdebd6 100644 --- a/tests/Avalonia.Base.UnitTests/Rendering/SceneGraph/DrawOperationTests.cs +++ b/tests/Avalonia.Base.UnitTests/Rendering/SceneGraph/DrawOperationTests.cs @@ -126,7 +126,7 @@ namespace Avalonia.Base.UnitTests.Rendering.SceneGraph ctx.Context.DrawGeometry(Brushes.Black, null, geometry.Object); } - Assert.False(ctx.Context.GetRenderResults()!.HitTest(default)); + Assert.False(ctx.Context.GetRenderResults()!.HitTest(default(Point))); } [Fact] diff --git a/tests/Avalonia.Base.UnitTests/VisualTree/VisualExtensions_GetVisualsAt.cs b/tests/Avalonia.Base.UnitTests/VisualTree/VisualExtensions_GetVisualsAt.cs index 3f5cb9dd01..c6919cae10 100644 --- a/tests/Avalonia.Base.UnitTests/VisualTree/VisualExtensions_GetVisualsAt.cs +++ b/tests/Avalonia.Base.UnitTests/VisualTree/VisualExtensions_GetVisualsAt.cs @@ -50,6 +50,44 @@ namespace Avalonia.Base.UnitTests.VisualTree } + [Fact] + public void Should_Find_Control_With_Geometry() + { + Border target; + using var services = new CompositorTestServices(new Size(200, 200)) + { + TopLevel = + { + Content = new StackPanel + { + Background = null, + Children = + { + (target = new Border + { + Width = 100, + Height = 200, + Background = Brushes.Red, + }), + new Border + { + Width = 100, + Height = 200, + Background = Brushes.Green, + } + }, + Orientation = Orientation.Horizontal, + } + } + }; + + services.RunJobs(); + var geo = new RectangleGeometry(target.Bounds); + var result = target.GetVisualsAt(geo); + + Assert.Equal(new GeometryHitTestResult(target, IntersectionResult.FullyContains), result.Single()); + } + [Fact] public void Should_Not_Find_Sibling_Control() { diff --git a/tests/Avalonia.RenderTests/TestRenderRoot.cs b/tests/Avalonia.RenderTests/TestRenderRoot.cs index f4a0815e8a..6f63770647 100644 --- a/tests/Avalonia.RenderTests/TestRenderRoot.cs +++ b/tests/Avalonia.RenderTests/TestRenderRoot.cs @@ -1,5 +1,3 @@ -using Avalonia.Rendering; -using System.Threading.Tasks; using System; using System.Collections.Generic; using Avalonia.Controls; @@ -7,7 +5,9 @@ using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Layout; using Avalonia.LogicalTree; +using Avalonia.Media; using Avalonia.Platform; +using Avalonia.Rendering; using Avalonia.Rendering.Composition; @@ -45,7 +45,11 @@ namespace Avalonia.Skia.RenderTests { public IEnumerable HitTest(Point p, Visual root, Func? filter) => Array.Empty(); + public IEnumerable HitTest(Geometry geometry, Visual root, Func filter) => Array.Empty(); + public Visual? HitTestFirst(Point p, Visual root, Func? filter) => null; + + public GeometryHitTestResult? HitTestFirst(Geometry geometry, Visual root, Func? filter) => null; } internal void Initialize(CompositingRenderer renderer, Control child) diff --git a/tests/Avalonia.UnitTests/CompositorTestServices.cs b/tests/Avalonia.UnitTests/CompositorTestServices.cs index 1ba03f5974..281c8d0cd2 100644 --- a/tests/Avalonia.UnitTests/CompositorTestServices.cs +++ b/tests/Avalonia.UnitTests/CompositorTestServices.cs @@ -9,6 +9,7 @@ using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.Raw; +using Avalonia.Media; using Avalonia.Platform; using Avalonia.Platform.Surfaces; using Avalonia.Rendering; @@ -107,6 +108,13 @@ public class CompositorTestServices : IDisposable Assert.Equal(expected, tested); } + public void AssertHitTest(Geometry geometry, Func? filter, params GeometryHitTestResult[] expected) + { + RunJobs(); + var tested = Renderer.HitTest(geometry, TopLevel, filter); + Assert.Equal(expected, tested); + } + public void AssertHitTestFirst(Point pt, Func? filter, Visual? expected) { RunJobs(); @@ -114,6 +122,13 @@ public class CompositorTestServices : IDisposable Assert.Equal(expected, tested); } + public void AssertHitTestFirst(Geometry geometry, Func? filter, Visual? expected) + { + RunJobs(); + var tested = Renderer.HitTestFirst(geometry, TopLevel, filter); + Assert.Equal(expected, tested?.VisualHit); + } + public class DebugEvents : ICompositionTargetDebugEvents { public List Rects = new(); diff --git a/tests/Avalonia.UnitTests/TestRoot.cs b/tests/Avalonia.UnitTests/TestRoot.cs index 18edafed0a..547d5f6c22 100644 --- a/tests/Avalonia.UnitTests/TestRoot.cs +++ b/tests/Avalonia.UnitTests/TestRoot.cs @@ -7,6 +7,7 @@ using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Layout; using Avalonia.LogicalTree; +using Avalonia.Media; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Styling; @@ -30,11 +31,15 @@ namespace Avalonia.UnitTests SetPresentationSourceForRootVisual(this); } - class NullHitTester : IHitTester + class NullHitTester : IHitTester { public IEnumerable HitTest(Point p, Visual root, Func? filter) => Array.Empty(); + public IEnumerable HitTest(Geometry geometry, Visual root, Func filter) => Array.Empty(); + public Visual? HitTestFirst(Point p, Visual root, Func? filter) => null; + + public GeometryHitTestResult? HitTestFirst(Geometry geometry, Visual root, Func? filter) => null; } public TestRoot(Control? child)