Application.Initialization.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #nullable enable
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Reflection;
  4. namespace Terminal.Gui;
  5. public static partial class Application // Initialization (Init/Shutdown)
  6. {
  7. /// <summary>Initializes a new instance of <see cref="Terminal.Gui"/> Application.</summary>
  8. /// <para>Call this method once per instance (or after <see cref="Shutdown"/> has been called).</para>
  9. /// <para>
  10. /// This function loads the right <see cref="ConsoleDriver"/> for the platform, Creates a <see cref="Toplevel"/>. and
  11. /// assigns it to <see cref="Top"/>
  12. /// </para>
  13. /// <para>
  14. /// <see cref="Shutdown"/> must be called when the application is closing (typically after
  15. /// <see cref="Run{T}"/> has returned) to ensure resources are cleaned up and
  16. /// terminal settings
  17. /// restored.
  18. /// </para>
  19. /// <para>
  20. /// The <see cref="Run{T}"/> function combines
  21. /// <see cref="Init(Terminal.Gui.ConsoleDriver,string)"/> and <see cref="Run(Toplevel, Func{Exception, bool})"/>
  22. /// into a single
  23. /// call. An application cam use <see cref="Run{T}"/> without explicitly calling
  24. /// <see cref="Init(Terminal.Gui.ConsoleDriver,string)"/>.
  25. /// </para>
  26. /// <param name="driver">
  27. /// The <see cref="ConsoleDriver"/> to use. If neither <paramref name="driver"/> or
  28. /// <paramref name="driverName"/> are specified the default driver for the platform will be used.
  29. /// </param>
  30. /// <param name="driverName">
  31. /// The short name (e.g. "net", "windows", "ansi", "fake", or "curses") of the
  32. /// <see cref="ConsoleDriver"/> to use. If neither <paramref name="driver"/> or <paramref name="driverName"/> are
  33. /// specified the default driver for the platform will be used.
  34. /// </param>
  35. [RequiresUnreferencedCode ("AOT")]
  36. [RequiresDynamicCode ("AOT")]
  37. public static void Init (ConsoleDriver? driver = null, string? driverName = null) { InternalInit (driver, driverName); }
  38. internal static bool IsInitialized { get; set; }
  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 (IsInitialized && driver is null)
  58. {
  59. return;
  60. }
  61. if (IsInitialized)
  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 ();
  69. }
  70. // For UnitTests
  71. if (driver is { })
  72. {
  73. Driver = driver;
  74. }
  75. // Start the process of configuration management.
  76. // Note that we end up calling LoadConfigurationFromAllSources
  77. // multiple times. We need to do this because some settings are only
  78. // valid after a Driver is loaded. In this case we need just
  79. // `Settings` so we can determine which driver to use.
  80. // Don't reset, so we can inherit the theme from the previous run.
  81. Load ();
  82. Apply ();
  83. AddApplicationKeyBindings ();
  84. // Ignore Configuration for ForceDriver if driverName is specified
  85. if (!string.IsNullOrEmpty (driverName))
  86. {
  87. ForceDriver = driverName;
  88. }
  89. if (Driver is null)
  90. {
  91. PlatformID p = Environment.OSVersion.Platform;
  92. if (string.IsNullOrEmpty (ForceDriver))
  93. {
  94. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  95. {
  96. Driver = new WindowsDriver ();
  97. }
  98. else
  99. {
  100. Driver = new CursesDriver ();
  101. }
  102. }
  103. else
  104. {
  105. List<Type?> drivers = GetDriverTypes ();
  106. Type? driverType = drivers.FirstOrDefault (t => t!.Name.Equals (ForceDriver, StringComparison.InvariantCultureIgnoreCase));
  107. if (driverType is { })
  108. {
  109. Driver = (ConsoleDriver)Activator.CreateInstance (driverType)!;
  110. }
  111. else
  112. {
  113. throw new ArgumentException (
  114. $"Invalid driver name: {ForceDriver}. Valid names are {string.Join (", ", drivers.Select (t => t!.Name))}"
  115. );
  116. }
  117. }
  118. }
  119. try
  120. {
  121. MainLoop = Driver!.Init ();
  122. }
  123. catch (InvalidOperationException ex)
  124. {
  125. // This is a case where the driver is unable to initialize the console.
  126. // This can happen if the console is already in use by another process or
  127. // if running in unit tests.
  128. // In this case, we want to throw a more specific exception.
  129. throw new InvalidOperationException (
  130. "Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.",
  131. ex
  132. );
  133. }
  134. Driver.SizeChanged += (s, args) => OnSizeChanging (args);
  135. Driver.KeyDown += (s, args) => OnKeyDown (args);
  136. Driver.KeyUp += (s, args) => OnKeyUp (args);
  137. Driver.MouseEvent += (s, args) => OnMouseEvent (args);
  138. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  139. SupportedCultures = GetSupportedCultures ();
  140. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  141. bool init = IsInitialized = true;
  142. InitializedChanged?.Invoke (null, new (init));
  143. }
  144. private static void Driver_SizeChanged (object? sender, SizeChangedEventArgs e) { OnSizeChanging (e); }
  145. private static void Driver_KeyDown (object? sender, Key e) { OnKeyDown (e); }
  146. private static void Driver_KeyUp (object? sender, Key e) { OnKeyUp (e); }
  147. private static void Driver_MouseEvent (object? sender, MouseEvent e) { OnMouseEvent (e); }
  148. /// <summary>Gets of list of <see cref="ConsoleDriver"/> types that are available.</summary>
  149. /// <returns></returns>
  150. [RequiresUnreferencedCode ("AOT")]
  151. public static List<Type?> GetDriverTypes ()
  152. {
  153. // use reflection to get the list of drivers
  154. List<Type?> driverTypes = new ();
  155. foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ())
  156. {
  157. foreach (Type? type in asm.GetTypes ())
  158. {
  159. if (type.IsSubclassOf (typeof (ConsoleDriver)) && !type.IsAbstract)
  160. {
  161. driverTypes.Add (type);
  162. }
  163. }
  164. }
  165. return driverTypes;
  166. }
  167. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  168. /// <remarks>
  169. /// Shutdown must be called for every call to <see cref="Init"/> or
  170. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  171. /// up (Disposed)
  172. /// and terminal settings are restored.
  173. /// </remarks>
  174. public static void Shutdown ()
  175. {
  176. // TODO: Throw an exception if Init hasn't been called.
  177. ResetState ();
  178. PrintJsonErrors ();
  179. bool init = IsInitialized;
  180. InitializedChanged?.Invoke (null, new (in init));
  181. }
  182. /// <summary>
  183. /// This event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  184. /// </summary>
  185. /// <remarks>
  186. /// Intended to support unit tests that need to know when the application has been initialized.
  187. /// </remarks>
  188. public static event EventHandler<EventArgs<bool>>? InitializedChanged;
  189. }