Application.Mouse.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. // TODO: Build a use/test case for the popover not handling Quit
  153. if (visiblePopover.InvokeCommand (Command.Quit) is true && visiblePopover.Visible)
  154. {
  155. visiblePopover.Visible = false;
  156. }
  157. // Recurse once so the event can be handled below the popover
  158. RaiseMouseEvent (mouseEvent);
  159. return;
  160. }
  161. if (HandleMouseGrab (deepestViewUnderMouse, mouseEvent))
  162. {
  163. return;
  164. }
  165. if (Initialized)
  166. {
  167. WantContinuousButtonPressedView = deepestViewUnderMouse switch
  168. {
  169. { WantContinuousButtonPressed: true } => deepestViewUnderMouse,
  170. _ => null
  171. };
  172. }
  173. // May be null before the prior condition or the condition may set it as null.
  174. // So, the checking must be outside the prior condition.
  175. if (deepestViewUnderMouse is null)
  176. {
  177. return;
  178. }
  179. // if the mouse is outside the Application.Top or Application.Popover hierarchy, we don't want to
  180. // send the mouse event to the deepest view under the mouse.
  181. if (!View.IsInHierarchy (Application.Top, deepestViewUnderMouse, true) && !View.IsInHierarchy (Popover?.GetActivePopover () as View, deepestViewUnderMouse, true))
  182. {
  183. return;
  184. }
  185. // Create a view-relative mouse event to send to the view that is under the mouse.
  186. MouseEventArgs viewMouseEvent;
  187. if (deepestViewUnderMouse is Adornment adornment)
  188. {
  189. Point frameLoc = adornment.ScreenToFrame (mouseEvent.ScreenPosition);
  190. viewMouseEvent = new ()
  191. {
  192. Position = frameLoc,
  193. Flags = mouseEvent.Flags,
  194. ScreenPosition = mouseEvent.ScreenPosition,
  195. View = deepestViewUnderMouse
  196. };
  197. }
  198. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.ScreenPosition))
  199. {
  200. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  201. viewMouseEvent = new ()
  202. {
  203. Position = viewportLocation,
  204. Flags = mouseEvent.Flags,
  205. ScreenPosition = mouseEvent.ScreenPosition,
  206. View = deepestViewUnderMouse
  207. };
  208. }
  209. else
  210. {
  211. // The mouse was outside any View's Viewport.
  212. // Debug.Fail ("This should never happen. If it does please file an Issue!!");
  213. return;
  214. }
  215. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  216. if (Initialized)
  217. {
  218. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  219. }
  220. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  221. {
  222. if (deepestViewUnderMouse is Adornment adornmentView)
  223. {
  224. deepestViewUnderMouse = adornmentView.Parent?.SuperView;
  225. }
  226. else
  227. {
  228. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  229. }
  230. if (deepestViewUnderMouse is null)
  231. {
  232. break;
  233. }
  234. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  235. viewMouseEvent = new ()
  236. {
  237. Position = boundsPoint,
  238. Flags = mouseEvent.Flags,
  239. ScreenPosition = mouseEvent.ScreenPosition,
  240. View = deepestViewUnderMouse
  241. };
  242. }
  243. }
  244. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
  245. /// <summary>
  246. /// Raised when a mouse event occurs. Can be cancelled by setting <see cref="HandledEventArgs.Handled"/> to <see langword="true"/>.
  247. /// </summary>
  248. /// <remarks>
  249. /// <para>
  250. /// <see cref="MouseEventArgs.ScreenPosition"/> coordinates are screen-relative.
  251. /// </para>
  252. /// <para>
  253. /// <see cref="MouseEventArgs.View"/> will be the deepest view under the mouse.
  254. /// </para>
  255. /// <para>
  256. /// <see cref="MouseEventArgs.Position"/> coordinates are view-relative. Only valid if <see cref="MouseEventArgs.View"/> is set.
  257. /// </para>
  258. /// <para>
  259. /// Use this even to handle mouse events at the application level, before View-specific handling.
  260. /// </para>
  261. /// </remarks>
  262. public static event EventHandler<MouseEventArgs>? MouseEvent;
  263. #pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
  264. internal static bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEventArgs mouseEvent)
  265. {
  266. if (MouseGrabView is { })
  267. {
  268. #if DEBUG_IDISPOSABLE
  269. if (View.EnableDebugIDisposableAsserts && MouseGrabView.WasDisposed)
  270. {
  271. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  272. }
  273. #endif
  274. // If the mouse is grabbed, send the event to the view that grabbed it.
  275. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  276. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  277. var viewRelativeMouseEvent = new MouseEventArgs
  278. {
  279. Position = frameLoc,
  280. Flags = mouseEvent.Flags,
  281. ScreenPosition = mouseEvent.ScreenPosition,
  282. View = deepestViewUnderMouse ?? MouseGrabView
  283. };
  284. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  285. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  286. {
  287. return true;
  288. }
  289. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  290. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  291. {
  292. // The view that grabbed the mouse has been disposed
  293. return true;
  294. }
  295. }
  296. return false;
  297. }
  298. /// <summary>
  299. /// INTERNAL: Holds the non-<see cref="ViewportSettingsFlags.TransparentMouse"/> views that are currently under the mouse.
  300. /// </summary>
  301. internal static List<View?> CachedViewsUnderMouse { get; } = [];
  302. /// <summary>
  303. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  304. /// </summary>
  305. /// <param name="screenPosition">The position of the mouse.</param>
  306. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderLocation().</param>
  307. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  308. {
  309. // Tell any views that are no longer under the mouse that the mouse has left
  310. List<View?> viewsToLeave = CachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  311. foreach (View? view in viewsToLeave)
  312. {
  313. if (view is null)
  314. {
  315. continue;
  316. }
  317. view.NewMouseLeaveEvent ();
  318. CachedViewsUnderMouse.Remove (view);
  319. }
  320. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  321. foreach (View? view in currentViewsUnderMouse)
  322. {
  323. if (view is null)
  324. {
  325. continue;
  326. }
  327. if (CachedViewsUnderMouse.Contains (view))
  328. {
  329. continue;
  330. }
  331. CachedViewsUnderMouse.Add (view);
  332. var raise = false;
  333. if (view is Adornment { Parent: { } } adornmentView)
  334. {
  335. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  336. raise = adornmentView.Contains (superViewLoc);
  337. }
  338. else
  339. {
  340. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  341. raise = view.Contains (superViewLoc);
  342. }
  343. if (!raise)
  344. {
  345. continue;
  346. }
  347. CancelEventArgs eventArgs = new ();
  348. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  349. if (cancelled is true || eventArgs.Cancel)
  350. {
  351. break;
  352. }
  353. }
  354. }
  355. }