Application.Mouse.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. #nullable enable
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. namespace Terminal.Gui;
  5. public static partial class Application // Mouse handling
  6. {
  7. internal static Point _lastMousePosition = Point.Empty;
  8. /// <summary>
  9. /// Gets the most recent position of the mouse.
  10. /// </summary>
  11. public static Point GetLastMousePosition () => _lastMousePosition;
  12. /// <summary>Disable or enable the mouse. The mouse is enabled by default.</summary>
  13. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  14. public static bool IsMouseDisabled { get; set; }
  15. /// <summary>The current <see cref="View"/> object that wants continuous mouse button pressed events.</summary>
  16. public static View? WantContinuousButtonPressedView { get; private set; }
  17. /// <summary>
  18. /// Gets the view that grabbed the mouse (e.g. for dragging). When this is set, all mouse events will be routed to
  19. /// this view until the view calls <see cref="UngrabMouse"/> or the mouse is released.
  20. /// </summary>
  21. public static View? MouseGrabView { get; private set; }
  22. /// <summary>Invoked when a view wants to grab the mouse; can be canceled.</summary>
  23. public static event EventHandler<GrabMouseEventArgs>? GrabbingMouse;
  24. /// <summary>Invoked when a view wants un-grab the mouse; can be canceled.</summary>
  25. public static event EventHandler<GrabMouseEventArgs>? UnGrabbingMouse;
  26. /// <summary>Invoked after a view has grabbed the mouse.</summary>
  27. public static event EventHandler<ViewEventArgs>? GrabbedMouse;
  28. /// <summary>Invoked after a view has un-grabbed the mouse.</summary>
  29. public static event EventHandler<ViewEventArgs>? UnGrabbedMouse;
  30. /// <summary>
  31. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/>
  32. /// is called.
  33. /// </summary>
  34. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  35. public static void GrabMouse (View? view)
  36. {
  37. if (view is null || OnGrabbingMouse (view))
  38. {
  39. return;
  40. }
  41. OnGrabbedMouse (view);
  42. MouseGrabView = view;
  43. }
  44. /// <summary>Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.</summary>
  45. public static void UngrabMouse ()
  46. {
  47. if (MouseGrabView is null)
  48. {
  49. return;
  50. }
  51. #if DEBUG_IDISPOSABLE
  52. ObjectDisposedException.ThrowIf (MouseGrabView.WasDisposed, MouseGrabView);
  53. #endif
  54. if (!OnUnGrabbingMouse (MouseGrabView))
  55. {
  56. View view = MouseGrabView;
  57. MouseGrabView = null;
  58. OnUnGrabbedMouse (view);
  59. }
  60. }
  61. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  62. private static bool OnGrabbingMouse (View? view)
  63. {
  64. if (view is null)
  65. {
  66. return false;
  67. }
  68. var evArgs = new GrabMouseEventArgs (view);
  69. GrabbingMouse?.Invoke (view, evArgs);
  70. return evArgs.Cancel;
  71. }
  72. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  73. private static bool OnUnGrabbingMouse (View? view)
  74. {
  75. if (view is null)
  76. {
  77. return false;
  78. }
  79. var evArgs = new GrabMouseEventArgs (view);
  80. UnGrabbingMouse?.Invoke (view, evArgs);
  81. return evArgs.Cancel;
  82. }
  83. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  84. private static void OnGrabbedMouse (View? view)
  85. {
  86. if (view is null)
  87. {
  88. return;
  89. }
  90. GrabbedMouse?.Invoke (view, new (view));
  91. }
  92. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  93. private static void OnUnGrabbedMouse (View? view)
  94. {
  95. if (view is null)
  96. {
  97. return;
  98. }
  99. UnGrabbedMouse?.Invoke (view, new (view));
  100. }
  101. /// <summary>Event fired when a mouse move or click occurs. Coordinates are screen relative.</summary>
  102. /// <remarks>
  103. /// <para>
  104. /// Use this event to receive mouse events in screen coordinates. Use <see cref="MouseEvent"/> to
  105. /// receive mouse events relative to a <see cref="View.Viewport"/>.
  106. /// </para>
  107. /// <para>The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.</para>
  108. /// </remarks>
  109. public static event EventHandler<MouseEvent>? MouseEvent;
  110. /// <summary>Called when a mouse event is raised by the driver.</summary>
  111. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  112. /// <param name="mouseEvent">The mouse event with coordinates relative to the screen.</param>
  113. internal static void OnMouseEvent (MouseEvent mouseEvent)
  114. {
  115. _lastMousePosition = mouseEvent.ScreenPosition;
  116. if (IsMouseDisabled)
  117. {
  118. return;
  119. }
  120. // The position of the mouse is the same as the screen position at the application level.
  121. //Debug.Assert (mouseEvent.Position == mouseEvent.ScreenPosition);
  122. mouseEvent.Position = mouseEvent.ScreenPosition;
  123. List<View?> currentViewsUnderMouse = View.GetViewsUnderMouse (mouseEvent.ScreenPosition);
  124. View? deepestViewUnderMouse = currentViewsUnderMouse.LastOrDefault ();
  125. if (deepestViewUnderMouse is { })
  126. {
  127. #if DEBUG_IDISPOSABLE
  128. if (deepestViewUnderMouse.WasDisposed)
  129. {
  130. throw new ObjectDisposedException (deepestViewUnderMouse.GetType ().FullName);
  131. }
  132. #endif
  133. mouseEvent.View = deepestViewUnderMouse;
  134. }
  135. MouseEvent?.Invoke (null, mouseEvent);
  136. if (mouseEvent.Handled)
  137. {
  138. return;
  139. }
  140. if (HandleMouseGrab (deepestViewUnderMouse, mouseEvent))
  141. {
  142. return;
  143. }
  144. // We can combine this into the switch expression to reduce cognitive complexity even more and likely
  145. // avoid one or two of these checks in the process, as well.
  146. WantContinuousButtonPressedView = deepestViewUnderMouse switch
  147. {
  148. { WantContinuousButtonPressed: true } => deepestViewUnderMouse,
  149. _ => null
  150. };
  151. // May be null before the prior condition or the condition may set it as null.
  152. // So, the checking must be outside the prior condition.
  153. if (deepestViewUnderMouse is null)
  154. {
  155. return;
  156. }
  157. // Create a view-relative mouse event to send to the view that is under the mouse.
  158. MouseEvent? viewMouseEvent;
  159. if (deepestViewUnderMouse is Adornment adornment)
  160. {
  161. Point frameLoc = adornment.ScreenToFrame (mouseEvent.ScreenPosition);
  162. viewMouseEvent = new ()
  163. {
  164. Position = frameLoc,
  165. Flags = mouseEvent.Flags,
  166. ScreenPosition = mouseEvent.ScreenPosition,
  167. View = deepestViewUnderMouse
  168. };
  169. }
  170. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.Position))
  171. {
  172. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  173. viewMouseEvent = new ()
  174. {
  175. Position = viewportLocation,
  176. Flags = mouseEvent.Flags,
  177. ScreenPosition = mouseEvent.ScreenPosition,
  178. View = deepestViewUnderMouse
  179. };
  180. }
  181. else
  182. {
  183. // The mouse was outside any View's Viewport.
  184. return;
  185. }
  186. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  187. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  188. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  189. {
  190. if (deepestViewUnderMouse is Adornment adornmentView)
  191. {
  192. deepestViewUnderMouse = adornmentView.Parent!.SuperView;
  193. }
  194. else
  195. {
  196. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  197. }
  198. if (deepestViewUnderMouse is null)
  199. {
  200. break;
  201. }
  202. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  203. viewMouseEvent = new ()
  204. {
  205. Position = boundsPoint,
  206. Flags = mouseEvent.Flags,
  207. ScreenPosition = mouseEvent.ScreenPosition,
  208. View = deepestViewUnderMouse
  209. };
  210. }
  211. }
  212. internal static bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEvent mouseEvent)
  213. {
  214. if (MouseGrabView is { })
  215. {
  216. #if DEBUG_IDISPOSABLE
  217. if (MouseGrabView.WasDisposed)
  218. {
  219. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  220. }
  221. #endif
  222. // If the mouse is grabbed, send the event to the view that grabbed it.
  223. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  224. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  225. var viewRelativeMouseEvent = new MouseEvent
  226. {
  227. Position = frameLoc,
  228. Flags = mouseEvent.Flags,
  229. ScreenPosition = mouseEvent.ScreenPosition,
  230. View = deepestViewUnderMouse ?? MouseGrabView
  231. };
  232. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  233. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  234. {
  235. return true;
  236. }
  237. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  238. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  239. {
  240. // The view that grabbed the mouse has been disposed
  241. return true;
  242. }
  243. }
  244. return false;
  245. }
  246. internal static readonly List<View?> _cachedViewsUnderMouse = new ();
  247. // TODO: Refactor MouseEnter/LeaveEvents to not take MouseEvent param.
  248. /// <summary>
  249. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  250. /// </summary>
  251. /// <param name="screenPosition">The position of the mouse.</param>
  252. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderMouse().</param>
  253. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  254. {
  255. // Tell any views that are no longer under the mouse that the mouse has left
  256. List<View?> viewsToLeave = _cachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  257. foreach (View? view in viewsToLeave)
  258. {
  259. if (view is null)
  260. {
  261. continue;
  262. }
  263. view.NewMouseLeaveEvent ();
  264. _cachedViewsUnderMouse.Remove (view);
  265. }
  266. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  267. foreach (View? view in currentViewsUnderMouse)
  268. {
  269. if (view is null)
  270. {
  271. continue;
  272. }
  273. if (_cachedViewsUnderMouse.Contains (view))
  274. {
  275. continue;
  276. }
  277. _cachedViewsUnderMouse.Add (view);
  278. var raise = false;
  279. if (view is Adornment { Parent: { } } adornmentView)
  280. {
  281. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  282. raise = adornmentView.Contains (superViewLoc);
  283. }
  284. else
  285. {
  286. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  287. raise = view.Contains (superViewLoc);
  288. }
  289. if (!raise)
  290. {
  291. continue;
  292. }
  293. CancelEventArgs eventArgs = new ();
  294. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  295. if (cancelled is true || eventArgs.Cancel)
  296. {
  297. break;
  298. }
  299. }
  300. }
  301. }