Application.cs 40 KB

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