Application.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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. // Ensure disposing the toplevel before throwing
  581. top.Dispose ();
  582. // This code path should be impossible because Init(null, null) will select the platform default driver
  583. throw new InvalidOperationException (
  584. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  585. );
  586. }
  587. }
  588. else
  589. {
  590. // Init() has NOT been called.
  591. InternalInit (driver, null, true);
  592. }
  593. }
  594. /// <summary>Adds a timeout to the application.</summary>
  595. /// <remarks>
  596. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  597. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  598. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  599. /// </remarks>
  600. public static object AddTimeout (TimeSpan time, Func<bool> callback) { return MainLoop?.AddTimeout (time, callback); }
  601. /// <summary>Removes a previously scheduled timeout</summary>
  602. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  603. /// Returns
  604. /// <c>true</c>
  605. /// if the timeout is successfully removed; otherwise,
  606. /// <c>false</c>
  607. /// .
  608. /// This method also returns
  609. /// <c>false</c>
  610. /// if the timeout is not found.
  611. public static bool RemoveTimeout (object token) { return MainLoop?.RemoveTimeout (token) ?? false; }
  612. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  613. /// <param name="action">the action to be invoked on the main processing thread.</param>
  614. public static void Invoke (Action action)
  615. {
  616. MainLoop?.AddIdle (
  617. () =>
  618. {
  619. action ();
  620. return false;
  621. }
  622. );
  623. }
  624. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  625. // is ProgressBarStyles and it's not clear it needs to.
  626. /// <summary>Wakes up the running application that might be waiting on input.</summary>
  627. public static void Wakeup () { MainLoop?.Wakeup (); }
  628. /// <summary>Triggers a refresh of the entire display.</summary>
  629. public static void Refresh ()
  630. {
  631. // TODO: Figure out how to remove this call to ClearContents. Refresh should just repaint damaged areas, not clear
  632. Driver.ClearContents ();
  633. View last = null;
  634. foreach (Toplevel v in _topLevels.Reverse ())
  635. {
  636. if (v.Visible)
  637. {
  638. v.SetNeedsDisplay ();
  639. v.SetSubViewNeedsDisplay ();
  640. v.Draw ();
  641. }
  642. last = v;
  643. }
  644. last?.PositionCursor ();
  645. Driver.Refresh ();
  646. }
  647. /// <summary>This event is raised on each iteration of the main loop.</summary>
  648. /// <remarks>See also <see cref="Timeout"/></remarks>
  649. public static event EventHandler<IterationEventArgs> Iteration;
  650. /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
  651. /// <value>The main loop.</value>
  652. internal static MainLoop MainLoop { get; private set; }
  653. /// <summary>
  654. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  655. /// cause the application to continue running until Application.RequestStop () is called.
  656. /// </summary>
  657. public static bool EndAfterFirstIteration { get; set; }
  658. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  659. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  660. public static void RunLoop (RunState state)
  661. {
  662. if (state is null)
  663. {
  664. throw new ArgumentNullException (nameof (state));
  665. }
  666. if (state.Toplevel is null)
  667. {
  668. throw new ObjectDisposedException ("state");
  669. }
  670. var firstIteration = true;
  671. for (state.Toplevel.Running = true; state.Toplevel.Running;)
  672. {
  673. MainLoop.Running = true;
  674. if (EndAfterFirstIteration && !firstIteration)
  675. {
  676. return;
  677. }
  678. RunIteration (ref state, ref firstIteration);
  679. }
  680. MainLoop.Running = false;
  681. // Run one last iteration to consume any outstanding input events from Driver
  682. // This is important for remaining OnKeyUp events.
  683. RunIteration (ref state, ref firstIteration);
  684. }
  685. /// <summary>Run one application iteration.</summary>
  686. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  687. /// <param name="firstIteration">
  688. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  689. /// will be set to <see langword="false"/> if at least one iteration happened.
  690. /// </param>
  691. public static void RunIteration (ref RunState state, ref bool firstIteration)
  692. {
  693. if (MainLoop.Running && MainLoop.EventsPending ())
  694. {
  695. // Notify Toplevel it's ready
  696. if (firstIteration)
  697. {
  698. state.Toplevel.OnReady ();
  699. }
  700. MainLoop.RunIteration ();
  701. Iteration?.Invoke (null, new IterationEventArgs ());
  702. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  703. if (state.Toplevel != Current)
  704. {
  705. OverlappedTop?.OnDeactivate (state.Toplevel);
  706. state.Toplevel = Current;
  707. OverlappedTop?.OnActivate (state.Toplevel);
  708. Top.SetSubViewNeedsDisplay ();
  709. Refresh ();
  710. }
  711. }
  712. firstIteration = false;
  713. if (state.Toplevel != Top && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  714. {
  715. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  716. Top.Draw ();
  717. foreach (Toplevel top in _topLevels.Reverse ())
  718. {
  719. if (top != Top && top != state.Toplevel)
  720. {
  721. top.SetNeedsDisplay ();
  722. top.SetSubViewNeedsDisplay ();
  723. top.Draw ();
  724. }
  725. }
  726. }
  727. if (_topLevels.Count == 1
  728. && state.Toplevel == Top
  729. && (Driver.Cols != state.Toplevel.Frame.Width
  730. || Driver.Rows != state.Toplevel.Frame.Height)
  731. && (state.Toplevel.NeedsDisplay
  732. || state.Toplevel.SubViewNeedsDisplay
  733. || state.Toplevel.LayoutNeeded))
  734. {
  735. Driver.ClearContents ();
  736. }
  737. if (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded || OverlappedChildNeedsDisplay ())
  738. {
  739. state.Toplevel.Draw ();
  740. state.Toplevel.PositionCursor ();
  741. Driver.Refresh ();
  742. }
  743. else
  744. {
  745. Driver.UpdateCursor ();
  746. }
  747. if (state.Toplevel != Top && !state.Toplevel.Modal && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  748. {
  749. Top.Draw ();
  750. }
  751. }
  752. /// <summary>Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.</summary>
  753. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  754. /// <remarks>
  755. /// <para>This will cause <see cref="Application.Run(Func{Exception, bool}, ConsoleDriver)"/> to return.</para>
  756. /// <para>
  757. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  758. /// property on the currently running <see cref="Toplevel"/> to false.
  759. /// </para>
  760. /// </remarks>
  761. public static void RequestStop (Toplevel top = null)
  762. {
  763. if (OverlappedTop is null || top is null || (OverlappedTop is null && top is { }))
  764. {
  765. top = Current;
  766. }
  767. if (OverlappedTop != null
  768. && top.IsOverlappedContainer
  769. && top?.Running == true
  770. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false)))
  771. {
  772. OverlappedTop.RequestStop ();
  773. }
  774. else if (OverlappedTop != null
  775. && top != Current
  776. && Current?.Running == true
  777. && Current?.Modal == true
  778. && top.Modal
  779. && top.Running)
  780. {
  781. var ev = new ToplevelClosingEventArgs (Current);
  782. Current.OnClosing (ev);
  783. if (ev.Cancel)
  784. {
  785. return;
  786. }
  787. ev = new ToplevelClosingEventArgs (top);
  788. top.OnClosing (ev);
  789. if (ev.Cancel)
  790. {
  791. return;
  792. }
  793. Current.Running = false;
  794. OnNotifyStopRunState (Current);
  795. top.Running = false;
  796. OnNotifyStopRunState (top);
  797. }
  798. else if ((OverlappedTop != null
  799. && top != OverlappedTop
  800. && top != Current
  801. && Current?.Modal == false
  802. && Current?.Running == true
  803. && !top.Running)
  804. || (OverlappedTop != null
  805. && top != OverlappedTop
  806. && top != Current
  807. && Current?.Modal == false
  808. && Current?.Running == false
  809. && !top.Running
  810. && _topLevels.ToArray () [1].Running))
  811. {
  812. MoveCurrent (top);
  813. }
  814. else if (OverlappedTop != null
  815. && Current != top
  816. && Current?.Running == true
  817. && !top.Running
  818. && Current?.Modal == true
  819. && top.Modal)
  820. {
  821. // The Current and the top are both modal so needed to set the Current.Running to false too.
  822. Current.Running = false;
  823. OnNotifyStopRunState (Current);
  824. }
  825. else if (OverlappedTop != null
  826. && Current == top
  827. && OverlappedTop?.Running == true
  828. && Current?.Running == true
  829. && top.Running
  830. && Current?.Modal == true
  831. && top.Modal)
  832. {
  833. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  834. // both are the same, so needed to set the Current.Running to false too.
  835. Current.Running = false;
  836. OnNotifyStopRunState (Current);
  837. }
  838. else
  839. {
  840. Toplevel currentTop;
  841. if (top == Current || (Current?.Modal == true && !top.Modal))
  842. {
  843. currentTop = Current;
  844. }
  845. else
  846. {
  847. currentTop = top;
  848. }
  849. if (!currentTop.Running)
  850. {
  851. return;
  852. }
  853. var ev = new ToplevelClosingEventArgs (currentTop);
  854. currentTop.OnClosing (ev);
  855. if (ev.Cancel)
  856. {
  857. return;
  858. }
  859. currentTop.Running = false;
  860. OnNotifyStopRunState (currentTop);
  861. }
  862. }
  863. private static void OnNotifyStopRunState (Toplevel top)
  864. {
  865. if (EndAfterFirstIteration)
  866. {
  867. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  868. }
  869. }
  870. private static Toplevel _latestClosedRunStateToplevel;
  871. /// <summary>
  872. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  873. /// <see cref="Begin(Toplevel)"/> .
  874. /// </summary>
  875. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  876. public static void End (RunState runState)
  877. {
  878. if (runState is null)
  879. {
  880. throw new ArgumentNullException (nameof (runState));
  881. }
  882. if (OverlappedTop is { })
  883. {
  884. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  885. }
  886. else
  887. {
  888. runState.Toplevel.OnUnloaded ();
  889. }
  890. // End the RunState.Toplevel
  891. // First, take it off the Toplevel Stack
  892. if (_topLevels.Count > 0)
  893. {
  894. if (_topLevels.Peek () != runState.Toplevel)
  895. {
  896. // If there the top of the stack is not the RunState.Toplevel then
  897. // this call to End is not balanced with the call to Begin that started the RunState
  898. throw new ArgumentException ("End must be balanced with calls to Begin");
  899. }
  900. _topLevels.Pop ();
  901. }
  902. // Notify that it is closing
  903. runState.Toplevel?.OnClosed (runState.Toplevel);
  904. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  905. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  906. if (OverlappedTop is { } && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop)
  907. {
  908. OverlappedTop.OnChildClosed (runState.Toplevel);
  909. }
  910. // Set Current and Top to the next TopLevel on the stack
  911. if (_topLevels.Count == 0)
  912. {
  913. Current = null;
  914. }
  915. else
  916. {
  917. Current = _topLevels.Peek ();
  918. if (_topLevels.Count == 1 && Current == OverlappedTop)
  919. {
  920. OverlappedTop.OnAllChildClosed ();
  921. }
  922. else
  923. {
  924. SetCurrentOverlappedAsTop ();
  925. runState.Toplevel.OnLeave (Current);
  926. Current.OnEnter (runState.Toplevel);
  927. }
  928. Refresh ();
  929. }
  930. // Don't dispose runState.Toplevel. It's up to caller dispose it
  931. // If it's not the same as the current in the RunIteration,
  932. // it will be fixed later in the next RunIteration.
  933. _latestClosedRunStateToplevel = runState.Toplevel;
  934. runState.Toplevel = null;
  935. runState.Dispose ();
  936. }
  937. #endregion Run (Begin, Run, End)
  938. #region Toplevel handling
  939. /// <summary>Holds the stack of TopLevel views.</summary>
  940. // BUGBUG: Techncally, this is not the full lst of TopLevels. THere be dragons hwre. E.g. see how Toplevel.Id is used. What
  941. // about TopLevels that are just a SubView of another View?
  942. internal static readonly Stack<Toplevel> _topLevels = new ();
  943. /// <summary>The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)</summary>
  944. /// <value>The top.</value>
  945. public static Toplevel Top { get; private set; }
  946. /// <summary>
  947. /// The current <see cref="Toplevel"/> object. This is updated when
  948. /// <see cref="Application.Run(Func{Exception, bool}, ConsoleDriver)"/> enters and leaves to point to the current
  949. /// <see cref="Toplevel"/> .
  950. /// </summary>
  951. /// <value>The current.</value>
  952. public static Toplevel Current { get; private set; }
  953. private static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  954. {
  955. if (!Toplevel.Running
  956. || (Toplevel == Current && Toplevel.Visible)
  957. || OverlappedTop == null
  958. || _topLevels.Peek ().Modal)
  959. {
  960. return;
  961. }
  962. foreach (Toplevel top in _topLevels.Reverse ())
  963. {
  964. if (top.Modal && top != Current)
  965. {
  966. MoveCurrent (top);
  967. return;
  968. }
  969. }
  970. if (!Toplevel.Visible && Toplevel == Current)
  971. {
  972. OverlappedMoveNext ();
  973. }
  974. }
  975. #nullable enable
  976. private static Toplevel? FindDeepestTop (Toplevel start, int x, int y)
  977. {
  978. if (!start.Frame.Contains (x, y))
  979. {
  980. return null;
  981. }
  982. if (_topLevels is { Count: > 0 })
  983. {
  984. int rx = x - start.Frame.X;
  985. int ry = y - start.Frame.Y;
  986. foreach (Toplevel t in _topLevels)
  987. {
  988. if (t != Current)
  989. {
  990. if (t != start && t.Visible && t.Frame.Contains (rx, ry))
  991. {
  992. start = t;
  993. break;
  994. }
  995. }
  996. }
  997. }
  998. return start;
  999. }
  1000. #nullable restore
  1001. private static View FindTopFromView (View view)
  1002. {
  1003. View top = view?.SuperView is { } && view?.SuperView != Top
  1004. ? view.SuperView
  1005. : view;
  1006. while (top?.SuperView is { } && top?.SuperView != Top)
  1007. {
  1008. top = top.SuperView;
  1009. }
  1010. return top;
  1011. }
  1012. #nullable enable
  1013. // Only return true if the Current has changed.
  1014. private static bool MoveCurrent (Toplevel? top)
  1015. {
  1016. // The Current is modal and the top is not modal Toplevel then
  1017. // the Current must be moved above the first not modal Toplevel.
  1018. if (OverlappedTop is { }
  1019. && top != OverlappedTop
  1020. && top != Current
  1021. && Current?.Modal == true
  1022. && !_topLevels.Peek ().Modal)
  1023. {
  1024. lock (_topLevels)
  1025. {
  1026. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1027. }
  1028. var index = 0;
  1029. Toplevel [] savedToplevels = _topLevels.ToArray ();
  1030. foreach (Toplevel t in savedToplevels)
  1031. {
  1032. if (!t.Modal && t != Current && t != top && t != savedToplevels [index])
  1033. {
  1034. lock (_topLevels)
  1035. {
  1036. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  1037. }
  1038. }
  1039. index++;
  1040. }
  1041. return false;
  1042. }
  1043. // The Current and the top are both not running Toplevel then
  1044. // the top must be moved above the first not running Toplevel.
  1045. if (OverlappedTop is { }
  1046. && top != OverlappedTop
  1047. && top != Current
  1048. && Current?.Running == false
  1049. && top?.Running == false)
  1050. {
  1051. lock (_topLevels)
  1052. {
  1053. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1054. }
  1055. var index = 0;
  1056. foreach (Toplevel t in _topLevels.ToArray ())
  1057. {
  1058. if (!t.Running && t != Current && index > 0)
  1059. {
  1060. lock (_topLevels)
  1061. {
  1062. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  1063. }
  1064. }
  1065. index++;
  1066. }
  1067. return false;
  1068. }
  1069. if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top)
  1070. || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  1071. || (OverlappedTop is { } && Current?.Modal == false && top != Current)
  1072. || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop))
  1073. {
  1074. lock (_topLevels)
  1075. {
  1076. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1077. Current = top;
  1078. }
  1079. }
  1080. return true;
  1081. }
  1082. #nullable restore
  1083. /// <summary>Invoked when the terminal's size changed. The new size of the terminal is provided.</summary>
  1084. /// <remarks>
  1085. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/> to prevent
  1086. /// <see cref="Application"/> from changing it's size to match the new terminal size.
  1087. /// </remarks>
  1088. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  1089. /// <summary>
  1090. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and fires the
  1091. /// <see cref="SizeChanging"/> event.
  1092. /// </summary>
  1093. /// <param name="args">The new size.</param>
  1094. /// <returns><see lanword="true"/>if the size was changed.</returns>
  1095. public static bool OnSizeChanging (SizeChangedEventArgs args)
  1096. {
  1097. SizeChanging?.Invoke (null, args);
  1098. if (args.Cancel)
  1099. {
  1100. return false;
  1101. }
  1102. foreach (Toplevel t in _topLevels)
  1103. {
  1104. t.SetRelativeLayout (Rectangle.Empty with { Size = args.Size });
  1105. t.LayoutSubviews ();
  1106. t.PositionToplevels ();
  1107. t.OnSizeChanging (new SizeChangedEventArgs (args.Size));
  1108. }
  1109. Refresh ();
  1110. return true;
  1111. }
  1112. #endregion Toplevel handling
  1113. #region Mouse handling
  1114. /// <summary>Disable or enable the mouse. The mouse is enabled by default.</summary>
  1115. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1116. public static bool IsMouseDisabled { get; set; }
  1117. /// <summary>The current <see cref="View"/> object that wants continuous mouse button pressed events.</summary>
  1118. public static View WantContinuousButtonPressedView { get; private set; }
  1119. /// <summary>
  1120. /// Gets the view that grabbed the mouse (e.g. for dragging). When this is set, all mouse events will be routed to
  1121. /// this view until the view calls <see cref="UngrabMouse"/> or the mouse is released.
  1122. /// </summary>
  1123. public static View MouseGrabView { get; private set; }
  1124. /// <summary>Invoked when a view wants to grab the mouse; can be canceled.</summary>
  1125. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  1126. /// <summary>Invoked when a view wants un-grab the mouse; can be canceled.</summary>
  1127. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  1128. /// <summary>Invoked after a view has grabbed the mouse.</summary>
  1129. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  1130. /// <summary>Invoked after a view has un-grabbed the mouse.</summary>
  1131. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  1132. /// <summary>
  1133. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/>
  1134. /// is called.
  1135. /// </summary>
  1136. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  1137. public static void GrabMouse (View view)
  1138. {
  1139. if (view is null)
  1140. {
  1141. return;
  1142. }
  1143. if (!OnGrabbingMouse (view))
  1144. {
  1145. OnGrabbedMouse (view);
  1146. MouseGrabView = view;
  1147. }
  1148. }
  1149. /// <summary>Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.</summary>
  1150. public static void UngrabMouse ()
  1151. {
  1152. if (MouseGrabView is null)
  1153. {
  1154. return;
  1155. }
  1156. if (!OnUnGrabbingMouse (MouseGrabView))
  1157. {
  1158. var view = MouseGrabView;
  1159. MouseGrabView = null;
  1160. OnUnGrabbedMouse (view);
  1161. }
  1162. }
  1163. private static bool OnGrabbingMouse (View view)
  1164. {
  1165. if (view is null)
  1166. {
  1167. return false;
  1168. }
  1169. var evArgs = new GrabMouseEventArgs (view);
  1170. GrabbingMouse?.Invoke (view, evArgs);
  1171. return evArgs.Cancel;
  1172. }
  1173. private static bool OnUnGrabbingMouse (View view)
  1174. {
  1175. if (view is null)
  1176. {
  1177. return false;
  1178. }
  1179. var evArgs = new GrabMouseEventArgs (view);
  1180. UnGrabbingMouse?.Invoke (view, evArgs);
  1181. return evArgs.Cancel;
  1182. }
  1183. private static void OnGrabbedMouse (View view)
  1184. {
  1185. if (view is null)
  1186. {
  1187. return;
  1188. }
  1189. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1190. }
  1191. private static void OnUnGrabbedMouse (View view)
  1192. {
  1193. if (view is null)
  1194. {
  1195. return;
  1196. }
  1197. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1198. }
  1199. #nullable enable
  1200. // Used by OnMouseEvent to track the last view that was clicked on.
  1201. internal static View? _mouseEnteredView;
  1202. /// <summary>Event fired when a mouse move or click occurs. Coordinates are screen relative.</summary>
  1203. /// <remarks>
  1204. /// <para>
  1205. /// Use this event to receive mouse events in screen coordinates. Use <see cref="MouseEvent"/> to
  1206. /// receive mouse events relative to a <see cref="View"/>'s bounds.
  1207. /// </para>
  1208. /// <para>The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.</para>
  1209. /// </remarks>
  1210. public static event EventHandler<MouseEventEventArgs> MouseEvent;
  1211. /// <summary>Called when a mouse event occurs. Raises the <see cref="MouseEvent"/> event.</summary>
  1212. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  1213. /// <param name="a">The mouse event with coordinates relative to the screen.</param>
  1214. internal static void OnMouseEvent (MouseEventEventArgs a)
  1215. {
  1216. if (IsMouseDisabled)
  1217. {
  1218. return;
  1219. }
  1220. // TODO: In PR #3273, FindDeepestView will return adornments. Update logic below to fix adornment mouse handling
  1221. var view = View.FindDeepestView (Current, a.MouseEvent.X, a.MouseEvent.Y);
  1222. if (view is { WantContinuousButtonPressed: true })
  1223. {
  1224. WantContinuousButtonPressedView = view;
  1225. }
  1226. else
  1227. {
  1228. WantContinuousButtonPressedView = null;
  1229. }
  1230. if (view is { })
  1231. {
  1232. a.MouseEvent.View = view;
  1233. }
  1234. MouseEvent?.Invoke (null, new MouseEventEventArgs (a.MouseEvent));
  1235. if (a.MouseEvent.Handled)
  1236. {
  1237. return;
  1238. }
  1239. if (MouseGrabView is { })
  1240. {
  1241. // If the mouse is grabbed, send the event to the view that grabbed it.
  1242. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  1243. Point frameLoc = MouseGrabView.ScreenToFrame (a.MouseEvent.X, a.MouseEvent.Y);
  1244. var viewRelativeMouseEvent = new MouseEvent
  1245. {
  1246. X = frameLoc.X,
  1247. Y = frameLoc.Y,
  1248. Flags = a.MouseEvent.Flags,
  1249. ScreenPosition = new (a.MouseEvent.X, a.MouseEvent.Y),
  1250. View = view
  1251. };
  1252. if (MouseGrabView.Bounds.Contains (viewRelativeMouseEvent.X, viewRelativeMouseEvent.Y) is false)
  1253. {
  1254. // The mouse has moved outside the bounds of the view that
  1255. // grabbed the mouse, so we tell the view that last got
  1256. // OnMouseEnter the mouse is leaving
  1257. // BUGBUG: That sentence makes no sense. Either I'm missing something or this logic is flawed.
  1258. _mouseEnteredView?.OnMouseLeave (a.MouseEvent);
  1259. }
  1260. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1261. if (MouseGrabView?.OnMouseEvent (viewRelativeMouseEvent) == true)
  1262. {
  1263. return;
  1264. }
  1265. }
  1266. if (view is not Adornment)
  1267. {
  1268. if ((view is null || view == OverlappedTop)
  1269. && Current is { Modal: false }
  1270. && OverlappedTop != null
  1271. && a.MouseEvent.Flags != MouseFlags.ReportMousePosition
  1272. && a.MouseEvent.Flags != 0)
  1273. {
  1274. // This occurs when there are multiple overlapped "tops"
  1275. // E.g. "Mdi" - in the Background Worker Scenario
  1276. View? top = FindDeepestTop (Top, a.MouseEvent.X, a.MouseEvent.Y);
  1277. view = View.FindDeepestView (top, a.MouseEvent.X, a.MouseEvent.Y);
  1278. if (view is { } && view != OverlappedTop && top != Current)
  1279. {
  1280. MoveCurrent ((Toplevel)top);
  1281. }
  1282. }
  1283. }
  1284. if (view is null)
  1285. {
  1286. return;
  1287. }
  1288. MouseEvent? me = null;
  1289. if (view is Adornment adornment)
  1290. {
  1291. var frameLoc = adornment.ScreenToFrame (a.MouseEvent.X, a.MouseEvent.Y);
  1292. me = new MouseEvent
  1293. {
  1294. X = frameLoc.X,
  1295. Y = frameLoc.Y,
  1296. Flags = a.MouseEvent.Flags,
  1297. ScreenPosition = new (a.MouseEvent.X, a.MouseEvent.Y),
  1298. View = view
  1299. };
  1300. }
  1301. else if (view.BoundsToScreen (view.Bounds).Contains (a.MouseEvent.X, a.MouseEvent.Y))
  1302. {
  1303. Point boundsPoint = view.ScreenToBounds (a.MouseEvent.X, a.MouseEvent.Y);
  1304. me = new MouseEvent
  1305. {
  1306. X = boundsPoint.X,
  1307. Y = boundsPoint.Y,
  1308. Flags = a.MouseEvent.Flags,
  1309. ScreenPosition = new (a.MouseEvent.X, a.MouseEvent.Y),
  1310. View = view
  1311. };
  1312. }
  1313. if (me is null)
  1314. {
  1315. return;
  1316. }
  1317. if (_mouseEnteredView is null)
  1318. {
  1319. _mouseEnteredView = view;
  1320. view.OnMouseEnter (me);
  1321. }
  1322. else if (_mouseEnteredView != view)
  1323. {
  1324. _mouseEnteredView.OnMouseLeave (me);
  1325. view.OnMouseEnter (me);
  1326. _mouseEnteredView = view;
  1327. }
  1328. if (!view.WantMousePositionReports && a.MouseEvent.Flags == MouseFlags.ReportMousePosition)
  1329. {
  1330. return;
  1331. }
  1332. WantContinuousButtonPressedView = view.WantContinuousButtonPressed ? view : null;
  1333. //Debug.WriteLine ($"OnMouseEvent: ({a.MouseEvent.X},{a.MouseEvent.Y}) - {a.MouseEvent.Flags}");
  1334. if (view.OnMouseEvent (me))
  1335. {
  1336. // Should we bubble up the event, if it is not handled?
  1337. //return;
  1338. }
  1339. BringOverlappedTopToFront ();
  1340. }
  1341. #nullable restore
  1342. #endregion Mouse handling
  1343. #region Keyboard handling
  1344. private static Key _alternateForwardKey = Key.Empty; // Defined in config.json
  1345. /// <summary>Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.</summary>
  1346. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1347. [JsonConverter (typeof (KeyJsonConverter))]
  1348. public static Key AlternateForwardKey
  1349. {
  1350. get => _alternateForwardKey;
  1351. set
  1352. {
  1353. if (_alternateForwardKey != value)
  1354. {
  1355. Key oldKey = _alternateForwardKey;
  1356. _alternateForwardKey = value;
  1357. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1358. }
  1359. }
  1360. }
  1361. private static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1362. {
  1363. foreach (Toplevel top in _topLevels.ToArray ())
  1364. {
  1365. top.OnAlternateForwardKeyChanged (e);
  1366. }
  1367. }
  1368. private static Key _alternateBackwardKey = Key.Empty; // Defined in config.json
  1369. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  1370. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1371. [JsonConverter (typeof (KeyJsonConverter))]
  1372. public static Key AlternateBackwardKey
  1373. {
  1374. get => _alternateBackwardKey;
  1375. set
  1376. {
  1377. if (_alternateBackwardKey != value)
  1378. {
  1379. Key oldKey = _alternateBackwardKey;
  1380. _alternateBackwardKey = value;
  1381. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1382. }
  1383. }
  1384. }
  1385. private static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1386. {
  1387. foreach (Toplevel top in _topLevels.ToArray ())
  1388. {
  1389. top.OnAlternateBackwardKeyChanged (oldKey);
  1390. }
  1391. }
  1392. private static Key _quitKey = Key.Empty; // Defined in config.json
  1393. /// <summary>Gets or sets the key to quit the application.</summary>
  1394. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1395. [JsonConverter (typeof (KeyJsonConverter))]
  1396. public static Key QuitKey
  1397. {
  1398. get => _quitKey;
  1399. set
  1400. {
  1401. if (_quitKey != value)
  1402. {
  1403. Key oldKey = _quitKey;
  1404. _quitKey = value;
  1405. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1406. }
  1407. }
  1408. }
  1409. private static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1410. {
  1411. // Duplicate the list so if it changes during enumeration we're safe
  1412. foreach (Toplevel top in _topLevels.ToArray ())
  1413. {
  1414. top.OnQuitKeyChanged (e);
  1415. }
  1416. }
  1417. /// <summary>
  1418. /// Event fired when the user presses a key. Fired by <see cref="OnKeyDown"/>.
  1419. /// <para>
  1420. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1421. /// additional processing.
  1422. /// </para>
  1423. /// </summary>
  1424. /// <remarks>
  1425. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1426. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1427. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  1428. /// </remarks>
  1429. public static event EventHandler<Key> KeyDown;
  1430. /// <summary>
  1431. /// Called by the <see cref="ConsoleDriver"/> when the user presses a key. Fires the <see cref="KeyDown"/> event
  1432. /// then calls <see cref="View.NewKeyDownEvent"/> on all top level views. Called after <see cref="OnKeyDown"/> and
  1433. /// before <see cref="OnKeyUp"/>.
  1434. /// </summary>
  1435. /// <remarks>Can be used to simulate key press events.</remarks>
  1436. /// <param name="keyEvent"></param>
  1437. /// <returns><see langword="true"/> if the key was handled.</returns>
  1438. public static bool OnKeyDown (Key keyEvent)
  1439. {
  1440. if (!_initialized)
  1441. {
  1442. return true;
  1443. }
  1444. KeyDown?.Invoke (null, keyEvent);
  1445. if (keyEvent.Handled)
  1446. {
  1447. return true;
  1448. }
  1449. foreach (Toplevel topLevel in _topLevels.ToList ())
  1450. {
  1451. if (topLevel.NewKeyDownEvent (keyEvent))
  1452. {
  1453. return true;
  1454. }
  1455. if (topLevel.Modal)
  1456. {
  1457. break;
  1458. }
  1459. }
  1460. // Invoke any Global KeyBindings
  1461. foreach (Toplevel topLevel in _topLevels.ToList ())
  1462. {
  1463. foreach (View view in topLevel.Subviews.Where (
  1464. v => v.KeyBindings.TryGet (
  1465. keyEvent,
  1466. KeyBindingScope.Application,
  1467. out KeyBinding _
  1468. )
  1469. ))
  1470. {
  1471. if (view.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.Application, out KeyBinding _))
  1472. {
  1473. bool? handled = view.OnInvokingKeyBindings (keyEvent);
  1474. if (handled is { } && (bool)handled)
  1475. {
  1476. return true;
  1477. }
  1478. }
  1479. }
  1480. }
  1481. return false;
  1482. }
  1483. /// <summary>
  1484. /// Event fired when the user releases a key. Fired by <see cref="OnKeyUp"/>.
  1485. /// <para>
  1486. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1487. /// additional processing.
  1488. /// </para>
  1489. /// </summary>
  1490. /// <remarks>
  1491. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1492. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1493. /// <para>Fired after <see cref="KeyDown"/>.</para>
  1494. /// </remarks>
  1495. public static event EventHandler<Key> KeyUp;
  1496. /// <summary>
  1497. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  1498. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  1499. /// </summary>
  1500. /// <remarks>Can be used to simulate key press events.</remarks>
  1501. /// <param name="a"></param>
  1502. /// <returns><see langword="true"/> if the key was handled.</returns>
  1503. public static bool OnKeyUp (Key a)
  1504. {
  1505. if (!_initialized)
  1506. {
  1507. return true;
  1508. }
  1509. KeyUp?.Invoke (null, a);
  1510. if (a.Handled)
  1511. {
  1512. return true;
  1513. }
  1514. foreach (Toplevel topLevel in _topLevels.ToList ())
  1515. {
  1516. if (topLevel.NewKeyUpEvent (a))
  1517. {
  1518. return true;
  1519. }
  1520. if (topLevel.Modal)
  1521. {
  1522. break;
  1523. }
  1524. }
  1525. return false;
  1526. }
  1527. #endregion Keyboard handling
  1528. }