From f4319df84cb5741fafdcea2bfc2d71bca74992f1 Mon Sep 17 00:00:00 2001 From: zignd Date: Mon, 16 Nov 2026 09:59:08 -0300 Subject: [PATCH] feat(input): a pointer-route trace and a pointer-click locator A click that reaches the wrong handler used to need a debugger or a bespoke repro. Two additions make it observable: - UIContext.TracePointerRoutes (also FORMA_UI_EVENTS=1) records the dispatch chain for each press and release: the hit target, every bubbled stop with its MouseFilter and press ownership, and the row owner that receives a press the row content stopped. TakePointerRouteTrace() drains it; it allocates nothing while off. - Locator.ClickPointer() injects move + press + release, the path a user's click takes, instead of running the accessibility action. Click() cannot reproduce a routing bug because it bypasses dispatch entirely. AccessibilityTree.FindControl(id) resolves the live control behind a snapshot node, so template content (a row's buttons) can be clicked by automation id; walking Control.Children never reached it. The accessibility and inspect helpers now use it, and the docs say why a row test asserts both sides: the widget ran and the row did not activate. --- docs/headless-testing.md | 6 ++ docs/input-and-focus.md | 18 ++++ src/Forma.Testing/Locator.cs | 26 ++++-- src/Forma/AccessibilityTree.cs | 19 ++++ src/Forma/PointerRoutes.cs | 92 +++++++++++++++++++ src/Forma/UIContext.cs | 19 +++- tests/Forma.Tests/LocatorTest.cs | 38 ++++++++ tests/Forma.Tests/PointerRouteTraceTest.cs | 101 +++++++++++++++++++++ 8 files changed, 308 insertions(+), 11 deletions(-) create mode 100644 src/Forma/PointerRoutes.cs create mode 100644 tests/Forma.Tests/PointerRouteTraceTest.cs diff --git a/docs/headless-testing.md b/docs/headless-testing.md index 0d121611..7bc29b83 100644 --- a/docs/headless-testing.md +++ b/docs/headless-testing.md @@ -26,6 +26,12 @@ Notes: - For game-level tests, drive the same context the game's screens read, and make the game's own input (for example a mouse snapshot) come from one source, or a test can pass while real input fails. - Time-based behavior (double-click window) follows `UIContext.CurrentTime`; use `Advance` rather than sleeping. +- `locator.Click()` runs the element's accessibility action; `locator.ClickPointer()` injects move + press + release + instead. Use the pointer one when dispatch is what you are testing — which control receives the press, bubbling, + `MouseFilter`, or a row owner also reacting. A semantic click cannot reproduce a routing bug. +- A row-interaction test asserts both sides: the widget's own action ran **and** the row did not select or + activate. A one-sided assertion cannot see a press that reached both handlers, which is what a row whose + content stops bubbling will do. `PointerRouteTraceTest` and `ListBoxRowPointerTest` are the reference. - Rendering (`Draw`, render targets) still needs a graphics device. A game built on a MonoGame fork with a headless backend can run `SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy` set in the *process* environment (setting them inside the test is too late on Unix). diff --git a/docs/input-and-focus.md b/docs/input-and-focus.md index 88657c7e..b5f312b6 100644 --- a/docs/input-and-focus.md +++ b/docs/input-and-focus.md @@ -31,6 +31,24 @@ status label: [!code-csharp[](examples/csharp-first-ui.cs)] +### Diagnosing pointer routing + +When a click reaches the wrong handler, the dispatch chain explains it. Set `FORMA_UI_EVENTS=1` in the +process environment to copy a route trace to standard error, or turn `UIContext.TracePointerRoutes` on +and read `UIContext.TakePointerRouteTrace()` after one dispatch (the method clears what it returns). +Each line names the hit target, every control the event bubbled through, its `MouseFilter`, whether it +consumes a press, and which `ListBox` received the event when a row stopped the bubble: + +```text +[pointer] press at (140, 45) target=Button#map.delete "Delete" + Label "Delete" filter=Pass consumesPress=no accepted=no + Button#map.delete "Delete" filter=Stop consumesPress=yes accepted=no + -> stopped at Button#map.delete "Delete"; it consumes the press, so the row owner is not consulted +``` + +A press that reads as row content instead reports `row owner ListBox "MapList" also receives the +event`. The trace is off by default and allocates nothing while off; it is a diagnostic, not a log. + ## System cursors `UIComponent` routes `Control.EffectiveCursor` to the runtime's system cursor. `LineEdit` and diff --git a/src/Forma.Testing/Locator.cs b/src/Forma.Testing/Locator.cs index d2e86375..664472aa 100644 --- a/src/Forma.Testing/Locator.cs +++ b/src/Forma.Testing/Locator.cs @@ -198,6 +198,25 @@ public ActionabilityFailure GetActionability() /// public void Click() => Perform(AccessibilityActions.Press, null, "click"); + /// + /// Clicks the element with a real pointer sequence - move, press, release at its centre - instead of + /// running its accessibility action. + /// + /// Use this when the behavior under test is pointer dispatch itself: which control receives the press, + /// how it bubbles through , and whether a row owner also treats it as + /// row content. runs the semantic action and cannot reproduce a routing bug; a + /// widget inside a row can pass that test while both the widget and the row react to a user's click. + /// + /// + public void ClickPointer(PointerButton button = PointerButton.Left) + { + var bounds = ResolveActionable().Bounds; + var point = new Point(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2); + _context.InjectPointerMove(point); + _context.InjectPointerPress(point, button); + _context.InjectPointerRelease(point, button); + } + /// Gives the element keyboard focus. public void Focus() => Perform(AccessibilityActions.Focus, null, "focus"); @@ -235,12 +254,7 @@ private void Perform(AccessibilityActions action, object argument, string verb) throw new LocatorException($"Cannot {verb} {Quote(Description)}: {action} was refused by {node.Role} \"{node.Name}\"."); } - private Control FindControl(int id) - { - foreach (var control in AccessibilityTree.EnumerateControls(_context)) - if (control.AccessibilityId == id) return control; - return null; - } + private Control FindControl(int id) => AccessibilityTree.FindControl(_context, id); // --- assertions ------------------------------------------------------------------------- diff --git a/src/Forma/AccessibilityTree.cs b/src/Forma/AccessibilityTree.cs index 1f5808ad..7ee7fada 100644 --- a/src/Forma/AccessibilityTree.cs +++ b/src/Forma/AccessibilityTree.cs @@ -332,6 +332,25 @@ static bool Perform(AccessibilityPeer peer, AccessibilityActions action, object (peer.Actions & action) != 0 && peer.Invoke(action, argument); } + /// + /// The live control behind an accessibility node id, or null when the node is a virtual peer + /// (a virtualized list row or a menu entry) and has no control of its own. + /// + /// A snapshot is a value; pointer input needs the control to hit-test against. Template content — + /// the buttons inside a list row, say — is not reachable by walking , + /// so a caller that resolves a node and then wants to click it should use this rather than its own walk. + /// + /// + public static Control FindControl(UIContext context, int nodeId) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + foreach (var control in EnumerateControls(context)) + if (control.AccessibilityId == nodeId) return control; + + return null; + } + internal static IEnumerable EnumerateControls(UIContext context) { var modal = context.GetActiveModalPopup(); diff --git a/src/Forma/PointerRoutes.cs b/src/Forma/PointerRoutes.cs new file mode 100644 index 00000000..32fad800 --- /dev/null +++ b/src/Forma/PointerRoutes.cs @@ -0,0 +1,92 @@ +// Copyright (c) 2026 Igor Hipólito Vieira +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.Xna.Framework; + +namespace Forma +{ + /// + /// Records where a pointer press, release or wheel event travelled: the hit target, every control it + /// bubbled through, whether each one filtered or accepted it, and which ListBox received it when a row + /// stopped the bubble. Off by default; set FORMA_UI_EVENTS=1 in the process environment, or turn + /// on for one dispatch, to collect it. + /// + public sealed partial class UIContext + { + private const int MaximumPointerRouteEntries = 512; + private static readonly bool s_PointerRoutesFromEnvironment = + !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("FORMA_UI_EVENTS")); + private readonly List _pointerRouteTrace = new List(); + + /// + /// Whether pointer dispatch appends to . Defaults to on when + /// FORMA_UI_EVENTS is set in the environment, which also copies the lines to standard error. + /// + public bool TracePointerRoutes { get; set; } = s_PointerRoutesFromEnvironment; + + /// + /// Returns the pointer-route lines recorded since the previous call and clears them. Empty when the + /// trace is off or no pointer event was dispatched. + /// + public IReadOnlyList TakePointerRouteTrace() + { + if (_pointerRouteTrace.Count == 0) return Array.Empty(); + var lines = _pointerRouteTrace.ToArray(); + _pointerRouteTrace.Clear(); + return lines; + } + + private void RecordPointerRoute(string line) + { + if (!TracePointerRoutes) return; + if (_pointerRouteTrace.Count >= MaximumPointerRouteEntries) _pointerRouteTrace.RemoveAt(0); + _pointerRouteTrace.Add(line); + if (s_PointerRoutesFromEnvironment) Console.Error.WriteLine(line); + } + + private void TracePointerTarget(string phase, Control target, Point point) + { + if (!TracePointerRoutes) return; + RecordPointerRoute($"[pointer] {phase} at ({point.X}, {point.Y}) target={DescribePointerControl(target)}"); + } + + private void TracePointerStop(Control control, bool accepted) + { + if (!TracePointerRoutes) return; + var consumes = control.ConsumesPointerPress ? "yes" : "no"; + RecordPointerRoute($" {DescribePointerControl(control)} filter={control.MouseFilter} consumesPress={consumes} accepted={(accepted ? "yes" : "no")}"); + } + + private void TracePointerRowOwner(Control stoppedAt, ListBox owner) + { + if (!TracePointerRoutes) return; + if (stoppedAt.ConsumesPointerPress) + { + RecordPointerRoute($" -> stopped at {DescribePointerControl(stoppedAt)}; it consumes the press, so the row owner is not consulted"); + return; + } + + RecordPointerRoute(owner is null + ? $" -> stopped at {DescribePointerControl(stoppedAt)}; no row owner" + : $" -> stopped at {DescribePointerControl(stoppedAt)}; row owner {DescribePointerControl(owner)} also receives the event"); + } + + private static string DescribePointerControl(Control control) + { + if (control is null) return ""; + var text = new StringBuilder(control.GetType().Name); + if (!string.IsNullOrEmpty(control.AutomationId)) text.Append('#').Append(control.AutomationId); + var name = control.AccessibilityName; + if (!string.IsNullOrEmpty(name)) + { + name = name.ReplaceLineEndings(" "); + if (name.Length > 40) name = name[..37] + "..."; + text.Append(" \"").Append(name).Append('"'); + } + return text.ToString(); + } + } +} diff --git a/src/Forma/UIContext.cs b/src/Forma/UIContext.cs index cbe008f7..0380e6db 100644 --- a/src/Forma/UIContext.cs +++ b/src/Forma/UIContext.cs @@ -861,15 +861,20 @@ private static Control HitTest(Control control, Point point) return control.MouseFilter != MouseFilter.Ignore && control.ContainsPoint(point) ? control : null; } - private static void DispatchPointerPressed(Control target, Point point) + private void DispatchPointerPressed(Control target, Point point) { + TracePointerTarget("press", target, point); for (var control = target; control != null; control = control.VisualParent) { control.PointerPressed(point); - if (control.ConsumeEventAccepted()) break; + var accepted = control.ConsumeEventAccepted(); + TracePointerStop(control, accepted); + if (accepted) break; if (control.MouseFilter != MouseFilter.Pass) { - GetRowOwnerForStoppedPointer(control)?.PointerPressed(point); + var owner = GetRowOwnerForStoppedPointer(control); + TracePointerRowOwner(control, owner); + owner?.PointerPressed(point); break; } } @@ -926,15 +931,19 @@ private static void DispatchPointerButtonTransition(Control target, Point point, } } - private static void DispatchPointerReleased(Control target, Point point) + private void DispatchPointerReleased(Control target, Point point) { + TracePointerTarget("release", target, point); for (var control = target; control != null; control = control.VisualParent) { control.PointerReleased(point, control.ContainsPoint(point)); - if (control.ConsumeEventAccepted()) break; + var accepted = control.ConsumeEventAccepted(); + TracePointerStop(control, accepted); + if (accepted) break; if (control.MouseFilter != MouseFilter.Pass) { var owner = GetRowOwnerForStoppedPointer(control); + TracePointerRowOwner(control, owner); owner?.PointerReleased(point, owner.ContainsPoint(point)); break; } diff --git a/tests/Forma.Tests/LocatorTest.cs b/tests/Forma.Tests/LocatorTest.cs index 5a52c06c..9b3bf58e 100644 --- a/tests/Forma.Tests/LocatorTest.cs +++ b/tests/Forma.Tests/LocatorTest.cs @@ -49,6 +49,44 @@ public void ResolvesByAutomationId() Assert.That(context.ByAutomationId("cmd.save").Resolve().Id, Is.EqualTo(save.AccessibilityId)); } + [Test] + public void ClickPointerRunsARealPointerSequence() + { + var (context, save, _) = TwoButtons(); + using var _context = context; + var entered = 0; + var pressed = 0; + save.MouseEntered += (_, _) => entered++; + save.Pressed += (_, _) => pressed++; + + context.ByAutomationId("cmd.save").ClickPointer(); + + Assert.That(pressed, Is.EqualTo(1)); + Assert.That(entered, Is.EqualTo(1), "the pointer moved over the button, which the accessibility action never does"); + Assert.That(context.FocusedControl, Is.EqualTo(save)); + } + + [Test] + public void AccessibilityTreeFindControlReachesTemplateContent() + { + var context = CreateContext(); + using var _context = context; + var list = new ListBox + { + Size = new Vector2(300, 200), + ItemTemplate = DataTemplate.Create((_, _) => new Button { Text = "Row action", AutomationId = "row.action" }), + ItemsSource = new[] { "row" }, + }; + context.Add(list); + context.Layout(); + + var node = context.ByAutomationId("row.action").Resolve(); + var control = AccessibilityTree.FindControl(context, node.Id); + + Assert.That(control, Is.Not.Null, "template content is not reachable by walking Control.Children"); + Assert.That(control.AutomationId, Is.EqualTo("row.action")); + } + [Test] public void ByTextMatchesLooselyByDefault() { diff --git a/tests/Forma.Tests/PointerRouteTraceTest.cs b/tests/Forma.Tests/PointerRouteTraceTest.cs new file mode 100644 index 00000000..cf9c7e36 --- /dev/null +++ b/tests/Forma.Tests/PointerRouteTraceTest.cs @@ -0,0 +1,101 @@ +// Copyright (c) 2026 Igor Hipólito Vieira +// SPDX-License-Identifier: MIT + +using System; +using Forma.Testing; +using Microsoft.Xna.Framework; + +namespace Forma.Tests; + +/// +/// The pointer-route trace is the diagnostic for "the wrong handler ran": it names the control a press +/// stopped at and the row owner that received it instead, without a debugger attached to the game. +/// +public sealed class PointerRouteTraceTest +{ + private static (HeadlessInput Input, ListBox List) Build(Func row, bool singleClick = false) + { + var input = HeadlessInput.Create(); + var list = new ListBox + { + Name = "Rows", + Size = new Vector2(300, 300), + ActivateOnSingleClick = singleClick, + ItemTemplate = DataTemplate.Create((_, _) => row()), + ItemsSource = new[] { "a", "b", "c" }, + }; + input.Context.Add(list); + input.Context.TracePointerRoutes = true; + input.Context.Layout(); + return (input, list); + } + + private static Control Row(Control child) + { + var box = new HBoxContainer { CustomMinimumSize = new Vector2(280, 30) }; + box.AddChild(child); + return box; + } + + [Test] + public void PressOnAWidgetInsideARowSaysTheRowOwnerWasNotConsulted() + { + var (input, list) = Build(() => Row(new Button + { + Text = "Delete", + AutomationId = "row.delete", + CustomMinimumSize = new Vector2(280, 30), + FocusMode = FocusMode.None, + }), singleClick: true); + using var context = input.Context; + + input.Click(HeadlessInput.CenterOf(list.GetRealizedContainer(1))); + var trace = context.TakePointerRouteTrace(); + + Assert.That(trace, Has.Some.Contains("press at")); + Assert.That(trace, Has.Some.Matches(line => + line.Contains("Button#row.delete \"Delete\"") && line.Contains("consumesPress=yes"))); + Assert.That(trace, Has.Some.Contains("it consumes the press, so the row owner is not consulted")); + Assert.That(trace, Has.None.Contains("row owner ListBox")); + } + + [Test] + public void PressOnRowContentNamesTheRowOwnerThatReceivesIt() + { + var (input, list) = Build(() => Row(new Label { Text = "miguel", CustomMinimumSize = new Vector2(280, 30) })); + using var context = input.Context; + + input.Click(HeadlessInput.CenterOf(list.GetRealizedContainer(1))); + var trace = context.TakePointerRouteTrace(); + + Assert.That(trace, Has.Some.Matches(line => + line.Contains("Label \"miguel\"") && line.Contains("consumesPress=no"))); + Assert.That(trace, Has.Some.Contains("row owner ListBox \"Rows\" also receives the event")); + } + + [Test] + public void TakingTheTraceClearsIt() + { + var (input, list) = Build(() => Row(new Label { Text = "miguel", CustomMinimumSize = new Vector2(280, 30) })); + using var context = input.Context; + + input.Click(HeadlessInput.CenterOf(list.GetRealizedContainer(0))); + Assert.That(context.TakePointerRouteTrace(), Is.Not.Empty); + Assert.That(context.TakePointerRouteTrace(), Is.Empty); + } + + [Test] + public void TraceStaysOffWhenItWasNotEnabled() + { + Assume.That(Environment.GetEnvironmentVariable("FORMA_UI_EVENTS"), Is.Null.Or.Empty); + var input = HeadlessInput.Create(); + using var context = input.Context; + var button = new Button { Text = "x", Size = new Vector2(80, 30) }; + context.Add(button); + context.Layout(); + + input.Click(button); + + Assert.That(context.TakePointerRouteTrace(), Is.Empty); + } +}