ApplicationImpl.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using Microsoft.Extensions.Logging;
  6. using Terminal.Gui.Drivers;
  7. namespace Terminal.Gui.App;
  8. /// <summary>
  9. /// Implementation of core <see cref="Application"/> methods using the modern
  10. /// main loop architecture with component factories for different platforms.
  11. /// </summary>
  12. public class ApplicationImpl : IApplication
  13. {
  14. private readonly IComponentFactory? _componentFactory;
  15. private IMainLoopCoordinator? _coordinator;
  16. private string? _driverName;
  17. private readonly ITimedEvents _timedEvents = new TimedEvents ();
  18. // Private static readonly Lazy instance of Application
  19. private static Lazy<IApplication> _lazyInstance = new (() => new ApplicationImpl ());
  20. /// <summary>
  21. /// Gets the currently configured backend implementation of <see cref="Application"/> gateway methods.
  22. /// Change to your own implementation by using <see cref="ChangeInstance"/> (before init).
  23. /// </summary>
  24. public static IApplication Instance => _lazyInstance.Value;
  25. /// <inheritdoc/>
  26. public ITimedEvents? TimedEvents => _timedEvents;
  27. internal IMainLoopCoordinator? Coordinator => _coordinator;
  28. /// <summary>
  29. /// Handles which <see cref="View"/> (if any) has captured the mouse
  30. /// </summary>
  31. public IMouseGrabHandler MouseGrabHandler { get; set; } = new MouseGrabHandler ();
  32. /// <summary>
  33. /// Creates a new instance of the Application backend.
  34. /// </summary>
  35. public ApplicationImpl ()
  36. {
  37. }
  38. internal ApplicationImpl (IComponentFactory componentFactory)
  39. {
  40. _componentFactory = componentFactory;
  41. }
  42. /// <summary>
  43. /// Change the singleton implementation, should not be called except before application
  44. /// startup. This method lets you provide alternative implementations of core static gateway
  45. /// methods of <see cref="Application"/>.
  46. /// </summary>
  47. /// <param name="newApplication"></param>
  48. public static void ChangeInstance (IApplication newApplication)
  49. {
  50. _lazyInstance = new Lazy<IApplication> (newApplication);
  51. }
  52. /// <inheritdoc/>
  53. [RequiresUnreferencedCode ("AOT")]
  54. [RequiresDynamicCode ("AOT")]
  55. public void Init (IConsoleDriver? driver = null, string? driverName = null)
  56. {
  57. if (Application.Initialized)
  58. {
  59. Logging.Logger.LogError ("Init called multiple times without shutdown, aborting.");
  60. throw new InvalidOperationException ("Init called multiple times without Shutdown");
  61. }
  62. if (!string.IsNullOrWhiteSpace (driverName))
  63. {
  64. _driverName = driverName;
  65. }
  66. if (string.IsNullOrWhiteSpace (_driverName))
  67. {
  68. _driverName = Application.ForceDriver;
  69. }
  70. Debug.Assert(Application.Navigation is null);
  71. Application.Navigation = new ();
  72. Debug.Assert (Application.Popover is null);
  73. Application.Popover = new ();
  74. Application.AddKeyBindings ();
  75. CreateDriver (driverName ?? _driverName);
  76. Application.Initialized = true;
  77. Application.OnInitializedChanged (this, new (true));
  78. Application.SubscribeDriverEvents ();
  79. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  80. Application.MainThreadId = Thread.CurrentThread.ManagedThreadId;
  81. }
  82. private void CreateDriver (string? driverName)
  83. {
  84. // When running unit tests, always use FakeDriver unless explicitly specified
  85. if (ConsoleDriver.RunningUnitTests &&
  86. string.IsNullOrEmpty (driverName) &&
  87. _componentFactory is null)
  88. {
  89. Logging.Logger.LogDebug ("Unit test safeguard: forcing FakeDriver (RunningUnitTests=true, driverName=null, componentFactory=null)");
  90. _coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  91. _coordinator.StartAsync ().Wait ();
  92. if (Application.Driver == null)
  93. {
  94. throw new ("Application.Driver was null even after booting MainLoopCoordinator");
  95. }
  96. return;
  97. }
  98. PlatformID p = Environment.OSVersion.Platform;
  99. // Check component factory type first - this takes precedence over driverName
  100. bool factoryIsWindows = _componentFactory is IComponentFactory<WindowsConsole.InputRecord>;
  101. bool factoryIsDotNet = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  102. bool factoryIsUnix = _componentFactory is IComponentFactory<char>;
  103. bool factoryIsFake = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  104. // Then check driverName
  105. bool nameIsWindows = driverName?.Contains ("win", StringComparison.OrdinalIgnoreCase) ?? false;
  106. bool nameIsDotNet = (driverName?.Contains ("dotnet", StringComparison.OrdinalIgnoreCase) ?? false);
  107. bool nameIsUnix = driverName?.Contains ("unix", StringComparison.OrdinalIgnoreCase) ?? false;
  108. bool nameIsFake = driverName?.Contains ("fake", StringComparison.OrdinalIgnoreCase) ?? false;
  109. // Decide which driver to use - component factory type takes priority
  110. if (factoryIsFake || (!factoryIsWindows && !factoryIsDotNet && !factoryIsUnix && nameIsFake))
  111. {
  112. _coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  113. }
  114. else if (factoryIsWindows || (!factoryIsDotNet && !factoryIsUnix && nameIsWindows))
  115. {
  116. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  117. }
  118. else if (factoryIsDotNet || (!factoryIsWindows && !factoryIsUnix && nameIsDotNet))
  119. {
  120. _coordinator = CreateSubcomponents (() => new NetComponentFactory ());
  121. }
  122. else if (factoryIsUnix || (!factoryIsWindows && !factoryIsDotNet && nameIsUnix))
  123. {
  124. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  125. }
  126. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  127. {
  128. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  129. }
  130. else
  131. {
  132. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  133. }
  134. _coordinator.StartAsync ().Wait ();
  135. if (Application.Driver == null)
  136. {
  137. throw new ("Application.Driver was null even after booting MainLoopCoordinator");
  138. }
  139. }
  140. private IMainLoopCoordinator CreateSubcomponents<T> (Func<IComponentFactory<T>> fallbackFactory)
  141. {
  142. ConcurrentQueue<T> inputBuffer = new ();
  143. ApplicationMainLoop<T> loop = new ();
  144. IComponentFactory<T> cf;
  145. if (_componentFactory is IComponentFactory<T> typedFactory)
  146. {
  147. cf = typedFactory;
  148. }
  149. else
  150. {
  151. cf = fallbackFactory ();
  152. }
  153. return new MainLoopCoordinator<T> (_timedEvents, inputBuffer, loop, cf);
  154. }
  155. /// <summary>
  156. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  157. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  158. /// </summary>
  159. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  160. [RequiresUnreferencedCode ("AOT")]
  161. [RequiresDynamicCode ("AOT")]
  162. public Toplevel Run (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  163. /// <summary>
  164. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  165. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  166. /// </summary>
  167. /// <param name="errorHandler"></param>
  168. /// <param name="driver">
  169. /// The <see cref="IConsoleDriver"/> to use. If not specified the default driver for the platform will
  170. /// be used. Must be <see langword="null"/> if <see cref="Init"/> has already been called.
  171. /// </param>
  172. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  173. [RequiresUnreferencedCode ("AOT")]
  174. [RequiresDynamicCode ("AOT")]
  175. public T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  176. where T : Toplevel, new()
  177. {
  178. if (!Application.Initialized)
  179. {
  180. // Init() has NOT been called. Auto-initialize as per interface contract.
  181. Init (driver, null);
  182. }
  183. var top = new T ();
  184. Run (top, errorHandler);
  185. return top;
  186. }
  187. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  188. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  189. /// <param name="errorHandler">Handler for any unhandled exceptions.</param>
  190. public void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  191. {
  192. Logging.Information ($"Run '{view}'");
  193. ArgumentNullException.ThrowIfNull (view);
  194. if (!Application.Initialized)
  195. {
  196. throw new NotInitializedException (nameof (Run));
  197. }
  198. if (Application.Driver == null)
  199. {
  200. throw new InvalidOperationException ("Driver was inexplicably null when trying to Run view");
  201. }
  202. Application.Top = view;
  203. RunState rs = Application.Begin (view);
  204. Application.Top.Running = true;
  205. while (Application.TopLevels.TryPeek (out Toplevel? found) && found == view && view.Running)
  206. {
  207. if (_coordinator is null)
  208. {
  209. throw new ($"{nameof (IMainLoopCoordinator)} inexplicably became null during Run");
  210. }
  211. _coordinator.RunIteration ();
  212. }
  213. Logging.Information ($"Run - Calling End");
  214. Application.End (rs);
  215. }
  216. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  217. public void Shutdown ()
  218. {
  219. _coordinator?.Stop ();
  220. bool wasInitialized = Application.Initialized;
  221. Application.ResetState ();
  222. ConfigurationManager.PrintJsonErrors ();
  223. if (wasInitialized)
  224. {
  225. bool init = Application.Initialized;
  226. Application.OnInitializedChanged (this, new (in init));
  227. }
  228. Application.Driver = null;
  229. _lazyInstance = new (() => new ApplicationImpl ());
  230. }
  231. /// <inheritdoc />
  232. public void RequestStop (Toplevel? top)
  233. {
  234. Logging.Logger.LogInformation ($"RequestStop '{(top is {} ? top : "null")}'");
  235. top ??= Application.Top;
  236. if (top == null)
  237. {
  238. return;
  239. }
  240. var ev = new ToplevelClosingEventArgs (top);
  241. top.OnClosing (ev);
  242. if (ev.Cancel)
  243. {
  244. return;
  245. }
  246. top.Running = false;
  247. }
  248. /// <inheritdoc />
  249. public void Invoke (Action action)
  250. {
  251. // If we are already on the main UI thread
  252. if (Application.MainThreadId == Thread.CurrentThread.ManagedThreadId)
  253. {
  254. action ();
  255. return;
  256. }
  257. _timedEvents.Add (TimeSpan.Zero,
  258. () =>
  259. {
  260. action ();
  261. return false;
  262. }
  263. );
  264. }
  265. /// <inheritdoc />
  266. public bool IsLegacy => false;
  267. /// <inheritdoc />
  268. public object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.Add (time, callback); }
  269. /// <inheritdoc />
  270. public bool RemoveTimeout (object token) { return _timedEvents.Remove (token); }
  271. /// <inheritdoc />
  272. public void LayoutAndDraw (bool forceDraw)
  273. {
  274. Application.Top?.SetNeedsDraw();
  275. Application.Top?.SetNeedsLayout ();
  276. }
  277. }