MouseImpl.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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?.Running?.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.Running 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?.Running, 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. MouseGrabView = 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. }