Application.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. using System.Diagnostics;
  2. using System.Globalization;
  3. using System.Reflection;
  4. using System.Text.Json.Serialization;
  5. namespace Terminal.Gui;
  6. /// <summary>A static, singleton class representing the application. This class is the entry point for the application.</summary>
  7. /// <example>
  8. /// <code>
  9. /// Application.Init();
  10. /// var win = new Window ($"Example App ({Application.QuitKey} to quit)");
  11. /// Application.Run(win);
  12. /// win.Dispose();
  13. /// Application.Shutdown();
  14. /// </code>
  15. /// </example>
  16. /// <remarks>TODO: Flush this out.</remarks>
  17. public static partial class Application
  18. {
  19. // For Unit testing - ignores UseSystemConsole
  20. internal static bool _forceFakeConsole;
  21. /// <summary>Gets the <see cref="ConsoleDriver"/> that has been selected. See also <see cref="ForceDriver"/>.</summary>
  22. public static ConsoleDriver Driver { get; internal set; }
  23. /// <summary>
  24. /// Gets or sets whether <see cref="Application.Driver"/> will be forced to output only the 16 colors defined in
  25. /// <see cref="ColorName"/>. The default is <see langword="false"/>, meaning 24-bit (TrueColor) colors will be output
  26. /// as long as the selected <see cref="ConsoleDriver"/> supports TrueColor.
  27. /// </summary>
  28. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  29. public static bool Force16Colors { get; set; }
  30. /// <summary>
  31. /// Forces the use of the specified driver (one of "fake", "ansi", "curses", "net", or "windows"). If not
  32. /// specified, the driver is selected based on the platform.
  33. /// </summary>
  34. /// <remarks>
  35. /// Note, <see cref="Application.Init(ConsoleDriver, string)"/> will override this configuration setting if called
  36. /// with either `driver` or `driverName` specified.
  37. /// </remarks>
  38. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  39. public static string ForceDriver { get; set; } = string.Empty;
  40. /// <summary>Gets all cultures supported by the application without the invariant language.</summary>
  41. public static List<CultureInfo> SupportedCultures { get; private set; }
  42. internal static List<CultureInfo> GetSupportedCultures ()
  43. {
  44. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  45. // Get the assembly
  46. var assembly = Assembly.GetExecutingAssembly ();
  47. //Find the location of the assembly
  48. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  49. // Find the resource file name of the assembly
  50. var resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  51. // Return all culture for which satellite folder found with culture code.
  52. return culture.Where (
  53. cultureInfo =>
  54. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  55. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  56. )
  57. .ToList ();
  58. }
  59. // When `End ()` is called, it is possible `RunState.Toplevel` is a different object than `Top`.
  60. // This variable is set in `End` in this case so that `Begin` correctly sets `Top`.
  61. private static Toplevel _cachedRunStateToplevel;
  62. // IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  63. // Encapsulate all setting of initial state for Application; Having
  64. // this in a function like this ensures we don't make mistakes in
  65. // guaranteeing that the state of this singleton is deterministic when Init
  66. // starts running and after Shutdown returns.
  67. internal static void ResetState ()
  68. {
  69. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  70. // Init created. Apps that do any threading will need to code defensively for this.
  71. // e.g. see Issue #537
  72. foreach (Toplevel t in _topLevels)
  73. {
  74. t.Running = false;
  75. #if DEBUG_IDISPOSABLE
  76. // Don't dispose the toplevels. It's up to caller dispose them
  77. //Debug.Assert (t.WasDisposed);
  78. #endif
  79. }
  80. _topLevels.Clear ();
  81. Current = null;
  82. #if DEBUG_IDISPOSABLE
  83. // Don't dispose the Top. It's up to caller dispose it
  84. if (Top is { })
  85. {
  86. Debug.Assert (Top.WasDisposed);
  87. // If End wasn't called _cachedRunStateToplevel may be null
  88. if (_cachedRunStateToplevel is { })
  89. {
  90. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  91. Debug.Assert (_cachedRunStateToplevel == Top);
  92. }
  93. }
  94. #endif
  95. Top = null;
  96. _cachedRunStateToplevel = null;
  97. // MainLoop stuff
  98. MainLoop?.Dispose ();
  99. MainLoop = null;
  100. _mainThreadId = -1;
  101. Iteration = null;
  102. EndAfterFirstIteration = false;
  103. // Driver stuff
  104. if (Driver is { })
  105. {
  106. Driver.SizeChanged -= Driver_SizeChanged;
  107. Driver.KeyDown -= Driver_KeyDown;
  108. Driver.KeyUp -= Driver_KeyUp;
  109. Driver.MouseEvent -= Driver_MouseEvent;
  110. Driver?.End ();
  111. Driver = null;
  112. }
  113. // Don't reset ForceDriver; it needs to be set before Init is called.
  114. //ForceDriver = string.Empty;
  115. //Force16Colors = false;
  116. _forceFakeConsole = false;
  117. // Run State stuff
  118. NotifyNewRunState = null;
  119. NotifyStopRunState = null;
  120. MouseGrabView = null;
  121. _initialized = false;
  122. // Mouse
  123. _mouseEnteredView = null;
  124. WantContinuousButtonPressedView = null;
  125. MouseEvent = null;
  126. GrabbedMouse = null;
  127. UnGrabbingMouse = null;
  128. GrabbedMouse = null;
  129. UnGrabbedMouse = null;
  130. // Keyboard
  131. AlternateBackwardKey = Key.Empty;
  132. AlternateForwardKey = Key.Empty;
  133. QuitKey = Key.Empty;
  134. KeyDown = null;
  135. KeyUp = null;
  136. SizeChanging = null;
  137. ClearKeyBindings ();
  138. Colors.Reset ();
  139. // Reset synchronization context to allow the user to run async/await,
  140. // as the main loop has been ended, the synchronization context from
  141. // gui.cs does no longer process any callbacks. See #1084 for more details:
  142. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  143. SynchronizationContext.SetSynchronizationContext (null);
  144. }
  145. #region Initialization (Init/Shutdown)
  146. /// <summary>Initializes a new instance of <see cref="Terminal.Gui"/> Application.</summary>
  147. /// <para>Call this method once per instance (or after <see cref="Shutdown"/> has been called).</para>
  148. /// <para>
  149. /// This function loads the right <see cref="ConsoleDriver"/> for the platform, Creates a <see cref="Toplevel"/>. and
  150. /// assigns it to <see cref="Top"/>
  151. /// </para>
  152. /// <para>
  153. /// <see cref="Shutdown"/> must be called when the application is closing (typically after
  154. /// <see cref="Run(Func{Exception, bool}, ConsoleDriver)"/> has returned) to ensure resources are cleaned up and
  155. /// terminal settings
  156. /// restored.
  157. /// </para>
  158. /// <para>
  159. /// The <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver)"/> function combines
  160. /// <see cref="Init(ConsoleDriver, string)"/> and <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>
  161. /// into a single
  162. /// call. An application cam use <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver)"/> without explicitly calling
  163. /// <see cref="Init(ConsoleDriver, string)"/>.
  164. /// </para>
  165. /// <param name="driver">
  166. /// The <see cref="ConsoleDriver"/> to use. If neither <paramref name="driver"/> or
  167. /// <paramref name="driverName"/> are specified the default driver for the platform will be used.
  168. /// </param>
  169. /// <param name="driverName">
  170. /// The short name (e.g. "net", "windows", "ansi", "fake", or "curses") of the
  171. /// <see cref="ConsoleDriver"/> to use. If neither <paramref name="driver"/> or <paramref name="driverName"/> are
  172. /// specified the default driver for the platform will be used.
  173. /// </param>
  174. public static void Init (ConsoleDriver driver = null, string driverName = null) { InternalInit (driver, driverName); }
  175. internal static bool _initialized;
  176. internal static int _mainThreadId = -1;
  177. // INTERNAL function for initializing an app with a Toplevel factory object, driver, and mainloop.
  178. //
  179. // Called from:
  180. //
  181. // Init() - When the user wants to use the default Toplevel. calledViaRunT will be false, causing all state to be reset.
  182. // Run<T>() - When the user wants to use a custom Toplevel. calledViaRunT will be true, enabling Run<T>() to be called without calling Init first.
  183. // Unit Tests - To initialize the app with a custom Toplevel, using the FakeDriver. calledViaRunT will be false, causing all state to be reset.
  184. //
  185. // calledViaRunT: If false (default) all state will be reset. If true the state will not be reset.
  186. internal static void InternalInit (
  187. ConsoleDriver driver = null,
  188. string driverName = null,
  189. bool calledViaRunT = false
  190. )
  191. {
  192. if (_initialized && driver is null)
  193. {
  194. return;
  195. }
  196. if (_initialized)
  197. {
  198. throw new InvalidOperationException ("Init has already been called and must be bracketed by Shutdown.");
  199. }
  200. if (!calledViaRunT)
  201. {
  202. // Reset all class variables (Application is a singleton).
  203. ResetState ();
  204. }
  205. // For UnitTests
  206. if (driver is { })
  207. {
  208. Driver = driver;
  209. }
  210. // Start the process of configuration management.
  211. // Note that we end up calling LoadConfigurationFromAllSources
  212. // multiple times. We need to do this because some settings are only
  213. // valid after a Driver is loaded. In this cases we need just
  214. // `Settings` so we can determine which driver to use.
  215. // Don't reset, so we can inherit the theme from the previous run.
  216. Load ();
  217. Apply ();
  218. // Ignore Configuration for ForceDriver if driverName is specified
  219. if (!string.IsNullOrEmpty (driverName))
  220. {
  221. ForceDriver = driverName;
  222. }
  223. if (Driver is null)
  224. {
  225. PlatformID p = Environment.OSVersion.Platform;
  226. if (string.IsNullOrEmpty (ForceDriver))
  227. {
  228. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  229. {
  230. Driver = new WindowsDriver ();
  231. }
  232. else
  233. {
  234. Driver = new CursesDriver ();
  235. }
  236. }
  237. else
  238. {
  239. List<Type> drivers = GetDriverTypes ();
  240. Type driverType = drivers.FirstOrDefault (t => t.Name.Equals (ForceDriver, StringComparison.InvariantCultureIgnoreCase));
  241. if (driverType is { })
  242. {
  243. Driver = (ConsoleDriver)Activator.CreateInstance (driverType);
  244. }
  245. else
  246. {
  247. throw new ArgumentException (
  248. $"Invalid driver name: {ForceDriver}. Valid names are {string.Join (", ", drivers.Select (t => t.Name))}"
  249. );
  250. }
  251. }
  252. }
  253. try
  254. {
  255. MainLoop = Driver.Init ();
  256. }
  257. catch (InvalidOperationException ex)
  258. {
  259. // This is a case where the driver is unable to initialize the console.
  260. // This can happen if the console is already in use by another process or
  261. // if running in unit tests.
  262. // In this case, we want to throw a more specific exception.
  263. throw new InvalidOperationException (
  264. "Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.",
  265. ex
  266. );
  267. }
  268. Driver.SizeChanged += (s, args) => OnSizeChanging (args);
  269. Driver.KeyDown += (s, args) => OnKeyDown (args);
  270. Driver.KeyUp += (s, args) => OnKeyUp (args);
  271. Driver.MouseEvent += (s, args) => OnMouseEvent (args);
  272. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  273. SupportedCultures = GetSupportedCultures ();
  274. _mainThreadId = Thread.CurrentThread.ManagedThreadId;
  275. _initialized = true;
  276. }
  277. private static void Driver_SizeChanged (object sender, SizeChangedEventArgs e) { OnSizeChanging (e); }
  278. private static void Driver_KeyDown (object sender, Key e) { OnKeyDown (e); }
  279. private static void Driver_KeyUp (object sender, Key e) { OnKeyUp (e); }
  280. private static void Driver_MouseEvent (object sender, MouseEvent e) { OnMouseEvent (e); }
  281. /// <summary>Gets of list of <see cref="ConsoleDriver"/> types that are available.</summary>
  282. /// <returns></returns>
  283. public static List<Type> GetDriverTypes ()
  284. {
  285. // use reflection to get the list of drivers
  286. List<Type> driverTypes = new ();
  287. foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ())
  288. {
  289. foreach (Type type in asm.GetTypes ())
  290. {
  291. if (type.IsSubclassOf (typeof (ConsoleDriver)) && !type.IsAbstract)
  292. {
  293. driverTypes.Add (type);
  294. }
  295. }
  296. }
  297. return driverTypes;
  298. }
  299. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  300. /// <remarks>
  301. /// Shutdown must be called for every call to <see cref="Init"/> or
  302. /// <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> to ensure all resources are cleaned
  303. /// up (Disposed)
  304. /// and terminal settings are restored.
  305. /// </remarks>
  306. public static void Shutdown ()
  307. {
  308. // TODO: Throw an exception if Init hasn't been called.
  309. ResetState ();
  310. PrintJsonErrors ();
  311. }
  312. #endregion Initialization (Init/Shutdown)
  313. #region Run (Begin, Run, End, Stop)
  314. /// <summary>
  315. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is
  316. /// created in <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  317. /// </summary>
  318. /// <remarks>
  319. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  320. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  321. /// when the application is done.
  322. /// </remarks>
  323. public static event EventHandler<RunStateEventArgs> NotifyNewRunState;
  324. /// <summary>Notify that a existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).</summary>
  325. /// <remarks>
  326. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  327. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  328. /// when the application is done.
  329. /// </remarks>
  330. public static event EventHandler<ToplevelEventArgs> NotifyStopRunState;
  331. /// <summary>Building block API: Prepares the provided <see cref="Toplevel"/> for execution.</summary>
  332. /// <returns>
  333. /// The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon
  334. /// completion.
  335. /// </returns>
  336. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  337. /// <remarks>
  338. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus, it adds this to the list
  339. /// of <see cref="Toplevel"/>s, lays out the Subviews, focuses the first element, and draws the <see cref="Toplevel"/>
  340. /// in the screen. This is usually followed by executing the <see cref="RunLoop"/> method, and then the
  341. /// <see cref="End(RunState)"/> method upon termination which will undo these changes.
  342. /// </remarks>
  343. public static RunState Begin (Toplevel toplevel)
  344. {
  345. ArgumentNullException.ThrowIfNull (toplevel);
  346. #if DEBUG_IDISPOSABLE
  347. Debug.Assert (!toplevel.WasDisposed);
  348. if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
  349. {
  350. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  351. }
  352. #endif
  353. if (toplevel.IsOverlappedContainer && OverlappedTop != toplevel && OverlappedTop is { })
  354. {
  355. throw new InvalidOperationException ("Only one Overlapped Container is allowed.");
  356. }
  357. // Ensure the mouse is ungrabbed.
  358. MouseGrabView = null;
  359. var rs = new RunState (toplevel);
  360. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  361. if (!toplevel.IsInitialized)
  362. {
  363. toplevel.BeginInit ();
  364. toplevel.EndInit ();
  365. }
  366. #if DEBUG_IDISPOSABLE
  367. if (Top is { } && toplevel != Top && !_topLevels.Contains (Top))
  368. {
  369. // This assertion confirm if the Top was already disposed
  370. Debug.Assert (Top.WasDisposed);
  371. Debug.Assert (Top == _cachedRunStateToplevel);
  372. }
  373. #endif
  374. lock (_topLevels)
  375. {
  376. if (Top is { } && toplevel != Top && !_topLevels.Contains (Top))
  377. {
  378. // If Top was already disposed and isn't on the Toplevels Stack,
  379. // clean it up here if is the same as _cachedRunStateToplevel
  380. if (Top == _cachedRunStateToplevel)
  381. {
  382. Top = null;
  383. }
  384. else
  385. {
  386. // Probably this will never hit
  387. throw new ObjectDisposedException (Top.GetType ().FullName);
  388. }
  389. }
  390. else if (OverlappedTop is { } && toplevel != Top && _topLevels.Contains (Top))
  391. {
  392. Top.OnLeave (toplevel);
  393. }
  394. // BUGBUG: We should not depend on `Id` internally.
  395. // BUGBUG: It is super unclear what this code does anyway.
  396. if (string.IsNullOrEmpty (toplevel.Id))
  397. {
  398. var count = 1;
  399. var id = (_topLevels.Count + count).ToString ();
  400. while (_topLevels.Count > 0 && _topLevels.FirstOrDefault (x => x.Id == id) is { })
  401. {
  402. count++;
  403. id = (_topLevels.Count + count).ToString ();
  404. }
  405. toplevel.Id = (_topLevels.Count + count).ToString ();
  406. _topLevels.Push (toplevel);
  407. }
  408. else
  409. {
  410. Toplevel dup = _topLevels.FirstOrDefault (x => x.Id == toplevel.Id);
  411. if (dup is null)
  412. {
  413. _topLevels.Push (toplevel);
  414. }
  415. }
  416. if (_topLevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0)
  417. {
  418. throw new ArgumentException ("There are duplicates Toplevel IDs");
  419. }
  420. }
  421. if (Top is null || toplevel.IsOverlappedContainer)
  422. {
  423. Top = toplevel;
  424. }
  425. var refreshDriver = true;
  426. if (OverlappedTop is null
  427. || toplevel.IsOverlappedContainer
  428. || (Current?.Modal == false && toplevel.Modal)
  429. || (Current?.Modal == false && !toplevel.Modal)
  430. || (Current?.Modal == true && toplevel.Modal))
  431. {
  432. if (toplevel.Visible)
  433. {
  434. Current?.OnDeactivate (toplevel);
  435. Toplevel previousCurrent = Current;
  436. Current = toplevel;
  437. Current.OnActivate (previousCurrent);
  438. SetCurrentOverlappedAsTop ();
  439. }
  440. else
  441. {
  442. refreshDriver = false;
  443. }
  444. }
  445. else if ((OverlappedTop != null
  446. && toplevel != OverlappedTop
  447. && Current?.Modal == true
  448. && !_topLevels.Peek ().Modal)
  449. || (OverlappedTop is { } && toplevel != OverlappedTop && Current?.Running == false))
  450. {
  451. refreshDriver = false;
  452. MoveCurrent (toplevel);
  453. }
  454. else
  455. {
  456. refreshDriver = false;
  457. MoveCurrent (Current);
  458. }
  459. toplevel.SetRelativeLayout (Driver.Screen.Size);
  460. toplevel.LayoutSubviews ();
  461. toplevel.PositionToplevels ();
  462. toplevel.FocusFirst ();
  463. if (refreshDriver)
  464. {
  465. OverlappedTop?.OnChildLoaded (toplevel);
  466. toplevel.OnLoaded ();
  467. toplevel.SetNeedsDisplay ();
  468. toplevel.Draw ();
  469. Driver.UpdateScreen ();
  470. if (PositionCursor (toplevel))
  471. {
  472. Driver.UpdateCursor ();
  473. }
  474. }
  475. NotifyNewRunState?.Invoke (toplevel, new (rs));
  476. return rs;
  477. }
  478. /// <summary>
  479. /// Calls <see cref="View.PositionCursor"/> on the most focused view in the view starting with <paramref name="view"/>.
  480. /// </summary>
  481. /// <remarks>
  482. /// Does nothing if <paramref name="view"/> is <see langword="null"/> or if the most focused view is not visible or
  483. /// enabled.
  484. /// <para>
  485. /// If the most focused view is not visible within it's superview, the cursor will be hidden.
  486. /// </para>
  487. /// </remarks>
  488. /// <returns><see langword="true"/> if a view positioned the cursor and the position is visible.</returns>
  489. internal static bool PositionCursor (View view)
  490. {
  491. // Find the most focused view and position the cursor there.
  492. View mostFocused = view?.MostFocused;
  493. if (mostFocused is null)
  494. {
  495. if (view is { HasFocus: true })
  496. {
  497. mostFocused = view;
  498. }
  499. else
  500. {
  501. return false;
  502. }
  503. }
  504. // If the view is not visible or enabled, don't position the cursor
  505. if (!mostFocused.Visible || !mostFocused.Enabled)
  506. {
  507. Driver.GetCursorVisibility (out CursorVisibility current);
  508. if (current != CursorVisibility.Invisible)
  509. {
  510. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  511. }
  512. return false;
  513. }
  514. // If the view is not visible within it's superview, don't position the cursor
  515. Rectangle mostFocusedViewport = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = Point.Empty });
  516. Rectangle superViewViewport = mostFocused.SuperView?.ViewportToScreen (mostFocused.SuperView.Viewport with { Location = Point.Empty }) ?? Driver.Screen;
  517. if (!superViewViewport.IntersectsWith (mostFocusedViewport))
  518. {
  519. return false;
  520. }
  521. Point? cursor = mostFocused.PositionCursor ();
  522. Driver.GetCursorVisibility (out CursorVisibility currentCursorVisibility);
  523. if (cursor is { })
  524. {
  525. // Convert cursor to screen coords
  526. cursor = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = cursor.Value }).Location;
  527. // If the cursor is not in a visible location in the SuperView, hide it
  528. if (!superViewViewport.Contains (cursor.Value))
  529. {
  530. if (currentCursorVisibility != CursorVisibility.Invisible)
  531. {
  532. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  533. }
  534. return false;
  535. }
  536. // Show it
  537. if (currentCursorVisibility == CursorVisibility.Invisible)
  538. {
  539. Driver.SetCursorVisibility (mostFocused.CursorVisibility);
  540. }
  541. return true;
  542. }
  543. if (currentCursorVisibility != CursorVisibility.Invisible)
  544. {
  545. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  546. }
  547. return false;
  548. }
  549. /// <summary>
  550. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  551. /// <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
  552. /// </summary>
  553. /// <remarks>
  554. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  555. /// <para>
  556. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  557. /// ensure resources are cleaned up and terminal settings restored.
  558. /// </para>
  559. /// <para>
  560. /// The caller is responsible for disposing the object returned by this method.
  561. /// </para>
  562. /// </remarks>
  563. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  564. public static Toplevel Run (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null) { return Run<Toplevel> (errorHandler, driver); }
  565. /// <summary>
  566. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  567. /// <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
  568. /// </summary>
  569. /// <remarks>
  570. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  571. /// <para>
  572. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  573. /// ensure resources are cleaned up and terminal settings restored.
  574. /// </para>
  575. /// <para>
  576. /// The caller is responsible for disposing the object returned by this method.
  577. /// </para>
  578. /// </remarks>
  579. /// <param name="errorHandler"></param>
  580. /// <param name="driver">
  581. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  582. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  583. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  584. /// </param>
  585. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  586. public static T Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
  587. where T : Toplevel, new ()
  588. {
  589. var top = new T ();
  590. Run (top, errorHandler, driver);
  591. return top;
  592. }
  593. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  594. /// <remarks>
  595. /// <para>
  596. /// This method is used to start processing events for the main application, but it is also used to run other
  597. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  598. /// </para>
  599. /// <para>
  600. /// To make a <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> stop execution, call
  601. /// <see cref="Application.RequestStop"/>.
  602. /// </para>
  603. /// <para>
  604. /// Calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> is equivalent to calling
  605. /// <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState)"/>, and then calling
  606. /// <see cref="End(RunState)"/>.
  607. /// </para>
  608. /// <para>
  609. /// Alternatively, to have a program control the main loop and process events manually, call
  610. /// <see cref="Begin(Toplevel)"/> to set things up manually and then repeatedly call
  611. /// <see cref="RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  612. /// <see cref="RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  613. /// return control immediately.
  614. /// </para>
  615. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  616. /// <para>
  617. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  618. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  619. /// returns <see langword="true"/> the <see cref="RunLoop(RunState)"/> will resume; otherwise this method will
  620. /// exit.
  621. /// </para>
  622. /// </remarks>
  623. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  624. /// <param name="errorHandler">
  625. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  626. /// rethrows when null).
  627. /// </param>
  628. /// <param name="driver">
  629. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  630. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  631. /// <see langword="null"/> if <see cref="Init"/> was called.
  632. /// </param>
  633. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
  634. {
  635. ArgumentNullException.ThrowIfNull (view);
  636. if (_initialized)
  637. {
  638. if (Driver is null)
  639. {
  640. // Disposing before throwing
  641. view.Dispose ();
  642. // This code path should be impossible because Init(null, null) will select the platform default driver
  643. throw new InvalidOperationException (
  644. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  645. );
  646. }
  647. }
  648. else
  649. {
  650. // Init() has NOT been called.
  651. InternalInit (driver, null, true);
  652. }
  653. var resume = true;
  654. while (resume)
  655. {
  656. #if !DEBUG
  657. try
  658. {
  659. #endif
  660. resume = false;
  661. RunState runState = Begin (view);
  662. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  663. // by using NotifyStopRunState event.
  664. RunLoop (runState);
  665. if (runState.Toplevel is null)
  666. {
  667. #if DEBUG_IDISPOSABLE
  668. Debug.Assert (_topLevels.Count == 0);
  669. #endif
  670. runState.Dispose ();
  671. return;
  672. }
  673. if (!EndAfterFirstIteration)
  674. {
  675. End (runState);
  676. }
  677. #if !DEBUG
  678. }
  679. catch (Exception error)
  680. {
  681. if (errorHandler is null)
  682. {
  683. throw;
  684. }
  685. resume = errorHandler (error);
  686. }
  687. #endif
  688. }
  689. }
  690. /// <summary>Adds a timeout to the application.</summary>
  691. /// <remarks>
  692. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  693. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  694. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  695. /// </remarks>
  696. public static object AddTimeout (TimeSpan time, Func<bool> callback) { return MainLoop?.AddTimeout (time, callback); }
  697. /// <summary>Removes a previously scheduled timeout</summary>
  698. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  699. /// Returns
  700. /// <c>true</c>
  701. /// if the timeout is successfully removed; otherwise,
  702. /// <c>false</c>
  703. /// .
  704. /// This method also returns
  705. /// <c>false</c>
  706. /// if the timeout is not found.
  707. public static bool RemoveTimeout (object token) { return MainLoop?.RemoveTimeout (token) ?? false; }
  708. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  709. /// <param name="action">the action to be invoked on the main processing thread.</param>
  710. public static void Invoke (Action action)
  711. {
  712. MainLoop?.AddIdle (
  713. () =>
  714. {
  715. action ();
  716. return false;
  717. }
  718. );
  719. }
  720. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  721. // is ProgressBarStyles and it's not clear it needs to.
  722. /// <summary>Wakes up the running application that might be waiting on input.</summary>
  723. public static void Wakeup () { MainLoop?.Wakeup (); }
  724. /// <summary>Triggers a refresh of the entire display.</summary>
  725. public static void Refresh ()
  726. {
  727. // TODO: Figure out how to remove this call to ClearContents. Refresh should just repaint damaged areas, not clear
  728. Driver.ClearContents ();
  729. View last = null;
  730. foreach (Toplevel v in _topLevels.Reverse ())
  731. {
  732. if (v.Visible)
  733. {
  734. v.SetNeedsDisplay ();
  735. v.SetSubViewNeedsDisplay ();
  736. v.Draw ();
  737. }
  738. last = v;
  739. }
  740. Driver.Refresh ();
  741. }
  742. /// <summary>This event is raised on each iteration of the main loop.</summary>
  743. /// <remarks>See also <see cref="Timeout"/></remarks>
  744. public static event EventHandler<IterationEventArgs> Iteration;
  745. /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
  746. /// <value>The main loop.</value>
  747. internal static MainLoop MainLoop { get; private set; }
  748. /// <summary>
  749. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  750. /// cause the application to continue running until Application.RequestStop () is called.
  751. /// </summary>
  752. public static bool EndAfterFirstIteration { get; set; }
  753. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  754. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  755. public static void RunLoop (RunState state)
  756. {
  757. ArgumentNullException.ThrowIfNull (state);
  758. ObjectDisposedException.ThrowIf (state.Toplevel is null, "state");
  759. var firstIteration = true;
  760. for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
  761. {
  762. MainLoop.Running = true;
  763. if (EndAfterFirstIteration && !firstIteration)
  764. {
  765. return;
  766. }
  767. RunIteration (ref state, ref firstIteration);
  768. }
  769. MainLoop.Running = false;
  770. // Run one last iteration to consume any outstanding input events from Driver
  771. // This is important for remaining OnKeyUp events.
  772. RunIteration (ref state, ref firstIteration);
  773. }
  774. /// <summary>Run one application iteration.</summary>
  775. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  776. /// <param name="firstIteration">
  777. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  778. /// will be set to <see langword="false"/> if at least one iteration happened.
  779. /// </param>
  780. public static void RunIteration (ref RunState state, ref bool firstIteration)
  781. {
  782. if (MainLoop.Running && MainLoop.EventsPending ())
  783. {
  784. // Notify Toplevel it's ready
  785. if (firstIteration)
  786. {
  787. state.Toplevel.OnReady ();
  788. }
  789. MainLoop.RunIteration ();
  790. Iteration?.Invoke (null, new ());
  791. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  792. if (state.Toplevel != Current)
  793. {
  794. OverlappedTop?.OnDeactivate (state.Toplevel);
  795. state.Toplevel = Current;
  796. OverlappedTop?.OnActivate (state.Toplevel);
  797. Top.SetSubViewNeedsDisplay ();
  798. Refresh ();
  799. }
  800. }
  801. firstIteration = false;
  802. if (Current == null)
  803. {
  804. return;
  805. }
  806. if (state.Toplevel != Top && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  807. {
  808. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  809. Top.Draw ();
  810. foreach (Toplevel top in _topLevels.Reverse ())
  811. {
  812. if (top != Top && top != state.Toplevel)
  813. {
  814. top.SetNeedsDisplay ();
  815. top.SetSubViewNeedsDisplay ();
  816. top.Draw ();
  817. }
  818. }
  819. }
  820. if (_topLevels.Count == 1
  821. && state.Toplevel == Top
  822. && (Driver.Cols != state.Toplevel.Frame.Width
  823. || Driver.Rows != state.Toplevel.Frame.Height)
  824. && (state.Toplevel.NeedsDisplay
  825. || state.Toplevel.SubViewNeedsDisplay
  826. || state.Toplevel.LayoutNeeded))
  827. {
  828. Driver.ClearContents ();
  829. }
  830. if (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded || OverlappedChildNeedsDisplay ())
  831. {
  832. state.Toplevel.Draw ();
  833. Driver.UpdateScreen ();
  834. //Driver.UpdateCursor ();
  835. }
  836. if (PositionCursor (state.Toplevel))
  837. {
  838. Driver.UpdateCursor ();
  839. }
  840. // else
  841. {
  842. //if (PositionCursor (state.Toplevel))
  843. //{
  844. // Driver.Refresh ();
  845. //}
  846. //Driver.UpdateCursor ();
  847. }
  848. if (state.Toplevel != Top && !state.Toplevel.Modal && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  849. {
  850. Top.Draw ();
  851. }
  852. }
  853. /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
  854. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  855. /// <remarks>
  856. /// <para>This will cause <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> to return.</para>
  857. /// <para>
  858. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  859. /// property on the currently running <see cref="Toplevel"/> to false.
  860. /// </para>
  861. /// </remarks>
  862. public static void RequestStop (Toplevel top = null)
  863. {
  864. if (OverlappedTop is null || top is null || (OverlappedTop is null && top is { }))
  865. {
  866. top = Current;
  867. }
  868. if (OverlappedTop != null
  869. && top.IsOverlappedContainer
  870. && top?.Running == true
  871. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false)))
  872. {
  873. OverlappedTop.RequestStop ();
  874. }
  875. else if (OverlappedTop != null
  876. && top != Current
  877. && Current?.Running == true
  878. && Current?.Modal == true
  879. && top.Modal
  880. && top.Running)
  881. {
  882. var ev = new ToplevelClosingEventArgs (Current);
  883. Current.OnClosing (ev);
  884. if (ev.Cancel)
  885. {
  886. return;
  887. }
  888. ev = new (top);
  889. top.OnClosing (ev);
  890. if (ev.Cancel)
  891. {
  892. return;
  893. }
  894. Current.Running = false;
  895. OnNotifyStopRunState (Current);
  896. top.Running = false;
  897. OnNotifyStopRunState (top);
  898. }
  899. else if ((OverlappedTop != null
  900. && top != OverlappedTop
  901. && top != Current
  902. && Current?.Modal == false
  903. && Current?.Running == true
  904. && !top.Running)
  905. || (OverlappedTop != null
  906. && top != OverlappedTop
  907. && top != Current
  908. && Current?.Modal == false
  909. && Current?.Running == false
  910. && !top.Running
  911. && _topLevels.ToArray () [1].Running))
  912. {
  913. MoveCurrent (top);
  914. }
  915. else if (OverlappedTop != null
  916. && Current != top
  917. && Current?.Running == true
  918. && !top.Running
  919. && Current?.Modal == true
  920. && top.Modal)
  921. {
  922. // The Current and the top are both modal so needed to set the Current.Running to false too.
  923. Current.Running = false;
  924. OnNotifyStopRunState (Current);
  925. }
  926. else if (OverlappedTop != null
  927. && Current == top
  928. && OverlappedTop?.Running == true
  929. && Current?.Running == true
  930. && top.Running
  931. && Current?.Modal == true
  932. && top.Modal)
  933. {
  934. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  935. // both are the same, so needed to set the Current.Running to false too.
  936. Current.Running = false;
  937. OnNotifyStopRunState (Current);
  938. }
  939. else
  940. {
  941. Toplevel currentTop;
  942. if (top == Current || (Current?.Modal == true && !top.Modal))
  943. {
  944. currentTop = Current;
  945. }
  946. else
  947. {
  948. currentTop = top;
  949. }
  950. if (!currentTop.Running)
  951. {
  952. return;
  953. }
  954. var ev = new ToplevelClosingEventArgs (currentTop);
  955. currentTop.OnClosing (ev);
  956. if (ev.Cancel)
  957. {
  958. return;
  959. }
  960. currentTop.Running = false;
  961. OnNotifyStopRunState (currentTop);
  962. }
  963. }
  964. private static void OnNotifyStopRunState (Toplevel top)
  965. {
  966. if (EndAfterFirstIteration)
  967. {
  968. NotifyStopRunState?.Invoke (top, new (top));
  969. }
  970. }
  971. /// <summary>
  972. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  973. /// <see cref="Begin(Toplevel)"/> .
  974. /// </summary>
  975. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  976. public static void End (RunState runState)
  977. {
  978. ArgumentNullException.ThrowIfNull (runState);
  979. if (OverlappedTop is { })
  980. {
  981. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  982. }
  983. else
  984. {
  985. runState.Toplevel.OnUnloaded ();
  986. }
  987. // End the RunState.Toplevel
  988. // First, take it off the Toplevel Stack
  989. if (_topLevels.Count > 0)
  990. {
  991. if (_topLevels.Peek () != runState.Toplevel)
  992. {
  993. // If there the top of the stack is not the RunState.Toplevel then
  994. // this call to End is not balanced with the call to Begin that started the RunState
  995. throw new ArgumentException ("End must be balanced with calls to Begin");
  996. }
  997. _topLevels.Pop ();
  998. }
  999. // Notify that it is closing
  1000. runState.Toplevel?.OnClosed (runState.Toplevel);
  1001. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  1002. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  1003. if (OverlappedTop is { } && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop)
  1004. {
  1005. OverlappedTop.OnChildClosed (runState.Toplevel);
  1006. }
  1007. // Set Current and Top to the next TopLevel on the stack
  1008. if (_topLevels.Count == 0)
  1009. {
  1010. Current = null;
  1011. }
  1012. else
  1013. {
  1014. if (_topLevels.Count > 1 && _topLevels.Peek () == OverlappedTop && OverlappedChildren.Any (t => t.Visible) is { })
  1015. {
  1016. OverlappedMoveNext ();
  1017. }
  1018. Current = _topLevels.Peek ();
  1019. if (_topLevels.Count == 1 && Current == OverlappedTop)
  1020. {
  1021. OverlappedTop.OnAllChildClosed ();
  1022. }
  1023. else
  1024. {
  1025. SetCurrentOverlappedAsTop ();
  1026. runState.Toplevel.OnLeave (Current);
  1027. Current.OnEnter (runState.Toplevel);
  1028. }
  1029. Refresh ();
  1030. }
  1031. // Don't dispose runState.Toplevel. It's up to caller dispose it
  1032. // If it's not the same as the current in the RunIteration,
  1033. // it will be fixed later in the next RunIteration.
  1034. if (OverlappedTop is { } && !_topLevels.Contains (OverlappedTop))
  1035. {
  1036. _cachedRunStateToplevel = OverlappedTop;
  1037. }
  1038. else
  1039. {
  1040. _cachedRunStateToplevel = runState.Toplevel;
  1041. }
  1042. runState.Toplevel = null;
  1043. runState.Dispose ();
  1044. }
  1045. #endregion Run (Begin, Run, End)
  1046. #region Toplevel handling
  1047. /// <summary>Holds the stack of TopLevel views.</summary>
  1048. // BUGBUG: Techncally, this is not the full lst of TopLevels. THere be dragons hwre. E.g. see how Toplevel.Id is used. What
  1049. // about TopLevels that are just a SubView of another View?
  1050. internal static readonly Stack<Toplevel> _topLevels = new ();
  1051. /// <summary>The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)</summary>
  1052. /// <value>The top.</value>
  1053. public static Toplevel Top { get; private set; }
  1054. /// <summary>
  1055. /// The current <see cref="Toplevel"/> object. This is updated in <see cref="Application.Begin"/> enters and leaves to
  1056. /// point to the current
  1057. /// <see cref="Toplevel"/> .
  1058. /// </summary>
  1059. /// <remarks>
  1060. /// Only relevant in scenarios where <see cref="Toplevel.IsOverlappedContainer"/> is <see langword="true"/>.
  1061. /// </remarks>
  1062. /// <value>The current.</value>
  1063. public static Toplevel Current { get; private set; }
  1064. private static void EnsureModalOrVisibleAlwaysOnTop (Toplevel topLevel)
  1065. {
  1066. if (!topLevel.Running
  1067. || (topLevel == Current && topLevel.Visible)
  1068. || OverlappedTop == null
  1069. || _topLevels.Peek ().Modal)
  1070. {
  1071. return;
  1072. }
  1073. foreach (Toplevel top in _topLevels.Reverse ())
  1074. {
  1075. if (top.Modal && top != Current)
  1076. {
  1077. MoveCurrent (top);
  1078. return;
  1079. }
  1080. }
  1081. if (!topLevel.Visible && topLevel == Current)
  1082. {
  1083. OverlappedMoveNext ();
  1084. }
  1085. }
  1086. #nullable enable
  1087. private static Toplevel? FindDeepestTop (Toplevel start, in Point location)
  1088. {
  1089. if (!start.Frame.Contains (location))
  1090. {
  1091. return null;
  1092. }
  1093. if (_topLevels is { Count: > 0 })
  1094. {
  1095. int rx = location.X - start.Frame.X;
  1096. int ry = location.Y - start.Frame.Y;
  1097. foreach (Toplevel t in _topLevels)
  1098. {
  1099. if (t != Current)
  1100. {
  1101. if (t != start && t.Visible && t.Frame.Contains (rx, ry))
  1102. {
  1103. start = t;
  1104. break;
  1105. }
  1106. }
  1107. }
  1108. }
  1109. return start;
  1110. }
  1111. #nullable restore
  1112. private static View FindTopFromView (View view)
  1113. {
  1114. View top = view?.SuperView is { } && view?.SuperView != Top
  1115. ? view.SuperView
  1116. : view;
  1117. while (top?.SuperView is { } && top?.SuperView != Top)
  1118. {
  1119. top = top.SuperView;
  1120. }
  1121. return top;
  1122. }
  1123. #nullable enable
  1124. // Only return true if the Current has changed.
  1125. private static bool MoveCurrent (Toplevel? top)
  1126. {
  1127. // The Current is modal and the top is not modal Toplevel then
  1128. // the Current must be moved above the first not modal Toplevel.
  1129. if (OverlappedTop is { }
  1130. && top != OverlappedTop
  1131. && top != Current
  1132. && Current?.Modal == true
  1133. && !_topLevels.Peek ().Modal)
  1134. {
  1135. lock (_topLevels)
  1136. {
  1137. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1138. }
  1139. var index = 0;
  1140. Toplevel [] savedToplevels = _topLevels.ToArray ();
  1141. foreach (Toplevel t in savedToplevels)
  1142. {
  1143. if (!t.Modal && t != Current && t != top && t != savedToplevels [index])
  1144. {
  1145. lock (_topLevels)
  1146. {
  1147. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  1148. }
  1149. }
  1150. index++;
  1151. }
  1152. return false;
  1153. }
  1154. // The Current and the top are both not running Toplevel then
  1155. // the top must be moved above the first not running Toplevel.
  1156. if (OverlappedTop is { }
  1157. && top != OverlappedTop
  1158. && top != Current
  1159. && Current?.Running == false
  1160. && top?.Running == false)
  1161. {
  1162. lock (_topLevels)
  1163. {
  1164. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1165. }
  1166. var index = 0;
  1167. foreach (Toplevel t in _topLevels.ToArray ())
  1168. {
  1169. if (!t.Running && t != Current && index > 0)
  1170. {
  1171. lock (_topLevels)
  1172. {
  1173. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  1174. }
  1175. }
  1176. index++;
  1177. }
  1178. return false;
  1179. }
  1180. if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top)
  1181. || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  1182. || (OverlappedTop is { } && Current?.Modal == false && top != Current)
  1183. || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop))
  1184. {
  1185. lock (_topLevels)
  1186. {
  1187. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1188. Current = top;
  1189. }
  1190. }
  1191. return true;
  1192. }
  1193. #nullable restore
  1194. /// <summary>Invoked when the terminal's size changed. The new size of the terminal is provided.</summary>
  1195. /// <remarks>
  1196. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/> to prevent
  1197. /// <see cref="Application"/> from changing it's size to match the new terminal size.
  1198. /// </remarks>
  1199. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  1200. /// <summary>
  1201. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and fires the
  1202. /// <see cref="SizeChanging"/> event.
  1203. /// </summary>
  1204. /// <param name="args">The new size.</param>
  1205. /// <returns><see lanword="true"/>if the size was changed.</returns>
  1206. public static bool OnSizeChanging (SizeChangedEventArgs args)
  1207. {
  1208. SizeChanging?.Invoke (null, args);
  1209. if (args.Cancel || args.Size is null)
  1210. {
  1211. return false;
  1212. }
  1213. foreach (Toplevel t in _topLevels)
  1214. {
  1215. t.SetRelativeLayout (args.Size.Value);
  1216. t.LayoutSubviews ();
  1217. t.PositionToplevels ();
  1218. t.OnSizeChanging (new (args.Size));
  1219. if (PositionCursor (t))
  1220. {
  1221. Driver.UpdateCursor ();
  1222. }
  1223. }
  1224. Refresh ();
  1225. return true;
  1226. }
  1227. #endregion Toplevel handling
  1228. }