MouseImpl.cs 13 KB

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