Application.cs 22 KB

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