Application.cs 24 KB

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