Application.Mouse.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. mouseEvent.Position = mouseEvent.ScreenPosition;
  122. List<View?> currentViewsUnderMouse = View.GetViewsUnderMouse (mouseEvent.ScreenPosition);
  123. View? deepestViewUnderMouse = currentViewsUnderMouse.LastOrDefault ();
  124. if (deepestViewUnderMouse is { })
  125. {
  126. #if DEBUG_IDISPOSABLE
  127. if (deepestViewUnderMouse.WasDisposed)
  128. {
  129. throw new ObjectDisposedException (deepestViewUnderMouse.GetType ().FullName);
  130. }
  131. #endif
  132. mouseEvent.View = deepestViewUnderMouse;
  133. }
  134. MouseEvent?.Invoke (null, mouseEvent);
  135. if (mouseEvent.Handled)
  136. {
  137. return;
  138. }
  139. if (HandleMouseGrab (deepestViewUnderMouse, mouseEvent))
  140. {
  141. return;
  142. }
  143. // We can combine this into the switch expression to reduce cognitive complexity even more and likely
  144. // avoid one or two of these checks in the process, as well.
  145. WantContinuousButtonPressedView = deepestViewUnderMouse switch
  146. {
  147. { WantContinuousButtonPressed: true } => deepestViewUnderMouse,
  148. _ => null
  149. };
  150. // May be null before the prior condition or the condition may set it as null.
  151. // So, the checking must be outside the prior condition.
  152. if (deepestViewUnderMouse is null)
  153. {
  154. return;
  155. }
  156. // Create a view-relative mouse event to send to the view that is under the mouse.
  157. MouseEvent? viewMouseEvent;
  158. if (deepestViewUnderMouse is Adornment adornment)
  159. {
  160. Point frameLoc = adornment.ScreenToFrame (mouseEvent.ScreenPosition);
  161. viewMouseEvent = new ()
  162. {
  163. Position = frameLoc,
  164. Flags = mouseEvent.Flags,
  165. ScreenPosition = mouseEvent.ScreenPosition,
  166. View = deepestViewUnderMouse
  167. };
  168. }
  169. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.Position))
  170. {
  171. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  172. viewMouseEvent = new ()
  173. {
  174. Position = viewportLocation,
  175. Flags = mouseEvent.Flags,
  176. ScreenPosition = mouseEvent.ScreenPosition,
  177. View = deepestViewUnderMouse
  178. };
  179. }
  180. else
  181. {
  182. // The mouse was outside any View's Viewport.
  183. return;
  184. }
  185. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  186. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  187. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  188. {
  189. if (deepestViewUnderMouse is Adornment adornmentView)
  190. {
  191. deepestViewUnderMouse = adornmentView.Parent!.SuperView;
  192. }
  193. else
  194. {
  195. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  196. }
  197. if (deepestViewUnderMouse is null)
  198. {
  199. break;
  200. }
  201. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  202. viewMouseEvent = new ()
  203. {
  204. Position = boundsPoint,
  205. Flags = mouseEvent.Flags,
  206. ScreenPosition = mouseEvent.ScreenPosition,
  207. View = deepestViewUnderMouse
  208. };
  209. }
  210. }
  211. internal static bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEvent mouseEvent)
  212. {
  213. if (MouseGrabView is { })
  214. {
  215. #if DEBUG_IDISPOSABLE
  216. if (MouseGrabView.WasDisposed)
  217. {
  218. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  219. }
  220. #endif
  221. // If the mouse is grabbed, send the event to the view that grabbed it.
  222. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  223. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  224. var viewRelativeMouseEvent = new MouseEvent
  225. {
  226. Position = frameLoc,
  227. Flags = mouseEvent.Flags,
  228. ScreenPosition = mouseEvent.ScreenPosition,
  229. View = deepestViewUnderMouse ?? MouseGrabView
  230. };
  231. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  232. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  233. {
  234. return true;
  235. }
  236. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  237. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  238. {
  239. // The view that grabbed the mouse has been disposed
  240. return true;
  241. }
  242. }
  243. return false;
  244. }
  245. internal static readonly List<View?> _cachedViewsUnderMouse = new ();
  246. // TODO: Refactor MouseEnter/LeaveEvents to not take MouseEvent param.
  247. /// <summary>
  248. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  249. /// </summary>
  250. /// <param name="screenPosition">The position of the mouse.</param>
  251. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderMouse().</param>
  252. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  253. {
  254. // Tell any views that are no longer under the mouse that the mouse has left
  255. List<View?> viewsToLeave = _cachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  256. foreach (View? view in viewsToLeave)
  257. {
  258. if (view is null)
  259. {
  260. continue;
  261. }
  262. view.NewMouseLeaveEvent ();
  263. _cachedViewsUnderMouse.Remove (view);
  264. }
  265. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  266. foreach (View? view in currentViewsUnderMouse)
  267. {
  268. if (view is null)
  269. {
  270. continue;
  271. }
  272. if (_cachedViewsUnderMouse.Contains (view))
  273. {
  274. continue;
  275. }
  276. _cachedViewsUnderMouse.Add (view);
  277. var raise = false;
  278. if (view is Adornment { Parent: { } } adornmentView)
  279. {
  280. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  281. raise = adornmentView.Contains (superViewLoc);
  282. }
  283. else
  284. {
  285. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  286. raise = view.Contains (superViewLoc);
  287. }
  288. if (!raise)
  289. {
  290. continue;
  291. }
  292. CancelEventArgs eventArgs = new ();
  293. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  294. if (cancelled is true || eventArgs.Cancel)
  295. {
  296. break;
  297. }
  298. }
  299. }
  300. }