23 private static readonly
MouseButton[] _mouseButtons =
30 private readonly
object _syncRoot =
new();
31 private readonly List<WidgetBase> _widgets = [];
32 private readonly Dictionary<int, PointerCapture> _touchCaptures = [];
33 private readonly HashSet<int> _unhandledTouchContacts = [];
34 private readonly Dictionary<int, TappedEventArgs> _pendingTaps = [];
41 private PointerCapture? _mouseCapture;
42 private WidgetHit? _hoveredHit;
45 private bool _isStarted;
46 private bool _disposed;
61 _renderSurfaceHost = renderSurfaceHost ??
throw new ArgumentNullException(nameof(renderSurfaceHost));
63 _keyboardEventPoller = keyboardEventPoller;
64 _mouseEventPoller = mouseEventPoller;
65 _touchEventPoller = touchEventPoller;
100 ObjectDisposedException.ThrowIf(_disposed,
this);
101 ArgumentNullException.ThrowIfNull(widget);
105 throw new ArgumentException(
"The widget belongs to a different RenderSurfaceHost.", nameof(widget));
110 if (_widgets.Contains(widget))
113 _widgets.Add(widget);
114 widget.Disposing += OnWidgetDisposing;
124 ArgumentNullException.ThrowIfNull(widget);
134 ObjectDisposedException.ThrowIf(_disposed,
this);
135 ArgumentNullException.ThrowIfNull(widget);
139 if (!_widgets.Remove(widget))
140 throw new InvalidOperationException(
"The widget is not registered.");
142 _widgets.Add(widget);
152 if (ReferenceEquals(_focusedWidget, widget))
155 if (widget is not
null && !CanReceiveKeyboardInput(widget))
159 _focusedWidget = widget;
161 previous?.DispatchFocusLost();
162 widget?.DispatchFocusGained();
178 ObjectDisposedException.ThrowIf(_disposed,
this);
183 if (_keyboardEventPoller is not
null)
184 _keyboardEventPoller.KeyDown += OnKeyDown;
186 if (_mouseEventPoller is not
null)
187 _mouseEventPoller.MouseEvent += OnMouseEvent;
189 if (_touchEventPoller is not
null)
191 _touchEventPoller.TouchBegan += OnTouchBegan;
192 _touchEventPoller.TouchMoved += OnTouchMoved;
193 _touchEventPoller.TouchEnded += OnTouchEnded;
194 _touchEventPoller.TouchEvent += OnTouchGesture;
197 WidgetInputRouterRegistry.Attach(
212 WidgetInputRouterRegistry.Detach(
216 if (_keyboardEventPoller is not
null)
217 _keyboardEventPoller.KeyDown -= OnKeyDown;
219 if (_mouseEventPoller is not
null)
220 _mouseEventPoller.MouseEvent -= OnMouseEvent;
222 if (_touchEventPoller is not
null)
224 _touchEventPoller.TouchBegan -= OnTouchBegan;
225 _touchEventPoller.TouchMoved -= OnTouchMoved;
226 _touchEventPoller.TouchEnded -= OnTouchEnded;
227 _touchEventPoller.TouchEvent -= OnTouchGesture;
232 _mouseCapture =
null;
233 _touchCaptures.Clear();
234 _unhandledTouchContacts.Clear();
235 _pendingTaps.Clear();
254 widgets = [.. _widgets];
259 widget.Disposing -= OnWidgetDisposing;
264 internal void NotifyWidgetHidden(
WidgetBase widget)
266 ArgumentNullException.ThrowIfNull(widget);
267 ReleaseInputState(widget, dispatchPointerUp:
true);
270 internal void NotifyWidgetInputDisabled(WidgetBase widget)
272 ArgumentNullException.ThrowIfNull(widget);
273 ReleaseInputState(widget, dispatchPointerUp:
true);
276 internal void NotifyWidgetPointerInputDisabled(WidgetBase widget)
278 ArgumentNullException.ThrowIfNull(widget);
279 ReleasePointerState(widget, dispatchPointerUp:
true);
282 internal void NotifyWidgetKeyboardFocusDisabled(WidgetBase widget)
284 ArgumentNullException.ThrowIfNull(widget);
285 ReleaseKeyboardFocus(widget);
288 private void OnKeyDown(KeyDownEventArgs args)
290 if (!_isStarted || _disposed)
301 WidgetBase? target = _focusedWidget;
303 if (target is not
null && !CanReceiveKeyboardInput(target))
309 if (target is not
null)
311 var focusedArgs =
new WidgetKeyboardEventArgs(
317 target.DispatchKeyboardInput(focusedArgs);
319 if (focusedArgs.Handled)
323 WidgetBase[] snapshot;
326 snapshot = [.. _widgets];
329 for (
int index = snapshot.Length - 1; index >= 0; index--)
331 WidgetBase widget = snapshot[index];
333 if (widget is not IWidgetKeyboardFallback fallback || !IsRegistered(widget) ||
334 !HasValidTarget(widget) || !widget.Visible ||
335 !widget.IsInputEnabled || !widget.IsKeyboardInputEnabled)
338 var fallbackArgs =
new WidgetKeyboardEventArgs(
344 fallback.HandleUnhandledKeyboardInput(fallbackArgs);
346 if (fallbackArgs.Handled)
351 private void OnMouseEvent(MouseEventArgs args)
353 if (!_isStarted || _disposed)
357 WidgetHit? initialHit = HitTest(currentPosition);
359 UpdateMouseHover(initialHit, currentPosition, args.
Tick);
375 GetTopmostViewAt(currentPosition) is
View gameplayView)
378 new PrimaryPointerActionEventArgs(
390 if (args.
ScrollDelta != 0 && initialHit is not
null && IsPointerRoutable(initialHit.Widget, initialHit.View))
392 initialHit.Widget.DispatchMouseWheel(
393 new WidgetMouseWheelEventArgs(
396 new PointF(currentPosition.X, currentPosition.Y),
405 ProcessMouseUp(currentPosition, mouseButton, args.
Tick);
409 UpdateMouseHover(HitTest(currentPosition), currentPosition, args.
Tick);
412 private void ProcessMouseDown(
418 if (_mouseCapture is not
null || hit is
null)
421 FocusFromPointer(hit.Widget);
425 hit.Widget.DispatchPointerDown(
434 _mouseCapture =
new PointerCapture(
442 private void ProcessMouseMove(
443 Point previousPosition,
444 Point currentPosition,
447 PointerCapture? capture = GetValidMouseCapture(tick);
448 WidgetHit? hit = capture is
null ? HitTest(currentPosition) : null;
449 WidgetBase? recipient = capture?.Widget ?? hit?.Widget;
450 View? view = capture?.View ?? hit?.View;
452 if (recipient is
null || view is
null)
455 var delta =
new Vector2(
456 currentPosition.X - previousPosition.X,
457 currentPosition.Y - previousPosition.Y);
461 recipient.DispatchPointerMove(
471 if (capture is not
null)
472 capture.LastPosition = currentPosition;
475 private void ProcessMouseUp(
481 PointerCapture? capture = GetValidMouseCapture(tick);
483 if (capture is
null || capture.Button != releasedButton)
486 WidgetBase recipient = capture.Widget;
488 recipient.DispatchPointerUp(
497 WidgetHit? releaseHit = HitTest(position);
499 if (IsSameHit(releaseHit, recipient, capture.View) &&
500 recipient.GetWrappedHitOffset(capture.View, position) == capture.InstanceOffset)
502 recipient.DispatchPointerClick(
513 _mouseCapture =
null;
516 private void UpdateMouseHover(
521 if (IsSameHit(_hoveredHit, hit))
524 WidgetHit? previous = _hoveredHit;
527 if (previous is not
null)
529 previous.Widget.DispatchPointerLeave(
541 hit.Widget.DispatchPointerEnter(
552 private PointerCapture? GetValidMouseCapture(
long tick)
554 if (_mouseCapture is
null)
557 if (IsPointerRoutable(_mouseCapture.Widget, _mouseCapture.View))
558 return _mouseCapture;
560 _mouseCapture.Widget.DispatchPointerUp(
562 _mouseCapture.Widget,
564 _mouseCapture.LastPosition,
565 _mouseCapture.Button,
569 _mouseCapture =
null;
573 private void OnTouchBegan(
object? sender, TouchEventArgs args)
575 if (!_isStarted || _disposed)
583 _unhandledTouchContacts.Remove(touch.Id);
584 _touchCaptures.Remove(touch.Id);
585 _pendingTaps.Remove(touch.Id);
587 WidgetHit? hit = HitTest(touch.Position);
591 if (GetTopmostViewAt(touch.Position) is not
null)
592 _unhandledTouchContacts.Add(touch.Id);
597 FocusFromPointer(hit.Widget);
599 hit.Widget.DispatchPointerDown(
608 _touchCaptures[touch.Id] =
new PointerCapture(
616 private void OnTouchMoved(
object? sender, TouchEventArgs args)
618 if (!_isStarted || _disposed)
623 if (!_touchCaptures.TryGetValue(touch.Id, out PointerCapture? capture))
626 if (!IsPointerRoutable(capture.Widget, capture.View))
628 capture.Widget.DispatchPointerUp(
632 capture.LastPosition,
637 _touchCaptures.Remove(touch.Id);
641 var delta =
new Vector2(
642 touch.Position.X - capture.LastPosition.X,
643 touch.Position.Y - capture.LastPosition.Y);
645 capture.Widget.DispatchPointerMove(
655 capture.LastPosition = touch.Position;
658 private void OnTouchEnded(
object? sender, TouchEventArgs args)
660 if (!_isStarted || _disposed)
667 bool wasUnhandled = _unhandledTouchContacts.Remove(touch.Id);
668 bool hasPendingTap = _pendingTaps.Remove(touch.Id, out TappedEventArgs? tap);
670 if (hasPendingTap && wasUnhandled && tap is not
null && touch.Phase !=
TouchPhase.Cancelled)
672 View? releaseView = GetTopmostViewAt(touch.Position);
673 View? tapView = GetTopmostViewAt(tap.Position);
675 if (releaseView is not
null &&
676 releaseView == tapView &&
677 HitTest(touch.Position) is
null &&
678 HitTest(tap.Position) is
null)
681 new PrimaryPointerActionEventArgs(
689 if (!_touchCaptures.Remove(touch.Id, out PointerCapture? capture))
692 WidgetBase recipient = capture.Widget;
694 recipient.DispatchPointerUp(
702 instanceOffset: capture.InstanceOffset));
704 WidgetHit? releaseHit = HitTest(touch.Position);
706 if (touch.Phase !=
TouchPhase.Cancelled && IsSameHit(releaseHit, recipient, capture.View) &&
707 recipient.GetWrappedHitOffset(capture.View, touch.Position) == capture.InstanceOffset)
709 recipient.DispatchPointerClick(
718 instanceOffset: capture.InstanceOffset));
722 private void OnTouchGesture(GestureEventArgs args)
724 if (!_isStarted || _disposed || !args.
IsTap || args.
Tap is
null)
729 if (!_unhandledTouchContacts.Contains(tap.TouchId))
732 _pendingTaps[tap.TouchId] = tap;
735 private WidgetHit? HitTest(Point screenPositionPx)
737 View? view = GetTopmostViewAt(screenPositionPx);
742 WidgetBase[] snapshot;
745 snapshot = [.. _widgets];
747 for (
int index = snapshot.Length - 1; index >= 0; index--)
749 WidgetBase widget = snapshot[index];
751 if (widget.HitTest(view, screenPositionPx))
752 return new WidgetHit(widget, view, widget.GetWrappedHitOffset(view, screenPositionPx) ?? PointF.Empty);
758 private View? GetTopmostViewAt(Point screenPositionPx)
760 if (_renderSurfaceHost.RenderSurfaceAdapter is not
null &&
761 (screenPositionPx.X < 0 || screenPositionPx.Y < 0 ||
762 screenPositionPx.X >= _renderSurfaceHost.Backbuffer.Width ||
763 screenPositionPx.Y >= _renderSurfaceHost.Backbuffer.Height))
766 var views = _renderSurfaceHost.ViewManager.Views;
768 for (
int index = views.Count - 1; index >= 0; index--)
770 View view = views[index];
779 private bool IsRegistered(WidgetBase widget)
782 return _widgets.Contains(widget);
785 private bool IsManagedView(
View view)
787 return _renderSurfaceHost.ViewManager.Views.Contains(view);
790 private bool HasValidTarget(
792 View? routedView =
null)
795 return widget.SceneLayer is not
null;
797 if (widget.View is
null || !IsManagedView(widget.View))
800 return routedView is
null || ReferenceEquals(widget.View, routedView);
803 private bool IsPointerRoutable(
807 return IsRegistered(widget) &&
808 IsManagedView(view) &&
809 ReferenceEquals(widget.RenderSurfaceHost, _renderSurfaceHost) &&
810 HasValidTarget(widget, view) &&
811 widget.IsInputEnabled &&
812 widget.IsPointerInputEnabled &&
816 private bool CanReceiveKeyboardInput(WidgetBase widget)
818 return IsRegistered(widget) &&
819 ReferenceEquals(widget.RenderSurfaceHost, _renderSurfaceHost) &&
820 HasValidTarget(widget) &&
822 widget.IsInputEnabled &&
823 widget.IsKeyboardInputEnabled &&
824 widget.CanReceiveFocus;
827 private void FocusFromPointer(WidgetBase widget)
829 if (widget.IsInputEnabled &&
830 widget.IsKeyboardInputEnabled &&
831 widget.CanReceiveFocus)
837 private void ReleaseInputState(
839 bool dispatchPointerUp)
845 ReleaseKeyboardFocus(widget);
848 private void ReleasePointerState(
850 bool dispatchPointerUp)
852 if (ReferenceEquals(_hoveredHit?.Widget, widget))
855 if (ReferenceEquals(_mouseCapture?.Widget, widget))
857 PointerCapture capture = _mouseCapture;
859 if (dispatchPointerUp)
861 widget.DispatchPointerUp(
865 capture.LastPosition,
871 _mouseCapture =
null;
874 int[] touchIds = _touchCaptures.Where(x => ReferenceEquals(x.Value.Widget, widget))
878 foreach (
int touchId
in touchIds)
880 PointerCapture capture = _touchCaptures[touchId];
882 if (dispatchPointerUp)
884 widget.DispatchPointerUp(
888 capture.LastPosition,
891 pointerId: touchId));
894 _touchCaptures.Remove(touchId);
898 private void ReleaseKeyboardFocus(WidgetBase widget)
900 if (ReferenceEquals(_focusedWidget, widget))
904 private static bool IsSameHit(
908 if (left is
null || right is
null)
909 return left is
null && right is
null;
911 return ReferenceEquals(left.Widget, right.Widget)
912 && ReferenceEquals(left.View, right.View);
915 private static bool IsSameHit(
920 return hit is not
null
921 && ReferenceEquals(hit.Widget, widget)
922 && ReferenceEquals(hit.View, view);
925 private WidgetPointerEventArgs CreatePointerArgs(
933 Vector2 deltaPx =
default,
934 PointF? instanceOffset =
null)
936 return new WidgetPointerEventArgs(
939 new PointF(position.X, position.Y),
946 WrappedOffsetWorldPx = instanceOffset ?? (pointerId ==
MousePointerId && _mouseCapture is { } mouse &&
947 ReferenceEquals(mouse.Widget, widget)
948 ? mouse.InstanceOffset
949 : _touchCaptures.TryGetValue(pointerId, out var touch) && ReferenceEquals(touch.Widget, widget)
950 ? touch.InstanceOffset
951 : widget.GetWrappedHitOffset(view, position) ?? PointF.Empty)
962 _ => WidgetPointerButtonEnum.None
966 private void OnWidgetDisposing(
object? sender, IDirectDrawable drawing)
968 if (drawing is WidgetBase widget)
976 bool dispatchPointerUp)
981 removed = _widgets.Remove(widget);
986 widget.Disposing -= OnWidgetDisposing;
988 ReleaseInputState(widget, dispatchPointerUp);
991 private sealed class WidgetHit
1002 PointF instanceOffset)
1006 InstanceOffset = instanceOffset;
1012 public PointF InstanceOffset {
get; }
1017 public WidgetBase Widget {
get; }
1022 public View View {
get; }
1025 private sealed class PointerCapture
1035 public PointerCapture(
1040 PointF instanceOffset)
1045 LastPosition = lastPosition;
1046 InstanceOffset = instanceOffset;
1052 public WidgetBase Widget {
get; }
1057 public View View {
get; }
1070 public Point LastPosition {
get;
set; }
1075 public PointF InstanceOffset {
get; }