Application.Run.cs 27 KB

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