Application.cs 48 KB

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