Application.Mouse.cs 12 KB

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