Application.Run.cs 21 KB

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