Application.cs 54 KB

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