IApplication.cs 36 KB

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