Application.cs 37 KB

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