Application.Initialization.cs 11 KB

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