Application.Run.cs 25 KB

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