Application.Mouse.cs 13 KB

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