Application.cs 65 KB

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