Application.cs 49 KB

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