Application.Initialization.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Reflection;
  5. namespace Terminal.Gui;
  6. public static partial class Application // Initialization (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(Terminal.Gui.IConsoleDriver,string)"/> and <see cref="Run(Toplevel, Func{Exception, bool})"/>
  23. /// into a single
  24. /// call. An application cam use <see cref="Run{T}"/> without explicitly calling
  25. /// <see cref="Init(Terminal.Gui.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. "net", "windows", "ansi", "fake", or "curses") 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. if (driverName?.StartsWith ("v2") ?? false)
  41. {
  42. ApplicationImpl.ChangeInstance (new ApplicationV2 ());
  43. }
  44. ApplicationImpl.Instance.Init (driver, driverName);
  45. }
  46. internal static int MainThreadId { get; set; } = -1;
  47. // INTERNAL function for initializing an app with a Toplevel factory object, driver, and mainloop.
  48. //
  49. // Called from:
  50. //
  51. // Init() - When the user wants to use the default Toplevel. calledViaRunT will be false, causing all state to be reset.
  52. // 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.
  53. // Unit Tests - To initialize the app with a custom Toplevel, using the FakeDriver. calledViaRunT will be false, causing all state to be reset.
  54. //
  55. // calledViaRunT: If false (default) all state will be reset. If true the state will not be reset.
  56. [RequiresUnreferencedCode ("AOT")]
  57. [RequiresDynamicCode ("AOT")]
  58. internal static void InternalInit (
  59. IConsoleDriver? driver = null,
  60. string? driverName = null,
  61. bool calledViaRunT = false
  62. )
  63. {
  64. if (Initialized && driver is null)
  65. {
  66. return;
  67. }
  68. if (Initialized)
  69. {
  70. throw new InvalidOperationException ("Init has already been called and must be bracketed by Shutdown.");
  71. }
  72. if (!calledViaRunT)
  73. {
  74. // Reset all class variables (Application is a singleton).
  75. ResetState (ignoreDisposed: true);
  76. }
  77. Debug.Assert (Navigation is null);
  78. Navigation = new ();
  79. Debug.Assert(Popover is null);
  80. Popover = new ();
  81. // For UnitTests
  82. if (driver is { })
  83. {
  84. Driver = driver;
  85. if (driver is FakeDriver)
  86. {
  87. // We're running unit tests. Disable loading config files other than default
  88. if (Locations == ConfigLocations.All)
  89. {
  90. Locations = ConfigLocations.Default;
  91. Reset ();
  92. }
  93. }
  94. }
  95. AddKeyBindings ();
  96. InitializeConfigurationManagement ();
  97. // Ignore Configuration for ForceDriver if driverName is specified
  98. if (!string.IsNullOrEmpty (driverName))
  99. {
  100. ForceDriver = driverName;
  101. }
  102. if (Driver is null)
  103. {
  104. PlatformID p = Environment.OSVersion.Platform;
  105. if (string.IsNullOrEmpty (ForceDriver))
  106. {
  107. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  108. {
  109. Driver = new WindowsDriver ();
  110. }
  111. else
  112. {
  113. Driver = new CursesDriver ();
  114. }
  115. }
  116. else
  117. {
  118. List<Type?> drivers = GetDriverTypes ();
  119. Type? driverType = drivers.FirstOrDefault (t => t!.Name.Equals (ForceDriver, StringComparison.InvariantCultureIgnoreCase));
  120. if (driverType is { })
  121. {
  122. Driver = (IConsoleDriver)Activator.CreateInstance (driverType)!;
  123. }
  124. else
  125. {
  126. throw new ArgumentException (
  127. $"Invalid driver name: {ForceDriver}. Valid names are {string.Join (", ", drivers.Select (t => t!.Name))}"
  128. );
  129. }
  130. }
  131. }
  132. try
  133. {
  134. MainLoop = Driver!.Init ();
  135. SubscribeDriverEvents ();
  136. }
  137. catch (InvalidOperationException ex)
  138. {
  139. // This is a case where the driver is unable to initialize the console.
  140. // This can happen if the console is already in use by another process or
  141. // if running in unit tests.
  142. // In this case, we want to throw a more specific exception.
  143. throw new InvalidOperationException (
  144. "Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.",
  145. ex
  146. );
  147. }
  148. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  149. // TODO: This is probably not needed
  150. if (Popover.GetActivePopover () is View popover)
  151. {
  152. popover.Visible = false;
  153. }
  154. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  155. bool init = Initialized = true;
  156. InitializedChanged?.Invoke (null, new (init));
  157. }
  158. [RequiresUnreferencedCode ("AOT")]
  159. [RequiresDynamicCode ("AOT")]
  160. internal static void InitializeConfigurationManagement ()
  161. {
  162. // Start the process of configuration management.
  163. // Note that we end up calling LoadConfigurationFromAllSources
  164. // multiple times. We need to do this because some settings are only
  165. // valid after a Driver is loaded. In this case we need just
  166. // `Settings` so we can determine which driver to use.
  167. // Don't reset, so we can inherit the theme from the previous run.
  168. string previousTheme = Themes?.Theme ?? string.Empty;
  169. Load ();
  170. if (Themes is { } && !string.IsNullOrEmpty (previousTheme) && previousTheme != "Default")
  171. {
  172. ThemeManager.SelectedTheme = previousTheme;
  173. }
  174. Apply ();
  175. }
  176. internal static void SubscribeDriverEvents ()
  177. {
  178. ArgumentNullException.ThrowIfNull (Driver);
  179. Driver.SizeChanged += Driver_SizeChanged;
  180. Driver.KeyDown += Driver_KeyDown;
  181. Driver.KeyUp += Driver_KeyUp;
  182. Driver.MouseEvent += Driver_MouseEvent;
  183. }
  184. internal static void UnsubscribeDriverEvents ()
  185. {
  186. ArgumentNullException.ThrowIfNull (Driver);
  187. Driver.SizeChanged -= Driver_SizeChanged;
  188. Driver.KeyDown -= Driver_KeyDown;
  189. Driver.KeyUp -= Driver_KeyUp;
  190. Driver.MouseEvent -= Driver_MouseEvent;
  191. }
  192. private static void Driver_SizeChanged (object? sender, SizeChangedEventArgs e) { OnSizeChanging (e); }
  193. private static void Driver_KeyDown (object? sender, Key e) { RaiseKeyDownEvent (e); }
  194. private static void Driver_KeyUp (object? sender, Key e) { RaiseKeyUpEvent (e); }
  195. private static void Driver_MouseEvent (object? sender, MouseEventArgs e) { RaiseMouseEvent (e); }
  196. /// <summary>Gets of list of <see cref="IConsoleDriver"/> types that are available.</summary>
  197. /// <returns></returns>
  198. [RequiresUnreferencedCode ("AOT")]
  199. public static List<Type?> GetDriverTypes ()
  200. {
  201. // use reflection to get the list of drivers
  202. List<Type?> driverTypes = new ();
  203. foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ())
  204. {
  205. foreach (Type? type in asm.GetTypes ())
  206. {
  207. if (typeof (IConsoleDriver).IsAssignableFrom (type) && !type.IsAbstract && type.IsClass)
  208. {
  209. driverTypes.Add (type);
  210. }
  211. }
  212. }
  213. return driverTypes;
  214. }
  215. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  216. /// <remarks>
  217. /// Shutdown must be called for every call to <see cref="Init"/> or
  218. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  219. /// up (Disposed)
  220. /// and terminal settings are restored.
  221. /// </remarks>
  222. public static void Shutdown () => ApplicationImpl.Instance.Shutdown ();
  223. /// <summary>
  224. /// Gets whether the application has been initialized with <see cref="Init"/> and not yet shutdown with <see cref="Shutdown"/>.
  225. /// </summary>
  226. /// <remarks>
  227. /// <para>
  228. /// The <see cref="InitializedChanged"/> event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  229. /// </para>
  230. /// </remarks>
  231. public static bool Initialized { get; internal set; }
  232. /// <summary>
  233. /// This event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  234. /// </summary>
  235. /// <remarks>
  236. /// Intended to support unit tests that need to know when the application has been initialized.
  237. /// </remarks>
  238. public static event EventHandler<EventArgs<bool>>? InitializedChanged;
  239. /// <summary>
  240. /// Raises the <see cref="InitializedChanged"/> event.
  241. /// </summary>
  242. internal static void OnInitializedChanged (object sender, EventArgs<bool> e)
  243. {
  244. Application.InitializedChanged?.Invoke (sender, e);
  245. }
  246. }