Application.Initialization.cs 9.6 KB

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