View.cs 46 KB

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