Application.cs 61 KB

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