Application.Run.cs 24 KB

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