Application.Mouse.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. #nullable enable
  2. using System.ComponentModel;
  3. namespace Terminal.Gui.App;
  4. public static partial class Application // Mouse handling
  5. {
  6. /// <summary>
  7. /// INTERNAL API: Holds the last mouse position.
  8. /// </summary>
  9. internal static Point? LastMousePosition { get; set; }
  10. /// <summary>
  11. /// Gets the most recent position of the mouse.
  12. /// </summary>
  13. public static Point? GetLastMousePosition () { return LastMousePosition; }
  14. /// <summary>Disable or enable the mouse. The mouse is enabled by default.</summary>
  15. [ConfigurationProperty (Scope = typeof (SettingsScope))]
  16. public static bool IsMouseDisabled { get; set; }
  17. /// <summary>Gets <see cref="View"/> that has registered to get continuous mouse button pressed events.</summary>
  18. public static View? WantContinuousButtonPressedView { get; internal set; }
  19. /// <summary>
  20. /// Gets the view that grabbed the mouse (e.g. for dragging). When this is set, all mouse events will be routed to
  21. /// this view until the view calls <see cref="UngrabMouse"/> or the mouse is released.
  22. /// </summary>
  23. public static View? MouseGrabView { get; private set; }
  24. /// <summary>Invoked when a view wants to grab the mouse; can be canceled.</summary>
  25. public static event EventHandler<GrabMouseEventArgs>? GrabbingMouse;
  26. /// <summary>Invoked when a view wants un-grab the mouse; can be canceled.</summary>
  27. public static event EventHandler<GrabMouseEventArgs>? UnGrabbingMouse;
  28. /// <summary>Invoked after a view has grabbed the mouse.</summary>
  29. public static event EventHandler<ViewEventArgs>? GrabbedMouse;
  30. /// <summary>Invoked after a view has un-grabbed the mouse.</summary>
  31. public static event EventHandler<ViewEventArgs>? UnGrabbedMouse;
  32. /// <summary>
  33. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/>
  34. /// is called.
  35. /// </summary>
  36. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  37. public static void GrabMouse (View? view)
  38. {
  39. if (view is null || RaiseGrabbingMouseEvent (view))
  40. {
  41. return;
  42. }
  43. RaiseGrabbedMouseEvent (view);
  44. if (Initialized)
  45. {
  46. // MouseGrabView is a static; only set if the application is initialized.
  47. MouseGrabView = view;
  48. }
  49. }
  50. /// <summary>Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.</summary>
  51. public static void UngrabMouse ()
  52. {
  53. if (MouseGrabView is null)
  54. {
  55. return;
  56. }
  57. #if DEBUG_IDISPOSABLE
  58. if (View.EnableDebugIDisposableAsserts)
  59. {
  60. ObjectDisposedException.ThrowIf (MouseGrabView.WasDisposed, MouseGrabView);
  61. }
  62. #endif
  63. if (!RaiseUnGrabbingMouseEvent (MouseGrabView))
  64. {
  65. View view = MouseGrabView;
  66. MouseGrabView = null;
  67. RaiseUnGrabbedMouseEvent (view);
  68. }
  69. }
  70. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  71. private static bool RaiseGrabbingMouseEvent (View? view)
  72. {
  73. if (view is null)
  74. {
  75. return false;
  76. }
  77. var evArgs = new GrabMouseEventArgs (view);
  78. GrabbingMouse?.Invoke (view, evArgs);
  79. return evArgs.Cancel;
  80. }
  81. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  82. private static bool RaiseUnGrabbingMouseEvent (View? view)
  83. {
  84. if (view is null)
  85. {
  86. return false;
  87. }
  88. var evArgs = new GrabMouseEventArgs (view);
  89. UnGrabbingMouse?.Invoke (view, evArgs);
  90. return evArgs.Cancel;
  91. }
  92. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  93. private static void RaiseGrabbedMouseEvent (View? view)
  94. {
  95. if (view is null)
  96. {
  97. return;
  98. }
  99. GrabbedMouse?.Invoke (view, new (view));
  100. }
  101. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  102. private static void RaiseUnGrabbedMouseEvent (View? view)
  103. {
  104. if (view is null)
  105. {
  106. return;
  107. }
  108. UnGrabbedMouse?.Invoke (view, new (view));
  109. }
  110. /// <summary>
  111. /// INTERNAL API: Called when a mouse event is raised by the driver. Determines the view under the mouse and
  112. /// calls the appropriate View mouse event handlers.
  113. /// </summary>
  114. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  115. /// <param name="mouseEvent">The mouse event with coordinates relative to the screen.</param>
  116. internal static void RaiseMouseEvent (MouseEventArgs mouseEvent)
  117. {
  118. if (Initialized)
  119. {
  120. // LastMousePosition is a static; only set if the application is initialized.
  121. LastMousePosition = mouseEvent.ScreenPosition;
  122. }
  123. if (IsMouseDisabled)
  124. {
  125. return;
  126. }
  127. // The position of the mouse is the same as the screen position at the application level.
  128. //Debug.Assert (mouseEvent.Position == mouseEvent.ScreenPosition);
  129. mouseEvent.Position = mouseEvent.ScreenPosition;
  130. List<View?> currentViewsUnderMouse = View.GetViewsUnderLocation (mouseEvent.ScreenPosition, ViewportSettingsFlags.TransparentMouse);
  131. View? deepestViewUnderMouse = currentViewsUnderMouse.LastOrDefault ();
  132. if (deepestViewUnderMouse is { })
  133. {
  134. #if DEBUG_IDISPOSABLE
  135. if (View.EnableDebugIDisposableAsserts && deepestViewUnderMouse.WasDisposed)
  136. {
  137. throw new ObjectDisposedException (deepestViewUnderMouse.GetType ().FullName);
  138. }
  139. #endif
  140. mouseEvent.View = deepestViewUnderMouse;
  141. }
  142. MouseEvent?.Invoke (null, mouseEvent);
  143. if (mouseEvent.Handled)
  144. {
  145. return;
  146. }
  147. // Dismiss the Popover if the user presses mouse outside of it
  148. if (mouseEvent.IsPressed
  149. && Popover?.GetActivePopover () as View is { Visible: true } visiblePopover
  150. && View.IsInHierarchy (visiblePopover, deepestViewUnderMouse, includeAdornments: true) is false)
  151. {
  152. ApplicationPopover.HideWithQuitCommand (visiblePopover);
  153. // Recurse once so the event can be handled below the popover
  154. RaiseMouseEvent (mouseEvent);
  155. return;
  156. }
  157. if (HandleMouseGrab (deepestViewUnderMouse, mouseEvent))
  158. {
  159. return;
  160. }
  161. if (Initialized)
  162. {
  163. WantContinuousButtonPressedView = deepestViewUnderMouse switch
  164. {
  165. { WantContinuousButtonPressed: true } => deepestViewUnderMouse,
  166. _ => null
  167. };
  168. }
  169. // May be null before the prior condition or the condition may set it as null.
  170. // So, the checking must be outside the prior condition.
  171. if (deepestViewUnderMouse is null)
  172. {
  173. return;
  174. }
  175. // if the mouse is outside the Application.Top or Application.Popover hierarchy, we don't want to
  176. // send the mouse event to the deepest view under the mouse.
  177. if (!View.IsInHierarchy (Application.Top, deepestViewUnderMouse, true) && !View.IsInHierarchy (Popover?.GetActivePopover () as View, deepestViewUnderMouse, true))
  178. {
  179. return;
  180. }
  181. // Create a view-relative mouse event to send to the view that is under the mouse.
  182. MouseEventArgs viewMouseEvent;
  183. if (deepestViewUnderMouse is Adornment adornment)
  184. {
  185. Point frameLoc = adornment.ScreenToFrame (mouseEvent.ScreenPosition);
  186. viewMouseEvent = new ()
  187. {
  188. Position = frameLoc,
  189. Flags = mouseEvent.Flags,
  190. ScreenPosition = mouseEvent.ScreenPosition,
  191. View = deepestViewUnderMouse
  192. };
  193. }
  194. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.ScreenPosition))
  195. {
  196. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  197. viewMouseEvent = new ()
  198. {
  199. Position = viewportLocation,
  200. Flags = mouseEvent.Flags,
  201. ScreenPosition = mouseEvent.ScreenPosition,
  202. View = deepestViewUnderMouse
  203. };
  204. }
  205. else
  206. {
  207. // The mouse was outside any View's Viewport.
  208. // Debug.Fail ("This should never happen. If it does please file an Issue!!");
  209. return;
  210. }
  211. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  212. if (Initialized)
  213. {
  214. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  215. }
  216. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  217. {
  218. if (deepestViewUnderMouse is Adornment adornmentView)
  219. {
  220. deepestViewUnderMouse = adornmentView.Parent?.SuperView;
  221. }
  222. else
  223. {
  224. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  225. }
  226. if (deepestViewUnderMouse is null)
  227. {
  228. break;
  229. }
  230. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  231. viewMouseEvent = new ()
  232. {
  233. Position = boundsPoint,
  234. Flags = mouseEvent.Flags,
  235. ScreenPosition = mouseEvent.ScreenPosition,
  236. View = deepestViewUnderMouse
  237. };
  238. }
  239. }
  240. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
  241. /// <summary>
  242. /// Raised when a mouse event occurs. Can be cancelled by setting <see cref="HandledEventArgs.Handled"/> to <see langword="true"/>.
  243. /// </summary>
  244. /// <remarks>
  245. /// <para>
  246. /// <see cref="MouseEventArgs.ScreenPosition"/> coordinates are screen-relative.
  247. /// </para>
  248. /// <para>
  249. /// <see cref="MouseEventArgs.View"/> will be the deepest view under the mouse.
  250. /// </para>
  251. /// <para>
  252. /// <see cref="MouseEventArgs.Position"/> coordinates are view-relative. Only valid if <see cref="MouseEventArgs.View"/> is set.
  253. /// </para>
  254. /// <para>
  255. /// Use this even to handle mouse events at the application level, before View-specific handling.
  256. /// </para>
  257. /// </remarks>
  258. public static event EventHandler<MouseEventArgs>? MouseEvent;
  259. #pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
  260. internal static bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEventArgs mouseEvent)
  261. {
  262. if (MouseGrabView is { })
  263. {
  264. #if DEBUG_IDISPOSABLE
  265. if (View.EnableDebugIDisposableAsserts && MouseGrabView.WasDisposed)
  266. {
  267. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  268. }
  269. #endif
  270. // If the mouse is grabbed, send the event to the view that grabbed it.
  271. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  272. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  273. var viewRelativeMouseEvent = new MouseEventArgs
  274. {
  275. Position = frameLoc,
  276. Flags = mouseEvent.Flags,
  277. ScreenPosition = mouseEvent.ScreenPosition,
  278. View = deepestViewUnderMouse ?? MouseGrabView
  279. };
  280. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  281. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  282. {
  283. return true;
  284. }
  285. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  286. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  287. {
  288. // The view that grabbed the mouse has been disposed
  289. return true;
  290. }
  291. }
  292. return false;
  293. }
  294. /// <summary>
  295. /// INTERNAL: Holds the non-<see cref="ViewportSettingsFlags.TransparentMouse"/> views that are currently under the mouse.
  296. /// </summary>
  297. internal static List<View?> CachedViewsUnderMouse { get; } = [];
  298. /// <summary>
  299. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  300. /// </summary>
  301. /// <param name="screenPosition">The position of the mouse.</param>
  302. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderLocation().</param>
  303. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  304. {
  305. // Tell any views that are no longer under the mouse that the mouse has left
  306. List<View?> viewsToLeave = CachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  307. foreach (View? view in viewsToLeave)
  308. {
  309. if (view is null)
  310. {
  311. continue;
  312. }
  313. view.NewMouseLeaveEvent ();
  314. CachedViewsUnderMouse.Remove (view);
  315. }
  316. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  317. foreach (View? view in currentViewsUnderMouse)
  318. {
  319. if (view is null)
  320. {
  321. continue;
  322. }
  323. if (CachedViewsUnderMouse.Contains (view))
  324. {
  325. continue;
  326. }
  327. CachedViewsUnderMouse.Add (view);
  328. var raise = false;
  329. if (view is Adornment { Parent: { } } adornmentView)
  330. {
  331. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  332. raise = adornmentView.Contains (superViewLoc);
  333. }
  334. else
  335. {
  336. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  337. raise = view.Contains (superViewLoc);
  338. }
  339. if (!raise)
  340. {
  341. continue;
  342. }
  343. CancelEventArgs eventArgs = new ();
  344. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  345. if (cancelled is true || eventArgs.Cancel)
  346. {
  347. break;
  348. }
  349. }
  350. }
  351. }