Application.cs 49 KB

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