MouseImpl.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. using System.ComponentModel;
  2. namespace Terminal.Gui.App;
  3. /// <summary>
  4. /// INTERNAL: Implements <see cref="IMouse"/> to manage mouse event handling and state.
  5. /// <para>
  6. /// This class holds all mouse-related state that was previously in the static <see cref="App"/> class,
  7. /// enabling better testability and parallel test execution.
  8. /// </para>
  9. /// </summary>
  10. internal class MouseImpl : IMouse, IDisposable
  11. {
  12. /// <summary>
  13. /// Initializes a new instance of the <see cref="MouseImpl"/> class and subscribes to Application configuration property events.
  14. /// </summary>
  15. public MouseImpl ()
  16. {
  17. // Subscribe to Application static property change events
  18. Application.IsMouseDisabledChanged += OnIsMouseDisabledChanged;
  19. }
  20. /// <inheritdoc/>
  21. public IApplication? App { get; set; }
  22. /// <inheritdoc/>
  23. public Point? LastMousePosition { get; set; }
  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 (App?.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 = App?.TopRunnableView?.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. && App?.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.TopRunnable or Popover hierarchy, we don't want to
  95. // send the mouse event to the deepest view under the mouse.
  96. if (!View.IsInHierarchy (App?.TopRunnableView, deepestViewUnderMouse, true) && !View.IsInHierarchy (App?.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. if (currentViewsUnderMouse is { })
  131. {
  132. RaiseMouseEnterLeaveEvents (viewMouseEvent.ScreenPosition, currentViewsUnderMouse);
  133. }
  134. while (deepestViewUnderMouse.NewMouseEvent (viewMouseEvent) is not true && MouseGrabView is not { })
  135. {
  136. if (deepestViewUnderMouse is Adornment adornmentView)
  137. {
  138. deepestViewUnderMouse = adornmentView.Parent?.SuperView;
  139. }
  140. else
  141. {
  142. deepestViewUnderMouse = deepestViewUnderMouse.SuperView;
  143. }
  144. if (deepestViewUnderMouse is null)
  145. {
  146. break;
  147. }
  148. Point boundsPoint = deepestViewUnderMouse.ScreenToViewport (mouseEvent.ScreenPosition);
  149. viewMouseEvent = new ()
  150. {
  151. Position = boundsPoint,
  152. Flags = mouseEvent.Flags,
  153. ScreenPosition = mouseEvent.ScreenPosition,
  154. View = deepestViewUnderMouse
  155. };
  156. }
  157. }
  158. /// <inheritdoc/>
  159. public void RaiseMouseEnterLeaveEvents (Point screenPosition, List<View?> currentViewsUnderMouse)
  160. {
  161. // Tell any views that are no longer under the mouse that the mouse has left
  162. List<View?> viewsToLeave = CachedViewsUnderMouse.Where (v => v is { } && !currentViewsUnderMouse.Contains (v)).ToList ();
  163. foreach (View? view in viewsToLeave)
  164. {
  165. if (view is null)
  166. {
  167. continue;
  168. }
  169. view.NewMouseLeaveEvent ();
  170. CachedViewsUnderMouse.Remove (view);
  171. }
  172. // Tell any views that are now under the mouse that the mouse has entered and add them to the list
  173. foreach (View? view in currentViewsUnderMouse)
  174. {
  175. if (view is null)
  176. {
  177. continue;
  178. }
  179. if (CachedViewsUnderMouse.Contains (view))
  180. {
  181. continue;
  182. }
  183. CachedViewsUnderMouse.Add (view);
  184. var raise = false;
  185. if (view is Adornment { Parent: { } } adornmentView)
  186. {
  187. Point superViewLoc = adornmentView.Parent.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  188. raise = adornmentView.Contains (superViewLoc);
  189. }
  190. else
  191. {
  192. Point superViewLoc = view.SuperView?.ScreenToViewport (screenPosition) ?? screenPosition;
  193. raise = view.Contains (superViewLoc);
  194. }
  195. if (!raise)
  196. {
  197. continue;
  198. }
  199. CancelEventArgs eventArgs = new CancelEventArgs ();
  200. bool? cancelled = view.NewMouseEnterEvent (eventArgs);
  201. if (cancelled is true || eventArgs.Cancel)
  202. {
  203. break;
  204. }
  205. }
  206. }
  207. /// <inheritdoc/>
  208. public void ResetState ()
  209. {
  210. // Do not clear LastMousePosition; Popover's require it to stay set with last mouse pos.
  211. CachedViewsUnderMouse.Clear ();
  212. MouseEvent = null;
  213. MouseGrabView = null;
  214. }
  215. // Mouse grab functionality merged from MouseGrabHandler
  216. /// <inheritdoc/>
  217. public void GrabMouse (View? view)
  218. {
  219. if (RaiseGrabbingMouseEvent (view))
  220. {
  221. return;
  222. }
  223. if (view is null)
  224. {
  225. UngrabMouse();
  226. return;
  227. }
  228. RaiseGrabbedMouseEvent (view);
  229. // MouseGrabView is only set if the application is initialized.
  230. MouseGrabView = view;
  231. }
  232. /// <inheritdoc/>
  233. public void UngrabMouse ()
  234. {
  235. if (MouseGrabView is null)
  236. {
  237. return;
  238. }
  239. if (!RaiseUnGrabbingMouseEvent (MouseGrabView))
  240. {
  241. View view = MouseGrabView;
  242. MouseGrabView = null;
  243. RaiseUnGrabbedMouseEvent (view);
  244. }
  245. }
  246. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  247. private bool RaiseGrabbingMouseEvent (View? view)
  248. {
  249. if (view is null)
  250. {
  251. return false;
  252. }
  253. GrabMouseEventArgs evArgs = new (view);
  254. GrabbingMouse?.Invoke (view, evArgs);
  255. return evArgs.Cancel;
  256. }
  257. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  258. private bool RaiseUnGrabbingMouseEvent (View? view)
  259. {
  260. if (view is null)
  261. {
  262. return false;
  263. }
  264. GrabMouseEventArgs evArgs = new (view);
  265. UnGrabbingMouse?.Invoke (view, evArgs);
  266. return evArgs.Cancel;
  267. }
  268. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  269. private void RaiseGrabbedMouseEvent (View? view)
  270. {
  271. if (view is null)
  272. {
  273. return;
  274. }
  275. GrabbedMouse?.Invoke (view, new (view));
  276. }
  277. /// <exception cref="Exception">A delegate callback throws an exception.</exception>
  278. private void RaiseUnGrabbedMouseEvent (View? view)
  279. {
  280. if (view is null)
  281. {
  282. return;
  283. }
  284. UnGrabbedMouse?.Invoke (view, new (view));
  285. }
  286. /// <summary>
  287. /// Handles mouse grab logic for a mouse event.
  288. /// </summary>
  289. /// <param name="deepestViewUnderMouse">The deepest view under the mouse.</param>
  290. /// <param name="mouseEvent">The mouse event to handle.</param>
  291. /// <returns><see langword="true"/> if the event was handled by the grab handler; otherwise <see langword="false"/>.</returns>
  292. public bool HandleMouseGrab (View? deepestViewUnderMouse, MouseEventArgs mouseEvent)
  293. {
  294. if (MouseGrabView is { })
  295. {
  296. #if DEBUG_IDISPOSABLE
  297. if (View.EnableDebugIDisposableAsserts && MouseGrabView.WasDisposed)
  298. {
  299. throw new ObjectDisposedException (MouseGrabView.GetType ().FullName);
  300. }
  301. #endif
  302. // If the mouse is grabbed, send the event to the view that grabbed it.
  303. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  304. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.ScreenPosition);
  305. MouseEventArgs viewRelativeMouseEvent = new ()
  306. {
  307. Position = frameLoc,
  308. Flags = mouseEvent.Flags,
  309. ScreenPosition = mouseEvent.ScreenPosition,
  310. View = MouseGrabView // Always set to the grab view. See Issue #4370
  311. };
  312. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  313. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) is true || viewRelativeMouseEvent.IsSingleClicked)
  314. {
  315. return true;
  316. }
  317. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  318. if (MouseGrabView is null && deepestViewUnderMouse is Adornment)
  319. {
  320. // The view that grabbed the mouse has been disposed
  321. return true;
  322. }
  323. }
  324. return false;
  325. }
  326. // Event handler for Application static property changes
  327. private void OnIsMouseDisabledChanged (object? sender, ValueChangedEventArgs<bool> e)
  328. {
  329. IsMouseDisabled = e.NewValue;
  330. }
  331. /// <inheritdoc/>
  332. public void Dispose ()
  333. {
  334. // Unsubscribe from Application static property change events
  335. Application.IsMouseDisabledChanged -= OnIsMouseDisabledChanged;
  336. }
  337. }