Application.Mouse.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. /// <summary>Disable or enable the mouse. The mouse is enabled by default.</summary>
  8. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  9. public static bool IsMouseDisabled { get; set; }
  10. /// <summary>The current <see cref="View"/> object that wants continuous mouse button pressed events.</summary>
  11. public static View? WantContinuousButtonPressedView { get; private set; }
  12. /// <summary>
  13. /// Gets the view that grabbed the mouse (e.g. for dragging). When this is set, all mouse events will be routed to
  14. /// this view until the view calls <see cref="UngrabMouse"/> or the mouse is released.
  15. /// </summary>
  16. public static View? MouseGrabView { get; private set; }
  17. /// <summary>Invoked when a view wants to grab the mouse; can be canceled.</summary>
  18. public static event EventHandler<GrabMouseEventArgs>? GrabbingMouse;
  19. /// <summary>Invoked when a view wants un-grab the mouse; can be canceled.</summary>
  20. public static event EventHandler<GrabMouseEventArgs>? UnGrabbingMouse;
  21. /// <summary>Invoked after a view has grabbed the mouse.</summary>
  22. public static event EventHandler<ViewEventArgs>? GrabbedMouse;
  23. /// <summary>Invoked after a view has un-grabbed the mouse.</summary>
  24. public static event EventHandler<ViewEventArgs>? UnGrabbedMouse;
  25. /// <summary>
  26. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/>
  27. /// is called.
  28. /// </summary>
  29. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  30. public static void GrabMouse (View? view)
  31. {
  32. if (view is null || OnGrabbingMouse (view))
  33. {
  34. return;
  35. }
  36. OnGrabbedMouse (view);
  37. MouseGrabView = view;
  38. }
  39. /// <summary>Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.</summary>
  40. public static void UngrabMouse ()
  41. {
  42. if (MouseGrabView is null)
  43. {
  44. return;
  45. }
  46. #if DEBUG_IDISPOSABLE
  47. ObjectDisposedException.ThrowIf (MouseGrabView.WasDisposed, MouseGrabView);
  48. #endif
  49. if (!OnUnGrabbingMouse (MouseGrabView))
  50. {
  51. View view = MouseGrabView;
  52. MouseGrabView = null;
  53. OnUnGrabbedMouse (view);
  54. }
  55. }
  56. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  57. private static bool OnGrabbingMouse (View? view)
  58. {
  59. if (view is null)
  60. {
  61. return false;
  62. }
  63. var evArgs = new GrabMouseEventArgs (view);
  64. GrabbingMouse?.Invoke (view, evArgs);
  65. return evArgs.Cancel;
  66. }
  67. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  68. private static bool OnUnGrabbingMouse (View? view)
  69. {
  70. if (view is null)
  71. {
  72. return false;
  73. }
  74. var evArgs = new GrabMouseEventArgs (view);
  75. UnGrabbingMouse?.Invoke (view, evArgs);
  76. return evArgs.Cancel;
  77. }
  78. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  79. private static void OnGrabbedMouse (View? view)
  80. {
  81. if (view is null)
  82. {
  83. return;
  84. }
  85. GrabbedMouse?.Invoke (view, new (view));
  86. }
  87. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  88. private static void OnUnGrabbedMouse (View? view)
  89. {
  90. if (view is null)
  91. {
  92. return;
  93. }
  94. UnGrabbedMouse?.Invoke (view, new (view));
  95. }
  96. /// <summary>Event fired when a mouse move or click occurs. Coordinates are screen relative.</summary>
  97. /// <remarks>
  98. /// <para>
  99. /// Use this event to receive mouse events in screen coordinates. Use <see cref="MouseEvent"/> to
  100. /// receive mouse events relative to a <see cref="View.Viewport"/>.
  101. /// </para>
  102. /// <para>The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.</para>
  103. /// </remarks>
  104. public static event EventHandler<MouseEvent>? MouseEvent;
  105. /// <summary>Called when a mouse event is raised by the driver.</summary>
  106. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  107. /// <param name="mouseEvent">The mouse event with coordinates relative to the screen.</param>
  108. internal static void OnMouseEvent (MouseEvent mouseEvent)
  109. {
  110. if (IsMouseDisabled)
  111. {
  112. return;
  113. }
  114. List<View?> currentViewsUnderMouse = View.GetViewsUnderMouse (mouseEvent.Position);
  115. View? deepestViewUnderMouse = currentViewsUnderMouse.LastOrDefault ();
  116. if (deepestViewUnderMouse is { })
  117. {
  118. #if DEBUG_IDISPOSABLE
  119. if (deepestViewUnderMouse.WasDisposed)
  120. {
  121. throw new ObjectDisposedException (deepestViewUnderMouse.GetType ().FullName);
  122. }
  123. #endif
  124. mouseEvent.View = deepestViewUnderMouse;
  125. }
  126. MouseEvent?.Invoke (null, mouseEvent);
  127. if (mouseEvent.Handled)
  128. {
  129. return;
  130. }
  131. if (HandleMouseGrab (deepestViewUnderMouse, mouseEvent))
  132. {
  133. return;
  134. }
  135. // We can combine this into the switch expression to reduce cognitive complexity even more and likely
  136. // avoid one or two of these checks in the process, as well.
  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. // TODO: Move this after call to RaiseMouseEnterLeaveEvents once MouseEnter/Leave don't use MouseEvent anymore.
  149. MouseEvent? me;
  150. if (deepestViewUnderMouse is Adornment adornment)
  151. {
  152. Point frameLoc = adornment.ScreenToFrame (mouseEvent.Position);
  153. me = new ()
  154. {
  155. Position = frameLoc,
  156. Flags = mouseEvent.Flags,
  157. ScreenPosition = mouseEvent.Position,
  158. View = deepestViewUnderMouse
  159. };
  160. }
  161. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.Position))
  162. {
  163. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.Position);
  164. me = new ()
  165. {
  166. Position = viewportLocation,
  167. Flags = mouseEvent.Flags,
  168. ScreenPosition = mouseEvent.Position,
  169. View = deepestViewUnderMouse
  170. };
  171. }
  172. else
  173. {
  174. Debug.Fail ("This should never happen");
  175. return;
  176. }
  177. RaiseMouseEnterLeaveEvents (me.ScreenPosition, currentViewsUnderMouse);
  178. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  179. while (deepestViewUnderMouse.NewMouseEvent (me) is not true && MouseGrabView is not { })
  180. {
  181. if (deepestViewUnderMouse is Adornment adornmentView)
  182. {
  183. deepestViewUnderMouse = adornmentView.Parent!.SuperView;
  184. }
  185. else
  186. {
  187. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  188. }
  189. if (deepestViewUnderMouse is null)
  190. {
  191. break;
  192. }
  193. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.Position);
  194. me = new ()
  195. {
  196. Position = boundsPoint,
  197. Flags = mouseEvent.Flags,
  198. ScreenPosition = mouseEvent.Position,
  199. View = deepestViewUnderMouse
  200. };
  201. }
  202. }
  203. internal static bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEvent mouseEvent)
  204. {
  205. if (MouseGrabView is { })
  206. {
  207. #if DEBUG_IDISPOSABLE
  208. if (MouseGrabView.WasDisposed)
  209. {
  210. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  211. }
  212. #endif
  213. // If the mouse is grabbed, send the event to the view that grabbed it.
  214. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  215. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.Position);
  216. var viewRelativeMouseEvent = new MouseEvent
  217. {
  218. Position = frameLoc,
  219. Flags = mouseEvent.Flags,
  220. ScreenPosition = mouseEvent.Position,
  221. View = deepestViewUnderMouse ?? MouseGrabView
  222. };
  223. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  224. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  225. {
  226. return true;
  227. }
  228. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  229. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  230. {
  231. // The view that grabbed the mouse has been disposed
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. internal static readonly List<View?> _cachedViewsUnderMouse = new ();
  238. // TODO: Refactor MouseEnter/LeaveEvents to not take MouseEvent param.
  239. /// <summary>
  240. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  241. /// </summary>
  242. /// <param name="screenPosition">The position of the mouse.</param>
  243. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderMouse().</param>
  244. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  245. {
  246. // Tell any views that are no longer under the mouse that the mouse has left
  247. List<View?> viewsToLeave = _cachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  248. foreach (View? view in viewsToLeave)
  249. {
  250. if (view is null)
  251. {
  252. continue;
  253. }
  254. view.NewMouseLeaveEvent ();
  255. _cachedViewsUnderMouse.Remove (view);
  256. }
  257. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  258. foreach (View? view in currentViewsUnderMouse)
  259. {
  260. if (view is null)
  261. {
  262. continue;
  263. }
  264. if (_cachedViewsUnderMouse.Contains (view))
  265. {
  266. continue;
  267. }
  268. _cachedViewsUnderMouse.Add (view);
  269. bool raise = false;
  270. if (view is Adornment { Parent: { } } adornmentView)
  271. {
  272. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  273. raise = adornmentView.Contains (superViewLoc);
  274. }
  275. else
  276. {
  277. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  278. raise = view.Contains (superViewLoc);
  279. }
  280. if (!raise)
  281. {
  282. continue;
  283. }
  284. CancelEventArgs eventArgs = new ();
  285. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  286. if (cancelled is true || eventArgs.Cancel)
  287. {
  288. break;
  289. }
  290. }
  291. }
  292. }