Application.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. // Optimziations
  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, singelton class provding 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. /// <summary>
  57. /// The current <see cref="ConsoleDriver"/> in use.
  58. /// </summary>
  59. public static ConsoleDriver Driver;
  60. /// <summary>
  61. /// The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)
  62. /// </summary>
  63. /// <value>The top.</value>
  64. public static Toplevel Top { get; private set; }
  65. /// <summary>
  66. /// The current <see cref="Toplevel"/> object. This is updated when <see cref="Application.Run()"/> enters and leaves to point to the current <see cref="Toplevel"/> .
  67. /// </summary>
  68. /// <value>The current.</value>
  69. public static Toplevel Current { get; private set; }
  70. /// <summary>
  71. /// TThe current <see cref="View"/> object being redrawn.
  72. /// </summary>
  73. /// /// <value>The current.</value>
  74. public static View CurrentView { get; set; }
  75. /// <summary>
  76. /// The <see cref="MainLoop"/> driver for the applicaiton
  77. /// </summary>
  78. /// <value>The main loop.</value>
  79. public static MainLoop MainLoop { get; private set; }
  80. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  81. /// <summary>
  82. /// This event is raised on each iteration of the <see cref="MainLoop"/>
  83. /// </summary>
  84. /// <remarks>
  85. /// See also <see cref="Timeout"/>
  86. /// </remarks>
  87. public static Action Iteration;
  88. /// <summary>
  89. /// Returns a rectangle that is centered in the screen for the provided size.
  90. /// </summary>
  91. /// <returns>The centered rect.</returns>
  92. /// <param name="size">Size for the rectangle.</param>
  93. public static Rect MakeCenteredRect (Size size)
  94. {
  95. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  96. }
  97. //
  98. // provides the sync context set while executing code in Terminal.Gui, to let
  99. // users use async/await on their code
  100. //
  101. class MainLoopSyncContext : SynchronizationContext {
  102. MainLoop mainLoop;
  103. public MainLoopSyncContext (MainLoop mainLoop)
  104. {
  105. this.mainLoop = mainLoop;
  106. }
  107. public override SynchronizationContext CreateCopy ()
  108. {
  109. return new MainLoopSyncContext (MainLoop);
  110. }
  111. public override void Post (SendOrPostCallback d, object state)
  112. {
  113. mainLoop.AddIdle (() => {
  114. d (state);
  115. return false;
  116. });
  117. //mainLoop.Driver.Wakeup ();
  118. }
  119. public override void Send (SendOrPostCallback d, object state)
  120. {
  121. mainLoop.Invoke (() => {
  122. d (state);
  123. });
  124. }
  125. }
  126. /// <summary>
  127. /// If set, it forces the use of the System.Console-based driver.
  128. /// </summary>
  129. public static bool UseSystemConsole;
  130. /// <summary>
  131. /// Initializes a new instance of <see cref="Terminal.Gui"/> Application.
  132. /// </summary>
  133. /// <remarks>
  134. /// <para>
  135. /// Call this method once per instance (or after <see cref="Shutdown"/> has been called).
  136. /// </para>
  137. /// <para>
  138. /// Loads the right <see cref="ConsoleDriver"/> for the platform.
  139. /// </para>
  140. /// <para>
  141. /// Creates a <see cref="Toplevel"/> and assigns it to <see cref="Top"/> and <see cref="CurrentView"/>
  142. /// </para>
  143. /// </remarks>
  144. public static void Init (ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) => Init (() => Toplevel.Create (), driver, mainLoopDriver);
  145. internal static bool _initialized = false;
  146. /// <summary>
  147. /// Initializes the Terminal.Gui application
  148. /// </summary>
  149. static void Init (Func<Toplevel> topLevelFactory, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null)
  150. {
  151. if (_initialized) return;
  152. // This supports Unit Tests and the passing of a mock driver/loopdriver
  153. if (driver != null) {
  154. if (mainLoopDriver == null) {
  155. throw new ArgumentNullException ("mainLoopDriver cannot be null if driver is provided.");
  156. }
  157. Driver = driver;
  158. Driver.Init (TerminalResized);
  159. MainLoop = new MainLoop (mainLoopDriver);
  160. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  161. }
  162. if (Driver == null) {
  163. var p = Environment.OSVersion.Platform;
  164. if (UseSystemConsole) {
  165. mainLoopDriver = new NetMainLoop (() => Console.ReadKey (true));
  166. Driver = new NetDriver ();
  167. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  168. var windowsDriver = new WindowsDriver ();
  169. mainLoopDriver = windowsDriver;
  170. Driver = windowsDriver;
  171. } else {
  172. mainLoopDriver = new UnixMainLoop ();
  173. Driver = new CursesDriver ();
  174. }
  175. Driver.Init (TerminalResized);
  176. MainLoop = new MainLoop (mainLoopDriver);
  177. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  178. }
  179. Top = topLevelFactory ();
  180. Current = Top;
  181. CurrentView = Top;
  182. _initialized = true;
  183. }
  184. /// <summary>
  185. /// Captures the execution state for the provided <see cref="Toplevel"/> view.
  186. /// </summary>
  187. public class RunState : IDisposable {
  188. internal bool closeDriver = true;
  189. /// <summary>
  190. /// Initializes a new <see cref="RunState"/> class.
  191. /// </summary>
  192. /// <param name="view"></param>
  193. public RunState (Toplevel view)
  194. {
  195. Toplevel = view;
  196. }
  197. internal Toplevel Toplevel;
  198. /// <summary>
  199. /// Releases alTop = l resource used by the <see cref="Application.RunState"/> object.
  200. /// </summary>
  201. /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="Application.RunState"/>. The
  202. /// <see cref="Dispose()"/> method leaves the <see cref="Application.RunState"/> in an unusable state. After
  203. /// calling <see cref="Dispose()"/>, you must release all references to the
  204. /// <see cref="Application.RunState"/> so the garbage collector can reclaim the memory that the
  205. /// <see cref="Application.RunState"/> was occupying.</remarks>
  206. public void Dispose ()
  207. {
  208. Dispose (closeDriver);
  209. GC.SuppressFinalize (this);
  210. }
  211. /// <summary>
  212. /// Dispose the specified disposing.
  213. /// </summary>
  214. /// <returns>The dispose.</returns>
  215. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  216. protected virtual void Dispose (bool disposing)
  217. {
  218. if (Toplevel != null) {
  219. End (Toplevel, disposing);
  220. Toplevel.Dispose ();
  221. Toplevel = null;
  222. }
  223. }
  224. }
  225. static void ProcessKeyEvent (KeyEvent ke)
  226. {
  227. var chain = toplevels.ToList ();
  228. foreach (var topLevel in chain) {
  229. if (topLevel.ProcessHotKey (ke))
  230. return;
  231. if (topLevel.Modal)
  232. break;
  233. }
  234. foreach (var topLevel in chain) {
  235. if (topLevel.ProcessKey (ke))
  236. return;
  237. if (topLevel.Modal)
  238. break;
  239. }
  240. foreach (var topLevel in chain) {
  241. // Process the key normally
  242. if (topLevel.ProcessColdKey (ke))
  243. return;
  244. if (topLevel.Modal)
  245. break;
  246. }
  247. }
  248. static void ProcessKeyDownEvent (KeyEvent ke)
  249. {
  250. var chain = toplevels.ToList ();
  251. foreach (var topLevel in chain) {
  252. if (topLevel.OnKeyDown (ke))
  253. return;
  254. if (topLevel.Modal)
  255. break;
  256. }
  257. }
  258. static void ProcessKeyUpEvent (KeyEvent ke)
  259. {
  260. var chain = toplevels.ToList ();
  261. foreach (var topLevel in chain) {
  262. if (topLevel.OnKeyUp (ke))
  263. return;
  264. if (topLevel.Modal)
  265. break;
  266. }
  267. }
  268. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  269. {
  270. var startFrame = start.Frame;
  271. if (!startFrame.Contains (x, y)) {
  272. resx = 0;
  273. resy = 0;
  274. return null;
  275. }
  276. if (start.InternalSubviews != null) {
  277. int count = start.InternalSubviews.Count;
  278. if (count > 0) {
  279. var rx = x - startFrame.X;
  280. var ry = y - startFrame.Y;
  281. for (int i = count - 1; i >= 0; i--) {
  282. View v = start.InternalSubviews [i];
  283. if (v.Frame.Contains (rx, ry)) {
  284. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  285. if (deep == null)
  286. return v;
  287. return deep;
  288. }
  289. }
  290. }
  291. }
  292. resx = x - startFrame.X;
  293. resy = y - startFrame.Y;
  294. return start;
  295. }
  296. internal static View mouseGrabView;
  297. /// <summary>
  298. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  299. /// </summary>
  300. /// <returns>The grab.</returns>
  301. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  302. public static void GrabMouse (View view)
  303. {
  304. if (view == null)
  305. return;
  306. mouseGrabView = view;
  307. Driver.UncookMouse ();
  308. }
  309. /// <summary>
  310. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  311. /// </summary>
  312. public static void UngrabMouse ()
  313. {
  314. mouseGrabView = null;
  315. Driver.CookMouse ();
  316. }
  317. /// <summary>
  318. /// Merely a debugging aid to see the raw mouse events
  319. /// </summary>
  320. public static Action<MouseEvent> RootMouseEvent;
  321. internal static View wantContinuousButtonPressedView;
  322. static View lastMouseOwnerView;
  323. static void ProcessMouseEvent (MouseEvent me)
  324. {
  325. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  326. if (view != null && view.WantContinuousButtonPressed)
  327. wantContinuousButtonPressedView = view;
  328. else
  329. wantContinuousButtonPressedView = null;
  330. RootMouseEvent?.Invoke (me);
  331. if (mouseGrabView != null) {
  332. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  333. var nme = new MouseEvent () {
  334. X = newxy.X,
  335. Y = newxy.Y,
  336. Flags = me.Flags,
  337. OfX = me.X - newxy.X,
  338. OfY = me.Y - newxy.Y,
  339. View = view
  340. };
  341. if (OutsideFrame (new Point (nme.X, nme.Y), mouseGrabView.Frame)) {
  342. lastMouseOwnerView?.OnMouseLeave (me);
  343. }
  344. if (mouseGrabView != null) {
  345. mouseGrabView.OnMouseEvent (nme);
  346. return;
  347. }
  348. }
  349. if (view != null) {
  350. var nme = new MouseEvent () {
  351. X = rx,
  352. Y = ry,
  353. Flags = me.Flags,
  354. OfX = rx,
  355. OfY = ry,
  356. View = view
  357. };
  358. if (lastMouseOwnerView == null) {
  359. lastMouseOwnerView = view;
  360. view.OnMouseEnter (nme);
  361. } else if (lastMouseOwnerView != view) {
  362. lastMouseOwnerView.OnMouseLeave (nme);
  363. view.OnMouseEnter (nme);
  364. lastMouseOwnerView = view;
  365. }
  366. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  367. return;
  368. if (view.WantContinuousButtonPressed)
  369. wantContinuousButtonPressedView = view;
  370. else
  371. wantContinuousButtonPressedView = null;
  372. // Should we bubbled up the event, if it is not handled?
  373. view.OnMouseEvent (nme);
  374. }
  375. }
  376. static bool OutsideFrame (Point p, Rect r)
  377. {
  378. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  379. }
  380. /// <summary>
  381. /// This event is fired once when the application is first loaded. The dimensions of the
  382. /// terminal are provided.
  383. /// </summary>
  384. public static Action<ResizedEventArgs> Loaded;
  385. /// <summary>
  386. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  387. /// </summary>
  388. /// <returns>The runstate handle that needs to be passed to the <see cref="End(RunState, bool)"/> method upon completion.</returns>
  389. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  390. /// <remarks>
  391. /// This method prepares the provided toplevel for running with the focus,
  392. /// it adds this to the list of toplevels, sets up the mainloop to process the
  393. /// event, lays out the subviews, focuses the first element, and draws the
  394. /// toplevel in the screen. This is usually followed by executing
  395. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState, bool)"/> method upon termination which will
  396. /// undo these changes.
  397. /// </remarks>
  398. public static RunState Begin (Toplevel toplevel)
  399. {
  400. if (toplevel == null)
  401. throw new ArgumentNullException (nameof (toplevel));
  402. var rs = new RunState (toplevel);
  403. Init ();
  404. if (toplevel is ISupportInitializeNotification initializableNotification &&
  405. !initializableNotification.IsInitialized) {
  406. initializableNotification.BeginInit ();
  407. initializableNotification.EndInit ();
  408. } else if (toplevel is ISupportInitialize initializable) {
  409. initializable.BeginInit ();
  410. initializable.EndInit ();
  411. }
  412. toplevels.Push (toplevel);
  413. Current = toplevel;
  414. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  415. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  416. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  417. toplevel.LayoutSubviews ();
  418. Loaded?.Invoke (new ResizedEventArgs () { Rows = Driver.Rows, Cols = Driver.Cols });
  419. toplevel.WillPresent ();
  420. Redraw (toplevel);
  421. toplevel.PositionCursor ();
  422. Driver.Refresh ();
  423. return rs;
  424. }
  425. /// <summary>
  426. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  427. /// </summary>
  428. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  429. /// <param name="closeDriver">If <c>true</c>, closes the application. If <c>false</c> closes the toplevels only.</param>
  430. public static void End (RunState runState, bool closeDriver = true)
  431. {
  432. if (runState == null)
  433. throw new ArgumentNullException (nameof (runState));
  434. runState.closeDriver = closeDriver;
  435. runState.Dispose ();
  436. }
  437. /// <summary>
  438. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>
  439. /// </summary>
  440. /// <param name="closeDriver"><c>true</c>Closes the application.<c>false</c>Closes toplevels only.</param>
  441. public static void Shutdown (bool closeDriver = true)
  442. {
  443. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  444. // Init created. Apps that do any threading will need to code defensively for this.
  445. // e.g. see Issue #537
  446. // TODO: Some of this state is actually related to Begin/End (not Init/Shutdown) and should be moved to `RunState` (#520)
  447. foreach (var t in toplevels) {
  448. t.Running = false;
  449. t.Dispose ();
  450. }
  451. toplevels.Clear ();
  452. Current = null;
  453. CurrentView = null;
  454. Top = null;
  455. // Closes the application if it's true.
  456. if (closeDriver) {
  457. MainLoop = null;
  458. Driver?.End ();
  459. Driver = null;
  460. }
  461. _initialized = false;
  462. }
  463. static void Redraw (View view)
  464. {
  465. Application.CurrentView = view;
  466. view.Redraw (view.Bounds);
  467. Driver.Refresh ();
  468. }
  469. static void Refresh (View view)
  470. {
  471. view.Redraw (view.Bounds);
  472. Driver.Refresh ();
  473. }
  474. /// <summary>
  475. /// Triggers a refresh of the entire display.
  476. /// </summary>
  477. public static void Refresh ()
  478. {
  479. Driver.UpdateScreen ();
  480. View last = null;
  481. foreach (var v in toplevels.Reverse ()) {
  482. v.SetNeedsDisplay ();
  483. v.Redraw (v.Bounds);
  484. last = v;
  485. }
  486. last?.PositionCursor ();
  487. Driver.Refresh ();
  488. }
  489. internal static void End (View view, bool closeDriver = true)
  490. {
  491. if (toplevels.Peek () != view)
  492. throw new ArgumentException ("The view that you end with must be balanced");
  493. toplevels.Pop ();
  494. if (toplevels.Count == 0)
  495. Shutdown (closeDriver);
  496. else {
  497. Current = toplevels.Peek ();
  498. Refresh ();
  499. }
  500. }
  501. /// <summary>
  502. /// Building block API: Runs the main loop for the created dialog
  503. /// </summary>
  504. /// <remarks>
  505. /// Use the wait parameter to control whether this is a
  506. /// blocking or non-blocking call.
  507. /// </remarks>
  508. /// <param name="state">The state returned by the Begin method.</param>
  509. /// <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>
  510. public static void RunLoop (RunState state, bool wait = true)
  511. {
  512. if (state == null)
  513. throw new ArgumentNullException (nameof (state));
  514. if (state.Toplevel == null)
  515. throw new ObjectDisposedException ("state");
  516. bool firstIteration = true;
  517. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  518. if (MainLoop.EventsPending (wait)) {
  519. // Notify Toplevel it's ready
  520. if (firstIteration) {
  521. state.Toplevel.OnReady ();
  522. }
  523. firstIteration = false;
  524. MainLoop.MainIteration ();
  525. Iteration?.Invoke ();
  526. } else if (wait == false) {
  527. return;
  528. }
  529. if (state.Toplevel != Top && (!Top.NeedDisplay.IsEmpty || Top.childNeedsDisplay)) {
  530. Top.Redraw (Top.Bounds);
  531. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  532. }
  533. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  534. state.Toplevel.Redraw (state.Toplevel.Bounds);
  535. if (DebugDrawBounds) {
  536. DrawBounds (state.Toplevel);
  537. }
  538. state.Toplevel.PositionCursor ();
  539. Driver.Refresh ();
  540. } else {
  541. Driver.UpdateCursor ();
  542. }
  543. }
  544. }
  545. internal static bool DebugDrawBounds = false;
  546. // Need to look into why this does not work properly.
  547. static void DrawBounds (View v)
  548. {
  549. v.DrawFrame (v.Frame, padding: 0, fill: false);
  550. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  551. foreach (var sub in v.InternalSubviews)
  552. DrawBounds (sub);
  553. }
  554. /// <summary>
  555. /// Runs the application by calling <see cref="Run(Toplevel, bool)"/> with the value of <see cref="Top"/>
  556. /// </summary>
  557. public static void Run ()
  558. {
  559. Run (Top);
  560. }
  561. /// <summary>
  562. /// Runs the application by calling <see cref="Run(Toplevel, bool)"/> with a new instance of the specified <see cref="Toplevel"/>-derived class
  563. /// </summary>
  564. public static void Run<T> () where T : Toplevel, new()
  565. {
  566. Init (() => new T ());
  567. Run (Top);
  568. }
  569. /// <summary>
  570. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  571. /// </summary>
  572. /// <remarks>
  573. /// <para>
  574. /// This method is used to start processing events
  575. /// for the main application, but it is also used to
  576. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  577. /// </para>
  578. /// <para>
  579. /// To make a <see cref="Run(Toplevel, bool)"/> stop execution, call <see cref="Application.RequestStop"/>.
  580. /// </para>
  581. /// <para>
  582. /// Calling <see cref="Run(Toplevel, bool)"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  583. /// and then calling <see cref="End(RunState, bool)"/>.
  584. /// </para>
  585. /// <para>
  586. /// Alternatively, to have a program control the main loop and
  587. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  588. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  589. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  590. /// then return control immediately.
  591. /// </para>
  592. /// </remarks>
  593. /// <param name="view">The <see cref="Toplevel"/> tu run modally.</param>
  594. /// <param name="closeDriver">Set to <true/> to cause the MainLoop to end when <see cref="End(RunState, bool)"/> is called, clsing the toplevels only.</param>
  595. public static void Run (Toplevel view, bool closeDriver = true)
  596. {
  597. var runToken = Begin (view);
  598. RunLoop (runToken);
  599. End (runToken, closeDriver);
  600. }
  601. /// <summary>
  602. /// Stops running the most recent <see cref="Toplevel"/>.
  603. /// </summary>
  604. /// <remarks>
  605. /// <para>
  606. /// This will cause <see cref="Application.Run()"/> to return.
  607. /// </para>
  608. /// <para>
  609. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the curently running <see cref="Toplevel"/> to false.
  610. /// </para>
  611. /// </remarks>
  612. public static void RequestStop ()
  613. {
  614. Current.Running = false;
  615. }
  616. /// <summary>
  617. /// Event arguments for the <see cref="Application.Resized"/> event.
  618. /// </summary>
  619. public class ResizedEventArgs : EventArgs {
  620. /// <summary>
  621. /// The number of rows in the resized terminal.
  622. /// </summary>
  623. public int Rows { get; set; }
  624. /// <summary>
  625. /// The number of columns in the resized terminal.
  626. /// </summary>
  627. public int Cols { get; set; }
  628. }
  629. /// <summary>
  630. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  631. /// </summary>
  632. public static Action<ResizedEventArgs> Resized;
  633. static void TerminalResized ()
  634. {
  635. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  636. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  637. Driver.Clip = full;
  638. foreach (var t in toplevels) {
  639. t.PositionToplevels ();
  640. t.SetRelativeLayout (full);
  641. t.LayoutSubviews ();
  642. }
  643. Refresh ();
  644. }
  645. }
  646. }