2
0

Application.Run.cs 21 KB

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