Application.cs 53 KB

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