ApplicationImpl.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 IConsoleDriver? _driver;
  19. private bool _initialized;
  20. private ApplicationPopover? _popover;
  21. private ApplicationNavigation? _navigation;
  22. private Toplevel? _top;
  23. private readonly ConcurrentStack<Toplevel> _topLevels = new ();
  24. private int _mainThreadId = -1;
  25. // Private static readonly Lazy instance of Application
  26. private static Lazy<IApplication> _lazyInstance = new (() => new ApplicationImpl ());
  27. /// <summary>
  28. /// Gets the currently configured backend implementation of <see cref="Application"/> gateway methods.
  29. /// Change to your own implementation by using <see cref="ChangeInstance"/> (before init).
  30. /// </summary>
  31. public static IApplication Instance => _lazyInstance.Value;
  32. /// <inheritdoc/>
  33. public ITimedEvents? TimedEvents => _timedEvents;
  34. internal IMainLoopCoordinator? Coordinator => _coordinator;
  35. private IMouse? _mouse;
  36. /// <summary>
  37. /// Handles mouse event state and processing.
  38. /// </summary>
  39. public IMouse Mouse
  40. {
  41. get
  42. {
  43. if (_mouse is null)
  44. {
  45. _mouse = new MouseImpl { Application = this };
  46. }
  47. return _mouse;
  48. }
  49. set => _mouse = value ?? throw new ArgumentNullException (nameof (value));
  50. }
  51. /// <summary>
  52. /// Handles which <see cref="View"/> (if any) has captured the mouse
  53. /// </summary>
  54. public IMouseGrabHandler MouseGrabHandler { get; set; } = new MouseGrabHandler ();
  55. private IKeyboard? _keyboard;
  56. /// <summary>
  57. /// Handles keyboard input and key bindings at the Application level
  58. /// </summary>
  59. public IKeyboard Keyboard
  60. {
  61. get
  62. {
  63. if (_keyboard is null)
  64. {
  65. _keyboard = new KeyboardImpl { Application = this };
  66. }
  67. return _keyboard;
  68. }
  69. set => _keyboard = value ?? throw new ArgumentNullException (nameof (value));
  70. }
  71. /// <inheritdoc/>
  72. public IConsoleDriver? Driver
  73. {
  74. get => _driver;
  75. set => _driver = value;
  76. }
  77. /// <inheritdoc/>
  78. public bool Initialized
  79. {
  80. get => _initialized;
  81. set => _initialized = value;
  82. }
  83. /// <inheritdoc/>
  84. public ApplicationPopover? Popover
  85. {
  86. get => _popover;
  87. set => _popover = value;
  88. }
  89. /// <inheritdoc/>
  90. public ApplicationNavigation? Navigation
  91. {
  92. get => _navigation;
  93. set => _navigation = value;
  94. }
  95. /// <inheritdoc/>
  96. public Toplevel? Top
  97. {
  98. get => _top;
  99. set => _top = value;
  100. }
  101. /// <inheritdoc/>
  102. public ConcurrentStack<Toplevel> TopLevels => _topLevels;
  103. /// <summary>
  104. /// Gets or sets the main thread ID for the application.
  105. /// </summary>
  106. internal int MainThreadId
  107. {
  108. get => _mainThreadId;
  109. set => _mainThreadId = value;
  110. }
  111. /// <inheritdoc/>
  112. public void RequestStop () => RequestStop (null);
  113. /// <summary>
  114. /// Creates a new instance of the Application backend.
  115. /// </summary>
  116. public ApplicationImpl ()
  117. {
  118. }
  119. internal ApplicationImpl (IComponentFactory componentFactory)
  120. {
  121. _componentFactory = componentFactory;
  122. }
  123. /// <summary>
  124. /// Change the singleton implementation, should not be called except before application
  125. /// startup. This method lets you provide alternative implementations of core static gateway
  126. /// methods of <see cref="Application"/>.
  127. /// </summary>
  128. /// <param name="newApplication"></param>
  129. public static void ChangeInstance (IApplication newApplication)
  130. {
  131. _lazyInstance = new Lazy<IApplication> (newApplication);
  132. }
  133. /// <inheritdoc/>
  134. [RequiresUnreferencedCode ("AOT")]
  135. [RequiresDynamicCode ("AOT")]
  136. public void Init (IConsoleDriver? driver = null, string? driverName = null)
  137. {
  138. if (_initialized)
  139. {
  140. Logging.Logger.LogError ("Init called multiple times without shutdown, aborting.");
  141. throw new InvalidOperationException ("Init called multiple times without Shutdown");
  142. }
  143. if (!string.IsNullOrWhiteSpace (driverName))
  144. {
  145. _driverName = driverName;
  146. }
  147. if (string.IsNullOrWhiteSpace (_driverName))
  148. {
  149. _driverName = Application.ForceDriver;
  150. }
  151. Debug.Assert(_navigation is null);
  152. _navigation = new ();
  153. Debug.Assert (_popover is null);
  154. _popover = new ();
  155. // Preserve existing keyboard settings if they exist
  156. bool hasExistingKeyboard = _keyboard is not null;
  157. Key existingQuitKey = _keyboard?.QuitKey ?? Key.Esc;
  158. Key existingArrangeKey = _keyboard?.ArrangeKey ?? Key.F5.WithCtrl;
  159. Key existingNextTabKey = _keyboard?.NextTabKey ?? Key.Tab;
  160. Key existingPrevTabKey = _keyboard?.PrevTabKey ?? Key.Tab.WithShift;
  161. Key existingNextTabGroupKey = _keyboard?.NextTabGroupKey ?? Key.F6;
  162. Key existingPrevTabGroupKey = _keyboard?.PrevTabGroupKey ?? Key.F6.WithShift;
  163. // Reset keyboard to ensure fresh state with default bindings
  164. _keyboard = new KeyboardImpl { Application = this };
  165. // Restore previously set keys if they existed and were different from defaults
  166. if (hasExistingKeyboard)
  167. {
  168. _keyboard.QuitKey = existingQuitKey;
  169. _keyboard.ArrangeKey = existingArrangeKey;
  170. _keyboard.NextTabKey = existingNextTabKey;
  171. _keyboard.PrevTabKey = existingPrevTabKey;
  172. _keyboard.NextTabGroupKey = existingNextTabGroupKey;
  173. _keyboard.PrevTabGroupKey = existingPrevTabGroupKey;
  174. }
  175. CreateDriver (driverName ?? _driverName);
  176. _initialized = true;
  177. Application.OnInitializedChanged (this, new (true));
  178. Application.SubscribeDriverEvents ();
  179. SynchronizationContext.SetSynchronizationContext (new ());
  180. _mainThreadId = Thread.CurrentThread.ManagedThreadId;
  181. }
  182. private void CreateDriver (string? driverName)
  183. {
  184. // When running unit tests, always use FakeDriver unless explicitly specified
  185. if (ConsoleDriver.RunningUnitTests &&
  186. string.IsNullOrEmpty (driverName) &&
  187. _componentFactory is null)
  188. {
  189. Logging.Logger.LogDebug ("Unit test safeguard: forcing FakeDriver (RunningUnitTests=true, driverName=null, componentFactory=null)");
  190. _coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  191. _coordinator.StartAsync ().Wait ();
  192. if (_driver == null)
  193. {
  194. throw new ("Driver was null even after booting MainLoopCoordinator");
  195. }
  196. return;
  197. }
  198. PlatformID p = Environment.OSVersion.Platform;
  199. // Check component factory type first - this takes precedence over driverName
  200. bool factoryIsWindows = _componentFactory is IComponentFactory<WindowsConsole.InputRecord>;
  201. bool factoryIsDotNet = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  202. bool factoryIsUnix = _componentFactory is IComponentFactory<char>;
  203. bool factoryIsFake = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  204. // Then check driverName
  205. bool nameIsWindows = driverName?.Contains ("win", StringComparison.OrdinalIgnoreCase) ?? false;
  206. bool nameIsDotNet = (driverName?.Contains ("dotnet", StringComparison.OrdinalIgnoreCase) ?? false);
  207. bool nameIsUnix = driverName?.Contains ("unix", StringComparison.OrdinalIgnoreCase) ?? false;
  208. bool nameIsFake = driverName?.Contains ("fake", StringComparison.OrdinalIgnoreCase) ?? false;
  209. // Decide which driver to use - component factory type takes priority
  210. if (factoryIsFake || (!factoryIsWindows && !factoryIsDotNet && !factoryIsUnix && nameIsFake))
  211. {
  212. _coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  213. }
  214. else if (factoryIsWindows || (!factoryIsDotNet && !factoryIsUnix && nameIsWindows))
  215. {
  216. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  217. }
  218. else if (factoryIsDotNet || (!factoryIsWindows && !factoryIsUnix && nameIsDotNet))
  219. {
  220. _coordinator = CreateSubcomponents (() => new NetComponentFactory ());
  221. }
  222. else if (factoryIsUnix || (!factoryIsWindows && !factoryIsDotNet && nameIsUnix))
  223. {
  224. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  225. }
  226. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  227. {
  228. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  229. }
  230. else
  231. {
  232. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  233. }
  234. _coordinator.StartAsync ().Wait ();
  235. if (_driver == null)
  236. {
  237. throw new ("Driver was null even after booting MainLoopCoordinator");
  238. }
  239. }
  240. private IMainLoopCoordinator CreateSubcomponents<T> (Func<IComponentFactory<T>> fallbackFactory)
  241. {
  242. ConcurrentQueue<T> inputBuffer = new ();
  243. ApplicationMainLoop<T> loop = new ();
  244. IComponentFactory<T> cf;
  245. if (_componentFactory is IComponentFactory<T> typedFactory)
  246. {
  247. cf = typedFactory;
  248. }
  249. else
  250. {
  251. cf = fallbackFactory ();
  252. }
  253. return new MainLoopCoordinator<T> (_timedEvents, inputBuffer, loop, cf);
  254. }
  255. /// <summary>
  256. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  257. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  258. /// </summary>
  259. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  260. [RequiresUnreferencedCode ("AOT")]
  261. [RequiresDynamicCode ("AOT")]
  262. public Toplevel Run (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  263. /// <summary>
  264. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  265. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  266. /// </summary>
  267. /// <param name="errorHandler"></param>
  268. /// <param name="driver">
  269. /// The <see cref="IConsoleDriver"/> to use. If not specified the default driver for the platform will
  270. /// be used. Must be <see langword="null"/> if <see cref="Init"/> has already been called.
  271. /// </param>
  272. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  273. [RequiresUnreferencedCode ("AOT")]
  274. [RequiresDynamicCode ("AOT")]
  275. public T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  276. where T : Toplevel, new()
  277. {
  278. if (!_initialized)
  279. {
  280. // Init() has NOT been called. Auto-initialize as per interface contract.
  281. Init (driver, null);
  282. }
  283. T top = new ();
  284. Run (top, errorHandler);
  285. return top;
  286. }
  287. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  288. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  289. /// <param name="errorHandler">Handler for any unhandled exceptions.</param>
  290. public void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  291. {
  292. Logging.Information ($"Run '{view}'");
  293. ArgumentNullException.ThrowIfNull (view);
  294. if (!_initialized)
  295. {
  296. throw new NotInitializedException (nameof (Run));
  297. }
  298. if (_driver == null)
  299. {
  300. throw new InvalidOperationException ("Driver was inexplicably null when trying to Run view");
  301. }
  302. _top = view;
  303. RunState rs = Application.Begin (view);
  304. _top.Running = true;
  305. while (_topLevels.TryPeek (out Toplevel? found) && found == view && view.Running)
  306. {
  307. if (_coordinator is null)
  308. {
  309. throw new ($"{nameof (IMainLoopCoordinator)} inexplicably became null during Run");
  310. }
  311. _coordinator.RunIteration ();
  312. }
  313. Logging.Information ($"Run - Calling End");
  314. Application.End (rs);
  315. }
  316. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  317. public void Shutdown ()
  318. {
  319. _coordinator?.Stop ();
  320. bool wasInitialized = _initialized;
  321. // Call ResetState FIRST so it can properly dispose Popover and other resources
  322. // that are accessed via Application.* static properties that now delegate to instance fields
  323. Application.ResetState ();
  324. ConfigurationManager.PrintJsonErrors ();
  325. // Clear instance fields after ResetState has disposed everything
  326. _driver = null;
  327. _mouse = null;
  328. _keyboard = null;
  329. _initialized = false;
  330. _navigation = null;
  331. _popover = null;
  332. _top = null;
  333. _topLevels.Clear ();
  334. _mainThreadId = -1;
  335. if (wasInitialized)
  336. {
  337. bool init = _initialized; // Will be false after clearing fields above
  338. Application.OnInitializedChanged (this, new (in init));
  339. }
  340. _lazyInstance = new (() => new ApplicationImpl ());
  341. }
  342. /// <inheritdoc />
  343. public void RequestStop (Toplevel? top)
  344. {
  345. Logging.Logger.LogInformation ($"RequestStop '{(top is {} ? top : "null")}'");
  346. top ??= _top;
  347. if (top == null)
  348. {
  349. return;
  350. }
  351. ToplevelClosingEventArgs ev = new (top);
  352. top.OnClosing (ev);
  353. if (ev.Cancel)
  354. {
  355. return;
  356. }
  357. top.Running = false;
  358. }
  359. /// <inheritdoc />
  360. public void Invoke (Action action)
  361. {
  362. // If we are already on the main UI thread
  363. if (_mainThreadId == Thread.CurrentThread.ManagedThreadId)
  364. {
  365. action ();
  366. return;
  367. }
  368. _timedEvents.Add (TimeSpan.Zero,
  369. () =>
  370. {
  371. action ();
  372. return false;
  373. }
  374. );
  375. }
  376. /// <inheritdoc />
  377. public bool IsLegacy => false;
  378. /// <inheritdoc />
  379. public object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.Add (time, callback); }
  380. /// <inheritdoc />
  381. public bool RemoveTimeout (object token) { return _timedEvents.Remove (token); }
  382. /// <inheritdoc />
  383. public void LayoutAndDraw (bool forceRedraw = false)
  384. {
  385. List<View> tops = [.. _topLevels];
  386. if (_popover?.GetActivePopover () as View is { Visible: true } visiblePopover)
  387. {
  388. visiblePopover.SetNeedsDraw ();
  389. visiblePopover.SetNeedsLayout ();
  390. tops.Insert (0, visiblePopover);
  391. }
  392. // BUGBUG: Application.Screen needs to be moved to IApplication
  393. bool neededLayout = View.Layout (tops.ToArray ().Reverse (), Application.Screen.Size);
  394. // BUGBUG: Application.ClearScreenNextIteration needs to be moved to IApplication
  395. if (Application.ClearScreenNextIteration)
  396. {
  397. forceRedraw = true;
  398. // BUGBUG: Application.Screen needs to be moved to IApplication
  399. Application.ClearScreenNextIteration = false;
  400. }
  401. if (forceRedraw)
  402. {
  403. _driver?.ClearContents ();
  404. }
  405. View.SetClipToScreen ();
  406. View.Draw (tops, neededLayout || forceRedraw);
  407. View.SetClipToScreen ();
  408. _driver?.Refresh ();
  409. }
  410. }