Application.cs 50 KB

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