Application.cs 52 KB

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