Application.cs 68 KB

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