Application.Run.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. // When `End ()` is called, it is possible `RunState.Toplevel` is a different object than `Top`.
  8. // This variable is set in `End` in this case so that `Begin` correctly sets `Top`.
  9. private static Toplevel? _cachedRunStateToplevel;
  10. /// <summary>
  11. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is
  12. /// created in <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  13. /// </summary>
  14. /// <remarks>
  15. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  16. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  17. /// when the application is done.
  18. /// </remarks>
  19. public static event EventHandler<RunStateEventArgs>? NotifyNewRunState;
  20. /// <summary>Notify that an existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).</summary>
  21. /// <remarks>
  22. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  23. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  24. /// when the application is done.
  25. /// </remarks>
  26. public static event EventHandler<ToplevelEventArgs>? NotifyStopRunState;
  27. /// <summary>Building block API: Prepares the provided <see cref="Toplevel"/> for execution.</summary>
  28. /// <returns>
  29. /// The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon
  30. /// completion.
  31. /// </returns>
  32. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  33. /// <remarks>
  34. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus, it adds this to the list
  35. /// of <see cref="Toplevel"/>s, lays out the Subviews, focuses the first element, and draws the <see cref="Toplevel"/>
  36. /// in the screen. This is usually followed by executing the <see cref="RunLoop"/> method, and then the
  37. /// <see cref="End(RunState)"/> method upon termination which will undo these changes.
  38. /// </remarks>
  39. public static RunState Begin (Toplevel toplevel)
  40. {
  41. ArgumentNullException.ThrowIfNull (toplevel);
  42. #if DEBUG_IDISPOSABLE
  43. Debug.Assert (!toplevel.WasDisposed);
  44. if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
  45. {
  46. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  47. }
  48. #endif
  49. if (toplevel.IsOverlappedContainer && ApplicationOverlapped.OverlappedTop != toplevel && ApplicationOverlapped.OverlappedTop is { })
  50. {
  51. throw new InvalidOperationException ("Only one Overlapped Container is allowed.");
  52. }
  53. // Ensure the mouse is ungrabbed.
  54. MouseGrabView = null;
  55. var rs = new RunState (toplevel);
  56. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  57. if (!toplevel.IsInitialized)
  58. {
  59. toplevel.BeginInit ();
  60. toplevel.EndInit ();
  61. }
  62. #if DEBUG_IDISPOSABLE
  63. if (Top is { } && toplevel != Top && !TopLevels.Contains (Top))
  64. {
  65. // This assertion confirm if the Top was already disposed
  66. Debug.Assert (Top.WasDisposed);
  67. Debug.Assert (Top == _cachedRunStateToplevel);
  68. }
  69. #endif
  70. lock (TopLevels)
  71. {
  72. if (Top is { } && toplevel != Top && !TopLevels.Contains (Top))
  73. {
  74. // If Top was already disposed and isn't on the Toplevels Stack,
  75. // clean it up here if is the same as _cachedRunStateToplevel
  76. if (Top == _cachedRunStateToplevel)
  77. {
  78. Top = null;
  79. }
  80. else
  81. {
  82. // Probably this will never hit
  83. throw new ObjectDisposedException (Top.GetType ().FullName);
  84. }
  85. }
  86. else if (ApplicationOverlapped.OverlappedTop is { } && toplevel != Top && TopLevels.Contains (Top!))
  87. {
  88. // BUGBUG: Don't call OnLeave/OnEnter directly! Set HasFocus to false and let the system handle it.
  89. //Top!.OnLeave (toplevel);
  90. }
  91. // BUGBUG: We should not depend on `Id` internally.
  92. // BUGBUG: It is super unclear what this code does anyway.
  93. if (string.IsNullOrEmpty (toplevel.Id))
  94. {
  95. var count = 1;
  96. var id = (TopLevels.Count + count).ToString ();
  97. while (TopLevels.Count > 0 && TopLevels.FirstOrDefault (x => x.Id == id) is { })
  98. {
  99. count++;
  100. id = (TopLevels.Count + count).ToString ();
  101. }
  102. toplevel.Id = (TopLevels.Count + count).ToString ();
  103. TopLevels.Push (toplevel);
  104. }
  105. else
  106. {
  107. Toplevel? dup = TopLevels.FirstOrDefault (x => x.Id == toplevel.Id);
  108. if (dup is null)
  109. {
  110. TopLevels.Push (toplevel);
  111. }
  112. }
  113. if (TopLevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0)
  114. {
  115. throw new ArgumentException ("There are duplicates Toplevel IDs");
  116. }
  117. }
  118. if (Top is null || toplevel.IsOverlappedContainer)
  119. {
  120. Top = toplevel;
  121. }
  122. var refreshDriver = true;
  123. if (ApplicationOverlapped.OverlappedTop is null
  124. || toplevel.IsOverlappedContainer
  125. || (Current?.Modal == false && toplevel.Modal)
  126. || (Current?.Modal == false && !toplevel.Modal)
  127. || (Current?.Modal == true && toplevel.Modal))
  128. {
  129. if (toplevel.Visible)
  130. {
  131. if (Current is { HasFocus: true })
  132. {
  133. Current.HasFocus = false;
  134. }
  135. Current?.OnDeactivate (toplevel);
  136. Toplevel previousCurrent = Current!;
  137. Current = toplevel;
  138. Current.OnActivate (previousCurrent);
  139. ApplicationOverlapped.SetCurrentOverlappedAsTop ();
  140. }
  141. else
  142. {
  143. refreshDriver = false;
  144. }
  145. }
  146. else if ((toplevel != ApplicationOverlapped.OverlappedTop
  147. && Current?.Modal == true
  148. && !TopLevels.Peek ().Modal)
  149. || (toplevel != ApplicationOverlapped.OverlappedTop && Current?.Running == false))
  150. {
  151. refreshDriver = false;
  152. ApplicationOverlapped.MoveCurrent (toplevel);
  153. }
  154. else
  155. {
  156. refreshDriver = false;
  157. ApplicationOverlapped.MoveCurrent (Current!);
  158. }
  159. toplevel.SetRelativeLayout (Driver!.Screen.Size);
  160. toplevel.LayoutSubviews ();
  161. toplevel.PositionToplevels ();
  162. // TODO: Should this use FindDeepestFocusableView instead?
  163. // Try to set initial focus to any TabStop
  164. if (!toplevel.HasFocus)
  165. {
  166. toplevel.SetFocus ();
  167. //if (!toplevel.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop))
  168. //{
  169. // // That didn't work. Try TabGroup.
  170. // toplevel.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup);
  171. //}
  172. }
  173. ApplicationOverlapped.BringOverlappedTopToFront ();
  174. if (refreshDriver)
  175. {
  176. ApplicationOverlapped.OverlappedTop?.OnChildLoaded (toplevel);
  177. toplevel.OnLoaded ();
  178. toplevel.SetNeedsDisplay ();
  179. toplevel.Draw ();
  180. Driver.UpdateScreen ();
  181. if (PositionCursor (toplevel))
  182. {
  183. Driver.UpdateCursor ();
  184. }
  185. }
  186. NotifyNewRunState?.Invoke (toplevel, new (rs));
  187. return rs;
  188. }
  189. /// <summary>
  190. /// Calls <see cref="View.PositionCursor"/> on the most focused view in the view starting with <paramref name="view"/>.
  191. /// </summary>
  192. /// <remarks>
  193. /// Does nothing if <paramref name="view"/> is <see langword="null"/> or if the most focused view is not visible or
  194. /// enabled.
  195. /// <para>
  196. /// If the most focused view is not visible within it's superview, the cursor will be hidden.
  197. /// </para>
  198. /// </remarks>
  199. /// <returns><see langword="true"/> if a view positioned the cursor and the position is visible.</returns>
  200. internal static bool PositionCursor (View view)
  201. {
  202. // Find the most focused view and position the cursor there.
  203. View? mostFocused = view?.MostFocused;
  204. if (mostFocused is null)
  205. {
  206. if (view is { HasFocus: true })
  207. {
  208. mostFocused = view;
  209. }
  210. else
  211. {
  212. return false;
  213. }
  214. }
  215. // If the view is not visible or enabled, don't position the cursor
  216. if (!mostFocused.Visible || !mostFocused.Enabled)
  217. {
  218. Driver!.GetCursorVisibility (out CursorVisibility current);
  219. if (current != CursorVisibility.Invisible)
  220. {
  221. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  222. }
  223. return false;
  224. }
  225. // If the view is not visible within it's superview, don't position the cursor
  226. Rectangle mostFocusedViewport = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = Point.Empty });
  227. Rectangle superViewViewport = mostFocused.SuperView?.ViewportToScreen (mostFocused.SuperView.Viewport with { Location = Point.Empty }) ?? Driver!.Screen;
  228. if (!superViewViewport.IntersectsWith (mostFocusedViewport))
  229. {
  230. return false;
  231. }
  232. Point? cursor = mostFocused.PositionCursor ();
  233. Driver!.GetCursorVisibility (out CursorVisibility currentCursorVisibility);
  234. if (cursor is { })
  235. {
  236. // Convert cursor to screen coords
  237. cursor = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = cursor.Value }).Location;
  238. // If the cursor is not in a visible location in the SuperView, hide it
  239. if (!superViewViewport.Contains (cursor.Value))
  240. {
  241. if (currentCursorVisibility != CursorVisibility.Invisible)
  242. {
  243. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  244. }
  245. return false;
  246. }
  247. // Show it
  248. if (currentCursorVisibility == CursorVisibility.Invisible)
  249. {
  250. Driver.SetCursorVisibility (mostFocused.CursorVisibility);
  251. }
  252. return true;
  253. }
  254. if (currentCursorVisibility != CursorVisibility.Invisible)
  255. {
  256. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  257. }
  258. return false;
  259. }
  260. /// <summary>
  261. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  262. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  263. /// </summary>
  264. /// <remarks>
  265. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  266. /// <para>
  267. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  268. /// ensure resources are cleaned up and terminal settings restored.
  269. /// </para>
  270. /// <para>
  271. /// The caller is responsible for disposing the object returned by this method.
  272. /// </para>
  273. /// </remarks>
  274. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  275. [RequiresUnreferencedCode ("AOT")]
  276. [RequiresDynamicCode ("AOT")]
  277. public static Toplevel Run (Func<Exception, bool>? errorHandler = null, ConsoleDriver? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  278. /// <summary>
  279. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  280. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  281. /// </summary>
  282. /// <remarks>
  283. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  284. /// <para>
  285. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  286. /// ensure resources are cleaned up and terminal settings restored.
  287. /// </para>
  288. /// <para>
  289. /// The caller is responsible for disposing the object returned by this method.
  290. /// </para>
  291. /// </remarks>
  292. /// <param name="errorHandler"></param>
  293. /// <param name="driver">
  294. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  295. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  296. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  297. /// </param>
  298. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  299. [RequiresUnreferencedCode ("AOT")]
  300. [RequiresDynamicCode ("AOT")]
  301. public static T Run<T> (Func<Exception, bool>? errorHandler = null, ConsoleDriver? driver = null)
  302. where T : Toplevel, new()
  303. {
  304. if (!IsInitialized)
  305. {
  306. // Init() has NOT been called.
  307. InternalInit (driver, null, true);
  308. }
  309. var top = new T ();
  310. Run (top, errorHandler);
  311. return top;
  312. }
  313. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  314. /// <remarks>
  315. /// <para>
  316. /// This method is used to start processing events for the main application, but it is also used to run other
  317. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  318. /// </para>
  319. /// <para>
  320. /// To make a <see cref="Run(Terminal.Gui.Toplevel,System.Func{System.Exception,bool})"/> stop execution, call
  321. /// <see cref="Application.RequestStop"/>.
  322. /// </para>
  323. /// <para>
  324. /// Calling <see cref="Run(Terminal.Gui.Toplevel,System.Func{System.Exception,bool})"/> is equivalent to calling
  325. /// <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState)"/>, and then calling
  326. /// <see cref="End(RunState)"/>.
  327. /// </para>
  328. /// <para>
  329. /// Alternatively, to have a program control the main loop and process events manually, call
  330. /// <see cref="Begin(Toplevel)"/> to set things up manually and then repeatedly call
  331. /// <see cref="RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  332. /// <see cref="RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  333. /// return control immediately.
  334. /// </para>
  335. /// <para>When using <see cref="Run{T}"/> or
  336. /// <see cref="Run(System.Func{System.Exception,bool},Terminal.Gui.ConsoleDriver)"/>
  337. /// <see cref="Init"/> will be called automatically.
  338. /// </para>
  339. /// <para>
  340. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  341. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  342. /// returns <see langword="true"/> the <see cref="RunLoop(RunState)"/> will resume; otherwise this method will
  343. /// exit.
  344. /// </para>
  345. /// </remarks>
  346. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  347. /// <param name="errorHandler">
  348. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  349. /// rethrows when null).
  350. /// </param>
  351. public static void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  352. {
  353. ArgumentNullException.ThrowIfNull (view);
  354. if (IsInitialized)
  355. {
  356. if (Driver is null)
  357. {
  358. // Disposing before throwing
  359. view.Dispose ();
  360. // This code path should be impossible because Init(null, null) will select the platform default driver
  361. throw new InvalidOperationException (
  362. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  363. );
  364. }
  365. }
  366. else
  367. {
  368. // Init() has NOT been called.
  369. throw new InvalidOperationException (
  370. "Init() has not been called. Only Run() or Run<T>() can be used without calling Init()."
  371. );
  372. }
  373. var resume = true;
  374. while (resume)
  375. {
  376. #if !DEBUG
  377. try
  378. {
  379. #endif
  380. resume = false;
  381. RunState runState = Begin (view);
  382. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  383. // by using NotifyStopRunState event.
  384. RunLoop (runState);
  385. if (runState.Toplevel is null)
  386. {
  387. #if DEBUG_IDISPOSABLE
  388. Debug.Assert (TopLevels.Count == 0);
  389. #endif
  390. runState.Dispose ();
  391. return;
  392. }
  393. if (!EndAfterFirstIteration)
  394. {
  395. End (runState);
  396. }
  397. #if !DEBUG
  398. }
  399. catch (Exception error)
  400. {
  401. if (errorHandler is null)
  402. {
  403. throw;
  404. }
  405. resume = errorHandler (error);
  406. }
  407. #endif
  408. }
  409. }
  410. /// <summary>Adds a timeout to the application.</summary>
  411. /// <remarks>
  412. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  413. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  414. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  415. /// </remarks>
  416. public static object AddTimeout (TimeSpan time, Func<bool> callback) { return MainLoop!.AddTimeout (time, callback); }
  417. /// <summary>Removes a previously scheduled timeout</summary>
  418. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  419. /// Returns
  420. /// <c>true</c>
  421. /// if the timeout is successfully removed; otherwise,
  422. /// <c>false</c>
  423. /// .
  424. /// This method also returns
  425. /// <c>false</c>
  426. /// if the timeout is not found.
  427. public static bool RemoveTimeout (object token) { return MainLoop?.RemoveTimeout (token) ?? false; }
  428. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  429. /// <param name="action">the action to be invoked on the main processing thread.</param>
  430. public static void Invoke (Action action)
  431. {
  432. MainLoop?.AddIdle (
  433. () =>
  434. {
  435. action ();
  436. return false;
  437. }
  438. );
  439. }
  440. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  441. // is ProgressBarStyles, and it's not clear it needs to.
  442. /// <summary>Wakes up the running application that might be waiting on input.</summary>
  443. public static void Wakeup () { MainLoop?.Wakeup (); }
  444. /// <summary>Triggers a refresh of the entire display.</summary>
  445. public static void Refresh ()
  446. {
  447. // TODO: Figure out how to remove this call to ClearContents. Refresh should just repaint damaged areas, not clear
  448. Driver!.ClearContents ();
  449. foreach (Toplevel v in TopLevels.Reverse ())
  450. {
  451. if (v.Visible)
  452. {
  453. v.SetNeedsDisplay ();
  454. v.SetSubViewNeedsDisplay ();
  455. v.Draw ();
  456. }
  457. }
  458. Driver.Refresh ();
  459. }
  460. /// <summary>This event is raised on each iteration of the main loop.</summary>
  461. /// <remarks>See also <see cref="Timeout"/></remarks>
  462. public static event EventHandler<IterationEventArgs>? Iteration;
  463. /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
  464. /// <value>The main loop.</value>
  465. internal static MainLoop? MainLoop { get; private set; }
  466. /// <summary>
  467. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  468. /// cause the application to continue running until Application.RequestStop () is called.
  469. /// </summary>
  470. public static bool EndAfterFirstIteration { get; set; }
  471. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  472. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  473. public static void RunLoop (RunState state)
  474. {
  475. ArgumentNullException.ThrowIfNull (state);
  476. ObjectDisposedException.ThrowIf (state.Toplevel is null, "state");
  477. var firstIteration = true;
  478. for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
  479. {
  480. MainLoop!.Running = true;
  481. if (EndAfterFirstIteration && !firstIteration)
  482. {
  483. return;
  484. }
  485. RunIteration (ref state, ref firstIteration);
  486. }
  487. MainLoop!.Running = false;
  488. // Run one last iteration to consume any outstanding input events from Driver
  489. // This is important for remaining OnKeyUp events.
  490. RunIteration (ref state, ref firstIteration);
  491. }
  492. /// <summary>Run one application iteration.</summary>
  493. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  494. /// <param name="firstIteration">
  495. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  496. /// will be set to <see langword="false"/> if at least one iteration happened.
  497. /// </param>
  498. public static void RunIteration (ref RunState state, ref bool firstIteration)
  499. {
  500. if (MainLoop!.Running && MainLoop.EventsPending ())
  501. {
  502. // Notify Toplevel it's ready
  503. if (firstIteration)
  504. {
  505. state.Toplevel.OnReady ();
  506. }
  507. MainLoop.RunIteration ();
  508. Iteration?.Invoke (null, new ());
  509. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  510. // TODO: Overlapped - Move elsewhere
  511. if (state.Toplevel != Current)
  512. {
  513. ApplicationOverlapped.OverlappedTop?.OnDeactivate (state.Toplevel);
  514. state.Toplevel = Current;
  515. ApplicationOverlapped.OverlappedTop?.OnActivate (state.Toplevel!);
  516. Top!.SetSubViewNeedsDisplay ();
  517. Refresh ();
  518. }
  519. }
  520. firstIteration = false;
  521. if (Current == null)
  522. {
  523. return;
  524. }
  525. if (state.Toplevel != Top && (Top!.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  526. {
  527. state.Toplevel!.SetNeedsDisplay (state.Toplevel.Frame);
  528. Top.Draw ();
  529. foreach (Toplevel top in TopLevels.Reverse ())
  530. {
  531. if (top != Top && top != state.Toplevel)
  532. {
  533. top.SetNeedsDisplay ();
  534. top.SetSubViewNeedsDisplay ();
  535. top.Draw ();
  536. }
  537. }
  538. }
  539. if (TopLevels.Count == 1
  540. && state.Toplevel == Top
  541. && (Driver!.Cols != state.Toplevel!.Frame.Width
  542. || Driver!.Rows != state.Toplevel.Frame.Height)
  543. && (state.Toplevel.NeedsDisplay
  544. || state.Toplevel.SubViewNeedsDisplay
  545. || state.Toplevel.LayoutNeeded))
  546. {
  547. Driver.ClearContents ();
  548. }
  549. if (state.Toplevel!.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded || ApplicationOverlapped.OverlappedChildNeedsDisplay ())
  550. {
  551. state.Toplevel.SetNeedsDisplay ();
  552. state.Toplevel.Draw ();
  553. Driver!.UpdateScreen ();
  554. //Driver.UpdateCursor ();
  555. }
  556. if (PositionCursor (state.Toplevel))
  557. {
  558. Driver!.UpdateCursor ();
  559. }
  560. // else
  561. {
  562. //if (PositionCursor (state.Toplevel))
  563. //{
  564. // Driver.Refresh ();
  565. //}
  566. //Driver.UpdateCursor ();
  567. }
  568. if (state.Toplevel != Top && !state.Toplevel.Modal && (Top!.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  569. {
  570. Top.Draw ();
  571. }
  572. }
  573. /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
  574. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  575. /// <remarks>
  576. /// <para>This will cause <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to return.</para>
  577. /// <para>
  578. /// Calling <see cref="RequestStop(Terminal.Gui.Toplevel)"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  579. /// property on the currently running <see cref="Toplevel"/> to false.
  580. /// </para>
  581. /// </remarks>
  582. public static void RequestStop (Toplevel? top = null)
  583. {
  584. if (ApplicationOverlapped.OverlappedTop is null || top is null)
  585. {
  586. top = Current;
  587. }
  588. if (ApplicationOverlapped.OverlappedTop != null
  589. && top!.IsOverlappedContainer
  590. && top?.Running == true
  591. && (Current?.Modal == false || Current is { Modal: true, Running: false }))
  592. {
  593. ApplicationOverlapped.OverlappedTop.RequestStop ();
  594. }
  595. else if (ApplicationOverlapped.OverlappedTop != null
  596. && top != Current
  597. && Current is { Running: true, Modal: true }
  598. && top!.Modal
  599. && top.Running)
  600. {
  601. var ev = new ToplevelClosingEventArgs (Current);
  602. Current.OnClosing (ev);
  603. if (ev.Cancel)
  604. {
  605. return;
  606. }
  607. ev = new (top);
  608. top.OnClosing (ev);
  609. if (ev.Cancel)
  610. {
  611. return;
  612. }
  613. Current.Running = false;
  614. OnNotifyStopRunState (Current);
  615. top.Running = false;
  616. OnNotifyStopRunState (top);
  617. }
  618. else if ((ApplicationOverlapped.OverlappedTop != null
  619. && top != ApplicationOverlapped.OverlappedTop
  620. && top != Current
  621. && Current is { Modal: false, Running: true }
  622. && !top!.Running)
  623. || (ApplicationOverlapped.OverlappedTop != null
  624. && top != ApplicationOverlapped.OverlappedTop
  625. && top != Current
  626. && Current is { Modal: false, Running: false }
  627. && !top!.Running
  628. && TopLevels.ToArray () [1].Running))
  629. {
  630. ApplicationOverlapped.MoveCurrent (top);
  631. }
  632. else if (ApplicationOverlapped.OverlappedTop != null
  633. && Current != top
  634. && Current?.Running == true
  635. && !top!.Running
  636. && Current?.Modal == true
  637. && top.Modal)
  638. {
  639. // The Current and the top are both modal so needed to set the Current.Running to false too.
  640. Current.Running = false;
  641. OnNotifyStopRunState (Current);
  642. }
  643. else if (ApplicationOverlapped.OverlappedTop != null
  644. && Current == top
  645. && ApplicationOverlapped.OverlappedTop?.Running == true
  646. && Current?.Running == true
  647. && top!.Running
  648. && Current?.Modal == true
  649. && top!.Modal)
  650. {
  651. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  652. // both are the same, so needed to set the Current.Running to false too.
  653. Current.Running = false;
  654. OnNotifyStopRunState (Current);
  655. }
  656. else
  657. {
  658. Toplevel currentTop;
  659. if (top == Current || (Current?.Modal == true && !top!.Modal))
  660. {
  661. currentTop = Current!;
  662. }
  663. else
  664. {
  665. currentTop = top!;
  666. }
  667. if (!currentTop.Running)
  668. {
  669. return;
  670. }
  671. var ev = new ToplevelClosingEventArgs (currentTop);
  672. currentTop.OnClosing (ev);
  673. if (ev.Cancel)
  674. {
  675. return;
  676. }
  677. currentTop.Running = false;
  678. OnNotifyStopRunState (currentTop);
  679. }
  680. }
  681. private static void OnNotifyStopRunState (Toplevel top)
  682. {
  683. if (EndAfterFirstIteration)
  684. {
  685. NotifyStopRunState?.Invoke (top, new (top));
  686. }
  687. }
  688. /// <summary>
  689. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  690. /// <see cref="Begin(Toplevel)"/> .
  691. /// </summary>
  692. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  693. public static void End (RunState runState)
  694. {
  695. ArgumentNullException.ThrowIfNull (runState);
  696. if (ApplicationOverlapped.OverlappedTop is { })
  697. {
  698. ApplicationOverlapped.OverlappedTop.OnChildUnloaded (runState.Toplevel);
  699. }
  700. else
  701. {
  702. runState.Toplevel.OnUnloaded ();
  703. }
  704. // End the RunState.Toplevel
  705. // First, take it off the Toplevel Stack
  706. if (TopLevels.Count > 0)
  707. {
  708. if (TopLevels.Peek () != runState.Toplevel)
  709. {
  710. // If the top of the stack is not the RunState.Toplevel then
  711. // this call to End is not balanced with the call to Begin that started the RunState
  712. throw new ArgumentException ("End must be balanced with calls to Begin");
  713. }
  714. TopLevels.Pop ();
  715. }
  716. // Notify that it is closing
  717. runState.Toplevel?.OnClosed (runState.Toplevel);
  718. // If there is a OverlappedTop that is not the RunState.Toplevel then RunState.Toplevel
  719. // is a child of MidTop, and we should notify the OverlappedTop that it is closing
  720. if (ApplicationOverlapped.OverlappedTop is { } && !runState.Toplevel!.Modal && runState.Toplevel != ApplicationOverlapped.OverlappedTop)
  721. {
  722. ApplicationOverlapped.OverlappedTop.OnChildClosed (runState.Toplevel);
  723. }
  724. // Set Current and Top to the next TopLevel on the stack
  725. if (TopLevels.Count == 0)
  726. {
  727. if (Current is { HasFocus: true })
  728. {
  729. Current.HasFocus = false;
  730. }
  731. Current = null;
  732. }
  733. else
  734. {
  735. if (TopLevels.Count > 1 && TopLevels.Peek () == ApplicationOverlapped.OverlappedTop && ApplicationOverlapped.OverlappedChildren?.Any (t => t.Visible) != null)
  736. {
  737. ApplicationOverlapped.OverlappedMoveNext ();
  738. }
  739. Current = TopLevels.Peek ();
  740. if (TopLevels.Count == 1 && Current == ApplicationOverlapped.OverlappedTop)
  741. {
  742. ApplicationOverlapped.OverlappedTop.OnAllChildClosed ();
  743. }
  744. else
  745. {
  746. ApplicationOverlapped.SetCurrentOverlappedAsTop ();
  747. // BUGBUG: We should not call OnEnter/OnLeave directly; they should only be called by SetHasFocus
  748. if (runState.Toplevel is { HasFocus: true })
  749. {
  750. runState.Toplevel.HasFocus = false;
  751. }
  752. if (Current is { HasFocus: false })
  753. {
  754. Current.SetFocus ();
  755. }
  756. }
  757. Refresh ();
  758. }
  759. // Don't dispose runState.Toplevel. It's up to caller dispose it
  760. // If it's not the same as the current in the RunIteration,
  761. // it will be fixed later in the next RunIteration.
  762. if (ApplicationOverlapped.OverlappedTop is { } && !TopLevels.Contains (ApplicationOverlapped.OverlappedTop))
  763. {
  764. _cachedRunStateToplevel = ApplicationOverlapped.OverlappedTop;
  765. }
  766. else
  767. {
  768. _cachedRunStateToplevel = runState.Toplevel;
  769. }
  770. runState.Toplevel = null;
  771. runState.Dispose ();
  772. }
  773. }