Application.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  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 (me.Handled) {
  597. return;
  598. }
  599. if (mouseGrabView != null) {
  600. if (view == null) {
  601. UngrabMouse ();
  602. return;
  603. }
  604. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  605. var nme = new MouseEvent () {
  606. X = newxy.X,
  607. Y = newxy.Y,
  608. Flags = me.Flags,
  609. OfX = me.X - newxy.X,
  610. OfY = me.Y - newxy.Y,
  611. View = view
  612. };
  613. if (OutsideFrame (new Point (nme.X, nme.Y), mouseGrabView.Frame)) {
  614. lastMouseOwnerView?.OnMouseLeave (me);
  615. }
  616. // System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  617. if (mouseGrabView?.OnMouseEvent (nme) == true) {
  618. return;
  619. }
  620. }
  621. if ((view == null || view == MdiTop) && !Current.Modal && MdiTop != null
  622. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  623. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  624. view = FindDeepestView (top, me.X, me.Y, out rx, out ry);
  625. if (view != null && view != MdiTop && top != Current) {
  626. MoveCurrent ((Toplevel)top);
  627. }
  628. }
  629. if (view != null) {
  630. var nme = new MouseEvent () {
  631. X = rx,
  632. Y = ry,
  633. Flags = me.Flags,
  634. OfX = 0,
  635. OfY = 0,
  636. View = view
  637. };
  638. if (lastMouseOwnerView == null) {
  639. lastMouseOwnerView = view;
  640. view.OnMouseEnter (nme);
  641. } else if (lastMouseOwnerView != view) {
  642. lastMouseOwnerView.OnMouseLeave (nme);
  643. view.OnMouseEnter (nme);
  644. lastMouseOwnerView = view;
  645. }
  646. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  647. return;
  648. if (view.WantContinuousButtonPressed)
  649. WantContinuousButtonPressedView = view;
  650. else
  651. WantContinuousButtonPressedView = null;
  652. // Should we bubbled up the event, if it is not handled?
  653. view.OnMouseEvent (nme);
  654. EnsuresTopOnFront ();
  655. }
  656. }
  657. // Only return true if the Current has changed.
  658. static bool MoveCurrent (Toplevel top)
  659. {
  660. // The Current is modal and the top is not modal toplevel then
  661. // the Current must be moved above the first not modal toplevel.
  662. if (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == true && !toplevels.Peek ().Modal) {
  663. lock (toplevels) {
  664. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  665. }
  666. var index = 0;
  667. var savedToplevels = toplevels.ToArray ();
  668. foreach (var t in savedToplevels) {
  669. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  670. lock (toplevels) {
  671. toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  672. }
  673. }
  674. index++;
  675. }
  676. return false;
  677. }
  678. // The Current and the top are both not running toplevel then
  679. // the top must be moved above the first not running toplevel.
  680. if (MdiTop != null && top != MdiTop && top != Current && Current?.Running == false && !top.Running) {
  681. lock (toplevels) {
  682. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  683. }
  684. var index = 0;
  685. foreach (var t in toplevels.ToArray ()) {
  686. if (!t.Running && t != Current && index > 0) {
  687. lock (toplevels) {
  688. toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  689. }
  690. }
  691. index++;
  692. }
  693. return false;
  694. }
  695. if ((MdiTop != null && top?.Modal == true && toplevels.Peek () != top)
  696. || (MdiTop != null && Current != MdiTop && Current?.Modal == false && top == MdiTop)
  697. || (MdiTop != null && Current?.Modal == false && top != Current)
  698. || (MdiTop != null && Current?.Modal == true && top == MdiTop)) {
  699. lock (toplevels) {
  700. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  701. Current = top;
  702. }
  703. }
  704. return true;
  705. }
  706. static bool OutsideFrame (Point p, Rect r)
  707. {
  708. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  709. }
  710. /// <summary>
  711. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  712. /// </summary>
  713. /// <returns>The runstate handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  714. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  715. /// <remarks>
  716. /// This method prepares the provided toplevel for running with the focus,
  717. /// it adds this to the list of toplevels, sets up the mainloop to process the
  718. /// event, lays out the subviews, focuses the first element, and draws the
  719. /// toplevel in the screen. This is usually followed by executing
  720. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  721. /// undo these changes.
  722. /// </remarks>
  723. public static RunState Begin (Toplevel toplevel)
  724. {
  725. if (toplevel == null) {
  726. throw new ArgumentNullException (nameof (toplevel));
  727. } else if (toplevel.IsMdiContainer && MdiTop != toplevel && MdiTop != null) {
  728. throw new InvalidOperationException ("Only one Mdi Container is allowed.");
  729. }
  730. var rs = new RunState (toplevel);
  731. Init ();
  732. if (toplevel is ISupportInitializeNotification initializableNotification &&
  733. !initializableNotification.IsInitialized) {
  734. initializableNotification.BeginInit ();
  735. initializableNotification.EndInit ();
  736. } else if (toplevel is ISupportInitialize initializable) {
  737. initializable.BeginInit ();
  738. initializable.EndInit ();
  739. }
  740. lock (toplevels) {
  741. if (string.IsNullOrEmpty (toplevel.Id.ToString ())) {
  742. var count = 1;
  743. var id = (toplevels.Count + count).ToString ();
  744. while (toplevels.Count > 0 && toplevels.FirstOrDefault (x => x.Id.ToString () == id) != null) {
  745. count++;
  746. id = (toplevels.Count + count).ToString ();
  747. }
  748. toplevel.Id = (toplevels.Count + count).ToString ();
  749. toplevels.Push (toplevel);
  750. } else {
  751. var dup = toplevels.FirstOrDefault (x => x.Id.ToString () == toplevel.Id);
  752. if (dup == null) {
  753. toplevels.Push (toplevel);
  754. }
  755. }
  756. if (toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  757. throw new ArgumentException ("There are duplicates toplevels Id's");
  758. }
  759. }
  760. if (toplevel.IsMdiContainer) {
  761. Top = toplevel;
  762. }
  763. var refreshDriver = true;
  764. if (MdiTop == null || toplevel.IsMdiContainer || (Current?.Modal == false && toplevel.Modal)
  765. || (Current?.Modal == false && !toplevel.Modal) || (Current?.Modal == true && toplevel.Modal)) {
  766. if (toplevel.Visible) {
  767. Current = toplevel;
  768. SetCurrentAsTop ();
  769. } else {
  770. refreshDriver = false;
  771. }
  772. } else if ((MdiTop != null && toplevel != MdiTop && Current?.Modal == true && !toplevels.Peek ().Modal)
  773. || (MdiTop != null && toplevel != MdiTop && Current?.Running == false)) {
  774. refreshDriver = false;
  775. MoveCurrent (toplevel);
  776. } else {
  777. refreshDriver = false;
  778. MoveCurrent (Current);
  779. }
  780. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  781. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  782. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  783. toplevel.LayoutSubviews ();
  784. toplevel.PositionToplevels ();
  785. toplevel.WillPresent ();
  786. if (refreshDriver) {
  787. if (MdiTop != null) {
  788. MdiTop.OnChildLoaded (toplevel);
  789. }
  790. toplevel.OnLoaded ();
  791. Redraw (toplevel);
  792. toplevel.PositionCursor ();
  793. Driver.Refresh ();
  794. }
  795. return rs;
  796. }
  797. /// <summary>
  798. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  799. /// </summary>
  800. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  801. public static void End (RunState runState)
  802. {
  803. if (runState == null)
  804. throw new ArgumentNullException (nameof (runState));
  805. if (MdiTop != null) {
  806. MdiTop.OnChildUnloaded (runState.Toplevel);
  807. } else {
  808. runState.Toplevel.OnUnloaded ();
  809. }
  810. runState.Dispose ();
  811. }
  812. /// <summary>
  813. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>
  814. /// </summary>
  815. public static void Shutdown ()
  816. {
  817. ResetState ();
  818. }
  819. // Encapsulate all setting of initial state for Application; Having
  820. // this in a function like this ensures we don't make mistakes in
  821. // guaranteeing that the state of this singleton is deterministic when Init
  822. // starts running and after Shutdown returns.
  823. static void ResetState ()
  824. {
  825. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  826. // Init created. Apps that do any threading will need to code defensively for this.
  827. // e.g. see Issue #537
  828. // TODO: Some of this state is actually related to Begin/End (not Init/Shutdown) and should be moved to `RunState` (#520)
  829. foreach (var t in toplevels) {
  830. t.Running = false;
  831. t.Dispose ();
  832. }
  833. toplevels.Clear ();
  834. Current = null;
  835. Top = null;
  836. MainLoop = null;
  837. Driver?.End ();
  838. Driver = null;
  839. Iteration = null;
  840. RootMouseEvent = null;
  841. RootKeyEvent = null;
  842. Resized = null;
  843. _mainThreadId = -1;
  844. NotifyNewRunState = null;
  845. NotifyStopRunState = null;
  846. _initialized = false;
  847. mouseGrabView = null;
  848. // Reset synchronization context to allow the user to run async/await,
  849. // as the main loop has been ended, the synchronization context from
  850. // gui.cs does no longer process any callbacks. See #1084 for more details:
  851. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  852. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  853. }
  854. static void Redraw (View view)
  855. {
  856. view.Redraw (view.Bounds);
  857. Driver.Refresh ();
  858. }
  859. static void Refresh (View view)
  860. {
  861. view.Redraw (view.Bounds);
  862. Driver.Refresh ();
  863. }
  864. /// <summary>
  865. /// Triggers a refresh of the entire display.
  866. /// </summary>
  867. public static void Refresh ()
  868. {
  869. Driver.UpdateOffScreen ();
  870. View last = null;
  871. foreach (var v in toplevels.Reverse ()) {
  872. if (v.Visible) {
  873. v.SetNeedsDisplay ();
  874. v.Redraw (v.Bounds);
  875. }
  876. last = v;
  877. }
  878. last?.PositionCursor ();
  879. Driver.Refresh ();
  880. }
  881. internal static void End (View view)
  882. {
  883. if (toplevels.Peek () != view)
  884. throw new ArgumentException ("The view that you end with must be balanced");
  885. toplevels.Pop ();
  886. (view as Toplevel)?.OnClosed ((Toplevel)view);
  887. if (MdiTop != null && !((Toplevel)view).Modal && view != MdiTop) {
  888. MdiTop.OnChildClosed (view as Toplevel);
  889. }
  890. if (toplevels.Count == 0) {
  891. Current = null;
  892. } else {
  893. Current = toplevels.Peek ();
  894. if (toplevels.Count == 1 && Current == MdiTop) {
  895. MdiTop.OnAllChildClosed ();
  896. } else {
  897. SetCurrentAsTop ();
  898. }
  899. Refresh ();
  900. }
  901. }
  902. /// <summary>
  903. /// Building block API: Runs the main loop for the created dialog
  904. /// </summary>
  905. /// <remarks>
  906. /// Use the wait parameter to control whether this is a
  907. /// blocking or non-blocking call.
  908. /// </remarks>
  909. /// <param name="state">The state returned by the Begin method.</param>
  910. /// <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>
  911. public static void RunLoop (RunState state, bool wait = true)
  912. {
  913. if (state == null)
  914. throw new ArgumentNullException (nameof (state));
  915. if (state.Toplevel == null)
  916. throw new ObjectDisposedException ("state");
  917. bool firstIteration = true;
  918. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  919. if (ExitRunLoopAfterFirstIteration && !firstIteration)
  920. return;
  921. RunMainLoopIteration (ref state, wait, ref firstIteration);
  922. }
  923. }
  924. /// <summary>
  925. /// Run one iteration of the MainLoop.
  926. /// </summary>
  927. /// <param name="state">The state returned by the Begin method.</param>
  928. /// <param name="wait">If will execute the runloop waiting for events.</param>
  929. /// <param name="firstIteration">If it's the first run loop iteration.</param>
  930. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  931. {
  932. if (MainLoop.EventsPending (wait)) {
  933. // Notify Toplevel it's ready
  934. if (firstIteration) {
  935. state.Toplevel.OnReady ();
  936. }
  937. MainLoop.MainIteration ();
  938. Iteration?.Invoke ();
  939. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  940. if ((state.Toplevel != Current && Current?.Modal == true)
  941. || (state.Toplevel != Current && Current?.Modal == false)) {
  942. MdiTop?.OnDeactivate (state.Toplevel);
  943. state.Toplevel = Current;
  944. MdiTop?.OnActivate (state.Toplevel);
  945. Top.SetChildNeedsDisplay ();
  946. Refresh ();
  947. }
  948. if (Driver.EnsureCursorVisibility ()) {
  949. state.Toplevel.SetNeedsDisplay ();
  950. }
  951. } else if (!wait) {
  952. return;
  953. }
  954. firstIteration = false;
  955. if (state.Toplevel != Top
  956. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  957. Top.Redraw (Top.Bounds);
  958. foreach (var top in toplevels.Reverse ()) {
  959. if (top != Top && top != state.Toplevel) {
  960. top.SetNeedsDisplay ();
  961. top.Redraw (top.Bounds);
  962. }
  963. }
  964. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  965. }
  966. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.ChildNeedsDisplay || state.Toplevel.LayoutNeeded
  967. || MdiChildNeedsDisplay ()) {
  968. state.Toplevel.Redraw (state.Toplevel.Bounds);
  969. if (DebugDrawBounds) {
  970. DrawBounds (state.Toplevel);
  971. }
  972. state.Toplevel.PositionCursor ();
  973. Driver.Refresh ();
  974. } else {
  975. Driver.UpdateCursor ();
  976. }
  977. if (state.Toplevel != Top && !state.Toplevel.Modal
  978. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  979. Top.Redraw (Top.Bounds);
  980. }
  981. }
  982. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel toplevel)
  983. {
  984. if (!toplevel.Running || (toplevel == Current && toplevel.Visible) || MdiTop == null || toplevels.Peek ().Modal) {
  985. return;
  986. }
  987. foreach (var top in toplevels.Reverse ()) {
  988. if (top.Modal && top != Current) {
  989. MoveCurrent (top);
  990. return;
  991. }
  992. }
  993. if (!toplevel.Visible && toplevel == Current) {
  994. MoveNext ();
  995. }
  996. }
  997. static bool MdiChildNeedsDisplay ()
  998. {
  999. if (MdiTop == null) {
  1000. return false;
  1001. }
  1002. foreach (var top in toplevels) {
  1003. if (top != Current && top.Visible && (!top.NeedDisplay.IsEmpty || top.ChildNeedsDisplay || top.LayoutNeeded)) {
  1004. MdiTop.SetChildNeedsDisplay ();
  1005. return true;
  1006. }
  1007. }
  1008. return false;
  1009. }
  1010. internal static bool DebugDrawBounds = false;
  1011. // Need to look into why this does not work properly.
  1012. static void DrawBounds (View v)
  1013. {
  1014. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1015. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1016. foreach (var sub in v.InternalSubviews)
  1017. DrawBounds (sub);
  1018. }
  1019. /// <summary>
  1020. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>
  1021. /// </summary>
  1022. public static void Run (Func<Exception, bool> errorHandler = null)
  1023. {
  1024. Run (Top, errorHandler);
  1025. }
  1026. /// <summary>
  1027. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  1028. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  1029. /// <para>
  1030. /// If <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has not arleady been called, this function will
  1031. /// call <see cref="Init(Func{Toplevel}, ConsoleDriver, IMainLoopDriver)"/>.
  1032. /// </para>
  1033. /// </summary>
  1034. public static void Run<T> (Func<Exception, bool> errorHandler = null) where T : Toplevel, new()
  1035. {
  1036. if (_initialized && Driver != null) {
  1037. var top = new T ();
  1038. var type = top.GetType ().BaseType;
  1039. while (type != typeof (Toplevel) && type != typeof (object)) {
  1040. type = type.BaseType;
  1041. }
  1042. if (type != typeof (Toplevel)) {
  1043. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  1044. }
  1045. Run (top, errorHandler);
  1046. } else {
  1047. Init (() => new T ());
  1048. Run (Top, errorHandler);
  1049. }
  1050. }
  1051. /// <summary>
  1052. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  1053. /// </summary>
  1054. /// <remarks>
  1055. /// <para>
  1056. /// This method is used to start processing events
  1057. /// for the main application, but it is also used to
  1058. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  1059. /// </para>
  1060. /// <para>
  1061. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  1062. /// </para>
  1063. /// <para>
  1064. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  1065. /// and then calling <see cref="End(RunState)"/>.
  1066. /// </para>
  1067. /// <para>
  1068. /// Alternatively, to have a program control the main loop and
  1069. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  1070. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  1071. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  1072. /// then return control immediately.
  1073. /// </para>
  1074. /// <para>
  1075. /// When <paramref name="errorHandler"/> is null the exception is rethrown, when it returns true the application is resumed and when false method exits gracefully.
  1076. /// </para>
  1077. /// </remarks>
  1078. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  1079. /// <param name="errorHandler">Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  1080. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  1081. {
  1082. var resume = true;
  1083. while (resume) {
  1084. #if !DEBUG
  1085. try {
  1086. #endif
  1087. resume = false;
  1088. var runToken = Begin (view);
  1089. RunLoop (runToken);
  1090. if (!ExitRunLoopAfterFirstIteration)
  1091. End (runToken);
  1092. else
  1093. // If ExitRunLoopAfterFirstIteration is true then the user must deal his disposing when it ends
  1094. // by using NotifyStopRunState event.
  1095. NotifyNewRunState?.Invoke (runToken);
  1096. #if !DEBUG
  1097. }
  1098. catch (Exception error)
  1099. {
  1100. if (errorHandler == null)
  1101. {
  1102. throw;
  1103. }
  1104. resume = errorHandler(error);
  1105. }
  1106. #endif
  1107. }
  1108. }
  1109. /// <summary>
  1110. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  1111. /// </summary>
  1112. /// <param name="top">The toplevel to request stop.</param>
  1113. /// <remarks>
  1114. /// <para>
  1115. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  1116. /// </para>
  1117. /// <para>
  1118. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the currently running <see cref="Toplevel"/> to false.
  1119. /// </para>
  1120. /// </remarks>
  1121. public static void RequestStop (Toplevel top = null)
  1122. {
  1123. if (MdiTop == null || top == null || (MdiTop == null && top != null)) {
  1124. top = Current;
  1125. }
  1126. if (MdiTop != null && top.IsMdiContainer && top?.Running == true
  1127. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  1128. MdiTop.RequestStop ();
  1129. } else if (MdiTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  1130. && top.Modal && top.Running) {
  1131. var ev = new ToplevelClosingEventArgs (Current);
  1132. Current.OnClosing (ev);
  1133. if (ev.Cancel) {
  1134. return;
  1135. }
  1136. ev = new ToplevelClosingEventArgs (top);
  1137. top.OnClosing (ev);
  1138. if (ev.Cancel) {
  1139. return;
  1140. }
  1141. Current.Running = false;
  1142. OnNotifyStopRunState (Current);
  1143. top.Running = false;
  1144. OnNotifyStopRunState (top);
  1145. } else if ((MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1146. && Current?.Running == true && !top.Running)
  1147. || (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1148. && Current?.Running == false && !top.Running && toplevels.ToArray () [1].Running)) {
  1149. MoveCurrent (top);
  1150. } else if (MdiTop != null && Current != top && Current?.Running == true && !top.Running
  1151. && Current?.Modal == true && top.Modal) {
  1152. // The Current and the top are both modal so needed to set the Current.Running to false too.
  1153. Current.Running = false;
  1154. OnNotifyStopRunState (Current);
  1155. } else if (MdiTop != null && Current == top && MdiTop?.Running == true && Current?.Running == true && top.Running
  1156. && Current?.Modal == true && top.Modal) {
  1157. // The MdiTop was requested to stop inside a modal toplevel which is the Current and top,
  1158. // both are the same, so needed to set the Current.Running to false too.
  1159. Current.Running = false;
  1160. OnNotifyStopRunState (Current);
  1161. } else {
  1162. Toplevel currentTop;
  1163. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  1164. currentTop = Current;
  1165. } else {
  1166. currentTop = top;
  1167. }
  1168. if (!currentTop.Running) {
  1169. return;
  1170. }
  1171. var ev = new ToplevelClosingEventArgs (currentTop);
  1172. currentTop.OnClosing (ev);
  1173. if (ev.Cancel) {
  1174. return;
  1175. }
  1176. currentTop.Running = false;
  1177. OnNotifyStopRunState (currentTop);
  1178. }
  1179. }
  1180. static void OnNotifyStopRunState (Toplevel top)
  1181. {
  1182. if (ExitRunLoopAfterFirstIteration)
  1183. NotifyStopRunState?.Invoke (top);
  1184. }
  1185. /// <summary>
  1186. /// Event arguments for the <see cref="Application.Resized"/> event.
  1187. /// </summary>
  1188. public class ResizedEventArgs : EventArgs {
  1189. /// <summary>
  1190. /// The number of rows in the resized terminal.
  1191. /// </summary>
  1192. public int Rows { get; set; }
  1193. /// <summary>
  1194. /// The number of columns in the resized terminal.
  1195. /// </summary>
  1196. public int Cols { get; set; }
  1197. }
  1198. /// <summary>
  1199. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  1200. /// </summary>
  1201. public static Action<ResizedEventArgs> Resized;
  1202. static void TerminalResized ()
  1203. {
  1204. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1205. SetToplevelsSize (full);
  1206. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  1207. Driver.Clip = full;
  1208. foreach (var t in toplevels) {
  1209. t.SetRelativeLayout (full);
  1210. t.LayoutSubviews ();
  1211. t.PositionToplevels ();
  1212. t.OnResized (full.Size);
  1213. }
  1214. Refresh ();
  1215. }
  1216. static void SetToplevelsSize (Rect full)
  1217. {
  1218. if (MdiTop == null) {
  1219. foreach (var t in toplevels) {
  1220. if (t?.SuperView == null && !t.Modal) {
  1221. t.Frame = full;
  1222. t.Width = full.Width;
  1223. t.Height = full.Height;
  1224. }
  1225. }
  1226. } else {
  1227. Top.Frame = full;
  1228. Top.Width = full.Width;
  1229. Top.Height = full.Height;
  1230. }
  1231. }
  1232. static bool SetCurrentAsTop ()
  1233. {
  1234. if (MdiTop == null && Current != Top && Current?.SuperView == null && Current?.Modal == false) {
  1235. if (Current.Frame != new Rect (0, 0, Driver.Cols, Driver.Rows)) {
  1236. Current.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1237. }
  1238. Top = Current;
  1239. return true;
  1240. }
  1241. return false;
  1242. }
  1243. /// <summary>
  1244. /// Move to the next Mdi child from the <see cref="MdiTop"/>.
  1245. /// </summary>
  1246. public static void MoveNext ()
  1247. {
  1248. if (MdiTop != null && !Current.Modal) {
  1249. lock (toplevels) {
  1250. toplevels.MoveNext ();
  1251. var isMdi = false;
  1252. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1253. if (!isMdi && toplevels.Peek () == MdiTop) {
  1254. isMdi = true;
  1255. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1256. MoveCurrent (Top);
  1257. break;
  1258. }
  1259. toplevels.MoveNext ();
  1260. }
  1261. Current = toplevels.Peek ();
  1262. }
  1263. }
  1264. }
  1265. /// <summary>
  1266. /// Move to the previous Mdi child from the <see cref="MdiTop"/>.
  1267. /// </summary>
  1268. public static void MovePrevious ()
  1269. {
  1270. if (MdiTop != null && !Current.Modal) {
  1271. lock (toplevels) {
  1272. toplevels.MovePrevious ();
  1273. var isMdi = false;
  1274. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1275. if (!isMdi && toplevels.Peek () == MdiTop) {
  1276. isMdi = true;
  1277. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1278. MoveCurrent (Top);
  1279. break;
  1280. }
  1281. toplevels.MovePrevious ();
  1282. }
  1283. Current = toplevels.Peek ();
  1284. }
  1285. }
  1286. }
  1287. internal static bool ShowChild (Toplevel top)
  1288. {
  1289. if (top.Visible && MdiTop != null && Current?.Modal == false) {
  1290. lock (toplevels) {
  1291. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1292. Current = top;
  1293. }
  1294. return true;
  1295. }
  1296. return false;
  1297. }
  1298. /// <summary>
  1299. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  1300. /// </summary>
  1301. public static void DoEvents ()
  1302. {
  1303. MainLoop.Driver.Wakeup ();
  1304. }
  1305. /// <summary>
  1306. /// Ensures that the superview of the most focused view is on front.
  1307. /// </summary>
  1308. public static void EnsuresTopOnFront ()
  1309. {
  1310. if (MdiTop != null) {
  1311. return;
  1312. }
  1313. var top = FindTopFromView (Top?.MostFocused);
  1314. if (top != null && Top.Subviews.Count > 1 && Top.Subviews [Top.Subviews.Count - 1] != top) {
  1315. Top.BringSubviewToFront (top);
  1316. }
  1317. }
  1318. internal static List<CultureInfo> GetSupportedCultures ()
  1319. {
  1320. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  1321. // Get the assembly
  1322. Assembly assembly = Assembly.GetExecutingAssembly ();
  1323. //Find the location of the assembly
  1324. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  1325. // Find the resource file name of the assembly
  1326. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  1327. // Return all culture for which satellite folder found with culture code.
  1328. return culture.Where (cultureInfo =>
  1329. assemblyLocation != null &&
  1330. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  1331. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  1332. ).ToList ();
  1333. }
  1334. }
  1335. }