Application.cs 53 KB

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