Application.cs 54 KB

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