Application.cs 64 KB

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