View.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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. /// To flag a region of the View's <see cref="Bounds"/> to be redrawn call <see cref="SetNeedsDisplay(Rect)"/>. To flag the entire view
  76. /// for redraw call <see cref="SetNeedsDisplay()"/>.
  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 view's container (<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 of 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; the area inside of the view.
  239. /// </summary>
  240. /// <value>The bounds.</value>
  241. /// <remarks>
  242. /// <para>
  243. /// Updates to the Bounds update the <see cref="Frame"/>,
  244. /// and has the same side effects as updating the <see cref="Frame"/>.
  245. /// </para>
  246. /// <para>
  247. /// Because <see cref="Bounds"/> coordinates are relative to the upper-left corner of the <see cref="View"/>,
  248. /// the coordinates of the upper-left corner of the rectangle returned by this property are (0,0).
  249. /// Use this property to obtain the size and coordinates of the client area of the
  250. /// control for tasks such as drawing on the surface of the control.
  251. /// </para>
  252. /// </remarks>
  253. public Rect Bounds {
  254. get => new Rect (Point.Empty, Frame.Size);
  255. set {
  256. Frame = new Rect (frame.Location, value.Size);
  257. }
  258. }
  259. Pos x = Pos.At (0);
  260. Pos y = Pos.At (0);
  261. /// <summary>
  262. /// Gets or sets the X position for the view (the column). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  263. /// </summary>
  264. /// <value>The X Position.</value>
  265. /// <remarks>
  266. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  267. /// </remarks>
  268. public Pos X {
  269. get => x;
  270. set {
  271. x = value;
  272. SetNeedsLayout ();
  273. }
  274. }
  275. /// <summary>
  276. /// Gets or sets the Y position for the view (the row). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  277. /// </summary>
  278. /// <value>The y position (line).</value>
  279. /// <remarks>
  280. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  281. /// </remarks>
  282. public Pos Y {
  283. get => y;
  284. set {
  285. y = value;
  286. SetNeedsLayout ();
  287. }
  288. }
  289. Dim width, height;
  290. /// <summary>
  291. /// Gets or sets the width of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  292. /// </summary>
  293. /// <value>The width.</value>
  294. /// <remarks>
  295. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  296. /// </remarks>
  297. public Dim Width {
  298. get => width;
  299. set {
  300. width = value;
  301. SetNeedsLayout ();
  302. }
  303. }
  304. /// <summary>
  305. /// Gets or sets the height of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  306. /// </summary>
  307. /// <value>The height.</value>
  308. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  309. public Dim Height {
  310. get => height;
  311. set {
  312. height = value;
  313. SetNeedsLayout ();
  314. }
  315. }
  316. /// <summary>
  317. /// Returns the container for this view, or null if this view has not been added to a container.
  318. /// </summary>
  319. /// <value>The super view.</value>
  320. public View SuperView => container;
  321. /// <summary>
  322. /// Initializes a new instance of a <see cref="LayoutStyle.Absolute"/> <see cref="View"/> class with the absolute
  323. /// dimensions specified in the <c>frame</c> parameter.
  324. /// </summary>
  325. /// <param name="frame">The region covered by this view.</param>
  326. /// <remarks>
  327. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Absolute"/>. Use <see cref="View()"/> to
  328. /// initialize a View with <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>
  329. /// </remarks>
  330. public View (Rect frame)
  331. {
  332. this.Frame = frame;
  333. CanFocus = false;
  334. LayoutStyle = LayoutStyle.Absolute;
  335. }
  336. /// <summary>
  337. /// Initializes a new instance of <see cref="LayoutStyle.Computed"/> <see cref="View"/> class.
  338. /// </summary>
  339. /// <remarks>
  340. /// 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.
  341. /// </remarks>
  342. /// <remarks>
  343. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>.
  344. /// 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.
  345. /// </remarks>
  346. public View ()
  347. {
  348. CanFocus = false;
  349. LayoutStyle = LayoutStyle.Computed;
  350. Height = 0;
  351. Width = 0;
  352. }
  353. /// <summary>
  354. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  355. /// </summary>
  356. public void SetNeedsDisplay ()
  357. {
  358. SetNeedsDisplay (Bounds);
  359. }
  360. internal bool layoutNeeded = true;
  361. internal void SetNeedsLayout ()
  362. {
  363. if (layoutNeeded)
  364. return;
  365. layoutNeeded = true;
  366. if (SuperView == null)
  367. return;
  368. SuperView.SetNeedsLayout ();
  369. }
  370. /// <summary>
  371. /// Flags the view-relative region on this View as needing to be repainted.
  372. /// </summary>
  373. /// <param name="region">The view-relative region that must be flagged for repaint.</param>
  374. public void SetNeedsDisplay (Rect region)
  375. {
  376. if (NeedDisplay == null || NeedDisplay.IsEmpty)
  377. NeedDisplay = region;
  378. else {
  379. var x = Math.Min (NeedDisplay.X, region.X);
  380. var y = Math.Min (NeedDisplay.Y, region.Y);
  381. var w = Math.Max (NeedDisplay.Width, region.Width);
  382. var h = Math.Max (NeedDisplay.Height, region.Height);
  383. NeedDisplay = new Rect (x, y, w, h);
  384. }
  385. if (container != null)
  386. container.ChildNeedsDisplay ();
  387. if (subviews == null)
  388. return;
  389. foreach (var view in subviews)
  390. if (view.Frame.IntersectsWith (region)) {
  391. var childRegion = Rect.Intersect (view.Frame, region);
  392. childRegion.X -= view.Frame.X;
  393. childRegion.Y -= view.Frame.Y;
  394. view.SetNeedsDisplay (childRegion);
  395. }
  396. }
  397. internal bool childNeedsDisplay;
  398. /// <summary>
  399. /// Indicates that any child views (in the <see cref="Subviews"/> list) need to be repainted.
  400. /// </summary>
  401. public void ChildNeedsDisplay ()
  402. {
  403. childNeedsDisplay = true;
  404. if (container != null)
  405. container.ChildNeedsDisplay ();
  406. }
  407. /// <summary>
  408. /// Adds a subview (child) to this view.
  409. /// </summary>
  410. /// <remarks>
  411. /// 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"/>
  412. /// </remarks>
  413. public virtual void Add (View view)
  414. {
  415. if (view == null)
  416. return;
  417. if (subviews == null)
  418. subviews = new List<View> ();
  419. subviews.Add (view);
  420. view.container = this;
  421. if (view.CanFocus)
  422. CanFocus = true;
  423. SetNeedsLayout ();
  424. SetNeedsDisplay ();
  425. }
  426. /// <summary>
  427. /// Adds the specified views (children) to the view.
  428. /// </summary>
  429. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  430. /// <remarks>
  431. /// 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"/>
  432. /// </remarks>
  433. public void Add (params View [] views)
  434. {
  435. if (views == null)
  436. return;
  437. foreach (var view in views)
  438. Add (view);
  439. }
  440. /// <summary>
  441. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  442. /// </summary>
  443. public virtual void RemoveAll ()
  444. {
  445. if (subviews == null)
  446. return;
  447. while (subviews.Count > 0) {
  448. Remove (subviews [0]);
  449. }
  450. }
  451. /// <summary>
  452. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  453. /// </summary>
  454. /// <remarks>
  455. /// </remarks>
  456. public virtual void Remove (View view)
  457. {
  458. if (view == null || subviews == null)
  459. return;
  460. SetNeedsLayout ();
  461. SetNeedsDisplay ();
  462. var touched = view.Frame;
  463. subviews.Remove (view);
  464. view.container = null;
  465. if (subviews.Count < 1)
  466. this.CanFocus = false;
  467. foreach (var v in subviews) {
  468. if (v.Frame.IntersectsWith (touched))
  469. view.SetNeedsDisplay ();
  470. }
  471. }
  472. void PerformActionForSubview (View subview, Action<View> action)
  473. {
  474. if (subviews.Contains (subview)) {
  475. action (subview);
  476. }
  477. SetNeedsDisplay ();
  478. subview.SetNeedsDisplay ();
  479. }
  480. /// <summary>
  481. /// Brings the specified subview to the front so it is drawn on top of any other views.
  482. /// </summary>
  483. /// <param name="subview">The subview to send to the front</param>
  484. /// <remarks>
  485. /// <seealso cref="SendSubviewToBack"/>.
  486. /// </remarks>
  487. public void BringSubviewToFront (View subview)
  488. {
  489. PerformActionForSubview (subview, x => {
  490. subviews.Remove (x);
  491. subviews.Add (x);
  492. });
  493. }
  494. /// <summary>
  495. /// Sends the specified subview to the front so it is the first view drawn
  496. /// </summary>
  497. /// <param name="subview">The subview to send to the front</param>
  498. /// <remarks>
  499. /// <seealso cref="BringSubviewToFront(View)"/>.
  500. /// </remarks>
  501. public void SendSubviewToBack (View subview)
  502. {
  503. PerformActionForSubview (subview, x => {
  504. subviews.Remove (x);
  505. subviews.Insert (0, subview);
  506. });
  507. }
  508. /// <summary>
  509. /// Moves the subview backwards in the hierarchy, only one step
  510. /// </summary>
  511. /// <param name="subview">The subview to send backwards</param>
  512. /// <remarks>
  513. /// If you want to send the view all the way to the back use SendSubviewToBack.
  514. /// </remarks>
  515. public void SendSubviewBackwards (View subview)
  516. {
  517. PerformActionForSubview (subview, x => {
  518. var idx = subviews.IndexOf (x);
  519. if (idx > 0) {
  520. subviews.Remove (x);
  521. subviews.Insert (idx - 1, x);
  522. }
  523. });
  524. }
  525. /// <summary>
  526. /// Moves the subview backwards in the hierarchy, only one step
  527. /// </summary>
  528. /// <param name="subview">The subview to send backwards</param>
  529. /// <remarks>
  530. /// If you want to send the view all the way to the back use SendSubviewToBack.
  531. /// </remarks>
  532. public void BringSubviewForward (View subview)
  533. {
  534. PerformActionForSubview (subview, x => {
  535. var idx = subviews.IndexOf (x);
  536. if (idx + 1 < subviews.Count) {
  537. subviews.Remove (x);
  538. subviews.Insert (idx + 1, x);
  539. }
  540. });
  541. }
  542. /// <summary>
  543. /// Clears the view region with the current color.
  544. /// </summary>
  545. /// <remarks>
  546. /// <para>
  547. /// This clears the entire region used by this view.
  548. /// </para>
  549. /// </remarks>
  550. public void Clear ()
  551. {
  552. var h = Frame.Height;
  553. var w = Frame.Width;
  554. for (int line = 0; line < h; line++) {
  555. Move (0, line);
  556. for (int col = 0; col < w; col++)
  557. Driver.AddRune (' ');
  558. }
  559. }
  560. /// <summary>
  561. /// Clears the specified region with the current color.
  562. /// </summary>
  563. /// <remarks>
  564. /// </remarks>
  565. /// <param name="regionScreen">The screen-relative region to clear.</param>
  566. public void Clear (Rect regionScreen)
  567. {
  568. var h = regionScreen.Height;
  569. var w = regionScreen.Width;
  570. for (int line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  571. Driver.Move (regionScreen.X, line);
  572. for (int col = 0; col < w; col++)
  573. Driver.AddRune (' ');
  574. }
  575. }
  576. /// <summary>
  577. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  578. /// </summary>
  579. /// <param name="col">View-relative column.</param>
  580. /// <param name="row">View-relative row.</param>
  581. /// <param name="rcol">Absolute column; screen-relative.</param>
  582. /// <param name="rrow">Absolute row; screen-relative.</param>
  583. /// <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>
  584. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  585. {
  586. // Computes the real row, col relative to the screen.
  587. rrow = row + frame.Y;
  588. rcol = col + frame.X;
  589. var ccontainer = container;
  590. while (ccontainer != null) {
  591. rrow += ccontainer.frame.Y;
  592. rcol += ccontainer.frame.X;
  593. ccontainer = ccontainer.container;
  594. }
  595. // The following ensures that the cursor is always in the screen boundaries.
  596. if (clipped) {
  597. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  598. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  599. }
  600. }
  601. /// <summary>
  602. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  603. /// </summary>
  604. /// <returns>The mapped point.</returns>
  605. /// <param name="x">X screen-coordinate point.</param>
  606. /// <param name="y">Y screen-coordinate point.</param>
  607. public Point ScreenToView (int x, int y)
  608. {
  609. if (SuperView == null) {
  610. return new Point (x - Frame.X, y - frame.Y);
  611. } else {
  612. var parent = SuperView.ScreenToView (x, y);
  613. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  614. }
  615. }
  616. /// <summary>
  617. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  618. /// </summary>
  619. internal Rect ViewToScreen (Rect region)
  620. {
  621. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  622. return new Rect (x, y, region.Width, region.Height);
  623. }
  624. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  625. internal Rect ScreenClip (Rect regionScreen)
  626. {
  627. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  628. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  629. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  630. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  631. return new Rect (x, y, w, h);
  632. }
  633. /// <summary>
  634. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  635. /// </summary>
  636. /// <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>
  637. /// <remarks>
  638. /// <see cref="Bounds"/> is View-relative.
  639. /// </remarks>
  640. public Rect ClipToBounds ()
  641. {
  642. return SetClip (Bounds);
  643. }
  644. /// <summary>
  645. /// Sets the clip region to the specified view-relative region.
  646. /// </summary>
  647. /// <returns>The previous screen-relative clip region.</returns>
  648. /// <param name="region">View-relative clip region.</param>
  649. public Rect SetClip (Rect region)
  650. {
  651. var previous = Driver.Clip;
  652. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  653. return previous;
  654. }
  655. /// <summary>
  656. /// Draws a frame in the current view, clipped by the boundary of this view
  657. /// </summary>
  658. /// <param name="region">View-relative region for the frame to be drawn.</param>
  659. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  660. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  661. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  662. {
  663. var scrRect = ViewToScreen (region);
  664. var savedClip = ClipToBounds ();
  665. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  666. Driver.Clip = savedClip;
  667. }
  668. /// <summary>
  669. /// Utility function to draw strings that contain a hotkey.
  670. /// </summary>
  671. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  672. /// <param name="hotColor">Hot color.</param>
  673. /// <param name="normalColor">Normal color.</param>
  674. /// <remarks>
  675. /// The hotkey is any character following an underscore ('_') character.</remarks>
  676. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  677. {
  678. Driver.SetAttribute (normalColor);
  679. foreach (var rune in text) {
  680. if (rune == '_') {
  681. Driver.SetAttribute (hotColor);
  682. continue;
  683. }
  684. Driver.AddRune (rune);
  685. Driver.SetAttribute (normalColor);
  686. }
  687. }
  688. /// <summary>
  689. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  690. /// </summary>
  691. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  692. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  693. /// <param name="scheme">The color scheme to use.</param>
  694. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  695. {
  696. if (focused)
  697. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  698. else
  699. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  700. }
  701. /// <summary>
  702. /// This moves the cursor to the specified column and row in the view.
  703. /// </summary>
  704. /// <returns>The move.</returns>
  705. /// <param name="col">Col (view-relative).</param>
  706. /// <param name="row">Row (view-relative).</param>
  707. public void Move (int col, int row)
  708. {
  709. ViewToScreen (col, row, out var rcol, out var rrow);
  710. Driver.Move (rcol, rrow);
  711. }
  712. /// <summary>
  713. /// Positions the cursor in the right position based on the currently focused view in the chain.
  714. /// </summary>
  715. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  716. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  717. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  718. /// the last focused view. Views should make sure that they place the cursor
  719. /// in a visually sensible place.
  720. public virtual void PositionCursor ()
  721. {
  722. if (focused != null)
  723. focused.PositionCursor ();
  724. else
  725. Move (frame.X, frame.Y);
  726. }
  727. /// <inheritdoc/>
  728. public override bool HasFocus {
  729. get {
  730. return base.HasFocus;
  731. }
  732. internal set {
  733. if (base.HasFocus != value)
  734. if (value)
  735. OnEnter ();
  736. else
  737. OnLeave ();
  738. SetNeedsDisplay ();
  739. base.HasFocus = value;
  740. // Remove focus down the chain of subviews if focus is removed
  741. if (!value && focused != null) {
  742. focused.OnLeave ();
  743. focused.HasFocus = false;
  744. focused = null;
  745. }
  746. }
  747. }
  748. /// <summary>
  749. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  750. /// </summary>
  751. public class FocusEventArgs : EventArgs {
  752. /// <summary>
  753. /// Constructs.
  754. /// </summary>
  755. public FocusEventArgs () { }
  756. /// <summary>
  757. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  758. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  759. /// </summary>
  760. public bool Handled { get; set; }
  761. }
  762. /// <inheritdoc/>
  763. public override bool OnEnter ()
  764. {
  765. FocusEventArgs args = new FocusEventArgs ();
  766. Enter?.Invoke (this, args);
  767. if (args.Handled)
  768. return true;
  769. if (base.OnEnter ())
  770. return true;
  771. return false;
  772. }
  773. /// <inheritdoc/>
  774. public override bool OnLeave ()
  775. {
  776. FocusEventArgs args = new FocusEventArgs ();
  777. Leave?.Invoke (this, args);
  778. if (args.Handled)
  779. return true;
  780. if (base.OnLeave ())
  781. return true;
  782. return false;
  783. }
  784. /// <summary>
  785. /// Returns the currently focused view inside this view, or null if nothing is focused.
  786. /// </summary>
  787. /// <value>The focused.</value>
  788. public View Focused => focused;
  789. /// <summary>
  790. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  791. /// </summary>
  792. /// <value>The most focused.</value>
  793. public View MostFocused {
  794. get {
  795. if (Focused == null)
  796. return null;
  797. var most = Focused.MostFocused;
  798. if (most != null)
  799. return most;
  800. return Focused;
  801. }
  802. }
  803. /// <summary>
  804. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  805. /// color scheme.
  806. /// </summary>
  807. public ColorScheme ColorScheme {
  808. get {
  809. if (colorScheme == null)
  810. return SuperView?.ColorScheme;
  811. return colorScheme;
  812. }
  813. set {
  814. colorScheme = value;
  815. }
  816. }
  817. ColorScheme colorScheme;
  818. /// <summary>
  819. /// Displays the specified character in the specified column and row of the View.
  820. /// </summary>
  821. /// <param name="col">Column (view-relative).</param>
  822. /// <param name="row">Row (view-relative).</param>
  823. /// <param name="ch">Ch.</param>
  824. public void AddRune (int col, int row, Rune ch)
  825. {
  826. if (row < 0 || col < 0)
  827. return;
  828. if (row > frame.Height - 1 || col > frame.Width - 1)
  829. return;
  830. Move (col, row);
  831. Driver.AddRune (ch);
  832. }
  833. /// <summary>
  834. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  835. /// </summary>
  836. protected void ClearNeedsDisplay ()
  837. {
  838. NeedDisplay = Rect.Empty;
  839. childNeedsDisplay = false;
  840. }
  841. /// <summary>
  842. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  843. /// </summary>
  844. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  845. /// <remarks>
  846. /// <para>
  847. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  848. /// </para>
  849. /// <para>
  850. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  851. /// the last color that was set globaly on the driver.
  852. /// </para>
  853. /// <para>
  854. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  855. /// larger than the <c>region</c> parameter.
  856. /// </para>
  857. /// </remarks>
  858. public virtual void Redraw (Rect bounds)
  859. {
  860. var clipRect = new Rect (Point.Empty, frame.Size);
  861. // Invoke DrawContentEvent
  862. OnDrawContent (bounds);
  863. if (subviews != null) {
  864. foreach (var view in subviews) {
  865. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  866. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (bounds)) {
  867. // FIXED: optimize this by computing the intersection of region and view.Bounds
  868. if (view.layoutNeeded)
  869. view.LayoutSubviews ();
  870. Application.CurrentView = view;
  871. // Clip the sub-view
  872. var savedClip = ClipToBounds ();
  873. // Draw the subview
  874. // Use the view's bounds (view-relative; Location will always be (0,0) because
  875. view.Redraw (view.Bounds);
  876. // Undo the clip
  877. Driver.Clip = savedClip;
  878. }
  879. view.NeedDisplay = Rect.Empty;
  880. view.childNeedsDisplay = false;
  881. }
  882. }
  883. }
  884. ClearNeedsDisplay ();
  885. }
  886. /// <summary>
  887. /// Event invoked when the content area of the View is to be drawn.
  888. /// </summary>
  889. /// <remarks>
  890. /// <para>
  891. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  892. /// </para>
  893. /// <para>
  894. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  895. /// </para>
  896. /// </remarks>
  897. public event EventHandler<Rect> DrawContent;
  898. /// <summary>
  899. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  900. /// </summary>
  901. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  902. /// <remarks>
  903. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  904. /// </remarks>
  905. public virtual void OnDrawContent (Rect viewport)
  906. {
  907. DrawContent?.Invoke (this, viewport);
  908. }
  909. /// <summary>
  910. /// Causes the specified subview to have focus.
  911. /// </summary>
  912. /// <param name="view">View.</param>
  913. public void SetFocus (View view)
  914. {
  915. if (view == null)
  916. return;
  917. //Console.WriteLine ($"Request to focus {view}");
  918. if (!view.CanFocus)
  919. return;
  920. if (focused == view)
  921. return;
  922. // Make sure that this view is a subview
  923. View c;
  924. for (c = view.container; c != null; c = c.container)
  925. if (c == this)
  926. break;
  927. if (c == null)
  928. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  929. if (focused != null)
  930. focused.HasFocus = false;
  931. focused = view;
  932. focused.HasFocus = true;
  933. focused.EnsureFocus ();
  934. // Send focus upwards
  935. SuperView?.SetFocus (this);
  936. }
  937. /// <summary>
  938. /// Defines the event arguments for <see cref="KeyEvent"/>
  939. /// </summary>
  940. public class KeyEventEventArgs : EventArgs {
  941. /// <summary>
  942. /// Constructs.
  943. /// </summary>
  944. /// <param name="ke"></param>
  945. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  946. /// <summary>
  947. /// The <see cref="KeyEvent"/> for the event.
  948. /// </summary>
  949. public KeyEvent KeyEvent { get; set; }
  950. /// <summary>
  951. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  952. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  953. /// </summary>
  954. public bool Handled { get; set; } = false;
  955. }
  956. /// <summary>
  957. /// Invoked when a character key is pressed and occurs after the key up event.
  958. /// </summary>
  959. public event EventHandler<KeyEventEventArgs> KeyPress;
  960. /// <inheritdoc/>
  961. public override bool ProcessKey (KeyEvent keyEvent)
  962. {
  963. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  964. KeyPress?.Invoke (this, args);
  965. if (args.Handled)
  966. return true;
  967. if (Focused?.ProcessKey (keyEvent) == true)
  968. return true;
  969. return false;
  970. }
  971. /// <inheritdoc/>
  972. public override bool ProcessHotKey (KeyEvent keyEvent)
  973. {
  974. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  975. KeyPress?.Invoke (this, args);
  976. if (args.Handled)
  977. return true;
  978. if (subviews == null || subviews.Count == 0)
  979. return false;
  980. foreach (var view in subviews)
  981. if (view.SuperView.IsCurrentTop && view.ProcessHotKey (keyEvent))
  982. return true;
  983. return false;
  984. }
  985. /// <inheritdoc/>
  986. public override bool ProcessColdKey (KeyEvent keyEvent)
  987. {
  988. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  989. KeyPress?.Invoke (this, args);
  990. if (args.Handled)
  991. return true;
  992. if (subviews == null || subviews.Count == 0)
  993. return false;
  994. foreach (var view in subviews)
  995. if (view.SuperView.IsCurrentTop && view.ProcessColdKey (keyEvent))
  996. return true;
  997. return false;
  998. }
  999. /// <summary>
  1000. /// Invoked when a key is pressed
  1001. /// </summary>
  1002. public event EventHandler<KeyEventEventArgs> KeyDown;
  1003. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1004. public override bool OnKeyDown (KeyEvent keyEvent)
  1005. {
  1006. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1007. KeyDown?.Invoke (this, args);
  1008. if (args.Handled)
  1009. return true;
  1010. if (subviews == null || subviews.Count == 0)
  1011. return false;
  1012. foreach (var view in subviews)
  1013. if (view.SuperView.IsCurrentTop && view.OnKeyDown (keyEvent))
  1014. return true;
  1015. return false;
  1016. }
  1017. /// <summary>
  1018. /// Invoked when a key is released
  1019. /// </summary>
  1020. public event EventHandler<KeyEventEventArgs> KeyUp;
  1021. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1022. public override bool OnKeyUp (KeyEvent keyEvent)
  1023. {
  1024. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1025. KeyUp?.Invoke (this, args);
  1026. if (args.Handled)
  1027. return true;
  1028. if (subviews == null || subviews.Count == 0)
  1029. return false;
  1030. foreach (var view in subviews)
  1031. if (view.SuperView.IsCurrentTop && view.OnKeyUp (keyEvent))
  1032. return true;
  1033. return false;
  1034. }
  1035. /// <summary>
  1036. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1037. /// </summary>
  1038. public void EnsureFocus ()
  1039. {
  1040. if (focused == null)
  1041. if (FocusDirection == Direction.Forward)
  1042. FocusFirst ();
  1043. else
  1044. FocusLast ();
  1045. }
  1046. /// <summary>
  1047. /// Focuses the first focusable subview if one exists.
  1048. /// </summary>
  1049. public void FocusFirst ()
  1050. {
  1051. if (subviews == null) {
  1052. SuperView?.SetFocus (this);
  1053. return;
  1054. }
  1055. foreach (var view in subviews) {
  1056. if (view.CanFocus) {
  1057. SetFocus (view);
  1058. return;
  1059. }
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// Focuses the last focusable subview if one exists.
  1064. /// </summary>
  1065. public void FocusLast ()
  1066. {
  1067. if (subviews == null) {
  1068. SuperView?.SetFocus (this);
  1069. return;
  1070. }
  1071. for (int i = subviews.Count; i > 0;) {
  1072. i--;
  1073. View v = subviews [i];
  1074. if (v.CanFocus) {
  1075. SetFocus (v);
  1076. return;
  1077. }
  1078. }
  1079. }
  1080. /// <summary>
  1081. /// Focuses the previous view.
  1082. /// </summary>
  1083. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1084. public bool FocusPrev ()
  1085. {
  1086. FocusDirection = Direction.Backward;
  1087. if (subviews == null || subviews.Count == 0)
  1088. return false;
  1089. if (focused == null) {
  1090. FocusLast ();
  1091. return focused != null;
  1092. }
  1093. int focused_idx = -1;
  1094. for (int i = subviews.Count; i > 0;) {
  1095. i--;
  1096. View w = subviews [i];
  1097. if (w.HasFocus) {
  1098. if (w.FocusPrev ())
  1099. return true;
  1100. focused_idx = i;
  1101. continue;
  1102. }
  1103. if (w.CanFocus && focused_idx != -1) {
  1104. focused.HasFocus = false;
  1105. if (w != null && w.CanFocus)
  1106. w.FocusLast ();
  1107. SetFocus (w);
  1108. return true;
  1109. }
  1110. }
  1111. if (focused != null) {
  1112. focused.HasFocus = false;
  1113. focused = null;
  1114. }
  1115. return false;
  1116. }
  1117. /// <summary>
  1118. /// Focuses the next view.
  1119. /// </summary>
  1120. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1121. public bool FocusNext ()
  1122. {
  1123. FocusDirection = Direction.Forward;
  1124. if (subviews == null || subviews.Count == 0)
  1125. return false;
  1126. if (focused == null) {
  1127. FocusFirst ();
  1128. return focused != null;
  1129. }
  1130. int n = subviews.Count;
  1131. int focused_idx = -1;
  1132. for (int i = 0; i < n; i++) {
  1133. View w = subviews [i];
  1134. if (w.HasFocus) {
  1135. if (w.FocusNext ())
  1136. return true;
  1137. focused_idx = i;
  1138. continue;
  1139. }
  1140. if (w.CanFocus && focused_idx != -1) {
  1141. focused.HasFocus = false;
  1142. if (w != null && w.CanFocus)
  1143. w.FocusFirst ();
  1144. SetFocus (w);
  1145. return true;
  1146. }
  1147. }
  1148. if (focused != null) {
  1149. focused.HasFocus = false;
  1150. focused = null;
  1151. }
  1152. return false;
  1153. }
  1154. /// <summary>
  1155. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1156. /// </summary>
  1157. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1158. /// <remarks>
  1159. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1160. /// </remarks>
  1161. internal void SetRelativeLayout (Rect hostFrame)
  1162. {
  1163. int w, h, _x, _y;
  1164. if (x is Pos.PosCenter) {
  1165. if (width == null)
  1166. w = hostFrame.Width;
  1167. else
  1168. w = width.Anchor (hostFrame.Width);
  1169. _x = x.Anchor (hostFrame.Width - w);
  1170. } else {
  1171. if (x == null)
  1172. _x = 0;
  1173. else
  1174. _x = x.Anchor (hostFrame.Width);
  1175. if (width == null)
  1176. w = hostFrame.Width;
  1177. else
  1178. w = width.Anchor (hostFrame.Width - _x);
  1179. }
  1180. if (y is Pos.PosCenter) {
  1181. if (height == null)
  1182. h = hostFrame.Height;
  1183. else
  1184. h = height.Anchor (hostFrame.Height);
  1185. _y = y.Anchor (hostFrame.Height - h);
  1186. } else {
  1187. if (y == null)
  1188. _y = 0;
  1189. else
  1190. _y = y.Anchor (hostFrame.Height);
  1191. if (height == null)
  1192. h = hostFrame.Height;
  1193. else
  1194. h = height.Anchor (hostFrame.Height - _y);
  1195. }
  1196. Frame = new Rect (_x, _y, w, h);
  1197. }
  1198. // https://en.wikipedia.org/wiki/Topological_sorting
  1199. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1200. {
  1201. var result = new List<View> ();
  1202. // Set of all nodes with no incoming edges
  1203. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1204. while (S.Any ()) {
  1205. // remove a node n from S
  1206. var n = S.First ();
  1207. S.Remove (n);
  1208. // add n to tail of L
  1209. if (n != this?.SuperView)
  1210. result.Add (n);
  1211. // for each node m with an edge e from n to m do
  1212. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1213. var m = e.To;
  1214. // remove edge e from the graph
  1215. edges.Remove (e);
  1216. // if m has no other incoming edges then
  1217. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1218. // insert m into S
  1219. S.Add (m);
  1220. }
  1221. }
  1222. }
  1223. // if graph has edges then
  1224. if (edges.Any ()) {
  1225. // return error (graph has at least one cycle)
  1226. return null;
  1227. } else {
  1228. // return L (a topologically sorted order)
  1229. return result;
  1230. }
  1231. }
  1232. /// <summary>
  1233. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1234. /// </summary>
  1235. public class LayoutEventArgs : EventArgs {
  1236. /// <summary>
  1237. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1238. /// </summary>
  1239. public Rect OldBounds { get; set; }
  1240. }
  1241. /// <summary>
  1242. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1243. /// </summary>
  1244. /// <remarks>
  1245. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1246. /// </remarks>
  1247. public event EventHandler<LayoutEventArgs> LayoutComplete;
  1248. /// <summary>
  1249. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> after all sub-views have been laid out.
  1250. /// </summary>
  1251. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1252. {
  1253. LayoutComplete?.Invoke (this, args);
  1254. }
  1255. /// <summary>
  1256. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1257. /// response to the container view or terminal resizing.
  1258. /// </summary>
  1259. /// <remarks>
  1260. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1261. /// </remarks>
  1262. public virtual void LayoutSubviews ()
  1263. {
  1264. if (!layoutNeeded)
  1265. return;
  1266. Rect oldBounds = Bounds;
  1267. // Sort out the dependencies of the X, Y, Width, Height properties
  1268. var nodes = new HashSet<View> ();
  1269. var edges = new HashSet<(View, View)> ();
  1270. foreach (var v in InternalSubviews) {
  1271. nodes.Add (v);
  1272. if (v.LayoutStyle == LayoutStyle.Computed) {
  1273. if (v.X is Pos.PosView vX)
  1274. edges.Add ((vX.Target, v));
  1275. if (v.Y is Pos.PosView vY)
  1276. edges.Add ((vY.Target, v));
  1277. if (v.Width is Dim.DimView vWidth)
  1278. edges.Add ((vWidth.Target, v));
  1279. if (v.Height is Dim.DimView vHeight)
  1280. edges.Add ((vHeight.Target, v));
  1281. }
  1282. }
  1283. var ordered = TopologicalSort (nodes, edges);
  1284. if (ordered == null)
  1285. throw new Exception ("There is a recursive cycle in the relative Pos/Dim in the views of " + this);
  1286. foreach (var v in ordered) {
  1287. if (v.LayoutStyle == LayoutStyle.Computed)
  1288. v.SetRelativeLayout (Frame);
  1289. v.LayoutSubviews ();
  1290. v.layoutNeeded = false;
  1291. }
  1292. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1293. SetRelativeLayout (Frame);
  1294. }
  1295. layoutNeeded = false;
  1296. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1297. }
  1298. /// <summary>
  1299. /// Pretty prints the View
  1300. /// </summary>
  1301. /// <returns></returns>
  1302. public override string ToString ()
  1303. {
  1304. return $"{GetType ().Name}({Id})({Frame})";
  1305. }
  1306. /// <summary>
  1307. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1308. /// </summary>
  1309. public class MouseEventEventArgs : EventArgs {
  1310. /// <summary>
  1311. /// Constructs.
  1312. /// </summary>
  1313. /// <param name="me"></param>
  1314. public MouseEventEventArgs (MouseEvent me) => MouseEvent = me;
  1315. /// <summary>
  1316. /// The <see cref="MouseEvent"/> for the event.
  1317. /// </summary>
  1318. public MouseEvent MouseEvent { get; set; }
  1319. /// <summary>
  1320. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1321. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1322. /// </summary>
  1323. public bool Handled { get; set; }
  1324. }
  1325. /// <inheritdoc/>
  1326. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1327. {
  1328. MouseEventEventArgs args = new MouseEventEventArgs (mouseEvent);
  1329. MouseEnter?.Invoke (this, args);
  1330. if (args.Handled)
  1331. return true;
  1332. if (base.OnMouseEnter (mouseEvent))
  1333. return true;
  1334. return false;
  1335. }
  1336. /// <inheritdoc/>
  1337. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1338. {
  1339. MouseEventEventArgs args = new MouseEventEventArgs (mouseEvent);
  1340. MouseLeave?.Invoke (this, args);
  1341. if (args.Handled)
  1342. return true;
  1343. if (base.OnMouseLeave (mouseEvent))
  1344. return true;
  1345. return false;
  1346. }
  1347. /// <summary>
  1348. /// Method invoked when a mouse event is generated
  1349. /// </summary>
  1350. /// <param name="mouseEvent"></param>
  1351. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1352. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1353. {
  1354. MouseEventEventArgs args = new MouseEventEventArgs (mouseEvent);
  1355. MouseClick?.Invoke (this, args);
  1356. if (args.Handled)
  1357. return true;
  1358. if (MouseEvent (mouseEvent))
  1359. return true;
  1360. return false;
  1361. }
  1362. }
  1363. }