Application.Lifecycle.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Reflection;
  5. namespace Terminal.Gui.App;
  6. public static partial class Application // Lifecycle (Init/Shutdown)
  7. {
  8. /// <summary>Initializes a new instance of a Terminal.Gui Application. <see cref="Shutdown"/> must be called when the application is closing.</summary>
  9. /// <para>Call this method once per instance (or after <see cref="Shutdown"/> has been called).</para>
  10. /// <para>
  11. /// This function loads the right <see cref="IConsoleDriver"/> for the platform, Creates a <see cref="Toplevel"/>. and
  12. /// assigns it to <see cref="Top"/>
  13. /// </para>
  14. /// <para>
  15. /// <see cref="Shutdown"/> must be called when the application is closing (typically after
  16. /// <see cref="Run{T}"/> has returned) to ensure resources are cleaned up and
  17. /// terminal settings
  18. /// restored.
  19. /// </para>
  20. /// <para>
  21. /// The <see cref="Run{T}"/> function combines
  22. /// <see cref="Init(IConsoleDriver,string)"/> and <see cref="Run(Toplevel, Func{Exception, bool})"/>
  23. /// into a single
  24. /// call. An application can use <see cref="Run{T}"/> without explicitly calling
  25. /// <see cref="Init(IConsoleDriver,string)"/>.
  26. /// </para>
  27. /// <param name="driver">
  28. /// The <see cref="IConsoleDriver"/> to use. If neither <paramref name="driver"/> or
  29. /// <paramref name="driverName"/> are specified the default driver for the platform will be used.
  30. /// </param>
  31. /// <param name="driverName">
  32. /// The short name (e.g. "dotnet", "windows", "unix", or "fake") of the
  33. /// <see cref="IConsoleDriver"/> to use. If neither <paramref name="driver"/> or <paramref name="driverName"/> are
  34. /// specified the default driver for the platform will be used.
  35. /// </param>
  36. [RequiresUnreferencedCode ("AOT")]
  37. [RequiresDynamicCode ("AOT")]
  38. public static void Init (IConsoleDriver? driver = null, string? driverName = null)
  39. {
  40. // Check if this is a request for a legacy driver (like FakeDriver)
  41. // that isn't supported by the modern application architecture
  42. if (driver is null)
  43. {
  44. var driverNameToCheck = string.IsNullOrWhiteSpace (driverName) ? ForceDriver : driverName;
  45. if (!string.IsNullOrEmpty (driverNameToCheck))
  46. {
  47. (List<Type?> drivers, List<string?> driverTypeNames) = GetDriverTypes ();
  48. Type? driverType = drivers.FirstOrDefault (t => t!.Name.Equals (driverNameToCheck, StringComparison.InvariantCultureIgnoreCase));
  49. // If it's a legacy IConsoleDriver (not a Facade), use InternalInit which supports legacy drivers
  50. if (driverType is { } && !typeof (IConsoleDriverFacade).IsAssignableFrom (driverType))
  51. {
  52. InternalInit (driver, driverName);
  53. return;
  54. }
  55. }
  56. }
  57. // Otherwise delegate to the ApplicationImpl instance (which uses the modern architecture)
  58. ApplicationImpl.Instance.Init (driver, driverName ?? ForceDriver);
  59. }
  60. internal static int MainThreadId
  61. {
  62. get => ((ApplicationImpl)ApplicationImpl.Instance).MainThreadId;
  63. set => ((ApplicationImpl)ApplicationImpl.Instance).MainThreadId = value;
  64. }
  65. // INTERNAL function for initializing an app with a Toplevel factory object, driver, and mainloop.
  66. //
  67. // Called from:
  68. //
  69. // Init() - When the user wants to use the default Toplevel. calledViaRunT will be false, causing all state to be reset.
  70. // Run<T>() - When the user wants to use a custom Toplevel. calledViaRunT will be true, enabling Run<T>() to be called without calling Init first.
  71. // Unit Tests - To initialize the app with a custom Toplevel, using the FakeDriver. calledViaRunT will be false, causing all state to be reset.
  72. //
  73. // calledViaRunT: If false (default) all state will be reset. If true the state will not be reset.
  74. [RequiresUnreferencedCode ("AOT")]
  75. [RequiresDynamicCode ("AOT")]
  76. internal static void InternalInit (
  77. IConsoleDriver? driver = null,
  78. string? driverName = null,
  79. bool calledViaRunT = false
  80. )
  81. {
  82. if (Initialized && driver is null)
  83. {
  84. return;
  85. }
  86. if (Initialized)
  87. {
  88. throw new InvalidOperationException ("Init has already been called and must be bracketed by Shutdown.");
  89. }
  90. if (!calledViaRunT)
  91. {
  92. // Reset all class variables (Application is a singleton).
  93. ResetState (ignoreDisposed: true);
  94. }
  95. // For UnitTests
  96. if (driver is { })
  97. {
  98. Driver = driver;
  99. }
  100. // Ignore Configuration for ForceDriver if driverName is specified
  101. if (!string.IsNullOrEmpty (driverName))
  102. {
  103. ForceDriver = driverName;
  104. }
  105. // Check if we need to use a legacy driver (like FakeDriver)
  106. // or go through the modern application architecture
  107. if (Driver is null)
  108. {
  109. ApplicationImpl.Instance.Init (driver, driverName);
  110. Debug.Assert (Driver is { });
  111. return;
  112. }
  113. Debug.Assert (Navigation is null);
  114. Navigation = new ();
  115. Debug.Assert (Popover is null);
  116. Popover = new ();
  117. try
  118. {
  119. Driver!.Init ();
  120. SubscribeDriverEvents ();
  121. }
  122. catch (InvalidOperationException ex)
  123. {
  124. // This is a case where the driver is unable to initialize the console.
  125. // This can happen if the console is already in use by another process or
  126. // if running in unit tests.
  127. // In this case, we want to throw a more specific exception.
  128. throw new InvalidOperationException (
  129. "Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.",
  130. ex
  131. );
  132. }
  133. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  134. // TODO: This is probably not needed
  135. if (Popover.GetActivePopover () is View popover)
  136. {
  137. popover.Visible = false;
  138. }
  139. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  140. bool init = Initialized = true;
  141. // Raise InitializedChanged event
  142. OnInitializedChanged (ApplicationImpl.Instance, new (init));
  143. }
  144. internal static void SubscribeDriverEvents ()
  145. {
  146. ArgumentNullException.ThrowIfNull (Driver);
  147. Driver.SizeChanged += Driver_SizeChanged;
  148. Driver.KeyDown += Driver_KeyDown;
  149. Driver.KeyUp += Driver_KeyUp;
  150. Driver.MouseEvent += Driver_MouseEvent;
  151. }
  152. internal static void UnsubscribeDriverEvents ()
  153. {
  154. ArgumentNullException.ThrowIfNull (Driver);
  155. Driver.SizeChanged -= Driver_SizeChanged;
  156. Driver.KeyDown -= Driver_KeyDown;
  157. Driver.KeyUp -= Driver_KeyUp;
  158. Driver.MouseEvent -= Driver_MouseEvent;
  159. }
  160. private static void Driver_SizeChanged (object? sender, SizeChangedEventArgs e) { OnSizeChanging (e); }
  161. private static void Driver_KeyDown (object? sender, Key e) { RaiseKeyDownEvent (e); }
  162. private static void Driver_KeyUp (object? sender, Key e) { RaiseKeyUpEvent (e); }
  163. private static void Driver_MouseEvent (object? sender, MouseEventArgs e) { RaiseMouseEvent (e); }
  164. /// <summary>Gets a list of <see cref="IConsoleDriver"/> types and type names that are available.</summary>
  165. /// <returns></returns>
  166. [RequiresUnreferencedCode ("AOT")]
  167. public static (List<Type?>, List<string?>) GetDriverTypes ()
  168. {
  169. // use reflection to get the list of drivers
  170. List<Type?> driverTypes = new ();
  171. // Only inspect the IConsoleDriver assembly
  172. var asm = typeof (IConsoleDriver).Assembly;
  173. foreach (Type? type in asm.GetTypes ())
  174. {
  175. if (typeof (IConsoleDriver).IsAssignableFrom (type) &&
  176. type is { IsAbstract: false, IsClass: true })
  177. {
  178. driverTypes.Add (type);
  179. }
  180. }
  181. List<string?> driverTypeNames = driverTypes
  182. .Where (d => !typeof (IConsoleDriverFacade).IsAssignableFrom (d))
  183. .Select (d => d!.Name)
  184. .Union (["dotnet", "windows", "unix", "fake"])
  185. .ToList ()!;
  186. return (driverTypes, driverTypeNames);
  187. }
  188. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  189. /// <remarks>
  190. /// Shutdown must be called for every call to <see cref="Init"/> or
  191. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  192. /// up (Disposed)
  193. /// and terminal settings are restored.
  194. /// </remarks>
  195. public static void Shutdown () => ApplicationImpl.Instance.Shutdown ();
  196. /// <summary>
  197. /// Gets whether the application has been initialized with <see cref="Init"/> and not yet shutdown with <see cref="Shutdown"/>.
  198. /// </summary>
  199. /// <remarks>
  200. /// <para>
  201. /// The <see cref="InitializedChanged"/> event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  202. /// </para>
  203. /// </remarks>
  204. public static bool Initialized
  205. {
  206. get => ApplicationImpl.Instance.Initialized;
  207. internal set => ApplicationImpl.Instance.Initialized = value;
  208. }
  209. /// <summary>
  210. /// This event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  211. /// </summary>
  212. /// <remarks>
  213. /// Intended to support unit tests that need to know when the application has been initialized.
  214. /// </remarks>
  215. public static event EventHandler<EventArgs<bool>>? InitializedChanged;
  216. /// <summary>
  217. /// Raises the <see cref="InitializedChanged"/> event.
  218. /// </summary>
  219. internal static void OnInitializedChanged (object sender, EventArgs<bool> e)
  220. {
  221. InitializedChanged?.Invoke (sender, e);
  222. }
  223. }