Application.Run.cs 23 KB

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