Application.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  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 ExitRunLoopAfterFirstIteration 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. } else if (Current.SuperView == null && Current?.Modal == true) {
  603. Refresh ();
  604. }
  605. if (Driver.EnsureCursorVisibility ()) {
  606. state.Toplevel.SetNeedsDisplay ();
  607. }
  608. }
  609. firstIteration = false;
  610. if (state.Toplevel != Top &&
  611. (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded)) {
  612. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  613. Top.Clear ();
  614. Top.Draw ();
  615. foreach (var top in _topLevels.Reverse ()) {
  616. if (top != Top && top != state.Toplevel) {
  617. top.SetNeedsDisplay ();
  618. top.SetSubViewNeedsDisplay ();
  619. top.Clear ();
  620. top.Draw ();
  621. }
  622. }
  623. }
  624. if (_topLevels.Count == 1 && state.Toplevel == Top
  625. && (Driver.Cols != state.Toplevel.Frame.Width || Driver.Rows != state.Toplevel.Frame.Height)
  626. && (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded)) {
  627. state.Toplevel.Clear ();
  628. }
  629. if (state.Toplevel.NeedsDisplay ||
  630. state.Toplevel.SubViewNeedsDisplay ||
  631. state.Toplevel.LayoutNeeded ||
  632. OverlappedChildNeedsDisplay ()) {
  633. state.Toplevel.Clear ();
  634. state.Toplevel.Draw ();
  635. state.Toplevel.PositionCursor ();
  636. Driver.Refresh ();
  637. } else {
  638. Driver.UpdateCursor ();
  639. }
  640. if (state.Toplevel != Top &&
  641. !state.Toplevel.Modal &&
  642. (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded)) {
  643. Top.Draw ();
  644. }
  645. }
  646. /// <summary>
  647. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  648. /// </summary>
  649. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  650. /// <remarks>
  651. /// <para>
  652. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  653. /// </para>
  654. /// <para>
  655. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property
  656. /// on the currently running <see cref="Toplevel"/> to false.
  657. /// </para>
  658. /// </remarks>
  659. public static void RequestStop (Toplevel top = null)
  660. {
  661. if (OverlappedTop == null || top == null || (OverlappedTop == null && top != null)) {
  662. top = Current;
  663. }
  664. if (OverlappedTop != null && top.IsOverlappedContainer && top?.Running == true
  665. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  666. OverlappedTop.RequestStop ();
  667. } else if (OverlappedTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  668. && top.Modal && top.Running) {
  669. var ev = new ToplevelClosingEventArgs (Current);
  670. Current.OnClosing (ev);
  671. if (ev.Cancel) {
  672. return;
  673. }
  674. ev = new ToplevelClosingEventArgs (top);
  675. top.OnClosing (ev);
  676. if (ev.Cancel) {
  677. return;
  678. }
  679. Current.Running = false;
  680. OnNotifyStopRunState (Current);
  681. top.Running = false;
  682. OnNotifyStopRunState (top);
  683. } else if ((OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  684. && Current?.Running == true && !top.Running)
  685. || (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  686. && Current?.Running == false && !top.Running && _topLevels.ToArray () [1].Running)) {
  687. MoveCurrent (top);
  688. } else if (OverlappedTop != null && Current != top && Current?.Running == true && !top.Running
  689. && Current?.Modal == true && top.Modal) {
  690. // The Current and the top are both modal so needed to set the Current.Running to false too.
  691. Current.Running = false;
  692. OnNotifyStopRunState (Current);
  693. } else if (OverlappedTop != null && Current == top && OverlappedTop?.Running == true && Current?.Running == true && top.Running
  694. && Current?.Modal == true && top.Modal) {
  695. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  696. // both are the same, so needed to set the Current.Running to false too.
  697. Current.Running = false;
  698. OnNotifyStopRunState (Current);
  699. } else {
  700. Toplevel currentTop;
  701. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  702. currentTop = Current;
  703. } else {
  704. currentTop = top;
  705. }
  706. if (!currentTop.Running) {
  707. return;
  708. }
  709. var ev = new ToplevelClosingEventArgs (currentTop);
  710. currentTop.OnClosing (ev);
  711. if (ev.Cancel) {
  712. return;
  713. }
  714. currentTop.Running = false;
  715. OnNotifyStopRunState (currentTop);
  716. }
  717. }
  718. static void OnNotifyStopRunState (Toplevel top)
  719. {
  720. if (EndAfterFirstIteration) {
  721. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  722. }
  723. }
  724. /// <summary>
  725. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  726. /// </summary>
  727. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  728. public static void End (RunState runState)
  729. {
  730. if (runState == null) {
  731. throw new ArgumentNullException (nameof (runState));
  732. }
  733. if (OverlappedTop != null) {
  734. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  735. } else {
  736. runState.Toplevel.OnUnloaded ();
  737. }
  738. // End the RunState.Toplevel
  739. // First, take it off the Toplevel Stack
  740. if (_topLevels.Count > 0) {
  741. if (_topLevels.Peek () != runState.Toplevel) {
  742. // If there the top of the stack is not the RunState.Toplevel then
  743. // this call to End is not balanced with the call to Begin that started the RunState
  744. throw new ArgumentException ("End must be balanced with calls to Begin");
  745. }
  746. _topLevels.Pop ();
  747. }
  748. // Notify that it is closing
  749. runState.Toplevel?.OnClosed (runState.Toplevel);
  750. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  751. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  752. if (OverlappedTop != null && !(runState.Toplevel).Modal && runState.Toplevel != OverlappedTop) {
  753. OverlappedTop.OnChildClosed (runState.Toplevel);
  754. }
  755. // Set Current and Top to the next TopLevel on the stack
  756. if (_topLevels.Count == 0) {
  757. Current = null;
  758. } else {
  759. Current = _topLevels.Peek ();
  760. if (_topLevels.Count == 1 && Current == OverlappedTop) {
  761. OverlappedTop.OnAllChildClosed ();
  762. } else {
  763. SetCurrentOverlappedAsTop ();
  764. runState.Toplevel.OnLeave (Current);
  765. Current.OnEnter (runState.Toplevel);
  766. }
  767. Refresh ();
  768. }
  769. runState.Toplevel?.Dispose ();
  770. runState.Toplevel = null;
  771. runState.Dispose ();
  772. }
  773. #endregion Run (Begin, Run, End)
  774. #region Toplevel handling
  775. static readonly Stack<Toplevel> _topLevels = new Stack<Toplevel> ();
  776. /// <summary>
  777. /// The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)
  778. /// </summary>
  779. /// <value>The top.</value>
  780. public static Toplevel Top { get; private set; }
  781. /// <summary>
  782. /// The current <see cref="Toplevel"/> object. This is updated when <see cref="Application.Run(Func{Exception, bool})"/>
  783. /// enters and leaves to point to the current <see cref="Toplevel"/> .
  784. /// </summary>
  785. /// <value>The current.</value>
  786. public static Toplevel Current { get; private set; }
  787. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  788. {
  789. if (!Toplevel.Running || (Toplevel == Current && Toplevel.Visible) || OverlappedTop == null || _topLevels.Peek ().Modal) {
  790. return;
  791. }
  792. foreach (var top in _topLevels.Reverse ()) {
  793. if (top.Modal && top != Current) {
  794. MoveCurrent (top);
  795. return;
  796. }
  797. }
  798. if (!Toplevel.Visible && Toplevel == Current) {
  799. OverlappedMoveNext ();
  800. }
  801. }
  802. static View FindDeepestTop (Toplevel start, int x, int y, out int resx, out int resy)
  803. {
  804. var startFrame = start.Frame;
  805. if (!startFrame.Contains (x, y)) {
  806. resx = 0;
  807. resy = 0;
  808. return null;
  809. }
  810. if (_topLevels != null) {
  811. int count = _topLevels.Count;
  812. if (count > 0) {
  813. var rx = x - startFrame.X;
  814. var ry = y - startFrame.Y;
  815. foreach (var t in _topLevels) {
  816. if (t != Current) {
  817. if (t != start && t.Visible && t.Frame.Contains (rx, ry)) {
  818. start = t;
  819. break;
  820. }
  821. }
  822. }
  823. }
  824. }
  825. resx = x - startFrame.X;
  826. resy = y - startFrame.Y;
  827. return start;
  828. }
  829. static View FindTopFromView (View view)
  830. {
  831. View top = view?.SuperView != null && view?.SuperView != Top
  832. ? view.SuperView : view;
  833. while (top?.SuperView != null && top?.SuperView != Top) {
  834. top = top.SuperView;
  835. }
  836. return top;
  837. }
  838. // Only return true if the Current has changed.
  839. static bool MoveCurrent (Toplevel top)
  840. {
  841. // The Current is modal and the top is not modal Toplevel then
  842. // the Current must be moved above the first not modal Toplevel.
  843. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == true && !_topLevels.Peek ().Modal) {
  844. lock (_topLevels) {
  845. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  846. }
  847. var index = 0;
  848. var savedToplevels = _topLevels.ToArray ();
  849. foreach (var t in savedToplevels) {
  850. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  851. lock (_topLevels) {
  852. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  853. }
  854. }
  855. index++;
  856. }
  857. return false;
  858. }
  859. // The Current and the top are both not running Toplevel then
  860. // the top must be moved above the first not running Toplevel.
  861. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Running == false && !top.Running) {
  862. lock (_topLevels) {
  863. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  864. }
  865. var index = 0;
  866. foreach (var t in _topLevels.ToArray ()) {
  867. if (!t.Running && t != Current && index > 0) {
  868. lock (_topLevels) {
  869. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  870. }
  871. }
  872. index++;
  873. }
  874. return false;
  875. }
  876. if ((OverlappedTop != null && top?.Modal == true && _topLevels.Peek () != top)
  877. || (OverlappedTop != null && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  878. || (OverlappedTop != null && Current?.Modal == false && top != Current)
  879. || (OverlappedTop != null && Current?.Modal == true && top == OverlappedTop)) {
  880. lock (_topLevels) {
  881. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  882. Current = top;
  883. }
  884. }
  885. return true;
  886. }
  887. /// <summary>
  888. /// Invoked when the terminal's size changed. The new size of the terminal is provided.
  889. /// </summary>
  890. /// <remarks>
  891. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/>
  892. /// to prevent <see cref="Application"/> from changing it's size to match the new terminal size.
  893. /// </remarks>
  894. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  895. /// <summary>
  896. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and
  897. /// fires the <see cref="SizeChanging"/> event.
  898. /// </summary>
  899. /// <param name="args">The new size.</param>
  900. /// <returns><see lanword="true"/>if the size was changed.</returns>
  901. public static bool OnSizeChanging (SizeChangedEventArgs args)
  902. {
  903. SizeChanging?.Invoke (null, args);
  904. if (args.Cancel) {
  905. return false;
  906. }
  907. foreach (var t in _topLevels) {
  908. t.SetRelativeLayout (new Rect (0, 0, args.Size.Width, args.Size.Height));
  909. t.LayoutSubviews ();
  910. t.PositionToplevels ();
  911. t.OnSizeChanging (new SizeChangedEventArgs (args.Size));
  912. }
  913. Refresh ();
  914. return true;
  915. }
  916. #endregion Toplevel handling
  917. #region Mouse handling
  918. /// <summary>
  919. /// Disable or enable the mouse. The mouse is enabled by default.
  920. /// </summary>
  921. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  922. public static bool IsMouseDisabled { get; set; }
  923. /// <summary>
  924. /// The current <see cref="View"/> object that wants continuous mouse button pressed events.
  925. /// </summary>
  926. public static View WantContinuousButtonPressedView { get; private set; }
  927. static View _mouseGrabView;
  928. /// <summary>
  929. /// The view that grabbed the mouse, to where mouse events will be routed to.
  930. /// </summary>
  931. public static View MouseGrabView => _mouseGrabView;
  932. /// <summary>
  933. /// Invoked when a view wants to grab the mouse; can be canceled.
  934. /// </summary>
  935. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  936. /// <summary>
  937. /// Invoked when a view wants ungrab the mouse; can be canceled.
  938. /// </summary>
  939. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  940. /// <summary>
  941. /// Invoked after a view has grabbed the mouse.
  942. /// </summary>
  943. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  944. /// <summary>
  945. /// Invoked after a view has ungrabbed the mouse.
  946. /// </summary>
  947. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  948. /// <summary>
  949. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/> is called.
  950. /// </summary>
  951. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  952. public static void GrabMouse (View view)
  953. {
  954. if (view == null)
  955. return;
  956. if (!OnGrabbingMouse (view)) {
  957. OnGrabbedMouse (view);
  958. _mouseGrabView = view;
  959. //Driver.UncookMouse ();
  960. }
  961. }
  962. /// <summary>
  963. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  964. /// </summary>
  965. public static void UngrabMouse ()
  966. {
  967. if (_mouseGrabView == null)
  968. return;
  969. if (!OnUnGrabbingMouse (_mouseGrabView)) {
  970. OnUnGrabbedMouse (_mouseGrabView);
  971. _mouseGrabView = null;
  972. //Driver.CookMouse ();
  973. }
  974. }
  975. static bool OnGrabbingMouse (View view)
  976. {
  977. if (view == null)
  978. return false;
  979. var evArgs = new GrabMouseEventArgs (view);
  980. GrabbingMouse?.Invoke (view, evArgs);
  981. return evArgs.Cancel;
  982. }
  983. static bool OnUnGrabbingMouse (View view)
  984. {
  985. if (view == null)
  986. return false;
  987. var evArgs = new GrabMouseEventArgs (view);
  988. UnGrabbingMouse?.Invoke (view, evArgs);
  989. return evArgs.Cancel;
  990. }
  991. static void OnGrabbedMouse (View view)
  992. {
  993. if (view == null)
  994. return;
  995. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  996. }
  997. static void OnUnGrabbedMouse (View view)
  998. {
  999. if (view == null)
  1000. return;
  1001. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1002. }
  1003. static View _lastMouseOwnerView;
  1004. /// <summary>
  1005. /// Event fired when a mouse move or click occurs. Coordinates are screen relative.
  1006. /// </summary>
  1007. /// <remarks>
  1008. /// <para>
  1009. /// Use this event to receive mouse events in screen coordinates. Use <see cref="Responder.MouseEvent"/> to receive
  1010. /// mouse events relative to a <see cref="View"/>'s bounds.
  1011. /// </para>
  1012. /// <para>
  1013. /// The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.
  1014. /// </para>
  1015. /// </remarks>
  1016. public static event EventHandler<MouseEventEventArgs> MouseEvent;
  1017. /// <summary>
  1018. /// Called when a mouse event occurs. Fires the <see cref="MouseEvent"/> event.
  1019. /// </summary>
  1020. /// <remarks>
  1021. /// This method can be used to simulate a mouse event, e.g. in unit tests.
  1022. /// </remarks>
  1023. /// <param name="a"></param>
  1024. public static void OnMouseEvent (MouseEventEventArgs a)
  1025. {
  1026. static bool OutsideBounds (Point p, Rect r) => p.X < 0 || p.X > r.Right || p.Y < 0 || p.Y > r.Bottom;
  1027. if (IsMouseDisabled) {
  1028. return;
  1029. }
  1030. var view = View.FindDeepestView (Current, a.MouseEvent.X, a.MouseEvent.Y, out int rx, out int ry);
  1031. if (view != null && view.WantContinuousButtonPressed) {
  1032. WantContinuousButtonPressedView = view;
  1033. } else {
  1034. WantContinuousButtonPressedView = null;
  1035. }
  1036. if (view != null) {
  1037. a.MouseEvent.View = view;
  1038. }
  1039. MouseEvent?.Invoke (null, new MouseEventEventArgs (a.MouseEvent));
  1040. if (a.MouseEvent.Handled) {
  1041. return;
  1042. }
  1043. if (_mouseGrabView != null) {
  1044. var newxy = _mouseGrabView.ScreenToView (a.MouseEvent.X, a.MouseEvent.Y);
  1045. var nme = new MouseEvent () {
  1046. X = newxy.X,
  1047. Y = newxy.Y,
  1048. Flags = a.MouseEvent.Flags,
  1049. OfX = a.MouseEvent.X - newxy.X,
  1050. OfY = a.MouseEvent.Y - newxy.Y,
  1051. View = view
  1052. };
  1053. if (OutsideBounds (new Point (nme.X, nme.Y), _mouseGrabView.Bounds)) {
  1054. _lastMouseOwnerView?.OnMouseLeave (a.MouseEvent);
  1055. }
  1056. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1057. if (_mouseGrabView?.OnMouseEvent (nme) == true) {
  1058. return;
  1059. }
  1060. }
  1061. if ((view == null || view == OverlappedTop) && !Current.Modal && OverlappedTop != null
  1062. && a.MouseEvent.Flags != MouseFlags.ReportMousePosition && a.MouseEvent.Flags != 0) {
  1063. var top = FindDeepestTop (Top, a.MouseEvent.X, a.MouseEvent.Y, out _, out _);
  1064. view = View.FindDeepestView (top, a.MouseEvent.X, a.MouseEvent.Y, out rx, out ry);
  1065. if (view != null && view != OverlappedTop && top != Current) {
  1066. MoveCurrent ((Toplevel)top);
  1067. }
  1068. }
  1069. if (view != null) {
  1070. var nme = new MouseEvent () {
  1071. X = rx,
  1072. Y = ry,
  1073. Flags = a.MouseEvent.Flags,
  1074. OfX = 0,
  1075. OfY = 0,
  1076. View = view
  1077. };
  1078. if (_lastMouseOwnerView == null) {
  1079. _lastMouseOwnerView = view;
  1080. view.OnMouseEnter (nme);
  1081. } else if (_lastMouseOwnerView != view) {
  1082. _lastMouseOwnerView.OnMouseLeave (nme);
  1083. view.OnMouseEnter (nme);
  1084. _lastMouseOwnerView = view;
  1085. }
  1086. if (!view.WantMousePositionReports && a.MouseEvent.Flags == MouseFlags.ReportMousePosition)
  1087. return;
  1088. if (view.WantContinuousButtonPressed)
  1089. WantContinuousButtonPressedView = view;
  1090. else
  1091. WantContinuousButtonPressedView = null;
  1092. // Should we bubbled up the event, if it is not handled?
  1093. view.OnMouseEvent (nme);
  1094. BringOverlappedTopToFront ();
  1095. }
  1096. }
  1097. #endregion Mouse handling
  1098. #region Keyboard handling
  1099. static Key _alternateForwardKey = Key.PageDown | Key.CtrlMask;
  1100. /// <summary>
  1101. /// Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.
  1102. /// </summary>
  1103. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1104. public static Key AlternateForwardKey {
  1105. get => _alternateForwardKey;
  1106. set {
  1107. if (_alternateForwardKey != value) {
  1108. var oldKey = _alternateForwardKey;
  1109. _alternateForwardKey = value;
  1110. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1111. }
  1112. }
  1113. }
  1114. static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1115. {
  1116. foreach (var top in _topLevels.ToArray ()) {
  1117. top.OnAlternateForwardKeyChanged (e);
  1118. }
  1119. }
  1120. static Key _alternateBackwardKey = Key.PageUp | Key.CtrlMask;
  1121. /// <summary>
  1122. /// Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.
  1123. /// </summary>
  1124. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1125. public static Key AlternateBackwardKey {
  1126. get => _alternateBackwardKey;
  1127. set {
  1128. if (_alternateBackwardKey != value) {
  1129. var oldKey = _alternateBackwardKey;
  1130. _alternateBackwardKey = value;
  1131. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1132. }
  1133. }
  1134. }
  1135. static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1136. {
  1137. foreach (var top in _topLevels.ToArray ()) {
  1138. top.OnAlternateBackwardKeyChanged (oldKey);
  1139. }
  1140. }
  1141. static Key _quitKey = Key.Q | Key.CtrlMask;
  1142. /// <summary>
  1143. /// Gets or sets the key to quit the application.
  1144. /// </summary>
  1145. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1146. public static Key QuitKey {
  1147. get => _quitKey;
  1148. set {
  1149. if (_quitKey != value) {
  1150. var oldKey = _quitKey;
  1151. _quitKey = value;
  1152. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1153. }
  1154. }
  1155. }
  1156. static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1157. {
  1158. // Duplicate the list so if it changes during enumeration we're safe
  1159. foreach (var top in _topLevels.ToArray ()) {
  1160. top.OnQuitKeyChanged (e);
  1161. }
  1162. }
  1163. /// <summary>
  1164. /// Event fired after a key has been pressed and released.
  1165. /// <para>Set <see cref="KeyEventEventArgs.Handled"/> to <see langword="true"/> to suppress the event.</para>
  1166. /// </summary>
  1167. /// <remarks>
  1168. /// All drivers support firing the <see cref="KeyPressed"/> event. Some drivers (Curses)
  1169. /// do not support firing the <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1170. /// </remarks>
  1171. public static event EventHandler<KeyEventEventArgs> KeyPressed;
  1172. /// <summary>
  1173. /// Called after a key has been pressed and released. Fires the <see cref="KeyPressed"/> event.
  1174. /// <para>
  1175. /// Called for new KeyPressed events before any processing is performed or
  1176. /// views evaluate. Use for global key handling and/or debugging.
  1177. /// </para>
  1178. /// </summary>
  1179. /// <param name="a"></param>
  1180. /// <returns><see langword="true"/> if the key was handled.</returns>
  1181. public static bool OnKeyPressed (KeyEventEventArgs a)
  1182. {
  1183. KeyPressed?.Invoke (null, a);
  1184. if (a.Handled) {
  1185. return true;
  1186. }
  1187. var chain = _topLevels.ToList ();
  1188. foreach (var topLevel in chain) {
  1189. if (topLevel.ProcessHotKey (a.KeyEvent)) {
  1190. return true;
  1191. }
  1192. if (topLevel.Modal)
  1193. break;
  1194. }
  1195. foreach (var topLevel in chain) {
  1196. if (topLevel.ProcessKey (a.KeyEvent)) {
  1197. return true;
  1198. }
  1199. if (topLevel.Modal)
  1200. break;
  1201. }
  1202. foreach (var topLevel in chain) {
  1203. // Process the key normally
  1204. if (topLevel.ProcessColdKey (a.KeyEvent)) {
  1205. return true;
  1206. }
  1207. if (topLevel.Modal)
  1208. break;
  1209. }
  1210. return false;
  1211. }
  1212. /// <summary>
  1213. /// Event fired when a key is pressed (and not yet released).
  1214. /// </summary>
  1215. /// <remarks>
  1216. /// All drivers support firing the <see cref="KeyPressed"/> event. Some drivers (Curses)
  1217. /// do not support firing the <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1218. /// </remarks>
  1219. public static event EventHandler<KeyEventEventArgs> KeyDown;
  1220. /// <summary>
  1221. /// Called when a key is pressed (and not yet released). Fires the <see cref="KeyDown"/> event.
  1222. /// </summary>
  1223. /// <param name="a"></param>
  1224. public static void OnKeyDown (KeyEventEventArgs a)
  1225. {
  1226. KeyDown?.Invoke (null, a);
  1227. var chain = _topLevels.ToList ();
  1228. foreach (var topLevel in chain) {
  1229. if (topLevel.OnKeyDown (a.KeyEvent))
  1230. return;
  1231. if (topLevel.Modal)
  1232. break;
  1233. }
  1234. }
  1235. /// <summary>
  1236. /// Event fired when a key is released.
  1237. /// </summary>
  1238. /// <remarks>
  1239. /// All drivers support firing the <see cref="KeyPressed"/> event. Some drivers (Curses)
  1240. /// do not support firing the <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1241. /// </remarks>
  1242. public static event EventHandler<KeyEventEventArgs> KeyUp;
  1243. /// <summary>
  1244. /// Called when a key is released. Fires the <see cref="KeyUp"/> event.
  1245. /// </summary>
  1246. /// <param name="a"></param>
  1247. public static void OnKeyUp (KeyEventEventArgs a)
  1248. {
  1249. KeyUp?.Invoke (null, a);
  1250. var chain = _topLevels.ToList ();
  1251. foreach (var topLevel in chain) {
  1252. if (topLevel.OnKeyUp (a.KeyEvent))
  1253. return;
  1254. if (topLevel.Modal)
  1255. break;
  1256. }
  1257. }
  1258. #endregion Keyboard handling
  1259. }
  1260. /// <summary>
  1261. /// Event arguments for the <see cref="Application.Iteration"/> event.
  1262. /// </summary>
  1263. public class IterationEventArgs {
  1264. }
  1265. }