Application.cs 54 KB

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