Application.cs 51 KB

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