Application.Run.cs 25 KB

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