Application.Initialization.cs 8.4 KB

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