2
0

Application.cs 40 KB

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