Application.cs 64 KB

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