Application.cs 68 KB

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