Application.cs 36 KB

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