Application.Mouse.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 (GrabMouse (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. //Debug.WriteLine ($"OnMouseEvent: ({a.MouseEvent.X},{a.MouseEvent.Y}) - {a.MouseEvent.Flags}");
  180. if (deepestViewUnderMouse.Id == "mouseDemo")
  181. {
  182. }
  183. while (deepestViewUnderMouse.NewMouseEvent (me) is not true && MouseGrabView is not { })
  184. {
  185. if (deepestViewUnderMouse is Adornment adornmentView)
  186. {
  187. deepestViewUnderMouse = adornmentView.Parent!.SuperView;
  188. }
  189. else
  190. {
  191. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  192. }
  193. if (deepestViewUnderMouse is null)
  194. {
  195. break;
  196. }
  197. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.Position);
  198. me = new ()
  199. {
  200. Position = boundsPoint,
  201. Flags = mouseEvent.Flags,
  202. ScreenPosition = mouseEvent.Position,
  203. View = deepestViewUnderMouse
  204. };
  205. }
  206. }
  207. internal static bool GrabMouse (View? deepestViewUnderMouse, MouseEvent mouseEvent)
  208. {
  209. if (MouseGrabView is { })
  210. {
  211. #if DEBUG_IDISPOSABLE
  212. if (MouseGrabView.WasDisposed)
  213. {
  214. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  215. }
  216. #endif
  217. // If the mouse is grabbed, send the event to the view that grabbed it.
  218. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  219. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.Position);
  220. var viewRelativeMouseEvent = new MouseEvent
  221. {
  222. Position = frameLoc,
  223. Flags = mouseEvent.Flags,
  224. ScreenPosition = mouseEvent.Position,
  225. View = deepestViewUnderMouse ?? MouseGrabView
  226. };
  227. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  228. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true)
  229. {
  230. return true;
  231. }
  232. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  233. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  234. {
  235. // The view that grabbed the mouse has been disposed
  236. return true;
  237. }
  238. }
  239. return false;
  240. }
  241. internal static readonly List<View?> _cachedViewsUnderMouse = new ();
  242. // TODO: Refactor MouseEnter/LeaveEvents to not take MouseEvent param.
  243. /// <summary>
  244. /// INTERNAL: Raises the MouseEnter and MouseLeave events for the views that are under the mouse.
  245. /// </summary>
  246. /// <param name="screenPosition">The position of the mouse.</param>
  247. /// <param name="currentViewsUnderMouse">The most recent result from GetViewsUnderMouse().</param>
  248. internal static void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  249. {
  250. // Tell any views that are no longer under the mouse that the mouse has left
  251. List<View?> viewsToLeave = _cachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  252. foreach (View? view in viewsToLeave)
  253. {
  254. if (view is null)
  255. {
  256. continue;
  257. }
  258. view.NewMouseLeaveEvent ();
  259. _cachedViewsUnderMouse.Remove (view);
  260. }
  261. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  262. foreach (View? view in currentViewsUnderMouse)
  263. {
  264. if (view is null)
  265. {
  266. continue;
  267. }
  268. if (_cachedViewsUnderMouse.Contains (view))
  269. {
  270. continue;
  271. }
  272. _cachedViewsUnderMouse.Add (view);
  273. bool raise = false;
  274. if (view is Adornment { Parent: { } } adornmentView)
  275. {
  276. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  277. raise = adornmentView.Contains (superViewLoc);
  278. }
  279. else
  280. {
  281. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  282. raise = view.Contains (superViewLoc);
  283. }
  284. if (!raise)
  285. {
  286. continue;
  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. }