Application.cs 37 KB

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