Application.cs 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956
  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. if (view is null)
  497. {
  498. return false;
  499. }
  500. // Find the most focused view and position the cursor there.
  501. View mostFocused = view.MostFocused;
  502. if (mostFocused is null)
  503. {
  504. return false;
  505. }
  506. CursorVisibility cachedCursorVisibility;
  507. // If the view is not visible or enabled, don't position the cursor
  508. if (!mostFocused.Visible || !mostFocused.Enabled)
  509. {
  510. Driver.GetCursorVisibility (out cachedCursorVisibility);
  511. if (cachedCursorVisibility != CursorVisibility.Invisible)
  512. {
  513. _cachedCursorVisibility = cachedCursorVisibility;
  514. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  515. }
  516. return false;
  517. }
  518. // If the view is not visible within it's superview, don't position the cursor
  519. Rectangle mostFocusedViewport = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = Point.Empty });
  520. Rectangle superViewViewport = mostFocused.SuperView?.ViewportToScreen (mostFocused.SuperView.Viewport with { Location = Point.Empty }) ?? Driver.Screen;
  521. if (!superViewViewport.IntersectsWith (mostFocusedViewport))
  522. {
  523. return false;
  524. }
  525. Point? prevCursor = new (Driver.Row, Driver.Col);
  526. Point? cursor = mostFocused.PositionCursor ();
  527. // If the cursor is not in a visible location in the SuperView, hide it
  528. if (cursor is { })
  529. {
  530. // Convert cursor to screen coords
  531. cursor = mostFocused.ViewportToScreen (mostFocused.Viewport with { Location = cursor.Value }).Location;
  532. if (!superViewViewport.Contains (cursor.Value))
  533. {
  534. Driver.GetCursorVisibility (out cachedCursorVisibility);
  535. if (cachedCursorVisibility != CursorVisibility.Invisible)
  536. {
  537. _cachedCursorVisibility = cachedCursorVisibility;
  538. }
  539. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  540. return false;
  541. }
  542. Driver.GetCursorVisibility (out cachedCursorVisibility);
  543. if (cachedCursorVisibility == CursorVisibility.Invisible)
  544. {
  545. Driver.SetCursorVisibility (_cachedCursorVisibility);
  546. }
  547. return prevCursor != cursor;
  548. }
  549. Driver.GetCursorVisibility (out cachedCursorVisibility);
  550. if (cachedCursorVisibility != CursorVisibility.Invisible)
  551. {
  552. _cachedCursorVisibility = cachedCursorVisibility;
  553. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  554. }
  555. return false;
  556. }
  557. /// <summary>
  558. /// Runs the application by creating a <see cref="Toplevel"/> object and calling
  559. /// <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
  560. /// </summary>
  561. /// <remarks>
  562. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  563. /// <para>
  564. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  565. /// ensure resources are cleaned up and terminal settings restored.
  566. /// </para>
  567. /// <para>
  568. /// The caller is responsible for disposing the object returned by this method.
  569. /// </para>
  570. /// </remarks>
  571. /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
  572. public static Toplevel Run (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null) { return Run<Toplevel> (errorHandler, driver); }
  573. /// <summary>
  574. /// Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
  575. /// <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
  576. /// </summary>
  577. /// <remarks>
  578. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  579. /// <para>
  580. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  581. /// ensure resources are cleaned up and terminal settings restored.
  582. /// </para>
  583. /// <para>
  584. /// The caller is responsible for disposing the object returned by this method.
  585. /// </para>
  586. /// </remarks>
  587. /// <param name="errorHandler"></param>
  588. /// <param name="driver">
  589. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  590. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  591. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  592. /// </param>
  593. /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
  594. public static T Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
  595. where T : Toplevel, new()
  596. {
  597. var top = new T ();
  598. Run (top, errorHandler, driver);
  599. return top;
  600. }
  601. /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
  602. /// <remarks>
  603. /// <para>
  604. /// This method is used to start processing events for the main application, but it is also used to run other
  605. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  606. /// </para>
  607. /// <para>
  608. /// To make a <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> stop execution, call
  609. /// <see cref="Application.RequestStop"/>.
  610. /// </para>
  611. /// <para>
  612. /// Calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> is equivalent to calling
  613. /// <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState)"/>, and then calling
  614. /// <see cref="End(RunState)"/>.
  615. /// </para>
  616. /// <para>
  617. /// Alternatively, to have a program control the main loop and process events manually, call
  618. /// <see cref="Begin(Toplevel)"/> to set things up manually and then repeatedly call
  619. /// <see cref="RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  620. /// <see cref="RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  621. /// return control immediately.
  622. /// </para>
  623. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  624. /// <para>
  625. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  626. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  627. /// returns <see langword="true"/> the <see cref="RunLoop(RunState)"/> will resume; otherwise this method will
  628. /// exit.
  629. /// </para>
  630. /// </remarks>
  631. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  632. /// <param name="errorHandler">
  633. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  634. /// rethrows when null).
  635. /// </param>
  636. /// <param name="driver">
  637. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  638. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  639. /// <see langword="null"/> if <see cref="Init"/> was called.
  640. /// </param>
  641. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
  642. {
  643. ArgumentNullException.ThrowIfNull (view);
  644. if (_initialized)
  645. {
  646. if (Driver is null)
  647. {
  648. // Disposing before throwing
  649. view.Dispose ();
  650. // This code path should be impossible because Init(null, null) will select the platform default driver
  651. throw new InvalidOperationException (
  652. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  653. );
  654. }
  655. }
  656. else
  657. {
  658. // Init() has NOT been called.
  659. InternalInit (driver, null, true);
  660. }
  661. var resume = true;
  662. while (resume)
  663. {
  664. #if !DEBUG
  665. try
  666. {
  667. #endif
  668. resume = false;
  669. RunState runState = Begin (view);
  670. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  671. // by using NotifyStopRunState event.
  672. RunLoop (runState);
  673. if (runState.Toplevel is null)
  674. {
  675. #if DEBUG_IDISPOSABLE
  676. Debug.Assert (_topLevels.Count == 0);
  677. #endif
  678. runState.Dispose ();
  679. return;
  680. }
  681. if (!EndAfterFirstIteration)
  682. {
  683. End (runState);
  684. }
  685. #if !DEBUG
  686. }
  687. catch (Exception error)
  688. {
  689. if (errorHandler is null)
  690. {
  691. throw;
  692. }
  693. resume = errorHandler (error);
  694. }
  695. #endif
  696. }
  697. }
  698. /// <summary>Adds a timeout to the application.</summary>
  699. /// <remarks>
  700. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  701. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  702. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  703. /// </remarks>
  704. public static object AddTimeout (TimeSpan time, Func<bool> callback) { return MainLoop?.AddTimeout (time, callback); }
  705. /// <summary>Removes a previously scheduled timeout</summary>
  706. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  707. /// Returns
  708. /// <c>true</c>
  709. /// if the timeout is successfully removed; otherwise,
  710. /// <c>false</c>
  711. /// .
  712. /// This method also returns
  713. /// <c>false</c>
  714. /// if the timeout is not found.
  715. public static bool RemoveTimeout (object token) { return MainLoop?.RemoveTimeout (token) ?? false; }
  716. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  717. /// <param name="action">the action to be invoked on the main processing thread.</param>
  718. public static void Invoke (Action action)
  719. {
  720. MainLoop?.AddIdle (
  721. () =>
  722. {
  723. action ();
  724. return false;
  725. }
  726. );
  727. }
  728. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  729. // is ProgressBarStyles and it's not clear it needs to.
  730. /// <summary>Wakes up the running application that might be waiting on input.</summary>
  731. public static void Wakeup () { MainLoop?.Wakeup (); }
  732. /// <summary>Triggers a refresh of the entire display.</summary>
  733. public static void Refresh ()
  734. {
  735. // TODO: Figure out how to remove this call to ClearContents. Refresh should just repaint damaged areas, not clear
  736. Driver.ClearContents ();
  737. View last = null;
  738. foreach (Toplevel v in _topLevels.Reverse ())
  739. {
  740. if (v.Visible)
  741. {
  742. v.SetNeedsDisplay ();
  743. v.SetSubViewNeedsDisplay ();
  744. v.Draw ();
  745. }
  746. last = v;
  747. }
  748. Driver.Refresh ();
  749. }
  750. /// <summary>This event is raised on each iteration of the main loop.</summary>
  751. /// <remarks>See also <see cref="Timeout"/></remarks>
  752. public static event EventHandler<IterationEventArgs> Iteration;
  753. /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
  754. /// <value>The main loop.</value>
  755. internal static MainLoop MainLoop { get; private set; }
  756. /// <summary>
  757. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  758. /// cause the application to continue running until Application.RequestStop () is called.
  759. /// </summary>
  760. public static bool EndAfterFirstIteration { get; set; }
  761. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  762. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  763. public static void RunLoop (RunState state)
  764. {
  765. ArgumentNullException.ThrowIfNull (state);
  766. ObjectDisposedException.ThrowIf (state.Toplevel is null, "state");
  767. var firstIteration = true;
  768. for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
  769. {
  770. MainLoop.Running = true;
  771. if (EndAfterFirstIteration && !firstIteration)
  772. {
  773. return;
  774. }
  775. RunIteration (ref state, ref firstIteration);
  776. }
  777. MainLoop.Running = false;
  778. // Run one last iteration to consume any outstanding input events from Driver
  779. // This is important for remaining OnKeyUp events.
  780. RunIteration (ref state, ref firstIteration);
  781. }
  782. /// <summary>Run one application iteration.</summary>
  783. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  784. /// <param name="firstIteration">
  785. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  786. /// will be set to <see langword="false"/> if at least one iteration happened.
  787. /// </param>
  788. public static void RunIteration (ref RunState state, ref bool firstIteration)
  789. {
  790. if (MainLoop.Running && MainLoop.EventsPending ())
  791. {
  792. // Notify Toplevel it's ready
  793. if (firstIteration)
  794. {
  795. state.Toplevel.OnReady ();
  796. }
  797. MainLoop.RunIteration ();
  798. Iteration?.Invoke (null, new ());
  799. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  800. if (state.Toplevel != Current)
  801. {
  802. OverlappedTop?.OnDeactivate (state.Toplevel);
  803. state.Toplevel = Current;
  804. OverlappedTop?.OnActivate (state.Toplevel);
  805. Top.SetSubViewNeedsDisplay ();
  806. Refresh ();
  807. }
  808. }
  809. firstIteration = false;
  810. if (Current == null)
  811. {
  812. return;
  813. }
  814. if (state.Toplevel != Top && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  815. {
  816. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  817. Top.Draw ();
  818. foreach (Toplevel top in _topLevels.Reverse ())
  819. {
  820. if (top != Top && top != state.Toplevel)
  821. {
  822. top.SetNeedsDisplay ();
  823. top.SetSubViewNeedsDisplay ();
  824. top.Draw ();
  825. }
  826. }
  827. }
  828. if (_topLevels.Count == 1
  829. && state.Toplevel == Top
  830. && (Driver.Cols != state.Toplevel.Frame.Width
  831. || Driver.Rows != state.Toplevel.Frame.Height)
  832. && (state.Toplevel.NeedsDisplay
  833. || state.Toplevel.SubViewNeedsDisplay
  834. || state.Toplevel.LayoutNeeded))
  835. {
  836. Driver.ClearContents ();
  837. }
  838. if (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded || OverlappedChildNeedsDisplay ())
  839. {
  840. state.Toplevel.Draw ();
  841. Driver.UpdateScreen ();
  842. //Driver.UpdateCursor ();
  843. }
  844. if (PositionCursor (state.Toplevel))
  845. {
  846. Driver.UpdateCursor();
  847. }
  848. // else
  849. {
  850. //if (PositionCursor (state.Toplevel))
  851. //{
  852. // Driver.Refresh ();
  853. //}
  854. //Driver.UpdateCursor ();
  855. }
  856. if (state.Toplevel != Top && !state.Toplevel.Modal && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  857. {
  858. Top.Draw ();
  859. }
  860. }
  861. /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
  862. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  863. /// <remarks>
  864. /// <para>This will cause <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> to return.</para>
  865. /// <para>
  866. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  867. /// property on the currently running <see cref="Toplevel"/> to false.
  868. /// </para>
  869. /// </remarks>
  870. public static void RequestStop (Toplevel top = null)
  871. {
  872. if (OverlappedTop is null || top is null || (OverlappedTop is null && top is { }))
  873. {
  874. top = Current;
  875. }
  876. if (OverlappedTop != null
  877. && top.IsOverlappedContainer
  878. && top?.Running == true
  879. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false)))
  880. {
  881. OverlappedTop.RequestStop ();
  882. }
  883. else if (OverlappedTop != null
  884. && top != Current
  885. && Current?.Running == true
  886. && Current?.Modal == true
  887. && top.Modal
  888. && top.Running)
  889. {
  890. var ev = new ToplevelClosingEventArgs (Current);
  891. Current.OnClosing (ev);
  892. if (ev.Cancel)
  893. {
  894. return;
  895. }
  896. ev = new (top);
  897. top.OnClosing (ev);
  898. if (ev.Cancel)
  899. {
  900. return;
  901. }
  902. Current.Running = false;
  903. OnNotifyStopRunState (Current);
  904. top.Running = false;
  905. OnNotifyStopRunState (top);
  906. }
  907. else if ((OverlappedTop != null
  908. && top != OverlappedTop
  909. && top != Current
  910. && Current?.Modal == false
  911. && Current?.Running == true
  912. && !top.Running)
  913. || (OverlappedTop != null
  914. && top != OverlappedTop
  915. && top != Current
  916. && Current?.Modal == false
  917. && Current?.Running == false
  918. && !top.Running
  919. && _topLevels.ToArray () [1].Running))
  920. {
  921. MoveCurrent (top);
  922. }
  923. else if (OverlappedTop != null
  924. && Current != top
  925. && Current?.Running == true
  926. && !top.Running
  927. && Current?.Modal == true
  928. && top.Modal)
  929. {
  930. // The Current and the top are both modal so needed to set the Current.Running to false too.
  931. Current.Running = false;
  932. OnNotifyStopRunState (Current);
  933. }
  934. else if (OverlappedTop != null
  935. && Current == top
  936. && OverlappedTop?.Running == true
  937. && Current?.Running == true
  938. && top.Running
  939. && Current?.Modal == true
  940. && top.Modal)
  941. {
  942. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  943. // both are the same, so needed to set the Current.Running to false too.
  944. Current.Running = false;
  945. OnNotifyStopRunState (Current);
  946. }
  947. else
  948. {
  949. Toplevel currentTop;
  950. if (top == Current || (Current?.Modal == true && !top.Modal))
  951. {
  952. currentTop = Current;
  953. }
  954. else
  955. {
  956. currentTop = top;
  957. }
  958. if (!currentTop.Running)
  959. {
  960. return;
  961. }
  962. var ev = new ToplevelClosingEventArgs (currentTop);
  963. currentTop.OnClosing (ev);
  964. if (ev.Cancel)
  965. {
  966. return;
  967. }
  968. currentTop.Running = false;
  969. OnNotifyStopRunState (currentTop);
  970. }
  971. }
  972. private static void OnNotifyStopRunState (Toplevel top)
  973. {
  974. if (EndAfterFirstIteration)
  975. {
  976. NotifyStopRunState?.Invoke (top, new (top));
  977. }
  978. }
  979. /// <summary>
  980. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  981. /// <see cref="Begin(Toplevel)"/> .
  982. /// </summary>
  983. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  984. public static void End (RunState runState)
  985. {
  986. ArgumentNullException.ThrowIfNull (runState);
  987. if (OverlappedTop is { })
  988. {
  989. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  990. }
  991. else
  992. {
  993. runState.Toplevel.OnUnloaded ();
  994. }
  995. // End the RunState.Toplevel
  996. // First, take it off the Toplevel Stack
  997. if (_topLevels.Count > 0)
  998. {
  999. if (_topLevels.Peek () != runState.Toplevel)
  1000. {
  1001. // If there the top of the stack is not the RunState.Toplevel then
  1002. // this call to End is not balanced with the call to Begin that started the RunState
  1003. throw new ArgumentException ("End must be balanced with calls to Begin");
  1004. }
  1005. _topLevels.Pop ();
  1006. }
  1007. // Notify that it is closing
  1008. runState.Toplevel?.OnClosed (runState.Toplevel);
  1009. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  1010. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  1011. if (OverlappedTop is { } && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop)
  1012. {
  1013. OverlappedTop.OnChildClosed (runState.Toplevel);
  1014. }
  1015. // Set Current and Top to the next TopLevel on the stack
  1016. if (_topLevels.Count == 0)
  1017. {
  1018. Current = null;
  1019. }
  1020. else
  1021. {
  1022. if (_topLevels.Count > 1 && _topLevels.Peek () == OverlappedTop && OverlappedChildren.Any (t => t.Visible) is { })
  1023. {
  1024. OverlappedMoveNext ();
  1025. }
  1026. Current = _topLevels.Peek ();
  1027. if (_topLevels.Count == 1 && Current == OverlappedTop)
  1028. {
  1029. OverlappedTop.OnAllChildClosed ();
  1030. }
  1031. else
  1032. {
  1033. SetCurrentOverlappedAsTop ();
  1034. runState.Toplevel.OnLeave (Current);
  1035. Current.OnEnter (runState.Toplevel);
  1036. }
  1037. Refresh ();
  1038. }
  1039. // Don't dispose runState.Toplevel. It's up to caller dispose it
  1040. // If it's not the same as the current in the RunIteration,
  1041. // it will be fixed later in the next RunIteration.
  1042. if (OverlappedTop is { } && !_topLevels.Contains (OverlappedTop))
  1043. {
  1044. _cachedRunStateToplevel = OverlappedTop;
  1045. }
  1046. else
  1047. {
  1048. _cachedRunStateToplevel = runState.Toplevel;
  1049. }
  1050. runState.Toplevel = null;
  1051. runState.Dispose ();
  1052. }
  1053. #endregion Run (Begin, Run, End)
  1054. #region Toplevel handling
  1055. /// <summary>Holds the stack of TopLevel views.</summary>
  1056. // BUGBUG: Techncally, this is not the full lst of TopLevels. THere be dragons hwre. E.g. see how Toplevel.Id is used. What
  1057. // about TopLevels that are just a SubView of another View?
  1058. internal static readonly Stack<Toplevel> _topLevels = new ();
  1059. /// <summary>The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)</summary>
  1060. /// <value>The top.</value>
  1061. public static Toplevel Top { get; private set; }
  1062. /// <summary>
  1063. /// The current <see cref="Toplevel"/> object. This is updated in <see cref="Application.Begin"/> enters and leaves to
  1064. /// point to the current
  1065. /// <see cref="Toplevel"/> .
  1066. /// </summary>
  1067. /// <remarks>
  1068. /// Only relevant in scenarios where <see cref="Toplevel.IsOverlappedContainer"/> is <see langword="true"/>.
  1069. /// </remarks>
  1070. /// <value>The current.</value>
  1071. public static Toplevel Current { get; private set; }
  1072. private static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  1073. {
  1074. if (!Toplevel.Running
  1075. || (Toplevel == Current && Toplevel.Visible)
  1076. || OverlappedTop == null
  1077. || _topLevels.Peek ().Modal)
  1078. {
  1079. return;
  1080. }
  1081. foreach (Toplevel top in _topLevels.Reverse ())
  1082. {
  1083. if (top.Modal && top != Current)
  1084. {
  1085. MoveCurrent (top);
  1086. return;
  1087. }
  1088. }
  1089. if (!Toplevel.Visible && Toplevel == Current)
  1090. {
  1091. OverlappedMoveNext ();
  1092. }
  1093. }
  1094. #nullable enable
  1095. private static Toplevel? FindDeepestTop (Toplevel start, int x, int y)
  1096. {
  1097. if (!start.Frame.Contains (x, y))
  1098. {
  1099. return null;
  1100. }
  1101. if (_topLevels is { Count: > 0 })
  1102. {
  1103. int rx = x - start.Frame.X;
  1104. int ry = y - start.Frame.Y;
  1105. foreach (Toplevel t in _topLevels)
  1106. {
  1107. if (t != Current)
  1108. {
  1109. if (t != start && t.Visible && t.Frame.Contains (rx, ry))
  1110. {
  1111. start = t;
  1112. break;
  1113. }
  1114. }
  1115. }
  1116. }
  1117. return start;
  1118. }
  1119. #nullable restore
  1120. private static View FindTopFromView (View view)
  1121. {
  1122. View top = view?.SuperView is { } && view?.SuperView != Top
  1123. ? view.SuperView
  1124. : view;
  1125. while (top?.SuperView is { } && top?.SuperView != Top)
  1126. {
  1127. top = top.SuperView;
  1128. }
  1129. return top;
  1130. }
  1131. #nullable enable
  1132. // Only return true if the Current has changed.
  1133. private static bool MoveCurrent (Toplevel? top)
  1134. {
  1135. // The Current is modal and the top is not modal Toplevel then
  1136. // the Current must be moved above the first not modal Toplevel.
  1137. if (OverlappedTop is { }
  1138. && top != OverlappedTop
  1139. && top != Current
  1140. && Current?.Modal == true
  1141. && !_topLevels.Peek ().Modal)
  1142. {
  1143. lock (_topLevels)
  1144. {
  1145. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1146. }
  1147. var index = 0;
  1148. Toplevel [] savedToplevels = _topLevels.ToArray ();
  1149. foreach (Toplevel t in savedToplevels)
  1150. {
  1151. if (!t.Modal && t != Current && t != top && t != savedToplevels [index])
  1152. {
  1153. lock (_topLevels)
  1154. {
  1155. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  1156. }
  1157. }
  1158. index++;
  1159. }
  1160. return false;
  1161. }
  1162. // The Current and the top are both not running Toplevel then
  1163. // the top must be moved above the first not running Toplevel.
  1164. if (OverlappedTop is { }
  1165. && top != OverlappedTop
  1166. && top != Current
  1167. && Current?.Running == false
  1168. && top?.Running == false)
  1169. {
  1170. lock (_topLevels)
  1171. {
  1172. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1173. }
  1174. var index = 0;
  1175. foreach (Toplevel t in _topLevels.ToArray ())
  1176. {
  1177. if (!t.Running && t != Current && index > 0)
  1178. {
  1179. lock (_topLevels)
  1180. {
  1181. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  1182. }
  1183. }
  1184. index++;
  1185. }
  1186. return false;
  1187. }
  1188. if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top)
  1189. || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  1190. || (OverlappedTop is { } && Current?.Modal == false && top != Current)
  1191. || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop))
  1192. {
  1193. lock (_topLevels)
  1194. {
  1195. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1196. Current = top;
  1197. }
  1198. }
  1199. return true;
  1200. }
  1201. #nullable restore
  1202. /// <summary>Invoked when the terminal's size changed. The new size of the terminal is provided.</summary>
  1203. /// <remarks>
  1204. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/> to prevent
  1205. /// <see cref="Application"/> from changing it's size to match the new terminal size.
  1206. /// </remarks>
  1207. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  1208. /// <summary>
  1209. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and fires the
  1210. /// <see cref="SizeChanging"/> event.
  1211. /// </summary>
  1212. /// <param name="args">The new size.</param>
  1213. /// <returns><see lanword="true"/>if the size was changed.</returns>
  1214. public static bool OnSizeChanging (SizeChangedEventArgs args)
  1215. {
  1216. SizeChanging?.Invoke (null, args);
  1217. if (args.Cancel || args.Size is null)
  1218. {
  1219. return false;
  1220. }
  1221. foreach (Toplevel t in _topLevels)
  1222. {
  1223. t.SetRelativeLayout (args.Size.Value);
  1224. t.LayoutSubviews ();
  1225. t.PositionToplevels ();
  1226. t.OnSizeChanging (new (args.Size));
  1227. if (PositionCursor (t))
  1228. {
  1229. Driver.UpdateCursor ();
  1230. }
  1231. }
  1232. Refresh ();
  1233. return true;
  1234. }
  1235. #endregion Toplevel handling
  1236. #region Mouse handling
  1237. /// <summary>Disable or enable the mouse. The mouse is enabled by default.</summary>
  1238. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1239. public static bool IsMouseDisabled { get; set; }
  1240. /// <summary>The current <see cref="View"/> object that wants continuous mouse button pressed events.</summary>
  1241. public static View WantContinuousButtonPressedView { get; private set; }
  1242. /// <summary>
  1243. /// Gets the view that grabbed the mouse (e.g. for dragging). When this is set, all mouse events will be routed to
  1244. /// this view until the view calls <see cref="UngrabMouse"/> or the mouse is released.
  1245. /// </summary>
  1246. public static View MouseGrabView { get; private set; }
  1247. /// <summary>Invoked when a view wants to grab the mouse; can be canceled.</summary>
  1248. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  1249. /// <summary>Invoked when a view wants un-grab the mouse; can be canceled.</summary>
  1250. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  1251. /// <summary>Invoked after a view has grabbed the mouse.</summary>
  1252. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  1253. /// <summary>Invoked after a view has un-grabbed the mouse.</summary>
  1254. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  1255. /// <summary>
  1256. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/>
  1257. /// is called.
  1258. /// </summary>
  1259. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  1260. public static void GrabMouse (View view)
  1261. {
  1262. if (view is null)
  1263. {
  1264. return;
  1265. }
  1266. if (!OnGrabbingMouse (view))
  1267. {
  1268. OnGrabbedMouse (view);
  1269. MouseGrabView = view;
  1270. }
  1271. }
  1272. /// <summary>Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.</summary>
  1273. public static void UngrabMouse ()
  1274. {
  1275. if (MouseGrabView is null)
  1276. {
  1277. return;
  1278. }
  1279. if (!OnUnGrabbingMouse (MouseGrabView))
  1280. {
  1281. View view = MouseGrabView;
  1282. MouseGrabView = null;
  1283. OnUnGrabbedMouse (view);
  1284. }
  1285. }
  1286. private static bool OnGrabbingMouse (View view)
  1287. {
  1288. if (view is null)
  1289. {
  1290. return false;
  1291. }
  1292. var evArgs = new GrabMouseEventArgs (view);
  1293. GrabbingMouse?.Invoke (view, evArgs);
  1294. return evArgs.Cancel;
  1295. }
  1296. private static bool OnUnGrabbingMouse (View view)
  1297. {
  1298. if (view is null)
  1299. {
  1300. return false;
  1301. }
  1302. var evArgs = new GrabMouseEventArgs (view);
  1303. UnGrabbingMouse?.Invoke (view, evArgs);
  1304. return evArgs.Cancel;
  1305. }
  1306. private static void OnGrabbedMouse (View view)
  1307. {
  1308. if (view is null)
  1309. {
  1310. return;
  1311. }
  1312. GrabbedMouse?.Invoke (view, new (view));
  1313. }
  1314. private static void OnUnGrabbedMouse (View view)
  1315. {
  1316. if (view is null)
  1317. {
  1318. return;
  1319. }
  1320. UnGrabbedMouse?.Invoke (view, new (view));
  1321. }
  1322. #nullable enable
  1323. // Used by OnMouseEvent to track the last view that was clicked on.
  1324. internal static View? _mouseEnteredView;
  1325. /// <summary>Event fired when a mouse move or click occurs. Coordinates are screen relative.</summary>
  1326. /// <remarks>
  1327. /// <para>
  1328. /// Use this event to receive mouse events in screen coordinates. Use <see cref="MouseEvent"/> to
  1329. /// receive mouse events relative to a <see cref="View.Viewport"/>.
  1330. /// </para>
  1331. /// <para>The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.</para>
  1332. /// </remarks>
  1333. public static event EventHandler<MouseEvent>? MouseEvent;
  1334. /// <summary>Called when a mouse event occurs. Raises the <see cref="MouseEvent"/> event.</summary>
  1335. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  1336. /// <param name="mouseEvent">The mouse event with coordinates relative to the screen.</param>
  1337. internal static void OnMouseEvent (MouseEvent mouseEvent)
  1338. {
  1339. if (IsMouseDisabled)
  1340. {
  1341. return;
  1342. }
  1343. var view = View.FindDeepestView (Current, mouseEvent.X, mouseEvent.Y);
  1344. if (view is { })
  1345. {
  1346. mouseEvent.View = view;
  1347. }
  1348. MouseEvent?.Invoke (null, mouseEvent);
  1349. if (mouseEvent.Handled)
  1350. {
  1351. return;
  1352. }
  1353. if (MouseGrabView is { })
  1354. {
  1355. // If the mouse is grabbed, send the event to the view that grabbed it.
  1356. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  1357. Point frameLoc = MouseGrabView.ScreenToViewport (mouseEvent.X, mouseEvent.Y);
  1358. var viewRelativeMouseEvent = new MouseEvent
  1359. {
  1360. X = frameLoc.X,
  1361. Y = frameLoc.Y,
  1362. Flags = mouseEvent.Flags,
  1363. ScreenPosition = new (mouseEvent.X, mouseEvent.Y),
  1364. View = MouseGrabView
  1365. };
  1366. if ((MouseGrabView.Viewport with { Location = Point.Empty }).Contains (viewRelativeMouseEvent.X, viewRelativeMouseEvent.Y) is false)
  1367. {
  1368. // The mouse has moved outside the bounds of the view that grabbed the mouse
  1369. _mouseEnteredView?.NewMouseLeaveEvent (mouseEvent);
  1370. }
  1371. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1372. if (MouseGrabView?.NewMouseEvent (viewRelativeMouseEvent) == true)
  1373. {
  1374. return;
  1375. }
  1376. }
  1377. if (view is { WantContinuousButtonPressed: true })
  1378. {
  1379. WantContinuousButtonPressedView = view;
  1380. }
  1381. else
  1382. {
  1383. WantContinuousButtonPressedView = null;
  1384. }
  1385. if (view is not Adornment)
  1386. {
  1387. if ((view is null || view == OverlappedTop)
  1388. && Current is { Modal: false }
  1389. && OverlappedTop != null
  1390. && mouseEvent.Flags != MouseFlags.ReportMousePosition
  1391. && mouseEvent.Flags != 0)
  1392. {
  1393. // This occurs when there are multiple overlapped "tops"
  1394. // E.g. "Mdi" - in the Background Worker Scenario
  1395. View? top = FindDeepestTop (Top, mouseEvent.X, mouseEvent.Y);
  1396. view = View.FindDeepestView (top, mouseEvent.X, mouseEvent.Y);
  1397. if (view is { } && view != OverlappedTop && top != Current)
  1398. {
  1399. MoveCurrent ((Toplevel)top);
  1400. }
  1401. }
  1402. }
  1403. if (view is null)
  1404. {
  1405. return;
  1406. }
  1407. MouseEvent? me = null;
  1408. if (view is Adornment adornment)
  1409. {
  1410. Point frameLoc = adornment.ScreenToFrame (mouseEvent.X, mouseEvent.Y);
  1411. me = new ()
  1412. {
  1413. X = frameLoc.X,
  1414. Y = frameLoc.Y,
  1415. Flags = mouseEvent.Flags,
  1416. ScreenPosition = new (mouseEvent.X, mouseEvent.Y),
  1417. View = view
  1418. };
  1419. }
  1420. else if (view.ViewportToScreen (Rectangle.Empty with { Size = view.Viewport.Size }).Contains (mouseEvent.X, mouseEvent.Y))
  1421. {
  1422. Point viewportLocation = view.ScreenToViewport (mouseEvent.X, mouseEvent.Y);
  1423. me = new ()
  1424. {
  1425. X = viewportLocation.X,
  1426. Y = viewportLocation.Y,
  1427. Flags = mouseEvent.Flags,
  1428. ScreenPosition = new (mouseEvent.X, mouseEvent.Y),
  1429. View = view
  1430. };
  1431. }
  1432. if (me is null)
  1433. {
  1434. return;
  1435. }
  1436. if (_mouseEnteredView is null)
  1437. {
  1438. _mouseEnteredView = view;
  1439. view.NewMouseEnterEvent (me);
  1440. }
  1441. else if (_mouseEnteredView != view)
  1442. {
  1443. _mouseEnteredView.NewMouseLeaveEvent (me);
  1444. view.NewMouseEnterEvent (me);
  1445. _mouseEnteredView = view;
  1446. }
  1447. if (!view.WantMousePositionReports && mouseEvent.Flags == MouseFlags.ReportMousePosition)
  1448. {
  1449. return;
  1450. }
  1451. WantContinuousButtonPressedView = view.WantContinuousButtonPressed ? view : null;
  1452. //Debug.WriteLine ($"OnMouseEvent: ({a.MouseEvent.X},{a.MouseEvent.Y}) - {a.MouseEvent.Flags}");
  1453. while (view.NewMouseEvent (me) != true)
  1454. {
  1455. if (MouseGrabView is { })
  1456. {
  1457. break;
  1458. }
  1459. if (view is Adornment adornmentView)
  1460. {
  1461. view = adornmentView.Parent.SuperView;
  1462. }
  1463. else
  1464. {
  1465. view = view.SuperView;
  1466. }
  1467. if (view is null)
  1468. {
  1469. break;
  1470. }
  1471. Point boundsPoint = view.ScreenToViewport (mouseEvent.X, mouseEvent.Y);
  1472. me = new ()
  1473. {
  1474. X = boundsPoint.X,
  1475. Y = boundsPoint.Y,
  1476. Flags = mouseEvent.Flags,
  1477. ScreenPosition = new (mouseEvent.X, mouseEvent.Y),
  1478. View = view
  1479. };
  1480. }
  1481. BringOverlappedTopToFront ();
  1482. }
  1483. #nullable restore
  1484. #endregion Mouse handling
  1485. #region Keyboard handling
  1486. private static Key _alternateForwardKey = Key.Empty; // Defined in config.json
  1487. /// <summary>Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.</summary>
  1488. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1489. [JsonConverter (typeof (KeyJsonConverter))]
  1490. public static Key AlternateForwardKey
  1491. {
  1492. get => _alternateForwardKey;
  1493. set
  1494. {
  1495. if (_alternateForwardKey != value)
  1496. {
  1497. Key oldKey = _alternateForwardKey;
  1498. _alternateForwardKey = value;
  1499. OnAlternateForwardKeyChanged (new (oldKey, value));
  1500. }
  1501. }
  1502. }
  1503. private static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1504. {
  1505. foreach (Toplevel top in _topLevels.ToArray ())
  1506. {
  1507. top.OnAlternateForwardKeyChanged (e);
  1508. }
  1509. }
  1510. private static Key _alternateBackwardKey = Key.Empty; // Defined in config.json
  1511. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  1512. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1513. [JsonConverter (typeof (KeyJsonConverter))]
  1514. public static Key AlternateBackwardKey
  1515. {
  1516. get => _alternateBackwardKey;
  1517. set
  1518. {
  1519. if (_alternateBackwardKey != value)
  1520. {
  1521. Key oldKey = _alternateBackwardKey;
  1522. _alternateBackwardKey = value;
  1523. OnAlternateBackwardKeyChanged (new (oldKey, value));
  1524. }
  1525. }
  1526. }
  1527. private static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1528. {
  1529. foreach (Toplevel top in _topLevels.ToArray ())
  1530. {
  1531. top.OnAlternateBackwardKeyChanged (oldKey);
  1532. }
  1533. }
  1534. private static Key _quitKey = Key.Empty; // Defined in config.json
  1535. /// <summary>Gets or sets the key to quit the application.</summary>
  1536. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1537. [JsonConverter (typeof (KeyJsonConverter))]
  1538. public static Key QuitKey
  1539. {
  1540. get => _quitKey;
  1541. set
  1542. {
  1543. if (_quitKey != value)
  1544. {
  1545. Key oldKey = _quitKey;
  1546. _quitKey = value;
  1547. OnQuitKeyChanged (new (oldKey, value));
  1548. }
  1549. }
  1550. }
  1551. private static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1552. {
  1553. // Duplicate the list so if it changes during enumeration we're safe
  1554. foreach (Toplevel top in _topLevels.ToArray ())
  1555. {
  1556. top.OnQuitKeyChanged (e);
  1557. }
  1558. }
  1559. /// <summary>
  1560. /// Event fired when the user presses a key. Fired by <see cref="OnKeyDown"/>.
  1561. /// <para>
  1562. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1563. /// additional processing.
  1564. /// </para>
  1565. /// </summary>
  1566. /// <remarks>
  1567. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1568. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1569. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  1570. /// </remarks>
  1571. public static event EventHandler<Key> KeyDown;
  1572. /// <summary>
  1573. /// Called by the <see cref="ConsoleDriver"/> when the user presses a key. Fires the <see cref="KeyDown"/> event
  1574. /// then calls <see cref="View.NewKeyDownEvent"/> on all top level views. Called after <see cref="OnKeyDown"/> and
  1575. /// before <see cref="OnKeyUp"/>.
  1576. /// </summary>
  1577. /// <remarks>Can be used to simulate key press events.</remarks>
  1578. /// <param name="keyEvent"></param>
  1579. /// <returns><see langword="true"/> if the key was handled.</returns>
  1580. public static bool OnKeyDown (Key keyEvent)
  1581. {
  1582. if (!_initialized)
  1583. {
  1584. return true;
  1585. }
  1586. KeyDown?.Invoke (null, keyEvent);
  1587. if (keyEvent.Handled)
  1588. {
  1589. return true;
  1590. }
  1591. foreach (Toplevel topLevel in _topLevels.ToList ())
  1592. {
  1593. if (topLevel.NewKeyDownEvent (keyEvent))
  1594. {
  1595. return true;
  1596. }
  1597. if (topLevel.Modal)
  1598. {
  1599. break;
  1600. }
  1601. }
  1602. // Invoke any Global KeyBindings
  1603. foreach (Toplevel topLevel in _topLevels.ToList ())
  1604. {
  1605. foreach (View view in topLevel.Subviews.Where (
  1606. v => v.KeyBindings.TryGet (
  1607. keyEvent,
  1608. KeyBindingScope.Application,
  1609. out KeyBinding _
  1610. )
  1611. ))
  1612. {
  1613. if (view.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.Application, out KeyBinding _))
  1614. {
  1615. bool? handled = view.OnInvokingKeyBindings (keyEvent);
  1616. if (handled is { } && (bool)handled)
  1617. {
  1618. return true;
  1619. }
  1620. }
  1621. }
  1622. }
  1623. return false;
  1624. }
  1625. /// <summary>
  1626. /// Event fired when the user releases a key. Fired by <see cref="OnKeyUp"/>.
  1627. /// <para>
  1628. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1629. /// additional processing.
  1630. /// </para>
  1631. /// </summary>
  1632. /// <remarks>
  1633. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1634. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1635. /// <para>Fired after <see cref="KeyDown"/>.</para>
  1636. /// </remarks>
  1637. public static event EventHandler<Key> KeyUp;
  1638. /// <summary>
  1639. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  1640. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  1641. /// </summary>
  1642. /// <remarks>Can be used to simulate key press events.</remarks>
  1643. /// <param name="a"></param>
  1644. /// <returns><see langword="true"/> if the key was handled.</returns>
  1645. public static bool OnKeyUp (Key a)
  1646. {
  1647. if (!_initialized)
  1648. {
  1649. return true;
  1650. }
  1651. KeyUp?.Invoke (null, a);
  1652. if (a.Handled)
  1653. {
  1654. return true;
  1655. }
  1656. foreach (Toplevel topLevel in _topLevels.ToList ())
  1657. {
  1658. if (topLevel.NewKeyUpEvent (a))
  1659. {
  1660. return true;
  1661. }
  1662. if (topLevel.Modal)
  1663. {
  1664. break;
  1665. }
  1666. }
  1667. return false;
  1668. }
  1669. #endregion Keyboard handling
  1670. }