Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
WidgetInputRouter.cs
1using System.Drawing;
2using System.Numerics;
10
11namespace Gondwana.Widgets;
12
16public sealed class WidgetInputRouter : IDisposable
17{
21 public const int MousePointerId = -1;
22
23 private static readonly MouseButton[] _mouseButtons =
24 [
25 MouseButton.Left,
26 MouseButton.Right,
28 ];
29
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 = [];
35
36 private readonly RenderSurfaceHostBase _renderSurfaceHost;
37 private readonly KeyboardEventPoller? _keyboardEventPoller;
38 private readonly MouseEventPoller? _mouseEventPoller;
39 private readonly TouchEventPoller? _touchEventPoller;
40
41 private PointerCapture? _mouseCapture;
42 private WidgetHit? _hoveredHit;
43 private WidgetBase? _focusedWidget;
44
45 private bool _isStarted;
46 private bool _disposed;
47
56 RenderSurfaceHostBase renderSurfaceHost,
57 KeyboardEventPoller? keyboardEventPoller,
58 MouseEventPoller? mouseEventPoller,
59 TouchEventPoller? touchEventPoller)
60 {
61 _renderSurfaceHost = renderSurfaceHost ?? throw new ArgumentNullException(nameof(renderSurfaceHost));
62
63 _keyboardEventPoller = keyboardEventPoller;
64 _mouseEventPoller = mouseEventPoller;
65 _touchEventPoller = touchEventPoller;
66 }
67
74 public WidgetBase? FocusedWidget => _focusedWidget;
75
81 public Func<int, int>? KeyboardCodeMapper { get; set; }
82
92 public event Action<PrimaryPointerActionEventArgs>? UnhandledPrimaryAction;
93
98 public void Register(WidgetBase widget)
99 {
100 ObjectDisposedException.ThrowIf(_disposed, this);
101 ArgumentNullException.ThrowIfNull(widget);
102
103 if (!ReferenceEquals(widget.RenderSurfaceHost, _renderSurfaceHost))
104 {
105 throw new ArgumentException("The widget belongs to a different RenderSurfaceHost.", nameof(widget));
106 }
107
108 lock (_syncRoot)
109 {
110 if (_widgets.Contains(widget))
111 return;
112
113 _widgets.Add(widget);
114 widget.Disposing += OnWidgetDisposing;
115 }
116 }
117
122 public void Unregister(WidgetBase widget)
123 {
124 ArgumentNullException.ThrowIfNull(widget);
125 Unregister(widget, dispatchPointerUp: true);
126 }
127
132 public void BringToFront(WidgetBase widget)
133 {
134 ObjectDisposedException.ThrowIf(_disposed, this);
135 ArgumentNullException.ThrowIfNull(widget);
136
137 lock (_syncRoot)
138 {
139 if (!_widgets.Remove(widget))
140 throw new InvalidOperationException("The widget is not registered.");
141
142 _widgets.Add(widget);
143 }
144 }
145
150 public void Focus(WidgetBase? widget)
151 {
152 if (ReferenceEquals(_focusedWidget, widget))
153 return;
154
155 if (widget is not null && !CanReceiveKeyboardInput(widget))
156 return;
157
158 WidgetBase? previous = _focusedWidget;
159 _focusedWidget = widget;
160
161 previous?.DispatchFocusLost();
162 widget?.DispatchFocusGained();
163 }
164
168 public void ClearFocus()
169 {
170 Focus(null);
171 }
172
176 public void Start()
177 {
178 ObjectDisposedException.ThrowIf(_disposed, this);
179
180 if (_isStarted)
181 return;
182
183 if (_keyboardEventPoller is not null)
184 _keyboardEventPoller.KeyDown += OnKeyDown;
185
186 if (_mouseEventPoller is not null)
187 _mouseEventPoller.MouseEvent += OnMouseEvent;
188
189 if (_touchEventPoller is not null)
190 {
191 _touchEventPoller.TouchBegan += OnTouchBegan;
192 _touchEventPoller.TouchMoved += OnTouchMoved;
193 _touchEventPoller.TouchEnded += OnTouchEnded;
194 _touchEventPoller.TouchEvent += OnTouchGesture;
195 }
196
197 WidgetInputRouterRegistry.Attach(
198 _renderSurfaceHost,
199 this);
200
201 _isStarted = true;
202 }
203
207 public void Stop()
208 {
209 if (!_isStarted)
210 return;
211
212 WidgetInputRouterRegistry.Detach(
213 _renderSurfaceHost,
214 this);
215
216 if (_keyboardEventPoller is not null)
217 _keyboardEventPoller.KeyDown -= OnKeyDown;
218
219 if (_mouseEventPoller is not null)
220 _mouseEventPoller.MouseEvent -= OnMouseEvent;
221
222 if (_touchEventPoller is not null)
223 {
224 _touchEventPoller.TouchBegan -= OnTouchBegan;
225 _touchEventPoller.TouchMoved -= OnTouchMoved;
226 _touchEventPoller.TouchEnded -= OnTouchEnded;
227 _touchEventPoller.TouchEvent -= OnTouchGesture;
228 }
229
230 ClearFocus();
231
232 _mouseCapture = null;
233 _touchCaptures.Clear();
234 _unhandledTouchContacts.Clear();
235 _pendingTaps.Clear();
236 _hoveredHit = null;
237 _isStarted = false;
238 }
239
243 public void Dispose()
244 {
245 if (_disposed)
246 return;
247
248 Stop();
249
250 WidgetBase[] widgets;
251
252 lock (_syncRoot)
253 {
254 widgets = [.. _widgets];
255 _widgets.Clear();
256 }
257
258 foreach (WidgetBase widget in widgets)
259 widget.Disposing -= OnWidgetDisposing;
260
261 _disposed = true;
262 }
263
264 internal void NotifyWidgetHidden(WidgetBase widget)
265 {
266 ArgumentNullException.ThrowIfNull(widget);
267 ReleaseInputState(widget, dispatchPointerUp: true);
268 }
269
270 internal void NotifyWidgetInputDisabled(WidgetBase widget)
271 {
272 ArgumentNullException.ThrowIfNull(widget);
273 ReleaseInputState(widget, dispatchPointerUp: true);
274 }
275
276 internal void NotifyWidgetPointerInputDisabled(WidgetBase widget)
277 {
278 ArgumentNullException.ThrowIfNull(widget);
279 ReleasePointerState(widget, dispatchPointerUp: true);
280 }
281
282 internal void NotifyWidgetKeyboardFocusDisabled(WidgetBase widget)
283 {
284 ArgumentNullException.ThrowIfNull(widget);
285 ReleaseKeyboardFocus(widget);
286 }
287
288 private void OnKeyDown(KeyDownEventArgs args)
289 {
290 if (!_isStarted || _disposed)
291 return;
292
293 if (!int.TryParse(args.KeyConfig.Key, out int key))
294 return;
295
296 RouteKeyboardInput(KeyboardCodeMapper?.Invoke(key) ?? key, args.KeyAction, args.Modifiers);
297 }
298
299 internal void RouteKeyboardInput(int key, KeyAction action, KeyboardModifierState modifiers)
300 {
301 WidgetBase? target = _focusedWidget;
302
303 if (target is not null && !CanReceiveKeyboardInput(target))
304 {
305 ClearFocus();
306 target = null;
307 }
308
309 if (target is not null)
310 {
311 var focusedArgs = new WidgetKeyboardEventArgs(
312 target,
313 key,
314 action,
315 modifiers);
316
317 target.DispatchKeyboardInput(focusedArgs);
318
319 if (focusedArgs.Handled)
320 return;
321 }
322
323 WidgetBase[] snapshot;
324
325 lock (_syncRoot)
326 snapshot = [.. _widgets];
327
328 // Most recently activated/registered eligible bar wins, just like pointer routing.
329 for (int index = snapshot.Length - 1; index >= 0; index--)
330 {
331 WidgetBase widget = snapshot[index];
332
333 if (widget is not IWidgetKeyboardFallback fallback || !IsRegistered(widget) ||
334 !HasValidTarget(widget) || !widget.Visible ||
335 !widget.IsInputEnabled || !widget.IsKeyboardInputEnabled)
336 continue;
337
338 var fallbackArgs = new WidgetKeyboardEventArgs(
339 widget,
340 key,
341 action,
342 modifiers);
343
344 fallback.HandleUnhandledKeyboardInput(fallbackArgs);
345
346 if (fallbackArgs.Handled)
347 return;
348 }
349 }
350
351 private void OnMouseEvent(MouseEventArgs args)
352 {
353 if (!_isStarted || _disposed)
354 return;
355
356 Point currentPosition = args.CurrentPosition;
357 WidgetHit? initialHit = HitTest(currentPosition);
358
359 UpdateMouseHover(initialHit, currentPosition, args.Tick);
360
361 foreach (MouseButton mouseButton in _mouseButtons)
362 {
363 if (args.IsButtonJustPressed(mouseButton))
364 {
365 ProcessMouseDown(
366 initialHit,
367 currentPosition,
368 mouseButton,
369 args.Tick);
370 }
371 }
372
373 // A widget hit or an existing pointer capture takes precedence over gameplay.
374 if (args.LeftButtonJustPressed && initialHit is null && _mouseCapture is null &&
375 GetTopmostViewAt(currentPosition) is View gameplayView)
376 {
378 new PrimaryPointerActionEventArgs(
379 gameplayView,
380 currentPosition,
381 isTouch: false,
383 }
384
385 if (args.PreviousPosition != currentPosition)
386 {
387 ProcessMouseMove(args.PreviousPosition, currentPosition, args.Tick);
388 }
389
390 if (args.ScrollDelta != 0 && initialHit is not null && IsPointerRoutable(initialHit.Widget, initialHit.View))
391 {
392 initialHit.Widget.DispatchMouseWheel(
393 new WidgetMouseWheelEventArgs(
394 initialHit.Widget,
395 initialHit.View,
396 new PointF(currentPosition.X, currentPosition.Y),
397 args.ScrollDelta,
398 args.Tick));
399 }
400
401 foreach (MouseButton mouseButton in _mouseButtons)
402 {
403 if (args.IsButtonJustReleased(mouseButton))
404 {
405 ProcessMouseUp(currentPosition, mouseButton, args.Tick);
406 }
407 }
408
409 UpdateMouseHover(HitTest(currentPosition), currentPosition, args.Tick);
410 }
411
412 private void ProcessMouseDown(
413 WidgetHit? hit,
414 Point position,
415 MouseButton mouseButton,
416 long tick)
417 {
418 if (_mouseCapture is not null || hit is null)
419 return;
420
421 FocusFromPointer(hit.Widget);
422
423 WidgetPointerButtonEnum widgetButton = MapMouseButton(mouseButton);
424
425 hit.Widget.DispatchPointerDown(
426 CreatePointerArgs(
427 hit.Widget,
428 hit.View,
429 position,
430 widgetButton,
431 tick,
433
434 _mouseCapture = new PointerCapture(
435 hit.Widget,
436 hit.View,
437 widgetButton,
438 position,
439 hit.InstanceOffset);
440 }
441
442 private void ProcessMouseMove(
443 Point previousPosition,
444 Point currentPosition,
445 long tick)
446 {
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;
451
452 if (recipient is null || view is null)
453 return;
454
455 var delta = new Vector2(
456 currentPosition.X - previousPosition.X,
457 currentPosition.Y - previousPosition.Y);
458
459 WidgetPointerButtonEnum button = capture?.Button ?? WidgetPointerButtonEnum.None;
460
461 recipient.DispatchPointerMove(
462 CreatePointerArgs(
463 recipient,
464 view,
465 currentPosition,
466 button,
467 tick,
469 deltaPx: delta));
470
471 if (capture is not null)
472 capture.LastPosition = currentPosition;
473 }
474
475 private void ProcessMouseUp(
476 Point position,
477 MouseButton mouseButton,
478 long tick)
479 {
480 WidgetPointerButtonEnum releasedButton = MapMouseButton(mouseButton);
481 PointerCapture? capture = GetValidMouseCapture(tick);
482
483 if (capture is null || capture.Button != releasedButton)
484 return;
485
486 WidgetBase recipient = capture.Widget;
487
488 recipient.DispatchPointerUp(
489 CreatePointerArgs(
490 recipient,
491 capture.View,
492 position,
493 releasedButton,
494 tick,
496
497 WidgetHit? releaseHit = HitTest(position);
498
499 if (IsSameHit(releaseHit, recipient, capture.View) &&
500 recipient.GetWrappedHitOffset(capture.View, position) == capture.InstanceOffset)
501 {
502 recipient.DispatchPointerClick(
503 CreatePointerArgs(
504 recipient,
505 capture.View,
506 position,
507 releasedButton,
508 tick,
510 clickCount: 1));
511 }
512
513 _mouseCapture = null;
514 }
515
516 private void UpdateMouseHover(
517 WidgetHit? hit,
518 Point position,
519 long tick)
520 {
521 if (IsSameHit(_hoveredHit, hit))
522 return;
523
524 WidgetHit? previous = _hoveredHit;
525 _hoveredHit = hit;
526
527 if (previous is not null)
528 {
529 previous.Widget.DispatchPointerLeave(
530 CreatePointerArgs(
531 previous.Widget,
532 previous.View,
533 position,
535 tick,
537 }
538
539 if (hit is not null)
540 {
541 hit.Widget.DispatchPointerEnter(
542 CreatePointerArgs(
543 hit.Widget,
544 hit.View,
545 position,
547 tick,
549 }
550 }
551
552 private PointerCapture? GetValidMouseCapture(long tick)
553 {
554 if (_mouseCapture is null)
555 return null;
556
557 if (IsPointerRoutable(_mouseCapture.Widget, _mouseCapture.View))
558 return _mouseCapture;
559
560 _mouseCapture.Widget.DispatchPointerUp(
561 CreatePointerArgs(
562 _mouseCapture.Widget,
563 _mouseCapture.View,
564 _mouseCapture.LastPosition,
565 _mouseCapture.Button,
566 tick,
568
569 _mouseCapture = null;
570 return null;
571 }
572
573 private void OnTouchBegan(object? sender, TouchEventArgs args)
574 {
575 if (!_isStarted || _disposed)
576 return;
577
578 TouchPoint touch = args.Touch;
579
580 // A poller pause/reset may discard TouchEnded. IDs can be reused after
581 // resuming, so treat every emitted TouchBegan as a new logical contact
582 // boundary and reset both gameplay eligibility and widget capture for the ID.
583 _unhandledTouchContacts.Remove(touch.Id);
584 _touchCaptures.Remove(touch.Id);
585 _pendingTaps.Remove(touch.Id);
586
587 WidgetHit? hit = HitTest(touch.Position);
588
589 if (hit is null)
590 {
591 if (GetTopmostViewAt(touch.Position) is not null)
592 _unhandledTouchContacts.Add(touch.Id);
593
594 return;
595 }
596
597 FocusFromPointer(hit.Widget);
598
599 hit.Widget.DispatchPointerDown(
600 CreatePointerArgs(
601 hit.Widget,
602 hit.View,
603 touch.Position,
605 args.Tick,
606 touch.Id));
607
608 _touchCaptures[touch.Id] = new PointerCapture(
609 hit.Widget,
610 hit.View,
612 touch.Position,
613 hit.InstanceOffset);
614 }
615
616 private void OnTouchMoved(object? sender, TouchEventArgs args)
617 {
618 if (!_isStarted || _disposed)
619 return;
620
621 TouchPoint touch = args.Touch;
622
623 if (!_touchCaptures.TryGetValue(touch.Id, out PointerCapture? capture))
624 return;
625
626 if (!IsPointerRoutable(capture.Widget, capture.View))
627 {
628 capture.Widget.DispatchPointerUp(
629 CreatePointerArgs(
630 capture.Widget,
631 capture.View,
632 capture.LastPosition,
634 args.Tick,
635 touch.Id));
636
637 _touchCaptures.Remove(touch.Id);
638 return;
639 }
640
641 var delta = new Vector2(
642 touch.Position.X - capture.LastPosition.X,
643 touch.Position.Y - capture.LastPosition.Y);
644
645 capture.Widget.DispatchPointerMove(
646 CreatePointerArgs(
647 capture.Widget,
648 capture.View,
649 touch.Position,
651 args.Tick,
652 touch.Id,
653 deltaPx: delta));
654
655 capture.LastPosition = touch.Position;
656 }
657
658 private void OnTouchEnded(object? sender, TouchEventArgs args)
659 {
660 if (!_isStarted || _disposed)
661 return;
662
663 TouchPoint touch = args.Touch;
664
665 // The poller's tap recognizer dispatches the gesture during TouchEnded,
666 // before the router clears this contact's eligibility.
667 bool wasUnhandled = _unhandledTouchContacts.Remove(touch.Id);
668 bool hasPendingTap = _pendingTaps.Remove(touch.Id, out TappedEventArgs? tap);
669
670 if (hasPendingTap && wasUnhandled && tap is not null && touch.Phase != TouchPhase.Cancelled)
671 {
672 View? releaseView = GetTopmostViewAt(touch.Position);
673 View? tapView = GetTopmostViewAt(tap.Position);
674
675 if (releaseView is not null &&
676 releaseView == tapView &&
677 HitTest(touch.Position) is null &&
678 HitTest(tap.Position) is null)
679 {
681 new PrimaryPointerActionEventArgs(
682 releaseView,
683 tap.Position,
684 isTouch: true,
685 tap.TouchId));
686 }
687 }
688
689 if (!_touchCaptures.Remove(touch.Id, out PointerCapture? capture))
690 return;
691
692 WidgetBase recipient = capture.Widget;
693
694 recipient.DispatchPointerUp(
695 CreatePointerArgs(
696 recipient,
697 capture.View,
698 touch.Position,
700 args.Tick,
701 touch.Id,
702 instanceOffset: capture.InstanceOffset));
703
704 WidgetHit? releaseHit = HitTest(touch.Position);
705
706 if (touch.Phase != TouchPhase.Cancelled && IsSameHit(releaseHit, recipient, capture.View) &&
707 recipient.GetWrappedHitOffset(capture.View, touch.Position) == capture.InstanceOffset)
708 {
709 recipient.DispatchPointerClick(
710 CreatePointerArgs(
711 recipient,
712 capture.View,
713 touch.Position,
715 args.Tick,
716 touch.Id,
717 clickCount: 1,
718 instanceOffset: capture.InstanceOffset));
719 }
720 }
721
722 private void OnTouchGesture(GestureEventArgs args)
723 {
724 if (!_isStarted || _disposed || !args.IsTap || args.Tap is null)
725 return;
726
727 var tap = args.Tap;
728
729 if (!_unhandledTouchContacts.Contains(tap.TouchId))
730 return;
731
732 _pendingTaps[tap.TouchId] = tap;
733 }
734
735 private WidgetHit? HitTest(Point screenPositionPx)
736 {
737 View? view = GetTopmostViewAt(screenPositionPx);
738
739 if (view is null)
740 return null;
741
742 WidgetBase[] snapshot;
743
744 lock (_syncRoot)
745 snapshot = [.. _widgets];
746
747 for (int index = snapshot.Length - 1; index >= 0; index--)
748 {
749 WidgetBase widget = snapshot[index];
750
751 if (widget.HitTest(view, screenPositionPx))
752 return new WidgetHit(widget, view, widget.GetWrappedHitOffset(view, screenPositionPx) ?? PointF.Empty);
753 }
754
755 return null;
756 }
757
758 private View? GetTopmostViewAt(Point screenPositionPx)
759 {
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))
764 return null;
765
766 var views = _renderSurfaceHost.ViewManager.Views;
767
768 for (int index = views.Count - 1; index >= 0; index--)
769 {
770 View view = views[index];
771
772 if (view.Viewport.TargetRectPx.Contains(screenPositionPx))
773 return view;
774 }
775
776 return null;
777 }
778
779 private bool IsRegistered(WidgetBase widget)
780 {
781 lock (_syncRoot)
782 return _widgets.Contains(widget);
783 }
784
785 private bool IsManagedView(View view)
786 {
787 return _renderSurfaceHost.ViewManager.Views.Contains(view);
788 }
789
790 private bool HasValidTarget(
791 WidgetBase widget,
792 View? routedView = null)
793 {
794 if (widget.Mode == DirectDrawingMode.SceneLayer)
795 return widget.SceneLayer is not null;
796
797 if (widget.View is null || !IsManagedView(widget.View))
798 return false;
799
800 return routedView is null || ReferenceEquals(widget.View, routedView);
801 }
802
803 private bool IsPointerRoutable(
804 WidgetBase widget,
805 View view)
806 {
807 return IsRegistered(widget) &&
808 IsManagedView(view) &&
809 ReferenceEquals(widget.RenderSurfaceHost, _renderSurfaceHost) &&
810 HasValidTarget(widget, view) &&
811 widget.IsInputEnabled &&
812 widget.IsPointerInputEnabled &&
813 widget.Visible;
814 }
815
816 private bool CanReceiveKeyboardInput(WidgetBase widget)
817 {
818 return IsRegistered(widget) &&
819 ReferenceEquals(widget.RenderSurfaceHost, _renderSurfaceHost) &&
820 HasValidTarget(widget) &&
821 widget.Visible &&
822 widget.IsInputEnabled &&
823 widget.IsKeyboardInputEnabled &&
824 widget.CanReceiveFocus;
825 }
826
827 private void FocusFromPointer(WidgetBase widget)
828 {
829 if (widget.IsInputEnabled &&
830 widget.IsKeyboardInputEnabled &&
831 widget.CanReceiveFocus)
832 {
833 Focus(widget);
834 }
835 }
836
837 private void ReleaseInputState(
838 WidgetBase widget,
839 bool dispatchPointerUp)
840 {
841 ReleasePointerState(
842 widget,
843 dispatchPointerUp);
844
845 ReleaseKeyboardFocus(widget);
846 }
847
848 private void ReleasePointerState(
849 WidgetBase widget,
850 bool dispatchPointerUp)
851 {
852 if (ReferenceEquals(_hoveredHit?.Widget, widget))
853 _hoveredHit = null;
854
855 if (ReferenceEquals(_mouseCapture?.Widget, widget))
856 {
857 PointerCapture capture = _mouseCapture;
858
859 if (dispatchPointerUp)
860 {
861 widget.DispatchPointerUp(
862 CreatePointerArgs(
863 widget,
864 capture.View,
865 capture.LastPosition,
866 capture.Button,
867 tick: 0,
868 pointerId: MousePointerId));
869 }
870
871 _mouseCapture = null;
872 }
873
874 int[] touchIds = _touchCaptures.Where(x => ReferenceEquals(x.Value.Widget, widget))
875 .Select(x => x.Key)
876 .ToArray();
877
878 foreach (int touchId in touchIds)
879 {
880 PointerCapture capture = _touchCaptures[touchId];
881
882 if (dispatchPointerUp)
883 {
884 widget.DispatchPointerUp(
885 CreatePointerArgs(
886 widget,
887 capture.View,
888 capture.LastPosition,
890 tick: 0,
891 pointerId: touchId));
892 }
893
894 _touchCaptures.Remove(touchId);
895 }
896 }
897
898 private void ReleaseKeyboardFocus(WidgetBase widget)
899 {
900 if (ReferenceEquals(_focusedWidget, widget))
901 Focus(null);
902 }
903
904 private static bool IsSameHit(
905 WidgetHit? left,
906 WidgetHit? right)
907 {
908 if (left is null || right is null)
909 return left is null && right is null;
910
911 return ReferenceEquals(left.Widget, right.Widget)
912 && ReferenceEquals(left.View, right.View);
913 }
914
915 private static bool IsSameHit(
916 WidgetHit? hit,
917 WidgetBase widget,
918 View view)
919 {
920 return hit is not null
921 && ReferenceEquals(hit.Widget, widget)
922 && ReferenceEquals(hit.View, view);
923 }
924
925 private WidgetPointerEventArgs CreatePointerArgs(
926 WidgetBase widget,
927 View view,
928 Point position,
930 long tick,
931 int pointerId,
932 int clickCount = 0,
933 Vector2 deltaPx = default,
934 PointF? instanceOffset = null)
935 {
936 return new WidgetPointerEventArgs(
937 widget,
938 view,
939 new PointF(position.X, position.Y),
940 button,
941 clickCount,
942 deltaPx,
943 tick,
944 pointerId)
945 {
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)
952 };
953 }
954
955 private static WidgetPointerButtonEnum MapMouseButton(MouseButton button)
956 {
957 return button switch
958 {
959 MouseButton.Left => WidgetPointerButtonEnum.Left,
960 MouseButton.Right => WidgetPointerButtonEnum.Right,
961 MouseButton.Middle => WidgetPointerButtonEnum.Middle,
962 _ => WidgetPointerButtonEnum.None
963 };
964 }
965
966 private void OnWidgetDisposing(object? sender, IDirectDrawable drawing)
967 {
968 if (drawing is WidgetBase widget)
969 {
970 Unregister(widget, dispatchPointerUp: false);
971 }
972 }
973
974 private void Unregister(
975 WidgetBase widget,
976 bool dispatchPointerUp)
977 {
978 bool removed;
979
980 lock (_syncRoot)
981 removed = _widgets.Remove(widget);
982
983 if (!removed)
984 return;
985
986 widget.Disposing -= OnWidgetDisposing;
987
988 ReleaseInputState(widget, dispatchPointerUp);
989 }
990
991 private sealed class WidgetHit
992 {
999 public WidgetHit(
1000 WidgetBase widget,
1001 View view,
1002 PointF instanceOffset)
1003 {
1004 Widget = widget;
1005 View = view;
1006 InstanceOffset = instanceOffset;
1007 }
1008
1012 public PointF InstanceOffset { get; }
1013
1017 public WidgetBase Widget { get; }
1018
1022 public View View { get; }
1023 }
1024
1025 private sealed class PointerCapture
1026 {
1035 public PointerCapture(
1036 WidgetBase widget,
1037 View view,
1039 Point lastPosition,
1040 PointF instanceOffset)
1041 {
1042 Widget = widget;
1043 View = view;
1044 Button = button;
1045 LastPosition = lastPosition;
1046 InstanceOffset = instanceOffset;
1047 }
1048
1052 public WidgetBase Widget { get; }
1053
1057 public View View { get; }
1058
1062 public WidgetPointerButtonEnum Button { get; }
1063
1070 public Point LastPosition { get; set; }
1071
1075 public PointF InstanceOffset { get; }
1076 }
1077}
RenderSurfaceHostBase RenderSurfaceHost
Gets the render surface host shared by the composite and its children.
virtual DirectComposite Clear()
Removes every child without disposing them.
KeyboardModifierState Modifiers
Gets the state of keyboard modifier keys (Shift, Ctrl, Alt) at the time this event was generated....
KeyEventConfiguration KeyConfig
Gets the configuration details for the keyboard key that generated this event, including the key iden...
KeyAction KeyAction
Gets the type of action that occurred for this key, indicating whether the key was initially pressed,...
string Key
Gets the identifier of the keyboard key associated with this configuration. This can be a key name su...
Cross-platform singleton keyboard handler with throttling and manual input state feeding.
Point PreviousPosition
Gets the previous position of the mouse cursor before the current polling interval....
bool LeftButtonJustPressed
Gets a value indicating whether the left mouse button was pressed during the current polling interval...
Point CurrentPosition
Gets the current position of the mouse cursor at the time this event was generated....
long Tick
Gets the engine tick at the time this mouse event was generated.
bool IsButtonJustReleased(MouseButton button)
Determines whether the specified mouse button was released during the current polling interval.
int ScrollDelta
Gets the accumulated scroll wheel delta since the last poll, measured in implementation-defined units...
bool IsButtonJustPressed(MouseButton button)
Determines whether the specified mouse button was pressed during the current polling interval.
Provides centralized polling and event management for mouse input, including button presses,...
TappedEventArgs? Tap
Gets data specific to a tap gesture, or null when GestureType is not GestureType.Tap.
bool IsTap
Gets a value indicating whether this event represents a tap gesture. When true, Tap is non-null.
TouchPoint Touch
Gets the touch contact point associated with this event.
long Tick
Gets the engine tick at which this touch event was emitted.
Provides centralized polling and event management for touch input. This singleton class monitors touc...
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
Viewport Viewport
Gets the viewport that defines the screen-space rectangle, zoom level, and other rendering parameters...
Definition View.cs:44
Rectangle TargetRectPx
Screen-space rectangle (in SCREEN / RenderSurface pixels) where this view is drawn....
Definition Viewport.cs:40
Provides the base implementation for widgets that can be drawn and receive pointer,...
Definition WidgetBase.cs:12
void Focus(WidgetBase? widget)
Assigns keyboard focus to the specified widget.
void Unregister(WidgetBase widget)
Unregisters a widget so that it no longer receives routed input.
void ClearFocus()
Clears the current keyboard focus.
void Start()
Starts routing input events from the configured pollers to registered widgets.
void BringToFront(WidgetBase widget)
Moves a registered widget to the front of the input routing order.
WidgetBase? FocusedWidget
Gets the widget that currently has keyboard focus.
Func< int, int >? KeyboardCodeMapper
Optional translation from adapter-specific key codes into the key codes expected by widget controls (...
void Stop()
Stops routing input events and releases current pointer and focus state.
void Register(WidgetBase widget)
Registers a widget so that it can receive routed input.
Action< PrimaryPointerActionEventArgs >? UnhandledPrimaryAction
Occurs when a primary gameplay action was not claimed by a widget. Mouse left-button presses fire on ...
WidgetInputRouter(RenderSurfaceHostBase renderSurfaceHost, KeyboardEventPoller? keyboardEventPoller, MouseEventPoller? mouseEventPoller, TouchEventPoller? touchEventPoller)
Initializes a new instance of the WidgetInputRouter class.
void Dispose()
Releases the resources used by the router and unregisters all widgets.
const int MousePointerId
Identifies mouse pointer events in routed widget input.
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
@ View
Performs direct drawing at the view level using screen-space coordinates.
KeyboardModifierState
Represents the state of keyboard modifier keys (Shift, Ctrl, Alt) that can be pressed simultaneously ...
KeyAction
Represents the type of action performed on a keyboard key, indicating whether the key was pressed,...
Definition KeyAction.cs:10
MouseButton
Represents mouse button identifiers that can be used individually or combined to represent multiple s...
@ Middle
The middle mouse button, usually implemented as a clickable scroll wheel. This is often used for spec...
readonly record struct TouchPoint(int Id, Point Position, TouchPhase Phase)
Represents a single touch contact point, capturing its unique identifier, screen position,...
TouchPhase
Describes the current phase of a single touch contact point in its lifecycle.
Definition TouchPhase.cs:7
WidgetPointerButtonEnum
Represents a pointer button used by a widget interaction.