2
0

Application.cs 54 KB

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