Application.cs 22 KB

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