Application.cs 39 KB

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