Application.Run.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. namespace Terminal.Gui;
  5. public static partial class Application // Run (Begin, Run, End, Stop)
  6. {
  7. // When `End ()` is called, it is possible `RunState.Toplevel` is a different object than `Top`.
  8. // This variable is set in `End` in this case so that `Begin` correctly sets `Top`.
  9. private static Toplevel? _cachedRunStateToplevel;
  10. /// <summary>
  11. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is
  12. /// created in <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  13. /// </summary>
  14. /// <remarks>
  15. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  16. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  17. /// when the application is done.
  18. /// </remarks>
  19. public static event EventHandler<RunStateEventArgs>? NotifyNewRunState;
  20. /// <summary>Notify that an existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).</summary>
  21. /// <remarks>
  22. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  23. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  24. /// when the application is done.
  25. /// </remarks>
  26. public static event EventHandler<ToplevelEventArgs>? NotifyStopRunState;
  27. /// <summary>Building block API: Prepares the provided <see cref="Toplevel"/> for execution.</summary>
  28. /// <returns>
  29. /// The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon
  30. /// completion.
  31. /// </returns>
  32. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  33. /// <remarks>
  34. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus, it adds this to the list
  35. /// of <see cref="Toplevel"/>s, lays out the Subviews, focuses the first element, and draws the <see cref="Toplevel"/>
  36. /// in the screen. This is usually followed by executing the <see cref="RunLoop"/> method, and then the
  37. /// <see cref="End(RunState)"/> method upon termination which will undo these changes.
  38. /// </remarks>
  39. public static RunState Begin (Toplevel toplevel)
  40. {
  41. ArgumentNullException.ThrowIfNull (toplevel);
  42. #if DEBUG_IDISPOSABLE
  43. Debug.Assert (!toplevel.WasDisposed);
  44. if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
  45. {
  46. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  47. }
  48. #endif
  49. // Ensure the mouse is ungrabbed.
  50. MouseGrabView = null;
  51. var rs = new RunState (toplevel);
  52. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  53. if (!toplevel.IsInitialized)
  54. {
  55. toplevel.BeginInit ();
  56. toplevel.EndInit ();
  57. }
  58. #if DEBUG_IDISPOSABLE
  59. if (Top is { } && toplevel != Top && !TopLevels.Contains (Top))
  60. {
  61. // This assertion confirm if the Top was already disposed
  62. Debug.Assert (Top.WasDisposed);
  63. Debug.Assert (Top == _cachedRunStateToplevel);
  64. }
  65. #endif
  66. lock (TopLevels)
  67. {
  68. if (Top is { } && toplevel != Top && !TopLevels.Contains (Top))
  69. {
  70. // If Top was already disposed and isn't on the Toplevels Stack,
  71. // clean it up here if is the same as _cachedRunStateToplevel
  72. if (Top == _cachedRunStateToplevel)
  73. {
  74. Top = null;
  75. }
  76. else
  77. {
  78. // Probably this will never hit
  79. throw new ObjectDisposedException (Top.GetType ().FullName);
  80. }
  81. }
  82. // BUGBUG: We should not depend on `Id` internally.
  83. // BUGBUG: It is super unclear what this code does anyway.
  84. if (string.IsNullOrEmpty (toplevel.Id))
  85. {
  86. var count = 1;
  87. var id = (TopLevels.Count + count).ToString ();
  88. while (TopLevels.Count > 0 && TopLevels.FirstOrDefault (x => x.Id == id) is { })
  89. {
  90. count++;
  91. id = (TopLevels.Count + count).ToString ();
  92. }
  93. toplevel.Id = (TopLevels.Count + count).ToString ();
  94. TopLevels.Push (toplevel);
  95. }
  96. else
  97. {
  98. Toplevel? dup = TopLevels.FirstOrDefault (x => x.Id == toplevel.Id);
  99. if (dup is null)
  100. {
  101. TopLevels.Push (toplevel);
  102. }
  103. }
  104. if (TopLevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0)
  105. {
  106. throw new ArgumentException ("There are duplicates Toplevel IDs");
  107. }
  108. }
  109. if (Top is null)
  110. {
  111. Top = toplevel;
  112. }
  113. if ((Top?.Modal == false && toplevel.Modal)
  114. || (Top?.Modal == false && !toplevel.Modal)
  115. || (Top?.Modal == true && toplevel.Modal))
  116. {
  117. if (toplevel.Visible)
  118. {
  119. if (Top is { HasFocus: true })
  120. {
  121. Top.HasFocus = false;
  122. }
  123. Top?.OnDeactivate (toplevel);
  124. Toplevel previousCurrent = Top!;
  125. Top = toplevel;
  126. Top.OnActivate (previousCurrent);
  127. }
  128. }
  129. toplevel.SetRelativeLayout (Driver!.Screen.Size);
  130. toplevel.LayoutSubviews ();
  131. // Try to set initial focus to any TabStop
  132. if (!toplevel.HasFocus)
  133. {
  134. toplevel.SetFocus ();
  135. }
  136. toplevel.OnLoaded ();
  137. Refresh ();
  138. if (PositionCursor ())
  139. {
  140. Driver.UpdateCursor ();
  141. }
  142. NotifyNewRunState?.Invoke (toplevel, new (rs));
  143. return rs;
  144. }
  145. /// <summary>
  146. /// Calls <see cref="View.PositionCursor"/> on the most focused view in the view starting with <paramref name="view"/>.
  147. /// </summary>
  148. /// <remarks>
  149. /// Does nothing if <paramref name="view"/> is <see langword="null"/> or if the most focused view is not visible or
  150. /// enabled.
  151. /// <para>
  152. /// If the most focused view is not visible within it's superview, the cursor will be hidden.
  153. /// </para>
  154. /// </remarks>
  155. /// <returns><see langword="true"/> if a view positioned the cursor and the position is visible.</returns>
  156. internal static bool PositionCursor ()
  157. {
  158. // Find the most focused view and position the cursor there.
  159. View? mostFocused = Navigation?.GetFocused ();
  160. // If the view is not visible or enabled, don't position the cursor
  161. if (mostFocused is null || !mostFocused.Visible || !mostFocused.Enabled)
  162. {
  163. Driver!.GetCursorVisibility (out CursorVisibility current);
  164. if (current != CursorVisibility.Invisible)
  165. {
  166. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  167. }
  168. return false;
  169. }
  170. // If the view is not visible within it's superview, don't position the cursor
  171. Rectangle mostFocusedViewport = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = Point.Empty });
  172. Rectangle superViewViewport = mostFocused.SuperView?.ViewportToScreen (mostFocused.SuperView.Viewport with { Location = Point.Empty }) ?? Driver!.Screen;
  173. if (!superViewViewport.IntersectsWith (mostFocusedViewport))
  174. {
  175. return false;
  176. }
  177. Point? cursor = mostFocused.PositionCursor ();
  178. Driver!.GetCursorVisibility (out CursorVisibility currentCursorVisibility);
  179. if (cursor is { })
  180. {
  181. // Convert cursor to screen coords
  182. cursor = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = cursor.Value }).Location;
  183. // If the cursor is not in a visible location in the SuperView, hide it
  184. if (!superViewViewport.Contains (cursor.Value))
  185. {
  186. if (currentCursorVisibility != CursorVisibility.Invisible)
  187. {
  188. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  189. }
  190. return false;
  191. }
  192. // Show it
  193. if (currentCursorVisibility == CursorVisibility.Invisible)
  194. {
  195. Driver.SetCursorVisibility (mostFocused.CursorVisibility);
  196. }
  197. return true;
  198. }
  199. if (currentCursorVisibility != CursorVisibility.Invisible)
  200. {
  201. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  202. }
  203. return false;
  204. }
  205. /// <summary>
  206. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  207. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  208. /// </summary>
  209. /// <remarks>
  210. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  211. /// <para>
  212. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  213. /// ensure resources are cleaned up and terminal settings restored.
  214. /// </para>
  215. /// <para>
  216. /// The caller is responsible for disposing the object returned by this method.
  217. /// </para>
  218. /// </remarks>
  219. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  220. [RequiresUnreferencedCode ("AOT")]
  221. [RequiresDynamicCode ("AOT")]
  222. public static Toplevel Run (Func<Exception, bool>? errorHandler = null, ConsoleDriver? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  223. /// <summary>
  224. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  225. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  226. /// </summary>
  227. /// <remarks>
  228. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  229. /// <para>
  230. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  231. /// ensure resources are cleaned up and terminal settings restored.
  232. /// </para>
  233. /// <para>
  234. /// The caller is responsible for disposing the object returned by this method.
  235. /// </para>
  236. /// </remarks>
  237. /// <param name="errorHandler"></param>
  238. /// <param name="driver">
  239. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  240. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  241. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  242. /// </param>
  243. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  244. [RequiresUnreferencedCode ("AOT")]
  245. [RequiresDynamicCode ("AOT")]
  246. public static T Run<T> (Func<Exception, bool>? errorHandler = null, ConsoleDriver? driver = null)
  247. where T : Toplevel, new()
  248. {
  249. if (!IsInitialized)
  250. {
  251. // Init() has NOT been called.
  252. InternalInit (driver, null, true);
  253. }
  254. var top = new T ();
  255. Run (top, errorHandler);
  256. return top;
  257. }
  258. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  259. /// <remarks>
  260. /// <para>
  261. /// This method is used to start processing events for the main application, but it is also used to run other
  262. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  263. /// </para>
  264. /// <para>
  265. /// To make a <see cref="Run(Terminal.Gui.Toplevel,System.Func{System.Exception,bool})"/> stop execution, call
  266. /// <see cref="Application.RequestStop"/>.
  267. /// </para>
  268. /// <para>
  269. /// Calling <see cref="Run(Terminal.Gui.Toplevel,System.Func{System.Exception,bool})"/> is equivalent to calling
  270. /// <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState)"/>, and then calling
  271. /// <see cref="End(RunState)"/>.
  272. /// </para>
  273. /// <para>
  274. /// Alternatively, to have a program control the main loop and process events manually, call
  275. /// <see cref="Begin(Toplevel)"/> to set things up manually and then repeatedly call
  276. /// <see cref="RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  277. /// <see cref="RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  278. /// return control immediately.
  279. /// </para>
  280. /// <para>When using <see cref="Run{T}"/> or
  281. /// <see cref="Run(System.Func{System.Exception,bool},Terminal.Gui.ConsoleDriver)"/>
  282. /// <see cref="Init"/> will be called automatically.
  283. /// </para>
  284. /// <para>
  285. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  286. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  287. /// returns <see langword="true"/> the <see cref="RunLoop(RunState)"/> will resume; otherwise this method will
  288. /// exit.
  289. /// </para>
  290. /// </remarks>
  291. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  292. /// <param name="errorHandler">
  293. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  294. /// rethrows when null).
  295. /// </param>
  296. public static void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  297. {
  298. ArgumentNullException.ThrowIfNull (view);
  299. if (IsInitialized)
  300. {
  301. if (Driver is null)
  302. {
  303. // Disposing before throwing
  304. view.Dispose ();
  305. // This code path should be impossible because Init(null, null) will select the platform default driver
  306. throw new InvalidOperationException (
  307. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  308. );
  309. }
  310. }
  311. else
  312. {
  313. // Init() has NOT been called.
  314. throw new InvalidOperationException (
  315. "Init() has not been called. Only Run() or Run<T>() can be used without calling Init()."
  316. );
  317. }
  318. var resume = true;
  319. while (resume)
  320. {
  321. #if !DEBUG
  322. try
  323. {
  324. #endif
  325. resume = false;
  326. RunState runState = Begin (view);
  327. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  328. // by using NotifyStopRunState event.
  329. RunLoop (runState);
  330. if (runState.Toplevel is null)
  331. {
  332. #if DEBUG_IDISPOSABLE
  333. Debug.Assert (TopLevels.Count == 0);
  334. #endif
  335. runState.Dispose ();
  336. return;
  337. }
  338. if (!EndAfterFirstIteration)
  339. {
  340. End (runState);
  341. }
  342. #if !DEBUG
  343. }
  344. catch (Exception error)
  345. {
  346. if (errorHandler is null)
  347. {
  348. throw;
  349. }
  350. resume = errorHandler (error);
  351. }
  352. #endif
  353. }
  354. }
  355. /// <summary>Adds a timeout to the application.</summary>
  356. /// <remarks>
  357. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  358. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  359. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  360. /// </remarks>
  361. public static object AddTimeout (TimeSpan time, Func<bool> callback) { return MainLoop!.AddTimeout (time, callback); }
  362. /// <summary>Removes a previously scheduled timeout</summary>
  363. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  364. /// Returns
  365. /// <c>true</c>
  366. /// if the timeout is successfully removed; otherwise,
  367. /// <c>false</c>
  368. /// .
  369. /// This method also returns
  370. /// <c>false</c>
  371. /// if the timeout is not found.
  372. public static bool RemoveTimeout (object token) { return MainLoop?.RemoveTimeout (token) ?? false; }
  373. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  374. /// <param name="action">the action to be invoked on the main processing thread.</param>
  375. public static void Invoke (Action action)
  376. {
  377. MainLoop?.AddIdle (
  378. () =>
  379. {
  380. action ();
  381. return false;
  382. }
  383. );
  384. }
  385. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  386. // is ProgressBarStyles, and it's not clear it needs to.
  387. /// <summary>Wakes up the running application that might be waiting on input.</summary>
  388. public static void Wakeup () { MainLoop?.Wakeup (); }
  389. /// <summary>Triggers a refresh of the entire display.</summary>
  390. public static void Refresh ()
  391. {
  392. foreach (Toplevel v in TopLevels.Reverse ())
  393. {
  394. if (v.LayoutNeeded)
  395. {
  396. v.LayoutSubviews ();
  397. }
  398. if (v.Visible)
  399. {
  400. v.SetNeedsDisplay ();
  401. v.SetSubViewNeedsDisplay ();
  402. v.Draw ();
  403. }
  404. }
  405. Driver!.Refresh ();
  406. }
  407. /// <summary>This event is raised on each iteration of the main loop.</summary>
  408. /// <remarks>See also <see cref="Timeout"/></remarks>
  409. public static event EventHandler<IterationEventArgs>? Iteration;
  410. /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
  411. /// <value>The main loop.</value>
  412. internal static MainLoop? MainLoop { get; private set; }
  413. /// <summary>
  414. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  415. /// cause the application to continue running until Application.RequestStop () is called.
  416. /// </summary>
  417. public static bool EndAfterFirstIteration { get; set; }
  418. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  419. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  420. public static void RunLoop (RunState state)
  421. {
  422. ArgumentNullException.ThrowIfNull (state);
  423. ObjectDisposedException.ThrowIf (state.Toplevel is null, "state");
  424. var firstIteration = true;
  425. for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
  426. {
  427. MainLoop!.Running = true;
  428. if (EndAfterFirstIteration && !firstIteration)
  429. {
  430. return;
  431. }
  432. RunIteration (ref state, ref firstIteration);
  433. }
  434. MainLoop!.Running = false;
  435. // Run one last iteration to consume any outstanding input events from Driver
  436. // This is important for remaining OnKeyUp events.
  437. RunIteration (ref state, ref firstIteration);
  438. }
  439. /// <summary>Run one application iteration.</summary>
  440. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  441. /// <param name="firstIteration">
  442. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  443. /// will be set to <see langword="false"/> if at least one iteration happened.
  444. /// </param>
  445. public static void RunIteration (ref RunState state, ref bool firstIteration)
  446. {
  447. if (MainLoop!.Running && MainLoop.EventsPending ())
  448. {
  449. // Notify Toplevel it's ready
  450. if (firstIteration)
  451. {
  452. state.Toplevel.OnReady ();
  453. }
  454. MainLoop.RunIteration ();
  455. Iteration?.Invoke (null, new ());
  456. }
  457. firstIteration = false;
  458. if (Top is null)
  459. {
  460. return;
  461. }
  462. Refresh ();
  463. if (PositionCursor ())
  464. {
  465. Driver!.UpdateCursor ();
  466. }
  467. }
  468. /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
  469. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  470. /// <remarks>
  471. /// <para>This will cause <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to return.</para>
  472. /// <para>
  473. /// Calling <see cref="RequestStop(Terminal.Gui.Toplevel)"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  474. /// property on the currently running <see cref="Toplevel"/> to false.
  475. /// </para>
  476. /// </remarks>
  477. public static void RequestStop (Toplevel? top = null)
  478. {
  479. if (top is null)
  480. {
  481. top = Top;
  482. }
  483. if (!top!.Running)
  484. {
  485. return;
  486. }
  487. var ev = new ToplevelClosingEventArgs (top);
  488. top.OnClosing (ev);
  489. if (ev.Cancel)
  490. {
  491. return;
  492. }
  493. top.Running = false;
  494. OnNotifyStopRunState (top);
  495. }
  496. private static void OnNotifyStopRunState (Toplevel top)
  497. {
  498. if (EndAfterFirstIteration)
  499. {
  500. NotifyStopRunState?.Invoke (top, new (top));
  501. }
  502. }
  503. /// <summary>
  504. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  505. /// <see cref="Begin(Toplevel)"/> .
  506. /// </summary>
  507. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  508. public static void End (RunState runState)
  509. {
  510. ArgumentNullException.ThrowIfNull (runState);
  511. runState.Toplevel.OnUnloaded ();
  512. // End the RunState.Toplevel
  513. // First, take it off the Toplevel Stack
  514. if (TopLevels.Count > 0)
  515. {
  516. if (TopLevels.Peek () != runState.Toplevel)
  517. {
  518. // If the top of the stack is not the RunState.Toplevel then
  519. // this call to End is not balanced with the call to Begin that started the RunState
  520. throw new ArgumentException ("End must be balanced with calls to Begin");
  521. }
  522. TopLevels.Pop ();
  523. }
  524. // Notify that it is closing
  525. runState.Toplevel?.OnClosed (runState.Toplevel);
  526. if (TopLevels.Count > 0)
  527. {
  528. Top = TopLevels.Peek ();
  529. }
  530. // BUGBUG: We should not call OnEnter/OnLeave directly; they should only be called by SetHasFocus
  531. if (runState.Toplevel is { HasFocus: true })
  532. {
  533. runState.Toplevel.HasFocus = false;
  534. }
  535. if (Top is { HasFocus: false })
  536. {
  537. Top.SetFocus ();
  538. }
  539. //Refresh ();
  540. _cachedRunStateToplevel = runState.Toplevel;
  541. runState.Toplevel = null;
  542. runState.Dispose ();
  543. }
  544. }