Application.cs 42 KB

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