MouseImpl.cs 12 KB

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