ApplicationImpl.cs 24 KB

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