ApplicationImpl.cs 17 KB

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