Core.cs 24 KB

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