Application.Mouse.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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;
  8. /// <summary>
  9. /// Gets the most recent position of the mouse.
  10. /// </summary>
  11. public static Point? GetLastMousePosition () { return _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. // Debug.Fail ("This should never happen. If it does please file an Issue!!");
  185. return;
  186. }
  187. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  188. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  189. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  190. {
  191. if (deepestViewUnderMouse is Adornment adornmentView)
  192. {
  193. deepestViewUnderMouse = adornmentView.Parent!.SuperView;
  194. }
  195. else
  196. {
  197. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  198. }
  199. if (deepestViewUnderMouse is null)
  200. {
  201. break;
  202. }
  203. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  204. viewMouseEvent = new ()
  205. {
  206. Position = boundsPoint,
  207. Flags = mouseEvent.Flags,
  208. ScreenPosition = mouseEvent.ScreenPosition,
  209. View = deepestViewUnderMouse
  210. };
  211. }
  212. }
  213. internal static bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEvent mouseEvent)
  214. {
  215. if (MouseGrabView is { })
  216. {
  217. #if DEBUG_IDISPOSABLE
  218. if (MouseGrabView.WasDisposed)
  219. {
  220. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  221. }
  222. #endif
  223. // If the mouse is grabbed, send the event to the view that grabbed it.
  224. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  225. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  226. var viewRelativeMouseEvent = new MouseEvent
  227. {
  228. Position = frameLoc,
  229. Flags = mouseEvent.Flags,
  230. ScreenPosition = mouseEvent.ScreenPosition,
  231. View = deepestViewUnderMouse ?? MouseGrabView
  232. };
  233. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  234. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  235. {
  236. return true;
  237. }
  238. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  239. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  240. {
  241. // The view that grabbed the mouse has been disposed
  242. return true;
  243. }
  244. }
  245. return false;
  246. }
  247. internal static readonly List<View?> _cachedViewsUnderMouse = new ();
  248. // TODO: Refactor MouseEnter/LeaveEvents to not take MouseEvent param.
  249. /// <summary>
  250. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  251. /// </summary>
  252. /// <param name="screenPosition">The position of the mouse.</param>
  253. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderMouse().</param>
  254. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  255. {
  256. // Tell any views that are no longer under the mouse that the mouse has left
  257. List<View?> viewsToLeave = _cachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  258. foreach (View? view in viewsToLeave)
  259. {
  260. if (view is null)
  261. {
  262. continue;
  263. }
  264. view.NewMouseLeaveEvent ();
  265. _cachedViewsUnderMouse.Remove (view);
  266. }
  267. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  268. foreach (View? view in currentViewsUnderMouse)
  269. {
  270. if (view is null)
  271. {
  272. continue;
  273. }
  274. if (_cachedViewsUnderMouse.Contains (view))
  275. {
  276. continue;
  277. }
  278. _cachedViewsUnderMouse.Add (view);
  279. var raise = false;
  280. if (view is Adornment { Parent: { } } adornmentView)
  281. {
  282. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  283. raise = adornmentView.Contains (superViewLoc);
  284. }
  285. else
  286. {
  287. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  288. raise = view.Contains (superViewLoc);
  289. }
  290. if (!raise)
  291. {
  292. continue;
  293. }
  294. CancelEventArgs eventArgs = new ();
  295. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  296. if (cancelled is true || eventArgs.Cancel)
  297. {
  298. break;
  299. }
  300. }
  301. }
  302. }