Application.cs 63 KB

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