Application.cs 68 KB

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