MouseImpl.cs 12 KB

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