Application.Run.cs 31 KB

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