Application.cs 49 KB

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