ApplicationImpl.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. if (View.DebugIDisposable)
  163. {
  164. Debug.Assert (Application.TopLevels.Count == 0);
  165. }
  166. #endif
  167. runState.Dispose ();
  168. return;
  169. }
  170. if (!Application.EndAfterFirstIteration)
  171. {
  172. Application.End (runState);
  173. }
  174. #if !DEBUG
  175. }
  176. catch (Exception error)
  177. {
  178. if (errorHandler is null)
  179. {
  180. throw;
  181. }
  182. resume = errorHandler (error);
  183. }
  184. #endif
  185. }
  186. }
  187. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  188. /// <remarks>
  189. /// Shutdown must be called for every call to <see cref="Init"/> or
  190. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  191. /// up (Disposed)
  192. /// and terminal settings are restored.
  193. /// </remarks>
  194. public virtual void Shutdown ()
  195. {
  196. // TODO: Throw an exception if Init hasn't been called.
  197. bool wasInitialized = Application.Initialized;
  198. Application.ResetState ();
  199. LogJsonErrors ();
  200. PrintJsonErrors ();
  201. if (wasInitialized)
  202. {
  203. bool init = Application.Initialized;
  204. Application.OnInitializedChanged(this, new (in init));
  205. }
  206. }
  207. /// <inheritdoc />
  208. public virtual void RequestStop (Toplevel? top)
  209. {
  210. top ??= Application.Top;
  211. if (!top!.Running)
  212. {
  213. return;
  214. }
  215. var ev = new ToplevelClosingEventArgs (top);
  216. top.OnClosing (ev);
  217. if (ev.Cancel)
  218. {
  219. return;
  220. }
  221. top.Running = false;
  222. Application.OnNotifyStopRunState (top);
  223. }
  224. /// <inheritdoc />
  225. public virtual void Invoke (Action action)
  226. {
  227. Application.MainLoop?.AddIdle (
  228. () =>
  229. {
  230. action ();
  231. return false;
  232. }
  233. );
  234. }
  235. /// <inheritdoc />
  236. public bool IsLegacy { get; protected set; } = true;
  237. /// <inheritdoc />
  238. public virtual void AddIdle (Func<bool> func)
  239. {
  240. if(Application.MainLoop is null)
  241. {
  242. throw new NotInitializedException ("Cannot add idle before main loop is initialized");
  243. }
  244. // Yes in this case we cannot go direct via TimedEvents because legacy main loop
  245. // has established behaviour to do other stuff too e.g. 'wake up'.
  246. Application.MainLoop.AddIdle (func);
  247. }
  248. /// <inheritdoc />
  249. public virtual object AddTimeout (TimeSpan time, Func<bool> callback)
  250. {
  251. if (Application.MainLoop is null)
  252. {
  253. throw new NotInitializedException ("Cannot add timeout before main loop is initialized", null);
  254. }
  255. return Application.MainLoop.TimedEvents.AddTimeout (time, callback);
  256. }
  257. /// <inheritdoc />
  258. public virtual bool RemoveTimeout (object token)
  259. {
  260. return Application.MainLoop?.TimedEvents.RemoveTimeout (token) ?? false;
  261. }
  262. /// <inheritdoc />
  263. public virtual void LayoutAndDraw (bool forceDraw)
  264. {
  265. Application.LayoutAndDrawImpl (forceDraw);
  266. }
  267. }