Application.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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 (false, _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 (true, _initialized));
  308. }
  309. /// <summary>
  310. /// This event is fired after the <see cref="Init"/> and <see cref="Shutdown"/> methods have been called.
  311. /// </summary>
  312. /// <remarks>
  313. /// Intended to support unit tests that need to know when the application has been initialized.
  314. /// </remarks>
  315. public static event EventHandler<StateEventArgs<bool>> InitializedChanged;
  316. #endregion Initialization (Init/Shutdown)
  317. #region Run (Begin, Run, End, Stop)
  318. /// <summary>
  319. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is
  320. /// created in <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  321. /// </summary>
  322. /// <remarks>
  323. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  324. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  325. /// when the application is done.
  326. /// </remarks>
  327. public static event EventHandler<RunStateEventArgs> NotifyNewRunState;
  328. /// <summary>Notify that a existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).</summary>
  329. /// <remarks>
  330. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  331. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  332. /// when the application is done.
  333. /// </remarks>
  334. public static event EventHandler<ToplevelEventArgs> NotifyStopRunState;
  335. /// <summary>Building block API: Prepares the provided <see cref="Toplevel"/> for execution.</summary>
  336. /// <returns>
  337. /// The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon
  338. /// completion.
  339. /// </returns>
  340. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  341. /// <remarks>
  342. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus, it adds this to the list
  343. /// of <see cref="Toplevel"/>s, lays out the Subviews, focuses the first element, and draws the <see cref="Toplevel"/>
  344. /// in the screen. This is usually followed by executing the <see cref="RunLoop"/> method, and then the
  345. /// <see cref="End(RunState)"/> method upon termination which will undo these changes.
  346. /// </remarks>
  347. public static RunState Begin (Toplevel toplevel)
  348. {
  349. ArgumentNullException.ThrowIfNull (toplevel);
  350. #if DEBUG_IDISPOSABLE
  351. Debug.Assert (!toplevel.WasDisposed);
  352. if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
  353. {
  354. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  355. }
  356. #endif
  357. if (toplevel.IsOverlappedContainer && OverlappedTop != toplevel && OverlappedTop is { })
  358. {
  359. throw new InvalidOperationException ("Only one Overlapped Container is allowed.");
  360. }
  361. // Ensure the mouse is ungrabbed.
  362. MouseGrabView = null;
  363. var rs = new RunState (toplevel);
  364. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  365. if (!toplevel.IsInitialized)
  366. {
  367. toplevel.BeginInit ();
  368. toplevel.EndInit ();
  369. }
  370. #if DEBUG_IDISPOSABLE
  371. if (Top is { } && toplevel != Top && !_topLevels.Contains (Top))
  372. {
  373. // This assertion confirm if the Top was already disposed
  374. Debug.Assert (Top.WasDisposed);
  375. Debug.Assert (Top == _cachedRunStateToplevel);
  376. }
  377. #endif
  378. lock (_topLevels)
  379. {
  380. if (Top is { } && toplevel != Top && !_topLevels.Contains (Top))
  381. {
  382. // If Top was already disposed and isn't on the Toplevels Stack,
  383. // clean it up here if is the same as _cachedRunStateToplevel
  384. if (Top == _cachedRunStateToplevel)
  385. {
  386. Top = null;
  387. }
  388. else
  389. {
  390. // Probably this will never hit
  391. throw new ObjectDisposedException (Top.GetType ().FullName);
  392. }
  393. }
  394. else if (OverlappedTop is { } && toplevel != Top && _topLevels.Contains (Top))
  395. {
  396. Top.OnLeave (toplevel);
  397. }
  398. // BUGBUG: We should not depend on `Id` internally.
  399. // BUGBUG: It is super unclear what this code does anyway.
  400. if (string.IsNullOrEmpty (toplevel.Id))
  401. {
  402. var count = 1;
  403. var id = (_topLevels.Count + count).ToString ();
  404. while (_topLevels.Count > 0 && _topLevels.FirstOrDefault (x => x.Id == id) is { })
  405. {
  406. count++;
  407. id = (_topLevels.Count + count).ToString ();
  408. }
  409. toplevel.Id = (_topLevels.Count + count).ToString ();
  410. _topLevels.Push (toplevel);
  411. }
  412. else
  413. {
  414. Toplevel dup = _topLevels.FirstOrDefault (x => x.Id == toplevel.Id);
  415. if (dup is null)
  416. {
  417. _topLevels.Push (toplevel);
  418. }
  419. }
  420. if (_topLevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0)
  421. {
  422. throw new ArgumentException ("There are duplicates Toplevel IDs");
  423. }
  424. }
  425. if (Top is null || toplevel.IsOverlappedContainer)
  426. {
  427. Top = toplevel;
  428. }
  429. var refreshDriver = true;
  430. if (OverlappedTop is null
  431. || toplevel.IsOverlappedContainer
  432. || (Current?.Modal == false && toplevel.Modal)
  433. || (Current?.Modal == false && !toplevel.Modal)
  434. || (Current?.Modal == true && toplevel.Modal))
  435. {
  436. if (toplevel.Visible)
  437. {
  438. Current?.OnDeactivate (toplevel);
  439. Toplevel previousCurrent = Current;
  440. Current = toplevel;
  441. Current.OnActivate (previousCurrent);
  442. SetCurrentOverlappedAsTop ();
  443. }
  444. else
  445. {
  446. refreshDriver = false;
  447. }
  448. }
  449. else if ((OverlappedTop != null
  450. && toplevel != OverlappedTop
  451. && Current?.Modal == true
  452. && !_topLevels.Peek ().Modal)
  453. || (OverlappedTop is { } && toplevel != OverlappedTop && Current?.Running == false))
  454. {
  455. refreshDriver = false;
  456. MoveCurrent (toplevel);
  457. }
  458. else
  459. {
  460. refreshDriver = false;
  461. MoveCurrent (Current);
  462. }
  463. toplevel.SetRelativeLayout (Driver.Screen.Size);
  464. toplevel.LayoutSubviews ();
  465. toplevel.PositionToplevels ();
  466. toplevel.FocusFirst ();
  467. BringOverlappedTopToFront ();
  468. if (refreshDriver)
  469. {
  470. OverlappedTop?.OnChildLoaded (toplevel);
  471. toplevel.OnLoaded ();
  472. toplevel.SetNeedsDisplay ();
  473. toplevel.Draw ();
  474. Driver.UpdateScreen ();
  475. if (PositionCursor (toplevel))
  476. {
  477. Driver.UpdateCursor ();
  478. }
  479. }
  480. NotifyNewRunState?.Invoke (toplevel, new (rs));
  481. return rs;
  482. }
  483. /// <summary>
  484. /// Calls <see cref="View.PositionCursor"/> on the most focused view in the view starting with <paramref name="view"/>.
  485. /// </summary>
  486. /// <remarks>
  487. /// Does nothing if <paramref name="view"/> is <see langword="null"/> or if the most focused view is not visible or
  488. /// enabled.
  489. /// <para>
  490. /// If the most focused view is not visible within it's superview, the cursor will be hidden.
  491. /// </para>
  492. /// </remarks>
  493. /// <returns><see langword="true"/> if a view positioned the cursor and the position is visible.</returns>
  494. internal static bool PositionCursor (View view)
  495. {
  496. // Find the most focused view and position the cursor there.
  497. View mostFocused = view?.MostFocused;
  498. if (mostFocused is null)
  499. {
  500. if (view is { HasFocus: true })
  501. {
  502. mostFocused = view;
  503. }
  504. else
  505. {
  506. return false;
  507. }
  508. }
  509. // If the view is not visible or enabled, don't position the cursor
  510. if (!mostFocused.Visible || !mostFocused.Enabled)
  511. {
  512. Driver.GetCursorVisibility (out CursorVisibility current);
  513. if (current != CursorVisibility.Invisible)
  514. {
  515. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  516. }
  517. return false;
  518. }
  519. // If the view is not visible within it's superview, don't position the cursor
  520. Rectangle mostFocusedViewport = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = Point.Empty });
  521. Rectangle superViewViewport = mostFocused.SuperView?.ViewportToScreen (mostFocused.SuperView.Viewport with { Location = Point.Empty }) ?? Driver.Screen;
  522. if (!superViewViewport.IntersectsWith (mostFocusedViewport))
  523. {
  524. return false;
  525. }
  526. Point? cursor = mostFocused.PositionCursor ();
  527. Driver.GetCursorVisibility (out CursorVisibility currentCursorVisibility);
  528. if (cursor is { })
  529. {
  530. // Convert cursor to screen coords
  531. cursor = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = cursor.Value }).Location;
  532. // If the cursor is not in a visible location in the SuperView, hide it
  533. if (!superViewViewport.Contains (cursor.Value))
  534. {
  535. if (currentCursorVisibility != CursorVisibility.Invisible)
  536. {
  537. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  538. }
  539. return false;
  540. }
  541. // Show it
  542. if (currentCursorVisibility == CursorVisibility.Invisible)
  543. {
  544. Driver.SetCursorVisibility (mostFocused.CursorVisibility);
  545. }
  546. return true;
  547. }
  548. if (currentCursorVisibility != CursorVisibility.Invisible)
  549. {
  550. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  551. }
  552. return false;
  553. }
  554. /// <summary>
  555. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  556. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  557. /// </summary>
  558. /// <remarks>
  559. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  560. /// <para>
  561. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  562. /// ensure resources are cleaned up and terminal settings restored.
  563. /// </para>
  564. /// <para>
  565. /// The caller is responsible for disposing the object returned by this method.
  566. /// </para>
  567. /// </remarks>
  568. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  569. public static Toplevel Run (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null) { return Run<Toplevel> (errorHandler, driver); }
  570. /// <summary>
  571. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  572. /// <see cref="Run(Toplevel, Func{Exception, bool})"/>.
  573. /// </summary>
  574. /// <remarks>
  575. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  576. /// <para>
  577. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  578. /// ensure resources are cleaned up and terminal settings restored.
  579. /// </para>
  580. /// <para>
  581. /// The caller is responsible for disposing the object returned by this method.
  582. /// </para>
  583. /// </remarks>
  584. /// <param name="errorHandler"></param>
  585. /// <param name="driver">
  586. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  587. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  588. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  589. /// </param>
  590. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  591. public static T Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
  592. where T : Toplevel, new()
  593. {
  594. if (!_initialized)
  595. {
  596. // Init() has NOT been called.
  597. InternalInit (driver, null, true);
  598. }
  599. var top = new T ();
  600. Run (top, errorHandler);
  601. return top;
  602. }
  603. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  604. /// <remarks>
  605. /// <para>
  606. /// This method is used to start processing events for the main application, but it is also used to run other
  607. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  608. /// </para>
  609. /// <para>
  610. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call
  611. /// <see cref="Application.RequestStop"/>.
  612. /// </para>
  613. /// <para>
  614. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling
  615. /// <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState)"/>, and then calling
  616. /// <see cref="End(RunState)"/>.
  617. /// </para>
  618. /// <para>
  619. /// Alternatively, to have a program control the main loop and process events manually, call
  620. /// <see cref="Begin(Toplevel)"/> to set things up manually and then repeatedly call
  621. /// <see cref="RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  622. /// <see cref="RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  623. /// return control immediately.
  624. /// </para>
  625. /// <para>When using <see cref="Run{T}"/> or
  626. /// <see cref="Run(System.Func{System.Exception,bool},Terminal.Gui.ConsoleDriver)"/>
  627. /// <see cref="Init"/> will be called automatically.
  628. /// </para>
  629. /// <para>
  630. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  631. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  632. /// returns <see langword="true"/> the <see cref="RunLoop(RunState)"/> will resume; otherwise this method will
  633. /// exit.
  634. /// </para>
  635. /// </remarks>
  636. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  637. /// <param name="errorHandler">
  638. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  639. /// rethrows when null).
  640. /// </param>
  641. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  642. {
  643. ArgumentNullException.ThrowIfNull (view);
  644. if (_initialized)
  645. {
  646. if (Driver is null)
  647. {
  648. // Disposing before throwing
  649. view.Dispose ();
  650. // This code path should be impossible because Init(null, null) will select the platform default driver
  651. throw new InvalidOperationException (
  652. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  653. );
  654. }
  655. }
  656. else
  657. {
  658. // Init() has NOT been called.
  659. throw new InvalidOperationException (
  660. "Init() has not been called. Only Run() or Run<T>() can be used without calling Init()."
  661. );
  662. }
  663. var resume = true;
  664. while (resume)
  665. {
  666. #if !DEBUG
  667. try
  668. {
  669. #endif
  670. resume = false;
  671. RunState runState = Begin (view);
  672. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  673. // by using NotifyStopRunState event.
  674. RunLoop (runState);
  675. if (runState.Toplevel is null)
  676. {
  677. #if DEBUG_IDISPOSABLE
  678. Debug.Assert (_topLevels.Count == 0);
  679. #endif
  680. runState.Dispose ();
  681. return;
  682. }
  683. if (!EndAfterFirstIteration)
  684. {
  685. End (runState);
  686. }
  687. #if !DEBUG
  688. }
  689. catch (Exception error)
  690. {
  691. if (errorHandler is null)
  692. {
  693. throw;
  694. }
  695. resume = errorHandler (error);
  696. }
  697. #endif
  698. }
  699. }
  700. /// <summary>Adds a timeout to the application.</summary>
  701. /// <remarks>
  702. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  703. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  704. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  705. /// </remarks>
  706. public static object AddTimeout (TimeSpan time, Func<bool> callback) { return MainLoop?.AddTimeout (time, callback); }
  707. /// <summary>Removes a previously scheduled timeout</summary>
  708. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  709. /// Returns
  710. /// <c>true</c>
  711. /// if the timeout is successfully removed; otherwise,
  712. /// <c>false</c>
  713. /// .
  714. /// This method also returns
  715. /// <c>false</c>
  716. /// if the timeout is not found.
  717. public static bool RemoveTimeout (object token) { return MainLoop?.RemoveTimeout (token) ?? false; }
  718. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  719. /// <param name="action">the action to be invoked on the main processing thread.</param>
  720. public static void Invoke (Action action)
  721. {
  722. MainLoop?.AddIdle (
  723. () =>
  724. {
  725. action ();
  726. return false;
  727. }
  728. );
  729. }
  730. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  731. // is ProgressBarStyles and it's not clear it needs to.
  732. /// <summary>Wakes up the running application that might be waiting on input.</summary>
  733. public static void Wakeup () { MainLoop?.Wakeup (); }
  734. /// <summary>Triggers a refresh of the entire display.</summary>
  735. public static void Refresh ()
  736. {
  737. // TODO: Figure out how to remove this call to ClearContents. Refresh should just repaint damaged areas, not clear
  738. Driver.ClearContents ();
  739. View last = null;
  740. foreach (Toplevel v in _topLevels.Reverse ())
  741. {
  742. if (v.Visible)
  743. {
  744. v.SetNeedsDisplay ();
  745. v.SetSubViewNeedsDisplay ();
  746. v.Draw ();
  747. }
  748. last = v;
  749. }
  750. Driver.Refresh ();
  751. }
  752. /// <summary>This event is raised on each iteration of the main loop.</summary>
  753. /// <remarks>See also <see cref="Timeout"/></remarks>
  754. public static event EventHandler<IterationEventArgs> Iteration;
  755. /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
  756. /// <value>The main loop.</value>
  757. internal static MainLoop MainLoop { get; private set; }
  758. /// <summary>
  759. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  760. /// cause the application to continue running until Application.RequestStop () is called.
  761. /// </summary>
  762. public static bool EndAfterFirstIteration { get; set; }
  763. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  764. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  765. public static void RunLoop (RunState state)
  766. {
  767. ArgumentNullException.ThrowIfNull (state);
  768. ObjectDisposedException.ThrowIf (state.Toplevel is null, "state");
  769. var firstIteration = true;
  770. for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
  771. {
  772. MainLoop.Running = true;
  773. if (EndAfterFirstIteration && !firstIteration)
  774. {
  775. return;
  776. }
  777. RunIteration (ref state, ref firstIteration);
  778. }
  779. MainLoop.Running = false;
  780. // Run one last iteration to consume any outstanding input events from Driver
  781. // This is important for remaining OnKeyUp events.
  782. RunIteration (ref state, ref firstIteration);
  783. }
  784. /// <summary>Run one application iteration.</summary>
  785. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  786. /// <param name="firstIteration">
  787. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  788. /// will be set to <see langword="false"/> if at least one iteration happened.
  789. /// </param>
  790. public static void RunIteration (ref RunState state, ref bool firstIteration)
  791. {
  792. if (MainLoop.Running && MainLoop.EventsPending ())
  793. {
  794. // Notify Toplevel it's ready
  795. if (firstIteration)
  796. {
  797. state.Toplevel.OnReady ();
  798. }
  799. MainLoop.RunIteration ();
  800. Iteration?.Invoke (null, new ());
  801. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  802. if (state.Toplevel != Current)
  803. {
  804. OverlappedTop?.OnDeactivate (state.Toplevel);
  805. state.Toplevel = Current;
  806. OverlappedTop?.OnActivate (state.Toplevel);
  807. Top.SetSubViewNeedsDisplay ();
  808. Refresh ();
  809. }
  810. }
  811. firstIteration = false;
  812. if (Current == null)
  813. {
  814. return;
  815. }
  816. if (state.Toplevel != Top && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  817. {
  818. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  819. Top.Draw ();
  820. foreach (Toplevel top in _topLevels.Reverse ())
  821. {
  822. if (top != Top && top != state.Toplevel)
  823. {
  824. top.SetNeedsDisplay ();
  825. top.SetSubViewNeedsDisplay ();
  826. top.Draw ();
  827. }
  828. }
  829. }
  830. if (_topLevels.Count == 1
  831. && state.Toplevel == Top
  832. && (Driver.Cols != state.Toplevel.Frame.Width
  833. || Driver.Rows != state.Toplevel.Frame.Height)
  834. && (state.Toplevel.NeedsDisplay
  835. || state.Toplevel.SubViewNeedsDisplay
  836. || state.Toplevel.LayoutNeeded))
  837. {
  838. Driver.ClearContents ();
  839. }
  840. if (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded || OverlappedChildNeedsDisplay ())
  841. {
  842. state.Toplevel.Draw ();
  843. Driver.UpdateScreen ();
  844. //Driver.UpdateCursor ();
  845. }
  846. if (PositionCursor (state.Toplevel))
  847. {
  848. Driver.UpdateCursor ();
  849. }
  850. // else
  851. {
  852. //if (PositionCursor (state.Toplevel))
  853. //{
  854. // Driver.Refresh ();
  855. //}
  856. //Driver.UpdateCursor ();
  857. }
  858. if (state.Toplevel != Top && !state.Toplevel.Modal && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  859. {
  860. Top.Draw ();
  861. }
  862. }
  863. /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
  864. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  865. /// <remarks>
  866. /// <para>This will cause <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> to return.</para>
  867. /// <para>
  868. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  869. /// property on the currently running <see cref="Toplevel"/> to false.
  870. /// </para>
  871. /// </remarks>
  872. public static void RequestStop (Toplevel top = null)
  873. {
  874. if (OverlappedTop is null || top is null || (OverlappedTop is null && top is { }))
  875. {
  876. top = Current;
  877. }
  878. if (OverlappedTop != null
  879. && top.IsOverlappedContainer
  880. && top?.Running == true
  881. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false)))
  882. {
  883. OverlappedTop.RequestStop ();
  884. }
  885. else if (OverlappedTop != null
  886. && top != Current
  887. && Current?.Running == true
  888. && Current?.Modal == true
  889. && top.Modal
  890. && top.Running)
  891. {
  892. var ev = new ToplevelClosingEventArgs (Current);
  893. Current.OnClosing (ev);
  894. if (ev.Cancel)
  895. {
  896. return;
  897. }
  898. ev = new (top);
  899. top.OnClosing (ev);
  900. if (ev.Cancel)
  901. {
  902. return;
  903. }
  904. Current.Running = false;
  905. OnNotifyStopRunState (Current);
  906. top.Running = false;
  907. OnNotifyStopRunState (top);
  908. }
  909. else if ((OverlappedTop != null
  910. && top != OverlappedTop
  911. && top != Current
  912. && Current?.Modal == false
  913. && Current?.Running == true
  914. && !top.Running)
  915. || (OverlappedTop != null
  916. && top != OverlappedTop
  917. && top != Current
  918. && Current?.Modal == false
  919. && Current?.Running == false
  920. && !top.Running
  921. && _topLevels.ToArray () [1].Running))
  922. {
  923. MoveCurrent (top);
  924. }
  925. else if (OverlappedTop != null
  926. && Current != top
  927. && Current?.Running == true
  928. && !top.Running
  929. && Current?.Modal == true
  930. && top.Modal)
  931. {
  932. // The Current and the top are both modal so needed to set the Current.Running to false too.
  933. Current.Running = false;
  934. OnNotifyStopRunState (Current);
  935. }
  936. else if (OverlappedTop != null
  937. && Current == top
  938. && OverlappedTop?.Running == true
  939. && Current?.Running == true
  940. && top.Running
  941. && Current?.Modal == true
  942. && top.Modal)
  943. {
  944. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  945. // both are the same, so needed to set the Current.Running to false too.
  946. Current.Running = false;
  947. OnNotifyStopRunState (Current);
  948. }
  949. else
  950. {
  951. Toplevel currentTop;
  952. if (top == Current || (Current?.Modal == true && !top.Modal))
  953. {
  954. currentTop = Current;
  955. }
  956. else
  957. {
  958. currentTop = top;
  959. }
  960. if (!currentTop.Running)
  961. {
  962. return;
  963. }
  964. var ev = new ToplevelClosingEventArgs (currentTop);
  965. currentTop.OnClosing (ev);
  966. if (ev.Cancel)
  967. {
  968. return;
  969. }
  970. currentTop.Running = false;
  971. OnNotifyStopRunState (currentTop);
  972. }
  973. }
  974. private static void OnNotifyStopRunState (Toplevel top)
  975. {
  976. if (EndAfterFirstIteration)
  977. {
  978. NotifyStopRunState?.Invoke (top, new (top));
  979. }
  980. }
  981. /// <summary>
  982. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  983. /// <see cref="Begin(Toplevel)"/> .
  984. /// </summary>
  985. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  986. public static void End (RunState runState)
  987. {
  988. ArgumentNullException.ThrowIfNull (runState);
  989. if (OverlappedTop is { })
  990. {
  991. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  992. }
  993. else
  994. {
  995. runState.Toplevel.OnUnloaded ();
  996. }
  997. // End the RunState.Toplevel
  998. // First, take it off the Toplevel Stack
  999. if (_topLevels.Count > 0)
  1000. {
  1001. if (_topLevels.Peek () != runState.Toplevel)
  1002. {
  1003. // If there the top of the stack is not the RunState.Toplevel then
  1004. // this call to End is not balanced with the call to Begin that started the RunState
  1005. throw new ArgumentException ("End must be balanced with calls to Begin");
  1006. }
  1007. _topLevels.Pop ();
  1008. }
  1009. // Notify that it is closing
  1010. runState.Toplevel?.OnClosed (runState.Toplevel);
  1011. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  1012. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  1013. if (OverlappedTop is { } && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop)
  1014. {
  1015. OverlappedTop.OnChildClosed (runState.Toplevel);
  1016. }
  1017. // Set Current and Top to the next TopLevel on the stack
  1018. if (_topLevels.Count == 0)
  1019. {
  1020. Current = null;
  1021. }
  1022. else
  1023. {
  1024. if (_topLevels.Count > 1 && _topLevels.Peek () == OverlappedTop && OverlappedChildren.Any (t => t.Visible) is { })
  1025. {
  1026. OverlappedMoveNext ();
  1027. }
  1028. Current = _topLevels.Peek ();
  1029. if (_topLevels.Count == 1 && Current == OverlappedTop)
  1030. {
  1031. OverlappedTop.OnAllChildClosed ();
  1032. }
  1033. else
  1034. {
  1035. SetCurrentOverlappedAsTop ();
  1036. runState.Toplevel.OnLeave (Current);
  1037. Current.OnEnter (runState.Toplevel);
  1038. }
  1039. Refresh ();
  1040. }
  1041. // Don't dispose runState.Toplevel. It's up to caller dispose it
  1042. // If it's not the same as the current in the RunIteration,
  1043. // it will be fixed later in the next RunIteration.
  1044. if (OverlappedTop is { } && !_topLevels.Contains (OverlappedTop))
  1045. {
  1046. _cachedRunStateToplevel = OverlappedTop;
  1047. }
  1048. else
  1049. {
  1050. _cachedRunStateToplevel = runState.Toplevel;
  1051. }
  1052. runState.Toplevel = null;
  1053. runState.Dispose ();
  1054. }
  1055. #endregion Run (Begin, Run, End)
  1056. #region Toplevel handling
  1057. /// <summary>Holds the stack of TopLevel views.</summary>
  1058. // BUGBUG: Techncally, this is not the full lst of TopLevels. THere be dragons hwre. E.g. see how Toplevel.Id is used. What
  1059. // about TopLevels that are just a SubView of another View?
  1060. internal static readonly Stack<Toplevel> _topLevels = new ();
  1061. /// <summary>The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)</summary>
  1062. /// <value>The top.</value>
  1063. public static Toplevel Top { get; private set; }
  1064. /// <summary>
  1065. /// The current <see cref="Toplevel"/> object. This is updated in <see cref="Application.Begin"/> enters and leaves to
  1066. /// point to the current
  1067. /// <see cref="Toplevel"/> .
  1068. /// </summary>
  1069. /// <remarks>
  1070. /// Only relevant in scenarios where <see cref="Toplevel.IsOverlappedContainer"/> is <see langword="true"/>.
  1071. /// </remarks>
  1072. /// <value>The current.</value>
  1073. public static Toplevel Current { get; private set; }
  1074. private static void EnsureModalOrVisibleAlwaysOnTop (Toplevel topLevel)
  1075. {
  1076. if (!topLevel.Running
  1077. || (topLevel == Current && topLevel.Visible)
  1078. || OverlappedTop == null
  1079. || _topLevels.Peek ().Modal)
  1080. {
  1081. return;
  1082. }
  1083. foreach (Toplevel top in _topLevels.Reverse ())
  1084. {
  1085. if (top.Modal && top != Current)
  1086. {
  1087. MoveCurrent (top);
  1088. return;
  1089. }
  1090. }
  1091. if (!topLevel.Visible && topLevel == Current)
  1092. {
  1093. OverlappedMoveNext ();
  1094. }
  1095. }
  1096. #nullable enable
  1097. private static Toplevel? FindDeepestTop (Toplevel start, in Point location)
  1098. {
  1099. if (!start.Frame.Contains (location))
  1100. {
  1101. return null;
  1102. }
  1103. if (_topLevels is { Count: > 0 })
  1104. {
  1105. int rx = location.X - start.Frame.X;
  1106. int ry = location.Y - start.Frame.Y;
  1107. foreach (Toplevel t in _topLevels)
  1108. {
  1109. if (t != Current)
  1110. {
  1111. if (t != start && t.Visible && t.Frame.Contains (rx, ry))
  1112. {
  1113. start = t;
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. }
  1119. return start;
  1120. }
  1121. #nullable restore
  1122. private static View FindTopFromView (View view)
  1123. {
  1124. View top = view?.SuperView is { } && view?.SuperView != Top
  1125. ? view.SuperView
  1126. : view;
  1127. while (top?.SuperView is { } && top?.SuperView != Top)
  1128. {
  1129. top = top.SuperView;
  1130. }
  1131. return top;
  1132. }
  1133. #nullable enable
  1134. // Only return true if the Current has changed.
  1135. private static bool MoveCurrent (Toplevel? top)
  1136. {
  1137. // The Current is modal and the top is not modal Toplevel then
  1138. // the Current must be moved above the first not modal Toplevel.
  1139. if (OverlappedTop is { }
  1140. && top != OverlappedTop
  1141. && top != Current
  1142. && Current?.Modal == true
  1143. && !_topLevels.Peek ().Modal)
  1144. {
  1145. lock (_topLevels)
  1146. {
  1147. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1148. }
  1149. var index = 0;
  1150. Toplevel [] savedToplevels = _topLevels.ToArray ();
  1151. foreach (Toplevel t in savedToplevels)
  1152. {
  1153. if (!t.Modal && t != Current && t != top && t != savedToplevels [index])
  1154. {
  1155. lock (_topLevels)
  1156. {
  1157. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  1158. }
  1159. }
  1160. index++;
  1161. }
  1162. return false;
  1163. }
  1164. // The Current and the top are both not running Toplevel then
  1165. // the top must be moved above the first not running Toplevel.
  1166. if (OverlappedTop is { }
  1167. && top != OverlappedTop
  1168. && top != Current
  1169. && Current?.Running == false
  1170. && top?.Running == false)
  1171. {
  1172. lock (_topLevels)
  1173. {
  1174. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1175. }
  1176. var index = 0;
  1177. foreach (Toplevel t in _topLevels.ToArray ())
  1178. {
  1179. if (!t.Running && t != Current && index > 0)
  1180. {
  1181. lock (_topLevels)
  1182. {
  1183. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  1184. }
  1185. }
  1186. index++;
  1187. }
  1188. return false;
  1189. }
  1190. if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top)
  1191. || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  1192. || (OverlappedTop is { } && Current?.Modal == false && top != Current)
  1193. || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop))
  1194. {
  1195. lock (_topLevels)
  1196. {
  1197. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1198. Current = top;
  1199. }
  1200. }
  1201. return true;
  1202. }
  1203. #nullable restore
  1204. /// <summary>Invoked when the terminal's size changed. The new size of the terminal is provided.</summary>
  1205. /// <remarks>
  1206. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/> to prevent
  1207. /// <see cref="Application"/> from changing it's size to match the new terminal size.
  1208. /// </remarks>
  1209. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  1210. /// <summary>
  1211. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and fires the
  1212. /// <see cref="SizeChanging"/> event.
  1213. /// </summary>
  1214. /// <param name="args">The new size.</param>
  1215. /// <returns><see lanword="true"/>if the size was changed.</returns>
  1216. public static bool OnSizeChanging (SizeChangedEventArgs args)
  1217. {
  1218. SizeChanging?.Invoke (null, args);
  1219. if (args.Cancel || args.Size is null)
  1220. {
  1221. return false;
  1222. }
  1223. foreach (Toplevel t in _topLevels)
  1224. {
  1225. t.SetRelativeLayout (args.Size.Value);
  1226. t.LayoutSubviews ();
  1227. t.PositionToplevels ();
  1228. t.OnSizeChanging (new (args.Size));
  1229. if (PositionCursor (t))
  1230. {
  1231. Driver.UpdateCursor ();
  1232. }
  1233. }
  1234. Refresh ();
  1235. return true;
  1236. }
  1237. #endregion Toplevel handling
  1238. }