Application.Run.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. namespace Terminal.Gui.App;
  5. public static partial class Application // Run (Begin -> Run -> Layout/Draw -> End -> Stop)
  6. {
  7. /// <summary>Gets or sets the key to quit the application.</summary>
  8. [ConfigurationProperty (Scope = typeof (SettingsScope))]
  9. public static Key QuitKey
  10. {
  11. get => Keyboard.QuitKey;
  12. set => Keyboard.QuitKey = value;
  13. }
  14. /// <summary>Gets or sets the key to activate arranging views using the keyboard.</summary>
  15. [ConfigurationProperty (Scope = typeof (SettingsScope))]
  16. public static Key ArrangeKey
  17. {
  18. get => Keyboard.ArrangeKey;
  19. set => Keyboard.ArrangeKey = value;
  20. }
  21. // When `End ()` is called, it is possible `RunState.Toplevel` is a different object than `Top`.
  22. // This variable is set in `End` in this case so that `Begin` correctly sets `Top`.
  23. private static Toplevel? _cachedRunStateToplevel;
  24. /// <summary>
  25. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is
  26. /// created in <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  27. /// </summary>
  28. /// <remarks>
  29. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  30. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  31. /// when the application is done.
  32. /// </remarks>
  33. public static event EventHandler<RunStateEventArgs>? NotifyNewRunState;
  34. /// <summary>Notify that an existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).</summary>
  35. /// <remarks>
  36. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  37. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  38. /// when the application is done.
  39. /// </remarks>
  40. public static event EventHandler<ToplevelEventArgs>? NotifyStopRunState;
  41. /// <summary>Building block API: Prepares the provided <see cref="Toplevel"/> for execution.</summary>
  42. /// <returns>
  43. /// The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon
  44. /// completion.
  45. /// </returns>
  46. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  47. /// <remarks>
  48. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus, it adds this to the list
  49. /// of <see cref="Toplevel"/>s, lays out the SubViews, focuses the first element, and draws the <see cref="Toplevel"/>
  50. /// in the screen. This is usually followed by executing the <see cref="RunLoop"/> method, and then the
  51. /// <see cref="End(RunState)"/> method upon termination which will undo these changes.
  52. /// </remarks>
  53. public static RunState Begin (Toplevel toplevel)
  54. {
  55. ArgumentNullException.ThrowIfNull (toplevel);
  56. // Ensure the mouse is ungrabbed.
  57. if (Mouse.MouseGrabView is { })
  58. {
  59. Mouse.UngrabMouse ();
  60. }
  61. var rs = new RunState (toplevel);
  62. #if DEBUG_IDISPOSABLE
  63. if (View.EnableDebugIDisposableAsserts && 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. // BUGBUG: We should not depend on `Id` internally.
  87. // BUGBUG: It is super unclear what this code does anyway.
  88. if (string.IsNullOrEmpty (toplevel.Id))
  89. {
  90. var count = 1;
  91. var id = (TopLevels.Count + count).ToString ();
  92. while (TopLevels.Count > 0 && TopLevels.FirstOrDefault (x => x.Id == id) is { })
  93. {
  94. count++;
  95. id = (TopLevels.Count + count).ToString ();
  96. }
  97. toplevel.Id = (TopLevels.Count + count).ToString ();
  98. TopLevels.Push (toplevel);
  99. }
  100. else
  101. {
  102. Toplevel? dup = TopLevels.FirstOrDefault (x => x.Id == toplevel.Id);
  103. if (dup is null)
  104. {
  105. TopLevels.Push (toplevel);
  106. }
  107. }
  108. }
  109. if (Top is null)
  110. {
  111. Top = toplevel;
  112. }
  113. if ((Top?.Modal == false && toplevel.Modal)
  114. || (Top?.Modal == false && !toplevel.Modal)
  115. || (Top?.Modal == true && toplevel.Modal))
  116. {
  117. if (toplevel.Visible)
  118. {
  119. if (Top is { HasFocus: true })
  120. {
  121. Top.HasFocus = false;
  122. }
  123. // Force leave events for any entered views in the old Top
  124. if (GetLastMousePosition () is { })
  125. {
  126. RaiseMouseEnterLeaveEvents (GetLastMousePosition ()!.Value, new ());
  127. }
  128. Top?.OnDeactivate (toplevel);
  129. Toplevel previousTop = Top!;
  130. Top = toplevel;
  131. Top.OnActivate (previousTop);
  132. }
  133. }
  134. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  135. if (!toplevel.IsInitialized)
  136. {
  137. toplevel.BeginInit ();
  138. toplevel.EndInit (); // Calls Layout
  139. }
  140. // Try to set initial focus to any TabStop
  141. if (!toplevel.HasFocus)
  142. {
  143. toplevel.SetFocus ();
  144. }
  145. toplevel.OnLoaded ();
  146. ApplicationImpl.Instance.LayoutAndDraw (true);
  147. if (PositionCursor ())
  148. {
  149. Driver?.UpdateCursor ();
  150. }
  151. NotifyNewRunState?.Invoke (toplevel, new (rs));
  152. return rs;
  153. }
  154. /// <summary>
  155. /// Calls <see cref="View.PositionCursor"/> on the most focused view.
  156. /// </summary>
  157. /// <remarks>
  158. /// Does nothing if there is no most focused view.
  159. /// <para>
  160. /// If the most focused view is not visible within it's superview, the cursor will be hidden.
  161. /// </para>
  162. /// </remarks>
  163. /// <returns><see langword="true"/> if a view positioned the cursor and the position is visible.</returns>
  164. internal static bool PositionCursor ()
  165. {
  166. // Find the most focused view and position the cursor there.
  167. View? mostFocused = Navigation?.GetFocused ();
  168. // If the view is not visible or enabled, don't position the cursor
  169. if (mostFocused is null || !mostFocused.Visible || !mostFocused.Enabled)
  170. {
  171. var current = CursorVisibility.Invisible;
  172. Driver?.GetCursorVisibility (out current);
  173. if (current != CursorVisibility.Invisible)
  174. {
  175. Driver?.SetCursorVisibility (CursorVisibility.Invisible);
  176. }
  177. return false;
  178. }
  179. // If the view is not visible within it's superview, don't position the cursor
  180. Rectangle mostFocusedViewport = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = Point.Empty });
  181. Rectangle superViewViewport =
  182. mostFocused.SuperView?.ViewportToScreen (mostFocused.SuperView.Viewport with { Location = Point.Empty }) ?? Driver!.Screen;
  183. if (!superViewViewport.IntersectsWith (mostFocusedViewport))
  184. {
  185. return false;
  186. }
  187. Point? cursor = mostFocused.PositionCursor ();
  188. Driver!.GetCursorVisibility (out CursorVisibility currentCursorVisibility);
  189. if (cursor is { })
  190. {
  191. // Convert cursor to screen coords
  192. cursor = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = cursor.Value }).Location;
  193. // If the cursor is not in a visible location in the SuperView, hide it
  194. if (!superViewViewport.Contains (cursor.Value))
  195. {
  196. if (currentCursorVisibility != CursorVisibility.Invisible)
  197. {
  198. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  199. }
  200. return false;
  201. }
  202. // Show it
  203. if (currentCursorVisibility == CursorVisibility.Invisible)
  204. {
  205. Driver.SetCursorVisibility (mostFocused.CursorVisibility);
  206. }
  207. return true;
  208. }
  209. if (currentCursorVisibility != CursorVisibility.Invisible)
  210. {
  211. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  212. }
  213. return false;
  214. }
  215. /// <summary>
  216. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  217. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  218. /// </summary>
  219. /// <remarks>
  220. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  221. /// <para>
  222. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  223. /// ensure resources are cleaned up and terminal settings restored.
  224. /// </para>
  225. /// <para>
  226. /// The caller is responsible for disposing the object returned by this method.
  227. /// </para>
  228. /// </remarks>
  229. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  230. [RequiresUnreferencedCode ("AOT")]
  231. [RequiresDynamicCode ("AOT")]
  232. public static Toplevel Run (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  233. {
  234. return ApplicationImpl.Instance.Run (errorHandler, driver);
  235. }
  236. /// <summary>
  237. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  238. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  239. /// </summary>
  240. /// <remarks>
  241. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  242. /// <para>
  243. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  244. /// ensure resources are cleaned up and terminal settings restored.
  245. /// </para>
  246. /// <para>
  247. /// The caller is responsible for disposing the object returned by this method.
  248. /// </para>
  249. /// </remarks>
  250. /// <param name="errorHandler"></param>
  251. /// <param name="driver">
  252. /// The <see cref="IConsoleDriver"/> to use. If not specified the default driver for the platform will
  253. /// be used. Must be <see langword="null"/> if <see cref="Init"/> has already been called.
  254. /// </param>
  255. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  256. [RequiresUnreferencedCode ("AOT")]
  257. [RequiresDynamicCode ("AOT")]
  258. public static T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  259. where T : Toplevel, new()
  260. {
  261. return ApplicationImpl.Instance.Run<T> (errorHandler, driver);
  262. }
  263. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  264. /// <remarks>
  265. /// <para>
  266. /// This method is used to start processing events for the main application, but it is also used to run other
  267. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  268. /// </para>
  269. /// <para>
  270. /// To make a <see cref="Run(Toplevel,System.Func{System.Exception,bool})"/> stop execution, call
  271. /// <see cref="Application.RequestStop"/>.
  272. /// </para>
  273. /// <para>
  274. /// Calling <see cref="Run(Toplevel,System.Func{System.Exception,bool})"/> is equivalent to calling
  275. /// <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState)"/>, and then calling
  276. /// <see cref="End(RunState)"/>.
  277. /// </para>
  278. /// <para>
  279. /// Alternatively, to have a program control the main loop and process events manually, call
  280. /// <see cref="Begin(Toplevel)"/> to set things up manually and then repeatedly call
  281. /// <see cref="RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  282. /// <see cref="RunLoop(RunState)"/> method will only process any pending events, timers handlers and then
  283. /// return control immediately.
  284. /// </para>
  285. /// <para>
  286. /// When using <see cref="Run{T}"/> or
  287. /// <see cref="Run(System.Func{System.Exception,bool},IConsoleDriver)"/>
  288. /// <see cref="Init"/> will be called automatically.
  289. /// </para>
  290. /// <para>
  291. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  292. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  293. /// returns <see langword="true"/> the <see cref="RunLoop(RunState)"/> will resume; otherwise this method will
  294. /// exit.
  295. /// </para>
  296. /// </remarks>
  297. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  298. /// <param name="errorHandler">
  299. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  300. /// rethrows when null).
  301. /// </param>
  302. public static void Run (Toplevel view, Func<Exception, bool>? errorHandler = null) { ApplicationImpl.Instance.Run (view, errorHandler); }
  303. /// <summary>Adds a timeout to the application.</summary>
  304. /// <remarks>
  305. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  306. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  307. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  308. /// </remarks>
  309. public static object? AddTimeout (TimeSpan time, Func<bool> callback) { return ApplicationImpl.Instance.AddTimeout (time, callback); }
  310. /// <summary>Removes a previously scheduled timeout</summary>
  311. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  312. /// Returns
  313. /// <see langword="true"/>
  314. /// if the timeout is successfully removed; otherwise,
  315. /// <see langword="false"/>
  316. /// .
  317. /// This method also returns
  318. /// <see langword="false"/>
  319. /// if the timeout is not found.
  320. public static bool RemoveTimeout (object token) { return ApplicationImpl.Instance.RemoveTimeout (token); }
  321. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  322. /// <param name="action">the action to be invoked on the main processing thread.</param>
  323. public static void Invoke (Action action) { ApplicationImpl.Instance.Invoke (action); }
  324. /// <summary>
  325. /// Causes any Toplevels that need layout to be laid out. Then draws any Toplevels that need display. Only Views that
  326. /// need to be laid out (see <see cref="View.NeedsLayout"/>) will be laid out.
  327. /// Only Views that need to be drawn (see <see cref="View.NeedsDraw"/>) will be drawn.
  328. /// </summary>
  329. /// <param name="forceRedraw">
  330. /// If <see langword="true"/> the entire View hierarchy will be redrawn. The default is <see langword="false"/> and
  331. /// should only be overriden for testing.
  332. /// </param>
  333. public static void LayoutAndDraw (bool forceRedraw = false)
  334. {
  335. ApplicationImpl.Instance.LayoutAndDraw (forceRedraw);
  336. }
  337. /// <summary>This event is raised on each iteration of the main loop.</summary>
  338. /// <remarks>See also <see cref="Timeout"/></remarks>
  339. public static event EventHandler<IterationEventArgs>? Iteration;
  340. /// <summary>
  341. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  342. /// cause the application to continue running until Application.RequestStop () is called.
  343. /// </summary>
  344. public static bool EndAfterFirstIteration { get; set; }
  345. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  346. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  347. public static void RunLoop (RunState state)
  348. {
  349. ArgumentNullException.ThrowIfNull (state);
  350. ObjectDisposedException.ThrowIf (state.Toplevel is null, "state");
  351. var firstIteration = true;
  352. for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
  353. {
  354. if (EndAfterFirstIteration && !firstIteration)
  355. {
  356. return;
  357. }
  358. firstIteration = RunIteration (ref state, firstIteration);
  359. }
  360. // Run one last iteration to consume any outstanding input events from Driver
  361. // This is important for remaining OnKeyUp events.
  362. RunIteration (ref state, firstIteration);
  363. }
  364. /// <summary>Run one application iteration.</summary>
  365. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  366. /// <param name="firstIteration">
  367. /// Set to <see langword="true"/> if this is the first run loop iteration.
  368. /// </param>
  369. /// <returns><see langword="false"/> if at least one iteration happened.</returns>
  370. public static bool RunIteration (ref RunState state, bool firstIteration = false)
  371. {
  372. ApplicationImpl appImpl = (ApplicationImpl)ApplicationImpl.Instance;
  373. appImpl.Coordinator?.RunIteration ();
  374. return false;
  375. }
  376. /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
  377. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  378. /// <remarks>
  379. /// <para>This will cause <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to return.</para>
  380. /// <para>
  381. /// Calling <see cref="RequestStop(Toplevel)"/> is equivalent to setting the
  382. /// <see cref="Toplevel.Running"/>
  383. /// property on the currently running <see cref="Toplevel"/> to false.
  384. /// </para>
  385. /// </remarks>
  386. public static void RequestStop (Toplevel? top = null) { ApplicationImpl.Instance.RequestStop (top); }
  387. /// <summary>
  388. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  389. /// <see cref="Begin(Toplevel)"/> .
  390. /// </summary>
  391. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  392. public static void End (RunState runState)
  393. {
  394. ArgumentNullException.ThrowIfNull (runState);
  395. if (Popover?.GetActivePopover () as View is { Visible: true } visiblePopover)
  396. {
  397. ApplicationPopover.HideWithQuitCommand (visiblePopover);
  398. }
  399. runState.Toplevel.OnUnloaded ();
  400. // End the RunState.Toplevel
  401. // First, take it off the Toplevel Stack
  402. if (TopLevels.TryPop (out Toplevel? topOfStack))
  403. {
  404. if (topOfStack != runState.Toplevel)
  405. {
  406. // If the top of the stack is not the RunState.Toplevel then
  407. // this call to End is not balanced with the call to Begin that started the RunState
  408. throw new ArgumentException ("End must be balanced with calls to Begin");
  409. }
  410. }
  411. // Notify that it is closing
  412. runState.Toplevel?.OnClosed (runState.Toplevel);
  413. if (TopLevels.TryPeek (out Toplevel? newTop))
  414. {
  415. Top = newTop;
  416. Top?.SetNeedsDraw ();
  417. }
  418. if (runState.Toplevel is { HasFocus: true })
  419. {
  420. runState.Toplevel.HasFocus = false;
  421. }
  422. if (Top is { HasFocus: false })
  423. {
  424. Top.SetFocus ();
  425. }
  426. _cachedRunStateToplevel = runState.Toplevel;
  427. runState.Toplevel = null;
  428. runState.Dispose ();
  429. LayoutAndDraw (true);
  430. }
  431. internal static void RaiseIteration ()
  432. {
  433. Iteration?.Invoke (null, new ());
  434. }
  435. }