Application.cs 63 KB

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