Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/headless-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
18 changes: 18 additions & 0 deletions docs/input-and-focus.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 20 additions & 6 deletions src/Forma.Testing/Locator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,25 @@ public ActionabilityFailure GetActionability()
/// </summary>
public void Click() => Perform(AccessibilityActions.Press, null, "click");

/// <summary>
/// Clicks the element with a real pointer sequence - move, press, release at its centre - instead of
/// running its accessibility action.
/// <para>
/// Use this when the behavior under test is pointer dispatch itself: which control receives the press,
/// how it bubbles through <see cref="Control.MouseFilter"/>, and whether a row owner also treats it as
/// row content. <see cref="Click"/> 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.
/// </para>
/// </summary>
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);
}

/// <summary>Gives the element keyboard focus.</summary>
public void Focus() => Perform(AccessibilityActions.Focus, null, "focus");

Expand Down Expand Up @@ -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 -------------------------------------------------------------------------

Expand Down
19 changes: 19 additions & 0 deletions src/Forma/AccessibilityTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,25 @@ static bool Perform(AccessibilityPeer peer, AccessibilityActions action, object
(peer.Actions & action) != 0 && peer.Invoke(action, argument);
}

/// <summary>
/// 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.
/// <para>
/// 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 <see cref="Control.Children"/>,
/// so a caller that resolves a node and then wants to click it should use this rather than its own walk.
/// </para>
/// </summary>
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<Control> EnumerateControls(UIContext context)
{
var modal = context.GetActiveModalPopup();
Expand Down
92 changes: 92 additions & 0 deletions src/Forma/PointerRoutes.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// 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 <c>FORMA_UI_EVENTS=1</c> in the process environment, or turn
/// <see cref="TracePointerRoutes"/> on for one dispatch, to collect it.
/// </summary>
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<string> _pointerRouteTrace = new List<string>();

/// <summary>
/// Whether pointer dispatch appends to <see cref="TakePointerRouteTrace"/>. Defaults to on when
/// <c>FORMA_UI_EVENTS</c> is set in the environment, which also copies the lines to standard error.
/// </summary>
public bool TracePointerRoutes { get; set; } = s_PointerRoutesFromEnvironment;

/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<string> TakePointerRouteTrace()
{
if (_pointerRouteTrace.Count == 0) return Array.Empty<string>();
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 "<none>";
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();
}
}
}
19 changes: 14 additions & 5 deletions src/Forma/UIContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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;
}
Expand Down
38 changes: 38 additions & 0 deletions tests/Forma.Tests/LocatorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>((_, _) => 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()
{
Expand Down
101 changes: 101 additions & 0 deletions tests/Forma.Tests/PointerRouteTraceTest.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
public sealed class PointerRouteTraceTest
{
private static (HeadlessInput Input, ListBox List) Build(Func<Control> row, bool singleClick = false)
{
var input = HeadlessInput.Create();
var list = new ListBox
{
Name = "Rows",
Size = new Vector2(300, 300),
ActivateOnSingleClick = singleClick,
ItemTemplate = DataTemplate.Create<string>((_, _) => 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<string>(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<string>(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);
}
}
Loading