Application.cs 43 KB

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