Application.Mouse.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 || RaiseGrabbingMouseEvent (view))
  38. {
  39. return;
  40. }
  41. RaiseGrabbedMouseEvent (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. if (View.DebugIDisposable)
  53. {
  54. ObjectDisposedException.ThrowIf (MouseGrabView.WasDisposed, MouseGrabView);
  55. }
  56. #endif
  57. if (!RaiseUnGrabbingMouseEvent (MouseGrabView))
  58. {
  59. View view = MouseGrabView;
  60. MouseGrabView = null;
  61. RaiseUnGrabbedMouseEvent (view);
  62. }
  63. }
  64. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  65. private static bool RaiseGrabbingMouseEvent (View? view)
  66. {
  67. if (view is null)
  68. {
  69. return false;
  70. }
  71. var evArgs = new GrabMouseEventArgs (view);
  72. GrabbingMouse?.Invoke (view, evArgs);
  73. return evArgs.Cancel;
  74. }
  75. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  76. private static bool RaiseUnGrabbingMouseEvent (View? view)
  77. {
  78. if (view is null)
  79. {
  80. return false;
  81. }
  82. var evArgs = new GrabMouseEventArgs (view);
  83. UnGrabbingMouse?.Invoke (view, evArgs);
  84. return evArgs.Cancel;
  85. }
  86. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  87. private static void RaiseGrabbedMouseEvent (View? view)
  88. {
  89. if (view is null)
  90. {
  91. return;
  92. }
  93. GrabbedMouse?.Invoke (view, new (view));
  94. }
  95. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  96. private static void RaiseUnGrabbedMouseEvent (View? view)
  97. {
  98. if (view is null)
  99. {
  100. return;
  101. }
  102. UnGrabbedMouse?.Invoke (view, new (view));
  103. }
  104. /// <summary>
  105. /// INTERNAL API: Called when a mouse event is raised by the driver. Determines the view under the mouse and
  106. /// calls the appropriate View mouse event handlers.
  107. /// </summary>
  108. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  109. /// <param name="mouseEvent">The mouse event with coordinates relative to the screen.</param>
  110. internal static void RaiseMouseEvent (MouseEventArgs mouseEvent)
  111. {
  112. _lastMousePosition = mouseEvent.ScreenPosition;
  113. if (IsMouseDisabled)
  114. {
  115. return;
  116. }
  117. // The position of the mouse is the same as the screen position at the application level.
  118. //Debug.Assert (mouseEvent.Position == mouseEvent.ScreenPosition);
  119. mouseEvent.Position = mouseEvent.ScreenPosition;
  120. List<View?> currentViewsUnderMouse = View.GetViewsUnderMouse (mouseEvent.ScreenPosition);
  121. View? deepestViewUnderMouse = currentViewsUnderMouse.LastOrDefault ();
  122. if (deepestViewUnderMouse is { })
  123. {
  124. #if DEBUG_IDISPOSABLE
  125. if (View.DebugIDisposable && deepestViewUnderMouse.WasDisposed)
  126. {
  127. throw new ObjectDisposedException (deepestViewUnderMouse.GetType ().FullName);
  128. }
  129. #endif
  130. mouseEvent.View = deepestViewUnderMouse;
  131. }
  132. MouseEvent?.Invoke (null, mouseEvent);
  133. if (mouseEvent.Handled)
  134. {
  135. return;
  136. }
  137. // Dismiss the Popover if the user presses mouse outside of it
  138. if (mouseEvent.IsPressed
  139. && Popover?.GetActivePopover () as View is { Visible: true } visiblePopover
  140. && View.IsInHierarchy (visiblePopover, deepestViewUnderMouse, includeAdornments: true) is false)
  141. {
  142. visiblePopover.Visible = false;
  143. // Recurse once so the event can be handled below the popover
  144. RaiseMouseEvent (mouseEvent);
  145. return;
  146. }
  147. if (HandleMouseGrab (deepestViewUnderMouse, mouseEvent))
  148. {
  149. return;
  150. }
  151. WantContinuousButtonPressedView = deepestViewUnderMouse switch
  152. {
  153. { WantContinuousButtonPressed: true } => deepestViewUnderMouse,
  154. _ => null
  155. };
  156. // May be null before the prior condition or the condition may set it as null.
  157. // So, the checking must be outside the prior condition.
  158. if (deepestViewUnderMouse is null)
  159. {
  160. return;
  161. }
  162. // Create a view-relative mouse event to send to the view that is under the mouse.
  163. MouseEventArgs viewMouseEvent;
  164. if (deepestViewUnderMouse is Adornment adornment)
  165. {
  166. Point frameLoc = adornment.ScreenToFrame (mouseEvent.ScreenPosition);
  167. viewMouseEvent = new ()
  168. {
  169. Position = frameLoc,
  170. Flags = mouseEvent.Flags,
  171. ScreenPosition = mouseEvent.ScreenPosition,
  172. View = deepestViewUnderMouse
  173. };
  174. }
  175. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.ScreenPosition))
  176. {
  177. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  178. viewMouseEvent = new ()
  179. {
  180. Position = viewportLocation,
  181. Flags = mouseEvent.Flags,
  182. ScreenPosition = mouseEvent.ScreenPosition,
  183. View = deepestViewUnderMouse
  184. };
  185. }
  186. else
  187. {
  188. // The mouse was outside any View's Viewport.
  189. //Debug.Fail ("this should not happen.");
  190. // Debug.Fail ("This should never happen. If it does please file an Issue!!");
  191. return;
  192. }
  193. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  194. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  195. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  196. {
  197. if (deepestViewUnderMouse is Adornment adornmentView)
  198. {
  199. deepestViewUnderMouse = adornmentView.Parent?.SuperView;
  200. }
  201. else
  202. {
  203. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  204. }
  205. if (deepestViewUnderMouse is null)
  206. {
  207. break;
  208. }
  209. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  210. viewMouseEvent = new ()
  211. {
  212. Position = boundsPoint,
  213. Flags = mouseEvent.Flags,
  214. ScreenPosition = mouseEvent.ScreenPosition,
  215. View = deepestViewUnderMouse
  216. };
  217. }
  218. }
  219. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
  220. /// <summary>
  221. /// Raised when a mouse event occurs. Can be cancelled by setting <see cref="HandledEventArgs.Handled"/> to <see langword="true"/>.
  222. /// </summary>
  223. /// <remarks>
  224. /// <para>
  225. /// <see cref="MouseEventArgs.ScreenPosition"/> coordinates are screen-relative.
  226. /// </para>
  227. /// <para>
  228. /// <see cref="MouseEventArgs.View"/> will be the deepest view under the mouse.
  229. /// </para>
  230. /// <para>
  231. /// <see cref="MouseEventArgs.Position"/> coordinates are view-relative. Only valid if <see cref="MouseEventArgs.View"/> is set.
  232. /// </para>
  233. /// <para>
  234. /// Use this even to handle mouse events at the application level, before View-specific handling.
  235. /// </para>
  236. /// </remarks>
  237. public static event EventHandler<MouseEventArgs>? MouseEvent;
  238. #pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
  239. internal static bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEventArgs mouseEvent)
  240. {
  241. if (MouseGrabView is { })
  242. {
  243. #if DEBUG_IDISPOSABLE
  244. if (View.DebugIDisposable && MouseGrabView.WasDisposed)
  245. {
  246. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  247. }
  248. #endif
  249. // If the mouse is grabbed, send the event to the view that grabbed it.
  250. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  251. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  252. var viewRelativeMouseEvent = new MouseEventArgs
  253. {
  254. Position = frameLoc,
  255. Flags = mouseEvent.Flags,
  256. ScreenPosition = mouseEvent.ScreenPosition,
  257. View = deepestViewUnderMouse ?? MouseGrabView
  258. };
  259. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  260. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  261. {
  262. return true;
  263. }
  264. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  265. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  266. {
  267. // The view that grabbed the mouse has been disposed
  268. return true;
  269. }
  270. }
  271. return false;
  272. }
  273. internal static readonly List<View?> _cachedViewsUnderMouse = new ();
  274. /// <summary>
  275. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  276. /// </summary>
  277. /// <param name="screenPosition">The position of the mouse.</param>
  278. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderMouse().</param>
  279. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  280. {
  281. // Tell any views that are no longer under the mouse that the mouse has left
  282. List<View?> viewsToLeave = _cachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  283. foreach (View? view in viewsToLeave)
  284. {
  285. if (view is null)
  286. {
  287. continue;
  288. }
  289. view.NewMouseLeaveEvent ();
  290. _cachedViewsUnderMouse.Remove (view);
  291. }
  292. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  293. foreach (View? view in currentViewsUnderMouse)
  294. {
  295. if (view is null)
  296. {
  297. continue;
  298. }
  299. if (_cachedViewsUnderMouse.Contains (view))
  300. {
  301. continue;
  302. }
  303. _cachedViewsUnderMouse.Add (view);
  304. var raise = false;
  305. if (view is Adornment { Parent: { } } adornmentView)
  306. {
  307. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  308. raise = adornmentView.Contains (superViewLoc);
  309. }
  310. else
  311. {
  312. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  313. raise = view.Contains (superViewLoc);
  314. }
  315. if (!raise)
  316. {
  317. continue;
  318. }
  319. CancelEventArgs eventArgs = new ();
  320. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  321. if (cancelled is true || eventArgs.Cancel)
  322. {
  323. break;
  324. }
  325. }
  326. }
  327. }