View.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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 position (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. /// <summary>
  602. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  603. /// </summary>
  604. internal Rect ViewToScreen (Rect region)
  605. {
  606. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  607. return new Rect (x, y, region.Width, region.Height);
  608. }
  609. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  610. internal Rect ScreenClip (Rect regionScreen)
  611. {
  612. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  613. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  614. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  615. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  616. return new Rect (x, y, w, h);
  617. }
  618. /// <summary>
  619. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  620. /// </summary>
  621. /// <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>
  622. /// <remarks>
  623. /// <see cref="Bounds"/> is View-relative.
  624. /// </remarks>
  625. public Rect ClipToBounds ()
  626. {
  627. return SetClip (Bounds);
  628. }
  629. /// <summary>
  630. /// Sets the clip region to the specified view-relative region.
  631. /// </summary>
  632. /// <returns>The previous screen-relative clip region.</returns>
  633. /// <param name="region">View-relative clip region.</param>
  634. public Rect SetClip (Rect region)
  635. {
  636. var previous = Driver.Clip;
  637. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  638. return previous;
  639. }
  640. /// <summary>
  641. /// Draws a frame in the current view, clipped by the boundary of this view
  642. /// </summary>
  643. /// <param name="region">View-relative region for the frame to be drawn.</param>
  644. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  645. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  646. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  647. {
  648. var scrRect = ViewToScreen (region);
  649. var savedClip = ClipToBounds ();
  650. Driver.DrawFrame (scrRect, padding, fill);
  651. Driver.Clip = savedClip;
  652. }
  653. /// <summary>
  654. /// Utility function to draw strings that contain a hotkey.
  655. /// </summary>
  656. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  657. /// <param name="hotColor">Hot color.</param>
  658. /// <param name="normalColor">Normal color.</param>
  659. /// <remarks>
  660. /// The hotkey is any character following an underscore ('_') character.</remarks>
  661. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  662. {
  663. Driver.SetAttribute (normalColor);
  664. foreach (var rune in text) {
  665. if (rune == '_') {
  666. Driver.SetAttribute (hotColor);
  667. continue;
  668. }
  669. Driver.AddRune (rune);
  670. Driver.SetAttribute (normalColor);
  671. }
  672. }
  673. /// <summary>
  674. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  675. /// </summary>
  676. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  677. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  678. /// <param name="scheme">The color scheme to use.</param>
  679. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  680. {
  681. if (focused)
  682. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  683. else
  684. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  685. }
  686. /// <summary>
  687. /// This moves the cursor to the specified column and row in the view.
  688. /// </summary>
  689. /// <returns>The move.</returns>
  690. /// <param name="col">Col (view-relative).</param>
  691. /// <param name="row">Row (view-relative).</param>
  692. public void Move (int col, int row)
  693. {
  694. ViewToScreen (col, row, out var rcol, out var rrow);
  695. Driver.Move (rcol, rrow);
  696. }
  697. /// <summary>
  698. /// Positions the cursor in the right position based on the currently focused view in the chain.
  699. /// </summary>
  700. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  701. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  702. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  703. /// the last focused view. Views should make sure that they place the cursor
  704. /// in a visually sensible place.
  705. public virtual void PositionCursor ()
  706. {
  707. if (focused != null)
  708. focused.PositionCursor ();
  709. else
  710. Move (frame.X, frame.Y);
  711. }
  712. /// <inheritdoc cref="HasFocus"/>
  713. public override bool HasFocus {
  714. get {
  715. return base.HasFocus;
  716. }
  717. internal set {
  718. if (base.HasFocus != value)
  719. if (value)
  720. OnEnter ();
  721. else
  722. OnLeave ();
  723. SetNeedsDisplay ();
  724. base.HasFocus = value;
  725. // Remove focus down the chain of subviews if focus is removed
  726. if (!value && focused != null) {
  727. focused.OnLeave ();
  728. focused.HasFocus = false;
  729. focused = null;
  730. }
  731. }
  732. }
  733. /// <summary>
  734. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  735. /// </summary>
  736. public class FocusEventArgs : EventArgs {
  737. /// <summary>
  738. /// Constructs.
  739. /// </summary>
  740. public FocusEventArgs () { }
  741. /// <summary>
  742. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  743. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  744. /// </summary>
  745. public bool Handled { get; set; }
  746. }
  747. /// <inheritdoc cref="OnEnter"/>
  748. public override bool OnEnter ()
  749. {
  750. FocusEventArgs args = new FocusEventArgs ();
  751. Enter?.Invoke (this, args);
  752. if (args.Handled)
  753. return true;
  754. if (base.OnEnter ())
  755. return true;
  756. return false;
  757. }
  758. /// <inheritdoc cref="OnLeave"/>
  759. public override bool OnLeave ()
  760. {
  761. FocusEventArgs args = new FocusEventArgs ();
  762. Leave?.Invoke (this, args);
  763. if (args.Handled)
  764. return true;
  765. if (base.OnLeave ())
  766. return true;
  767. return false;
  768. }
  769. /// <summary>
  770. /// Returns the currently focused view inside this view, or null if nothing is focused.
  771. /// </summary>
  772. /// <value>The focused.</value>
  773. public View Focused => focused;
  774. /// <summary>
  775. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  776. /// </summary>
  777. /// <value>The most focused.</value>
  778. public View MostFocused {
  779. get {
  780. if (Focused == null)
  781. return null;
  782. var most = Focused.MostFocused;
  783. if (most != null)
  784. return most;
  785. return Focused;
  786. }
  787. }
  788. /// <summary>
  789. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  790. /// color scheme.
  791. /// </summary>
  792. public ColorScheme ColorScheme {
  793. get {
  794. if (colorScheme == null)
  795. return SuperView?.ColorScheme;
  796. return colorScheme;
  797. }
  798. set {
  799. colorScheme = value;
  800. }
  801. }
  802. ColorScheme colorScheme;
  803. /// <summary>
  804. /// Displays the specified character in the specified column and row of the View.
  805. /// </summary>
  806. /// <param name="col">Column (view-relative).</param>
  807. /// <param name="row">Row (view-relative).</param>
  808. /// <param name="ch">Ch.</param>
  809. public void AddRune (int col, int row, Rune ch)
  810. {
  811. if (row < 0 || col < 0)
  812. return;
  813. if (row > frame.Height - 1 || col > frame.Width - 1)
  814. return;
  815. Move (col, row);
  816. Driver.AddRune (ch);
  817. }
  818. /// <summary>
  819. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  820. /// </summary>
  821. protected void ClearNeedsDisplay ()
  822. {
  823. NeedDisplay = Rect.Empty;
  824. childNeedsDisplay = false;
  825. }
  826. /// <summary>
  827. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  828. /// </summary>
  829. /// <param name="bounds">The view-relative region to redraw.</param>
  830. /// <remarks>
  831. /// <para>
  832. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  833. /// the last color that was set globaly on the driver.
  834. /// </para>
  835. /// <para>
  836. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  837. /// larger than the <c>region</c> parameter.
  838. /// </para>
  839. /// </remarks>
  840. public virtual void Redraw (Rect bounds)
  841. {
  842. var clipRect = new Rect (Point.Empty, frame.Size);
  843. if (subviews != null) {
  844. foreach (var view in subviews) {
  845. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  846. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (bounds)) {
  847. // FIXED: optimize this by computing the intersection of region and view.Bounds
  848. if (view.layoutNeeded)
  849. view.LayoutSubviews ();
  850. Application.CurrentView = view;
  851. // Clip the sub-view
  852. var savedClip = ClipToBounds ();
  853. view.Redraw (view.Bounds);
  854. Driver.Clip = savedClip;
  855. }
  856. view.NeedDisplay = Rect.Empty;
  857. view.childNeedsDisplay = false;
  858. }
  859. }
  860. }
  861. ClearNeedsDisplay ();
  862. }
  863. /// <summary>
  864. /// Causes the specified subview to have focus.
  865. /// </summary>
  866. /// <param name="view">View.</param>
  867. public void SetFocus (View view)
  868. {
  869. if (view == null)
  870. return;
  871. //Console.WriteLine ($"Request to focus {view}");
  872. if (!view.CanFocus)
  873. return;
  874. if (focused == view)
  875. return;
  876. // Make sure that this view is a subview
  877. View c;
  878. for (c = view.container; c != null; c = c.container)
  879. if (c == this)
  880. break;
  881. if (c == null)
  882. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  883. if (focused != null)
  884. focused.HasFocus = false;
  885. focused = view;
  886. focused.HasFocus = true;
  887. focused.EnsureFocus ();
  888. // Send focus upwards
  889. SuperView?.SetFocus (this);
  890. }
  891. /// <summary>
  892. /// Defines the event arguments for <see cref="KeyEvent"/>
  893. /// </summary>
  894. public class KeyEventEventArgs : EventArgs {
  895. /// <summary>
  896. /// Constructs.
  897. /// </summary>
  898. /// <param name="ke"></param>
  899. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  900. /// <summary>
  901. /// The <see cref="KeyEvent"/> for the event.
  902. /// </summary>
  903. public KeyEvent KeyEvent { get; set; }
  904. /// <summary>
  905. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  906. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  907. /// </summary>
  908. public bool Handled { get; set; } = false;
  909. }
  910. /// <summary>
  911. /// Invoked when a character key is pressed and occurs after the key up event.
  912. /// </summary>
  913. public event EventHandler<KeyEventEventArgs> KeyPress;
  914. /// <inheritdoc cref="ProcessKey"/>
  915. public override bool ProcessKey (KeyEvent keyEvent)
  916. {
  917. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  918. KeyPress?.Invoke (this, args);
  919. if (args.Handled)
  920. return true;
  921. if (Focused?.ProcessKey (keyEvent) == true)
  922. return true;
  923. return false;
  924. }
  925. /// <inheritdoc cref="ProcessHotKey"/>
  926. public override bool ProcessHotKey (KeyEvent keyEvent)
  927. {
  928. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  929. KeyPress?.Invoke (this, args);
  930. if (args.Handled)
  931. return true;
  932. if (subviews == null || subviews.Count == 0)
  933. return false;
  934. foreach (var view in subviews)
  935. if (view.ProcessHotKey (keyEvent))
  936. return true;
  937. return false;
  938. }
  939. /// <inheritdoc cref="ProcessColdKey"/>
  940. public override bool ProcessColdKey (KeyEvent keyEvent)
  941. {
  942. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  943. KeyPress?.Invoke (this, args);
  944. if (args.Handled)
  945. return true;
  946. if (subviews == null || subviews.Count == 0)
  947. return false;
  948. foreach (var view in subviews)
  949. if (view.ProcessColdKey (keyEvent))
  950. return true;
  951. return false;
  952. }
  953. /// <summary>
  954. /// Invoked when a key is pressed
  955. /// </summary>
  956. public event EventHandler<KeyEventEventArgs> KeyDown;
  957. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  958. public override bool OnKeyDown (KeyEvent keyEvent)
  959. {
  960. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  961. KeyDown?.Invoke (this, args);
  962. if (args.Handled)
  963. return true;
  964. if (subviews == null || subviews.Count == 0)
  965. return false;
  966. foreach (var view in subviews)
  967. if (view.OnKeyDown (keyEvent))
  968. return true;
  969. return false;
  970. }
  971. /// <summary>
  972. /// Invoked when a key is released
  973. /// </summary>
  974. public event EventHandler<KeyEventEventArgs> KeyUp;
  975. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  976. public override bool OnKeyUp (KeyEvent keyEvent)
  977. {
  978. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  979. KeyUp?.Invoke (this, args);
  980. if (args.Handled)
  981. return true;
  982. if (subviews == null || subviews.Count == 0)
  983. return false;
  984. foreach (var view in subviews)
  985. if (view.OnKeyUp (keyEvent))
  986. return true;
  987. return false;
  988. }
  989. /// <summary>
  990. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  991. /// </summary>
  992. public void EnsureFocus ()
  993. {
  994. if (focused == null)
  995. if (FocusDirection == Direction.Forward)
  996. FocusFirst ();
  997. else
  998. FocusLast ();
  999. }
  1000. /// <summary>
  1001. /// Focuses the first focusable subview if one exists.
  1002. /// </summary>
  1003. public void FocusFirst ()
  1004. {
  1005. if (subviews == null) {
  1006. SuperView?.SetFocus (this);
  1007. return;
  1008. }
  1009. foreach (var view in subviews) {
  1010. if (view.CanFocus) {
  1011. SetFocus (view);
  1012. return;
  1013. }
  1014. }
  1015. }
  1016. /// <summary>
  1017. /// Focuses the last focusable subview if one exists.
  1018. /// </summary>
  1019. public void FocusLast ()
  1020. {
  1021. if (subviews == null) {
  1022. SuperView?.SetFocus (this);
  1023. return;
  1024. }
  1025. for (int i = subviews.Count; i > 0;) {
  1026. i--;
  1027. View v = subviews [i];
  1028. if (v.CanFocus) {
  1029. SetFocus (v);
  1030. return;
  1031. }
  1032. }
  1033. }
  1034. /// <summary>
  1035. /// Focuses the previous view.
  1036. /// </summary>
  1037. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1038. public bool FocusPrev ()
  1039. {
  1040. FocusDirection = Direction.Backward;
  1041. if (subviews == null || subviews.Count == 0)
  1042. return false;
  1043. if (focused == null) {
  1044. FocusLast ();
  1045. return focused != null;
  1046. }
  1047. int focused_idx = -1;
  1048. for (int i = subviews.Count; i > 0;) {
  1049. i--;
  1050. View w = subviews [i];
  1051. if (w.HasFocus) {
  1052. if (w.FocusPrev ())
  1053. return true;
  1054. focused_idx = i;
  1055. continue;
  1056. }
  1057. if (w.CanFocus && focused_idx != -1) {
  1058. focused.HasFocus = false;
  1059. if (w != null && w.CanFocus)
  1060. w.FocusLast ();
  1061. SetFocus (w);
  1062. return true;
  1063. }
  1064. }
  1065. if (focused != null) {
  1066. focused.HasFocus = false;
  1067. focused = null;
  1068. }
  1069. return false;
  1070. }
  1071. /// <summary>
  1072. /// Focuses the next view.
  1073. /// </summary>
  1074. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1075. public bool FocusNext ()
  1076. {
  1077. FocusDirection = Direction.Forward;
  1078. if (subviews == null || subviews.Count == 0)
  1079. return false;
  1080. if (focused == null) {
  1081. FocusFirst ();
  1082. return focused != null;
  1083. }
  1084. int n = subviews.Count;
  1085. int focused_idx = -1;
  1086. for (int i = 0; i < n; i++) {
  1087. View w = subviews [i];
  1088. if (w.HasFocus) {
  1089. if (w.FocusNext ())
  1090. return true;
  1091. focused_idx = i;
  1092. continue;
  1093. }
  1094. if (w.CanFocus && focused_idx != -1) {
  1095. focused.HasFocus = false;
  1096. if (w != null && w.CanFocus)
  1097. w.FocusFirst ();
  1098. SetFocus (w);
  1099. return true;
  1100. }
  1101. }
  1102. if (focused != null) {
  1103. focused.HasFocus = false;
  1104. focused = null;
  1105. }
  1106. return false;
  1107. }
  1108. /// <summary>
  1109. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1110. /// </summary>
  1111. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1112. /// <remarks>
  1113. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1114. /// </remarks>
  1115. internal void SetRelativeLayout (Rect hostFrame)
  1116. {
  1117. int w, h, _x, _y;
  1118. if (x is Pos.PosCenter) {
  1119. if (width == null)
  1120. w = hostFrame.Width;
  1121. else
  1122. w = width.Anchor (hostFrame.Width);
  1123. _x = x.Anchor (hostFrame.Width - w);
  1124. } else {
  1125. if (x == null)
  1126. _x = 0;
  1127. else
  1128. _x = x.Anchor (hostFrame.Width);
  1129. if (width == null)
  1130. w = hostFrame.Width;
  1131. else
  1132. w = width.Anchor (hostFrame.Width - _x);
  1133. }
  1134. if (y is Pos.PosCenter) {
  1135. if (height == null)
  1136. h = hostFrame.Height;
  1137. else
  1138. h = height.Anchor (hostFrame.Height);
  1139. _y = y.Anchor (hostFrame.Height - h);
  1140. } else {
  1141. if (y == null)
  1142. _y = 0;
  1143. else
  1144. _y = y.Anchor (hostFrame.Height);
  1145. if (height == null)
  1146. h = hostFrame.Height;
  1147. else
  1148. h = height.Anchor (hostFrame.Height - _y);
  1149. }
  1150. Frame = new Rect (_x, _y, w, h);
  1151. }
  1152. // https://en.wikipedia.org/wiki/Topological_sorting
  1153. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1154. {
  1155. var result = new List<View> ();
  1156. // Set of all nodes with no incoming edges
  1157. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1158. while (S.Any ()) {
  1159. // remove a node n from S
  1160. var n = S.First ();
  1161. S.Remove (n);
  1162. // add n to tail of L
  1163. if (n != this?.SuperView)
  1164. result.Add (n);
  1165. // for each node m with an edge e from n to m do
  1166. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1167. var m = e.To;
  1168. // remove edge e from the graph
  1169. edges.Remove (e);
  1170. // if m has no other incoming edges then
  1171. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1172. // insert m into S
  1173. S.Add (m);
  1174. }
  1175. }
  1176. }
  1177. // if graph has edges then
  1178. if (edges.Any ()) {
  1179. // return error (graph has at least one cycle)
  1180. return null;
  1181. } else {
  1182. // return L (a topologically sorted order)
  1183. return result;
  1184. }
  1185. }
  1186. /// <summary>
  1187. /// Invoked when a view starts executing or
  1188. /// when the dimensions of the view have changed, for example in
  1189. /// response to the container view or terminal resizing.
  1190. /// </summary>
  1191. public virtual void LayoutSubviews ()
  1192. {
  1193. if (!layoutNeeded)
  1194. return;
  1195. // Sort out the dependencies of the X, Y, Width, Height properties
  1196. var nodes = new HashSet<View> ();
  1197. var edges = new HashSet<(View, View)> ();
  1198. foreach (var v in InternalSubviews) {
  1199. nodes.Add (v);
  1200. if (v.LayoutStyle == LayoutStyle.Computed) {
  1201. if (v.X is Pos.PosView vX)
  1202. edges.Add ((vX.Target, v));
  1203. if (v.Y is Pos.PosView vY)
  1204. edges.Add ((vY.Target, v));
  1205. if (v.Width is Dim.DimView vWidth)
  1206. edges.Add ((vWidth.Target, v));
  1207. if (v.Height is Dim.DimView vHeight)
  1208. edges.Add ((vHeight.Target, v));
  1209. }
  1210. }
  1211. var ordered = TopologicalSort (nodes, edges);
  1212. if (ordered == null)
  1213. throw new Exception ("There is a recursive cycle in the relative Pos/Dim in the views of " + this);
  1214. foreach (var v in ordered) {
  1215. if (v.LayoutStyle == LayoutStyle.Computed)
  1216. v.SetRelativeLayout (Frame);
  1217. v.LayoutSubviews ();
  1218. v.layoutNeeded = false;
  1219. }
  1220. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1221. SetRelativeLayout (Frame);
  1222. }
  1223. layoutNeeded = false;
  1224. }
  1225. /// <inheritdoc cref="ToString"/>
  1226. public override string ToString ()
  1227. {
  1228. return $"{GetType ().Name}({Id})({Frame})";
  1229. }
  1230. /// <summary>
  1231. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1232. /// </summary>
  1233. public class MouseEventEventArgs : EventArgs {
  1234. /// <summary>
  1235. /// Constructs.
  1236. /// </summary>
  1237. /// <param name="me"></param>
  1238. public MouseEventEventArgs (MouseEvent me) => MouseEvent = me;
  1239. /// <summary>
  1240. /// The <see cref="MouseEvent"/> for the event.
  1241. /// </summary>
  1242. public MouseEvent MouseEvent { get; set; }
  1243. /// <summary>
  1244. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1245. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1246. /// </summary>
  1247. public bool Handled { get; set; }
  1248. }
  1249. /// <inheritdoc cref="OnMouseEnter(Gui.MouseEvent)"/>
  1250. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1251. {
  1252. MouseEventEventArgs args = new MouseEventEventArgs (mouseEvent);
  1253. MouseEnter?.Invoke (this, args);
  1254. if (args.Handled)
  1255. return true;
  1256. if (base.OnMouseEnter (mouseEvent))
  1257. return true;
  1258. return false;
  1259. }
  1260. /// <inheritdoc cref="OnMouseLeave(Gui.MouseEvent)"/>
  1261. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1262. {
  1263. MouseEventEventArgs args = new MouseEventEventArgs (mouseEvent);
  1264. MouseLeave?.Invoke (this, args);
  1265. if (args.Handled)
  1266. return true;
  1267. if (base.OnMouseLeave (mouseEvent))
  1268. return true;
  1269. return false;
  1270. }
  1271. /// <summary>
  1272. /// Method invoked when a mouse event is generated
  1273. /// </summary>
  1274. /// <param name="mouseEvent"></param>
  1275. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1276. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1277. {
  1278. MouseEventEventArgs args = new MouseEventEventArgs (mouseEvent);
  1279. MouseClick?.Invoke (this, args);
  1280. if (args.Handled)
  1281. return true;
  1282. if (MouseEvent (mouseEvent))
  1283. return true;
  1284. return false;
  1285. }
  1286. }
  1287. }