ApplicationImpl.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. namespace Terminal.Gui;
  5. /// <summary>
  6. /// Original Terminal.Gui implementation of core <see cref="Application"/> methods.
  7. /// </summary>
  8. public class ApplicationImpl : IApplication
  9. {
  10. // Private static readonly Lazy instance of Application
  11. private static Lazy<IApplication> _lazyInstance = new (() => new ApplicationImpl ());
  12. /// <summary>
  13. /// Gets the currently configured backend implementation of <see cref="Application"/> gateway methods.
  14. /// Change to your own implementation by using <see cref="ChangeInstance"/> (before init).
  15. /// </summary>
  16. public static IApplication Instance => _lazyInstance.Value;
  17. /// <summary>
  18. /// Change the singleton implementation, should not be called except before application
  19. /// startup. This method lets you provide alternative implementations of core static gateway
  20. /// methods of <see cref="Application"/>.
  21. /// </summary>
  22. /// <param name="newApplication"></param>
  23. public static void ChangeInstance (IApplication newApplication)
  24. {
  25. _lazyInstance = new Lazy<IApplication> (newApplication);
  26. }
  27. /// <inheritdoc/>
  28. [RequiresUnreferencedCode ("AOT")]
  29. [RequiresDynamicCode ("AOT")]
  30. public virtual void Init (IConsoleDriver? driver = null, string? driverName = null)
  31. {
  32. Application.InternalInit (driver, driverName);
  33. }
  34. /// <summary>
  35. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  36. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  37. /// </summary>
  38. /// <remarks>
  39. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  40. /// <para>
  41. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  42. /// ensure resources are cleaned up and terminal settings restored.
  43. /// </para>
  44. /// <para>
  45. /// The caller is responsible for disposing the object returned by this method.
  46. /// </para>
  47. /// </remarks>
  48. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  49. [RequiresUnreferencedCode ("AOT")]
  50. [RequiresDynamicCode ("AOT")]
  51. public Toplevel Run (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  52. /// <summary>
  53. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  54. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  55. /// </summary>
  56. /// <remarks>
  57. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  58. /// <para>
  59. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  60. /// ensure resources are cleaned up and terminal settings restored.
  61. /// </para>
  62. /// <para>
  63. /// The caller is responsible for disposing the object returned by this method.
  64. /// </para>
  65. /// </remarks>
  66. /// <param name="errorHandler"></param>
  67. /// <param name="driver">
  68. /// The <see cref="IConsoleDriver"/> to use. If not specified the default driver for the platform will
  69. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  70. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  71. /// </param>
  72. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  73. [RequiresUnreferencedCode ("AOT")]
  74. [RequiresDynamicCode ("AOT")]
  75. public virtual T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  76. where T : Toplevel, new()
  77. {
  78. if (!Application.Initialized)
  79. {
  80. // Init() has NOT been called.
  81. Application.InternalInit (driver, null, true);
  82. }
  83. var top = new T ();
  84. Run (top, errorHandler);
  85. return top;
  86. }
  87. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  88. /// <remarks>
  89. /// <para>
  90. /// This method is used to start processing events for the main application, but it is also used to run other
  91. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  92. /// </para>
  93. /// <para>
  94. /// To make a <see cref="Run(Terminal.Gui.Toplevel,System.Func{System.Exception,bool})"/> stop execution, call
  95. /// <see cref="Application.RequestStop"/>.
  96. /// </para>
  97. /// <para>
  98. /// Calling <see cref="Run(Terminal.Gui.Toplevel,System.Func{System.Exception,bool})"/> is equivalent to calling
  99. /// <see cref="Application.Begin(Toplevel)"/>, followed by <see cref="Application.RunLoop(RunState)"/>, and then calling
  100. /// <see cref="Application.End(RunState)"/>.
  101. /// </para>
  102. /// <para>
  103. /// Alternatively, to have a program control the main loop and process events manually, call
  104. /// <see cref="Application.Begin(Toplevel)"/> to set things up manually and then repeatedly call
  105. /// <see cref="Application.RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  106. /// <see cref="Application.RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  107. /// return control immediately.
  108. /// </para>
  109. /// <para>When using <see cref="Run{T}"/> or
  110. /// <see cref="Run(System.Func{System.Exception,bool},Terminal.Gui.IConsoleDriver)"/>
  111. /// <see cref="Init"/> will be called automatically.
  112. /// </para>
  113. /// <para>
  114. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  115. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  116. /// returns <see langword="true"/> the <see cref="Application.RunLoop(RunState)"/> will resume; otherwise this method will
  117. /// exit.
  118. /// </para>
  119. /// </remarks>
  120. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  121. /// <param name="errorHandler">
  122. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  123. /// rethrows when null).
  124. /// </param>
  125. public virtual void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  126. {
  127. ArgumentNullException.ThrowIfNull (view);
  128. if (Application.Initialized)
  129. {
  130. if (Application.Driver is null)
  131. {
  132. // Disposing before throwing
  133. view.Dispose ();
  134. // This code path should be impossible because Init(null, null) will select the platform default driver
  135. throw new InvalidOperationException (
  136. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  137. );
  138. }
  139. }
  140. else
  141. {
  142. // Init() has NOT been called.
  143. throw new InvalidOperationException (
  144. "Init() has not been called. Only Run() or Run<T>() can be used without calling Init()."
  145. );
  146. }
  147. var resume = true;
  148. while (resume)
  149. {
  150. #if !DEBUG
  151. try
  152. {
  153. #endif
  154. resume = false;
  155. RunState runState = Application.Begin (view);
  156. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  157. // by using NotifyStopRunState event.
  158. Application.RunLoop (runState);
  159. if (runState.Toplevel is null)
  160. {
  161. #if DEBUG_IDISPOSABLE
  162. Debug.Assert (Application.TopLevels.Count == 0);
  163. #endif
  164. runState.Dispose ();
  165. return;
  166. }
  167. if (!Application.EndAfterFirstIteration)
  168. {
  169. Application.End (runState);
  170. }
  171. #if !DEBUG
  172. }
  173. catch (Exception error)
  174. {
  175. if (errorHandler is null)
  176. {
  177. throw;
  178. }
  179. resume = errorHandler (error);
  180. }
  181. #endif
  182. }
  183. }
  184. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  185. /// <remarks>
  186. /// Shutdown must be called for every call to <see cref="Init"/> or
  187. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  188. /// up (Disposed)
  189. /// and terminal settings are restored.
  190. /// </remarks>
  191. public virtual void Shutdown ()
  192. {
  193. // TODO: Throw an exception if Init hasn't been called.
  194. bool wasInitialized = Application.Initialized;
  195. Application.ResetState ();
  196. LogJsonErrors ();
  197. PrintJsonErrors ();
  198. if (wasInitialized)
  199. {
  200. bool init = Application.Initialized;
  201. Application.OnInitializedChanged(this, new (in init));
  202. }
  203. }
  204. /// <inheritdoc />
  205. public virtual void RequestStop (Toplevel? top)
  206. {
  207. top ??= Application.Top;
  208. if (!top!.Running)
  209. {
  210. return;
  211. }
  212. var ev = new ToplevelClosingEventArgs (top);
  213. top.OnClosing (ev);
  214. if (ev.Cancel)
  215. {
  216. return;
  217. }
  218. top.Running = false;
  219. Application.OnNotifyStopRunState (top);
  220. }
  221. /// <inheritdoc />
  222. public virtual void Invoke (Action action)
  223. {
  224. Application.MainLoop?.AddIdle (
  225. () =>
  226. {
  227. action ();
  228. return false;
  229. }
  230. );
  231. }
  232. /// <inheritdoc />
  233. public bool IsLegacy { get; protected set; } = true;
  234. /// <inheritdoc />
  235. public virtual void AddIdle (Func<bool> func)
  236. {
  237. if(Application.MainLoop is null)
  238. {
  239. throw new NotInitializedException ("Cannot add idle before main loop is initialized");
  240. }
  241. // Yes in this case we cannot go direct via TimedEvents because legacy main loop
  242. // has established behaviour to do other stuff too e.g. 'wake up'.
  243. Application.MainLoop.AddIdle (func);
  244. }
  245. /// <inheritdoc />
  246. public virtual object AddTimeout (TimeSpan time, Func<bool> callback)
  247. {
  248. if (Application.MainLoop is null)
  249. {
  250. throw new NotInitializedException ("Cannot add timeout before main loop is initialized", null);
  251. }
  252. return Application.MainLoop.TimedEvents.AddTimeout (time, callback);
  253. }
  254. /// <inheritdoc />
  255. public virtual bool RemoveTimeout (object token)
  256. {
  257. return Application.MainLoop?.TimedEvents.RemoveTimeout (token) ?? false;
  258. }
  259. /// <inheritdoc />
  260. public virtual void LayoutAndDraw (bool forceDraw)
  261. {
  262. Application.LayoutAndDrawImpl (forceDraw);
  263. }
  264. }