Application.Mouse.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. // Used by OnMouseEvent to suppport MouseEnter and MouseLeave events
  98. internal static List<View?> ViewsUnderMouse { get; } = new ();
  99. /// <summary>Event fired when a mouse move or click occurs. Coordinates are screen relative.</summary>
  100. /// <remarks>
  101. /// <para>
  102. /// Use this event to receive mouse events in screen coordinates. Use <see cref="MouseEvent"/> to
  103. /// receive mouse events relative to a <see cref="View.Viewport"/>.
  104. /// </para>
  105. /// <para>The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.</para>
  106. /// </remarks>
  107. public static event EventHandler<MouseEvent>? MouseEvent;
  108. /// <summary>Called when a mouse event occurs. Raises the <see cref="MouseEvent"/> event.</summary>
  109. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  110. /// <param name="mouseEvent">The mouse event with coordinates relative to the screen.</param>
  111. internal static void OnMouseEvent (MouseEvent mouseEvent)
  112. {
  113. if (IsMouseDisabled)
  114. {
  115. return;
  116. }
  117. List<View?> currentViewsUnderMouse = View.GetViewsUnderMouse (mouseEvent.Position);
  118. View? deepestViewUnderMouse = currentViewsUnderMouse.LastOrDefault ();
  119. if (deepestViewUnderMouse is { })
  120. {
  121. #if DEBUG_IDISPOSABLE
  122. if (deepestViewUnderMouse.WasDisposed)
  123. {
  124. throw new ObjectDisposedException (deepestViewUnderMouse.GetType ().FullName);
  125. }
  126. #endif
  127. mouseEvent.View = deepestViewUnderMouse;
  128. }
  129. MouseEvent?.Invoke (null, mouseEvent);
  130. if (mouseEvent.Handled)
  131. {
  132. return;
  133. }
  134. if (MouseGrabView is { })
  135. {
  136. #if DEBUG_IDISPOSABLE
  137. if (MouseGrabView.WasDisposed)
  138. {
  139. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  140. }
  141. #endif
  142. // If the mouse is grabbed, send the event to the view that grabbed it.
  143. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  144. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.Position);
  145. var viewRelativeMouseEvent = new MouseEvent
  146. {
  147. Position = frameLoc,
  148. Flags = mouseEvent.Flags,
  149. ScreenPosition = mouseEvent.Position,
  150. View = deepestViewUnderMouse ?? MouseGrabView
  151. };
  152. if ((MouseGrabView.Viewport with { Location = Point.Empty }).Contains (viewRelativeMouseEvent.Position) is false)
  153. {
  154. // The mouse has moved outside the bounds of the view that grabbed the mouse
  155. //MouseGrabView.NewMouseLeaveEvent (mouseEvent);
  156. }
  157. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  158. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  159. {
  160. return;
  161. }
  162. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  163. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  164. {
  165. // The view that grabbed the mouse has been disposed
  166. return;
  167. }
  168. }
  169. // We can combine this into the switch expression to reduce cognitive complexity even more and likely
  170. // avoid one or two of these checks in the process, as well.
  171. WantContinuousButtonPressedView = deepestViewUnderMouse switch
  172. {
  173. { WantContinuousButtonPressed: true } => deepestViewUnderMouse,
  174. _ => null
  175. };
  176. // May be null before the prior condition or the condition may set it as null.
  177. // So, the checking must be outside the prior condition.
  178. if (deepestViewUnderMouse is null)
  179. {
  180. return;
  181. }
  182. MouseEvent? me;
  183. if (deepestViewUnderMouse is Adornment adornment)
  184. {
  185. Point frameLoc = adornment.ScreenToFrame (mouseEvent.Position);
  186. me = new ()
  187. {
  188. Position = frameLoc,
  189. Flags = mouseEvent.Flags,
  190. ScreenPosition = mouseEvent.Position,
  191. View = deepestViewUnderMouse
  192. };
  193. }
  194. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.Position))
  195. {
  196. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.Position);
  197. me = new ()
  198. {
  199. Position = viewportLocation,
  200. Flags = mouseEvent.Flags,
  201. ScreenPosition = mouseEvent.Position,
  202. View = deepestViewUnderMouse
  203. };
  204. }
  205. else
  206. {
  207. Debug.Fail ("This should never happen");
  208. return;
  209. }
  210. RaiseMouseEnterLeaveEvents (me.ScreenPosition, currentViewsUnderMouse, me);
  211. WantContinuousButtonPressedView = deepestViewUnderMouse.WantContinuousButtonPressed ? deepestViewUnderMouse : null;
  212. //Debug.WriteLine ($"OnMouseEvent: ({a.MouseEvent.X},{a.MouseEvent.Y}) - {a.MouseEvent.Flags}");
  213. if (deepestViewUnderMouse.Id == "mouseDemo")
  214. {
  215. }
  216. while (deepestViewUnderMouse.NewMouseEvent (me) is not true && MouseGrabView is not { })
  217. {
  218. if (deepestViewUnderMouse is Adornment adornmentView)
  219. {
  220. deepestViewUnderMouse = adornmentView.Parent!.SuperView;
  221. }
  222. else
  223. {
  224. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  225. }
  226. if (deepestViewUnderMouse is null)
  227. {
  228. break;
  229. }
  230. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.Position);
  231. me = new ()
  232. {
  233. Position = boundsPoint,
  234. Flags = mouseEvent.Flags,
  235. ScreenPosition = mouseEvent.Position,
  236. View = deepestViewUnderMouse
  237. };
  238. }
  239. ApplicationOverlapped.BringOverlappedTopToFront ();
  240. }
  241. // TODO: Refactor MouseEnter/LeaveEvents to not take MouseEvent param.
  242. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse, MouseEvent me)
  243. {
  244. // Tell any views that are no longer under the mouse that the mouse has left
  245. List<View?> viewsToLeave = ViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  246. foreach (View? view in viewsToLeave)
  247. {
  248. if (view is null)
  249. {
  250. continue;
  251. }
  252. if (view is Adornment adornmentView)
  253. {
  254. Point frameLoc = adornmentView.ScreenToFrame (screenPosition);
  255. if (adornmentView.Parent is { } && !adornmentView.Contains (frameLoc))
  256. {
  257. view.NewMouseLeaveEvent (me);
  258. }
  259. }
  260. else
  261. {
  262. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  263. if (!view.Contains (superViewLoc))
  264. {
  265. view.NewMouseLeaveEvent (me);
  266. }
  267. }
  268. }
  269. ViewsUnderMouse.Clear ();
  270. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  271. foreach (View? view in currentViewsUnderMouse)
  272. {
  273. if (view is null)
  274. {
  275. continue;
  276. }
  277. ViewsUnderMouse.Add (view);
  278. if (view is Adornment adornmentView)
  279. {
  280. Point frameLoc = view.ScreenToFrame (me.ScreenPosition);
  281. if (adornmentView.Parent is { } && !adornmentView.Contains (frameLoc))
  282. {
  283. view.NewMouseEnterEvent (me);
  284. }
  285. }
  286. else
  287. {
  288. Point superViewLoc = view.SuperView?.ScreenToViewport (me.ScreenPosition) ?? me.ScreenPosition;
  289. if (view.Contains (superViewLoc))
  290. {
  291. view.NewMouseEnterEvent (me);
  292. }
  293. }
  294. }
  295. }
  296. }