Application.cs 62 KB

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