Application.cs 36 KB

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