Application.cs 55 KB

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