2
0

ApplicationImpl.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. namespace Terminal.Gui.App;
  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, string.IsNullOrWhiteSpace (driverName) ? Application.ForceDriver : 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, Application.ForceDriver, true);
  82. }
  83. if (Instance is ApplicationV2)
  84. {
  85. return Instance.Run<T> (errorHandler, driver);
  86. }
  87. var top = new T ();
  88. Run (top, errorHandler);
  89. return top;
  90. }
  91. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  92. /// <remarks>
  93. /// <para>
  94. /// This method is used to start processing events for the main application, but it is also used to run other
  95. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  96. /// </para>
  97. /// <para>
  98. /// To make a <see cref="Run(Toplevel,System.Func{System.Exception,bool})"/> stop execution, call
  99. /// <see cref="Application.RequestStop"/>.
  100. /// </para>
  101. /// <para>
  102. /// Calling <see cref="Run(Toplevel,System.Func{System.Exception,bool})"/> is equivalent to calling
  103. /// <see cref="Application.Begin(Toplevel)"/>, followed by <see cref="Application.RunLoop(RunState)"/>, and then calling
  104. /// <see cref="Application.End(RunState)"/>.
  105. /// </para>
  106. /// <para>
  107. /// Alternatively, to have a program control the main loop and process events manually, call
  108. /// <see cref="Application.Begin(Toplevel)"/> to set things up manually and then repeatedly call
  109. /// <see cref="Application.RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  110. /// <see cref="Application.RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  111. /// return control immediately.
  112. /// </para>
  113. /// <para>When using <see cref="Run{T}"/> or
  114. /// <see cref="Run(System.Func{System.Exception,bool},IConsoleDriver)"/>
  115. /// <see cref="Init"/> will be called automatically.
  116. /// </para>
  117. /// <para>
  118. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  119. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  120. /// returns <see langword="true"/> the <see cref="Application.RunLoop(RunState)"/> will resume; otherwise this method will
  121. /// exit.
  122. /// </para>
  123. /// </remarks>
  124. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  125. /// <param name="errorHandler">
  126. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  127. /// rethrows when null).
  128. /// </param>
  129. public virtual void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  130. {
  131. ArgumentNullException.ThrowIfNull (view);
  132. if (Application.Initialized)
  133. {
  134. if (Application.Driver is null)
  135. {
  136. // Disposing before throwing
  137. view.Dispose ();
  138. // This code path should be impossible because Init(null, null) will select the platform default driver
  139. throw new InvalidOperationException (
  140. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  141. );
  142. }
  143. }
  144. else
  145. {
  146. // Init() has NOT been called.
  147. throw new InvalidOperationException (
  148. "Init() has not been called. Only Run() or Run<T>() can be used without calling Init()."
  149. );
  150. }
  151. var resume = true;
  152. while (resume)
  153. {
  154. #if !DEBUG
  155. try
  156. {
  157. #endif
  158. resume = false;
  159. RunState runState = Application.Begin (view);
  160. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  161. // by using NotifyStopRunState event.
  162. Application.RunLoop (runState);
  163. if (runState.Toplevel is null)
  164. {
  165. #if DEBUG_IDISPOSABLE
  166. if (View.EnableDebugIDisposableAsserts)
  167. {
  168. Debug.Assert (Application.TopLevels.Count == 0);
  169. }
  170. #endif
  171. runState.Dispose ();
  172. return;
  173. }
  174. if (!Application.EndAfterFirstIteration)
  175. {
  176. Application.End (runState);
  177. }
  178. #if !DEBUG
  179. }
  180. catch (Exception error)
  181. {
  182. Logging.Warning ($"Release Build Exception: {error}");
  183. if (errorHandler is null)
  184. {
  185. throw;
  186. }
  187. resume = errorHandler (error);
  188. }
  189. #endif
  190. }
  191. }
  192. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  193. /// <remarks>
  194. /// Shutdown must be called for every call to <see cref="Init"/> or
  195. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  196. /// up (Disposed)
  197. /// and terminal settings are restored.
  198. /// </remarks>
  199. public virtual void Shutdown ()
  200. {
  201. // TODO: Throw an exception if Init hasn't been called.
  202. bool wasInitialized = Application.Initialized;
  203. Application.ResetState ();
  204. ConfigurationManager.PrintJsonErrors ();
  205. if (wasInitialized)
  206. {
  207. bool init = Application.Initialized;
  208. Application.OnInitializedChanged (this, new (in init));
  209. }
  210. _lazyInstance = new (() => new ApplicationImpl ());
  211. }
  212. /// <inheritdoc />
  213. public virtual void RequestStop (Toplevel? top)
  214. {
  215. top ??= Application.Top;
  216. if (!top!.Running)
  217. {
  218. return;
  219. }
  220. var ev = new ToplevelClosingEventArgs (top);
  221. top.OnClosing (ev);
  222. if (ev.Cancel)
  223. {
  224. return;
  225. }
  226. top.Running = false;
  227. Application.OnNotifyStopRunState (top);
  228. }
  229. /// <inheritdoc />
  230. public virtual void Invoke (Action action)
  231. {
  232. Application.MainLoop?.AddIdle (
  233. () =>
  234. {
  235. action ();
  236. return false;
  237. }
  238. );
  239. }
  240. /// <inheritdoc />
  241. public bool IsLegacy { get; protected set; } = true;
  242. /// <inheritdoc />
  243. public virtual void AddIdle (Func<bool> func)
  244. {
  245. if (Application.MainLoop is null)
  246. {
  247. throw new NotInitializedException ("Cannot add idle before main loop is initialized");
  248. }
  249. // Yes in this case we cannot go direct via TimedEvents because legacy main loop
  250. // has established behaviour to do other stuff too e.g. 'wake up'.
  251. Application.MainLoop.AddIdle (func);
  252. }
  253. /// <inheritdoc />
  254. public virtual object AddTimeout (TimeSpan time, Func<bool> callback)
  255. {
  256. if (Application.MainLoop is null)
  257. {
  258. throw new NotInitializedException ("Cannot add timeout before main loop is initialized", null);
  259. }
  260. return Application.MainLoop.TimedEvents.AddTimeout (time, callback);
  261. }
  262. /// <inheritdoc />
  263. public virtual bool RemoveTimeout (object token)
  264. {
  265. return Application.MainLoop?.TimedEvents.RemoveTimeout (token) ?? false;
  266. }
  267. /// <inheritdoc />
  268. public virtual void LayoutAndDraw (bool forceDraw)
  269. {
  270. Application.LayoutAndDrawImpl (forceDraw);
  271. }
  272. }