Application.Mouse.cs 13 KB

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