Application.cs 52 KB

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