Application.Mouse.cs 12 KB

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