IApplication.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. using System.Collections.Concurrent;
  2. using System.Diagnostics.CodeAnalysis;
  3. namespace Terminal.Gui.App;
  4. /// <summary>
  5. /// Interface for instances that provide backing functionality to static
  6. /// gateway class <see cref="Application"/>.
  7. /// </summary>
  8. public interface IApplication
  9. {
  10. #region Keyboard
  11. /// <summary>
  12. /// Handles keyboard input and key bindings at the Application level.
  13. /// </summary>
  14. /// <remarks>
  15. /// <para>
  16. /// Provides access to keyboard state, key bindings, and keyboard event handling. Set during <see cref="Init"/>.
  17. /// </para>
  18. /// </remarks>
  19. IKeyboard Keyboard { get; set; }
  20. #endregion Keyboard
  21. #region Mouse
  22. /// <summary>
  23. /// Handles mouse event state and processing.
  24. /// </summary>
  25. /// <remarks>
  26. /// <para>
  27. /// Provides access to mouse state, mouse grabbing, and mouse event handling. Set during <see cref="Init"/>.
  28. /// </para>
  29. /// </remarks>
  30. IMouse Mouse { get; set; }
  31. #endregion Mouse
  32. #region Initialization and Shutdown
  33. /// <summary>Initializes a new instance of <see cref="Terminal.Gui"/> Application.</summary>
  34. /// <param name="driverName">
  35. /// The short name (e.g. "dotnet", "windows", "unix", or "fake") of the
  36. /// <see cref="IDriver"/> to use. If not specified the default driver for the platform will be used.
  37. /// </param>
  38. /// <returns>This instance for fluent API chaining.</returns>
  39. /// <remarks>
  40. /// <para>Call this method once per instance (or after <see cref="Shutdown"/> has been called).</para>
  41. /// <para>
  42. /// This function loads the right <see cref="IDriver"/> for the platform, creates a main loop coordinator,
  43. /// initializes keyboard and mouse handlers, and subscribes to driver events.
  44. /// </para>
  45. /// <para>
  46. /// <see cref="Shutdown"/> must be called when the application is closing (typically after
  47. /// <see cref="Run{T}(Func{Exception, bool})"/> has returned) to ensure resources are cleaned up and terminal settings restored.
  48. /// </para>
  49. /// <para>
  50. /// The <see cref="Run{T}(Func{Exception, bool})"/> function combines <see cref="Init(string)"/> and
  51. /// <see cref="Run(Toplevel, Func{Exception, bool})"/> into a single call. An application can use
  52. /// <see cref="Run{T}(Func{Exception, bool})"/> without explicitly calling <see cref="Init(string)"/>.
  53. /// </para>
  54. /// <para>
  55. /// Supports fluent API: <c>Application.Create().Init().Run&lt;MyView&gt;().Shutdown()</c>
  56. /// </para>
  57. /// </remarks>
  58. [RequiresUnreferencedCode ("AOT")]
  59. [RequiresDynamicCode ("AOT")]
  60. public IApplication Init (string? driverName = null);
  61. /// <summary>
  62. /// This event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  63. /// </summary>
  64. /// <remarks>
  65. /// Intended to support unit tests that need to know when the application has been initialized.
  66. /// </remarks>
  67. public event EventHandler<EventArgs<bool>>? InitializedChanged;
  68. /// <summary>Gets or sets whether the application has been initialized.</summary>
  69. bool Initialized { get; set; }
  70. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  71. /// <returns>
  72. /// The result from the last <see cref="Run{T}(Func{Exception, bool})"/> call, or <see langword="null"/> if none.
  73. /// Automatically disposes any runnable created by <see cref="Run{T}(Func{Exception, bool})"/>.
  74. /// </returns>
  75. /// <remarks>
  76. /// <para>
  77. /// Shutdown must be called for every call to <see cref="Init"/> or
  78. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  79. /// up (Disposed) and terminal settings are restored.
  80. /// </para>
  81. /// <para>
  82. /// When used in a fluent chain with <see cref="Run{T}(Func{Exception, bool})"/>, this method automatically
  83. /// disposes the runnable instance and extracts its result for return.
  84. /// </para>
  85. /// <para>
  86. /// Supports fluent API: <c>var result = Application.Create().Init().Run&lt;MyView&gt;().Shutdown() as MyResultType</c>
  87. /// </para>
  88. /// </remarks>
  89. public object? Shutdown ();
  90. /// <summary>
  91. /// Resets the state of this instance.
  92. /// </summary>
  93. /// <param name="ignoreDisposed">If true, ignores disposed state checks during reset.</param>
  94. /// <remarks>
  95. /// <para>
  96. /// Encapsulates all setting of initial state for Application; having this in a function like this ensures we
  97. /// don't make mistakes in guaranteeing that the state of this singleton is deterministic when <see cref="Init"/>
  98. /// starts running and after <see cref="Shutdown"/> returns.
  99. /// </para>
  100. /// <para>
  101. /// IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  102. /// </para>
  103. /// </remarks>
  104. public void ResetState (bool ignoreDisposed = false);
  105. #endregion Initialization and Shutdown
  106. #region Begin->Run->Iteration->Stop->End
  107. /// <summary>
  108. /// Building block API: Creates a <see cref="SessionToken"/> and prepares the provided <see cref="Toplevel"/> for
  109. /// execution. Not usually called directly by applications. Use <see cref="Run(Toplevel, Func{Exception, bool})"/>
  110. /// instead.
  111. /// </summary>
  112. /// <returns>
  113. /// The <see cref="SessionToken"/> that needs to be passed to the <see cref="End(SessionToken)"/> method upon
  114. /// completion.
  115. /// </returns>
  116. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  117. /// <remarks>
  118. /// <para>
  119. /// This method prepares the provided <see cref="Toplevel"/> for running. It adds this to the
  120. /// list of <see cref="Toplevel"/>s, lays out the SubViews, focuses the first element, and draws the
  121. /// <see cref="Toplevel"/> on the screen. This is usually followed by starting the main loop, and then the
  122. /// <see cref="End(SessionToken)"/> method upon termination which will undo these changes.
  123. /// </para>
  124. /// <para>
  125. /// Raises the <see cref="SessionBegun"/> event before returning.
  126. /// </para>
  127. /// </remarks>
  128. public SessionToken Begin (Toplevel toplevel);
  129. /// <summary>
  130. /// Runs a new Session creating a <see cref="Toplevel"/> and calling <see cref="Begin(Toplevel)"/>. When the session is
  131. /// stopped, <see cref="End(SessionToken)"/> will be called.
  132. /// </summary>
  133. /// <param name="errorHandler">Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  134. /// <param name="driverName">
  135. /// The driver name. If not specified the default driver for the platform will be used. Must be
  136. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  137. /// </param>
  138. /// <returns>The created <see cref="Toplevel"/>. The caller is responsible for disposing this object.</returns>
  139. /// <remarks>
  140. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  141. /// <para>
  142. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run has returned) to
  143. /// ensure resources are cleaned up and terminal settings restored.
  144. /// </para>
  145. /// <para>
  146. /// The caller is responsible for disposing the object returned by this method.
  147. /// </para>
  148. /// </remarks>
  149. [RequiresUnreferencedCode ("AOT")]
  150. [RequiresDynamicCode ("AOT")]
  151. public Toplevel Run (Func<Exception, bool>? errorHandler = null, string? driverName = null);
  152. /// <summary>
  153. /// Runs a new Session creating a <see cref="Toplevel"/>-derived object of type <typeparamref name="TView"/>
  154. /// and calling <see cref="Run(Toplevel, Func{Exception, bool})"/>. When the session is stopped,
  155. /// <see cref="End(SessionToken)"/> will be called.
  156. /// </summary>
  157. /// <typeparam name="TView">The type of <see cref="Toplevel"/> to create and run.</typeparam>
  158. /// <param name="errorHandler">Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  159. /// <param name="driverName">
  160. /// The driver name. If not specified the default driver for the platform will be used. Must be
  161. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  162. /// </param>
  163. /// <returns>The created <typeparamref name="TView"/> object. The caller is responsible for disposing this object.</returns>
  164. /// <remarks>
  165. /// <para>
  166. /// This method is used to start processing events for the main application, but it is also used to run other
  167. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  168. /// </para>
  169. /// <para>
  170. /// To make <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call
  171. /// <see cref="RequestStop()"/> or <see cref="RequestStop(Toplevel)"/>.
  172. /// </para>
  173. /// <para>
  174. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling
  175. /// <see cref="Begin(Toplevel)"/>, followed by starting the main loop, and then calling
  176. /// <see cref="End(SessionToken)"/>.
  177. /// </para>
  178. /// <para>
  179. /// When using <see cref="Run{T}(Func{Exception, bool})"/> or <see cref="Run(Func{Exception, bool}, string)"/>,
  180. /// <see cref="Init"/> will be called automatically.
  181. /// </para>
  182. /// <para>
  183. /// In RELEASE builds: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  184. /// rethrown. Otherwise, <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  185. /// returns <see langword="true"/> the main loop will resume; otherwise this method will exit.
  186. /// </para>
  187. /// <para>
  188. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run has returned) to
  189. /// ensure resources are cleaned up and terminal settings restored.
  190. /// </para>
  191. /// <para>
  192. /// In RELEASE builds: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  193. /// rethrown. Otherwise, <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  194. /// returns <see langword="true"/> the main loop will resume; otherwise this method will exit.
  195. /// </para>
  196. /// <para>
  197. /// The caller is responsible for disposing the object returned by this method.
  198. /// </para>
  199. /// </remarks>
  200. [RequiresUnreferencedCode ("AOT")]
  201. [RequiresDynamicCode ("AOT")]
  202. public TView Run<TView> (Func<Exception, bool>? errorHandler = null, string? driverName = null)
  203. where TView : Toplevel, new ();
  204. /// <summary>
  205. /// Runs a new Session using the provided <see cref="Toplevel"/> view and calling
  206. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  207. /// When the session is stopped, <see cref="End(SessionToken)"/> will be called..
  208. /// </summary>
  209. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  210. /// <param name="errorHandler">Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  211. /// <remarks>
  212. /// <para>
  213. /// This method is used to start processing events for the main application, but it is also used to run other
  214. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  215. /// </para>
  216. /// <para>
  217. /// To make <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call
  218. /// <see cref="RequestStop()"/> or <see cref="RequestStop(Toplevel)"/>.
  219. /// </para>
  220. /// <para>
  221. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling
  222. /// <see cref="Begin(Toplevel)"/>, followed by starting the main loop, and then calling
  223. /// <see cref="End(SessionToken)"/>.
  224. /// </para>
  225. /// <para>
  226. /// When using <see cref="Run{T}(Func{Exception, bool})"/> or <see cref="Run(Func{Exception, bool}, string)"/>,
  227. /// <see cref="Init"/> will be called automatically.
  228. /// </para>
  229. /// <para>
  230. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run has returned) to
  231. /// ensure resources are cleaned up and terminal settings restored.
  232. /// </para>
  233. /// <para>
  234. /// In RELEASE builds: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  235. /// rethrown. Otherwise, <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  236. /// returns <see langword="true"/> the main loop will resume; otherwise this method will exit.
  237. /// </para>
  238. /// <para>
  239. /// The caller is responsible for disposing the object returned by this method.
  240. /// </para>
  241. /// </remarks>
  242. public void Run (Toplevel view, Func<Exception, bool>? errorHandler = null);
  243. /// <summary>
  244. /// Raises the <see cref="Iteration"/> event.
  245. /// </summary>
  246. /// <remarks>
  247. /// This is called once per main loop iteration, before processing input, timeouts, or rendering.
  248. /// </remarks>
  249. public void RaiseIteration ();
  250. /// <summary>This event is raised on each iteration of the main loop.</summary>
  251. /// <remarks>
  252. /// <para>
  253. /// This event is raised before input processing, timeout callbacks, and rendering occur each iteration.
  254. /// </para>
  255. /// <para>See also <see cref="AddTimeout"/> and <see cref="TimedEvents"/>.</para>
  256. /// </remarks>
  257. public event EventHandler<IterationEventArgs>? Iteration;
  258. /// <summary>Runs <paramref name="action"/> on the main UI loop thread.</summary>
  259. /// <param name="action">The action to be invoked on the main processing thread.</param>
  260. /// <remarks>
  261. /// <para>
  262. /// If called from the main thread, the action is executed immediately. Otherwise, it is queued via
  263. /// <see cref="AddTimeout"/> with <see cref="TimeSpan.Zero"/> and will be executed on the next main loop
  264. /// iteration.
  265. /// </para>
  266. /// </remarks>
  267. void Invoke (Action<IApplication>? action);
  268. /// <summary>Runs <paramref name="action"/> on the main UI loop thread.</summary>
  269. /// <param name="action">The action to be invoked on the main processing thread.</param>
  270. /// <remarks>
  271. /// <para>
  272. /// If called from the main thread, the action is executed immediately. Otherwise, it is queued via
  273. /// <see cref="AddTimeout"/> with <see cref="TimeSpan.Zero"/> and will be executed on the next main loop
  274. /// iteration.
  275. /// </para>
  276. /// </remarks>
  277. void Invoke (Action action);
  278. /// <summary>
  279. /// Building block API: Ends a Session and completes the execution of a <see cref="Toplevel"/> that was started with
  280. /// <see cref="Begin(Toplevel)"/>. Not usually called directly by applications.
  281. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>
  282. /// will automatically call this method when the session is stopped.
  283. /// </summary>
  284. /// <param name="sessionToken">The <see cref="SessionToken"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  285. /// <remarks>
  286. /// <para>
  287. /// This method removes the <see cref="Toplevel"/> from the stack, raises the <see cref="SessionEnded"/>
  288. /// event, and disposes the <paramref name="sessionToken"/>.
  289. /// </para>
  290. /// </remarks>
  291. public void End (SessionToken sessionToken);
  292. /// <summary>Requests that the currently running Session stop. The Session will stop after the current iteration completes.</summary>
  293. /// <remarks>
  294. /// <para>This will cause <see cref="Run(Toplevel, Func{Exception, bool})"/> to return.</para>
  295. /// <para>
  296. /// This is equivalent to calling <see cref="RequestStop(Toplevel)"/> with <see cref="TopRunnable"/> as the
  297. /// parameter.
  298. /// </para>
  299. /// </remarks>
  300. void RequestStop ();
  301. /// <summary>Requests that the currently running Session stop. The Session will stop after the current iteration completes.</summary>
  302. /// <param name="top">
  303. /// The <see cref="Toplevel"/> to stop. If <see langword="null"/>, stops the currently running
  304. /// <see cref="TopRunnable"/>.
  305. /// </param>
  306. /// <remarks>
  307. /// <para>This will cause <see cref="Run(Toplevel, Func{Exception, bool})"/> to return.</para>
  308. /// <para>
  309. /// Calling <see cref="RequestStop(Toplevel)"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  310. /// property on the specified <see cref="Toplevel"/> to <see langword="false"/>.
  311. /// </para>
  312. /// </remarks>
  313. void RequestStop (Toplevel? top);
  314. /// <summary>
  315. /// Set to <see langword="true"/> to cause the session to stop running after first iteration.
  316. /// </summary>
  317. /// <remarks>
  318. /// <para>
  319. /// Used primarily for unit testing. When <see langword="true"/>, <see cref="End(RunnableSessionToken)"/> will be called
  320. /// automatically after the first main loop iteration.
  321. /// </para>
  322. /// </remarks>
  323. bool StopAfterFirstIteration { get; set; }
  324. // TODO: This API is not used anywhere; it can be deleted
  325. /// <summary>
  326. /// Raised when <see cref="Begin(Toplevel)"/> has been called and has created a new <see cref="SessionToken"/>.
  327. /// </summary>
  328. /// <remarks>
  329. /// If <see cref="StopAfterFirstIteration"/> is <see langword="true"/>, callers to <see cref="Begin(Toplevel)"/>
  330. /// must also subscribe to <see cref="SessionEnded"/> and manually dispose of the <see cref="SessionToken"/> token
  331. /// when the application is done.
  332. /// </remarks>
  333. public event EventHandler<SessionTokenEventArgs>? SessionBegun;
  334. // TODO: This API is not used anywhere; it can be deleted
  335. /// <summary>
  336. /// Raised when <see cref="End(SessionToken)"/> was called and the session is stopping. The event args contain a
  337. /// reference to the <see cref="Toplevel"/>
  338. /// that was active during the session. This can be used to ensure the Toplevel is disposed of properly.
  339. /// </summary>
  340. /// <remarks>
  341. /// If <see cref="StopAfterFirstIteration"/> is <see langword="true"/>, callers to <see cref="Begin(Toplevel)"/>
  342. /// must also subscribe to <see cref="SessionEnded"/> and manually dispose of the <see cref="SessionToken"/> token
  343. /// when the application is done.
  344. /// </remarks>
  345. public event EventHandler<ToplevelEventArgs>? SessionEnded;
  346. #endregion Begin->Run->Iteration->Stop->End
  347. #region Toplevel Management
  348. /// <summary>Gets or sets the Toplevel that is on the top of the <see cref="SessionStack"/>.</summary>
  349. /// <remarks>
  350. /// <para>
  351. /// The top runnable in the session stack captures all mouse and keyboard input.
  352. /// This is set by <see cref="Begin(Toplevel)"/> and cleared by <see cref="End(SessionToken)"/>.
  353. /// </para>
  354. /// </remarks>
  355. Toplevel? TopRunnable { get; set; }
  356. /// <summary>Gets the stack of all active Toplevel sessions.</summary>
  357. /// <remarks>
  358. /// <para>
  359. /// Toplevels are added to this stack by <see cref="Begin(Toplevel)"/> and removed by
  360. /// <see cref="End(SessionToken)"/>.
  361. /// </para>
  362. /// </remarks>
  363. ConcurrentStack<Toplevel> SessionStack { get; }
  364. /// <summary>
  365. /// Caches the Toplevel associated with the current Session.
  366. /// </summary>
  367. /// <remarks>
  368. /// Used internally to optimize Toplevel state transitions.
  369. /// </remarks>
  370. Toplevel? CachedSessionTokenToplevel { get; set; }
  371. #endregion Toplevel Management
  372. #region IRunnable Management
  373. /// <summary>
  374. /// Gets the stack of all active runnable session tokens.
  375. /// Sessions execute serially - the top of stack is the currently modal session.
  376. /// </summary>
  377. /// <remarks>
  378. /// <para>
  379. /// Session tokens are pushed onto the stack when <see cref="Run(IRunnable, Func{Exception, bool})"/> is called and
  380. /// popped when
  381. /// <see cref="RequestStop(IRunnable)"/> completes. The stack grows during nested modal calls and
  382. /// shrinks as they complete.
  383. /// </para>
  384. /// <para>
  385. /// Only the top session (<see cref="TopRunnable"/>) has exclusive keyboard/mouse input (
  386. /// <see cref="IRunnable.IsModal"/> = true).
  387. /// All other sessions on the stack continue to be laid out, drawn, and receive iteration events (
  388. /// <see cref="IRunnable.IsRunning"/> = true),
  389. /// but they don't receive user input.
  390. /// </para>
  391. /// <example>
  392. /// Stack during nested modals:
  393. /// <code>
  394. /// RunnableSessionStack (top to bottom):
  395. /// - MessageBox (TopRunnable, IsModal=true, IsRunning=true, has input)
  396. /// - FileDialog (IsModal=false, IsRunning=true, continues to update/draw)
  397. /// - MainWindow (IsModal=false, IsRunning=true, continues to update/draw)
  398. /// </code>
  399. /// </example>
  400. /// </remarks>
  401. ConcurrentStack<RunnableSessionToken>? RunnableSessionStack { get; }
  402. /// <summary>
  403. /// Gets or sets the runnable that was created by <see cref="Run{T}(Func{Exception, bool})"/> for automatic disposal.
  404. /// </summary>
  405. /// <remarks>
  406. /// <para>
  407. /// When <see cref="Run{T}(Func{Exception, bool})"/> creates a runnable instance, it stores it here so
  408. /// <see cref="Shutdown"/> can automatically dispose it and extract its result.
  409. /// </para>
  410. /// <para>
  411. /// This property is <see langword="null"/> if <see cref="Run(IRunnable, Func{Exception, bool})"/> was used
  412. /// with an externally-created runnable.
  413. /// </para>
  414. /// </remarks>
  415. IRunnable? FrameworkOwnedRunnable { get; set; }
  416. /// <summary>
  417. /// Building block API: Creates a <see cref="RunnableSessionToken"/> and prepares the provided <see cref="IRunnable"/>
  418. /// for
  419. /// execution. Not usually called directly by applications. Use <see cref="Run(IRunnable, Func{Exception, bool})"/>
  420. /// instead.
  421. /// </summary>
  422. /// <param name="runnable">The <see cref="IRunnable"/> to prepare execution for.</param>
  423. /// <returns>
  424. /// The <see cref="RunnableSessionToken"/> that needs to be passed to the <see cref="End(RunnableSessionToken)"/>
  425. /// method upon
  426. /// completion.
  427. /// </returns>
  428. /// <remarks>
  429. /// <para>
  430. /// This method prepares the provided <see cref="IRunnable"/> for running. It adds this to the
  431. /// <see cref="RunnableSessionStack"/>, lays out the SubViews, focuses the first element, and draws the
  432. /// runnable on the screen. This is usually followed by starting the main loop, and then the
  433. /// <see cref="End(RunnableSessionToken)"/> method upon termination which will undo these changes.
  434. /// </para>
  435. /// <para>
  436. /// Raises the <see cref="IRunnable.IsRunningChanging"/>, <see cref="IRunnable.IsRunningChanged"/>,
  437. /// <see cref="IRunnable.IsModalChanging"/>, and <see cref="IRunnable.IsModalChanged"/> events.
  438. /// </para>
  439. /// </remarks>
  440. RunnableSessionToken Begin (IRunnable runnable);
  441. /// <summary>
  442. /// Runs a new Session with the provided runnable view.
  443. /// </summary>
  444. /// <param name="runnable">The runnable to execute.</param>
  445. /// <param name="errorHandler">Optional handler for unhandled exceptions (resumes when returns true, rethrows when null).</param>
  446. /// <remarks>
  447. /// <para>
  448. /// This method is used to start processing events for the main application, but it is also used to run other
  449. /// modal views such as dialogs.
  450. /// </para>
  451. /// <para>
  452. /// To make <see cref="Run(IRunnable, Func{Exception, bool})"/> stop execution, call
  453. /// <see cref="RequestStop()"/> or <see cref="RequestStop(IRunnable)"/>.
  454. /// </para>
  455. /// <para>
  456. /// Calling <see cref="Run(IRunnable, Func{Exception, bool})"/> is equivalent to calling
  457. /// <see cref="Begin(IRunnable)"/>, followed by starting the main loop, and then calling
  458. /// <see cref="End(RunnableSessionToken)"/>.
  459. /// </para>
  460. /// <para>
  461. /// In RELEASE builds: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  462. /// rethrown. Otherwise, <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  463. /// returns <see langword="true"/> the main loop will resume; otherwise this method will exit.
  464. /// </para>
  465. /// </remarks>
  466. void Run (IRunnable runnable, Func<Exception, bool>? errorHandler = null);
  467. /// <summary>
  468. /// Creates and runs a new session with a <typeparamref name="TRunnable"/> of the specified type.
  469. /// </summary>
  470. /// <typeparam name="TRunnable">The type of runnable to create and run. Must have a parameterless constructor.</typeparam>
  471. /// <param name="errorHandler">Optional handler for unhandled exceptions (resumes when returns true, rethrows when null).</param>
  472. /// <returns>This instance for fluent API chaining. The created runnable is stored internally for disposal.</returns>
  473. /// <remarks>
  474. /// <para>
  475. /// This is a convenience method that creates an instance of <typeparamref name="TRunnable"/> and runs it.
  476. /// The framework owns the created instance and will automatically dispose it when <see cref="Shutdown"/> is called.
  477. /// </para>
  478. /// <para>
  479. /// To access the result, use <see cref="Shutdown"/> which returns the result from <see cref="IRunnable{TResult}.Result"/>.
  480. /// </para>
  481. /// <para>
  482. /// Supports fluent API: <c>var result = Application.Create().Init().Run&lt;MyView&gt;().Shutdown() as MyResultType</c>
  483. /// </para>
  484. /// </remarks>
  485. IApplication Run<TRunnable> (Func<Exception, bool>? errorHandler = null) where TRunnable : IRunnable, new ();
  486. /// <summary>
  487. /// Requests that the specified runnable session stop.
  488. /// </summary>
  489. /// <param name="runnable">The runnable to stop. If <see langword="null"/>, stops the current <see cref="TopRunnable"/>.</param>
  490. /// <remarks>
  491. /// <para>
  492. /// This will cause <see cref="Run(IRunnable, Func{Exception, bool})"/> to return.
  493. /// </para>
  494. /// <para>
  495. /// Raises <see cref="IRunnable.IsRunningChanging"/>, <see cref="IRunnable.IsRunningChanged"/>,
  496. /// <see cref="IRunnable.IsModalChanging"/>, and <see cref="IRunnable.IsModalChanged"/> events.
  497. /// </para>
  498. /// </remarks>
  499. void RequestStop (IRunnable? runnable);
  500. /// <summary>
  501. /// Building block API: Ends the session associated with the token and completes the execution of an
  502. /// <see cref="IRunnable"/>.
  503. /// Not usually called directly by applications. <see cref="Run(IRunnable, Func{Exception, bool})"/>
  504. /// will automatically call this method when the session is stopped.
  505. /// </summary>
  506. /// <param name="sessionToken">
  507. /// The <see cref="RunnableSessionToken"/> returned by the <see cref="Begin(IRunnable)"/>
  508. /// method.
  509. /// </param>
  510. /// <remarks>
  511. /// <para>
  512. /// This method removes the <see cref="IRunnable"/> from the <see cref="RunnableSessionStack"/>,
  513. /// raises the lifecycle events, and disposes the <paramref name="sessionToken"/>.
  514. /// </para>
  515. /// <para>
  516. /// Raises <see cref="IRunnable.IsRunningChanging"/>, <see cref="IRunnable.IsRunningChanged"/>,
  517. /// <see cref="IRunnable.IsModalChanging"/>, and <see cref="IRunnable.IsModalChanged"/> events.
  518. /// </para>
  519. /// </remarks>
  520. void End (RunnableSessionToken sessionToken);
  521. #endregion IRunnable Management
  522. #region Screen and Driver
  523. /// <summary>Gets or sets the console driver being used.</summary>
  524. /// <remarks>
  525. /// <para>
  526. /// Set by <see cref="Init"/> based on the driver parameter or platform default.
  527. /// </para>
  528. /// </remarks>
  529. IDriver? Driver { get; set; }
  530. /// <summary>
  531. /// Gets or sets whether <see cref="Driver"/> will be forced to output only the 16 colors defined in
  532. /// <see cref="ColorName16"/>. The default is <see langword="false"/>, meaning 24-bit (TrueColor) colors will be
  533. /// output as long as the selected <see cref="IDriver"/> supports TrueColor.
  534. /// </summary>
  535. bool Force16Colors { get; set; }
  536. /// <summary>
  537. /// Forces the use of the specified driver (one of "fake", "dotnet", "windows", or "unix"). If not
  538. /// specified, the driver is selected based on the platform.
  539. /// </summary>
  540. string ForceDriver { get; set; }
  541. /// <summary>
  542. /// Gets or sets the size of the screen. By default, this is the size of the screen as reported by the
  543. /// <see cref="IDriver"/>.
  544. /// </summary>
  545. /// <remarks>
  546. /// <para>
  547. /// If the <see cref="IDriver"/> has not been initialized, this will return a default size of 2048x2048; useful
  548. /// for unit tests.
  549. /// </para>
  550. /// </remarks>
  551. Rectangle Screen { get; set; }
  552. /// <summary>Raised when the terminal's size changed. The new size of the terminal is provided.</summary>
  553. /// <remarks>
  554. /// <para>
  555. /// This event is raised when the driver detects a screen size change. The event provides the new screen
  556. /// rectangle.
  557. /// </para>
  558. /// </remarks>
  559. public event EventHandler<EventArgs<Rectangle>>? ScreenChanged;
  560. /// <summary>
  561. /// Gets or sets whether the screen will be cleared, and all Views redrawn, during the next Application iteration.
  562. /// </summary>
  563. /// <remarks>
  564. /// <para>
  565. /// This is typically set to <see langword="true"/> when a View's <see cref="View.Frame"/> changes and that view
  566. /// has no SuperView (e.g. when <see cref="TopRunnable"/> is moved or resized).
  567. /// </para>
  568. /// <para>
  569. /// Automatically reset to <see langword="false"/> after <see cref="LayoutAndDraw"/> processes it.
  570. /// </para>
  571. /// </remarks>
  572. bool ClearScreenNextIteration { get; set; }
  573. /// <summary>
  574. /// Collection of sixel images to write out to screen when updating.
  575. /// Only add to this collection if you are sure terminal supports sixel format.
  576. /// </summary>
  577. List<SixelToRender> Sixel { get; }
  578. #endregion Screen and Driver
  579. #region Layout and Drawing
  580. /// <summary>
  581. /// Causes any Toplevels that need layout to be laid out, then draws any Toplevels that need display. Only Views
  582. /// that need to be laid out (see <see cref="View.NeedsLayout"/>) will be laid out. Only Views that need to be drawn
  583. /// (see <see cref="View.NeedsDraw"/>) will be drawn.
  584. /// </summary>
  585. /// <param name="forceRedraw">
  586. /// If <see langword="true"/> the entire View hierarchy will be redrawn. The default is <see langword="false"/> and
  587. /// should only be overridden for testing.
  588. /// </param>
  589. /// <remarks>
  590. /// <para>
  591. /// This method is called automatically each main loop iteration when any views need layout or drawing.
  592. /// </para>
  593. /// <para>
  594. /// If <see cref="ClearScreenNextIteration"/> is <see langword="true"/>, the screen will be cleared before
  595. /// drawing and the flag will be reset to <see langword="false"/>.
  596. /// </para>
  597. /// </remarks>
  598. public void LayoutAndDraw (bool forceRedraw = false);
  599. /// <summary>
  600. /// Calls <see cref="View.PositionCursor"/> on the most focused view.
  601. /// </summary>
  602. /// <remarks>
  603. /// <para>Does nothing if there is no most focused view.</para>
  604. /// <para>
  605. /// If the most focused view is not visible within its superview, the cursor will be hidden.
  606. /// </para>
  607. /// </remarks>
  608. /// <returns><see langword="true"/> if a view positioned the cursor and the position is visible.</returns>
  609. public bool PositionCursor ();
  610. #endregion Layout and Drawing
  611. #region Navigation and Popover
  612. /// <summary>Gets or sets the popover manager.</summary>
  613. /// <remarks>
  614. /// <para>
  615. /// Manages application-level popover views. Initialized during <see cref="Init"/>.
  616. /// </para>
  617. /// </remarks>
  618. ApplicationPopover? Popover { get; set; }
  619. /// <summary>Gets or sets the navigation manager.</summary>
  620. /// <remarks>
  621. /// <para>
  622. /// Manages focus navigation and tracking of the most focused view. Initialized during <see cref="Init"/>.
  623. /// </para>
  624. /// </remarks>
  625. ApplicationNavigation? Navigation { get; set; }
  626. #endregion Navigation and Popover
  627. #region Timeouts
  628. /// <summary>Adds a timeout to the application.</summary>
  629. /// <param name="time">The time span to wait before invoking the callback.</param>
  630. /// <param name="callback">
  631. /// The callback to invoke. If it returns <see langword="true"/>, the timeout will be reset and repeat. If it
  632. /// returns <see langword="false"/>, the timeout will stop and be removed.
  633. /// </param>
  634. /// <returns>
  635. /// Call <see cref="RemoveTimeout(object)"/> with the returned value to stop the timeout.
  636. /// </returns>
  637. /// <remarks>
  638. /// <para>
  639. /// When the time specified passes, the callback will be invoked on the main UI thread.
  640. /// </para>
  641. /// <para>
  642. /// <see cref="IApplication.Shutdown"/> calls StopAll on <see cref="TimedEvents"/> to remove all timeouts.
  643. /// </para>
  644. /// </remarks>
  645. object AddTimeout (TimeSpan time, Func<bool> callback);
  646. /// <summary>Removes a previously scheduled timeout.</summary>
  647. /// <param name="token">The token returned by <see cref="AddTimeout"/>.</param>
  648. /// <returns>
  649. /// <see langword="true"/> if the timeout is successfully removed; otherwise, <see langword="false"/>.
  650. /// This method also returns <see langword="false"/> if the timeout is not found.
  651. /// </returns>
  652. bool RemoveTimeout (object token);
  653. /// <summary>
  654. /// Handles recurring events. These are invoked on the main UI thread - allowing for
  655. /// safe updates to <see cref="View"/> instances.
  656. /// </summary>
  657. /// <remarks>
  658. /// <para>
  659. /// Provides low-level access to the timeout management system. Most applications should use
  660. /// <see cref="AddTimeout"/> and <see cref="RemoveTimeout"/> instead.
  661. /// </para>
  662. /// </remarks>
  663. ITimedEvents? TimedEvents { get; }
  664. #endregion Timeouts
  665. /// <summary>
  666. /// Gets a string representation of the Application as rendered by <see cref="Driver"/>.
  667. /// </summary>
  668. /// <returns>A string representation of the Application </returns>
  669. public string ToString ();
  670. }