ApplicationImpl.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Globalization;
  6. using System.Reflection;
  7. using System.Resources;
  8. using Microsoft.Extensions.Logging;
  9. using Terminal.Gui.Drivers;
  10. namespace Terminal.Gui.App;
  11. /// <summary>
  12. /// Implementation of core <see cref="Application"/> methods using the modern
  13. /// main loop architecture with component factories for different platforms.
  14. /// </summary>
  15. public class ApplicationImpl : IApplication
  16. {
  17. private readonly IComponentFactory? _componentFactory;
  18. private IMainLoopCoordinator? _coordinator;
  19. private string? _driverName;
  20. private readonly ITimedEvents _timedEvents = new TimedEvents ();
  21. private IConsoleDriver? _driver;
  22. private bool _initialized;
  23. private ApplicationPopover? _popover;
  24. private ApplicationNavigation? _navigation;
  25. private Toplevel? _top;
  26. private readonly ConcurrentStack<Toplevel> _topLevels = new ();
  27. private int _mainThreadId = -1;
  28. private bool _force16Colors;
  29. private string _forceDriver = string.Empty;
  30. private readonly List<SixelToRender> _sixel = new ();
  31. private readonly object _lockScreen = new ();
  32. private Rectangle? _screen;
  33. private bool _clearScreenNextIteration;
  34. private ushort _maximumIterationsPerSecond = 25; // Default value for MaximumIterationsPerSecond
  35. private List<CultureInfo>? _supportedCultures;
  36. // When `End ()` is called, it is possible `RunState.Toplevel` is a different object than `Top`.
  37. // This variable is set in `End` in this case so that `Begin` correctly sets `Top`.
  38. internal Toplevel? _cachedRunStateToplevel;
  39. // Private static readonly Lazy instance of Application
  40. private static Lazy<IApplication> _lazyInstance = new (() => new ApplicationImpl ());
  41. /// <summary>
  42. /// Gets the currently configured backend implementation of <see cref="Application"/> gateway methods.
  43. /// Change to your own implementation by using <see cref="ChangeInstance"/> (before init).
  44. /// </summary>
  45. public static IApplication Instance => _lazyInstance.Value;
  46. /// <inheritdoc/>
  47. public ITimedEvents? TimedEvents => _timedEvents;
  48. internal IMainLoopCoordinator? Coordinator => _coordinator;
  49. private IMouse? _mouse;
  50. /// <summary>
  51. /// Handles mouse event state and processing.
  52. /// </summary>
  53. public IMouse Mouse
  54. {
  55. get
  56. {
  57. if (_mouse is null)
  58. {
  59. _mouse = new MouseImpl { Application = this };
  60. }
  61. return _mouse;
  62. }
  63. set => _mouse = value ?? throw new ArgumentNullException (nameof (value));
  64. }
  65. /// <summary>
  66. /// Handles which <see cref="View"/> (if any) has captured the mouse
  67. /// </summary>
  68. public IMouseGrabHandler MouseGrabHandler { get; set; } = new MouseGrabHandler ();
  69. private IKeyboard? _keyboard;
  70. /// <summary>
  71. /// Handles keyboard input and key bindings at the Application level
  72. /// </summary>
  73. public IKeyboard Keyboard
  74. {
  75. get
  76. {
  77. if (_keyboard is null)
  78. {
  79. _keyboard = new KeyboardImpl { Application = this };
  80. }
  81. return _keyboard;
  82. }
  83. set => _keyboard = value ?? throw new ArgumentNullException (nameof (value));
  84. }
  85. /// <inheritdoc/>
  86. public IConsoleDriver? Driver
  87. {
  88. get => _driver;
  89. set => _driver = value;
  90. }
  91. /// <inheritdoc/>
  92. public bool Initialized
  93. {
  94. get => _initialized;
  95. set => _initialized = value;
  96. }
  97. /// <inheritdoc/>
  98. public bool Force16Colors
  99. {
  100. get => _force16Colors;
  101. set => _force16Colors = value;
  102. }
  103. /// <inheritdoc/>
  104. public string ForceDriver
  105. {
  106. get => _forceDriver;
  107. set => _forceDriver = value;
  108. }
  109. /// <inheritdoc/>
  110. public List<SixelToRender> Sixel => _sixel;
  111. /// <inheritdoc/>
  112. public Rectangle Screen
  113. {
  114. get
  115. {
  116. lock (_lockScreen)
  117. {
  118. if (_screen == null)
  119. {
  120. _screen = Driver?.Screen ?? new (new (0, 0), new (2048, 2048));
  121. }
  122. return _screen.Value;
  123. }
  124. }
  125. set
  126. {
  127. if (value is {} && (value.X != 0 || value.Y != 0))
  128. {
  129. throw new NotImplementedException ($"Screen locations other than 0, 0 are not yet supported");
  130. }
  131. lock (_lockScreen)
  132. {
  133. _screen = value;
  134. }
  135. }
  136. }
  137. /// <inheritdoc/>
  138. public bool ClearScreenNextIteration
  139. {
  140. get => _clearScreenNextIteration;
  141. set => _clearScreenNextIteration = value;
  142. }
  143. /// <inheritdoc/>
  144. public ApplicationPopover? Popover
  145. {
  146. get => _popover;
  147. set => _popover = value;
  148. }
  149. /// <inheritdoc/>
  150. public ApplicationNavigation? Navigation
  151. {
  152. get => _navigation;
  153. set => _navigation = value;
  154. }
  155. /// <inheritdoc/>
  156. public Toplevel? Top
  157. {
  158. get => _top;
  159. set => _top = value;
  160. }
  161. /// <inheritdoc/>
  162. public ConcurrentStack<Toplevel> TopLevels => _topLevels;
  163. /// <inheritdoc/>
  164. public ushort MaximumIterationsPerSecond
  165. {
  166. get => _maximumIterationsPerSecond;
  167. set => _maximumIterationsPerSecond = value;
  168. }
  169. /// <inheritdoc/>
  170. public List<CultureInfo>? SupportedCultures
  171. {
  172. get
  173. {
  174. if (_supportedCultures is null)
  175. {
  176. _supportedCultures = GetSupportedCultures ();
  177. }
  178. return _supportedCultures;
  179. }
  180. }
  181. /// <summary>
  182. /// Internal helper to raise InitializedChanged static event. Used by both legacy and modern Init paths.
  183. /// </summary>
  184. internal void RaiseInitializedChanged (bool initialized)
  185. {
  186. Application.OnInitializedChanged (this, new (initialized));
  187. }
  188. /// <summary>
  189. /// Gets or sets the main thread ID for the application.
  190. /// </summary>
  191. internal int MainThreadId
  192. {
  193. get => _mainThreadId;
  194. set => _mainThreadId = value;
  195. }
  196. /// <inheritdoc/>
  197. public void RequestStop () => RequestStop (null);
  198. /// <summary>
  199. /// Creates a new instance of the Application backend.
  200. /// </summary>
  201. public ApplicationImpl ()
  202. {
  203. }
  204. internal ApplicationImpl (IComponentFactory componentFactory)
  205. {
  206. _componentFactory = componentFactory;
  207. }
  208. /// <summary>
  209. /// Change the singleton implementation, should not be called except before application
  210. /// startup. This method lets you provide alternative implementations of core static gateway
  211. /// methods of <see cref="Application"/>.
  212. /// </summary>
  213. /// <param name="newApplication"></param>
  214. public static void ChangeInstance (IApplication newApplication)
  215. {
  216. _lazyInstance = new Lazy<IApplication> (newApplication);
  217. }
  218. /// <inheritdoc/>
  219. [RequiresUnreferencedCode ("AOT")]
  220. [RequiresDynamicCode ("AOT")]
  221. public void Init (IConsoleDriver? driver = null, string? driverName = null)
  222. {
  223. if (_initialized)
  224. {
  225. Logging.Logger.LogError ("Init called multiple times without shutdown, aborting.");
  226. throw new InvalidOperationException ("Init called multiple times without Shutdown");
  227. }
  228. if (!string.IsNullOrWhiteSpace (driverName))
  229. {
  230. _driverName = driverName;
  231. }
  232. if (string.IsNullOrWhiteSpace (_driverName))
  233. {
  234. _driverName = _forceDriver;
  235. }
  236. Debug.Assert(_navigation is null);
  237. _navigation = new ();
  238. Debug.Assert (_popover is null);
  239. _popover = new ();
  240. // Preserve existing keyboard settings if they exist
  241. bool hasExistingKeyboard = _keyboard is not null;
  242. Key existingQuitKey = _keyboard?.QuitKey ?? Key.Esc;
  243. Key existingArrangeKey = _keyboard?.ArrangeKey ?? Key.F5.WithCtrl;
  244. Key existingNextTabKey = _keyboard?.NextTabKey ?? Key.Tab;
  245. Key existingPrevTabKey = _keyboard?.PrevTabKey ?? Key.Tab.WithShift;
  246. Key existingNextTabGroupKey = _keyboard?.NextTabGroupKey ?? Key.F6;
  247. Key existingPrevTabGroupKey = _keyboard?.PrevTabGroupKey ?? Key.F6.WithShift;
  248. // Reset keyboard to ensure fresh state with default bindings
  249. _keyboard = new KeyboardImpl { Application = this };
  250. // Restore previously set keys if they existed and were different from defaults
  251. if (hasExistingKeyboard)
  252. {
  253. _keyboard.QuitKey = existingQuitKey;
  254. _keyboard.ArrangeKey = existingArrangeKey;
  255. _keyboard.NextTabKey = existingNextTabKey;
  256. _keyboard.PrevTabKey = existingPrevTabKey;
  257. _keyboard.NextTabGroupKey = existingNextTabGroupKey;
  258. _keyboard.PrevTabGroupKey = existingPrevTabGroupKey;
  259. }
  260. CreateDriver (driverName ?? _driverName);
  261. _initialized = true;
  262. Application.OnInitializedChanged (this, new (true));
  263. SubscribeDriverEvents ();
  264. SynchronizationContext.SetSynchronizationContext (new ());
  265. _mainThreadId = Thread.CurrentThread.ManagedThreadId;
  266. }
  267. private void CreateDriver (string? driverName)
  268. {
  269. // When running unit tests, always use FakeDriver unless explicitly specified
  270. if (ConsoleDriver.RunningUnitTests &&
  271. string.IsNullOrEmpty (driverName) &&
  272. _componentFactory is null)
  273. {
  274. Logging.Logger.LogDebug ("Unit test safeguard: forcing FakeDriver (RunningUnitTests=true, driverName=null, componentFactory=null)");
  275. _coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  276. _coordinator.StartAsync ().Wait ();
  277. if (_driver == null)
  278. {
  279. throw new ("Driver was null even after booting MainLoopCoordinator");
  280. }
  281. return;
  282. }
  283. PlatformID p = Environment.OSVersion.Platform;
  284. // Check component factory type first - this takes precedence over driverName
  285. bool factoryIsWindows = _componentFactory is IComponentFactory<WindowsConsole.InputRecord>;
  286. bool factoryIsDotNet = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  287. bool factoryIsUnix = _componentFactory is IComponentFactory<char>;
  288. bool factoryIsFake = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  289. // Then check driverName
  290. bool nameIsWindows = driverName?.Contains ("win", StringComparison.OrdinalIgnoreCase) ?? false;
  291. bool nameIsDotNet = (driverName?.Contains ("dotnet", StringComparison.OrdinalIgnoreCase) ?? false);
  292. bool nameIsUnix = driverName?.Contains ("unix", StringComparison.OrdinalIgnoreCase) ?? false;
  293. bool nameIsFake = driverName?.Contains ("fake", StringComparison.OrdinalIgnoreCase) ?? false;
  294. // Decide which driver to use - component factory type takes priority
  295. if (factoryIsFake || (!factoryIsWindows && !factoryIsDotNet && !factoryIsUnix && nameIsFake))
  296. {
  297. _coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  298. }
  299. else if (factoryIsWindows || (!factoryIsDotNet && !factoryIsUnix && nameIsWindows))
  300. {
  301. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  302. }
  303. else if (factoryIsDotNet || (!factoryIsWindows && !factoryIsUnix && nameIsDotNet))
  304. {
  305. _coordinator = CreateSubcomponents (() => new NetComponentFactory ());
  306. }
  307. else if (factoryIsUnix || (!factoryIsWindows && !factoryIsDotNet && nameIsUnix))
  308. {
  309. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  310. }
  311. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  312. {
  313. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  314. }
  315. else
  316. {
  317. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  318. }
  319. _coordinator.StartAsync ().Wait ();
  320. if (_driver == null)
  321. {
  322. throw new ("Driver was null even after booting MainLoopCoordinator");
  323. }
  324. }
  325. private IMainLoopCoordinator CreateSubcomponents<T> (Func<IComponentFactory<T>> fallbackFactory)
  326. {
  327. ConcurrentQueue<T> inputBuffer = new ();
  328. ApplicationMainLoop<T> loop = new ();
  329. IComponentFactory<T> cf;
  330. if (_componentFactory is IComponentFactory<T> typedFactory)
  331. {
  332. cf = typedFactory;
  333. }
  334. else
  335. {
  336. cf = fallbackFactory ();
  337. }
  338. return new MainLoopCoordinator<T> (_timedEvents, inputBuffer, loop, cf);
  339. }
  340. /// <summary>
  341. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  342. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  343. /// </summary>
  344. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  345. [RequiresUnreferencedCode ("AOT")]
  346. [RequiresDynamicCode ("AOT")]
  347. public Toplevel Run (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  348. /// <summary>
  349. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  350. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  351. /// </summary>
  352. /// <param name="errorHandler"></param>
  353. /// <param name="driver">
  354. /// The <see cref="IConsoleDriver"/> to use. If not specified the default driver for the platform will
  355. /// be used. Must be <see langword="null"/> if <see cref="Init"/> has already been called.
  356. /// </param>
  357. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  358. [RequiresUnreferencedCode ("AOT")]
  359. [RequiresDynamicCode ("AOT")]
  360. public T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  361. where T : Toplevel, new()
  362. {
  363. if (!_initialized)
  364. {
  365. // Init() has NOT been called. Auto-initialize as per interface contract.
  366. Init (driver, null);
  367. }
  368. T top = new ();
  369. Run (top, errorHandler);
  370. return top;
  371. }
  372. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  373. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  374. /// <param name="errorHandler">Handler for any unhandled exceptions.</param>
  375. public void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  376. {
  377. Logging.Information ($"Run '{view}'");
  378. ArgumentNullException.ThrowIfNull (view);
  379. if (!_initialized)
  380. {
  381. throw new NotInitializedException (nameof (Run));
  382. }
  383. if (_driver == null)
  384. {
  385. throw new InvalidOperationException ("Driver was inexplicably null when trying to Run view");
  386. }
  387. _top = view;
  388. RunState rs = Application.Begin (view);
  389. _top.Running = true;
  390. while (_topLevels.TryPeek (out Toplevel? found) && found == view && view.Running)
  391. {
  392. if (_coordinator is null)
  393. {
  394. throw new ($"{nameof (IMainLoopCoordinator)} inexplicably became null during Run");
  395. }
  396. _coordinator.RunIteration ();
  397. }
  398. Logging.Information ($"Run - Calling End");
  399. Application.End (rs);
  400. }
  401. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  402. public void Shutdown ()
  403. {
  404. _coordinator?.Stop ();
  405. bool wasInitialized = _initialized;
  406. // Reset Screen before calling ResetState to avoid circular reference
  407. ResetScreen ();
  408. // Call ResetState FIRST so it can properly dispose Popover and other resources
  409. // that are accessed via Application.* static properties that now delegate to instance fields
  410. ResetState ();
  411. ConfigurationManager.PrintJsonErrors ();
  412. // Clear instance fields after ResetState has disposed everything
  413. _driver = null;
  414. _mouse = null;
  415. _keyboard = null;
  416. _initialized = false;
  417. _navigation = null;
  418. _popover = null;
  419. _top = null;
  420. _topLevels.Clear ();
  421. _mainThreadId = -1;
  422. _screen = null;
  423. _clearScreenNextIteration = false;
  424. _sixel.Clear ();
  425. // Don't reset ForceDriver and Force16Colors; they need to be set before Init is called
  426. if (wasInitialized)
  427. {
  428. bool init = _initialized; // Will be false after clearing fields above
  429. Application.OnInitializedChanged (this, new (in init));
  430. }
  431. _lazyInstance = new (() => new ApplicationImpl ());
  432. }
  433. /// <inheritdoc />
  434. public void RequestStop (Toplevel? top)
  435. {
  436. Logging.Logger.LogInformation ($"RequestStop '{(top is {} ? top : "null")}'");
  437. top ??= _top;
  438. if (top == null)
  439. {
  440. return;
  441. }
  442. ToplevelClosingEventArgs ev = new (top);
  443. top.OnClosing (ev);
  444. if (ev.Cancel)
  445. {
  446. return;
  447. }
  448. top.Running = false;
  449. }
  450. /// <inheritdoc />
  451. public void Invoke (Action action)
  452. {
  453. // If we are already on the main UI thread
  454. if (_top is { Running: true } && _mainThreadId == Thread.CurrentThread.ManagedThreadId)
  455. {
  456. action ();
  457. return;
  458. }
  459. _timedEvents.Add (TimeSpan.Zero,
  460. () =>
  461. {
  462. action ();
  463. return false;
  464. }
  465. );
  466. }
  467. /// <inheritdoc />
  468. public bool IsLegacy => false;
  469. /// <inheritdoc />
  470. public object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.Add (time, callback); }
  471. /// <inheritdoc />
  472. public bool RemoveTimeout (object token) { return _timedEvents.Remove (token); }
  473. /// <inheritdoc />
  474. public void LayoutAndDraw (bool forceRedraw = false)
  475. {
  476. List<View> tops = [.. _topLevels];
  477. if (_popover?.GetActivePopover () as View is { Visible: true } visiblePopover)
  478. {
  479. visiblePopover.SetNeedsDraw ();
  480. visiblePopover.SetNeedsLayout ();
  481. tops.Insert (0, visiblePopover);
  482. }
  483. bool neededLayout = View.Layout (tops.ToArray ().Reverse (), Screen.Size);
  484. if (ClearScreenNextIteration)
  485. {
  486. forceRedraw = true;
  487. ClearScreenNextIteration = false;
  488. }
  489. if (forceRedraw)
  490. {
  491. _driver?.ClearContents ();
  492. }
  493. View.SetClipToScreen ();
  494. View.Draw (tops, neededLayout || forceRedraw);
  495. View.SetClipToScreen ();
  496. _driver?.Refresh ();
  497. }
  498. /// <inheritdoc />
  499. public void ResetState (bool ignoreDisposed = false)
  500. {
  501. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  502. // Init created. Apps that do any threading will need to code defensively for this.
  503. // e.g. see Issue #537
  504. foreach (Toplevel? t in _topLevels)
  505. {
  506. t!.Running = false;
  507. }
  508. if (_popover?.GetActivePopover () is View popover)
  509. {
  510. // This forcefully closes the popover; invoking Command.Quit would be more graceful
  511. // but since this is shutdown, doing this is ok.
  512. popover.Visible = false;
  513. }
  514. _popover?.Dispose ();
  515. _popover = null;
  516. _topLevels.Clear ();
  517. #if DEBUG_IDISPOSABLE
  518. // Don't dispose the Top. It's up to caller dispose it
  519. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && _top is { })
  520. {
  521. Debug.Assert (_top.WasDisposed, $"Title = {_top.Title}, Id = {_top.Id}");
  522. // If End wasn't called _cachedRunStateToplevel may be null
  523. if (_cachedRunStateToplevel is { })
  524. {
  525. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  526. Debug.Assert (_cachedRunStateToplevel == _top);
  527. }
  528. }
  529. #endif
  530. _top = null;
  531. _cachedRunStateToplevel = null;
  532. _mainThreadId = -1;
  533. // These static properties need to be reset
  534. Application.EndAfterFirstIteration = false;
  535. Application.ClearScreenNextIteration = false;
  536. Application.ClearForceFakeConsole ();
  537. // Driver stuff
  538. if (_driver is { })
  539. {
  540. UnsubscribeDriverEvents ();
  541. _driver?.End ();
  542. _driver = null;
  543. }
  544. // Reset Screen to null so it will be recalculated on next access
  545. ResetScreen ();
  546. // Run State stuff - these are static events on Application class
  547. Application.ClearRunStateEvents ();
  548. // Mouse and Keyboard will be lazy-initialized in ApplicationImpl on next access
  549. _initialized = false;
  550. // Mouse
  551. // Do not clear _lastMousePosition; Popovers require it to stay set with
  552. // last mouse pos.
  553. //_lastMousePosition = null;
  554. Application.CachedViewsUnderMouse.Clear ();
  555. Application.ResetMouseState ();
  556. // Keyboard events and bindings are now managed by the Keyboard instance
  557. Application.ClearSizeChangingEvent ();
  558. _navigation = null;
  559. // Reset SupportedCultures so it's re-cached on next access
  560. _supportedCultures = null;
  561. // Reset synchronization context to allow the user to run async/await,
  562. // as the main loop has been ended, the synchronization context from
  563. // gui.cs does no longer process any callbacks. See #1084 for more details:
  564. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  565. SynchronizationContext.SetSynchronizationContext (null);
  566. }
  567. /// <summary>
  568. /// Resets the Screen field to null so it will be recalculated on next access.
  569. /// </summary>
  570. internal void ResetScreen ()
  571. {
  572. lock (_lockScreen)
  573. {
  574. _screen = null;
  575. }
  576. }
  577. private void SubscribeDriverEvents ()
  578. {
  579. if (_driver is null)
  580. {
  581. throw new ArgumentNullException (nameof (_driver));
  582. }
  583. _driver.SizeChanged += Driver_SizeChanged;
  584. _driver.KeyDown += Driver_KeyDown;
  585. _driver.KeyUp += Driver_KeyUp;
  586. _driver.MouseEvent += Driver_MouseEvent;
  587. }
  588. private void UnsubscribeDriverEvents ()
  589. {
  590. if (_driver is null)
  591. {
  592. throw new ArgumentNullException (nameof (_driver));
  593. }
  594. _driver.SizeChanged -= Driver_SizeChanged;
  595. _driver.KeyDown -= Driver_KeyDown;
  596. _driver.KeyUp -= Driver_KeyUp;
  597. _driver.MouseEvent -= Driver_MouseEvent;
  598. }
  599. private void Driver_SizeChanged (object? sender, SizeChangedEventArgs e) { Application.OnSizeChanging (e); }
  600. private void Driver_KeyDown (object? sender, Key e) { Application.RaiseKeyDownEvent (e); }
  601. private void Driver_KeyUp (object? sender, Key e) { Application.RaiseKeyUpEvent (e); }
  602. private void Driver_MouseEvent (object? sender, MouseEventArgs e) { Application.RaiseMouseEvent (e); }
  603. private static List<CultureInfo> GetAvailableCulturesFromEmbeddedResources ()
  604. {
  605. ResourceManager rm = new (typeof (Strings));
  606. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  607. return cultures.Where (
  608. cultureInfo =>
  609. !cultureInfo.Equals (CultureInfo.InvariantCulture)
  610. && rm.GetResourceSet (cultureInfo, true, false) is { }
  611. )
  612. .ToList ();
  613. }
  614. // BUGBUG: This does not return en-US even though it's supported by default
  615. private static List<CultureInfo> GetSupportedCultures ()
  616. {
  617. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  618. // Get the assembly
  619. var assembly = Assembly.GetExecutingAssembly ();
  620. //Find the location of the assembly
  621. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  622. // Find the resource file name of the assembly
  623. var resourceFilename = $"{assembly.GetName ().Name}.resources.dll";
  624. if (cultures.Length > 1 && Directory.Exists (Path.Combine (assemblyLocation, "pt-PT")))
  625. {
  626. // Return all culture for which satellite folder found with culture code.
  627. return cultures.Where (
  628. cultureInfo =>
  629. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  630. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  631. )
  632. .ToList ();
  633. }
  634. // It's called from a self-contained single-file and get available cultures from the embedded resources strings.
  635. return GetAvailableCulturesFromEmbeddedResources ();
  636. }
  637. }