Application.cs 54 KB

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