Application.Run.cs 31 KB

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