Core.cs 36 KB

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