Application.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Linq;
  5. using System.Globalization;
  6. using System.Reflection;
  7. using System.IO;
  8. using System.Text.Json.Serialization;
  9. using static Terminal.Gui.ConfigurationManager;
  10. namespace Terminal.Gui {
  11. /// <summary>
  12. /// A static, singleton class representing the application. This class is the entry point for the application.
  13. /// </summary>
  14. /// <example>
  15. /// <code>
  16. /// // A simple Terminal.Gui app that creates a window with a frame and title with
  17. /// // 5 rows/columns of padding.
  18. /// Application.Init();
  19. /// var win = new Window ($"Example App ({Application.QuitKey} to quit)") {
  20. /// X = 5,
  21. /// Y = 5,
  22. /// Width = Dim.Fill (5),
  23. /// Height = Dim.Fill (5)
  24. /// };
  25. /// Application.Top.Add(win);
  26. /// Application.Run();
  27. /// Application.Shutdown();
  28. /// </code>
  29. /// </example>
  30. /// <remarks>
  31. /// <para>
  32. /// Creates a instance of <see cref="Terminal.Gui.MainLoop"/> to process input events, handle timers and
  33. /// other sources of data. It is accessible via the <see cref="MainLoop"/> property.
  34. /// </para>
  35. /// <para>
  36. /// The <see cref="Iteration"/> event is invoked on each iteration of the <see cref="Terminal.Gui.MainLoop"/>.
  37. /// </para>
  38. /// <para>
  39. /// When invoked it sets the <see cref="SynchronizationContext"/> to one that is tied
  40. /// to the <see cref="MainLoop"/>, allowing user code to use async/await.
  41. /// </para>
  42. /// </remarks>
  43. public static partial class Application {
  44. /// <summary>
  45. /// The current <see cref="ConsoleDriver"/> in use.
  46. /// </summary>
  47. public static ConsoleDriver Driver;
  48. /// <summary>
  49. /// If <see langword="true"/>, forces the use of the System.Console-based (see <see cref="NetDriver"/>) driver. The default is <see langword="false"/>.
  50. /// </summary>
  51. public static bool UseSystemConsole { get; set; } = false;
  52. // For Unit testing - ignores UseSystemConsole
  53. internal static bool _forceFakeConsole;
  54. private static bool? _enableConsoleScrolling;
  55. /// <summary>
  56. /// The current <see cref="ConsoleDriver.EnableConsoleScrolling"/> used in the terminal.
  57. /// </summary>
  58. /// <remarks>
  59. /// <para>
  60. /// If <see langword="false"/> (the default) the height of the Terminal.Gui application (<see cref="ConsoleDriver.Rows"/>)
  61. /// tracks to the height of the visible console view when the console is resized. In this case
  62. /// scrolling in the console will be disabled and all <see cref="ConsoleDriver.Rows"/> will remain visible.
  63. /// </para>
  64. /// <para>
  65. /// If <see langword="true"/> then height of the Terminal.Gui application <see cref="ConsoleDriver.Rows"/> only tracks
  66. /// the height of the visible console view when the console is made larger (the application will only grow in height, never shrink).
  67. /// In this case console scrolling is enabled and the contents (<see cref="ConsoleDriver.Rows"/> high) will scroll
  68. /// as the console scrolls.
  69. /// </para>
  70. /// This API was previously named 'HeightAsBuffer` but was renamed to make its purpose more clear.
  71. /// </remarks>
  72. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  73. public static bool EnableConsoleScrolling {
  74. get {
  75. if (Driver == null) {
  76. return _enableConsoleScrolling.HasValue && _enableConsoleScrolling.Value;
  77. }
  78. return Driver.EnableConsoleScrolling;
  79. }
  80. set {
  81. _enableConsoleScrolling = value;
  82. if (Driver == null) {
  83. return;
  84. }
  85. Driver.EnableConsoleScrolling = value;
  86. }
  87. }
  88. private static List<CultureInfo> _cachedSupportedCultures;
  89. /// <summary>
  90. /// Gets all cultures supported by the application without the invariant language.
  91. /// </summary>
  92. public static List<CultureInfo> SupportedCultures => _cachedSupportedCultures;
  93. private static List<CultureInfo> GetSupportedCultures ()
  94. {
  95. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  96. // Get the assembly
  97. Assembly assembly = Assembly.GetExecutingAssembly ();
  98. //Find the location of the assembly
  99. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  100. // Find the resource file name of the assembly
  101. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  102. // Return all culture for which satellite folder found with culture code.
  103. return culture.Where (cultureInfo =>
  104. assemblyLocation != null &&
  105. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  106. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  107. ).ToList ();
  108. }
  109. #region Initialization (Init/Shutdown)
  110. /// <summary>
  111. /// Initializes a new instance of <see cref="Terminal.Gui"/> Application.
  112. /// </summary>
  113. /// <para>
  114. /// Call this method once per instance (or after <see cref="Shutdown"/> has been called).
  115. /// </para>
  116. /// <para>
  117. /// This function loads the right <see cref="ConsoleDriver"/> for the platform,
  118. /// Creates a <see cref="Toplevel"/>. and assigns it to <see cref="Top"/>
  119. /// </para>
  120. /// <para>
  121. /// <see cref="Shutdown"/> must be called when the application is closing (typically after <see cref="Run(Func{Exception, bool})"/> has
  122. /// returned) to ensure resources are cleaned up and terminal settings restored.
  123. /// </para>
  124. /// <para>
  125. /// The <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver, IMainLoopDriver)"/> function
  126. /// combines <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> and <see cref="Run(Toplevel, Func{Exception, bool})"/>
  127. /// into a single call. An applciation cam use <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver, IMainLoopDriver)"/>
  128. /// without explicitly calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  129. /// </para>
  130. /// <param name="driver">
  131. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  132. /// platform will be used (see <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, and <see cref="NetDriver"/>).</param>
  133. /// <param name="mainLoopDriver">
  134. /// Specifies the <see cref="MainLoop"/> to use.
  135. /// Must not be <see langword="null"/> if <paramref name="driver"/> is not <see langword="null"/>.
  136. /// </param>
  137. public static void Init (ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) => InternalInit (() => Toplevel.Create (), driver, mainLoopDriver);
  138. internal static bool _initialized = false;
  139. internal static int _mainThreadId = -1;
  140. // INTERNAL function for initializing an app with a Toplevel factory object, driver, and mainloop.
  141. //
  142. // Called from:
  143. //
  144. // Init() - When the user wants to use the default Toplevel. calledViaRunT will be false, causing all state to be reset.
  145. // 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.
  146. // Unit Tests - To initialize the app with a custom Toplevel, using the FakeDriver. calledViaRunT will be false, causing all state to be reset.
  147. //
  148. // calledViaRunT: If false (default) all state will be reset. If true the state will not be reset.
  149. internal static void InternalInit (Func<Toplevel> topLevelFactory, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null, bool calledViaRunT = false)
  150. {
  151. if (_initialized && driver == null) return;
  152. if (_initialized) {
  153. throw new InvalidOperationException ("Init has already been called and must be bracketed by Shutdown.");
  154. }
  155. if (!calledViaRunT) {
  156. // Reset all class variables (Application is a singleton).
  157. ResetState ();
  158. }
  159. // For UnitTests
  160. if (driver != null) {
  161. Driver = driver;
  162. }
  163. // Start the process of configuration management.
  164. // Note that we end up calling LoadConfigurationFromAllSources
  165. // multiple times. We need to do this because some settings are only
  166. // valid after a Driver is loaded. In this cases we need just
  167. // `Settings` so we can determine which driver to use.
  168. ConfigurationManager.Load (true);
  169. ConfigurationManager.Apply ();
  170. if (Driver == null) {
  171. var p = Environment.OSVersion.Platform;
  172. if (_forceFakeConsole) {
  173. // For Unit Testing only
  174. Driver = new FakeDriver ();
  175. } else if (UseSystemConsole) {
  176. Driver = new NetDriver ();
  177. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  178. Driver = new WindowsDriver ();
  179. } else {
  180. Driver = new CursesDriver ();
  181. }
  182. if (Driver == null) {
  183. throw new InvalidOperationException ("Init could not determine the ConsoleDriver to use.");
  184. }
  185. }
  186. if (mainLoopDriver == null) {
  187. // TODO: Move this logic into ConsoleDriver
  188. if (Driver is FakeDriver) {
  189. mainLoopDriver = new FakeMainLoop (Driver);
  190. } else if (Driver is NetDriver) {
  191. mainLoopDriver = new NetMainLoop (Driver);
  192. } else if (Driver is WindowsDriver) {
  193. mainLoopDriver = new WindowsMainLoop (Driver);
  194. } else if (Driver is CursesDriver) {
  195. mainLoopDriver = new UnixMainLoop (Driver);
  196. }
  197. if (mainLoopDriver == null) {
  198. throw new InvalidOperationException ("Init could not determine the MainLoopDriver to use.");
  199. }
  200. }
  201. MainLoop = new MainLoop (mainLoopDriver);
  202. try {
  203. Driver.EnableConsoleScrolling = EnableConsoleScrolling;
  204. Driver.Init (OnTerminalResized);
  205. } catch (InvalidOperationException ex) {
  206. // This is a case where the driver is unable to initialize the console.
  207. // This can happen if the console is already in use by another process or
  208. // if running in unit tests.
  209. // In this case, we want to throw a more specific exception.
  210. throw new InvalidOperationException ("Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.", ex);
  211. }
  212. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  213. Top = topLevelFactory ();
  214. Current = Top;
  215. _cachedSupportedCultures = GetSupportedCultures ();
  216. _mainThreadId = Thread.CurrentThread.ManagedThreadId;
  217. _initialized = true;
  218. }
  219. /// <summary>
  220. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  221. /// </summary>
  222. /// <remarks>
  223. /// Shutdown must be called for every call to <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> or <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  224. /// to ensure all resources are cleaned up (Disposed) and terminal settings are restored.
  225. /// </remarks>
  226. public static void Shutdown ()
  227. {
  228. ResetState ();
  229. ConfigurationManager.PrintJsonErrors ();
  230. }
  231. // Encapsulate all setting of initial state for Application; Having
  232. // this in a function like this ensures we don't make mistakes in
  233. // guaranteeing that the state of this singleton is deterministic when Init
  234. // starts running and after Shutdown returns.
  235. static void ResetState ()
  236. {
  237. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  238. // Init created. Apps that do any threading will need to code defensively for this.
  239. // e.g. see Issue #537
  240. foreach (var t in _toplevels) {
  241. t.Running = false;
  242. t.Dispose ();
  243. }
  244. _toplevels.Clear ();
  245. Current = null;
  246. Top?.Dispose ();
  247. Top = null;
  248. // BUGBUG: OverlappedTop is not cleared here, but it should be?
  249. MainLoop = null;
  250. Driver?.End ();
  251. Driver = null;
  252. Iteration = null;
  253. RootMouseEvent = null;
  254. RootKeyEvent = null;
  255. TerminalResized = null;
  256. _mainThreadId = -1;
  257. NotifyNewRunState = null;
  258. NotifyStopRunState = null;
  259. _initialized = false;
  260. _mouseGrabView = null;
  261. _enableConsoleScrolling = false;
  262. _lastMouseOwnerView = null;
  263. // Reset synchronization context to allow the user to run async/await,
  264. // as the main loop has been ended, the synchronization context from
  265. // gui.cs does no longer process any callbacks. See #1084 for more details:
  266. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  267. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  268. }
  269. #endregion Initialization (Init/Shutdown)
  270. #region Run (Begin, Run, End)
  271. /// <summary>
  272. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is created in
  273. /// <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  274. /// </summary>
  275. /// <remarks>
  276. /// If <see cref="ExitRunLoopAfterFirstIteration"/> is <see langword="true"/> callers to
  277. /// <see cref="Begin(Toplevel)"/> must also subscribe to <see cref="NotifyStopRunState"/>
  278. /// and manually dispose of the <see cref="RunState"/> token when the application is done.
  279. /// </remarks>
  280. public static event EventHandler<RunStateEventArgs> NotifyNewRunState;
  281. /// <summary>
  282. /// Notify that a existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).
  283. /// </summary>
  284. /// <remarks>
  285. /// If <see cref="ExitRunLoopAfterFirstIteration"/> is <see langword="true"/> callers to
  286. /// <see cref="Begin(Toplevel)"/> must also subscribe to <see cref="NotifyStopRunState"/>
  287. /// and manually dispose of the <see cref="RunState"/> token when the application is done.
  288. /// </remarks>
  289. public static event EventHandler<ToplevelEventArgs> NotifyStopRunState;
  290. /// <summary>
  291. /// The execution state for a <see cref="Toplevel"/> view.
  292. /// </summary>
  293. public class RunState : IDisposable {
  294. /// <summary>
  295. /// Initializes a new <see cref="RunState"/> class.
  296. /// </summary>
  297. /// <param name="view"></param>
  298. public RunState (Toplevel view)
  299. {
  300. Toplevel = view;
  301. }
  302. /// <summary>
  303. /// The <see cref="Toplevel"/> belonging to this <see cref="RunState"/>.
  304. /// </summary>
  305. public Toplevel Toplevel { get; internal set; }
  306. #if DEBUG_IDISPOSABLE
  307. /// <summary>
  308. /// For debug (see DEBUG_IDISPOSABLE define) purposes to verify objects are being disposed properly
  309. /// </summary>
  310. public bool WasDisposed = false;
  311. /// <summary>
  312. /// For debug (see DEBUG_IDISPOSABLE define) purposes to verify objects are being disposed properly
  313. /// </summary>
  314. public int DisposedCount = 0;
  315. /// <summary>
  316. /// For debug (see DEBUG_IDISPOSABLE define) purposes; the runstate instances that have been created
  317. /// </summary>
  318. public static List<RunState> Instances = new List<RunState> ();
  319. /// <summary>
  320. /// Creates a new RunState object.
  321. /// </summary>
  322. public RunState ()
  323. {
  324. Instances.Add (this);
  325. }
  326. #endif
  327. /// <summary>
  328. /// Releases all resource used by the <see cref="Application.RunState"/> object.
  329. /// </summary>
  330. /// <remarks>
  331. /// Call <see cref="Dispose()"/> when you are finished using the <see cref="Application.RunState"/>.
  332. /// </remarks>
  333. /// <remarks>
  334. /// <see cref="Dispose()"/> method leaves the <see cref="Application.RunState"/> in an unusable state. After
  335. /// calling <see cref="Dispose()"/>, you must release all references to the
  336. /// <see cref="Application.RunState"/> so the garbage collector can reclaim the memory that the
  337. /// <see cref="Application.RunState"/> was occupying.
  338. /// </remarks>
  339. public void Dispose ()
  340. {
  341. Dispose (true);
  342. GC.SuppressFinalize (this);
  343. #if DEBUG_IDISPOSABLE
  344. WasDisposed = true;
  345. #endif
  346. }
  347. /// <summary>
  348. /// Releases all resource used by the <see cref="Application.RunState"/> object.
  349. /// </summary>
  350. /// <param name="disposing">If set to <see langword="true"/> we are disposing and should dispose held objects.</param>
  351. protected virtual void Dispose (bool disposing)
  352. {
  353. if (Toplevel != null && disposing) {
  354. throw new InvalidOperationException ("You must clean up (Dispose) the Toplevel before calling Application.RunState.Dispose");
  355. }
  356. }
  357. }
  358. /// <summary>
  359. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  360. /// </summary>
  361. /// <returns>The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  362. /// <param name="Toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  363. /// <remarks>
  364. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus,
  365. /// it adds this to the list of <see cref="Toplevel"/>s, sets up the <see cref="MainLoop"/> to process the
  366. /// event, lays out the Subviews, focuses the first element, and draws the
  367. /// <see cref="Toplevel"/> in the screen. This is usually followed by executing
  368. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  369. /// undo these changes.
  370. /// </remarks>
  371. public static RunState Begin (Toplevel Toplevel)
  372. {
  373. if (Toplevel == null) {
  374. throw new ArgumentNullException (nameof (Toplevel));
  375. } else if (Toplevel.IsOverlappedContainer && OverlappedTop != Toplevel && OverlappedTop != null) {
  376. throw new InvalidOperationException ("Only one Overlapped Container is allowed.");
  377. }
  378. // Ensure the mouse is ungrabed.
  379. _mouseGrabView = null;
  380. var rs = new RunState (Toplevel);
  381. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  382. if (!Toplevel.IsInitialized) {
  383. Toplevel.BeginInit ();
  384. Toplevel.EndInit ();
  385. }
  386. lock (_toplevels) {
  387. // If Top was already initialized with Init, and Begin has never been called
  388. // Top was not added to the Toplevels Stack. It will thus never get disposed.
  389. // Clean it up here:
  390. if (Top != null && Toplevel != Top && !_toplevels.Contains (Top)) {
  391. Top.Dispose ();
  392. Top = null;
  393. } else if (Top != null && Toplevel != Top && _toplevels.Contains (Top)) {
  394. Top.OnLeave (Toplevel);
  395. }
  396. if (string.IsNullOrEmpty (Toplevel.Id)) {
  397. var count = 1;
  398. var id = (_toplevels.Count + count).ToString ();
  399. while (_toplevels.Count > 0 && _toplevels.FirstOrDefault (x => x.Id == id) != null) {
  400. count++;
  401. id = (_toplevels.Count + count).ToString ();
  402. }
  403. Toplevel.Id = (_toplevels.Count + count).ToString ();
  404. _toplevels.Push (Toplevel);
  405. } else {
  406. var dup = _toplevels.FirstOrDefault (x => x.Id == Toplevel.Id);
  407. if (dup == null) {
  408. _toplevels.Push (Toplevel);
  409. }
  410. }
  411. if (_toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  412. throw new ArgumentException ("There are duplicates Toplevels Id's");
  413. }
  414. }
  415. if (Top == null || Toplevel.IsOverlappedContainer) {
  416. Top = Toplevel;
  417. }
  418. var refreshDriver = true;
  419. if (OverlappedTop == null || Toplevel.IsOverlappedContainer || (Current?.Modal == false && Toplevel.Modal)
  420. || (Current?.Modal == false && !Toplevel.Modal) || (Current?.Modal == true && Toplevel.Modal)) {
  421. if (Toplevel.Visible) {
  422. Current = Toplevel;
  423. SetCurrentOverlappedAsTop ();
  424. } else {
  425. refreshDriver = false;
  426. }
  427. } else if ((OverlappedTop != null && Toplevel != OverlappedTop && Current?.Modal == true && !_toplevels.Peek ().Modal)
  428. || (OverlappedTop != null && Toplevel != OverlappedTop && Current?.Running == false)) {
  429. refreshDriver = false;
  430. MoveCurrent (Toplevel);
  431. } else {
  432. refreshDriver = false;
  433. MoveCurrent (Current);
  434. }
  435. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  436. if (Toplevel.LayoutStyle == LayoutStyle.Computed) {
  437. Toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  438. }
  439. Toplevel.LayoutSubviews ();
  440. Toplevel.PositionToplevels ();
  441. Toplevel.FocusFirst ();
  442. if (refreshDriver) {
  443. OverlappedTop?.OnChildLoaded (Toplevel);
  444. Toplevel.OnLoaded ();
  445. Toplevel.SetNeedsDisplay ();
  446. Toplevel.Draw ();
  447. Toplevel.PositionCursor ();
  448. Driver.Refresh ();
  449. }
  450. NotifyNewRunState?.Invoke (Toplevel, new RunStateEventArgs (rs));
  451. return rs;
  452. }
  453. /// <summary>
  454. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>.
  455. /// </summary>
  456. /// <remarks>
  457. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  458. /// </remarks>
  459. public static void Run (Func<Exception, bool> errorHandler = null)
  460. {
  461. Run (Top, errorHandler);
  462. }
  463. /// <summary>
  464. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  465. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  466. /// <para>
  467. /// Calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> first is not needed as this function will initialize the application.
  468. /// </para>
  469. /// <para>
  470. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has
  471. /// returned) to ensure resources are cleaned up and terminal settings restored.
  472. /// </para>
  473. /// </summary>
  474. /// <remarks>
  475. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  476. /// </remarks>
  477. /// <param name="errorHandler"></param>
  478. /// <param name="driver">The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  479. /// platform will be used (<see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>).
  480. /// Must be <see langword="null"/> if <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has already been called.
  481. /// </param>
  482. /// <param name="mainLoopDriver">Specifies the <see cref="MainLoop"/> to use.</param>
  483. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) where T : Toplevel, new()
  484. {
  485. if (_initialized) {
  486. if (Driver != null) {
  487. // Init() has been called and we have a driver, so just run the app.
  488. var top = new T ();
  489. var type = top.GetType ().BaseType;
  490. while (type != typeof (Toplevel) && type != typeof (object)) {
  491. type = type.BaseType;
  492. }
  493. if (type != typeof (Toplevel)) {
  494. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  495. }
  496. Run (top, errorHandler);
  497. } else {
  498. // This codepath should be impossible because Init(null, null) will select the platform default driver
  499. throw new InvalidOperationException ("Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called.");
  500. }
  501. } else {
  502. // Init() has NOT been called.
  503. InternalInit (() => new T (), driver, mainLoopDriver, calledViaRunT: true);
  504. Run (Top, errorHandler);
  505. }
  506. }
  507. /// <summary>
  508. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  509. /// </summary>
  510. /// <remarks>
  511. /// <para>
  512. /// This method is used to start processing events
  513. /// for the main application, but it is also used to
  514. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  515. /// </para>
  516. /// <para>
  517. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  518. /// </para>
  519. /// <para>
  520. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  521. /// and then calling <see cref="End(RunState)"/>.
  522. /// </para>
  523. /// <para>
  524. /// Alternatively, to have a program control the main loop and
  525. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  526. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  527. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  528. /// then return control immediately.
  529. /// </para>
  530. /// <para>
  531. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exeptions will be rethrown.
  532. /// Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  533. /// returns <see langword="true"/> the <see cref="RunLoop(RunState, bool)"/> will resume; otherwise
  534. /// this method will exit.
  535. /// </para>
  536. /// </remarks>
  537. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  538. /// <param name="errorHandler">RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  539. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  540. {
  541. var resume = true;
  542. while (resume) {
  543. #if !DEBUG
  544. try {
  545. #endif
  546. resume = false;
  547. var runToken = Begin (view);
  548. // If ExitRunLoopAfterFirstIteration is true then the user must dispose of the runToken
  549. // by using NotifyStopRunState event.
  550. RunLoop (runToken);
  551. if (!ExitRunLoopAfterFirstIteration) {
  552. End (runToken);
  553. }
  554. #if !DEBUG
  555. }
  556. catch (Exception error)
  557. {
  558. if (errorHandler == null)
  559. {
  560. throw;
  561. }
  562. resume = errorHandler(error);
  563. }
  564. #endif
  565. }
  566. }
  567. /// <summary>
  568. /// Triggers a refresh of the entire display.
  569. /// </summary>
  570. public static void Refresh ()
  571. {
  572. Driver.UpdateOffScreen ();
  573. View last = null;
  574. foreach (var v in _toplevels.Reverse ()) {
  575. if (v.Visible) {
  576. v.SetNeedsDisplay ();
  577. v.SetSubViewNeedsDisplay ();
  578. v.Draw ();
  579. }
  580. last = v;
  581. }
  582. last?.PositionCursor ();
  583. Driver.Refresh ();
  584. }
  585. /// <summary>
  586. /// This event is raised on each iteration of the <see cref="MainLoop"/>.
  587. /// </summary>
  588. /// <remarks>
  589. /// See also <see cref="Timeout"/>
  590. /// </remarks>
  591. public static Action Iteration;
  592. /// <summary>
  593. /// The <see cref="MainLoop"/> driver for the application
  594. /// </summary>
  595. /// <value>The main loop.</value>
  596. public static MainLoop MainLoop { get; private set; }
  597. /// <summary>
  598. /// Set to true to cause the RunLoop method to exit after the first iterations.
  599. /// Set to false (the default) to cause the RunLoop to continue running until Application.RequestStop() is called.
  600. /// </summary>
  601. public static bool ExitRunLoopAfterFirstIteration { get; set; } = false;
  602. //
  603. // provides the sync context set while executing code in Terminal.Gui, to let
  604. // users use async/await on their code
  605. //
  606. class MainLoopSyncContext : SynchronizationContext {
  607. readonly MainLoop mainLoop;
  608. public MainLoopSyncContext (MainLoop mainLoop)
  609. {
  610. this.mainLoop = mainLoop;
  611. }
  612. public override SynchronizationContext CreateCopy ()
  613. {
  614. return new MainLoopSyncContext (MainLoop);
  615. }
  616. public override void Post (SendOrPostCallback d, object state)
  617. {
  618. mainLoop.AddIdle (() => {
  619. d (state);
  620. return false;
  621. });
  622. //mainLoop.Driver.Wakeup ();
  623. }
  624. public override void Send (SendOrPostCallback d, object state)
  625. {
  626. if (Thread.CurrentThread.ManagedThreadId == _mainThreadId) {
  627. d (state);
  628. } else {
  629. var wasExecuted = false;
  630. mainLoop.Invoke (() => {
  631. d (state);
  632. wasExecuted = true;
  633. });
  634. while (!wasExecuted) {
  635. Thread.Sleep (15);
  636. }
  637. }
  638. }
  639. }
  640. /// <summary>
  641. /// Building block API: Runs the <see cref="MainLoop"/> for the created <see cref="Toplevel"/>.
  642. /// </summary>
  643. /// <remarks>
  644. /// Use the <paramref name="wait"/> parameter to control whether this is a blocking or non-blocking call.
  645. /// </remarks>
  646. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  647. /// <param name="wait">By default this is <see langword="true"/> which will execute the loop waiting for events,
  648. /// if set to <see langword="false"/>, a single iteration will execute.</param>
  649. public static void RunLoop (RunState state, bool wait = true)
  650. {
  651. if (state == null)
  652. throw new ArgumentNullException (nameof (state));
  653. if (state.Toplevel == null)
  654. throw new ObjectDisposedException ("state");
  655. bool firstIteration = true;
  656. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  657. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  658. return;
  659. }
  660. RunMainLoopIteration (ref state, wait, ref firstIteration);
  661. }
  662. }
  663. /// <summary>
  664. /// Run one iteration of the <see cref="MainLoop"/>.
  665. /// </summary>
  666. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  667. /// <param name="wait">If <see langword="true"/> will execute the <see cref="MainLoop"/> waiting for events. If <see langword="true"/>
  668. /// will return after a single iteration.</param>
  669. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  670. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  671. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  672. {
  673. if (MainLoop.EventsPending (wait)) {
  674. // Notify Toplevel it's ready
  675. if (firstIteration) {
  676. state.Toplevel.OnReady ();
  677. }
  678. MainLoop.RunIteration ();
  679. Iteration?.Invoke ();
  680. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  681. if ((state.Toplevel != Current && Current?.Modal == true)
  682. || (state.Toplevel != Current && Current?.Modal == false)) {
  683. OverlappedTop?.OnDeactivate (state.Toplevel);
  684. state.Toplevel = Current;
  685. OverlappedTop?.OnActivate (state.Toplevel);
  686. Top.SetSubViewNeedsDisplay ();
  687. Refresh ();
  688. }
  689. if (Driver.EnsureCursorVisibility ()) {
  690. state.Toplevel.SetNeedsDisplay ();
  691. }
  692. } else if (!wait) {
  693. return;
  694. }
  695. firstIteration = false;
  696. if (state.Toplevel != Top
  697. && (!Top._needsDisplay.IsEmpty || Top._subViewNeedsDisplay || Top.LayoutNeeded)) {
  698. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  699. Top.Draw ();
  700. foreach (var top in _toplevels.Reverse ()) {
  701. if (top != Top && top != state.Toplevel) {
  702. top.SetNeedsDisplay ();
  703. top.SetSubViewNeedsDisplay ();
  704. top.Draw ();
  705. }
  706. }
  707. }
  708. if (_toplevels.Count == 1 && state.Toplevel == Top
  709. && (Driver.Cols != state.Toplevel.Frame.Width || Driver.Rows != state.Toplevel.Frame.Height)
  710. && (!state.Toplevel._needsDisplay.IsEmpty || state.Toplevel._subViewNeedsDisplay || state.Toplevel.LayoutNeeded)) {
  711. Driver.SetAttribute (Colors.TopLevel.Normal);
  712. state.Toplevel.Clear (new Rect (0, 0, Driver.Cols, Driver.Rows));
  713. }
  714. if (!state.Toplevel._needsDisplay.IsEmpty || state.Toplevel._subViewNeedsDisplay || state.Toplevel.LayoutNeeded
  715. || OverlappedChildNeedsDisplay ()) {
  716. state.Toplevel.Draw ();
  717. //if (state.Toplevel.SuperView != null) {
  718. // state.Toplevel.SuperView?.OnRenderLineCanvas ();
  719. //} else {
  720. // state.Toplevel.OnRenderLineCanvas ();
  721. //}
  722. state.Toplevel.PositionCursor ();
  723. Driver.Refresh ();
  724. } else {
  725. Driver.UpdateCursor ();
  726. }
  727. if (state.Toplevel != Top && !state.Toplevel.Modal
  728. && (!Top._needsDisplay.IsEmpty || Top._subViewNeedsDisplay || Top.LayoutNeeded)) {
  729. Top.Draw ();
  730. }
  731. }
  732. /// <summary>
  733. /// Wakes up the <see cref="MainLoop"/> that might be waiting on input; must be thread safe.
  734. /// </summary>
  735. public static void DoEvents ()
  736. {
  737. MainLoop.Driver.Wakeup ();
  738. }
  739. /// <summary>
  740. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  741. /// </summary>
  742. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  743. /// <remarks>
  744. /// <para>
  745. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  746. /// </para>
  747. /// <para>
  748. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property
  749. /// on the currently running <see cref="Toplevel"/> to false.
  750. /// </para>
  751. /// </remarks>
  752. public static void RequestStop (Toplevel top = null)
  753. {
  754. if (OverlappedTop == null || top == null || (OverlappedTop == null && top != null)) {
  755. top = Current;
  756. }
  757. if (OverlappedTop != null && top.IsOverlappedContainer && top?.Running == true
  758. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  759. OverlappedTop.RequestStop ();
  760. } else if (OverlappedTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  761. && top.Modal && top.Running) {
  762. var ev = new ToplevelClosingEventArgs (Current);
  763. Current.OnClosing (ev);
  764. if (ev.Cancel) {
  765. return;
  766. }
  767. ev = new ToplevelClosingEventArgs (top);
  768. top.OnClosing (ev);
  769. if (ev.Cancel) {
  770. return;
  771. }
  772. Current.Running = false;
  773. OnNotifyStopRunState (Current);
  774. top.Running = false;
  775. OnNotifyStopRunState (top);
  776. } else if ((OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  777. && Current?.Running == true && !top.Running)
  778. || (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  779. && Current?.Running == false && !top.Running && _toplevels.ToArray () [1].Running)) {
  780. MoveCurrent (top);
  781. } else if (OverlappedTop != null && Current != top && Current?.Running == true && !top.Running
  782. && Current?.Modal == true && top.Modal) {
  783. // The Current and the top are both modal so needed to set the Current.Running to false too.
  784. Current.Running = false;
  785. OnNotifyStopRunState (Current);
  786. } else if (OverlappedTop != null && Current == top && OverlappedTop?.Running == true && Current?.Running == true && top.Running
  787. && Current?.Modal == true && top.Modal) {
  788. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  789. // both are the same, so needed to set the Current.Running to false too.
  790. Current.Running = false;
  791. OnNotifyStopRunState (Current);
  792. } else {
  793. Toplevel currentTop;
  794. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  795. currentTop = Current;
  796. } else {
  797. currentTop = top;
  798. }
  799. if (!currentTop.Running) {
  800. return;
  801. }
  802. var ev = new ToplevelClosingEventArgs (currentTop);
  803. currentTop.OnClosing (ev);
  804. if (ev.Cancel) {
  805. return;
  806. }
  807. currentTop.Running = false;
  808. OnNotifyStopRunState (currentTop);
  809. }
  810. }
  811. static void OnNotifyStopRunState (Toplevel top)
  812. {
  813. if (ExitRunLoopAfterFirstIteration) {
  814. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  815. }
  816. }
  817. /// <summary>
  818. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  819. /// </summary>
  820. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  821. public static void End (RunState runState)
  822. {
  823. if (runState == null)
  824. throw new ArgumentNullException (nameof (runState));
  825. if (OverlappedTop != null) {
  826. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  827. } else {
  828. runState.Toplevel.OnUnloaded ();
  829. }
  830. // End the RunState.Toplevel
  831. // First, take it off the Toplevel Stack
  832. if (_toplevels.Count > 0) {
  833. if (_toplevels.Peek () != runState.Toplevel) {
  834. // If there the top of the stack is not the RunState.Toplevel then
  835. // this call to End is not balanced with the call to Begin that started the RunState
  836. throw new ArgumentException ("End must be balanced with calls to Begin");
  837. }
  838. _toplevels.Pop ();
  839. }
  840. // Notify that it is closing
  841. runState.Toplevel?.OnClosed (runState.Toplevel);
  842. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  843. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  844. if (OverlappedTop != null && !(runState.Toplevel).Modal && runState.Toplevel != OverlappedTop) {
  845. OverlappedTop.OnChildClosed (runState.Toplevel);
  846. }
  847. // Set Current and Top to the next TopLevel on the stack
  848. if (_toplevels.Count == 0) {
  849. Current = null;
  850. } else {
  851. Current = _toplevels.Peek ();
  852. if (_toplevels.Count == 1 && Current == OverlappedTop) {
  853. OverlappedTop.OnAllChildClosed ();
  854. } else {
  855. SetCurrentOverlappedAsTop ();
  856. Current.OnEnter (Current);
  857. }
  858. Refresh ();
  859. }
  860. runState.Toplevel?.Dispose ();
  861. runState.Toplevel = null;
  862. runState.Dispose ();
  863. }
  864. #endregion Run (Begin, Run, End)
  865. #region Toplevel handling
  866. static readonly Stack<Toplevel> _toplevels = new Stack<Toplevel> ();
  867. /// <summary>
  868. /// The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)
  869. /// </summary>
  870. /// <value>The top.</value>
  871. public static Toplevel Top { get; private set; }
  872. /// <summary>
  873. /// The current <see cref="Toplevel"/> object. This is updated when <see cref="Application.Run(Func{Exception, bool})"/>
  874. /// enters and leaves to point to the current <see cref="Toplevel"/> .
  875. /// </summary>
  876. /// <value>The current.</value>
  877. public static Toplevel Current { get; private set; }
  878. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  879. {
  880. if (!Toplevel.Running || (Toplevel == Current && Toplevel.Visible) || OverlappedTop == null || _toplevels.Peek ().Modal) {
  881. return;
  882. }
  883. foreach (var top in _toplevels.Reverse ()) {
  884. if (top.Modal && top != Current) {
  885. MoveCurrent (top);
  886. return;
  887. }
  888. }
  889. if (!Toplevel.Visible && Toplevel == Current) {
  890. OverlappedMoveNext ();
  891. }
  892. }
  893. static View FindDeepestTop (Toplevel start, int x, int y, out int resx, out int resy)
  894. {
  895. var startFrame = start.Frame;
  896. if (!startFrame.Contains (x, y)) {
  897. resx = 0;
  898. resy = 0;
  899. return null;
  900. }
  901. if (_toplevels != null) {
  902. int count = _toplevels.Count;
  903. if (count > 0) {
  904. var rx = x - startFrame.X;
  905. var ry = y - startFrame.Y;
  906. foreach (var t in _toplevels) {
  907. if (t != Current) {
  908. if (t != start && t.Visible && t.Frame.Contains (rx, ry)) {
  909. start = t;
  910. break;
  911. }
  912. }
  913. }
  914. }
  915. }
  916. resx = x - startFrame.X;
  917. resy = y - startFrame.Y;
  918. return start;
  919. }
  920. static View FindTopFromView (View view)
  921. {
  922. View top = view?.SuperView != null && view?.SuperView != Top
  923. ? view.SuperView : view;
  924. while (top?.SuperView != null && top?.SuperView != Top) {
  925. top = top.SuperView;
  926. }
  927. return top;
  928. }
  929. // Only return true if the Current has changed.
  930. static bool MoveCurrent (Toplevel top)
  931. {
  932. // The Current is modal and the top is not modal Toplevel then
  933. // the Current must be moved above the first not modal Toplevel.
  934. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == true && !_toplevels.Peek ().Modal) {
  935. lock (_toplevels) {
  936. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  937. }
  938. var index = 0;
  939. var savedToplevels = _toplevels.ToArray ();
  940. foreach (var t in savedToplevels) {
  941. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  942. lock (_toplevels) {
  943. _toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  944. }
  945. }
  946. index++;
  947. }
  948. return false;
  949. }
  950. // The Current and the top are both not running Toplevel then
  951. // the top must be moved above the first not running Toplevel.
  952. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Running == false && !top.Running) {
  953. lock (_toplevels) {
  954. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  955. }
  956. var index = 0;
  957. foreach (var t in _toplevels.ToArray ()) {
  958. if (!t.Running && t != Current && index > 0) {
  959. lock (_toplevels) {
  960. _toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  961. }
  962. }
  963. index++;
  964. }
  965. return false;
  966. }
  967. if ((OverlappedTop != null && top?.Modal == true && _toplevels.Peek () != top)
  968. || (OverlappedTop != null && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  969. || (OverlappedTop != null && Current?.Modal == false && top != Current)
  970. || (OverlappedTop != null && Current?.Modal == true && top == OverlappedTop)) {
  971. lock (_toplevels) {
  972. _toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  973. Current = top;
  974. }
  975. }
  976. return true;
  977. }
  978. /// <summary>
  979. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  980. /// </summary>
  981. public static Action<ResizedEventArgs> TerminalResized;
  982. static void OnTerminalResized ()
  983. {
  984. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  985. TerminalResized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  986. Driver.Clip = full;
  987. foreach (var t in _toplevels) {
  988. t.SetRelativeLayout (full);
  989. t.LayoutSubviews ();
  990. t.PositionToplevels ();
  991. t.OnTerminalResized (new SizeChangedEventArgs (full.Size));
  992. }
  993. Refresh ();
  994. }
  995. #endregion Toplevel handling
  996. #region Mouse handling
  997. /// <summary>
  998. /// Disable or enable the mouse. The mouse is enabled by default.
  999. /// </summary>
  1000. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1001. public static bool IsMouseDisabled { get; set; }
  1002. /// <summary>
  1003. /// The current <see cref="View"/> object that wants continuous mouse button pressed events.
  1004. /// </summary>
  1005. public static View WantContinuousButtonPressedView { get; private set; }
  1006. static View _mouseGrabView;
  1007. /// <summary>
  1008. /// The view that grabbed the mouse, to where mouse events will be routed to.
  1009. /// </summary>
  1010. public static View MouseGrabView => _mouseGrabView;
  1011. /// <summary>
  1012. /// Invoked when a view wants to grab the mouse; can be canceled.
  1013. /// </summary>
  1014. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  1015. /// <summary>
  1016. /// Invoked when a view wants ungrab the mouse; can be canceled.
  1017. /// </summary>
  1018. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  1019. /// <summary>
  1020. /// Invoked after a view has grabbed the mouse.
  1021. /// </summary>
  1022. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  1023. /// <summary>
  1024. /// Invoked after a view has ungrabbed the mouse.
  1025. /// </summary>
  1026. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  1027. /// <summary>
  1028. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/> is called.
  1029. /// </summary>
  1030. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  1031. public static void GrabMouse (View view)
  1032. {
  1033. if (view == null)
  1034. return;
  1035. if (!OnGrabbingMouse (view)) {
  1036. OnGrabbedMouse (view);
  1037. _mouseGrabView = view;
  1038. Driver.UncookMouse ();
  1039. }
  1040. }
  1041. /// <summary>
  1042. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1043. /// </summary>
  1044. public static void UngrabMouse ()
  1045. {
  1046. if (_mouseGrabView == null)
  1047. return;
  1048. if (!OnUnGrabbingMouse (_mouseGrabView)) {
  1049. OnUnGrabbedMouse (_mouseGrabView);
  1050. _mouseGrabView = null;
  1051. Driver.CookMouse ();
  1052. }
  1053. }
  1054. static bool OnGrabbingMouse (View view)
  1055. {
  1056. if (view == null)
  1057. return false;
  1058. var evArgs = new GrabMouseEventArgs (view);
  1059. GrabbingMouse?.Invoke (view, evArgs);
  1060. return evArgs.Cancel;
  1061. }
  1062. static bool OnUnGrabbingMouse (View view)
  1063. {
  1064. if (view == null)
  1065. return false;
  1066. var evArgs = new GrabMouseEventArgs (view);
  1067. UnGrabbingMouse?.Invoke (view, evArgs);
  1068. return evArgs.Cancel;
  1069. }
  1070. static void OnGrabbedMouse (View view)
  1071. {
  1072. if (view == null)
  1073. return;
  1074. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1075. }
  1076. static void OnUnGrabbedMouse (View view)
  1077. {
  1078. if (view == null)
  1079. return;
  1080. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1081. }
  1082. /// <summary>
  1083. /// Merely a debugging aid to see the raw mouse events
  1084. /// </summary>
  1085. public static Action<MouseEvent> RootMouseEvent;
  1086. static View _lastMouseOwnerView;
  1087. static void ProcessMouseEvent (MouseEvent me)
  1088. {
  1089. bool OutsideBounds (Point p, Rect r)
  1090. {
  1091. return p.X < 0 || p.X > r.Right || p.Y < 0 || p.Y > r.Bottom;
  1092. }
  1093. if (IsMouseDisabled) {
  1094. return;
  1095. }
  1096. var view = View.FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  1097. if (view != null && view.WantContinuousButtonPressed) {
  1098. WantContinuousButtonPressedView = view;
  1099. } else {
  1100. WantContinuousButtonPressedView = null;
  1101. }
  1102. if (view != null) {
  1103. me.View = view;
  1104. }
  1105. RootMouseEvent?.Invoke (me);
  1106. if (me.Handled) {
  1107. return;
  1108. }
  1109. if (_mouseGrabView != null) {
  1110. var newxy = _mouseGrabView.ScreenToView (me.X, me.Y);
  1111. var nme = new MouseEvent () {
  1112. X = newxy.X,
  1113. Y = newxy.Y,
  1114. Flags = me.Flags,
  1115. OfX = me.X - newxy.X,
  1116. OfY = me.Y - newxy.Y,
  1117. View = view
  1118. };
  1119. if (OutsideBounds (new Point (nme.X, nme.Y), _mouseGrabView.Bounds)) {
  1120. _lastMouseOwnerView?.OnMouseLeave (me);
  1121. }
  1122. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1123. if (_mouseGrabView?.OnMouseEvent (nme) == true) {
  1124. return;
  1125. }
  1126. }
  1127. if ((view == null || view == OverlappedTop) && !Current.Modal && OverlappedTop != null
  1128. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1129. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  1130. view = View.FindDeepestView (top, me.X, me.Y, out rx, out ry);
  1131. if (view != null && view != OverlappedTop && top != Current) {
  1132. MoveCurrent ((Toplevel)top);
  1133. }
  1134. }
  1135. if (view != null) {
  1136. var nme = new MouseEvent () {
  1137. X = rx,
  1138. Y = ry,
  1139. Flags = me.Flags,
  1140. OfX = 0,
  1141. OfY = 0,
  1142. View = view
  1143. };
  1144. if (_lastMouseOwnerView == null) {
  1145. _lastMouseOwnerView = view;
  1146. view.OnMouseEnter (nme);
  1147. } else if (_lastMouseOwnerView != view) {
  1148. _lastMouseOwnerView.OnMouseLeave (nme);
  1149. view.OnMouseEnter (nme);
  1150. _lastMouseOwnerView = view;
  1151. }
  1152. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1153. return;
  1154. if (view.WantContinuousButtonPressed)
  1155. WantContinuousButtonPressedView = view;
  1156. else
  1157. WantContinuousButtonPressedView = null;
  1158. // Should we bubbled up the event, if it is not handled?
  1159. view.OnMouseEvent (nme);
  1160. BringOverlappedTopToFront ();
  1161. }
  1162. }
  1163. #endregion Mouse handling
  1164. #region Keyboard handling
  1165. static Key _alternateForwardKey = Key.PageDown | Key.CtrlMask;
  1166. /// <summary>
  1167. /// Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.
  1168. /// </summary>
  1169. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1170. public static Key AlternateForwardKey {
  1171. get => _alternateForwardKey;
  1172. set {
  1173. if (_alternateForwardKey != value) {
  1174. var oldKey = _alternateForwardKey;
  1175. _alternateForwardKey = value;
  1176. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1177. }
  1178. }
  1179. }
  1180. static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1181. {
  1182. foreach (var top in _toplevels.ToArray ()) {
  1183. top.OnAlternateForwardKeyChanged (e);
  1184. }
  1185. }
  1186. static Key _alternateBackwardKey = Key.PageUp | Key.CtrlMask;
  1187. /// <summary>
  1188. /// Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.
  1189. /// </summary>
  1190. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1191. public static Key AlternateBackwardKey {
  1192. get => _alternateBackwardKey;
  1193. set {
  1194. if (_alternateBackwardKey != value) {
  1195. var oldKey = _alternateBackwardKey;
  1196. _alternateBackwardKey = value;
  1197. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1198. }
  1199. }
  1200. }
  1201. static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1202. {
  1203. foreach (var top in _toplevels.ToArray ()) {
  1204. top.OnAlternateBackwardKeyChanged (oldKey);
  1205. }
  1206. }
  1207. static Key _quitKey = Key.Q | Key.CtrlMask;
  1208. /// <summary>
  1209. /// Gets or sets the key to quit the application.
  1210. /// </summary>
  1211. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1212. public static Key QuitKey {
  1213. get => _quitKey;
  1214. set {
  1215. if (_quitKey != value) {
  1216. var oldKey = _quitKey;
  1217. _quitKey = value;
  1218. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1219. }
  1220. }
  1221. }
  1222. static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1223. {
  1224. // Duplicate the list so if it changes during enumeration we're safe
  1225. foreach (var top in _toplevels.ToArray ()) {
  1226. top.OnQuitKeyChanged (e);
  1227. }
  1228. }
  1229. static void ProcessKeyEvent (KeyEvent ke)
  1230. {
  1231. if (RootKeyEvent?.Invoke (ke) ?? false) {
  1232. return;
  1233. }
  1234. var chain = _toplevels.ToList ();
  1235. foreach (var topLevel in chain) {
  1236. if (topLevel.ProcessHotKey (ke))
  1237. return;
  1238. if (topLevel.Modal)
  1239. break;
  1240. }
  1241. foreach (var topLevel in chain) {
  1242. if (topLevel.ProcessKey (ke))
  1243. return;
  1244. if (topLevel.Modal)
  1245. break;
  1246. }
  1247. foreach (var topLevel in chain) {
  1248. // Process the key normally
  1249. if (topLevel.ProcessColdKey (ke))
  1250. return;
  1251. if (topLevel.Modal)
  1252. break;
  1253. }
  1254. }
  1255. static void ProcessKeyDownEvent (KeyEvent ke)
  1256. {
  1257. var chain = _toplevels.ToList ();
  1258. foreach (var topLevel in chain) {
  1259. if (topLevel.OnKeyDown (ke))
  1260. return;
  1261. if (topLevel.Modal)
  1262. break;
  1263. }
  1264. }
  1265. static void ProcessKeyUpEvent (KeyEvent ke)
  1266. {
  1267. var chain = _toplevels.ToList ();
  1268. foreach (var topLevel in chain) {
  1269. if (topLevel.OnKeyUp (ke))
  1270. return;
  1271. if (topLevel.Modal)
  1272. break;
  1273. }
  1274. }
  1275. /// <summary>
  1276. /// <para>
  1277. /// Called for new KeyPress events before any processing is performed or
  1278. /// views evaluate. Use for global key handling and/or debugging.
  1279. /// </para>
  1280. /// <para>Return true to suppress the KeyPress event</para>
  1281. /// </summary>
  1282. public static Func<KeyEvent, bool> RootKeyEvent;
  1283. #endregion Keyboard handling
  1284. }
  1285. }