Core.cs 24 KB

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