Application.cs 36 KB

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