Application.Initialization.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 // 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(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(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. ApplicationImpl.Instance.Init (driver, driverName);
  41. }
  42. internal static int MainThreadId { get; set; } = -1;
  43. // INTERNAL function for initializing an app with a Toplevel factory object, driver, and mainloop.
  44. //
  45. // Called from:
  46. //
  47. // Init() - When the user wants to use the default Toplevel. calledViaRunT will be false, causing all state to be reset.
  48. // 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.
  49. // Unit Tests - To initialize the app with a custom Toplevel, using the FakeDriver. calledViaRunT will be false, causing all state to be reset.
  50. //
  51. // calledViaRunT: If false (default) all state will be reset. If true the state will not be reset.
  52. [RequiresUnreferencedCode ("AOT")]
  53. [RequiresDynamicCode ("AOT")]
  54. internal static void InternalInit (
  55. IConsoleDriver? driver = null,
  56. string? driverName = null,
  57. bool calledViaRunT = false
  58. )
  59. {
  60. if (Initialized && driver is null)
  61. {
  62. return;
  63. }
  64. if (Initialized)
  65. {
  66. throw new InvalidOperationException ("Init has already been called and must be bracketed by Shutdown.");
  67. }
  68. if (!calledViaRunT)
  69. {
  70. // Reset all class variables (Application is a singleton).
  71. ResetState (ignoreDisposed: true);
  72. }
  73. // For UnitTests
  74. if (driver is { })
  75. {
  76. Driver = driver;
  77. }
  78. // Ignore Configuration for ForceDriver if driverName is specified
  79. if (!string.IsNullOrEmpty (driverName))
  80. {
  81. ForceDriver = driverName;
  82. }
  83. if (Driver is null)
  84. {
  85. PlatformID p = Environment.OSVersion.Platform;
  86. if (string.IsNullOrEmpty (ForceDriver))
  87. {
  88. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  89. {
  90. Driver = new WindowsDriver ();
  91. }
  92. else
  93. {
  94. Driver = new CursesDriver ();
  95. }
  96. }
  97. else
  98. {
  99. (List<Type?> drivers, List<string?> driverTypeNames) = GetDriverTypes ();
  100. Type? driverType = drivers.FirstOrDefault (t => t!.Name.Equals (ForceDriver, StringComparison.InvariantCultureIgnoreCase));
  101. if (driverType is { })
  102. {
  103. Driver = (IConsoleDriver)Activator.CreateInstance (driverType)!;
  104. }
  105. else if (ForceDriver?.StartsWith ("v2") ?? false)
  106. {
  107. ApplicationImpl.ChangeInstance (new ApplicationV2 ());
  108. ApplicationImpl.Instance.Init (driver, ForceDriver);
  109. Debug.Assert (Driver is { });
  110. return;
  111. }
  112. else
  113. {
  114. throw new ArgumentException (
  115. $"Invalid driver name: {ForceDriver}. Valid names are {string.Join (", ", drivers.Select (t => t!.Name))}"
  116. );
  117. }
  118. }
  119. }
  120. Debug.Assert (Navigation is null);
  121. Navigation = new ();
  122. Debug.Assert (Popover is null);
  123. Popover = new ();
  124. AddKeyBindings ();
  125. try
  126. {
  127. MainLoop = Driver!.Init ();
  128. SubscribeDriverEvents ();
  129. }
  130. catch (InvalidOperationException ex)
  131. {
  132. // This is a case where the driver is unable to initialize the console.
  133. // This can happen if the console is already in use by another process or
  134. // if running in unit tests.
  135. // In this case, we want to throw a more specific exception.
  136. throw new InvalidOperationException (
  137. "Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.",
  138. ex
  139. );
  140. }
  141. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  142. // TODO: This is probably not needed
  143. if (Popover.GetActivePopover () is View popover)
  144. {
  145. popover.Visible = false;
  146. }
  147. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  148. bool init = Initialized = true;
  149. InitializedChanged?.Invoke (null, new (init));
  150. }
  151. internal static void SubscribeDriverEvents ()
  152. {
  153. ArgumentNullException.ThrowIfNull (Driver);
  154. Driver.SizeChanged += Driver_SizeChanged;
  155. Driver.KeyDown += Driver_KeyDown;
  156. Driver.KeyUp += Driver_KeyUp;
  157. Driver.MouseEvent += Driver_MouseEvent;
  158. }
  159. internal static void UnsubscribeDriverEvents ()
  160. {
  161. ArgumentNullException.ThrowIfNull (Driver);
  162. Driver.SizeChanged -= Driver_SizeChanged;
  163. Driver.KeyDown -= Driver_KeyDown;
  164. Driver.KeyUp -= Driver_KeyUp;
  165. Driver.MouseEvent -= Driver_MouseEvent;
  166. }
  167. private static void Driver_SizeChanged (object? sender, SizeChangedEventArgs e) { OnSizeChanging (e); }
  168. private static void Driver_KeyDown (object? sender, Key e) { RaiseKeyDownEvent (e); }
  169. private static void Driver_KeyUp (object? sender, Key e) { RaiseKeyUpEvent (e); }
  170. private static void Driver_MouseEvent (object? sender, MouseEventArgs e) { RaiseMouseEvent (e); }
  171. /// <summary>Gets of list of <see cref="IConsoleDriver"/> types and type names that are available.</summary>
  172. /// <returns></returns>
  173. [RequiresUnreferencedCode ("AOT")]
  174. public static (List<Type?>, List<string?>) GetDriverTypes ()
  175. {
  176. // use reflection to get the list of drivers
  177. List<Type?> driverTypes = new ();
  178. // Only inspect the IConsoleDriver assembly
  179. var asm = typeof (IConsoleDriver).Assembly;
  180. foreach (Type? type in asm.GetTypes ())
  181. {
  182. if (typeof (IConsoleDriver).IsAssignableFrom (type) &&
  183. type is { IsAbstract: false, IsClass: true })
  184. {
  185. driverTypes.Add (type);
  186. }
  187. }
  188. List<string?> driverTypeNames = driverTypes
  189. .Where (d => !typeof (IConsoleDriverFacade).IsAssignableFrom (d))
  190. .Select (d => d!.Name)
  191. .Union (["v2", "v2win", "v2net", "v2unix"])
  192. .ToList ()!;
  193. return (driverTypes, driverTypeNames);
  194. }
  195. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  196. /// <remarks>
  197. /// Shutdown must be called for every call to <see cref="Init"/> or
  198. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to ensure all resources are cleaned
  199. /// up (Disposed)
  200. /// and terminal settings are restored.
  201. /// </remarks>
  202. public static void Shutdown () => ApplicationImpl.Instance.Shutdown ();
  203. /// <summary>
  204. /// Gets whether the application has been initialized with <see cref="Init"/> and not yet shutdown with <see cref="Shutdown"/>.
  205. /// </summary>
  206. /// <remarks>
  207. /// <para>
  208. /// The <see cref="InitializedChanged"/> event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  209. /// </para>
  210. /// </remarks>
  211. public static bool Initialized { get; internal set; }
  212. /// <summary>
  213. /// This event is raised after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  214. /// </summary>
  215. /// <remarks>
  216. /// Intended to support unit tests that need to know when the application has been initialized.
  217. /// </remarks>
  218. public static event EventHandler<EventArgs<bool>>? InitializedChanged;
  219. /// <summary>
  220. /// Raises the <see cref="InitializedChanged"/> event.
  221. /// </summary>
  222. internal static void OnInitializedChanged (object sender, EventArgs<bool> e)
  223. {
  224. Application.InitializedChanged?.Invoke (sender, e);
  225. }
  226. }