Application.cs 51 KB

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