View.cs 43 KB

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