View.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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.Linq;
  19. using NStack;
  20. namespace Terminal.Gui {
  21. /// <summary>
  22. /// Determines the LayoutStyle for a view, if Absolute, during LayoutSubviews, the
  23. /// value from the Frame will be used, if the value is Computer, then the Frame
  24. /// will be updated from the X, Y Pos objects and the Width and Height Dim objects.
  25. /// </summary>
  26. public enum LayoutStyle {
  27. /// <summary>
  28. /// The position and size of the view are based on the Frame value.
  29. /// </summary>
  30. Absolute,
  31. /// <summary>
  32. /// The position and size of the view will be computed based on the
  33. /// X, Y, Width and Height properties and set on the Frame.
  34. /// </summary>
  35. Computed
  36. }
  37. /// <summary>
  38. /// 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.
  39. /// </summary>
  40. /// <remarks>
  41. /// <para>
  42. /// The View defines the base functionality for user interface elements in Terminal/gui.cs. Views
  43. /// can contain one or more subviews, can respond to user input and render themselves on the screen.
  44. /// </para>
  45. /// <para>
  46. /// Views can either be created with an absolute position, by calling the constructor that takes a
  47. /// Rect parameter to specify the absolute position and size (the Frame of the View) or by setting the
  48. /// X, Y, Width and Height properties on the view. Both approaches use coordinates that are relative
  49. /// to the container they are being added to.
  50. /// </para>
  51. /// <para>
  52. /// When you do not specify a Rect frame you can use the more flexible
  53. /// Dim and Pos objects that can dynamically update the position of a view.
  54. /// The X and Y properties are of type <see cref="Pos"/>
  55. /// and you can use either absolute positions, percentages or anchor
  56. /// points. The Width and Height properties are of type
  57. /// <see cref="Dim"/> and can use absolute position,
  58. /// percentages and anchors. These are useful as they will take
  59. /// care of repositioning your views if your view's frames are resized
  60. /// or if the terminal size changes.
  61. /// </para>
  62. /// <para>
  63. /// When you specify the Rect parameter to a view, you are setting the LayoutStyle to Absolute, and the
  64. /// view will always stay in the position that you placed it. To change the position change the
  65. /// Frame property to the new position.
  66. /// </para>
  67. /// <para>
  68. /// Subviews can be added to a View by calling the Add method. The container of a view is the
  69. /// Superview.
  70. /// </para>
  71. /// <para>
  72. /// Developers can call the SetNeedsDisplay method on the view to flag a region or the entire view
  73. /// as requiring to be redrawn.
  74. /// </para>
  75. /// <para>
  76. /// Views have a ColorScheme property that defines the default colors that subviews
  77. /// should use for rendering. This ensures that the views fit in the context where
  78. /// they are being used, and allows for themes to be plugged in. For example, the
  79. /// default colors for windows and toplevels uses a blue background, while it uses
  80. /// a white background for dialog boxes and a red background for errors.
  81. /// </para>
  82. /// <para>
  83. /// If a ColorScheme is not set on a view, the result of the ColorScheme is the
  84. /// value of the SuperView and the value might only be valid once a view has been
  85. /// added to a SuperView, so your subclasses should not rely on ColorScheme being
  86. /// set at construction time.
  87. /// </para>
  88. /// <para>
  89. /// Using ColorSchemes has the advantage that your application will work both
  90. /// in color as well as black and white displays.
  91. /// </para>
  92. /// <para>
  93. /// Views that are focusable should implement the PositionCursor to make sure that
  94. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  95. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  96. /// the last focused view. So views should make sure that they place the cursor
  97. /// in a visually sensible place.
  98. /// </para>
  99. /// <para>
  100. /// The metnod LayoutSubviews is invoked when the size or layout of a view has
  101. /// changed. The default processing system will keep the size and dimensions
  102. /// for views that use the LayoutKind.Absolute, and will recompute the
  103. /// frames for the vies that use LayoutKind.Computed.
  104. /// </para>
  105. /// </remarks>
  106. public class View : Responder, IEnumerable {
  107. internal enum Direction {
  108. Forward,
  109. Backward
  110. }
  111. View container = null;
  112. View focused = null;
  113. Direction focusDirection;
  114. /// <summary>
  115. /// Event fired when the view get focus.
  116. /// </summary>
  117. public event EventHandler Enter;
  118. /// <summary>
  119. /// Event fired when the view lost focus.
  120. /// </summary>
  121. public event EventHandler Leave;
  122. /// <summary>
  123. /// Event fired when the view receives the mouse event for the first time.
  124. /// </summary>
  125. public event EventHandler<MouseEvent> MouseEnter;
  126. /// <summary>
  127. /// Event fired when the view loses mouse event for the last time.
  128. /// </summary>
  129. public event EventHandler<MouseEvent> MouseLeave;
  130. internal Direction FocusDirection {
  131. get => SuperView?.FocusDirection ?? focusDirection;
  132. set {
  133. if (SuperView != null)
  134. SuperView.FocusDirection = value;
  135. else
  136. focusDirection = value;
  137. }
  138. }
  139. /// <summary>
  140. /// Points to the current driver in use by the view, it is a convenience property
  141. /// for simplifying the development of new views.
  142. /// </summary>
  143. public static ConsoleDriver Driver { get { return Application.Driver; } }
  144. static IList<View> empty = new List<View> (0).AsReadOnly ();
  145. // This is null, and allocated on demand.
  146. List<View> subviews;
  147. /// <summary>
  148. /// This returns a list of the subviews contained by this view.
  149. /// </summary>
  150. /// <value>The subviews.</value>
  151. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  152. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  153. // to make the same mistakes our users make when they poke at the Subviews.
  154. internal IList<View> InternalSubviews => subviews ?? empty;
  155. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  156. // The frame for the object
  157. Rect frame;
  158. /// <summary>
  159. /// Gets or sets an identifier for the view;
  160. /// </summary>
  161. /// <value>The identifier.</value>
  162. public ustring Id { get; set; } = "";
  163. /// <summary>
  164. /// Returns a value indicating if this View is currently on Top (Active)
  165. /// </summary>
  166. public bool IsCurrentTop {
  167. get {
  168. return Application.Current == this;
  169. }
  170. }
  171. /// <summary>
  172. /// Gets or sets a value indicating whether this <see cref="View"/> want mouse position reports.
  173. /// </summary>
  174. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  175. public virtual bool WantMousePositionReports { get; set; } = false;
  176. /// <summary>
  177. /// Gets or sets a value indicating whether this <see cref="View"/> want continuous button pressed event.
  178. /// </summary>
  179. public virtual bool WantContinuousButtonPressed { get; set; } = false;
  180. /// <summary>
  181. /// Gets or sets the frame for the view.
  182. /// </summary>
  183. /// <value>The frame.</value>
  184. /// <remarks>
  185. /// Altering the Frame of a view will trigger the redrawing of the
  186. /// view as well as the redrawing of the affected regions in the superview.
  187. /// </remarks>
  188. public virtual Rect Frame {
  189. get => frame;
  190. set {
  191. if (SuperView != null) {
  192. SuperView.SetNeedsDisplay (frame);
  193. SuperView.SetNeedsDisplay (value);
  194. }
  195. frame = value;
  196. SetNeedsLayout ();
  197. SetNeedsDisplay (frame);
  198. }
  199. }
  200. /// <summary>
  201. /// Gets an enumerator that enumerates the subviews in this view.
  202. /// </summary>
  203. /// <returns>The enumerator.</returns>
  204. public IEnumerator GetEnumerator ()
  205. {
  206. foreach (var v in InternalSubviews)
  207. yield return v;
  208. }
  209. LayoutStyle layoutStyle;
  210. /// <summary>
  211. /// Controls how the view's Frame is computed during the LayoutSubviews method, if Absolute, then
  212. /// LayoutSubviews does not change the Frame properties, otherwise the Frame is updated from the
  213. /// values in X, Y, Width and Height properties.
  214. /// </summary>
  215. /// <value>The layout style.</value>
  216. public LayoutStyle LayoutStyle {
  217. get => layoutStyle;
  218. set {
  219. layoutStyle = value;
  220. SetNeedsLayout ();
  221. }
  222. }
  223. /// <summary>
  224. /// 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.
  225. /// </summary>
  226. /// <value>The bounds.</value>
  227. public Rect Bounds {
  228. get => new Rect (Point.Empty, Frame.Size);
  229. set {
  230. Frame = new Rect (frame.Location, value.Size);
  231. }
  232. }
  233. Pos x, y;
  234. /// <summary>
  235. /// Gets or sets the X position for the view (the column). This is only used when the LayoutStyle is Computed, if the
  236. /// LayoutStyle is set to Absolute, this value is ignored.
  237. /// </summary>
  238. /// <value>The X Position.</value>
  239. public Pos X {
  240. get => x;
  241. set {
  242. x = value;
  243. SetNeedsLayout ();
  244. }
  245. }
  246. /// <summary>
  247. /// Gets or sets the Y position for the view (line). This is only used when the LayoutStyle is Computed, if the
  248. /// LayoutStyle is set to Absolute, this value is ignored.
  249. /// </summary>
  250. /// <value>The y position (line).</value>
  251. public Pos Y {
  252. get => y;
  253. set {
  254. y = value;
  255. SetNeedsLayout ();
  256. }
  257. }
  258. Dim width, height;
  259. /// <summary>
  260. /// Gets or sets the width for the view. This is only used when the LayoutStyle is Computed, if the
  261. /// LayoutStyle is set to Absolute, this value is ignored.
  262. /// </summary>
  263. /// <value>The width.</value>
  264. public Dim Width {
  265. get => width;
  266. set {
  267. width = value;
  268. SetNeedsLayout ();
  269. }
  270. }
  271. /// <summary>
  272. /// Gets or sets the height for the view. This is only used when the LayoutStyle is Computed, if the
  273. /// LayoutStyle is set to Absolute, this value is ignored.
  274. /// </summary>
  275. /// <value>The height.</value>
  276. public Dim Height {
  277. get => height;
  278. set {
  279. height = value;
  280. SetNeedsLayout ();
  281. }
  282. }
  283. /// <summary>
  284. /// Returns the container for this view, or null if this view has not been added to a container.
  285. /// </summary>
  286. /// <value>The super view.</value>
  287. public View SuperView => container;
  288. /// <summary>
  289. /// Initializes a new instance of the <see cref="View"/> class with the absolute
  290. /// dimensions specified in the frame. If you want to have Views that can be positioned with
  291. /// Pos and Dim properties on X, Y, Width and Height, use the empty constructor.
  292. /// </summary>
  293. /// <param name="frame">The region covered by this view.</param>
  294. public View (Rect frame)
  295. {
  296. this.Frame = frame;
  297. CanFocus = false;
  298. LayoutStyle = LayoutStyle.Absolute;
  299. }
  300. /// <summary>
  301. /// Initializes a new instance of the <see cref="View"/> class and sets the
  302. /// view up for Computed layout, which will use the values in X, Y, Width and Height to
  303. /// compute the View's Frame.
  304. /// </summary>
  305. public View ()
  306. {
  307. CanFocus = false;
  308. LayoutStyle = LayoutStyle.Computed;
  309. }
  310. /// <summary>
  311. /// Invoke to flag that this view needs to be redisplayed, by any code
  312. /// that alters the state of the view.
  313. /// </summary>
  314. public void SetNeedsDisplay ()
  315. {
  316. SetNeedsDisplay (Bounds);
  317. }
  318. internal bool layoutNeeded = true;
  319. internal void SetNeedsLayout ()
  320. {
  321. if (layoutNeeded)
  322. return;
  323. layoutNeeded = true;
  324. if (SuperView == null)
  325. return;
  326. SuperView.SetNeedsLayout ();
  327. }
  328. /// <summary>
  329. /// Flags the specified rectangle region on this view as needing to be repainted.
  330. /// </summary>
  331. /// <param name="region">The region that must be flagged for repaint.</param>
  332. public void SetNeedsDisplay (Rect region)
  333. {
  334. if (NeedDisplay == null || NeedDisplay.IsEmpty)
  335. NeedDisplay = region;
  336. else {
  337. var x = Math.Min (NeedDisplay.X, region.X);
  338. var y = Math.Min (NeedDisplay.Y, region.Y);
  339. var w = Math.Max (NeedDisplay.Width, region.Width);
  340. var h = Math.Max (NeedDisplay.Height, region.Height);
  341. NeedDisplay = new Rect (x, y, w, h);
  342. }
  343. if (container != null)
  344. container.ChildNeedsDisplay ();
  345. if (subviews == null)
  346. return;
  347. foreach (var view in subviews)
  348. if (view.Frame.IntersectsWith (region)) {
  349. var childRegion = Rect.Intersect (view.Frame, region);
  350. childRegion.X -= view.Frame.X;
  351. childRegion.Y -= view.Frame.Y;
  352. view.SetNeedsDisplay (childRegion);
  353. }
  354. }
  355. internal bool childNeedsDisplay;
  356. /// <summary>
  357. /// Flags this view for requiring the children views to be repainted.
  358. /// </summary>
  359. public void ChildNeedsDisplay ()
  360. {
  361. childNeedsDisplay = true;
  362. if (container != null)
  363. container.ChildNeedsDisplay ();
  364. }
  365. /// <summary>
  366. /// Adds a subview to this view.
  367. /// </summary>
  368. /// <remarks>
  369. /// </remarks>
  370. public virtual void Add (View view)
  371. {
  372. if (view == null)
  373. return;
  374. if (subviews == null)
  375. subviews = new List<View> ();
  376. subviews.Add (view);
  377. view.container = this;
  378. if (view.CanFocus)
  379. CanFocus = true;
  380. SetNeedsLayout ();
  381. SetNeedsDisplay ();
  382. }
  383. /// <summary>
  384. /// Adds the specified views to the view.
  385. /// </summary>
  386. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  387. public void Add (params View [] views)
  388. {
  389. if (views == null)
  390. return;
  391. foreach (var view in views)
  392. Add (view);
  393. }
  394. /// <summary>
  395. /// Removes all the widgets from this container.
  396. /// </summary>
  397. /// <remarks>
  398. /// </remarks>
  399. public virtual void RemoveAll ()
  400. {
  401. if (subviews == null)
  402. return;
  403. while (subviews.Count > 0) {
  404. Remove (subviews [0]);
  405. }
  406. }
  407. /// <summary>
  408. /// Removes a widget from this container.
  409. /// </summary>
  410. /// <remarks>
  411. /// </remarks>
  412. public virtual void Remove (View view)
  413. {
  414. if (view == null || subviews == null)
  415. return;
  416. SetNeedsLayout ();
  417. SetNeedsDisplay ();
  418. var touched = view.Frame;
  419. subviews.Remove (view);
  420. view.container = null;
  421. if (subviews.Count < 1)
  422. this.CanFocus = false;
  423. foreach (var v in subviews) {
  424. if (v.Frame.IntersectsWith (touched))
  425. view.SetNeedsDisplay ();
  426. }
  427. }
  428. void PerformActionForSubview (View subview, Action<View> action)
  429. {
  430. if (subviews.Contains (subview)) {
  431. action (subview);
  432. }
  433. SetNeedsDisplay ();
  434. subview.SetNeedsDisplay ();
  435. }
  436. /// <summary>
  437. /// Brings the specified subview to the front so it is drawn on top of any other views.
  438. /// </summary>
  439. /// <param name="subview">The subview to send to the front</param>
  440. /// <remarks>
  441. /// <seealso cref="SendSubviewToBack"/>.
  442. /// </remarks>
  443. public void BringSubviewToFront (View subview)
  444. {
  445. PerformActionForSubview (subview, x => {
  446. subviews.Remove (x);
  447. subviews.Add (x);
  448. });
  449. }
  450. /// <summary>
  451. /// Sends the specified subview to the front so it is the first view drawn
  452. /// </summary>
  453. /// <param name="subview">The subview to send to the front</param>
  454. /// <remarks>
  455. /// <seealso cref="BringSubviewToFront(View)"/>.
  456. /// </remarks>
  457. public void SendSubviewToBack (View subview)
  458. {
  459. PerformActionForSubview (subview, x => {
  460. subviews.Remove (x);
  461. subviews.Insert (0, subview);
  462. });
  463. }
  464. /// <summary>
  465. /// Moves the subview backwards in the hierarchy, only one step
  466. /// </summary>
  467. /// <param name="subview">The subview to send backwards</param>
  468. /// <remarks>
  469. /// If you want to send the view all the way to the back use SendSubviewToBack.
  470. /// </remarks>
  471. public void SendSubviewBackwards (View subview)
  472. {
  473. PerformActionForSubview (subview, x => {
  474. var idx = subviews.IndexOf (x);
  475. if (idx > 0) {
  476. subviews.Remove (x);
  477. subviews.Insert (idx - 1, x);
  478. }
  479. });
  480. }
  481. /// <summary>
  482. /// Moves the subview backwards in the hierarchy, only one step
  483. /// </summary>
  484. /// <param name="subview">The subview to send backwards</param>
  485. /// <remarks>
  486. /// If you want to send the view all the way to the back use SendSubviewToBack.
  487. /// </remarks>
  488. public void BringSubviewForward (View subview)
  489. {
  490. PerformActionForSubview (subview, x => {
  491. var idx = subviews.IndexOf (x);
  492. if (idx + 1 < subviews.Count) {
  493. subviews.Remove (x);
  494. subviews.Insert (idx + 1, x);
  495. }
  496. });
  497. }
  498. /// <summary>
  499. /// Clears the view region with the current color.
  500. /// </summary>
  501. /// <remarks>
  502. /// <para>
  503. /// This clears the entire region used by this view.
  504. /// </para>
  505. /// </remarks>
  506. public void Clear ()
  507. {
  508. var h = Frame.Height;
  509. var w = Frame.Width;
  510. for (int line = 0; line < h; line++) {
  511. Move (0, line);
  512. for (int col = 0; col < w; col++)
  513. Driver.AddRune (' ');
  514. }
  515. }
  516. /// <summary>
  517. /// Clears the specified rectangular region with the current color
  518. /// </summary>
  519. public void Clear (Rect r)
  520. {
  521. var h = r.Height;
  522. var w = r.Width;
  523. for (int line = r.Y; line < r.Y + h; line++) {
  524. Driver.Move (r.X, line);
  525. for (int col = 0; col < w; col++)
  526. Driver.AddRune (' ');
  527. }
  528. }
  529. /// <summary>
  530. /// Converts the (col,row) position from the view into a screen (col,row). The values are clamped to (0..ScreenDim-1)
  531. /// </summary>
  532. /// <param name="col">View-based column.</param>
  533. /// <param name="row">View-based row.</param>
  534. /// <param name="rcol">Absolute column, display relative.</param>
  535. /// <param name="rrow">Absolute row, display relative.</param>
  536. /// <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>
  537. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  538. {
  539. // Computes the real row, col relative to the screen.
  540. rrow = row + frame.Y;
  541. rcol = col + frame.X;
  542. var ccontainer = container;
  543. while (ccontainer != null) {
  544. rrow += ccontainer.frame.Y;
  545. rcol += ccontainer.frame.X;
  546. ccontainer = ccontainer.container;
  547. }
  548. // The following ensures that the cursor is always in the screen boundaries.
  549. if (clipped) {
  550. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  551. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  552. }
  553. }
  554. /// <summary>
  555. /// Converts a point from screen coordinates into the view coordinate space.
  556. /// </summary>
  557. /// <returns>The mapped point.</returns>
  558. /// <param name="x">X screen-coordinate point.</param>
  559. /// <param name="y">Y screen-coordinate point.</param>
  560. public Point ScreenToView (int x, int y)
  561. {
  562. if (SuperView == null) {
  563. return new Point (x - Frame.X, y - frame.Y);
  564. } else {
  565. var parent = SuperView.ScreenToView (x, y);
  566. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  567. }
  568. }
  569. // Converts a rectangle in view coordinates to screen coordinates.
  570. internal Rect RectToScreen (Rect rect)
  571. {
  572. ViewToScreen (rect.X, rect.Y, out var x, out var y, clipped: false);
  573. return new Rect (x, y, rect.Width, rect.Height);
  574. }
  575. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  576. internal Rect ScreenClip (Rect rect)
  577. {
  578. var x = rect.X < 0 ? 0 : rect.X;
  579. var y = rect.Y < 0 ? 0 : rect.Y;
  580. var w = rect.X + rect.Width >= Driver.Cols ? Driver.Cols - rect.X : rect.Width;
  581. var h = rect.Y + rect.Height >= Driver.Rows ? Driver.Rows - rect.Y : rect.Height;
  582. return new Rect (x, y, w, h);
  583. }
  584. /// <summary>
  585. /// Sets the Console driver's clip region to the current View's Bounds.
  586. /// </summary>
  587. /// <returns>The existing driver's Clip region, which can be then set by setting the Driver.Clip property.</returns>
  588. public Rect ClipToBounds ()
  589. {
  590. return SetClip (Bounds);
  591. }
  592. /// <summary>
  593. /// Sets the clipping region to the specified region, the region is view-relative
  594. /// </summary>
  595. /// <returns>The previous clip region.</returns>
  596. /// <param name="rect">Rectangle region to clip into, the region is view-relative.</param>
  597. public Rect SetClip (Rect rect)
  598. {
  599. var bscreen = RectToScreen (rect);
  600. var previous = Driver.Clip;
  601. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  602. return previous;
  603. }
  604. /// <summary>
  605. /// Draws a frame in the current view, clipped by the boundary of this view
  606. /// </summary>
  607. /// <param name="rect">Rectangular region for the frame to be drawn.</param>
  608. /// <param name="padding">The padding to add to the drawn frame.</param>
  609. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  610. public void DrawFrame (Rect rect, int padding = 0, bool fill = false)
  611. {
  612. var scrRect = RectToScreen (rect);
  613. var savedClip = Driver.Clip;
  614. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  615. Driver.DrawFrame (scrRect, padding, fill);
  616. Driver.Clip = savedClip;
  617. }
  618. /// <summary>
  619. /// Utility function to draw strings that contain a hotkey
  620. /// </summary>
  621. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  622. /// <param name="hotColor">Hot color.</param>
  623. /// <param name="normalColor">Normal color.</param>
  624. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  625. {
  626. Driver.SetAttribute (normalColor);
  627. foreach (var rune in text) {
  628. if (rune == '_') {
  629. Driver.SetAttribute (hotColor);
  630. continue;
  631. }
  632. Driver.AddRune (rune);
  633. Driver.SetAttribute (normalColor);
  634. }
  635. }
  636. /// <summary>
  637. /// Utility function to draw strings that contains a hotkey using a colorscheme and the "focused" state.
  638. /// </summary>
  639. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  640. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  641. /// <param name="scheme">The color scheme to use.</param>
  642. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  643. {
  644. if (focused)
  645. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  646. else
  647. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  648. }
  649. /// <summary>
  650. /// This moves the cursor to the specified column and row in the view.
  651. /// </summary>
  652. /// <returns>The move.</returns>
  653. /// <param name="col">Col.</param>
  654. /// <param name="row">Row.</param>
  655. public void Move (int col, int row)
  656. {
  657. ViewToScreen (col, row, out var rcol, out var rrow);
  658. Driver.Move (rcol, rrow);
  659. }
  660. /// <summary>
  661. /// Positions the cursor in the right position based on the currently focused view in the chain.
  662. /// </summary>
  663. public virtual void PositionCursor ()
  664. {
  665. if (focused != null)
  666. focused.PositionCursor ();
  667. else
  668. Move (frame.X, frame.Y);
  669. }
  670. /// <inheritdoc cref="HasFocus"/>
  671. public override bool HasFocus {
  672. get {
  673. return base.HasFocus;
  674. }
  675. internal set {
  676. if (base.HasFocus != value)
  677. if (value)
  678. OnEnter ();
  679. else
  680. OnLeave ();
  681. SetNeedsDisplay ();
  682. base.HasFocus = value;
  683. // Remove focus down the chain of subviews if focus is removed
  684. if (!value && focused != null) {
  685. focused.OnLeave ();
  686. focused.HasFocus = false;
  687. focused = null;
  688. }
  689. }
  690. }
  691. /// <inheritdoc cref="OnEnter"/>
  692. public override bool OnEnter ()
  693. {
  694. Enter?.Invoke (this, new EventArgs ());
  695. return base.OnEnter ();
  696. }
  697. /// <inheritdoc cref="OnLeave"/>
  698. public override bool OnLeave ()
  699. {
  700. Leave?.Invoke (this, new EventArgs ());
  701. return base.OnLeave ();
  702. }
  703. /// <summary>
  704. /// Returns the currently focused view inside this view, or null if nothing is focused.
  705. /// </summary>
  706. /// <value>The focused.</value>
  707. public View Focused => focused;
  708. /// <summary>
  709. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  710. /// </summary>
  711. /// <value>The most focused.</value>
  712. public View MostFocused {
  713. get {
  714. if (Focused == null)
  715. return null;
  716. var most = Focused.MostFocused;
  717. if (most != null)
  718. return most;
  719. return Focused;
  720. }
  721. }
  722. /// <summary>
  723. /// The color scheme for this view, if it is not defined, it returns the parent's
  724. /// color scheme.
  725. /// </summary>
  726. public ColorScheme ColorScheme {
  727. get {
  728. if (colorScheme == null)
  729. return SuperView?.ColorScheme;
  730. return colorScheme;
  731. }
  732. set {
  733. colorScheme = value;
  734. }
  735. }
  736. ColorScheme colorScheme;
  737. /// <summary>
  738. /// Displays the specified character in the specified column and row.
  739. /// </summary>
  740. /// <param name="col">Col.</param>
  741. /// <param name="row">Row.</param>
  742. /// <param name="ch">Ch.</param>
  743. public void AddRune (int col, int row, Rune ch)
  744. {
  745. if (row < 0 || col < 0)
  746. return;
  747. if (row > frame.Height - 1 || col > frame.Width - 1)
  748. return;
  749. Move (col, row);
  750. Driver.AddRune (ch);
  751. }
  752. /// <summary>
  753. /// Removes the SetNeedsDisplay and the ChildNeedsDisplay setting on this view.
  754. /// </summary>
  755. protected void ClearNeedsDisplay ()
  756. {
  757. NeedDisplay = Rect.Empty;
  758. childNeedsDisplay = false;
  759. }
  760. /// <summary>
  761. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  762. /// </summary>
  763. /// <param name="region">The region to redraw, this is relative to the view itself.</param>
  764. /// <remarks>
  765. /// <para>
  766. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  767. /// the last color that was set globaly on the driver.
  768. /// </para>
  769. /// </remarks>
  770. public virtual void Redraw (Rect region)
  771. {
  772. var clipRect = new Rect (Point.Empty, frame.Size);
  773. if (subviews != null) {
  774. foreach (var view in subviews) {
  775. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  776. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  777. // FIXED: optimize this by computing the intersection of region and view.Bounds
  778. if (view.layoutNeeded)
  779. view.LayoutSubviews ();
  780. Application.CurrentView = view;
  781. view.Redraw (view.Bounds);
  782. }
  783. view.NeedDisplay = Rect.Empty;
  784. view.childNeedsDisplay = false;
  785. }
  786. }
  787. }
  788. ClearNeedsDisplay ();
  789. }
  790. /// <summary>
  791. /// Focuses the specified sub-view.
  792. /// </summary>
  793. /// <param name="view">View.</param>
  794. public void SetFocus (View view)
  795. {
  796. if (view == null)
  797. return;
  798. //Console.WriteLine ($"Request to focus {view}");
  799. if (!view.CanFocus)
  800. return;
  801. if (focused == view)
  802. return;
  803. // Make sure that this view is a subview
  804. View c;
  805. for (c = view.container; c != null; c = c.container)
  806. if (c == this)
  807. break;
  808. if (c == null)
  809. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  810. if (focused != null)
  811. focused.HasFocus = false;
  812. focused = view;
  813. focused.HasFocus = true;
  814. focused.EnsureFocus ();
  815. // Send focus upwards
  816. SuperView?.SetFocus (this);
  817. }
  818. /// <summary>
  819. /// Specifies the event arguments for <see cref="KeyEvent"/>
  820. /// </summary>
  821. public class KeyEventEventArgs : EventArgs {
  822. /// <summary>
  823. /// Constructs.
  824. /// </summary>
  825. /// <param name="ke"></param>
  826. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  827. /// <summary>
  828. /// The <see cref="KeyEvent"/> for the event.
  829. /// </summary>
  830. public KeyEvent KeyEvent { get; set; }
  831. /// <summary>
  832. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  833. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  834. /// </summary>
  835. public bool Handled { get; set; } = false;
  836. }
  837. /// <summary>
  838. /// Invoked when a character key is pressed and occurs after the key up event.
  839. /// </summary>
  840. public event EventHandler<KeyEventEventArgs> KeyPress;
  841. /// <inheritdoc cref="ProcessKey"/>
  842. public override bool ProcessKey (KeyEvent keyEvent)
  843. {
  844. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  845. KeyPress?.Invoke (this, args);
  846. if (args.Handled)
  847. return true;
  848. if (Focused?.ProcessKey (keyEvent) == true)
  849. return true;
  850. return false;
  851. }
  852. /// <inheritdoc cref="ProcessHotKey"/>
  853. public override bool ProcessHotKey (KeyEvent keyEvent)
  854. {
  855. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  856. KeyPress?.Invoke (this, args);
  857. if (args.Handled)
  858. return true;
  859. if (subviews == null || subviews.Count == 0)
  860. return false;
  861. foreach (var view in subviews)
  862. if (view.ProcessHotKey (keyEvent))
  863. return true;
  864. return false;
  865. }
  866. /// <inheritdoc cref="ProcessColdKey"/>
  867. public override bool ProcessColdKey (KeyEvent keyEvent)
  868. {
  869. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  870. KeyPress?.Invoke (this, args);
  871. if (args.Handled)
  872. return true;
  873. if (subviews == null || subviews.Count == 0)
  874. return false;
  875. foreach (var view in subviews)
  876. if (view.ProcessColdKey (keyEvent))
  877. return true;
  878. return false;
  879. }
  880. /// <summary>
  881. /// Invoked when a key is pressed
  882. /// </summary>
  883. public event EventHandler<KeyEventEventArgs> KeyDown;
  884. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  885. public override bool OnKeyDown (KeyEvent keyEvent)
  886. {
  887. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  888. KeyDown?.Invoke (this, args);
  889. if (args.Handled)
  890. return true;
  891. if (subviews == null || subviews.Count == 0)
  892. return false;
  893. foreach (var view in subviews)
  894. if (view.OnKeyDown (keyEvent))
  895. return true;
  896. return false;
  897. }
  898. /// <summary>
  899. /// Invoked when a key is released
  900. /// </summary>
  901. public event EventHandler<KeyEventEventArgs> KeyUp;
  902. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  903. public override bool OnKeyUp (KeyEvent keyEvent)
  904. {
  905. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  906. KeyUp?.Invoke (this, args);
  907. if (args.Handled)
  908. return true;
  909. if (subviews == null || subviews.Count == 0)
  910. return false;
  911. foreach (var view in subviews)
  912. if (view.OnKeyUp (keyEvent))
  913. return true;
  914. return false;
  915. }
  916. /// <summary>
  917. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  918. /// </summary>
  919. public void EnsureFocus ()
  920. {
  921. if (focused == null)
  922. if (FocusDirection == Direction.Forward)
  923. FocusFirst ();
  924. else
  925. FocusLast ();
  926. }
  927. /// <summary>
  928. /// Focuses the first focusable subview if one exists.
  929. /// </summary>
  930. public void FocusFirst ()
  931. {
  932. if (subviews == null) {
  933. SuperView?.SetFocus (this);
  934. return;
  935. }
  936. foreach (var view in subviews) {
  937. if (view.CanFocus) {
  938. SetFocus (view);
  939. return;
  940. }
  941. }
  942. }
  943. /// <summary>
  944. /// Focuses the last focusable subview if one exists.
  945. /// </summary>
  946. public void FocusLast ()
  947. {
  948. if (subviews == null) {
  949. SuperView?.SetFocus (this);
  950. return;
  951. }
  952. for (int i = subviews.Count; i > 0;) {
  953. i--;
  954. View v = subviews [i];
  955. if (v.CanFocus) {
  956. SetFocus (v);
  957. return;
  958. }
  959. }
  960. }
  961. /// <summary>
  962. /// Focuses the previous view.
  963. /// </summary>
  964. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  965. public bool FocusPrev ()
  966. {
  967. FocusDirection = Direction.Backward;
  968. if (subviews == null || subviews.Count == 0)
  969. return false;
  970. if (focused == null) {
  971. FocusLast ();
  972. return focused != null;
  973. }
  974. int focused_idx = -1;
  975. for (int i = subviews.Count; i > 0;) {
  976. i--;
  977. View w = subviews [i];
  978. if (w.HasFocus) {
  979. if (w.FocusPrev ())
  980. return true;
  981. focused_idx = i;
  982. continue;
  983. }
  984. if (w.CanFocus && focused_idx != -1) {
  985. focused.HasFocus = false;
  986. if (w != null && w.CanFocus)
  987. w.FocusLast ();
  988. SetFocus (w);
  989. return true;
  990. }
  991. }
  992. if (focused != null) {
  993. focused.HasFocus = false;
  994. focused = null;
  995. }
  996. return false;
  997. }
  998. /// <summary>
  999. /// Focuses the next view.
  1000. /// </summary>
  1001. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1002. public bool FocusNext ()
  1003. {
  1004. FocusDirection = Direction.Forward;
  1005. if (subviews == null || subviews.Count == 0)
  1006. return false;
  1007. if (focused == null) {
  1008. FocusFirst ();
  1009. return focused != null;
  1010. }
  1011. int n = subviews.Count;
  1012. int focused_idx = -1;
  1013. for (int i = 0; i < n; i++) {
  1014. View w = subviews [i];
  1015. if (w.HasFocus) {
  1016. if (w.FocusNext ())
  1017. return true;
  1018. focused_idx = i;
  1019. continue;
  1020. }
  1021. if (w.CanFocus && focused_idx != -1) {
  1022. focused.HasFocus = false;
  1023. if (w != null && w.CanFocus)
  1024. w.FocusFirst ();
  1025. SetFocus (w);
  1026. return true;
  1027. }
  1028. }
  1029. if (focused != null) {
  1030. focused.HasFocus = false;
  1031. focused = null;
  1032. }
  1033. return false;
  1034. }
  1035. /// <summary>
  1036. /// Computes the RelativeLayout for the view, given the frame for its container.
  1037. /// </summary>
  1038. /// <param name="hostFrame">The Frame for the host.</param>
  1039. internal void RelativeLayout (Rect hostFrame)
  1040. {
  1041. int w, h, _x, _y;
  1042. if (x is Pos.PosCenter) {
  1043. if (width == null)
  1044. w = hostFrame.Width;
  1045. else
  1046. w = width.Anchor (hostFrame.Width);
  1047. _x = x.Anchor (hostFrame.Width - w);
  1048. } else {
  1049. if (x == null)
  1050. _x = 0;
  1051. else
  1052. _x = x.Anchor (hostFrame.Width);
  1053. if (width == null)
  1054. w = hostFrame.Width;
  1055. else
  1056. w = width.Anchor (hostFrame.Width - _x);
  1057. }
  1058. if (y is Pos.PosCenter) {
  1059. if (height == null)
  1060. h = hostFrame.Height;
  1061. else
  1062. h = height.Anchor (hostFrame.Height);
  1063. _y = y.Anchor (hostFrame.Height - h);
  1064. } else {
  1065. if (y == null)
  1066. _y = 0;
  1067. else
  1068. _y = y.Anchor (hostFrame.Height);
  1069. if (height == null)
  1070. h = hostFrame.Height;
  1071. else
  1072. h = height.Anchor (hostFrame.Height - _y);
  1073. }
  1074. Frame = new Rect (_x, _y, w, h);
  1075. // layoutNeeded = false;
  1076. }
  1077. // https://en.wikipedia.org/wiki/Topological_sorting
  1078. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1079. {
  1080. var result = new List<View> ();
  1081. // Set of all nodes with no incoming edges
  1082. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1083. while (S.Any ()) {
  1084. // remove a node n from S
  1085. var n = S.First ();
  1086. S.Remove (n);
  1087. // add n to tail of L
  1088. if (n != this?.SuperView)
  1089. result.Add (n);
  1090. // for each node m with an edge e from n to m do
  1091. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1092. var m = e.To;
  1093. // remove edge e from the graph
  1094. edges.Remove (e);
  1095. // if m has no other incoming edges then
  1096. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1097. // insert m into S
  1098. S.Add (m);
  1099. }
  1100. }
  1101. }
  1102. // if graph has edges then
  1103. if (edges.Any ()) {
  1104. // return error (graph has at least one cycle)
  1105. return null;
  1106. } else {
  1107. // return L (a topologically sorted order)
  1108. return result;
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// This virtual method is invoked when a view starts executing or
  1113. /// when the dimensions of the view have changed, for example in
  1114. /// response to the container view or terminal resizing.
  1115. /// </summary>
  1116. public virtual void LayoutSubviews ()
  1117. {
  1118. if (!layoutNeeded)
  1119. return;
  1120. // Sort out the dependencies of the X, Y, Width, Height properties
  1121. var nodes = new HashSet<View> ();
  1122. var edges = new HashSet<(View, View)> ();
  1123. foreach (var v in InternalSubviews) {
  1124. nodes.Add (v);
  1125. if (v.LayoutStyle == LayoutStyle.Computed) {
  1126. if (v.X is Pos.PosView vX)
  1127. edges.Add ((vX.Target, v));
  1128. if (v.Y is Pos.PosView vY)
  1129. edges.Add ((vY.Target, v));
  1130. if (v.Width is Dim.DimView vWidth)
  1131. edges.Add ((vWidth.Target, v));
  1132. if (v.Height is Dim.DimView vHeight)
  1133. edges.Add ((vHeight.Target, v));
  1134. }
  1135. }
  1136. var ordered = TopologicalSort (nodes, edges);
  1137. if (ordered == null)
  1138. throw new Exception ("There is a recursive cycle in the relative Pos/Dim in the views of " + this);
  1139. foreach (var v in ordered) {
  1140. if (v.LayoutStyle == LayoutStyle.Computed)
  1141. v.RelativeLayout (Frame);
  1142. v.LayoutSubviews ();
  1143. v.layoutNeeded = false;
  1144. }
  1145. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1146. RelativeLayout (Frame);
  1147. }
  1148. layoutNeeded = false;
  1149. }
  1150. /// <inheritdoc cref="ToString"/>
  1151. public override string ToString ()
  1152. {
  1153. return $"{GetType ().Name}({Id})({Frame})";
  1154. }
  1155. /// <inheritdoc cref="OnMouseEnter(Gui.MouseEvent)"/>
  1156. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1157. {
  1158. if (!base.OnMouseEnter (mouseEvent)) {
  1159. MouseEnter?.Invoke (this, mouseEvent);
  1160. return false;
  1161. }
  1162. return true;
  1163. }
  1164. /// <inheritdoc cref="OnMouseLeave(Gui.MouseEvent)"/>
  1165. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1166. {
  1167. if (!base.OnMouseLeave (mouseEvent)) {
  1168. MouseLeave?.Invoke (this, mouseEvent);
  1169. return false;
  1170. }
  1171. return true;
  1172. }
  1173. }
  1174. }