Application.cs 53 KB

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