Application.cs 55 KB

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