ApplicationImpl.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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 ApplicationPopover? Popover { get; set; }
  111. /// <inheritdoc/>
  112. public ApplicationNavigation? Navigation { get; set; }
  113. /// <inheritdoc/>
  114. public Toplevel? Top { get; set; }
  115. /// <inheritdoc/>
  116. public ConcurrentStack<Toplevel> TopLevels { get; } = new ();
  117. /// <inheritdoc/>
  118. public ushort MaximumIterationsPerSecond { get; set; } = 25;
  119. /// <inheritdoc/>
  120. public List<CultureInfo>? SupportedCultures
  121. {
  122. get
  123. {
  124. if (_supportedCultures is null)
  125. {
  126. _supportedCultures = GetSupportedCultures ();
  127. }
  128. return _supportedCultures;
  129. }
  130. }
  131. /// <inheritdoc/>
  132. public void RequestStop () { RequestStop (null); }
  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 = 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 { };
  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. SubscribeDriverEvents ();
  179. SynchronizationContext.SetSynchronizationContext (new ());
  180. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  181. }
  182. /// <summary>
  183. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  184. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  185. /// </summary>
  186. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  187. [RequiresUnreferencedCode ("AOT")]
  188. [RequiresDynamicCode ("AOT")]
  189. public Toplevel Run (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  190. /// <summary>
  191. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  192. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  193. /// </summary>
  194. /// <param name="errorHandler"></param>
  195. /// <param name="driver">
  196. /// The <see cref="IConsoleDriver"/> to use. If not specified the default driver for the platform will
  197. /// be used. Must be <see langword="null"/> if <see cref="Init"/> has already been called.
  198. /// </param>
  199. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  200. [RequiresUnreferencedCode ("AOT")]
  201. [RequiresDynamicCode ("AOT")]
  202. public T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  203. where T : Toplevel, new ()
  204. {
  205. if (!Initialized)
  206. {
  207. // Init() has NOT been called. Auto-initialize as per interface contract.
  208. Init (driver);
  209. }
  210. T top = new ();
  211. Run (top, errorHandler);
  212. return top;
  213. }
  214. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  215. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  216. /// <param name="errorHandler">Handler for any unhandled exceptions.</param>
  217. public void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  218. {
  219. Logging.Information ($"Run '{view}'");
  220. ArgumentNullException.ThrowIfNull (view);
  221. if (!Initialized)
  222. {
  223. throw new NotInitializedException (nameof (Run));
  224. }
  225. if (_driver == null)
  226. {
  227. throw new InvalidOperationException ("Driver was inexplicably null when trying to Run view");
  228. }
  229. Top = view;
  230. RunState rs = Application.Begin (view);
  231. Top.Running = true;
  232. while (TopLevels.TryPeek (out Toplevel? found) && found == view && view.Running)
  233. {
  234. if (Coordinator is null)
  235. {
  236. throw new ($"{nameof (IMainLoopCoordinator)} inexplicably became null during Run");
  237. }
  238. Coordinator.RunIteration ();
  239. }
  240. Logging.Information ("Run - Calling End");
  241. Application.End (rs);
  242. }
  243. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  244. public void Shutdown ()
  245. {
  246. Coordinator?.Stop ();
  247. bool wasInitialized = Initialized;
  248. // Reset Screen before calling ResetState to avoid circular reference
  249. ResetScreen ();
  250. // Call ResetState FIRST so it can properly dispose Popover and other resources
  251. // that are accessed via Application.* static properties that now delegate to instance fields
  252. ResetState ();
  253. ConfigurationManager.PrintJsonErrors ();
  254. // Clear instance fields after ResetState has disposed everything
  255. _driver = null;
  256. _mouse = null;
  257. _keyboard = null;
  258. Initialized = false;
  259. Navigation = null;
  260. Popover = null;
  261. Top = null;
  262. TopLevels.Clear ();
  263. MainThreadId = -1;
  264. _screen = null;
  265. ClearScreenNextIteration = false;
  266. Sixel.Clear ();
  267. // Don't reset ForceDriver and Force16Colors; they need to be set before Init is called
  268. if (wasInitialized)
  269. {
  270. bool init = Initialized; // Will be false after clearing fields above
  271. Application.OnInitializedChanged (this, new (in init));
  272. }
  273. _lazyInstance = new (() => new ApplicationImpl ());
  274. }
  275. /// <inheritdoc/>
  276. public void RequestStop (Toplevel? top)
  277. {
  278. Logging.Logger.LogInformation ($"RequestStop '{(top is { } ? top : "null")}'");
  279. top ??= Top;
  280. if (top == null)
  281. {
  282. return;
  283. }
  284. ToplevelClosingEventArgs ev = new (top);
  285. top.OnClosing (ev);
  286. if (ev.Cancel)
  287. {
  288. return;
  289. }
  290. top.Running = false;
  291. }
  292. /// <inheritdoc/>
  293. public void Invoke (Action action)
  294. {
  295. // If we are already on the main UI thread
  296. if (Top is { Running: true } && MainThreadId == Thread.CurrentThread.ManagedThreadId)
  297. {
  298. action ();
  299. return;
  300. }
  301. _timedEvents.Add (
  302. TimeSpan.Zero,
  303. () =>
  304. {
  305. action ();
  306. return false;
  307. }
  308. );
  309. }
  310. /// <inheritdoc/>
  311. public bool IsLegacy => false;
  312. /// <inheritdoc/>
  313. public object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.Add (time, callback); }
  314. /// <inheritdoc/>
  315. public bool RemoveTimeout (object token) { return _timedEvents.Remove (token); }
  316. /// <inheritdoc/>
  317. public void LayoutAndDraw (bool forceRedraw = false)
  318. {
  319. List<View> tops = [.. TopLevels];
  320. if (Popover?.GetActivePopover () as View is { Visible: true } visiblePopover)
  321. {
  322. visiblePopover.SetNeedsDraw ();
  323. visiblePopover.SetNeedsLayout ();
  324. tops.Insert (0, visiblePopover);
  325. }
  326. bool neededLayout = View.Layout (tops.ToArray ().Reverse (), Screen.Size);
  327. if (ClearScreenNextIteration)
  328. {
  329. forceRedraw = true;
  330. ClearScreenNextIteration = false;
  331. }
  332. if (forceRedraw)
  333. {
  334. _driver?.ClearContents ();
  335. }
  336. View.SetClipToScreen ();
  337. View.Draw (tops, neededLayout || forceRedraw);
  338. View.SetClipToScreen ();
  339. _driver?.Refresh ();
  340. }
  341. /// <inheritdoc/>
  342. public void ResetState (bool ignoreDisposed = false)
  343. {
  344. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  345. // Init created. Apps that do any threading will need to code defensively for this.
  346. // e.g. see Issue #537
  347. foreach (Toplevel? t in TopLevels)
  348. {
  349. t!.Running = false;
  350. }
  351. if (Popover?.GetActivePopover () is View popover)
  352. {
  353. // This forcefully closes the popover; invoking Command.Quit would be more graceful
  354. // but since this is shutdown, doing this is ok.
  355. popover.Visible = false;
  356. }
  357. Popover?.Dispose ();
  358. Popover = null;
  359. TopLevels.Clear ();
  360. #if DEBUG_IDISPOSABLE
  361. // Don't dispose the Top. It's up to caller dispose it
  362. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && Top is { })
  363. {
  364. Debug.Assert (Top.WasDisposed, $"Title = {Top.Title}, Id = {Top.Id}");
  365. // If End wasn't called _cachedRunStateToplevel may be null
  366. if (_cachedRunStateToplevel is { })
  367. {
  368. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  369. Debug.Assert (_cachedRunStateToplevel == Top);
  370. }
  371. }
  372. #endif
  373. Top = null;
  374. _cachedRunStateToplevel = null;
  375. MainThreadId = -1;
  376. // These static properties need to be reset
  377. Application.EndAfterFirstIteration = false;
  378. Application.ClearScreenNextIteration = false;
  379. // Driver stuff
  380. if (_driver is { })
  381. {
  382. UnsubscribeDriverEvents ();
  383. _driver?.End ();
  384. _driver = null;
  385. }
  386. // Reset Screen to null so it will be recalculated on next access
  387. ResetScreen ();
  388. // Run State stuff - these are static events on Application class
  389. Application.ClearRunStateEvents ();
  390. // Mouse and Keyboard will be lazy-initialized in ApplicationImpl on next access
  391. Initialized = false;
  392. // Mouse
  393. // Do not clear _lastMousePosition; Popovers require it to stay set with
  394. // last mouse pos.
  395. //_lastMousePosition = null;
  396. Application.CachedViewsUnderMouse.Clear ();
  397. Application.ResetMouseState ();
  398. // Keyboard events and bindings are now managed by the Keyboard instance
  399. Application.ClearSizeChangingEvent ();
  400. Navigation = null;
  401. // Reset SupportedCultures so it's re-cached on next access
  402. _supportedCultures = null;
  403. // Reset synchronization context to allow the user to run async/await,
  404. // as the main loop has been ended, the synchronization context from
  405. // gui.cs does no longer process any callbacks. See #1084 for more details:
  406. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  407. SynchronizationContext.SetSynchronizationContext (null);
  408. }
  409. /// <summary>
  410. /// Change the singleton implementation, should not be called except before application
  411. /// startup. This method lets you provide alternative implementations of core static gateway
  412. /// methods of <see cref="Application"/>.
  413. /// </summary>
  414. /// <param name="newApplication"></param>
  415. public static void ChangeInstance (IApplication newApplication) { _lazyInstance = new (newApplication); }
  416. /// <summary>
  417. /// Gets the currently configured backend implementation of <see cref="Application"/> gateway methods.
  418. /// Change to your own implementation by using <see cref="ChangeInstance"/> (before init).
  419. /// </summary>
  420. public static IApplication Instance => _lazyInstance.Value;
  421. internal IMainLoopCoordinator? Coordinator { get; private set; }
  422. /// <summary>
  423. /// Gets or sets the main thread ID for the application.
  424. /// </summary>
  425. internal int MainThreadId { get; set; } = -1;
  426. /// <summary>
  427. /// Resets the Screen field to null so it will be recalculated on next access.
  428. /// </summary>
  429. internal void ResetScreen ()
  430. {
  431. lock (_lockScreen)
  432. {
  433. _screen = null;
  434. }
  435. }
  436. private void CreateDriver (string? driverName)
  437. {
  438. // When running unit tests, always use FakeDriver unless explicitly specified
  439. if (ConsoleDriver.RunningUnitTests && string.IsNullOrEmpty (driverName) && _componentFactory is null)
  440. {
  441. Logging.Logger.LogDebug ("Unit test safeguard: forcing FakeDriver (RunningUnitTests=true, driverName=null, componentFactory=null)");
  442. Coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  443. Coordinator.StartAsync ().Wait ();
  444. if (_driver == null)
  445. {
  446. throw new ("Driver was null even after booting MainLoopCoordinator");
  447. }
  448. return;
  449. }
  450. PlatformID p = Environment.OSVersion.Platform;
  451. // Check component factory type first - this takes precedence over driverName
  452. bool factoryIsWindows = _componentFactory is IComponentFactory<WindowsConsole.InputRecord>;
  453. bool factoryIsDotNet = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  454. bool factoryIsUnix = _componentFactory is IComponentFactory<char>;
  455. bool factoryIsFake = _componentFactory is IComponentFactory<ConsoleKeyInfo>;
  456. // Then check driverName
  457. bool nameIsWindows = driverName?.Contains ("win", StringComparison.OrdinalIgnoreCase) ?? false;
  458. bool nameIsDotNet = driverName?.Contains ("dotnet", StringComparison.OrdinalIgnoreCase) ?? false;
  459. bool nameIsUnix = driverName?.Contains ("unix", StringComparison.OrdinalIgnoreCase) ?? false;
  460. bool nameIsFake = driverName?.Contains ("fake", StringComparison.OrdinalIgnoreCase) ?? false;
  461. // Decide which driver to use - component factory type takes priority
  462. if (factoryIsFake || (!factoryIsWindows && !factoryIsDotNet && !factoryIsUnix && nameIsFake))
  463. {
  464. Coordinator = CreateSubcomponents (() => new FakeComponentFactory ());
  465. }
  466. else if (factoryIsWindows || (!factoryIsDotNet && !factoryIsUnix && nameIsWindows))
  467. {
  468. Coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  469. }
  470. else if (factoryIsDotNet || (!factoryIsWindows && !factoryIsUnix && nameIsDotNet))
  471. {
  472. Coordinator = CreateSubcomponents (() => new NetComponentFactory ());
  473. }
  474. else if (factoryIsUnix || (!factoryIsWindows && !factoryIsDotNet && nameIsUnix))
  475. {
  476. Coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  477. }
  478. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  479. {
  480. Coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  481. }
  482. else
  483. {
  484. Coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  485. }
  486. Coordinator.StartAsync ().Wait ();
  487. if (_driver == null)
  488. {
  489. throw new ("Driver was null even after booting MainLoopCoordinator");
  490. }
  491. }
  492. private IMainLoopCoordinator CreateSubcomponents<T> (Func<IComponentFactory<T>> fallbackFactory)
  493. {
  494. ConcurrentQueue<T> inputBuffer = new ();
  495. ApplicationMainLoop<T> loop = new ();
  496. IComponentFactory<T> cf;
  497. if (_componentFactory is IComponentFactory<T> typedFactory)
  498. {
  499. cf = typedFactory;
  500. }
  501. else
  502. {
  503. cf = fallbackFactory ();
  504. }
  505. return new MainLoopCoordinator<T> (_timedEvents, inputBuffer, loop, cf);
  506. }
  507. private void Driver_KeyDown (object? sender, Key e) { Application.RaiseKeyDownEvent (e); }
  508. private void Driver_KeyUp (object? sender, Key e) { Application.RaiseKeyUpEvent (e); }
  509. private void Driver_MouseEvent (object? sender, MouseEventArgs e) { Application.RaiseMouseEvent (e); }
  510. private void Driver_SizeChanged (object? sender, SizeChangedEventArgs e) { Application.OnSizeChanging (e); }
  511. private static List<CultureInfo> GetAvailableCulturesFromEmbeddedResources ()
  512. {
  513. ResourceManager rm = new (typeof (Strings));
  514. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  515. return cultures.Where (cultureInfo =>
  516. !cultureInfo.Equals (CultureInfo.InvariantCulture)
  517. && rm.GetResourceSet (cultureInfo, true, false) is { }
  518. )
  519. .ToList ();
  520. }
  521. // BUGBUG: This does not return en-US even though it's supported by default
  522. private static List<CultureInfo> GetSupportedCultures ()
  523. {
  524. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  525. // Get the assembly
  526. var assembly = Assembly.GetExecutingAssembly ();
  527. //Find the location of the assembly
  528. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  529. // Find the resource file name of the assembly
  530. var resourceFilename = $"{assembly.GetName ().Name}.resources.dll";
  531. if (cultures.Length > 1 && Directory.Exists (Path.Combine (assemblyLocation, "pt-PT")))
  532. {
  533. // Return all culture for which satellite folder found with culture code.
  534. return cultures.Where (cultureInfo =>
  535. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  536. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  537. )
  538. .ToList ();
  539. }
  540. // It's called from a self-contained single-file and get available cultures from the embedded resources strings.
  541. return GetAvailableCulturesFromEmbeddedResources ();
  542. }
  543. private void SubscribeDriverEvents ()
  544. {
  545. if (_driver is null)
  546. {
  547. throw new ArgumentNullException (nameof (_driver));
  548. }
  549. _driver.SizeChanged += Driver_SizeChanged;
  550. _driver.KeyDown += Driver_KeyDown;
  551. _driver.KeyUp += Driver_KeyUp;
  552. _driver.MouseEvent += Driver_MouseEvent;
  553. }
  554. private void UnsubscribeDriverEvents ()
  555. {
  556. if (_driver is null)
  557. {
  558. throw new ArgumentNullException (nameof (_driver));
  559. }
  560. _driver.SizeChanged -= Driver_SizeChanged;
  561. _driver.KeyDown -= Driver_KeyDown;
  562. _driver.KeyUp -= Driver_KeyUp;
  563. _driver.MouseEvent -= Driver_MouseEvent;
  564. }
  565. }