Application.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  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. /// Invoked when a view wants to grab the mouse; can be canceled.
  623. /// </summary>
  624. public static event Func<View, bool> GrabbingMouse;
  625. /// <summary>
  626. /// Invoked when a view wants ungrab the mouse; can be canceled.
  627. /// </summary>
  628. public static event Func<View, bool> UnGrabbingMouse;
  629. /// <summary>
  630. /// Event to be invoked when a view grab the mouse.
  631. /// </summary>
  632. public static event Action<View> GrabbedMouse;
  633. /// <summary>
  634. /// Event to be invoked when a view ungrab the mouse.
  635. /// </summary>
  636. public static event Action<View> UnGrabbedMouse;
  637. /// <summary>
  638. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  639. /// </summary>
  640. /// <returns>The grab.</returns>
  641. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  642. public static void GrabMouse (View view)
  643. {
  644. if (view == null)
  645. return;
  646. if (!OnGrabbingMouse (view)) {
  647. OnGrabbedMouse (view);
  648. mouseGrabView = view;
  649. Driver.UncookMouse ();
  650. }
  651. }
  652. /// <summary>
  653. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  654. /// </summary>
  655. public static void UngrabMouse ()
  656. {
  657. if (mouseGrabView == null)
  658. return;
  659. if (!OnUnGrabbingMouse (mouseGrabView)) {
  660. OnUnGrabbedMouse (mouseGrabView);
  661. mouseGrabView = null;
  662. Driver.CookMouse ();
  663. }
  664. }
  665. static bool OnGrabbingMouse (View view)
  666. {
  667. if (view == null || GrabbingMouse == null)
  668. return false;
  669. return (bool)(GrabbingMouse?.Invoke (view));
  670. }
  671. static bool OnUnGrabbingMouse (View view)
  672. {
  673. if (view == null || UnGrabbingMouse == null)
  674. return false;
  675. return (bool)(UnGrabbingMouse?.Invoke (view));
  676. }
  677. static void OnGrabbedMouse (View view)
  678. {
  679. if (view == null)
  680. return;
  681. GrabbedMouse?.Invoke (view);
  682. }
  683. static void OnUnGrabbedMouse (View view)
  684. {
  685. if (view == null)
  686. return;
  687. UnGrabbedMouse?.Invoke (view);
  688. }
  689. /// <summary>
  690. /// Merely a debugging aid to see the raw mouse events
  691. /// </summary>
  692. public static Action<MouseEvent> RootMouseEvent;
  693. /// <summary>
  694. /// <para>
  695. /// Called for new KeyPress events before any processing is performed or
  696. /// views evaluate. Use for global key handling and/or debugging.
  697. /// </para>
  698. /// <para>Return true to suppress the KeyPress event</para>
  699. /// </summary>
  700. public static Func<KeyEvent, bool> RootKeyEvent;
  701. static View lastMouseOwnerView;
  702. static void ProcessMouseEvent (MouseEvent me)
  703. {
  704. if (IsMouseDisabled) {
  705. return;
  706. }
  707. EnsuresMdiTopOnFrontIfMdiTopMostFocused ();
  708. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  709. if (view != null && view.WantContinuousButtonPressed)
  710. WantContinuousButtonPressedView = view;
  711. else
  712. WantContinuousButtonPressedView = null;
  713. if (view != null) {
  714. me.View = view;
  715. }
  716. RootMouseEvent?.Invoke (me);
  717. if (me.Handled) {
  718. return;
  719. }
  720. if (mouseGrabView != null) {
  721. if (view == null) {
  722. view = mouseGrabView;
  723. }
  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 || view.SuperView == MdiTop) && !Current.Modal && MdiTop != null
  742. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  743. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  744. view = FindDeepestView (top, me.X, me.Y, out rx, out ry);
  745. if (view != null && view != MdiTop && top != Current && top.MostFocused != null
  746. && top.MostFocused.GetType ().Name != "ContentView") {
  747. MoveCurrent ((Toplevel)top);
  748. }
  749. }
  750. if (view != null) {
  751. var nme = new MouseEvent () {
  752. X = rx,
  753. Y = ry,
  754. Flags = me.Flags,
  755. OfX = 0,
  756. OfY = 0,
  757. View = view
  758. };
  759. if (lastMouseOwnerView == null) {
  760. lastMouseOwnerView = view;
  761. view.OnMouseEnter (nme);
  762. } else if (lastMouseOwnerView != view) {
  763. lastMouseOwnerView.OnMouseLeave (nme);
  764. view.OnMouseEnter (nme);
  765. lastMouseOwnerView = view;
  766. }
  767. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  768. return;
  769. if (view.WantContinuousButtonPressed)
  770. WantContinuousButtonPressedView = view;
  771. else
  772. WantContinuousButtonPressedView = null;
  773. // Should we bubbled up the event, if it is not handled?
  774. if (view.OnMouseEvent (nme)) {
  775. EnsuresMdiTopOnFrontIfMdiTopMostFocused ();
  776. }
  777. EnsuresTopOnFront ();
  778. }
  779. }
  780. static void EnsuresMdiTopOnFrontIfMdiTopMostFocused ()
  781. {
  782. if (MdiTop != null && Current != MdiTop && MdiTop.MostFocused != null
  783. && MdiTop.MostFocused.GetType ().Name != "ContentView") {
  784. MoveCurrent (Top);
  785. }
  786. }
  787. // Only return true if the Current has changed.
  788. static bool MoveCurrent (Toplevel top)
  789. {
  790. // The Current is modal and the top is not modal toplevel then
  791. // the Current must be moved above the first not modal toplevel.
  792. if (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == true && !toplevels.Peek ().Modal) {
  793. lock (toplevels) {
  794. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  795. }
  796. var index = 0;
  797. var savedToplevels = toplevels.ToArray ();
  798. foreach (var t in savedToplevels) {
  799. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  800. lock (toplevels) {
  801. toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  802. }
  803. }
  804. index++;
  805. }
  806. return false;
  807. }
  808. // The Current and the top are both not running toplevel then
  809. // the top must be moved above the first not running toplevel.
  810. if (MdiTop != null && top != MdiTop && top != Current && Current?.Running == false && !top.Running) {
  811. lock (toplevels) {
  812. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  813. }
  814. var index = 0;
  815. foreach (var t in toplevels.ToArray ()) {
  816. if (!t.Running && t != Current && index > 0) {
  817. lock (toplevels) {
  818. toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  819. }
  820. }
  821. index++;
  822. }
  823. return false;
  824. }
  825. if ((MdiTop != null && top?.Modal == true && toplevels.Peek () != top)
  826. || (MdiTop != null && Current != MdiTop && Current?.Modal == false && top == MdiTop)
  827. || (MdiTop != null && Current?.Modal == false && top != Current)
  828. || (MdiTop != null && Current?.Modal == true && top == MdiTop)) {
  829. lock (toplevels) {
  830. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  831. Current = top;
  832. }
  833. }
  834. return true;
  835. }
  836. static bool OutsideFrame (Point p, Rect r)
  837. {
  838. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  839. }
  840. /// <summary>
  841. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  842. /// </summary>
  843. /// <returns>The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  844. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  845. /// <remarks>
  846. /// This method prepares the provided toplevel for running with the focus,
  847. /// it adds this to the list of toplevels, sets up the mainloop to process the
  848. /// event, lays out the subviews, focuses the first element, and draws the
  849. /// toplevel in the screen. This is usually followed by executing
  850. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  851. /// undo these changes.
  852. /// </remarks>
  853. public static RunState Begin (Toplevel toplevel)
  854. {
  855. if (toplevel == null) {
  856. throw new ArgumentNullException (nameof (toplevel));
  857. } else if (toplevel.IsMdiContainer && MdiTop != toplevel && MdiTop != null) {
  858. throw new InvalidOperationException ("Only one Mdi Container is allowed.");
  859. }
  860. var rs = new RunState (toplevel);
  861. if (toplevel is ISupportInitializeNotification initializableNotification &&
  862. !initializableNotification.IsInitialized) {
  863. initializableNotification.BeginInit ();
  864. initializableNotification.EndInit ();
  865. } else if (toplevel is ISupportInitialize initializable) {
  866. initializable.BeginInit ();
  867. initializable.EndInit ();
  868. }
  869. lock (toplevels) {
  870. // If Top was already initialized with Init, and Begin has never been called
  871. // Top was not added to the toplevels Stack. It will thus never get disposed.
  872. // Clean it up here:
  873. if (Top != null && toplevel != Top && !toplevels.Contains (Top)) {
  874. Top.Dispose ();
  875. Top = null;
  876. } else if (Top != null && toplevel != Top && toplevels.Contains (Top)) {
  877. Top.OnLeave (toplevel);
  878. }
  879. if (string.IsNullOrEmpty (toplevel.Id.ToString ())) {
  880. var count = 1;
  881. var id = (toplevels.Count + count).ToString ();
  882. while (toplevels.Count > 0 && toplevels.FirstOrDefault (x => x.Id.ToString () == id) != null) {
  883. count++;
  884. id = (toplevels.Count + count).ToString ();
  885. }
  886. toplevel.Id = (toplevels.Count + count).ToString ();
  887. toplevels.Push (toplevel);
  888. } else {
  889. var dup = toplevels.FirstOrDefault (x => x.Id.ToString () == toplevel.Id);
  890. if (dup == null) {
  891. toplevels.Push (toplevel);
  892. }
  893. }
  894. if (toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  895. throw new ArgumentException ("There are duplicates toplevels Id's");
  896. }
  897. }
  898. // Fix $520 - Set Top = toplevel if Top == null
  899. if (Top == null || toplevel.IsMdiContainer) {
  900. Top = toplevel;
  901. }
  902. var refreshDriver = true;
  903. if (MdiTop == null || toplevel.IsMdiContainer || (Current?.Modal == false && toplevel.Modal)
  904. || (Current?.Modal == false && !toplevel.Modal) || (Current?.Modal == true && toplevel.Modal)) {
  905. if (toplevel.Visible) {
  906. Current = toplevel;
  907. SetCurrentAsTop ();
  908. } else {
  909. refreshDriver = false;
  910. }
  911. } else if ((MdiTop != null && toplevel != MdiTop && Current?.Modal == true && !toplevels.Peek ().Modal)
  912. || (MdiTop != null && toplevel != MdiTop && Current?.Running == false)) {
  913. refreshDriver = false;
  914. MoveCurrent (toplevel);
  915. } else {
  916. refreshDriver = false;
  917. MoveCurrent (Current);
  918. }
  919. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  920. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  921. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  922. toplevel.LayoutSubviews ();
  923. toplevel.PositionToplevels ();
  924. toplevel.WillPresent ();
  925. EnsuresTopOnFront ();
  926. if (refreshDriver) {
  927. MdiTop?.OnChildLoaded (toplevel);
  928. toplevel.OnLoaded ();
  929. Refresh ();
  930. }
  931. NotifyNewRunState?.Invoke (rs);
  932. return rs;
  933. }
  934. /// <summary>
  935. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  936. /// </summary>
  937. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  938. public static void End (RunState runState)
  939. {
  940. if (runState == null)
  941. throw new ArgumentNullException (nameof (runState));
  942. if (MdiTop != null) {
  943. MdiTop.OnChildUnloaded (runState.Toplevel);
  944. } else {
  945. runState.Toplevel.OnUnloaded ();
  946. }
  947. // End the RunState.Toplevel
  948. // First, take it off the toplevel Stack
  949. if (toplevels.Count > 0) {
  950. if (toplevels.Peek () != runState.Toplevel) {
  951. // If there the top of the stack is not the RunState.Toplevel then
  952. // this call to End is not balanced with the call to Begin that started the RunState
  953. throw new ArgumentException ("End must be balanced with calls to Begin");
  954. }
  955. toplevels.Pop ();
  956. }
  957. // Notify that it is closing
  958. runState.Toplevel?.OnClosed (runState.Toplevel);
  959. // If there is a MdiTop that is not the RunState.Toplevel then runstate.TopLevel
  960. // is a child of MidTop and we should notify the MdiTop that it is closing
  961. if (MdiTop != null && !(runState.Toplevel).Modal && runState.Toplevel != MdiTop) {
  962. MdiTop.OnChildClosed (runState.Toplevel);
  963. }
  964. // Set Current and Top to the next TopLevel on the stack
  965. if (toplevels.Count == 0) {
  966. Current = null;
  967. Top = null;
  968. } else {
  969. Current = toplevels.Peek ();
  970. if (toplevels.Count == 1 && Current == MdiTop) {
  971. MdiTop.OnAllChildClosed ();
  972. } else {
  973. SetCurrentAsTop ();
  974. runState.Toplevel.OnLeave (Current);
  975. Current.OnEnter (runState.Toplevel);
  976. }
  977. Refresh ();
  978. }
  979. runState.Dispose ();
  980. }
  981. /// <summary>
  982. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  983. /// </summary>
  984. /// <remarks>
  985. /// Shutdown must be called for every call to <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> or <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  986. /// to ensure all resources are cleaned up (Disposed) and terminal settings are restored.
  987. /// </remarks>
  988. public static void Shutdown ()
  989. {
  990. ResetState ();
  991. }
  992. // Encapsulate all setting of initial state for Application; Having
  993. // this in a function like this ensures we don't make mistakes in
  994. // guaranteeing that the state of this singleton is deterministic when Init
  995. // starts running and after Shutdown returns.
  996. static void ResetState ()
  997. {
  998. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  999. // Init created. Apps that do any threading will need to code defensively for this.
  1000. // e.g. see Issue #537
  1001. foreach (var t in toplevels) {
  1002. t.Running = false;
  1003. t.Dispose ();
  1004. }
  1005. toplevels.Clear ();
  1006. Current = null;
  1007. Top?.Dispose ();
  1008. Top = null;
  1009. // BUGBUG: MdiTop is not cleared here, but it should be?
  1010. Driver?.End ();
  1011. Driver = null;
  1012. MainLoop = null;
  1013. Iteration = null;
  1014. RootMouseEvent = null;
  1015. RootKeyEvent = null;
  1016. Resized = null;
  1017. _mainThreadId = -1;
  1018. NotifyNewRunState = null;
  1019. NotifyStopRunState = null;
  1020. _initialized = false;
  1021. mouseGrabView = null;
  1022. // Reset synchronization context to allow the user to run async/await,
  1023. // as the main loop has been ended, the synchronization context from
  1024. // gui.cs does no longer process any callbacks. See #1084 for more details:
  1025. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  1026. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  1027. }
  1028. static void Redraw (View view)
  1029. {
  1030. view.Redraw (view.Bounds);
  1031. Driver.Refresh ();
  1032. }
  1033. /// <summary>
  1034. /// Triggers a refresh of the entire display.
  1035. /// </summary>
  1036. public static void Refresh ()
  1037. {
  1038. Driver.UpdateOffScreen ();
  1039. View last = null;
  1040. foreach (var v in toplevels.Reverse ()) {
  1041. if (v.Visible) {
  1042. v.SetNeedsDisplay ();
  1043. v.Redraw (v.Bounds);
  1044. }
  1045. last = v;
  1046. }
  1047. last?.PositionCursor ();
  1048. Driver.Refresh ();
  1049. }
  1050. /// <summary>
  1051. /// Building block API: Runs the <see cref="MainLoop"/> for the created <see cref="Toplevel"/>.
  1052. /// </summary>
  1053. /// <remarks>
  1054. /// Use the <paramref name="wait"/> parameter to control whether this is a blocking or non-blocking call.
  1055. /// </remarks>
  1056. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1057. /// <param name="wait">By default this is <see langword="true"/> which will execute the runloop waiting for events,
  1058. /// if set to <see langword="false"/>, a single iteration will execute.</param>
  1059. public static void RunLoop (RunState state, bool wait = true)
  1060. {
  1061. if (state == null)
  1062. throw new ArgumentNullException (nameof (state));
  1063. if (state.Toplevel == null)
  1064. throw new ObjectDisposedException ("state");
  1065. bool firstIteration = true;
  1066. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1067. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  1068. return;
  1069. }
  1070. RunMainLoopIteration (ref state, wait, ref firstIteration);
  1071. }
  1072. }
  1073. /// <summary>
  1074. /// Run one iteration of the <see cref="MainLoop"/>.
  1075. /// </summary>
  1076. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  1077. /// <param name="wait">If <see langword="true"/> will execute the runloop waiting for events. If <see langword="true"/>
  1078. /// will return after a single iteration.</param>
  1079. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  1080. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  1081. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  1082. {
  1083. if (MainLoop.EventsPending (wait)) {
  1084. // Notify Toplevel it's ready
  1085. if (firstIteration) {
  1086. state.Toplevel.OnReady ();
  1087. }
  1088. MainLoop.MainIteration ();
  1089. Iteration?.Invoke ();
  1090. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  1091. if (!EnsuresNotModalNotRunningAndNotCurrent (state.Toplevel)) {
  1092. EnsuresMdiChildOnFrontIfMdiTopNotMostFocused ();
  1093. }
  1094. if ((state.Toplevel != Current && Current?.Modal == true)
  1095. || (state.Toplevel != Current && Current?.Modal == false)) {
  1096. MdiTop?.OnDeactivate (state.Toplevel);
  1097. state.Toplevel = Current;
  1098. MdiTop?.OnActivate (state.Toplevel);
  1099. Top.SetChildNeedsDisplay ();
  1100. Refresh ();
  1101. }
  1102. if (Driver.EnsureCursorVisibility ()) {
  1103. state.Toplevel.SetNeedsDisplay ();
  1104. }
  1105. } else if (!wait) {
  1106. return;
  1107. }
  1108. firstIteration = false;
  1109. if (state.Toplevel != Top
  1110. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  1111. Top.Redraw (Top.Bounds);
  1112. foreach (var top in toplevels.Reverse ()) {
  1113. if (top != Top && top != state.Toplevel) {
  1114. top.SetNeedsDisplay ();
  1115. top.Redraw (top.Bounds);
  1116. }
  1117. }
  1118. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  1119. }
  1120. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.ChildNeedsDisplay || state.Toplevel.LayoutNeeded
  1121. || MdiChildNeedsDisplay ()) {
  1122. bool isTopNeedsDisplay;
  1123. do {
  1124. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1125. if (DebugDrawBounds) {
  1126. DrawBounds (state.Toplevel);
  1127. }
  1128. state.Toplevel.PositionCursor ();
  1129. Driver.Refresh ();
  1130. isTopNeedsDisplay = IsTopNeedsDisplay (state.Toplevel);
  1131. if (isTopNeedsDisplay) {
  1132. Top.Redraw (Top.Bounds);
  1133. state.Toplevel.SetNeedsDisplay ();
  1134. }
  1135. } while (isTopNeedsDisplay);
  1136. } else {
  1137. Driver.UpdateCursor ();
  1138. }
  1139. bool IsTopNeedsDisplay (Toplevel toplevel)
  1140. {
  1141. if (toplevel != Top && !toplevel.Modal
  1142. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  1143. return true;
  1144. }
  1145. return false;
  1146. }
  1147. }
  1148. static void EnsuresMdiChildOnFrontIfMdiTopNotMostFocused ()
  1149. {
  1150. if (MdiTop != null && Current == MdiTop && (MdiTop.MostFocused == null
  1151. || MdiTop.MostFocused.GetType ().Name == "ContentView")) {
  1152. MoveNext ();
  1153. }
  1154. }
  1155. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel toplevel)
  1156. {
  1157. if (!toplevel.Running || (toplevel == Current && toplevel.Visible) || MdiTop == null || toplevels.Peek ().Modal) {
  1158. return;
  1159. }
  1160. foreach (var top in toplevels.Reverse ()) {
  1161. if (top.Modal && top != Current) {
  1162. MoveCurrent (top);
  1163. return;
  1164. }
  1165. }
  1166. if (!toplevel.Visible && toplevel == Current) {
  1167. MoveNext ();
  1168. }
  1169. }
  1170. static bool EnsuresNotModalNotRunningAndNotCurrent (Toplevel curRunStateTop)
  1171. {
  1172. if (MdiTop == null || !curRunStateTop.Running) {
  1173. return false;
  1174. }
  1175. foreach (var top in toplevels) {
  1176. if (!top.IsMdiContainer && top?.Running == false && top != Current && top?.Modal == false) {
  1177. MoveCurrent (top);
  1178. return true;
  1179. }
  1180. }
  1181. return false;
  1182. }
  1183. static bool MdiChildNeedsDisplay ()
  1184. {
  1185. if (MdiTop == null) {
  1186. return false;
  1187. }
  1188. foreach (var top in toplevels) {
  1189. if (top != Current && top.Visible && (!top.NeedDisplay.IsEmpty || top.ChildNeedsDisplay || top.LayoutNeeded)) {
  1190. MdiTop.SetChildNeedsDisplay ();
  1191. return true;
  1192. }
  1193. }
  1194. return false;
  1195. }
  1196. internal static bool DebugDrawBounds = false;
  1197. // Need to look into why this does not work properly.
  1198. static void DrawBounds (View v)
  1199. {
  1200. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1201. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1202. foreach (var sub in v.InternalSubviews)
  1203. DrawBounds (sub);
  1204. }
  1205. /// <summary>
  1206. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>.
  1207. /// </summary>
  1208. /// <remarks>
  1209. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1210. /// </remarks>
  1211. public static void Run (Func<Exception, bool> errorHandler = null)
  1212. {
  1213. Run (Top, errorHandler);
  1214. }
  1215. /// <summary>
  1216. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  1217. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  1218. /// <para>
  1219. /// Calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> first is not needed as this function will initialze the application.
  1220. /// </para>
  1221. /// <para>
  1222. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has
  1223. /// returned) to ensure resources are cleaned up and terminal settings restored.
  1224. /// </para>
  1225. /// </summary>
  1226. /// <remarks>
  1227. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1228. /// </remarks>
  1229. /// <param name="errorHandler"></param>
  1230. /// <param name="driver">The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  1231. /// platform will be used (<see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>).
  1232. /// This parameteter must be <see langword="null"/> if <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has already been called.
  1233. /// </param>
  1234. /// <param name="mainLoopDriver">Specifies the <see cref="MainLoop"/> to use.</param>
  1235. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) where T : Toplevel, new()
  1236. {
  1237. if (_initialized) {
  1238. if (Driver != null) {
  1239. // Init() has been called and we have a driver, so just run the app.
  1240. var top = new T ();
  1241. var type = top.GetType ().BaseType;
  1242. while (type != typeof (Toplevel) && type != typeof (object)) {
  1243. type = type.BaseType;
  1244. }
  1245. if (type != typeof (Toplevel)) {
  1246. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  1247. }
  1248. Run (top, errorHandler);
  1249. } else {
  1250. // This codepath should be impossible because Init(null, null) will select the platform default driver
  1251. throw new InvalidOperationException ("Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called.");
  1252. }
  1253. } else {
  1254. // Init() has NOT been called.
  1255. InternalInit (() => new T (), driver, mainLoopDriver, calledViaRunT: true);
  1256. Run (Top, errorHandler);
  1257. }
  1258. }
  1259. /// <summary>
  1260. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  1261. /// </summary>
  1262. /// <remarks>
  1263. /// <para>
  1264. /// This method is used to start processing events
  1265. /// for the main application, but it is also used to
  1266. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  1267. /// </para>
  1268. /// <para>
  1269. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  1270. /// </para>
  1271. /// <para>
  1272. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  1273. /// and then calling <see cref="End(RunState)"/>.
  1274. /// </para>
  1275. /// <para>
  1276. /// Alternatively, to have a program control the main loop and
  1277. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  1278. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  1279. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  1280. /// then return control immediately.
  1281. /// </para>
  1282. /// <para>
  1283. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exeptions will be rethrown.
  1284. /// Otheriwse, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  1285. /// returns <see langword="true"/> the <see cref="RunLoop(RunState, bool)"/> will resume; otherwise
  1286. /// this method will exit.
  1287. /// </para>
  1288. /// </remarks>
  1289. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  1290. /// <param name="errorHandler">RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  1291. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  1292. {
  1293. var resume = true;
  1294. while (resume) {
  1295. #if !DEBUG
  1296. try {
  1297. #endif
  1298. resume = false;
  1299. var runToken = Begin (view);
  1300. // If ExitRunLoopAfterFirstIteration is true then the user must dispose of the runToken
  1301. // by using NotifyStopRunState event.
  1302. RunLoop (runToken);
  1303. if (!ExitRunLoopAfterFirstIteration) {
  1304. End (runToken);
  1305. }
  1306. #if !DEBUG
  1307. }
  1308. catch (Exception error)
  1309. {
  1310. if (errorHandler == null)
  1311. {
  1312. throw;
  1313. }
  1314. resume = errorHandler(error);
  1315. }
  1316. #endif
  1317. }
  1318. }
  1319. /// <summary>
  1320. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  1321. /// </summary>
  1322. /// <param name="top">The toplevel to request stop.</param>
  1323. /// <remarks>
  1324. /// <para>
  1325. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  1326. /// </para>
  1327. /// <para>
  1328. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the currently running <see cref="Toplevel"/> to false.
  1329. /// </para>
  1330. /// </remarks>
  1331. public static void RequestStop (Toplevel top = null)
  1332. {
  1333. if (MdiTop == null || top == null || (MdiTop == null && top != null)) {
  1334. top = Current;
  1335. }
  1336. if (MdiTop != null && top.IsMdiContainer && top?.Running == true
  1337. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  1338. MdiTop.RequestStop ();
  1339. } else if (MdiTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  1340. && top.Modal && top.Running) {
  1341. var ev = new ToplevelClosingEventArgs (Current);
  1342. Current.OnClosing (ev);
  1343. if (ev.Cancel) {
  1344. return;
  1345. }
  1346. ev = new ToplevelClosingEventArgs (top);
  1347. top.OnClosing (ev);
  1348. if (ev.Cancel) {
  1349. return;
  1350. }
  1351. Current.Running = false;
  1352. OnNotifyStopRunState (Current);
  1353. top.Running = false;
  1354. OnNotifyStopRunState (top);
  1355. } else if ((MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1356. && Current?.Running == true && !top.Running)
  1357. || (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1358. && Current?.Running == false && !top.Running && toplevels.ToArray () [1].Running)) {
  1359. MoveCurrent (top);
  1360. } else if (MdiTop != null && Current != top && Current?.Running == true && !top.Running
  1361. && Current?.Modal == true && top.Modal) {
  1362. // The Current and the top are both modal so needed to set the Current.Running to false too.
  1363. Current.Running = false;
  1364. OnNotifyStopRunState (Current);
  1365. } else if (MdiTop != null && Current == top && MdiTop?.Running == true && Current?.Running == true && top.Running
  1366. && Current?.Modal == true && top.Modal) {
  1367. // The MdiTop was requested to stop inside a modal toplevel which is the Current and top,
  1368. // both are the same, so needed to set the Current.Running to false too.
  1369. Current.Running = false;
  1370. OnNotifyStopRunState (Current);
  1371. } else {
  1372. Toplevel currentTop;
  1373. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  1374. currentTop = Current;
  1375. } else {
  1376. currentTop = top;
  1377. }
  1378. if (!currentTop.Running) {
  1379. return;
  1380. }
  1381. var ev = new ToplevelClosingEventArgs (currentTop);
  1382. currentTop.OnClosing (ev);
  1383. if (ev.Cancel) {
  1384. return;
  1385. }
  1386. currentTop.Running = false;
  1387. OnNotifyStopRunState (currentTop);
  1388. }
  1389. }
  1390. static void OnNotifyStopRunState (Toplevel top)
  1391. {
  1392. if (ExitRunLoopAfterFirstIteration) {
  1393. NotifyStopRunState?.Invoke (top);
  1394. }
  1395. }
  1396. /// <summary>
  1397. /// Event arguments for the <see cref="Application.Resized"/> event.
  1398. /// </summary>
  1399. public class ResizedEventArgs : EventArgs {
  1400. /// <summary>
  1401. /// The number of rows in the resized terminal.
  1402. /// </summary>
  1403. public int Rows { get; set; }
  1404. /// <summary>
  1405. /// The number of columns in the resized terminal.
  1406. /// </summary>
  1407. public int Cols { get; set; }
  1408. }
  1409. /// <summary>
  1410. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  1411. /// </summary>
  1412. public static Action<ResizedEventArgs> Resized;
  1413. static void TerminalResized ()
  1414. {
  1415. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1416. SetToplevelsSize (full);
  1417. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  1418. Driver.Clip = full;
  1419. foreach (var t in toplevels) {
  1420. t.SetRelativeLayout (full);
  1421. t.LayoutSubviews ();
  1422. t.PositionToplevels ();
  1423. t.OnResized (full.Size);
  1424. }
  1425. Refresh ();
  1426. }
  1427. static void SetToplevelsSize (Rect full)
  1428. {
  1429. if (MdiTop == null) {
  1430. foreach (var t in toplevels) {
  1431. if (t?.SuperView == null && !t.Modal) {
  1432. t.Frame = full;
  1433. t.Width = full.Width;
  1434. t.Height = full.Height;
  1435. }
  1436. }
  1437. } else {
  1438. Top.Frame = full;
  1439. Top.Width = full.Width;
  1440. Top.Height = full.Height;
  1441. }
  1442. }
  1443. static bool SetCurrentAsTop ()
  1444. {
  1445. if (MdiTop == null && Current != Top && Current?.SuperView == null && Current?.Modal == false) {
  1446. if (Current.Frame != new Rect (0, 0, Driver.Cols, Driver.Rows)) {
  1447. Current.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1448. }
  1449. Top = Current;
  1450. return true;
  1451. }
  1452. return false;
  1453. }
  1454. /// <summary>
  1455. /// Move to the next Mdi child from the <see cref="MdiTop"/>.
  1456. /// </summary>
  1457. public static void MoveNext ()
  1458. {
  1459. if (MdiTop != null && !Current.Modal) {
  1460. lock (toplevels) {
  1461. toplevels.MoveNext ();
  1462. var isMdi = false;
  1463. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1464. if (!isMdi && toplevels.Peek () == MdiTop) {
  1465. isMdi = true;
  1466. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1467. MoveCurrent (Top);
  1468. break;
  1469. }
  1470. toplevels.MoveNext ();
  1471. }
  1472. Current = toplevels.Peek ();
  1473. }
  1474. }
  1475. }
  1476. /// <summary>
  1477. /// Move to the previous Mdi child from the <see cref="MdiTop"/>.
  1478. /// </summary>
  1479. public static void MovePrevious ()
  1480. {
  1481. if (MdiTop != null && !Current.Modal) {
  1482. lock (toplevels) {
  1483. toplevels.MovePrevious ();
  1484. var isMdi = false;
  1485. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1486. if (!isMdi && toplevels.Peek () == MdiTop) {
  1487. isMdi = true;
  1488. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1489. MoveCurrent (Top);
  1490. break;
  1491. }
  1492. toplevels.MovePrevious ();
  1493. }
  1494. Current = toplevels.Peek ();
  1495. }
  1496. }
  1497. }
  1498. internal static bool ShowChild (Toplevel top)
  1499. {
  1500. if (Current == top) {
  1501. return false;
  1502. }
  1503. if (top.Visible && MdiTop != null && Current?.Modal == false) {
  1504. lock (toplevels) {
  1505. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1506. Current = top;
  1507. }
  1508. return true;
  1509. }
  1510. return false;
  1511. }
  1512. /// <summary>
  1513. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  1514. /// </summary>
  1515. public static void DoEvents ()
  1516. {
  1517. MainLoop.Driver.Wakeup ();
  1518. }
  1519. /// <summary>
  1520. /// Ensures that the superview of the most focused view is on front.
  1521. /// </summary>
  1522. public static void EnsuresTopOnFront ()
  1523. {
  1524. if (MdiTop != null) {
  1525. return;
  1526. }
  1527. var top = FindTopFromView (Top?.MostFocused);
  1528. if (top != null && Top.Subviews.Count > 1 && Top.Subviews [Top.Subviews.Count - 1] != top) {
  1529. Top.BringSubviewToFront (top);
  1530. }
  1531. }
  1532. internal static List<CultureInfo> GetSupportedCultures ()
  1533. {
  1534. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  1535. // Get the assembly
  1536. Assembly assembly = Assembly.GetExecutingAssembly ();
  1537. //Find the location of the assembly
  1538. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  1539. // Find the resource file name of the assembly
  1540. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  1541. // Return all culture for which satellite folder found with culture code.
  1542. return culture.Where (cultureInfo =>
  1543. assemblyLocation != null &&
  1544. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  1545. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  1546. ).ToList ();
  1547. }
  1548. }
  1549. }