Core.cs 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. //
  2. // Core.cs: The core engine for gui.cs
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. // Pending:
  8. // - Check for NeedDisplay on the hierarchy and repaint
  9. // - Layout support
  10. // - "Colors" type or "Attributes" type?
  11. // - What to surface as "BackgroundCOlor" when clearing a window, an attribute or colors?
  12. //
  13. // Optimziations
  14. // - Add rendering limitation to the exposed area
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Threading;
  19. using System.Linq;
  20. namespace Terminal {
  21. public class Responder {
  22. public virtual bool CanFocus { get; set; }
  23. public virtual bool HasFocus { get; internal set; }
  24. // Key handling
  25. /// <summary>
  26. /// This method can be overwritten by view that
  27. /// want to provide accelerator functionality
  28. /// (Alt-key for example).
  29. /// </summary>
  30. /// <remarks>
  31. /// <para>
  32. /// Before keys are sent to the subview on the
  33. /// current view, all the views are
  34. /// processed and the key is passed to the widgets
  35. /// to allow some of them to process the keystroke
  36. /// as a hot-key. </para>
  37. /// <para>
  38. /// For example, if you implement a button that
  39. /// has a hotkey ok "o", you would catch the
  40. /// combination Alt-o here. If the event is
  41. /// caught, you must return true to stop the
  42. /// keystroke from being dispatched to other
  43. /// views.
  44. /// </para>
  45. /// </remarks>
  46. public virtual bool ProcessHotKey (KeyEvent kb)
  47. {
  48. return false;
  49. }
  50. /// <summary>
  51. /// If the view is focused, gives the view a
  52. /// chance to process the keystroke.
  53. /// </summary>
  54. /// <remarks>
  55. /// <para>
  56. /// Views can override this method if they are
  57. /// interested in processing the given keystroke.
  58. /// If they consume the keystroke, they must
  59. /// return true to stop the keystroke from being
  60. /// processed by other widgets or consumed by the
  61. /// widget engine. If they return false, the
  62. /// keystroke will be passed using the ProcessColdKey
  63. /// method to other views to process.
  64. /// </para>
  65. /// <para>
  66. /// The View implementation does nothing but return false,
  67. /// so it is not necessary to call base.ProcessKey if you
  68. /// derive directly from View, but you should if you derive
  69. /// other View subclasses.
  70. /// </para>
  71. /// </remarks>
  72. public virtual bool ProcessKey (KeyEvent kb)
  73. {
  74. return false;
  75. }
  76. /// <summary>
  77. /// This method can be overwritten by views that
  78. /// want to provide accelerator functionality
  79. /// (Alt-key for example), but without
  80. /// interefering with normal ProcessKey behavior.
  81. /// </summary>
  82. /// <remarks>
  83. /// <para>
  84. /// After keys are sent to the subviews on the
  85. /// current view, all the view are
  86. /// processed and the key is passed to the views
  87. /// to allow some of them to process the keystroke
  88. /// as a cold-key. </para>
  89. /// <para>
  90. /// This functionality is used, for example, by
  91. /// default buttons to act on the enter key.
  92. /// Processing this as a hot-key would prevent
  93. /// non-default buttons from consuming the enter
  94. /// keypress when they have the focus.
  95. /// </para>
  96. /// </remarks>
  97. public virtual bool ProcessColdKey (KeyEvent kb)
  98. {
  99. return false;
  100. }
  101. // Mouse events
  102. public virtual bool MouseEvent (MouseEvent me)
  103. {
  104. return false;
  105. }
  106. }
  107. public class View : Responder, IEnumerable {
  108. string id = "";
  109. View container = null;
  110. View focused = null;
  111. public static ConsoleDriver Driver = Application.Driver;
  112. public static IList<View> empty = new List<View> (0).AsReadOnly ();
  113. List<View> subviews;
  114. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  115. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  116. // The frame for the object
  117. Rect frame;
  118. public string Id {
  119. get => id;
  120. set {
  121. id = value;
  122. }
  123. }
  124. /// <summary>
  125. /// Gets or sets a value indicating whether this <see cref="T:Terminal.View"/> want mouse position reports.
  126. /// </summary>
  127. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  128. public virtual bool WantMousePositionReports { get; set; } = false;
  129. // The frame for this view
  130. public Rect Frame {
  131. get => frame;
  132. set {
  133. if (SuperView != null) {
  134. SuperView.SetNeedsDisplay (frame);
  135. SuperView.SetNeedsDisplay (value);
  136. }
  137. frame = value;
  138. SetNeedsDisplay (frame);
  139. }
  140. }
  141. public IEnumerator GetEnumerator ()
  142. {
  143. foreach (var v in subviews)
  144. yield return v;
  145. }
  146. public Rect Bounds {
  147. get => new Rect (Point.Empty, Frame.Size);
  148. set {
  149. Frame = new Rect (frame.Location, value.Size);
  150. }
  151. }
  152. public View SuperView => container;
  153. public View (Rect frame)
  154. {
  155. this.Frame = frame;
  156. CanFocus = false;
  157. }
  158. /// <summary>
  159. /// Invoke to flag that this view needs to be redisplayed, by any code
  160. /// that alters the state of the view.
  161. /// </summary>
  162. public void SetNeedsDisplay ()
  163. {
  164. SetNeedsDisplay (Frame);
  165. }
  166. public void SetNeedsDisplay (Rect region)
  167. {
  168. if (NeedDisplay.IsEmpty)
  169. NeedDisplay = region;
  170. else {
  171. var x = Math.Min (NeedDisplay.X, region.X);
  172. var y = Math.Min (NeedDisplay.Y, region.Y);
  173. var w = Math.Max (NeedDisplay.Width, region.Width);
  174. var h = Math.Max (NeedDisplay.Height, region.Height);
  175. NeedDisplay = new Rect (x, y, w, h);
  176. }
  177. if (container != null)
  178. container.ChildNeedsDisplay ();
  179. if (subviews == null)
  180. return;
  181. foreach (var view in subviews)
  182. if (view.Frame.IntersectsWith (region)) {
  183. view.SetNeedsDisplay (Rect.Intersect (view.Frame, region));
  184. }
  185. }
  186. internal bool childNeedsDisplay;
  187. public void ChildNeedsDisplay ()
  188. {
  189. childNeedsDisplay = true;
  190. if (container != null)
  191. container.ChildNeedsDisplay ();
  192. }
  193. /// <summary>
  194. /// Adds a subview to this view.
  195. /// </summary>
  196. /// <remarks>
  197. /// </remarks>
  198. public virtual void Add (View view)
  199. {
  200. if (view == null)
  201. return;
  202. if (subviews == null)
  203. subviews = new List<View> ();
  204. subviews.Add (view);
  205. view.container = this;
  206. if (view.CanFocus)
  207. CanFocus = true;
  208. SetNeedsDisplay ();
  209. }
  210. public void Add (params View [] views)
  211. {
  212. if (views == null)
  213. return;
  214. foreach (var view in views)
  215. Add (view);
  216. }
  217. /// <summary>
  218. /// Removes all the widgets from this container.
  219. /// </summary>
  220. /// <remarks>
  221. /// </remarks>
  222. public virtual void RemoveAll ()
  223. {
  224. if (subviews == null)
  225. return;
  226. while (subviews.Count > 0) {
  227. var view = subviews [0];
  228. Remove (view);
  229. subviews.RemoveAt (0);
  230. }
  231. }
  232. /// <summary>
  233. /// Removes a widget from this container.
  234. /// </summary>
  235. /// <remarks>
  236. /// </remarks>
  237. public virtual void Remove (View view)
  238. {
  239. if (view == null)
  240. return;
  241. SetNeedsDisplay ();
  242. var touched = view.Frame;
  243. subviews.Remove (view);
  244. view.container = null;
  245. if (subviews.Count < 1)
  246. this.CanFocus = false;
  247. foreach (var v in subviews) {
  248. if (v.Frame.IntersectsWith (touched))
  249. view.SetNeedsDisplay ();
  250. }
  251. }
  252. /// <summary>
  253. /// Clears the view region with the current color.
  254. /// </summary>
  255. /// <remarks>
  256. /// <para>
  257. /// This clears the entire region used by this view.
  258. /// </para>
  259. /// </remarks>
  260. public void Clear ()
  261. {
  262. var h = Frame.Height;
  263. var w = Frame.Width;
  264. for (int line = 0; line < h; line++) {
  265. Move (0, line);
  266. for (int col = 0; col < w; col++)
  267. Driver.AddCh (' ');
  268. }
  269. }
  270. /// <summary>
  271. /// Converts the (col,row) position from the view into a screen (col,row). The values are clamped to (0..ScreenDim-1)
  272. /// </summary>
  273. /// <param name="col">View-based column.</param>
  274. /// <param name="row">View-based row.</param>
  275. /// <param name="rcol">Absolute column, display relative.</param>
  276. /// <param name="rrow">Absolute row, display relative.</param>
  277. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  278. {
  279. // Computes the real row, col relative to the screen.
  280. rrow = row + frame.Y;
  281. rcol = col + frame.X;
  282. var ccontainer = container;
  283. while (ccontainer != null) {
  284. rrow += ccontainer.frame.Y;
  285. rcol += ccontainer.frame.X;
  286. ccontainer = ccontainer.container;
  287. }
  288. // The following ensures that the cursor is always in the screen boundaries.
  289. if (clipped) {
  290. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  291. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  292. }
  293. }
  294. /// <summary>
  295. /// Converts a point from screen coordinates into the view coordinate space.
  296. /// </summary>
  297. /// <returns>The mapped point.</returns>
  298. /// <param name="x">X screen-coordinate point.</param>
  299. /// <param name="y">Y screen-coordinate point.</param>
  300. public Point ScreenToView (int x, int y)
  301. {
  302. if (SuperView == null) {
  303. return new Point (x - Frame.X, y - frame.Y);
  304. } else {
  305. var parent = SuperView.ScreenToView (x, y);
  306. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  307. }
  308. }
  309. // Converts a rectangle in view coordinates to screen coordinates.
  310. Rect RectToScreen (Rect rect)
  311. {
  312. ViewToScreen (rect.X, rect.Y, out var x, out var y, clipped: false);
  313. return new Rect (x, y, rect.Width, rect.Height);
  314. }
  315. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  316. Rect ScreenClip (Rect rect)
  317. {
  318. var x = rect.X < 0 ? 0 : rect.X;
  319. var y = rect.Y < 0 ? 0 : rect.Y;
  320. var w = rect.X + rect.Width >= Driver.Cols ? Driver.Cols - rect.X : rect.Width;
  321. var h = rect.Y + rect.Height >= Driver.Rows ? Driver.Rows - rect.Y : rect.Height;
  322. return new Rect (x, y, w, h);
  323. }
  324. /// <summary>
  325. /// Draws a frame in the current view, clipped by the boundary of this view
  326. /// </summary>
  327. /// <param name="rect">Rectangular region for the frame to be drawn.</param>
  328. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  329. public void DrawFrame (Rect rect, bool fill = false)
  330. {
  331. var scrRect = RectToScreen (rect);
  332. var savedClip = Driver.Clip;
  333. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  334. Driver.DrawFrame (scrRect, fill);
  335. Driver.Clip = savedClip;
  336. }
  337. /// <summary>
  338. /// Utility function to draw strings that contain a hotkey
  339. /// </summary>
  340. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  341. /// <param name="hotColor">Hot color.</param>
  342. /// <param name="normalColor">Normal color.</param>
  343. public void DrawHotString (string text, Attribute hotColor, Attribute normalColor)
  344. {
  345. Driver.SetAttribute (normalColor);
  346. foreach (var c in text) {
  347. if (c == '_') {
  348. Driver.SetAttribute (hotColor);
  349. continue;
  350. }
  351. Driver.AddCh (c);
  352. Driver.SetAttribute (normalColor);
  353. }
  354. }
  355. /// <summary>
  356. /// Utility function to draw strings that contains a hotkey using a colorscheme and the "focused" state.
  357. /// </summary>
  358. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  359. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  360. /// <param name="scheme">The color scheme to use.</param>
  361. public void DrawHotString (string text, bool focused, ColorScheme scheme)
  362. {
  363. if (focused)
  364. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  365. else
  366. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  367. }
  368. /// <summary>
  369. /// This moves the cursor to the specified column and row in the view.
  370. /// </summary>
  371. /// <returns>The move.</returns>
  372. /// <param name="col">Col.</param>
  373. /// <param name="row">Row.</param>
  374. public void Move (int col, int row)
  375. {
  376. ViewToScreen (col, row, out var rcol, out var rrow);
  377. Driver.Move (rcol, rrow);
  378. }
  379. /// <summary>
  380. /// Positions the cursor in the right position based on the currently focused view in the chain.
  381. /// </summary>
  382. public virtual void PositionCursor ()
  383. {
  384. if (focused != null)
  385. focused.PositionCursor ();
  386. else
  387. Move (frame.X, frame.Y);
  388. }
  389. public override bool HasFocus {
  390. get {
  391. return base.HasFocus;
  392. }
  393. internal set {
  394. if (base.HasFocus != value)
  395. SetNeedsDisplay ();
  396. base.HasFocus = value;
  397. }
  398. }
  399. /// <summary>
  400. /// Returns the currently focused view inside this view, or null if nothing is focused.
  401. /// </summary>
  402. /// <value>The focused.</value>
  403. public View Focused => focused;
  404. public View MostFocused {
  405. get {
  406. if (Focused == null)
  407. return null;
  408. var most = Focused.MostFocused;
  409. if (most != null)
  410. return most;
  411. return Focused;
  412. }
  413. }
  414. /// <summary>
  415. /// Displays the specified character in the specified column and row.
  416. /// </summary>
  417. /// <param name="col">Col.</param>
  418. /// <param name="row">Row.</param>
  419. /// <param name="ch">Ch.</param>
  420. public void AddCh (int col, int row, int ch)
  421. {
  422. if (row < 0 || col < 0)
  423. return;
  424. if (row > frame.Height - 1 || col > frame.Width - 1)
  425. return;
  426. Move (col, row);
  427. Driver.AddCh (ch);
  428. }
  429. protected void ClearNeedsDisplay ()
  430. {
  431. NeedDisplay = Rect.Empty;
  432. childNeedsDisplay = false;
  433. }
  434. /// <summary>
  435. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  436. /// </summary>
  437. /// <remarks>
  438. /// The region argument is relative to the view itself.
  439. /// </remarks>
  440. public virtual void Redraw (Rect region)
  441. {
  442. var clipRect = new Rect (Point.Empty, frame.Size);
  443. if (subviews != null) {
  444. foreach (var view in subviews) {
  445. if (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay) {
  446. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  447. // TODO: optimize this by computing the intersection of region and view.Bounds
  448. view.Redraw (view.Bounds);
  449. }
  450. view.NeedDisplay = Rect.Empty;
  451. view.childNeedsDisplay = false;
  452. }
  453. }
  454. }
  455. ClearNeedsDisplay ();
  456. }
  457. /// <summary>
  458. /// Focuses the specified sub-view.
  459. /// </summary>
  460. /// <param name="view">View.</param>
  461. public void SetFocus (View view)
  462. {
  463. if (view == null)
  464. return;
  465. //Console.WriteLine ($"Request to focus {view}");
  466. if (!view.CanFocus)
  467. return;
  468. if (focused == view)
  469. return;
  470. // Make sure that this view is a subview
  471. View c;
  472. for (c = view.container; c != null; c = c.container)
  473. if (c == this)
  474. break;
  475. if (c == null)
  476. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  477. if (focused != null)
  478. focused.HasFocus = false;
  479. focused = view;
  480. focused.HasFocus = true;
  481. focused.EnsureFocus ();
  482. }
  483. public override bool ProcessKey (KeyEvent kb)
  484. {
  485. if (Focused?.ProcessKey (kb) == true)
  486. return true;
  487. return false;
  488. }
  489. public override bool ProcessHotKey (KeyEvent kb)
  490. {
  491. if (subviews == null || subviews.Count == 0)
  492. return false;
  493. foreach (var view in subviews)
  494. if (view.ProcessHotKey (kb))
  495. return true;
  496. return false;
  497. }
  498. public override bool ProcessColdKey (KeyEvent kb)
  499. {
  500. if (subviews == null || subviews.Count == 0)
  501. return false;
  502. foreach (var view in subviews)
  503. if (view.ProcessColdKey (kb))
  504. return true;
  505. return false;
  506. }
  507. /// <summary>
  508. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  509. /// </summary>
  510. public void EnsureFocus ()
  511. {
  512. if (focused == null)
  513. FocusFirst ();
  514. }
  515. /// <summary>
  516. /// Focuses the first focusable subview if one exists.
  517. /// </summary>
  518. public void FocusFirst ()
  519. {
  520. if (subviews == null) {
  521. SuperView.SetFocus (this);
  522. return;
  523. }
  524. foreach (var view in subviews) {
  525. if (view.CanFocus) {
  526. SetFocus (view);
  527. return;
  528. }
  529. }
  530. }
  531. /// <summary>
  532. /// Focuses the last focusable subview if one exists.
  533. /// </summary>
  534. public void FocusLast ()
  535. {
  536. if (subviews == null)
  537. return;
  538. for (int i = subviews.Count; i > 0;) {
  539. i--;
  540. View v = subviews [i];
  541. if (v.CanFocus) {
  542. SetFocus (v);
  543. return;
  544. }
  545. }
  546. }
  547. /// <summary>
  548. /// Focuses the previous view.
  549. /// </summary>
  550. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  551. public bool FocusPrev ()
  552. {
  553. if (subviews == null || subviews.Count == 0)
  554. return false;
  555. if (focused == null) {
  556. FocusLast ();
  557. return true;
  558. }
  559. int focused_idx = -1;
  560. for (int i = subviews.Count; i > 0;) {
  561. i--;
  562. View w = subviews [i];
  563. if (w.HasFocus) {
  564. if (w.FocusPrev ())
  565. return true;
  566. focused_idx = i;
  567. continue;
  568. }
  569. if (w.CanFocus && focused_idx != -1) {
  570. focused.HasFocus = false;
  571. if (w.CanFocus)
  572. w.FocusLast ();
  573. SetFocus (w);
  574. return true;
  575. }
  576. }
  577. if (focused_idx != -1) {
  578. FocusLast ();
  579. return true;
  580. }
  581. if (focused != null) {
  582. focused.HasFocus = false;
  583. focused = null;
  584. }
  585. return false;
  586. }
  587. /// <summary>
  588. /// Focuses the next view.
  589. /// </summary>
  590. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  591. public bool FocusNext ()
  592. {
  593. if (subviews == null || subviews.Count == 0)
  594. return false;
  595. if (focused == null) {
  596. FocusFirst ();
  597. return focused != null;
  598. }
  599. int n = subviews.Count;
  600. int focused_idx = -1;
  601. for (int i = 0; i < n; i++) {
  602. View w = subviews [i];
  603. if (w.HasFocus) {
  604. if (w.FocusNext ())
  605. return true;
  606. focused_idx = i;
  607. continue;
  608. }
  609. if (w.CanFocus && focused_idx != -1) {
  610. focused.HasFocus = false;
  611. if (w != null && w.CanFocus)
  612. w.FocusFirst ();
  613. SetFocus (w);
  614. return true;
  615. }
  616. }
  617. if (focused != null) {
  618. focused.HasFocus = false;
  619. focused = null;
  620. }
  621. return false;
  622. }
  623. public virtual void LayoutSubviews ()
  624. {
  625. }
  626. public override string ToString ()
  627. {
  628. return $"{GetType ().Name}({id})({Frame})";
  629. }
  630. }
  631. /// <summary>
  632. /// Toplevel views can be modally executed.
  633. /// </summary>
  634. /// <remarks>
  635. /// <para>
  636. /// Toplevels can be modally executing views, and they return control
  637. /// to the caller when the "Running" property is set to false.
  638. /// </para>
  639. /// </remarks>
  640. public class Toplevel : View {
  641. public bool Running;
  642. public Toplevel (Rect frame) : base (frame)
  643. {
  644. }
  645. public static Toplevel Create ()
  646. {
  647. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  648. }
  649. public override bool CanFocus {
  650. get => true;
  651. }
  652. public override bool ProcessKey (KeyEvent kb)
  653. {
  654. if (base.ProcessKey (kb))
  655. return true;
  656. switch (kb.Key) {
  657. case Key.ControlC:
  658. // TODO: stop current execution of this container
  659. break;
  660. case Key.ControlZ:
  661. Driver.Suspend ();
  662. return true;
  663. #if false
  664. case Key.F5:
  665. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  666. SetNeedsDisplay ();
  667. return true;
  668. #endif
  669. case Key.Tab:
  670. var old = Focused;
  671. if (!FocusNext ())
  672. FocusNext ();
  673. if (old != Focused) {
  674. old?.SetNeedsDisplay ();
  675. Focused?.SetNeedsDisplay ();
  676. }
  677. return true;
  678. case Key.BackTab:
  679. old = Focused;
  680. if (!FocusPrev ())
  681. FocusPrev ();
  682. if (old != Focused) {
  683. old?.SetNeedsDisplay ();
  684. Focused?.SetNeedsDisplay ();
  685. }
  686. return true;
  687. case Key.ControlL:
  688. Application.Refresh ();
  689. return true;
  690. }
  691. return false;
  692. }
  693. }
  694. /// <summary>
  695. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  696. /// </summary>
  697. public class Window : Toplevel, IEnumerable {
  698. View contentView;
  699. string title;
  700. public string Title {
  701. get => title;
  702. set {
  703. title = value;
  704. SetNeedsDisplay ();
  705. }
  706. }
  707. class ContentView : View {
  708. public ContentView (Rect frame) : base (frame) { }
  709. }
  710. /// <summary>
  711. /// Initializes a new instance of the <see cref="T:Terminal.Window"/> class with an optioanl title
  712. /// </summary>
  713. /// <param name="frame">Frame.</param>
  714. /// <param name="title">Title.</param>
  715. public Window (Rect frame, string title = null) : base (frame)
  716. {
  717. this.Title = title;
  718. var cFrame = new Rect (1, 1, frame.Width - 2, frame.Height - 2);
  719. contentView = new ContentView (cFrame);
  720. base.Add (contentView);
  721. }
  722. /// <summary>
  723. /// Enumerates the various views in the ContentView.
  724. /// </summary>
  725. /// <returns>The enumerator.</returns>
  726. public new IEnumerator GetEnumerator ()
  727. {
  728. return contentView.GetEnumerator ();
  729. }
  730. void DrawFrame ()
  731. {
  732. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), true);
  733. }
  734. /// <summary>
  735. /// Add the specified view to the ContentView.
  736. /// </summary>
  737. /// <param name="view">View to add to the window.</param>
  738. public override void Add (View view)
  739. {
  740. contentView.Add (view);
  741. }
  742. public override void Redraw (Rect bounds)
  743. {
  744. if (!NeedDisplay.IsEmpty) {
  745. Driver.SetAttribute (Colors.Base.Normal);
  746. DrawFrame ();
  747. if (HasFocus)
  748. Driver.SetAttribute (Colors.Dialog.Normal);
  749. var width = Frame.Width;
  750. if (Title != null && width > 4) {
  751. Move (1, 0);
  752. Driver.AddCh (' ');
  753. var str = Title.Length > width ? Title.Substring (0, width - 4) : Title;
  754. Driver.AddStr (str);
  755. Driver.AddCh (' ');
  756. }
  757. Driver.SetAttribute (Colors.Dialog.Normal);
  758. }
  759. contentView.Redraw (contentView.Bounds);
  760. ClearNeedsDisplay ();
  761. }
  762. #if false
  763. //
  764. // It does not look like the event is raised on clicked-drag
  765. // need to figure that out.
  766. //
  767. Point? dragPosition;
  768. public override bool MouseEvent(MouseEvent me)
  769. {
  770. if (me.Flags == MouseFlags.Button1Pressed){
  771. if (dragPosition.HasValue) {
  772. var dx = me.X - dragPosition.Value.X;
  773. var dy = me.Y - dragPosition.Value.Y;
  774. var nx = Frame.X + dx;
  775. var ny = Frame.Y + dy;
  776. if (nx < 0)
  777. nx = 0;
  778. if (ny < 0)
  779. ny = 0;
  780. Demo.ml2.Text = $"{dx},{dy}";
  781. dragPosition = new Point (me.X, me.Y);
  782. // TODO: optimize, only SetNeedsDisplay on the before/after regions.
  783. if (SuperView == null)
  784. Application.Refresh ();
  785. else
  786. SuperView.SetNeedsDisplay ();
  787. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  788. SetNeedsDisplay ();
  789. return true;
  790. } else {
  791. dragPosition = new Point (me.X, me.Y);
  792. Application.GrabMouse (this);
  793. Demo.ml2.Text = $"Starting at {dragPosition}";
  794. return true;
  795. }
  796. }
  797. if (me.Flags == MouseFlags.Button1Released) {
  798. Application.UngrabMouse ();
  799. dragPosition = null;
  800. //Driver.StopReportingMouseMoves ();
  801. }
  802. Demo.ml.Text = me.ToString ();
  803. return false;
  804. }
  805. #endif
  806. }
  807. /// <summary>
  808. /// The application driver for gui.cs
  809. /// </summary>
  810. /// <remarks>
  811. /// <para>
  812. /// You can hook up to the Iteration event to have your method
  813. /// invoked on each iteration of the mainloop.
  814. /// </para>
  815. /// <para>
  816. /// Creates a mainloop to process input events, handle timers and
  817. /// other sources of data. It is accessible via the MainLoop property.
  818. /// </para>
  819. /// <para>
  820. /// When invoked sets the SynchronizationContext to one that is tied
  821. /// to the mainloop, allowing user code to use async/await.
  822. /// </para>
  823. /// </remarks>
  824. public class Application {
  825. public static ConsoleDriver Driver = new CursesDriver ();
  826. public static Toplevel Top { get; private set; }
  827. public static Toplevel Current { get; private set; }
  828. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  829. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  830. /// <summary>
  831. /// This event is raised on each iteration of the
  832. /// main loop.
  833. /// </summary>
  834. /// <remarks>
  835. /// See also <see cref="Timeout"/>
  836. /// </remarks>
  837. static public event EventHandler Iteration;
  838. /// <summary>
  839. /// Returns a rectangle that is centered in the screen for the provided size.
  840. /// </summary>
  841. /// <returns>The centered rect.</returns>
  842. /// <param name="size">Size for the rectangle.</param>
  843. public static Rect MakeCenteredRect (Size size)
  844. {
  845. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  846. }
  847. //
  848. // provides the sync context set while executing code in gui.cs, to let
  849. // users use async/await on their code
  850. //
  851. class MainLoopSyncContext : SynchronizationContext {
  852. Mono.Terminal.MainLoop mainLoop;
  853. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  854. {
  855. this.mainLoop = mainLoop;
  856. }
  857. public override SynchronizationContext CreateCopy ()
  858. {
  859. return new MainLoopSyncContext (MainLoop);
  860. }
  861. public override void Post (SendOrPostCallback d, object state)
  862. {
  863. mainLoop.AddIdle (() => {
  864. d (state);
  865. return false;
  866. });
  867. }
  868. public override void Send (SendOrPostCallback d, object state)
  869. {
  870. mainLoop.Invoke (() => {
  871. d (state);
  872. });
  873. }
  874. }
  875. /// <summary>
  876. /// Initializes the Application
  877. /// </summary>
  878. public static void Init ()
  879. {
  880. if (Top != null)
  881. return;
  882. Driver.Init (TerminalResized);
  883. MainLoop = new Mono.Terminal.MainLoop ();
  884. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  885. Top = Toplevel.Create ();
  886. Current = Top;
  887. }
  888. public class RunState : IDisposable {
  889. internal RunState (Toplevel view)
  890. {
  891. Toplevel = view;
  892. }
  893. internal Toplevel Toplevel;
  894. public void Dispose ()
  895. {
  896. Dispose (true);
  897. GC.SuppressFinalize (this);
  898. }
  899. public virtual void Dispose (bool disposing)
  900. {
  901. if (Toplevel != null) {
  902. Application.End (Toplevel);
  903. Toplevel = null;
  904. }
  905. }
  906. }
  907. static void ProcessKeyEvent (KeyEvent ke)
  908. {
  909. if (Current.ProcessHotKey (ke))
  910. return;
  911. if (Current.ProcessKey (ke))
  912. return;
  913. // Process the key normally
  914. if (Current.ProcessColdKey (ke))
  915. return;
  916. }
  917. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  918. {
  919. var startFrame = start.Frame;
  920. if (!startFrame.Contains (x, y)) {
  921. resx = 0;
  922. resy = 0;
  923. return null;
  924. }
  925. if (start.Subviews != null){
  926. int count = start.Subviews.Count;
  927. if (count > 0) {
  928. var rx = x - startFrame.X;
  929. var ry = y - startFrame.Y;
  930. for (int i = count - 1; i >= 0; i--) {
  931. View v = start.Subviews [i];
  932. if (v.Frame.Contains (rx, ry)) {
  933. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  934. if (deep == null)
  935. return v;
  936. return deep;
  937. }
  938. }
  939. }
  940. }
  941. resx = x-startFrame.X;
  942. resy = y-startFrame.Y;
  943. return start;
  944. }
  945. static View mouseGrabView;
  946. /// <summary>
  947. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  948. /// </summary>
  949. /// <returns>The grab.</returns>
  950. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  951. public static void GrabMouse (View view)
  952. {
  953. if (view == null)
  954. return;
  955. mouseGrabView = view;
  956. }
  957. /// <summary>
  958. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  959. /// </summary>
  960. public static void UngrabMouse ()
  961. {
  962. mouseGrabView = null;
  963. }
  964. /// <summary>
  965. /// Merely a debugging aid to see the raw mouse events
  966. /// </summary>
  967. static public Action<MouseEvent> RootMouseEvent;
  968. static void ProcessMouseEvent (MouseEvent me)
  969. {
  970. RootMouseEvent?.Invoke (me);
  971. if (mouseGrabView != null) {
  972. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  973. var nme = new MouseEvent () {
  974. X = newxy.X,
  975. Y = newxy.Y,
  976. Flags = me.Flags
  977. };
  978. mouseGrabView.MouseEvent (me);
  979. return;
  980. }
  981. int rx, ry;
  982. var view = FindDeepestView (Current, me.X, me.Y, out rx, out ry);
  983. if (view != null) {
  984. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  985. return;
  986. var nme = new MouseEvent () {
  987. X = rx,
  988. Y = ry,
  989. Flags = me.Flags
  990. };
  991. // Should we bubbled up the event, if it is not handled?
  992. view.MouseEvent (nme);
  993. }
  994. }
  995. static public RunState Begin (Toplevel toplevel)
  996. {
  997. if (toplevel == null)
  998. throw new ArgumentNullException (nameof (toplevel));
  999. var rs = new RunState (toplevel);
  1000. Init ();
  1001. toplevels.Push (toplevel);
  1002. Current = toplevel;
  1003. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessMouseEvent);
  1004. toplevel.LayoutSubviews ();
  1005. toplevel.FocusFirst ();
  1006. Redraw (toplevel);
  1007. toplevel.PositionCursor ();
  1008. Driver.Refresh ();
  1009. return rs;
  1010. }
  1011. static public void End (RunState rs)
  1012. {
  1013. if (rs == null)
  1014. throw new ArgumentNullException (nameof (rs));
  1015. rs.Dispose ();
  1016. }
  1017. static void Shutdown ()
  1018. {
  1019. Driver.End ();
  1020. }
  1021. static void Redraw (View view)
  1022. {
  1023. view.Redraw (view.Bounds);
  1024. Driver.Refresh ();
  1025. }
  1026. static void Refresh (View view)
  1027. {
  1028. view.Redraw (view.Bounds);
  1029. Driver.Refresh ();
  1030. }
  1031. /// <summary>
  1032. /// Triggers a refresh of the entire display.
  1033. /// </summary>
  1034. public static void Refresh ()
  1035. {
  1036. Driver.RedrawTop ();
  1037. View last = null;
  1038. foreach (var v in toplevels.Reverse ()) {
  1039. v.SetNeedsDisplay ();
  1040. v.Redraw (v.Bounds);
  1041. last = v;
  1042. }
  1043. last?.PositionCursor ();
  1044. Driver.Refresh ();
  1045. }
  1046. internal static void End (View view)
  1047. {
  1048. if (toplevels.Peek () != view)
  1049. throw new ArgumentException ("The view that you end with must be balanced");
  1050. toplevels.Pop ();
  1051. if (toplevels.Count == 0)
  1052. Shutdown ();
  1053. else {
  1054. Current = toplevels.Peek () as Toplevel;
  1055. Refresh ();
  1056. }
  1057. }
  1058. /// <summary>
  1059. /// Runs the main loop for the created dialog
  1060. /// </summary>
  1061. /// <remarks>
  1062. /// Use the wait parameter to control whether this is a
  1063. /// blocking or non-blocking call.
  1064. /// </remarks>
  1065. public static void RunLoop (RunState state, bool wait = true)
  1066. {
  1067. if (state == null)
  1068. throw new ArgumentNullException (nameof (state));
  1069. if (state.Toplevel == null)
  1070. throw new ObjectDisposedException ("state");
  1071. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1072. if (MainLoop.EventsPending (wait)) {
  1073. MainLoop.MainIteration ();
  1074. if (Iteration != null)
  1075. Iteration (null, EventArgs.Empty);
  1076. } else if (wait == false)
  1077. return;
  1078. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1079. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1080. if (DebugDrawBounds)
  1081. DrawBounds (state.Toplevel);
  1082. state.Toplevel.PositionCursor ();
  1083. Driver.Refresh ();
  1084. }
  1085. }
  1086. }
  1087. public static bool DebugDrawBounds;
  1088. // Need to look into why this does not work properly.
  1089. static void DrawBounds (View v)
  1090. {
  1091. v.DrawFrame (v.Frame, false);
  1092. if (v.Subviews != null && v.Subviews.Count > 0)
  1093. foreach (var sub in v.Subviews)
  1094. DrawBounds (sub);
  1095. }
  1096. /// <summary>
  1097. /// Runs the application with the built-in toplevel view
  1098. /// </summary>
  1099. public static void Run ()
  1100. {
  1101. Run (Top);
  1102. }
  1103. /// <summary>
  1104. /// Runs the main loop on the given container.
  1105. /// </summary>
  1106. /// <remarks>
  1107. /// <para>
  1108. /// This method is used to start processing events
  1109. /// for the main application, but it is also used to
  1110. /// run modal dialog boxes.
  1111. /// </para>
  1112. /// <para>
  1113. /// To make a toplevel stop execution, set the "Running"
  1114. /// property to false.
  1115. /// </para>
  1116. /// </remarks>
  1117. public static void Run (Toplevel view)
  1118. {
  1119. var runToken = Begin (view);
  1120. RunLoop (runToken);
  1121. End (runToken);
  1122. }
  1123. /// <summary>
  1124. /// Stops running the most recent toplevel
  1125. /// </summary>
  1126. public static void RequestStop ()
  1127. {
  1128. var ct = Current as Toplevel;
  1129. Current.Running = false;
  1130. }
  1131. static void TerminalResized ()
  1132. {
  1133. foreach (var t in toplevels) {
  1134. t.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1135. }
  1136. }
  1137. }
  1138. }