Application.cs 54 KB

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