Application.cs 52 KB

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