Application.cs 52 KB

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