Application.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  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;
  24. using System.Text.Json.Serialization;
  25. using static Terminal.Gui.ConfigurationManager;
  26. namespace Terminal.Gui {
  27. /// <summary>
  28. /// A static, singleton class providing the main application driver for Terminal.Gui apps.
  29. /// </summary>
  30. /// <example>
  31. /// <code>
  32. /// // A simple Terminal.Gui app that creates a window with a frame and title with
  33. /// // 5 rows/columns of padding.
  34. /// Application.Init();
  35. /// var win = new Window ($"Example App ({Application.QuitKey} to quit)") {
  36. /// X = 5,
  37. /// Y = 5,
  38. /// Width = Dim.Fill (5),
  39. /// Height = Dim.Fill (5)
  40. /// };
  41. /// Application.Top.Add(win);
  42. /// Application.Run();
  43. /// Application.Shutdown();
  44. /// </code>
  45. /// </example>
  46. /// <remarks>
  47. /// <para>
  48. /// Creates a instance of <see cref="Terminal.Gui.MainLoop"/> to process input events, handle timers and
  49. /// other sources of data. It is accessible via the <see cref="MainLoop"/> property.
  50. /// </para>
  51. /// <para>
  52. /// You can hook up to the <see cref="Iteration"/> event to have your method
  53. /// invoked on each iteration of the <see cref="Terminal.Gui.MainLoop"/>.
  54. /// </para>
  55. /// <para>
  56. /// When invoked sets the SynchronizationContext to one that is tied
  57. /// to the mainloop, allowing user code to use async/await.
  58. /// </para>
  59. /// </remarks>
  60. public static partial 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 (new KeyChangedEventArgs (oldKey, value));
  154. }
  155. }
  156. }
  157. static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  158. {
  159. foreach (var top in toplevels.ToArray ()) {
  160. top.OnAlternateForwardKeyChanged (e);
  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 (new KeyChangedEventArgs (oldKey, value));
  175. }
  176. }
  177. }
  178. static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs 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 (new KeyChangedEventArgs (oldKey, value));
  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 (KeyChangedEventArgs e)
  205. {
  206. // Duplicate the list so if it changes during enumeration we're safe
  207. foreach (var top in toplevels.ToArray ()) {
  208. top.OnQuitKeyChanged (e);
  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 EventHandler<RunStateEventArgs> 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 EventHandler<ToplevelEventArgs> 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 = View.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 FindTopFromView (View view)
  607. {
  608. View top = view?.SuperView != null && view?.SuperView != Top
  609. ? view.SuperView : view;
  610. while (top?.SuperView != null && top?.SuperView != Top) {
  611. top = top.SuperView;
  612. }
  613. return top;
  614. }
  615. static View mouseGrabView;
  616. /// <summary>
  617. /// The view that grabbed the mouse, to where will be routed all the mouse events.
  618. /// </summary>
  619. public static View MouseGrabView => mouseGrabView;
  620. /// <summary>
  621. /// Event to be invoked when a view want grab the mouse which can be canceled.
  622. /// </summary>
  623. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  624. /// <summary>
  625. /// Event to be invoked when a view want ungrab the mouse which can be canceled.
  626. /// </summary>
  627. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  628. /// <summary>
  629. /// Event to be invoked when a view grab the mouse.
  630. /// </summary>
  631. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  632. /// <summary>
  633. /// Event to be invoked when a view ungrab the mouse.
  634. /// </summary>
  635. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  636. /// <summary>
  637. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  638. /// </summary>
  639. /// <returns>The grab.</returns>
  640. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  641. public static void GrabMouse (View view)
  642. {
  643. if (view == null)
  644. return;
  645. if (!OnGrabbingMouse (view)) {
  646. OnGrabbedMouse (view);
  647. mouseGrabView = view;
  648. Driver.UncookMouse ();
  649. }
  650. }
  651. /// <summary>
  652. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  653. /// </summary>
  654. public static void UngrabMouse ()
  655. {
  656. if (mouseGrabView == null)
  657. return;
  658. if (!OnUnGrabbingMouse (mouseGrabView)) {
  659. OnUnGrabbedMouse (mouseGrabView);
  660. mouseGrabView = null;
  661. Driver.CookMouse ();
  662. }
  663. }
  664. static bool OnGrabbingMouse (View view)
  665. {
  666. if (view == null)
  667. return false;
  668. var evArgs = new GrabMouseEventArgs (view);
  669. GrabbingMouse?.Invoke (view, evArgs);
  670. return evArgs.Cancel;
  671. }
  672. static bool OnUnGrabbingMouse (View view)
  673. {
  674. if (view == null)
  675. return false;
  676. var evArgs = new GrabMouseEventArgs (view);
  677. UnGrabbingMouse?.Invoke (view, evArgs);
  678. return evArgs.Cancel;
  679. }
  680. static void OnGrabbedMouse (View view)
  681. {
  682. if (view == null)
  683. return;
  684. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  685. }
  686. static void OnUnGrabbedMouse (View view)
  687. {
  688. if (view == null)
  689. return;
  690. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (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 = 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. }
  716. if (view != null) {
  717. me.View = view;
  718. }
  719. RootMouseEvent?.Invoke (me);
  720. if (me.Handled) {
  721. return;
  722. }
  723. if (mouseGrabView != null) {
  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 = 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. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  852. if (!toplevel.IsInitialized) {
  853. toplevel.BeginInit ();
  854. toplevel.EndInit ();
  855. }
  856. lock (toplevels) {
  857. // If Top was already initialized with Init, and Begin has never been called
  858. // Top was not added to the toplevels Stack. It will thus never get disposed.
  859. // Clean it up here:
  860. if (Top != null && toplevel != Top && !toplevels.Contains (Top)) {
  861. Top.Dispose ();
  862. Top = null;
  863. } else if (Top != null && toplevel != Top && toplevels.Contains (Top)) {
  864. Top.OnLeave (toplevel);
  865. }
  866. if (string.IsNullOrEmpty (toplevel.Id.ToString ())) {
  867. var count = 1;
  868. var id = (toplevels.Count + count).ToString ();
  869. while (toplevels.Count > 0 && toplevels.FirstOrDefault (x => x.Id.ToString () == id) != null) {
  870. count++;
  871. id = (toplevels.Count + count).ToString ();
  872. }
  873. toplevel.Id = (toplevels.Count + count).ToString ();
  874. toplevels.Push (toplevel);
  875. } else {
  876. var dup = toplevels.FirstOrDefault (x => x.Id.ToString () == toplevel.Id);
  877. if (dup == null) {
  878. toplevels.Push (toplevel);
  879. }
  880. }
  881. if (toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  882. throw new ArgumentException ("There are duplicates toplevels Id's");
  883. }
  884. }
  885. // Fix $520 - Set Top = toplevel if Top == null
  886. if (Top == null || toplevel.IsMdiContainer) {
  887. Top = toplevel;
  888. }
  889. var refreshDriver = true;
  890. if (MdiTop == null || toplevel.IsMdiContainer || (Current?.Modal == false && toplevel.Modal)
  891. || (Current?.Modal == false && !toplevel.Modal) || (Current?.Modal == true && toplevel.Modal)) {
  892. if (toplevel.Visible) {
  893. Current = toplevel;
  894. SetCurrentAsTop ();
  895. } else {
  896. refreshDriver = false;
  897. }
  898. } else if ((MdiTop != null && toplevel != MdiTop && Current?.Modal == true && !toplevels.Peek ().Modal)
  899. || (MdiTop != null && toplevel != MdiTop && Current?.Running == false)) {
  900. refreshDriver = false;
  901. MoveCurrent (toplevel);
  902. } else {
  903. refreshDriver = false;
  904. MoveCurrent (Current);
  905. }
  906. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  907. if (toplevel.LayoutStyle == LayoutStyle.Computed) {
  908. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  909. }
  910. toplevel.LayoutSubviews ();
  911. toplevel.PositionToplevels ();
  912. toplevel.WillPresent ();
  913. if (refreshDriver) {
  914. MdiTop?.OnChildLoaded (toplevel);
  915. toplevel.OnLoaded ();
  916. Redraw (toplevel);
  917. toplevel.PositionCursor ();
  918. Driver.Refresh ();
  919. }
  920. NotifyNewRunState?.Invoke (toplevel, new RunStateEventArgs (rs));
  921. return rs;
  922. }
  923. /// <summary>
  924. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  925. /// </summary>
  926. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  927. public static void End (RunState runState)
  928. {
  929. if (runState == null)
  930. throw new ArgumentNullException (nameof (runState));
  931. if (MdiTop != null) {
  932. MdiTop.OnChildUnloaded (runState.Toplevel);
  933. } else {
  934. runState.Toplevel.OnUnloaded ();
  935. }
  936. // End the RunState.Toplevel
  937. // First, take it off the toplevel Stack
  938. if (toplevels.Count > 0) {
  939. if (toplevels.Peek () != runState.Toplevel) {
  940. // If there the top of the stack is not the RunState.Toplevel then
  941. // this call to End is not balanced with the call to Begin that started the RunState
  942. throw new ArgumentException ("End must be balanced with calls to Begin");
  943. }
  944. toplevels.Pop ();
  945. }
  946. // Notify that it is closing
  947. runState.Toplevel?.OnClosed (runState.Toplevel);
  948. // If there is a MdiTop that is not the RunState.Toplevel then runstate.TopLevel
  949. // is a child of MidTop and we should notify the MdiTop that it is closing
  950. if (MdiTop != null && !(runState.Toplevel).Modal && runState.Toplevel != MdiTop) {
  951. MdiTop.OnChildClosed (runState.Toplevel);
  952. }
  953. // Set Current and Top to the next TopLevel on the stack
  954. if (toplevels.Count == 0) {
  955. Current = null;
  956. } else {
  957. Current = toplevels.Peek ();
  958. if (toplevels.Count == 1 && Current == MdiTop) {
  959. MdiTop.OnAllChildClosed ();
  960. } else {
  961. SetCurrentAsTop ();
  962. Current.OnEnter (Current);
  963. }
  964. Refresh ();
  965. }
  966. runState.Toplevel?.Dispose ();
  967. runState.Toplevel = null;
  968. runState.Dispose ();
  969. }
  970. /// <summary>
  971. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  972. /// </summary>
  973. /// <remarks>
  974. /// Shutdown must be called for every call to <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> or <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  975. /// to ensure all resources are cleaned up (Disposed) and terminal settings are restored.
  976. /// </remarks>
  977. public static void Shutdown ()
  978. {
  979. ResetState ();
  980. ConfigurationManager.PrintJsonErrors ();
  981. }
  982. // Encapsulate all setting of initial state for Application; Having
  983. // this in a function like this ensures we don't make mistakes in
  984. // guaranteeing that the state of this singleton is deterministic when Init
  985. // starts running and after Shutdown returns.
  986. static void ResetState ()
  987. {
  988. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  989. // Init created. Apps that do any threading will need to code defensively for this.
  990. // e.g. see Issue #537
  991. foreach (var t in toplevels) {
  992. t.Running = false;
  993. t.Dispose ();
  994. }
  995. toplevels.Clear ();
  996. Current = null;
  997. Top?.Dispose ();
  998. Top = null;
  999. // BUGBUG: MdiTop is not cleared here, but it should be?
  1000. MainLoop = null;
  1001. Driver?.End ();
  1002. Driver = null;
  1003. Iteration = null;
  1004. RootMouseEvent = null;
  1005. RootKeyEvent = null;
  1006. Resized = null;
  1007. _mainThreadId = -1;
  1008. NotifyNewRunState = null;
  1009. NotifyStopRunState = null;
  1010. _initialized = false;
  1011. mouseGrabView = null;
  1012. _enableConsoleScrolling = false;
  1013. lastMouseOwnerView = null;
  1014. // Reset synchronization context to allow the user to run async/await,
  1015. // as the main loop has been ended, the synchronization context from
  1016. // gui.cs does no longer process any callbacks. See #1084 for more details:
  1017. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  1018. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  1019. }
  1020. static void Redraw (View view)
  1021. {
  1022. view.Redraw (view.Bounds);
  1023. Driver.Refresh ();
  1024. }
  1025. /// <summary>
  1026. /// Triggers a refresh of the entire display.
  1027. /// </summary>
  1028. public static void Refresh ()
  1029. {
  1030. Driver.UpdateOffScreen ();
  1031. View last = null;
  1032. foreach (var v in toplevels.Reverse ()) {
  1033. if (v.Visible) {
  1034. v.SetNeedsDisplay ();
  1035. v.Redraw (v.Bounds);
  1036. }
  1037. last = v;
  1038. }
  1039. last?.PositionCursor ();
  1040. Driver.Refresh ();
  1041. }
  1042. /// <summary>
  1043. /// Building block API: Runs the <see cref="MainLoop"/> for the created <see cref="Toplevel"/>.
  1044. /// </summary>
  1045. /// <remarks>
  1046. /// Use the <paramref name="wait"/> parameter to control whether this is a blocking or non-blocking call.
  1047. /// </remarks>
  1048. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1049. /// <param name="wait">By default this is <see langword="true"/> which will execute the runloop waiting for events,
  1050. /// if set to <see langword="false"/>, a single iteration will execute.</param>
  1051. public static void RunLoop (RunState state, bool wait = true)
  1052. {
  1053. if (state == null)
  1054. throw new ArgumentNullException (nameof (state));
  1055. if (state.Toplevel == null)
  1056. throw new ObjectDisposedException ("state");
  1057. bool firstIteration = true;
  1058. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1059. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  1060. return;
  1061. }
  1062. RunMainLoopIteration (ref state, wait, ref firstIteration);
  1063. }
  1064. }
  1065. /// <summary>
  1066. /// Run one iteration of the <see cref="MainLoop"/>.
  1067. /// </summary>
  1068. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  1069. /// <param name="wait">If <see langword="true"/> will execute the runloop waiting for events. If <see langword="true"/>
  1070. /// will return after a single iteration.</param>
  1071. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  1072. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  1073. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  1074. {
  1075. if (MainLoop.EventsPending (wait)) {
  1076. // Notify Toplevel it's ready
  1077. if (firstIteration) {
  1078. state.Toplevel.OnReady ();
  1079. }
  1080. MainLoop.MainIteration ();
  1081. Iteration?.Invoke ();
  1082. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  1083. if ((state.Toplevel != Current && Current?.Modal == true)
  1084. || (state.Toplevel != Current && Current?.Modal == false)) {
  1085. MdiTop?.OnDeactivate (state.Toplevel);
  1086. state.Toplevel = Current;
  1087. MdiTop?.OnActivate (state.Toplevel);
  1088. Top.SetSubViewNeedsDisplay ();
  1089. Refresh ();
  1090. }
  1091. if (Driver.EnsureCursorVisibility ()) {
  1092. state.Toplevel.SetNeedsDisplay ();
  1093. }
  1094. } else if (!wait) {
  1095. return;
  1096. }
  1097. firstIteration = false;
  1098. if (state.Toplevel != Top
  1099. && (!Top._needsDisplay.IsEmpty || Top._childNeedsDisplay || Top.LayoutNeeded)) {
  1100. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  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. }
  1109. if (toplevels.Count == 1 && state.Toplevel == Top
  1110. && (Driver.Cols != state.Toplevel.Frame.Width || Driver.Rows != state.Toplevel.Frame.Height)
  1111. && (!state.Toplevel._needsDisplay.IsEmpty || state.Toplevel._childNeedsDisplay || state.Toplevel.LayoutNeeded)) {
  1112. Driver.SetAttribute (Colors.TopLevel.Normal);
  1113. state.Toplevel.Clear (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1114. }
  1115. if (!state.Toplevel._needsDisplay.IsEmpty || state.Toplevel._childNeedsDisplay || state.Toplevel.LayoutNeeded
  1116. || MdiChildNeedsDisplay ()) {
  1117. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1118. if (DebugDrawBounds) {
  1119. DrawBounds (state.Toplevel);
  1120. }
  1121. state.Toplevel.PositionCursor ();
  1122. Driver.Refresh ();
  1123. } else {
  1124. Driver.UpdateCursor ();
  1125. }
  1126. if (state.Toplevel != Top && !state.Toplevel.Modal
  1127. && (!Top._needsDisplay.IsEmpty || Top._childNeedsDisplay || Top.LayoutNeeded)) {
  1128. Top.Redraw (Top.Bounds);
  1129. }
  1130. }
  1131. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel toplevel)
  1132. {
  1133. if (!toplevel.Running || (toplevel == Current && toplevel.Visible) || MdiTop == null || toplevels.Peek ().Modal) {
  1134. return;
  1135. }
  1136. foreach (var top in toplevels.Reverse ()) {
  1137. if (top.Modal && top != Current) {
  1138. MoveCurrent (top);
  1139. return;
  1140. }
  1141. }
  1142. if (!toplevel.Visible && toplevel == Current) {
  1143. MoveNext ();
  1144. }
  1145. }
  1146. static bool MdiChildNeedsDisplay ()
  1147. {
  1148. if (MdiTop == null) {
  1149. return false;
  1150. }
  1151. foreach (var top in toplevels) {
  1152. if (top != Current && top.Visible && (!top._needsDisplay.IsEmpty || top._childNeedsDisplay || top.LayoutNeeded)) {
  1153. MdiTop.SetSubViewNeedsDisplay ();
  1154. return true;
  1155. }
  1156. }
  1157. return false;
  1158. }
  1159. internal static bool DebugDrawBounds = false;
  1160. // Need to look into why this does not work properly.
  1161. static void DrawBounds (View v)
  1162. {
  1163. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1164. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1165. foreach (var sub in v.InternalSubviews)
  1166. DrawBounds (sub);
  1167. }
  1168. /// <summary>
  1169. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>.
  1170. /// </summary>
  1171. /// <remarks>
  1172. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1173. /// </remarks>
  1174. public static void Run (Func<Exception, bool> errorHandler = null)
  1175. {
  1176. Run (Top, errorHandler);
  1177. }
  1178. /// <summary>
  1179. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  1180. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  1181. /// <para>
  1182. /// Calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> first is not needed as this function will initialze the application.
  1183. /// </para>
  1184. /// <para>
  1185. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has
  1186. /// returned) to ensure resources are cleaned up and terminal settings restored.
  1187. /// </para>
  1188. /// </summary>
  1189. /// <remarks>
  1190. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1191. /// </remarks>
  1192. /// <param name="errorHandler"></param>
  1193. /// <param name="driver">The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  1194. /// platform will be used (<see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>).
  1195. /// This parameteter must be <see langword="null"/> if <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has already been called.
  1196. /// </param>
  1197. /// <param name="mainLoopDriver">Specifies the <see cref="MainLoop"/> to use.</param>
  1198. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) where T : Toplevel, new()
  1199. {
  1200. if (_initialized) {
  1201. if (Driver != null) {
  1202. // Init() has been called and we have a driver, so just run the app.
  1203. var top = new T ();
  1204. var type = top.GetType ().BaseType;
  1205. while (type != typeof (Toplevel) && type != typeof (object)) {
  1206. type = type.BaseType;
  1207. }
  1208. if (type != typeof (Toplevel)) {
  1209. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  1210. }
  1211. Run (top, errorHandler);
  1212. } else {
  1213. // This codepath should be impossible because Init(null, null) will select the platform default driver
  1214. throw new InvalidOperationException ("Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called.");
  1215. }
  1216. } else {
  1217. // Init() has NOT been called.
  1218. InternalInit (() => new T (), driver, mainLoopDriver, calledViaRunT: true);
  1219. Run (Top, errorHandler);
  1220. }
  1221. }
  1222. /// <summary>
  1223. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  1224. /// </summary>
  1225. /// <remarks>
  1226. /// <para>
  1227. /// This method is used to start processing events
  1228. /// for the main application, but it is also used to
  1229. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  1230. /// </para>
  1231. /// <para>
  1232. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  1233. /// </para>
  1234. /// <para>
  1235. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  1236. /// and then calling <see cref="End(RunState)"/>.
  1237. /// </para>
  1238. /// <para>
  1239. /// Alternatively, to have a program control the main loop and
  1240. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  1241. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  1242. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  1243. /// then return control immediately.
  1244. /// </para>
  1245. /// <para>
  1246. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exeptions will be rethrown.
  1247. /// Otheriwse, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  1248. /// returns <see langword="true"/> the <see cref="RunLoop(RunState, bool)"/> will resume; otherwise
  1249. /// this method will exit.
  1250. /// </para>
  1251. /// </remarks>
  1252. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  1253. /// <param name="errorHandler">RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  1254. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  1255. {
  1256. var resume = true;
  1257. while (resume) {
  1258. #if !DEBUG
  1259. try {
  1260. #endif
  1261. resume = false;
  1262. var runToken = Begin (view);
  1263. // If ExitRunLoopAfterFirstIteration is true then the user must dispose of the runToken
  1264. // by using NotifyStopRunState event.
  1265. RunLoop (runToken);
  1266. if (!ExitRunLoopAfterFirstIteration) {
  1267. End (runToken);
  1268. }
  1269. #if !DEBUG
  1270. }
  1271. catch (Exception error)
  1272. {
  1273. if (errorHandler == null)
  1274. {
  1275. throw;
  1276. }
  1277. resume = errorHandler(error);
  1278. }
  1279. #endif
  1280. }
  1281. }
  1282. /// <summary>
  1283. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  1284. /// </summary>
  1285. /// <param name="top">The toplevel to request stop.</param>
  1286. /// <remarks>
  1287. /// <para>
  1288. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  1289. /// </para>
  1290. /// <para>
  1291. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the currently running <see cref="Toplevel"/> to false.
  1292. /// </para>
  1293. /// </remarks>
  1294. public static void RequestStop (Toplevel top = null)
  1295. {
  1296. if (MdiTop == null || top == null || (MdiTop == null && top != null)) {
  1297. top = Current;
  1298. }
  1299. if (MdiTop != null && top.IsMdiContainer && top?.Running == true
  1300. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  1301. MdiTop.RequestStop ();
  1302. } else if (MdiTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  1303. && top.Modal && top.Running) {
  1304. var ev = new ToplevelClosingEventArgs (Current);
  1305. Current.OnClosing (ev);
  1306. if (ev.Cancel) {
  1307. return;
  1308. }
  1309. ev = new ToplevelClosingEventArgs (top);
  1310. top.OnClosing (ev);
  1311. if (ev.Cancel) {
  1312. return;
  1313. }
  1314. Current.Running = false;
  1315. OnNotifyStopRunState (Current);
  1316. top.Running = false;
  1317. OnNotifyStopRunState (top);
  1318. } else if ((MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1319. && Current?.Running == true && !top.Running)
  1320. || (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1321. && Current?.Running == false && !top.Running && toplevels.ToArray () [1].Running)) {
  1322. MoveCurrent (top);
  1323. } else if (MdiTop != null && Current != top && Current?.Running == true && !top.Running
  1324. && Current?.Modal == true && top.Modal) {
  1325. // The Current and the top are both modal so needed to set the Current.Running to false too.
  1326. Current.Running = false;
  1327. OnNotifyStopRunState (Current);
  1328. } else if (MdiTop != null && Current == top && MdiTop?.Running == true && Current?.Running == true && top.Running
  1329. && Current?.Modal == true && top.Modal) {
  1330. // The MdiTop was requested to stop inside a modal toplevel which is the Current and top,
  1331. // both are the same, so needed to set the Current.Running to false too.
  1332. Current.Running = false;
  1333. OnNotifyStopRunState (Current);
  1334. } else {
  1335. Toplevel currentTop;
  1336. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  1337. currentTop = Current;
  1338. } else {
  1339. currentTop = top;
  1340. }
  1341. if (!currentTop.Running) {
  1342. return;
  1343. }
  1344. var ev = new ToplevelClosingEventArgs (currentTop);
  1345. currentTop.OnClosing (ev);
  1346. if (ev.Cancel) {
  1347. return;
  1348. }
  1349. currentTop.Running = false;
  1350. OnNotifyStopRunState (currentTop);
  1351. }
  1352. }
  1353. static void OnNotifyStopRunState (Toplevel top)
  1354. {
  1355. if (ExitRunLoopAfterFirstIteration) {
  1356. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  1357. }
  1358. }
  1359. /// <summary>
  1360. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  1361. /// </summary>
  1362. public static Action<ResizedEventArgs> Resized;
  1363. static void TerminalResized ()
  1364. {
  1365. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1366. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  1367. Driver.Clip = full;
  1368. foreach (var t in toplevels) {
  1369. t.SetRelativeLayout (full);
  1370. t.LayoutSubviews ();
  1371. t.PositionToplevels ();
  1372. t.OnResized (new SizeChangedEventArgs (full.Size));
  1373. }
  1374. Refresh ();
  1375. }
  1376. static bool SetCurrentAsTop ()
  1377. {
  1378. if (MdiTop == null && Current != Top && Current?.SuperView == null && Current?.Modal == false) {
  1379. if (Current.Frame != new Rect (0, 0, Driver.Cols, Driver.Rows)) {
  1380. Current.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1381. }
  1382. Top = Current;
  1383. return true;
  1384. }
  1385. return false;
  1386. }
  1387. /// <summary>
  1388. /// Move to the next Mdi child from the <see cref="MdiTop"/>.
  1389. /// </summary>
  1390. public static void MoveNext ()
  1391. {
  1392. if (MdiTop != null && !Current.Modal) {
  1393. lock (toplevels) {
  1394. toplevels.MoveNext ();
  1395. var isMdi = false;
  1396. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1397. if (!isMdi && toplevels.Peek () == MdiTop) {
  1398. isMdi = true;
  1399. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1400. MoveCurrent (Top);
  1401. break;
  1402. }
  1403. toplevels.MoveNext ();
  1404. }
  1405. Current = toplevels.Peek ();
  1406. }
  1407. }
  1408. }
  1409. /// <summary>
  1410. /// Move to the previous Mdi child from the <see cref="MdiTop"/>.
  1411. /// </summary>
  1412. public static void MovePrevious ()
  1413. {
  1414. if (MdiTop != null && !Current.Modal) {
  1415. lock (toplevels) {
  1416. toplevels.MovePrevious ();
  1417. var isMdi = false;
  1418. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1419. if (!isMdi && toplevels.Peek () == MdiTop) {
  1420. isMdi = true;
  1421. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1422. MoveCurrent (Top);
  1423. break;
  1424. }
  1425. toplevels.MovePrevious ();
  1426. }
  1427. Current = toplevels.Peek ();
  1428. }
  1429. }
  1430. }
  1431. internal static bool ShowChild (Toplevel top)
  1432. {
  1433. if (top.Visible && MdiTop != null && Current?.Modal == false) {
  1434. lock (toplevels) {
  1435. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1436. Current = top;
  1437. }
  1438. return true;
  1439. }
  1440. return false;
  1441. }
  1442. /// <summary>
  1443. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  1444. /// </summary>
  1445. public static void DoEvents ()
  1446. {
  1447. MainLoop.Driver.Wakeup ();
  1448. }
  1449. /// <summary>
  1450. /// Ensures that the superview of the most focused view is on front.
  1451. /// </summary>
  1452. public static void EnsuresTopOnFront ()
  1453. {
  1454. if (MdiTop != null) {
  1455. return;
  1456. }
  1457. var top = FindTopFromView (Top?.MostFocused);
  1458. if (top != null && Top.Subviews.Count > 1 && Top.Subviews [Top.Subviews.Count - 1] != top) {
  1459. Top.BringSubviewToFront (top);
  1460. }
  1461. }
  1462. internal static List<CultureInfo> GetSupportedCultures ()
  1463. {
  1464. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  1465. // Get the assembly
  1466. Assembly assembly = Assembly.GetExecutingAssembly ();
  1467. //Find the location of the assembly
  1468. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  1469. // Find the resource file name of the assembly
  1470. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  1471. // Return all culture for which satellite folder found with culture code.
  1472. return culture.Where (cultureInfo =>
  1473. assemblyLocation != null &&
  1474. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  1475. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  1476. ).ToList ();
  1477. }
  1478. }
  1479. }