Application.cs 54 KB

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