Core.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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. /// Utility function to draw strings that contain a hotkey
  288. /// </summary>
  289. /// <param name="s">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  290. /// <param name="hotColor">Hot color.</param>
  291. /// <param name="normalColor">Normal color.</param>
  292. public void DrawHotString (string text, Attribute hotColor, Attribute normalColor)
  293. {
  294. Driver.SetAttribute (normalColor);
  295. foreach (var c in text) {
  296. if (c == '_') {
  297. Driver.SetAttribute (hotColor);
  298. continue;
  299. }
  300. Driver.AddCh (c);
  301. Driver.SetAttribute (normalColor);
  302. }
  303. }
  304. /// <summary>
  305. /// This moves the cursor to the specified column and row in the view.
  306. /// </summary>
  307. /// <returns>The move.</returns>
  308. /// <param name="col">Col.</param>
  309. /// <param name="row">Row.</param>
  310. public void Move (int col, int row)
  311. {
  312. ViewToScreen (col, row, out var rcol, out var rrow);
  313. Driver.Move (rcol, rrow);
  314. }
  315. /// <summary>
  316. /// Positions the cursor in the right position based on the currently focused view in the chain.
  317. /// </summary>
  318. public virtual void PositionCursor ()
  319. {
  320. if (focused != null)
  321. focused.PositionCursor ();
  322. else
  323. Move (frame.X, frame.Y);
  324. }
  325. public override bool HasFocus {
  326. get {
  327. return base.HasFocus;
  328. }
  329. internal set {
  330. if (base.HasFocus != value)
  331. SetNeedsDisplay ();
  332. base.HasFocus = value;
  333. }
  334. }
  335. /// <summary>
  336. /// Returns the currently focused view inside this view, or null if nothing is focused.
  337. /// </summary>
  338. /// <value>The focused.</value>
  339. public View Focused => focused;
  340. /// <summary>
  341. /// Displays the specified character in the specified column and row.
  342. /// </summary>
  343. /// <param name="col">Col.</param>
  344. /// <param name="row">Row.</param>
  345. /// <param name="ch">Ch.</param>
  346. public void AddCh (int col, int row, int ch)
  347. {
  348. if (row < 0 || col < 0)
  349. return;
  350. if (row > frame.Height - 1 || col > frame.Width - 1)
  351. return;
  352. Move (col, row);
  353. Driver.AddCh (ch);
  354. }
  355. /// <summary>
  356. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  357. /// </summary>
  358. /// <remarks>
  359. /// The region argument is relative to the view itself.
  360. /// </remarks>
  361. public virtual void Redraw (Rect region)
  362. {
  363. var clipRect = new Rect (Point.Empty, frame.Size);
  364. if (subviews != null) {
  365. foreach (var view in subviews) {
  366. if (view.NeedDisplay || view.childNeedsDisplay) {
  367. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  368. // TODO: optimize this by computing the intersection of region and view.Bounds
  369. view.Redraw (view.Bounds);
  370. }
  371. view.NeedDisplay = false;
  372. view.childNeedsDisplay = false;
  373. }
  374. }
  375. }
  376. NeedDisplay = false;
  377. childNeedsDisplay = false;
  378. }
  379. /// <summary>
  380. /// Focuses the specified sub-view.
  381. /// </summary>
  382. /// <param name="view">View.</param>
  383. public void SetFocus (View view)
  384. {
  385. if (view == null)
  386. return;
  387. //Console.WriteLine ($"Request to focus {view}");
  388. if (!view.CanFocus)
  389. return;
  390. if (focused == view)
  391. return;
  392. // Make sure that this view is a subview
  393. View c;
  394. for (c = view.container; c != null; c = c.container)
  395. if (c == this)
  396. break;
  397. if (c == null)
  398. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  399. if (focused != null)
  400. focused.HasFocus = false;
  401. focused = view;
  402. focused.HasFocus = true;
  403. focused.EnsureFocus ();
  404. }
  405. public override bool ProcessKey (KeyEvent kb)
  406. {
  407. if (Focused?.ProcessKey (kb) == true)
  408. return true;
  409. return false;
  410. }
  411. public override bool ProcessHotKey (KeyEvent kb)
  412. {
  413. if (subviews == null || subviews.Count == 0)
  414. return false;
  415. foreach (var view in subviews)
  416. if (view.ProcessHotKey (kb))
  417. return true;
  418. return false;
  419. }
  420. public override bool ProcessColdKey (KeyEvent kb)
  421. {
  422. if (subviews == null || subviews.Count == 0)
  423. return false;
  424. foreach (var view in subviews)
  425. if (view.ProcessHotKey (kb))
  426. return true;
  427. return false;
  428. }
  429. /// <summary>
  430. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  431. /// </summary>
  432. public void EnsureFocus ()
  433. {
  434. if (focused == null)
  435. FocusFirst ();
  436. }
  437. /// <summary>
  438. /// Focuses the first focusable subview if one exists.
  439. /// </summary>
  440. public void FocusFirst ()
  441. {
  442. if (subviews == null) {
  443. SuperView.SetFocus (this);
  444. return;
  445. }
  446. foreach (var view in subviews) {
  447. if (view.CanFocus) {
  448. SetFocus (view);
  449. return;
  450. }
  451. }
  452. }
  453. /// <summary>
  454. /// Focuses the last focusable subview if one exists.
  455. /// </summary>
  456. public void FocusLast ()
  457. {
  458. if (subviews == null)
  459. return;
  460. for (int i = subviews.Count; i > 0;) {
  461. i--;
  462. View v = subviews [i];
  463. if (v.CanFocus) {
  464. SetFocus (v);
  465. return;
  466. }
  467. }
  468. }
  469. /// <summary>
  470. /// Focuses the previous view.
  471. /// </summary>
  472. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  473. public bool FocusPrev ()
  474. {
  475. if (focused == null) {
  476. FocusLast ();
  477. return true;
  478. }
  479. int focused_idx = -1;
  480. for (int i = subviews.Count; i > 0;) {
  481. i--;
  482. View w = subviews [i];
  483. if (w.HasFocus) {
  484. if (w.FocusPrev ())
  485. return true;
  486. focused_idx = i;
  487. continue;
  488. }
  489. if (w.CanFocus && focused_idx != -1) {
  490. focused.HasFocus = false;
  491. if (w.CanFocus)
  492. w.FocusLast ();
  493. SetFocus (w);
  494. return true;
  495. }
  496. }
  497. if (focused != null) {
  498. focused.HasFocus = false;
  499. focused = null;
  500. }
  501. return false;
  502. }
  503. /// <summary>
  504. /// Focuses the next view.
  505. /// </summary>
  506. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  507. public bool FocusNext ()
  508. {
  509. if (subviews == null || subviews.Count == 0)
  510. return false;
  511. if (focused == null) {
  512. FocusFirst ();
  513. return focused != null;
  514. }
  515. int n = subviews.Count;
  516. int focused_idx = -1;
  517. for (int i = 0; i < n; i++) {
  518. View w = subviews [i];
  519. if (w.HasFocus) {
  520. if (w.FocusNext ())
  521. return true;
  522. focused_idx = i;
  523. continue;
  524. }
  525. if (w.CanFocus && focused_idx != -1) {
  526. focused.HasFocus = false;
  527. if (w != null && w.CanFocus)
  528. w.FocusFirst ();
  529. SetFocus (w);
  530. return true;
  531. }
  532. }
  533. if (focused != null) {
  534. focused.HasFocus = false;
  535. focused = null;
  536. }
  537. return false;
  538. }
  539. public virtual void LayoutSubviews ()
  540. {
  541. }
  542. public override string ToString ()
  543. {
  544. return $"{GetType ().Name}({id})({Frame})";
  545. }
  546. }
  547. /// <summary>
  548. /// Toplevel views can be modally executed.
  549. /// </summary>
  550. public class Toplevel : View {
  551. public bool Running;
  552. public Toplevel (Rect frame) : base (frame)
  553. {
  554. }
  555. public static Toplevel Create ()
  556. {
  557. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  558. }
  559. public override bool CanFocus {
  560. get => true;
  561. }
  562. public override bool ProcessKey (KeyEvent kb)
  563. {
  564. if (ProcessHotKey (kb))
  565. return true;
  566. if (base.ProcessKey (kb))
  567. return true;
  568. // Process the key normally
  569. if (ProcessColdKey (kb))
  570. return true;
  571. switch (kb.Key) {
  572. case Key.ControlC:
  573. // TODO: stop current execution of this container
  574. break;
  575. case Key.ControlZ:
  576. // TODO: should suspend
  577. // console_csharp_send_sigtstp ();
  578. break;
  579. case Key.Tab:
  580. var old = Focused;
  581. if (!FocusNext ())
  582. FocusNext ();
  583. if (old != Focused) {
  584. old?.SetNeedsDisplay ();
  585. Focused?.SetNeedsDisplay ();
  586. }
  587. return true;
  588. case Key.BackTab:
  589. old = Focused;
  590. if (!FocusPrev ())
  591. FocusPrev ();
  592. if (old != Focused) {
  593. old?.SetNeedsDisplay ();
  594. Focused?.SetNeedsDisplay ();
  595. }
  596. return true;
  597. case Key.ControlL:
  598. SetNeedsDisplayRecursive ();
  599. return true;
  600. }
  601. return false;
  602. }
  603. #if false
  604. public override void Redraw ()
  605. {
  606. base.Redraw ();
  607. for (int i = 0; i < Driver.Cols; i++) {
  608. Driver.Move (0, i);
  609. Driver.AddStr ("Line: " + i);
  610. }
  611. }
  612. #endif
  613. }
  614. /// <summary>
  615. /// A toplevel view that draws a frame around its region
  616. /// </summary>
  617. public class Window : Toplevel, IEnumerable {
  618. View contentView;
  619. string title;
  620. public string Title {
  621. get => title;
  622. set {
  623. title = value;
  624. SetNeedsDisplay ();
  625. }
  626. }
  627. class ContentView : View {
  628. public ContentView (Rect frame) : base (frame) { }
  629. }
  630. public Window (Rect frame, string title = null) : base (frame)
  631. {
  632. this.Title = title;
  633. frame.Inflate (-1, -1);
  634. contentView = new ContentView (frame);
  635. base.Add (contentView);
  636. }
  637. public new IEnumerator GetEnumerator ()
  638. {
  639. return contentView.GetEnumerator ();
  640. }
  641. void DrawFrame ()
  642. {
  643. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), true);
  644. }
  645. public override void Add (View view)
  646. {
  647. contentView.Add (view);
  648. }
  649. public override void Redraw (Rect bounds)
  650. {
  651. if (NeedDisplay) {
  652. Driver.SetAttribute (Colors.Base.Normal);
  653. DrawFrame ();
  654. if (HasFocus)
  655. Driver.SetAttribute (Colors.Dialog.Normal);
  656. var width = Frame.Width;
  657. if (Title != null && width > 4) {
  658. Move (1, 0);
  659. Driver.AddCh (' ');
  660. var str = Title.Length > width ? Title.Substring (0, width - 4) : Title;
  661. Driver.AddStr (str);
  662. Driver.AddCh (' ');
  663. }
  664. Driver.SetAttribute (Colors.Dialog.Normal);
  665. }
  666. contentView.Redraw (contentView.Bounds);
  667. }
  668. }
  669. public class Application {
  670. public static ConsoleDriver Driver = new CursesDriver ();
  671. public static Toplevel Top { get; private set; }
  672. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  673. static Stack<View> toplevels = new Stack<View> ();
  674. static Responder focus;
  675. /// <summary>
  676. /// This event is raised on each iteration of the
  677. /// main loop.
  678. /// </summary>
  679. /// <remarks>
  680. /// See also <see cref="Timeout"/>
  681. /// </remarks>
  682. static public event EventHandler Iteration;
  683. public static void MakeFirstResponder (Responder newResponder)
  684. {
  685. if (newResponder == null)
  686. throw new ArgumentNullException ();
  687. throw new NotImplementedException ();
  688. }
  689. /// <summary>
  690. /// Initializes the Application
  691. /// </summary>
  692. public static void Init ()
  693. {
  694. if (Top != null)
  695. return;
  696. Driver.Init (TerminalResized);
  697. MainLoop = new Mono.Terminal.MainLoop ();
  698. Top = Toplevel.Create ();
  699. focus = Top;
  700. }
  701. public class RunState : IDisposable {
  702. internal RunState (Toplevel view)
  703. {
  704. Toplevel = view;
  705. }
  706. internal Toplevel Toplevel;
  707. public void Dispose ()
  708. {
  709. Dispose (true);
  710. GC.SuppressFinalize (this);
  711. }
  712. public virtual void Dispose (bool disposing)
  713. {
  714. if (Toplevel != null) {
  715. Application.End (Toplevel);
  716. Toplevel = null;
  717. }
  718. }
  719. }
  720. static void KeyEvent (Key key)
  721. {
  722. }
  723. static public RunState Begin (Toplevel toplevel)
  724. {
  725. if (toplevel == null)
  726. throw new ArgumentNullException (nameof (toplevel));
  727. var rs = new RunState (toplevel);
  728. Init ();
  729. toplevels.Push (toplevel);
  730. Driver.PrepareToRun (MainLoop, toplevel);
  731. toplevel.LayoutSubviews ();
  732. toplevel.FocusFirst ();
  733. Redraw (toplevel);
  734. toplevel.PositionCursor ();
  735. Driver.Refresh ();
  736. return rs;
  737. }
  738. static public void End (RunState rs)
  739. {
  740. if (rs == null)
  741. throw new ArgumentNullException (nameof (rs));
  742. rs.Dispose ();
  743. }
  744. static void Shutdown ()
  745. {
  746. Driver.End ();
  747. }
  748. static void Redraw (View view)
  749. {
  750. view.Redraw (view.Bounds);
  751. Driver.Refresh ();
  752. }
  753. static void Refresh (View view)
  754. {
  755. view.Redraw (view.Bounds);
  756. Driver.Refresh ();
  757. }
  758. public static void Refresh ()
  759. {
  760. Driver.RedrawTop ();
  761. View last = null;
  762. foreach (var v in toplevels) {
  763. v.Redraw (v.Bounds);
  764. last = v;
  765. }
  766. if (last != null)
  767. last.PositionCursor ();
  768. Driver.Refresh ();
  769. }
  770. internal static void End (View view)
  771. {
  772. if (toplevels.Peek () != view)
  773. throw new ArgumentException ("The view that you end with must be balanced");
  774. toplevels.Pop ();
  775. if (toplevels.Count == 0)
  776. Shutdown ();
  777. else
  778. Refresh ();
  779. }
  780. /// <summary>
  781. /// Runs the main loop for the created dialog
  782. /// </summary>
  783. /// <remarks>
  784. /// Use the wait parameter to control whether this is a
  785. /// blocking or non-blocking call.
  786. /// </remarks>
  787. public static void RunLoop (RunState state, bool wait = true)
  788. {
  789. if (state == null)
  790. throw new ArgumentNullException (nameof (state));
  791. if (state.Toplevel == null)
  792. throw new ObjectDisposedException ("state");
  793. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  794. if (MainLoop.EventsPending (wait)) {
  795. MainLoop.MainIteration ();
  796. if (Iteration != null)
  797. Iteration (null, EventArgs.Empty);
  798. } else if (wait == false)
  799. return;
  800. if (state.Toplevel.NeedDisplay || state.Toplevel.childNeedsDisplay) {
  801. state.Toplevel.Redraw (state.Toplevel.Bounds);
  802. state.Toplevel.PositionCursor ();
  803. Driver.Refresh ();
  804. }
  805. }
  806. }
  807. public static void Run ()
  808. {
  809. Run (Top);
  810. }
  811. /// <summary>
  812. /// Runs the main loop on the given container.
  813. /// </summary>
  814. /// <remarks>
  815. /// This method is used to start processing events
  816. /// for the main application, but it is also used to
  817. /// run modal dialog boxes.
  818. /// </remarks>
  819. public static void Run (Toplevel view)
  820. {
  821. var runToken = Begin (view);
  822. RunLoop (runToken);
  823. End (runToken);
  824. }
  825. static void TerminalResized ()
  826. {
  827. foreach (var t in toplevels) {
  828. t.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  829. }
  830. }
  831. }
  832. }