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