MouseImpl.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #nullable enable
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. namespace Terminal.Gui.App;
  5. /// <summary>
  6. /// INTERNAL: Implements <see cref="IMouse"/> to manage mouse event handling and state.
  7. /// <para>
  8. /// This class holds all mouse-related state that was previously in the static <see cref="Application"/> class,
  9. /// enabling better testability and parallel test execution.
  10. /// </para>
  11. /// </summary>
  12. internal class MouseImpl : IMouse
  13. {
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="MouseImpl"/> class.
  16. /// </summary>
  17. public MouseImpl () { }
  18. /// <inheritdoc/>
  19. public IApplication? Application { get; set; }
  20. /// <inheritdoc/>
  21. public Point? LastMousePosition { get; set; }
  22. /// <inheritdoc/>
  23. public Point? GetLastMousePosition () { return LastMousePosition; }
  24. /// <inheritdoc/>
  25. public bool IsMouseDisabled { get; set; }
  26. /// <inheritdoc/>
  27. public List<View?> CachedViewsUnderMouse { get; } = [];
  28. /// <inheritdoc/>
  29. public event EventHandler<MouseEventArgs>? MouseEvent;
  30. // Mouse grab functionality merged from MouseGrabHandler
  31. /// <inheritdoc/>
  32. public View? MouseGrabView { get; private set; }
  33. /// <inheritdoc/>
  34. public event EventHandler<GrabMouseEventArgs>? GrabbingMouse;
  35. /// <inheritdoc/>
  36. public event EventHandler<GrabMouseEventArgs>? UnGrabbingMouse;
  37. /// <inheritdoc/>
  38. public event EventHandler<ViewEventArgs>? GrabbedMouse;
  39. /// <inheritdoc/>
  40. public event EventHandler<ViewEventArgs>? UnGrabbedMouse;
  41. /// <inheritdoc/>
  42. public void RaiseMouseEvent (MouseEventArgs mouseEvent)
  43. {
  44. //Debug.Assert (App.Application.MainThreadId == Thread.CurrentThread.ManagedThreadId);
  45. if (Application?.Initialized is true)
  46. {
  47. // LastMousePosition is only set if the application is initialized.
  48. LastMousePosition = mouseEvent.ScreenPosition;
  49. }
  50. if (IsMouseDisabled)
  51. {
  52. return;
  53. }
  54. // The position of the mouse is the same as the screen position at the application level.
  55. //Debug.Assert (mouseEvent.Position == mouseEvent.ScreenPosition);
  56. mouseEvent.Position = mouseEvent.ScreenPosition;
  57. List<View?> currentViewsUnderMouse = View.GetViewsUnderLocation (mouseEvent.ScreenPosition, ViewportSettingsFlags.TransparentMouse);
  58. View? deepestViewUnderMouse = currentViewsUnderMouse.LastOrDefault ();
  59. if (deepestViewUnderMouse is { })
  60. {
  61. #if DEBUG_IDISPOSABLE
  62. if (View.EnableDebugIDisposableAsserts && deepestViewUnderMouse.WasDisposed)
  63. {
  64. throw new ObjectDisposedException (deepestViewUnderMouse.GetType ().FullName);
  65. }
  66. #endif
  67. mouseEvent.View = deepestViewUnderMouse;
  68. }
  69. MouseEvent?.Invoke (null, mouseEvent);
  70. if (mouseEvent.Handled)
  71. {
  72. return;
  73. }
  74. // Dismiss the Popover if the user presses mouse outside of it
  75. if (mouseEvent.IsPressed
  76. && Application?.Popover?.GetActivePopover () as View is { Visible: true } visiblePopover
  77. && View.IsInHierarchy (visiblePopover, deepestViewUnderMouse, includeAdornments: true) is false)
  78. {
  79. ApplicationPopover.HideWithQuitCommand (visiblePopover);
  80. // Recurse once so the event can be handled below the popover
  81. RaiseMouseEvent (mouseEvent);
  82. return;
  83. }
  84. if (HandleMouseGrab (deepestViewUnderMouse, mouseEvent))
  85. {
  86. return;
  87. }
  88. // May be null before the prior condition or the condition may set it as null.
  89. // So, the checking must be outside the prior condition.
  90. if (deepestViewUnderMouse is null)
  91. {
  92. return;
  93. }
  94. // if the mouse is outside the Application.Top or Application.Popover hierarchy, we don't want to
  95. // send the mouse event to the deepest view under the mouse.
  96. if (!View.IsInHierarchy (Application?.Top, deepestViewUnderMouse, true) && !View.IsInHierarchy (Application?.Popover?.GetActivePopover () as View, deepestViewUnderMouse, true))
  97. {
  98. return;
  99. }
  100. // Create a view-relative mouse event to send to the view that is under the mouse.
  101. MouseEventArgs viewMouseEvent;
  102. if (deepestViewUnderMouse is Adornment adornment)
  103. {
  104. Point frameLoc = adornment.ScreenToFrame (mouseEvent.ScreenPosition);
  105. viewMouseEvent = new ()
  106. {
  107. Position = frameLoc,
  108. Flags = mouseEvent.Flags,
  109. ScreenPosition = mouseEvent.ScreenPosition,
  110. View = deepestViewUnderMouse
  111. };
  112. }
  113. else if (deepestViewUnderMouse.ViewportToScreen (Rectangle.Empty with { Size = deepestViewUnderMouse.Viewport.Size }).Contains (mouseEvent.ScreenPosition))
  114. {
  115. Point viewportLocation = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  116. viewMouseEvent = new ()
  117. {
  118. Position = viewportLocation,
  119. Flags = mouseEvent.Flags,
  120. ScreenPosition = mouseEvent.ScreenPosition,
  121. View = deepestViewUnderMouse
  122. };
  123. }
  124. else
  125. {
  126. // The mouse was outside any View's Viewport.
  127. // Debug.Fail ("This should never happen. If it does please file an Issue!!");
  128. return;
  129. }
  130. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  131. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  132. {
  133. if (deepestViewUnderMouse is Adornment adornmentView)
  134. {
  135. deepestViewUnderMouse = adornmentView.Parent?.SuperView;
  136. }
  137. else
  138. {
  139. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  140. }
  141. if (deepestViewUnderMouse is null)
  142. {
  143. break;
  144. }
  145. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  146. viewMouseEvent = new ()
  147. {
  148. Position = boundsPoint,
  149. Flags = mouseEvent.Flags,
  150. ScreenPosition = mouseEvent.ScreenPosition,
  151. View = deepestViewUnderMouse
  152. };
  153. }
  154. }
  155. /// <inheritdoc/>
  156. public void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  157. {
  158. // Tell any views that are no longer under the mouse that the mouse has left
  159. List<View?> viewsToLeave = CachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  160. foreach (View? view in viewsToLeave)
  161. {
  162. if (view is null)
  163. {
  164. continue;
  165. }
  166. view.NewMouseLeaveEvent ();
  167. CachedViewsUnderMouse.Remove (view);
  168. }
  169. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  170. foreach (View? view in currentViewsUnderMouse)
  171. {
  172. if (view is null)
  173. {
  174. continue;
  175. }
  176. if (CachedViewsUnderMouse.Contains (view))
  177. {
  178. continue;
  179. }
  180. CachedViewsUnderMouse.Add (view);
  181. var raise = false;
  182. if (view is Adornment { Parent: { } } adornmentView)
  183. {
  184. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  185. raise = adornmentView.Contains (superViewLoc);
  186. }
  187. else
  188. {
  189. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  190. raise = view.Contains (superViewLoc);
  191. }
  192. if (!raise)
  193. {
  194. continue;
  195. }
  196. CancelEventArgs eventArgs = new System.ComponentModel.CancelEventArgs ();
  197. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  198. if (cancelled is true || eventArgs.Cancel)
  199. {
  200. break;
  201. }
  202. }
  203. }
  204. /// <inheritdoc/>
  205. public void ResetState ()
  206. {
  207. // Do not clear LastMousePosition; Popover's require it to stay set with last mouse pos.
  208. CachedViewsUnderMouse.Clear ();
  209. MouseEvent = null;
  210. }
  211. // Mouse grab functionality merged from MouseGrabHandler
  212. /// <inheritdoc/>
  213. public void GrabMouse (View? view)
  214. {
  215. if (view is null || RaiseGrabbingMouseEvent (view))
  216. {
  217. return;
  218. }
  219. RaiseGrabbedMouseEvent (view);
  220. // MouseGrabView is only set if the application is initialized.
  221. MouseGrabView = view;
  222. }
  223. /// <inheritdoc/>
  224. public void UngrabMouse ()
  225. {
  226. if (MouseGrabView is null)
  227. {
  228. return;
  229. }
  230. #if DEBUG_IDISPOSABLE
  231. if (View.EnableDebugIDisposableAsserts)
  232. {
  233. ObjectDisposedException.ThrowIf (MouseGrabView.WasDisposed, MouseGrabView);
  234. }
  235. #endif
  236. if (!RaiseUnGrabbingMouseEvent (MouseGrabView))
  237. {
  238. View view = MouseGrabView;
  239. MouseGrabView = null;
  240. RaiseUnGrabbedMouseEvent (view);
  241. }
  242. }
  243. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  244. private bool RaiseGrabbingMouseEvent (View? view)
  245. {
  246. if (view is null)
  247. {
  248. return false;
  249. }
  250. GrabMouseEventArgs evArgs = new (view);
  251. GrabbingMouse?.Invoke (view, evArgs);
  252. return evArgs.Cancel;
  253. }
  254. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  255. private bool RaiseUnGrabbingMouseEvent (View? view)
  256. {
  257. if (view is null)
  258. {
  259. return false;
  260. }
  261. GrabMouseEventArgs evArgs = new (view);
  262. UnGrabbingMouse?.Invoke (view, evArgs);
  263. return evArgs.Cancel;
  264. }
  265. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  266. private void RaiseGrabbedMouseEvent (View? view)
  267. {
  268. if (view is null)
  269. {
  270. return;
  271. }
  272. GrabbedMouse?.Invoke (view, new (view));
  273. }
  274. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  275. private void RaiseUnGrabbedMouseEvent (View? view)
  276. {
  277. if (view is null)
  278. {
  279. return;
  280. }
  281. UnGrabbedMouse?.Invoke (view, new (view));
  282. }
  283. /// <summary>
  284. /// Handles mouse grab logic for a mouse event.
  285. /// </summary>
  286. /// <param name="deepestViewUnderMouse">The deepest view under the mouse.</param>
  287. /// <param name="mouseEvent">The mouse event to handle.</param>
  288. /// <returns><see langword="true"/> if the event was handled by the grab handler; otherwise <see langword="false"/>.</returns>
  289. public bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEventArgs mouseEvent)
  290. {
  291. if (MouseGrabView is { })
  292. {
  293. #if DEBUG_IDISPOSABLE
  294. if (View.EnableDebugIDisposableAsserts && MouseGrabView.WasDisposed)
  295. {
  296. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  297. }
  298. #endif
  299. // If the mouse is grabbed, send the event to the view that grabbed it.
  300. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  301. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  302. MouseEventArgs viewRelativeMouseEvent = new ()
  303. {
  304. Position = frameLoc,
  305. Flags = mouseEvent.Flags,
  306. ScreenPosition = mouseEvent.ScreenPosition,
  307. View = MouseGrabView // Always set to the grab view. See Issue #4370
  308. };
  309. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  310. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true || viewRelativeMouseEvent.IsSingleClicked)
  311. {
  312. return true;
  313. }
  314. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  315. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  316. {
  317. // The view that grabbed the mouse has been disposed
  318. return true;
  319. }
  320. }
  321. return false;
  322. }
  323. }