Core.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. //
  2. //
  3. // Pending:
  4. // - Check for NeedDisplay on the hierarchy and repaint
  5. // - Layout support
  6. // - "Colors" type or "Attributes" type?
  7. // - What to surface as "BackgroundCOlor" when clearing a window, an attribute or colors?
  8. //
  9. // Optimziations
  10. // - Add rendering limitation to the exposed area
  11. using System;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. namespace Terminal {
  15. public class Responder {
  16. public virtual bool CanFocus { get; set; }
  17. public virtual bool HasFocus { get; internal set; }
  18. // Key handling
  19. /// <summary>
  20. /// This method can be overwritten by view that
  21. /// want to provide accelerator functionality
  22. /// (Alt-key for example).
  23. /// </summary>
  24. /// <remarks>
  25. /// <para>
  26. /// Before keys are sent to the subview on the
  27. /// current view, all the views are
  28. /// processed and the key is passed to the widgets
  29. /// to allow some of them to process the keystroke
  30. /// as a hot-key. </para>
  31. /// <para>
  32. /// For example, if you implement a button that
  33. /// has a hotkey ok "o", you would catch the
  34. /// combination Alt-o here. If the event is
  35. /// caught, you must return true to stop the
  36. /// keystroke from being dispatched to other
  37. /// views.
  38. /// </para>
  39. /// </remarks>
  40. public virtual bool ProcessHotKey (KeyEvent kb)
  41. {
  42. return false;
  43. }
  44. /// <summary>
  45. /// If the view is focused, gives the view a
  46. /// chance to process the keystroke.
  47. /// </summary>
  48. /// <remarks>
  49. /// <para>
  50. /// Views can override this method if they are
  51. /// interested in processing the given keystroke.
  52. /// If they consume the keystroke, they must
  53. /// return true to stop the keystroke from being
  54. /// processed by other widgets or consumed by the
  55. /// widget engine. If they return false, the
  56. /// keystroke will be passed using the ProcessColdKey
  57. /// method to other views to process.
  58. /// </para>
  59. /// </remarks>
  60. public virtual bool ProcessKey (KeyEvent kb)
  61. {
  62. return false;
  63. }
  64. /// <summary>
  65. /// This method can be overwritten by views that
  66. /// want to provide accelerator functionality
  67. /// (Alt-key for example), but without
  68. /// interefering with normal ProcessKey behavior.
  69. /// </summary>
  70. /// <remarks>
  71. /// <para>
  72. /// After keys are sent to the subviews on the
  73. /// current view, all the view are
  74. /// processed and the key is passed to the views
  75. /// to allow some of them to process the keystroke
  76. /// as a cold-key. </para>
  77. /// <para>
  78. /// This functionality is used, for example, by
  79. /// default buttons to act on the enter key.
  80. /// Processing this as a hot-key would prevent
  81. /// non-default buttons from consuming the enter
  82. /// keypress when they have the focus.
  83. /// </para>
  84. /// </remarks>
  85. public virtual bool ProcessColdKey (KeyEvent kb)
  86. {
  87. return false;
  88. }
  89. // Mouse events
  90. public virtual void MouseEvent (Event.Mouse me) { }
  91. }
  92. public class View : Responder, IEnumerable {
  93. string id = "";
  94. View container = null;
  95. View focused = null;
  96. public static ConsoleDriver Driver = Application.Driver;
  97. public static IList<View> empty = new List<View> (0).AsReadOnly ();
  98. List<View> subviews;
  99. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  100. internal bool NeedDisplay { get; private set; } = true;
  101. // The frame for the object
  102. Rect frame;
  103. public string Id {
  104. get => id;
  105. set {
  106. id = value;
  107. }
  108. }
  109. // The frame for this view
  110. public Rect Frame {
  111. get => frame;
  112. set {
  113. frame = value;
  114. SetNeedsDisplay ();
  115. }
  116. }
  117. public IEnumerator GetEnumerator ()
  118. {
  119. foreach (var v in subviews)
  120. yield return v;
  121. }
  122. public Rect Bounds {
  123. get => new Rect (Point.Empty, Frame.Size);
  124. set {
  125. Frame = new Rect (frame.Location, value.Size);
  126. }
  127. }
  128. public View SuperView => container;
  129. public View (Rect frame)
  130. {
  131. this.Frame = frame;
  132. CanFocus = false;
  133. }
  134. /// <summary>
  135. /// Invoke to flag that this view needs to be redisplayed, by any code
  136. /// that alters the state of the view.
  137. /// </summary>
  138. public void SetNeedsDisplay ()
  139. {
  140. NeedDisplay = true;
  141. if (container != null)
  142. container.ChildNeedsDisplay ();
  143. }
  144. /// <summary>
  145. /// Sets the NeedsDisplay flag on this view and any child subviews.
  146. /// </summary>
  147. public void SetNeedsDisplayRecursive ()
  148. {
  149. NeedDisplay = true;
  150. if (subviews == null)
  151. return;
  152. foreach (var view in subviews)
  153. view.SetNeedsDisplayRecursive ();
  154. if (container != null)
  155. container.ChildNeedsDisplay ();
  156. }
  157. internal bool childNeedsDisplay;
  158. public void ChildNeedsDisplay ()
  159. {
  160. childNeedsDisplay = true;
  161. if (container != null)
  162. container.ChildNeedsDisplay ();
  163. }
  164. /// <summary>
  165. /// Adds a subview to this view.
  166. /// </summary>
  167. /// <remarks>
  168. /// </remarks>
  169. public virtual void Add (View view)
  170. {
  171. if (view == null)
  172. return;
  173. if (subviews == null)
  174. subviews = new List<View> ();
  175. subviews.Add (view);
  176. view.container = this;
  177. if (view.CanFocus)
  178. CanFocus = true;
  179. }
  180. public void Add (params View [] views)
  181. {
  182. if (views == null)
  183. return;
  184. foreach (var view in views)
  185. Add (view);
  186. }
  187. /// <summary>
  188. /// Removes all the widgets from this container.
  189. /// </summary>
  190. /// <remarks>
  191. /// </remarks>
  192. public virtual void RemoveAll ()
  193. {
  194. if (subviews == null)
  195. return;
  196. while (subviews.Count > 0) {
  197. var view = subviews [0];
  198. Remove (view);
  199. subviews.RemoveAt (0);
  200. }
  201. }
  202. /// <summary>
  203. /// Removes a widget from this container.
  204. /// </summary>
  205. /// <remarks>
  206. /// </remarks>
  207. public virtual void Remove (View view)
  208. {
  209. if (view == null)
  210. return;
  211. subviews.Remove (view);
  212. view.container = null;
  213. if (subviews.Count < 1)
  214. this.CanFocus = false;
  215. }
  216. /// <summary>
  217. /// Clears the view region with the current color.
  218. /// </summary>
  219. /// <remarks>
  220. /// <para>
  221. /// This clears the entire region used by this view.
  222. /// </para>
  223. /// </remarks>
  224. public void Clear ()
  225. {
  226. var h = Frame.Height;
  227. var w = Frame.Width;
  228. for (int line = 0; line < h; line++) {
  229. Move (0, line);
  230. for (int col = 0; col < w; col++)
  231. Driver.AddCh (' ');
  232. }
  233. }
  234. /// <summary>
  235. /// Converts the (col,row) position from the view into a screen (col,row). The values are clamped to (0..ScreenDim-1)
  236. /// </summary>
  237. /// <param name="col">View-based column.</param>
  238. /// <param name="row">View-based row.</param>
  239. /// <param name="rcol">Absolute column, display relative.</param>
  240. /// <param name="rrow">Absolute row, display relative.</param>
  241. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  242. {
  243. // Computes the real row, col relative to the screen.
  244. rrow = row + frame.Y;
  245. rcol = col + frame.X;
  246. var ccontainer = container;
  247. while (ccontainer != null) {
  248. rrow += ccontainer.frame.Y;
  249. rcol += ccontainer.frame.X;
  250. ccontainer = ccontainer.container;
  251. }
  252. // The following ensures that the cursor is always in the screen boundaries.
  253. if (clipped) {
  254. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  255. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  256. }
  257. }
  258. // Converts a rectangle in view coordinates to screen coordinates.
  259. Rect RectToScreen (Rect rect)
  260. {
  261. ViewToScreen (rect.X, rect.Y, out var x, out var y, clipped: false);
  262. return new Rect (x, y, rect.Width, rect.Height);
  263. }
  264. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  265. Rect ScreenClip (Rect rect)
  266. {
  267. var x = rect.X < 0 ? 0 : rect.X;
  268. var y = rect.Y < 0 ? 0 : rect.Y;
  269. var w = rect.X + rect.Width >= Driver.Cols ? Driver.Cols - rect.X : rect.Width;
  270. var h = rect.Y + rect.Height >= Driver.Rows ? Driver.Rows - rect.Y : rect.Height;
  271. return new Rect (x, y, w, h);
  272. }
  273. /// <summary>
  274. /// Draws a frame in the current view, clipped by the boundary of this view
  275. /// </summary>
  276. /// <param name="rect">Rectangular region for the frame to be drawn.</param>
  277. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  278. public void DrawFrame (Rect rect, bool fill = false)
  279. {
  280. var scrRect = RectToScreen (rect);
  281. var savedClip = Driver.Clip;
  282. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  283. Driver.DrawFrame (scrRect, fill);
  284. Driver.Clip = savedClip;
  285. }
  286. /// <summary>
  287. /// This moves the cursor to the specified column and row in the view.
  288. /// </summary>
  289. /// <returns>The move.</returns>
  290. /// <param name="col">Col.</param>
  291. /// <param name="row">Row.</param>
  292. public void Move (int col, int row)
  293. {
  294. ViewToScreen (col, row, out var rcol, out var rrow);
  295. Driver.Move (rcol, rrow);
  296. }
  297. /// <summary>
  298. /// Positions the cursor in the right position based on the currently focused view in the chain.
  299. /// </summary>
  300. public virtual void PositionCursor ()
  301. {
  302. if (focused != null)
  303. focused.PositionCursor ();
  304. else
  305. Move (frame.X, frame.Y);
  306. }
  307. public override bool HasFocus {
  308. get {
  309. return base.HasFocus;
  310. }
  311. internal set {
  312. if (base.HasFocus != value)
  313. SetNeedsDisplay ();
  314. base.HasFocus = value;
  315. }
  316. }
  317. /// <summary>
  318. /// Returns the currently focused view inside this view, or null if nothing is focused.
  319. /// </summary>
  320. /// <value>The focused.</value>
  321. public View Focused => focused;
  322. /// <summary>
  323. /// Displays the specified character in the specified column and row.
  324. /// </summary>
  325. /// <param name="col">Col.</param>
  326. /// <param name="row">Row.</param>
  327. /// <param name="ch">Ch.</param>
  328. public void AddCh (int col, int row, int ch)
  329. {
  330. if (row < 0 || col < 0)
  331. return;
  332. if (row > frame.Height - 1 || col > frame.Width - 1)
  333. return;
  334. Move (col, row);
  335. Driver.AddCh (ch);
  336. }
  337. /// <summary>
  338. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  339. /// </summary>
  340. /// <remarks>
  341. /// The region argument is relative to the view itself.
  342. /// </remarks>
  343. public virtual void Redraw (Rect region)
  344. {
  345. var clipRect = new Rect (Point.Empty, frame.Size);
  346. if (subviews != null) {
  347. foreach (var view in subviews) {
  348. if (view.NeedDisplay || view.childNeedsDisplay) {
  349. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  350. // TODO: optimize this by computing the intersection of region and view.Bounds
  351. view.Redraw (view.Bounds);
  352. }
  353. view.NeedDisplay = false;
  354. view.childNeedsDisplay = false;
  355. }
  356. }
  357. }
  358. NeedDisplay = false;
  359. childNeedsDisplay = false;
  360. }
  361. /// <summary>
  362. /// Focuses the specified sub-view.
  363. /// </summary>
  364. /// <param name="view">View.</param>
  365. public void SetFocus (View view)
  366. {
  367. if (view == null)
  368. return;
  369. //Console.WriteLine ($"Request to focus {view}");
  370. if (!view.CanFocus)
  371. return;
  372. if (focused == view)
  373. return;
  374. // Make sure that this view is a subview
  375. View c;
  376. for (c = view.container; c != null; c = c.container)
  377. if (c == this)
  378. break;
  379. if (c == null)
  380. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  381. if (focused != null)
  382. focused.HasFocus = false;
  383. focused = view;
  384. focused.HasFocus = true;
  385. focused.EnsureFocus ();
  386. }
  387. public override bool ProcessKey (KeyEvent kb)
  388. {
  389. if (Focused?.ProcessKey (kb) == true)
  390. return true;
  391. return false;
  392. }
  393. public override bool ProcessHotKey (KeyEvent kb)
  394. {
  395. if (subviews == null || subviews.Count == 0)
  396. return false;
  397. foreach (var view in subviews)
  398. if (view.ProcessHotKey (kb))
  399. return true;
  400. return false;
  401. }
  402. public override bool ProcessColdKey (KeyEvent kb)
  403. {
  404. if (subviews == null || subviews.Count == 0)
  405. return false;
  406. foreach (var view in subviews)
  407. if (view.ProcessHotKey (kb))
  408. return true;
  409. return false;
  410. }
  411. /// <summary>
  412. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  413. /// </summary>
  414. public void EnsureFocus ()
  415. {
  416. if (focused == null)
  417. FocusFirst ();
  418. }
  419. /// <summary>
  420. /// Focuses the first focusable subview if one exists.
  421. /// </summary>
  422. public void FocusFirst ()
  423. {
  424. if (subviews == null) {
  425. SuperView.SetFocus (this);
  426. return;
  427. }
  428. foreach (var view in subviews) {
  429. if (view.CanFocus) {
  430. SetFocus (view);
  431. return;
  432. }
  433. }
  434. }
  435. /// <summary>
  436. /// Focuses the last focusable subview if one exists.
  437. /// </summary>
  438. public void FocusLast ()
  439. {
  440. if (subviews == null)
  441. return;
  442. for (int i = subviews.Count; i > 0;) {
  443. i--;
  444. View v = subviews [i];
  445. if (v.CanFocus) {
  446. SetFocus (v);
  447. return;
  448. }
  449. }
  450. }
  451. /// <summary>
  452. /// Focuses the previous view.
  453. /// </summary>
  454. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  455. public bool FocusPrev ()
  456. {
  457. if (focused == null) {
  458. FocusLast ();
  459. return true;
  460. }
  461. int focused_idx = -1;
  462. for (int i = subviews.Count; i > 0;) {
  463. i--;
  464. View w = subviews [i];
  465. if (w.HasFocus) {
  466. if (w.FocusPrev ())
  467. return true;
  468. focused_idx = i;
  469. continue;
  470. }
  471. if (w.CanFocus && focused_idx != -1) {
  472. focused.HasFocus = false;
  473. if (w.CanFocus)
  474. w.FocusLast ();
  475. SetFocus (w);
  476. return true;
  477. }
  478. }
  479. if (focused != null) {
  480. focused.HasFocus = false;
  481. focused = null;
  482. }
  483. return false;
  484. }
  485. /// <summary>
  486. /// Focuses the next view.
  487. /// </summary>
  488. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  489. public bool FocusNext ()
  490. {
  491. if (subviews == null || subviews.Count == 0)
  492. return false;
  493. if (focused == null) {
  494. FocusFirst ();
  495. return focused != null;
  496. }
  497. int n = subviews.Count;
  498. int focused_idx = -1;
  499. for (int i = 0; i < n; i++) {
  500. View w = subviews [i];
  501. if (w.HasFocus) {
  502. if (w.FocusNext ())
  503. return true;
  504. focused_idx = i;
  505. continue;
  506. }
  507. if (w.CanFocus && focused_idx != -1) {
  508. focused.HasFocus = false;
  509. if (w != null && w.CanFocus)
  510. w.FocusFirst ();
  511. SetFocus (w);
  512. return true;
  513. }
  514. }
  515. if (focused != null) {
  516. focused.HasFocus = false;
  517. focused = null;
  518. }
  519. return false;
  520. }
  521. public virtual void LayoutSubviews ()
  522. {
  523. }
  524. public override string ToString ()
  525. {
  526. return $"{GetType ().Name}({id})({Frame})";
  527. }
  528. }
  529. /// <summary>
  530. /// Toplevel views can be modally executed.
  531. /// </summary>
  532. public class Toplevel : View {
  533. public bool Running;
  534. public Toplevel (Rect frame) : base (frame)
  535. {
  536. }
  537. public static Toplevel Create ()
  538. {
  539. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  540. }
  541. public override bool CanFocus {
  542. get => true;
  543. }
  544. public override bool ProcessKey (KeyEvent kb)
  545. {
  546. if (ProcessHotKey (kb))
  547. return true;
  548. if (base.ProcessKey (kb))
  549. return true;
  550. // Process the key normally
  551. if (ProcessColdKey (kb))
  552. return true;
  553. switch (kb.Key) {
  554. case Key.ControlC:
  555. // TODO: stop current execution of this container
  556. break;
  557. case Key.ControlZ:
  558. // TODO: should suspend
  559. // console_csharp_send_sigtstp ();
  560. break;
  561. case Key.Tab:
  562. var old = Focused;
  563. if (!FocusNext ())
  564. FocusNext ();
  565. if (old != Focused) {
  566. old?.SetNeedsDisplay ();
  567. Focused?.SetNeedsDisplay ();
  568. }
  569. return true;
  570. case Key.BackTab:
  571. old = Focused;
  572. if (!FocusPrev ())
  573. FocusPrev ();
  574. if (old != Focused) {
  575. old?.SetNeedsDisplay ();
  576. Focused?.SetNeedsDisplay ();
  577. }
  578. return true;
  579. case Key.ControlL:
  580. SetNeedsDisplayRecursive ();
  581. return true;
  582. }
  583. return false;
  584. }
  585. #if false
  586. public override void Redraw ()
  587. {
  588. base.Redraw ();
  589. for (int i = 0; i < Driver.Cols; i++) {
  590. Driver.Move (0, i);
  591. Driver.AddStr ("Line: " + i);
  592. }
  593. }
  594. #endif
  595. }
  596. /// <summary>
  597. /// A toplevel view that draws a frame around its region
  598. /// </summary>
  599. public class Window : Toplevel, IEnumerable {
  600. View contentView;
  601. string title;
  602. public string Title {
  603. get => title;
  604. set {
  605. title = value;
  606. SetNeedsDisplay ();
  607. }
  608. }
  609. class ContentView : View {
  610. public ContentView (Rect frame) : base (frame) { }
  611. }
  612. public Window (Rect frame, string title = null) : base (frame)
  613. {
  614. this.Title = title;
  615. frame.Inflate (-1, -1);
  616. contentView = new ContentView (frame);
  617. base.Add (contentView);
  618. }
  619. public new IEnumerator GetEnumerator ()
  620. {
  621. return contentView.GetEnumerator ();
  622. }
  623. void DrawFrame ()
  624. {
  625. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), true);
  626. }
  627. public override void Add (View view)
  628. {
  629. contentView.Add (view);
  630. }
  631. public override void Redraw (Rect bounds)
  632. {
  633. if (NeedDisplay) {
  634. Driver.SetAttribute (Colors.Base.Normal);
  635. DrawFrame ();
  636. if (HasFocus)
  637. Driver.SetAttribute (Colors.Dialog.Normal);
  638. var width = Frame.Width;
  639. if (Title != null && width > 4) {
  640. Move (1, 0);
  641. Driver.AddCh (' ');
  642. var str = Title.Length > width ? Title.Substring (0, width - 4) : Title;
  643. Driver.AddStr (str);
  644. Driver.AddCh (' ');
  645. }
  646. Driver.SetAttribute (Colors.Dialog.Normal);
  647. }
  648. contentView.Redraw (contentView.Bounds);
  649. }
  650. }
  651. public class Application {
  652. public static ConsoleDriver Driver = new CursesDriver ();
  653. public static Toplevel Top { get; private set; }
  654. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  655. static Stack<View> toplevels = new Stack<View> ();
  656. static Responder focus;
  657. /// <summary>
  658. /// This event is raised on each iteration of the
  659. /// main loop.
  660. /// </summary>
  661. /// <remarks>
  662. /// See also <see cref="Timeout"/>
  663. /// </remarks>
  664. static public event EventHandler Iteration;
  665. public static void MakeFirstResponder (Responder newResponder)
  666. {
  667. if (newResponder == null)
  668. throw new ArgumentNullException ();
  669. throw new NotImplementedException ();
  670. }
  671. /// <summary>
  672. /// Initializes the Application
  673. /// </summary>
  674. public static void Init ()
  675. {
  676. if (Top != null)
  677. return;
  678. Driver.Init (TerminalResized);
  679. MainLoop = new Mono.Terminal.MainLoop ();
  680. Top = Toplevel.Create ();
  681. focus = Top;
  682. }
  683. public class RunState : IDisposable {
  684. internal RunState (Toplevel view)
  685. {
  686. Toplevel = view;
  687. }
  688. internal Toplevel Toplevel;
  689. public void Dispose ()
  690. {
  691. Dispose (true);
  692. GC.SuppressFinalize (this);
  693. }
  694. public virtual void Dispose (bool disposing)
  695. {
  696. if (Toplevel != null) {
  697. Application.End (Toplevel);
  698. Toplevel = null;
  699. }
  700. }
  701. }
  702. static void KeyEvent (Key key)
  703. {
  704. }
  705. static public RunState Begin (Toplevel toplevel)
  706. {
  707. if (toplevel == null)
  708. throw new ArgumentNullException (nameof (toplevel));
  709. var rs = new RunState (toplevel);
  710. Init ();
  711. toplevels.Push (toplevel);
  712. Driver.PrepareToRun (MainLoop, toplevel);
  713. toplevel.LayoutSubviews ();
  714. toplevel.FocusFirst ();
  715. Redraw (toplevel);
  716. toplevel.PositionCursor ();
  717. Driver.Refresh ();
  718. return rs;
  719. }
  720. static public void End (RunState rs)
  721. {
  722. if (rs == null)
  723. throw new ArgumentNullException (nameof (rs));
  724. rs.Dispose ();
  725. }
  726. static void Shutdown ()
  727. {
  728. Driver.End ();
  729. }
  730. static void Redraw (View view)
  731. {
  732. view.Redraw (view.Bounds);
  733. Driver.Refresh ();
  734. }
  735. static void Refresh (View view)
  736. {
  737. view.Redraw (view.Bounds);
  738. Driver.Refresh ();
  739. }
  740. public static void Refresh ()
  741. {
  742. Driver.RedrawTop ();
  743. View last = null;
  744. foreach (var v in toplevels) {
  745. v.Redraw (v.Bounds);
  746. last = v;
  747. }
  748. if (last != null)
  749. last.PositionCursor ();
  750. Driver.Refresh ();
  751. }
  752. internal static void End (View view)
  753. {
  754. if (toplevels.Peek () != view)
  755. throw new ArgumentException ("The view that you end with must be balanced");
  756. toplevels.Pop ();
  757. if (toplevels.Count == 0)
  758. Shutdown ();
  759. else
  760. Refresh ();
  761. }
  762. /// <summary>
  763. /// Runs the main loop for the created dialog
  764. /// </summary>
  765. /// <remarks>
  766. /// Use the wait parameter to control whether this is a
  767. /// blocking or non-blocking call.
  768. /// </remarks>
  769. public static void RunLoop (RunState state, bool wait = true)
  770. {
  771. if (state == null)
  772. throw new ArgumentNullException (nameof (state));
  773. if (state.Toplevel == null)
  774. throw new ObjectDisposedException ("state");
  775. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  776. if (MainLoop.EventsPending (wait)) {
  777. MainLoop.MainIteration ();
  778. if (Iteration != null)
  779. Iteration (null, EventArgs.Empty);
  780. } else if (wait == false)
  781. return;
  782. if (state.Toplevel.NeedDisplay || state.Toplevel.childNeedsDisplay) {
  783. state.Toplevel.Redraw (state.Toplevel.Bounds);
  784. state.Toplevel.PositionCursor ();
  785. Driver.Refresh ();
  786. }
  787. }
  788. }
  789. public static void Run ()
  790. {
  791. Run (Top);
  792. }
  793. /// <summary>
  794. /// Runs the main loop on the given container.
  795. /// </summary>
  796. /// <remarks>
  797. /// This method is used to start processing events
  798. /// for the main application, but it is also used to
  799. /// run modal dialog boxes.
  800. /// </remarks>
  801. public static void Run (Toplevel view)
  802. {
  803. var runToken = Begin (view);
  804. RunLoop (runToken);
  805. End (runToken);
  806. }
  807. static void TerminalResized ()
  808. {
  809. foreach (var t in toplevels) {
  810. t.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  811. }
  812. }
  813. }
  814. }