Application.cs 51 KB

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