View.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  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.Diagnostics;
  17. using System.Linq;
  18. using NStack;
  19. namespace Terminal.Gui {
  20. /// <summary>
  21. /// Determines the LayoutStyle for a view, if Absolute, during LayoutSubviews, the
  22. /// value from the Frame will be used, if the value is Computed, then the Frame
  23. /// will be updated from the X, Y Pos objects and the Width and Height Dim objects.
  24. /// </summary>
  25. public enum LayoutStyle {
  26. /// <summary>
  27. /// The position and size of the view are based on the Frame value.
  28. /// </summary>
  29. Absolute,
  30. /// <summary>
  31. /// The position and size of the view will be computed based on the
  32. /// X, Y, Width and Height properties and set on the Frame.
  33. /// </summary>
  34. Computed
  35. }
  36. /// <summary>
  37. /// 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.
  38. /// </summary>
  39. /// <remarks>
  40. /// <para>
  41. /// The View defines the base functionality for user interface elements in Terminal.Gui. Views
  42. /// can contain one or more subviews, can respond to user input and render themselves on the screen.
  43. /// </para>
  44. /// <para>
  45. /// Views supports two layout styles: Absolute or Computed. The choice as to which layout style is used by the View
  46. /// is determined when the View is initizlied. To create a View using Absolute layout, call a constructor that takes a
  47. /// Rect parameter to specify the absolute position and size (the <c>View.<see cref="Frame "/></c>)/. To create a View
  48. /// using Computed layout use a constructor that does not take a Rect parametr and set the X, Y, Width and Height
  49. /// properties on the view. Both approaches use coordinates that are relative to the container they are being added to.
  50. /// </para>
  51. /// <para>
  52. /// To switch between Absolute and Computed layout, use the <see cref="LayoutStyle"/> property.
  53. /// </para>
  54. /// <para>
  55. /// Computed layout is more flexible and supports dynamic console apps where controls adjust layout
  56. /// as the terminal resizes or other Views change size or position. The X, Y, Width and Height
  57. /// properties are Dim and Pos objects that dynamically update the position of a view.
  58. /// The X and Y properties are of type <see cref="Pos"/>
  59. /// and you can use either absolute positions, percentages or anchor
  60. /// points. The Width and Height properties are of type
  61. /// <see cref="Dim"/> and can use absolute position,
  62. /// percentages and anchors. These are useful as they will take
  63. /// care of repositioning views when view's frames are resized or
  64. /// if the terminal size changes.
  65. /// </para>
  66. /// <para>
  67. /// Absolute layout requires specifying coordiantes and sizes of Views explicitly, and the
  68. /// View will typcialy stay in a fixed position and size. To change the position and size use the
  69. /// <see cref="Frame"/> property.
  70. /// </para>
  71. /// <para>
  72. /// Subviews (child views) can be added to a View by calling the <see cref="Add(View)"/> method.
  73. /// The container of a View can be accessed with the <see cref="SuperView"/> property.
  74. /// </para>
  75. /// <para>
  76. /// To flag a region of the View's <see cref="Bounds"/> to be redrawn call <see cref="SetNeedsDisplay(Rect)"/>. To flag the entire view
  77. /// for redraw call <see cref="SetNeedsDisplay()"/>.
  78. /// </para>
  79. /// <para>
  80. /// Views have a <see cref="ColorScheme"/> property that defines the default colors that subviews
  81. /// should use for rendering. This ensures that the views fit in the context where
  82. /// they are being used, and allows for themes to be plugged in. For example, the
  83. /// default colors for windows and toplevels uses a blue background, while it uses
  84. /// a white background for dialog boxes and a red background for errors.
  85. /// </para>
  86. /// <para>
  87. /// Subclasses should not rely on <see cref="ColorScheme"/> being
  88. /// set at construction time. If a <see cref="ColorScheme"/> is not set on a view, the view will inherit the
  89. /// value from its <see cref="SuperView"/> and the value might only be valid once a view has been
  90. /// added to a SuperView.
  91. /// </para>
  92. /// <para>
  93. /// By using <see cref="ColorScheme"/> applications will work both
  94. /// in color as well as black and white displays.
  95. /// </para>
  96. /// <para>
  97. /// Views that are focusable should implement the <see cref="PositionCursor"/> to make sure that
  98. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  99. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  100. /// the last focused view. So views should make sure that they place the cursor
  101. /// in a visually sensible place.
  102. /// </para>
  103. /// <para>
  104. /// The <see cref="LayoutSubviews"/> method is invoked when the size or layout of a view has
  105. /// changed. The default processing system will keep the size and dimensions
  106. /// for views that use the <see cref="LayoutStyle.Absolute"/>, and will recompute the
  107. /// frames for the vies that use <see cref="LayoutStyle.Computed"/>.
  108. /// </para>
  109. /// </remarks>
  110. public partial class View : Responder, IEnumerable {
  111. internal enum Direction {
  112. Forward,
  113. Backward
  114. }
  115. // container == SuperView
  116. View container = null;
  117. View focused = null;
  118. Direction focusDirection;
  119. TextFormatter viewText;
  120. /// <summary>
  121. /// Event fired when a subview is being added to this view.
  122. /// </summary>
  123. public Action<View> Added;
  124. /// <summary>
  125. /// Event fired when a subview is being removed from this view.
  126. /// </summary>
  127. public Action<View> Removed;
  128. /// <summary>
  129. /// Event fired when the view gets focus.
  130. /// </summary>
  131. public Action<FocusEventArgs> Enter;
  132. /// <summary>
  133. /// Event fired when the view looses focus.
  134. /// </summary>
  135. public Action<FocusEventArgs> Leave;
  136. /// <summary>
  137. /// Event fired when the view receives the mouse event for the first time.
  138. /// </summary>
  139. public Action<MouseEventArgs> MouseEnter;
  140. /// <summary>
  141. /// Event fired when the view receives a mouse event for the last time.
  142. /// </summary>
  143. public Action<MouseEventArgs> MouseLeave;
  144. /// <summary>
  145. /// Event fired when a mouse event is generated.
  146. /// </summary>
  147. public Action<MouseEventArgs> MouseClick;
  148. /// <summary>
  149. /// Gets or sets the HotKey defined for this view. A user pressing HotKey on the keyboard while this view has focus will cause the Clicked event to fire.
  150. /// </summary>
  151. public Key HotKey { get => viewText.HotKey; set => viewText.HotKey = value; }
  152. /// <summary>
  153. /// Gets or sets the specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  154. /// </summary>
  155. public Rune HotKeySpecifier { get => viewText.HotKeySpecifier; set => viewText.HotKeySpecifier = value; }
  156. internal Direction FocusDirection {
  157. get => SuperView?.FocusDirection ?? focusDirection;
  158. set {
  159. if (SuperView != null)
  160. SuperView.FocusDirection = value;
  161. else
  162. focusDirection = value;
  163. }
  164. }
  165. /// <summary>
  166. /// Points to the current driver in use by the view, it is a convenience property
  167. /// for simplifying the development of new views.
  168. /// </summary>
  169. public static ConsoleDriver Driver { get { return Application.Driver; } }
  170. static IList<View> empty = new List<View> (0).AsReadOnly ();
  171. // This is null, and allocated on demand.
  172. List<View> subviews;
  173. /// <summary>
  174. /// This returns a list of the subviews contained by this view.
  175. /// </summary>
  176. /// <value>The subviews.</value>
  177. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  178. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  179. // to make the same mistakes our users make when they poke at the Subviews.
  180. internal IList<View> InternalSubviews => subviews ?? empty;
  181. // This is null, and allocated on demand.
  182. List<View> tabIndexes;
  183. /// <summary>
  184. /// This returns a tab index list of the subviews contained by this view.
  185. /// </summary>
  186. /// <value>The tabIndexes.</value>
  187. public IList<View> TabIndexes => tabIndexes == null ? empty : tabIndexes.AsReadOnly ();
  188. int tabIndex = -1;
  189. /// <summary>
  190. /// Indicates the index of the current <see cref="View"/> from the <see cref="TabIndexes"/> list.
  191. /// </summary>
  192. public int TabIndex {
  193. get { return tabIndex; }
  194. set {
  195. if (!CanFocus || SuperView?.tabIndexes == null || SuperView?.tabIndexes.Count == 1 || tabIndex == value) {
  196. return;
  197. }
  198. tabIndex = value > SuperView.tabIndexes.Count - 1 ? SuperView.tabIndexes.Count - 1 : value < 0 ? 0 : value;
  199. SuperView.tabIndexes.Remove (this);
  200. SuperView.tabIndexes.Insert (tabIndex, this);
  201. }
  202. }
  203. bool tabStop = true;
  204. /// <summary>
  205. /// This only be <c>true</c> if the <see cref="CanFocus"/> is also <c>true</c> and the focus can be avoided by setting this to <c>false</c>
  206. /// </summary>
  207. public bool TabStop {
  208. get { return tabStop; }
  209. set {
  210. if (tabStop == value) {
  211. return;
  212. }
  213. tabStop = CanFocus && value;
  214. }
  215. }
  216. /// <inheritdoc/>
  217. public override bool CanFocus {
  218. get => base.CanFocus;
  219. set {
  220. if (base.CanFocus != value) {
  221. base.CanFocus = value;
  222. if (!value && tabIndex > -1) {
  223. tabIndex = -1;
  224. }
  225. if (!value && tabStop) {
  226. tabStop = false;
  227. }
  228. }
  229. }
  230. }
  231. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  232. // The frame for the object. Superview relative.
  233. Rect frame;
  234. /// <summary>
  235. /// Gets or sets an identifier for the view;
  236. /// </summary>
  237. /// <value>The identifier.</value>
  238. /// <remarks>The id should be unique across all Views that share a SuperView.</remarks>
  239. public ustring Id { get; set; } = "";
  240. /// <summary>
  241. /// Returns a value indicating if this View is currently on Top (Active)
  242. /// </summary>
  243. public bool IsCurrentTop {
  244. get {
  245. return Application.Current == this;
  246. }
  247. }
  248. /// <summary>
  249. /// Gets or sets a value indicating whether this <see cref="View"/> wants mouse position reports.
  250. /// </summary>
  251. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  252. public virtual bool WantMousePositionReports { get; set; } = false;
  253. /// <summary>
  254. /// Gets or sets a value indicating whether this <see cref="View"/> want continuous button pressed event.
  255. /// </summary>
  256. public virtual bool WantContinuousButtonPressed { get; set; } = false;
  257. /// <summary>
  258. /// Gets or sets the frame for the view. The frame is relative to the view's container (<see cref="SuperView"/>).
  259. /// </summary>
  260. /// <value>The frame.</value>
  261. /// <remarks>
  262. /// <para>
  263. /// Change the Frame when using the <see cref="LayoutStyle.Absolute"/> layout style to move or resize views.
  264. /// </para>
  265. /// <para>
  266. /// Altering the Frame of a view will trigger the redrawing of the
  267. /// view as well as the redrawing of the affected regions of the <see cref="SuperView"/>.
  268. /// </para>
  269. /// </remarks>
  270. public virtual Rect Frame {
  271. get => frame;
  272. set {
  273. if (SuperView != null) {
  274. SuperView.SetNeedsDisplay (frame);
  275. SuperView.SetNeedsDisplay (value);
  276. }
  277. frame = value;
  278. SetNeedsLayout ();
  279. SetNeedsDisplay (frame);
  280. }
  281. }
  282. /// <summary>
  283. /// Gets an enumerator that enumerates the subviews in this view.
  284. /// </summary>
  285. /// <returns>The enumerator.</returns>
  286. public IEnumerator GetEnumerator ()
  287. {
  288. foreach (var v in InternalSubviews)
  289. yield return v;
  290. }
  291. LayoutStyle layoutStyle;
  292. /// <summary>
  293. /// Controls how the View's <see cref="Frame"/> is computed during the LayoutSubviews method, if the style is set to <see cref="LayoutStyle.Absolute"/>,
  294. /// LayoutSubviews does not change the <see cref="Frame"/>. If the style is <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using
  295. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  296. /// </summary>
  297. /// <value>The layout style.</value>
  298. public LayoutStyle LayoutStyle {
  299. get => layoutStyle;
  300. set {
  301. layoutStyle = value;
  302. SetNeedsLayout ();
  303. }
  304. }
  305. /// <summary>
  306. /// The bounds represent the View-relative rectangle used for this view; the area inside of the view.
  307. /// </summary>
  308. /// <value>The bounds.</value>
  309. /// <remarks>
  310. /// <para>
  311. /// Updates to the Bounds update the <see cref="Frame"/>,
  312. /// and has the same side effects as updating the <see cref="Frame"/>.
  313. /// </para>
  314. /// <para>
  315. /// Because <see cref="Bounds"/> coordinates are relative to the upper-left corner of the <see cref="View"/>,
  316. /// the coordinates of the upper-left corner of the rectangle returned by this property are (0,0).
  317. /// Use this property to obtain the size and coordinates of the client area of the
  318. /// control for tasks such as drawing on the surface of the control.
  319. /// </para>
  320. /// </remarks>
  321. public Rect Bounds {
  322. get => new Rect (Point.Empty, Frame.Size);
  323. set {
  324. Frame = new Rect (frame.Location, value.Size);
  325. }
  326. }
  327. Pos x, y;
  328. /// <summary>
  329. /// Gets or sets the X position for the view (the column). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  330. /// </summary>
  331. /// <value>The X Position.</value>
  332. /// <remarks>
  333. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  334. /// </remarks>
  335. public Pos X {
  336. get => x;
  337. set {
  338. x = value;
  339. SetNeedsLayout ();
  340. SetNeedsDisplay (frame);
  341. }
  342. }
  343. /// <summary>
  344. /// Gets or sets the Y position for the view (the row). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  345. /// </summary>
  346. /// <value>The y position (line).</value>
  347. /// <remarks>
  348. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  349. /// </remarks>
  350. public Pos Y {
  351. get => y;
  352. set {
  353. y = value;
  354. SetNeedsLayout ();
  355. SetNeedsDisplay (frame);
  356. }
  357. }
  358. Dim width, height;
  359. /// <summary>
  360. /// Gets or sets the width of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  361. /// </summary>
  362. /// <value>The width.</value>
  363. /// <remarks>
  364. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  365. /// </remarks>
  366. public Dim Width {
  367. get => width;
  368. set {
  369. width = value;
  370. SetNeedsLayout ();
  371. SetNeedsDisplay (frame);
  372. }
  373. }
  374. /// <summary>
  375. /// Gets or sets the height of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  376. /// </summary>
  377. /// <value>The height.</value>
  378. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  379. public Dim Height {
  380. get => height;
  381. set {
  382. height = value;
  383. SetNeedsLayout ();
  384. SetNeedsDisplay (frame);
  385. }
  386. }
  387. /// <summary>
  388. /// Returns the container for this view, or null if this view has not been added to a container.
  389. /// </summary>
  390. /// <value>The super view.</value>
  391. public View SuperView => container;
  392. /// <summary>
  393. /// Initializes a new instance of a <see cref="LayoutStyle.Absolute"/> <see cref="View"/> class with the absolute
  394. /// dimensions specified in the <c>frame</c> parameter.
  395. /// </summary>
  396. /// <param name="frame">The region covered by this view.</param>
  397. /// <remarks>
  398. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Absolute"/>. Use <see cref="View()"/> to
  399. /// initialize a View with <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>
  400. /// </remarks>
  401. public View (Rect frame)
  402. {
  403. viewText = new TextFormatter ();
  404. this.Text = ustring.Empty;
  405. this.Frame = frame;
  406. LayoutStyle = LayoutStyle.Absolute;
  407. }
  408. /// <summary>
  409. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  410. /// </summary>
  411. /// <remarks>
  412. /// <para>
  413. /// 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.
  414. /// The <see cref="Label"/> will be created using <see cref="LayoutStyle.Computed"/>
  415. /// coordinates. The initial size (<see cref="View.Frame"/> will be
  416. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  417. /// </para>
  418. /// <para>
  419. /// If <c>Height</c> is greater than one, word wrapping is provided.
  420. /// </para>
  421. /// <para>
  422. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>.
  423. /// 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.
  424. /// </para>
  425. /// </remarks>
  426. public View () : this (text: string.Empty) { }
  427. /// <summary>
  428. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  429. /// </summary>
  430. /// <remarks>
  431. /// <para>
  432. /// The <see cref="View"/> will be created at the given
  433. /// coordinates with the given string. The size (<see cref="View.Frame"/> will be
  434. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  435. /// </para>
  436. /// <para>
  437. /// No line wrapping is provided.
  438. /// </para>
  439. /// </remarks>
  440. /// <param name="x">column to locate the Label.</param>
  441. /// <param name="y">row to locate the Label.</param>
  442. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  443. public View (int x, int y, ustring text) : this (TextFormatter.CalcRect (x, y, text), text) { }
  444. /// <summary>
  445. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  446. /// </summary>
  447. /// <remarks>
  448. /// <para>
  449. /// The <see cref="View"/> will be created at the given
  450. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  451. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  452. /// </para>
  453. /// <para>
  454. /// If <c>rect.Height</c> is greater than one, word wrapping is provided.
  455. /// </para>
  456. /// </remarks>
  457. /// <param name="rect">Location.</param>
  458. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  459. public View (Rect rect, ustring text) : this (rect)
  460. {
  461. viewText = new TextFormatter ();
  462. this.Text = text;
  463. }
  464. /// <summary>
  465. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  466. /// </summary>
  467. /// <remarks>
  468. /// <para>
  469. /// The <see cref="View"/> will be created using <see cref="LayoutStyle.Computed"/>
  470. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  471. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  472. /// </para>
  473. /// <para>
  474. /// If <c>Height</c> is greater than one, word wrapping is provided.
  475. /// </para>
  476. /// </remarks>
  477. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  478. public View (ustring text) : base ()
  479. {
  480. viewText = new TextFormatter ();
  481. this.Text = text;
  482. CanFocus = false;
  483. LayoutStyle = LayoutStyle.Computed;
  484. // BUGBUG: CalcRect doesn't account for line wrapping
  485. var r = TextFormatter.CalcRect (0, 0, text);
  486. x = Pos.At (0);
  487. y = Pos.At (0);
  488. Width = r.Width;
  489. Height = r.Height;
  490. }
  491. /// <summary>
  492. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  493. /// </summary>
  494. public void SetNeedsDisplay ()
  495. {
  496. SetNeedsDisplay (Bounds);
  497. }
  498. internal bool layoutNeeded = true;
  499. internal void SetNeedsLayout ()
  500. {
  501. if (layoutNeeded)
  502. return;
  503. layoutNeeded = true;
  504. if (SuperView == null)
  505. return;
  506. SuperView.SetNeedsLayout ();
  507. viewText.SetNeedsFormat ();
  508. }
  509. /// <summary>
  510. /// Flags the view-relative region on this View as needing to be repainted.
  511. /// </summary>
  512. /// <param name="region">The view-relative region that must be flagged for repaint.</param>
  513. public void SetNeedsDisplay (Rect region)
  514. {
  515. if (NeedDisplay == null || NeedDisplay.IsEmpty)
  516. NeedDisplay = region;
  517. else {
  518. var x = Math.Min (NeedDisplay.X, region.X);
  519. var y = Math.Min (NeedDisplay.Y, region.Y);
  520. var w = Math.Max (NeedDisplay.Width, region.Width);
  521. var h = Math.Max (NeedDisplay.Height, region.Height);
  522. NeedDisplay = new Rect (x, y, w, h);
  523. }
  524. if (container != null)
  525. container.ChildNeedsDisplay ();
  526. if (subviews == null)
  527. return;
  528. foreach (var view in subviews)
  529. if (view.Frame.IntersectsWith (region)) {
  530. var childRegion = Rect.Intersect (view.Frame, region);
  531. childRegion.X -= view.Frame.X;
  532. childRegion.Y -= view.Frame.Y;
  533. view.SetNeedsDisplay (childRegion);
  534. }
  535. }
  536. internal bool childNeedsDisplay;
  537. /// <summary>
  538. /// Indicates that any child views (in the <see cref="Subviews"/> list) need to be repainted.
  539. /// </summary>
  540. public void ChildNeedsDisplay ()
  541. {
  542. childNeedsDisplay = true;
  543. if (container != null)
  544. container.ChildNeedsDisplay ();
  545. }
  546. /// <summary>
  547. /// Adds a subview (child) to this view.
  548. /// </summary>
  549. /// <remarks>
  550. /// 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"/>
  551. /// </remarks>
  552. public virtual void Add (View view)
  553. {
  554. if (view == null)
  555. return;
  556. if (subviews == null) {
  557. subviews = new List<View> ();
  558. }
  559. if (tabIndexes == null) {
  560. tabIndexes = new List<View> ();
  561. }
  562. subviews.Add (view);
  563. tabIndexes.Add (view);
  564. view.container = this;
  565. OnAdded (view);
  566. if (view.CanFocus) {
  567. CanFocus = true;
  568. view.tabIndex = tabIndexes.IndexOf (view);
  569. }
  570. SetNeedsLayout ();
  571. SetNeedsDisplay ();
  572. }
  573. /// <summary>
  574. /// Adds the specified views (children) to the view.
  575. /// </summary>
  576. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  577. /// <remarks>
  578. /// 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"/>
  579. /// </remarks>
  580. public void Add (params View [] views)
  581. {
  582. if (views == null)
  583. return;
  584. foreach (var view in views)
  585. Add (view);
  586. }
  587. /// <summary>
  588. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  589. /// </summary>
  590. public virtual void RemoveAll ()
  591. {
  592. if (subviews == null)
  593. return;
  594. while (subviews.Count > 0) {
  595. Remove (subviews [0]);
  596. Remove (tabIndexes [0]);
  597. }
  598. }
  599. /// <summary>
  600. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  601. /// </summary>
  602. /// <remarks>
  603. /// </remarks>
  604. public virtual void Remove (View view)
  605. {
  606. if (view == null || subviews == null)
  607. return;
  608. SetNeedsLayout ();
  609. SetNeedsDisplay ();
  610. var touched = view.Frame;
  611. subviews.Remove (view);
  612. tabIndexes.Remove (view);
  613. view.container = null;
  614. OnRemoved (view);
  615. view.tabIndex = -1;
  616. if (subviews.Count < 1)
  617. this.CanFocus = false;
  618. foreach (var v in subviews) {
  619. if (v.Frame.IntersectsWith (touched))
  620. view.SetNeedsDisplay ();
  621. }
  622. }
  623. void PerformActionForSubview (View subview, Action<View> action)
  624. {
  625. if (subviews.Contains (subview)) {
  626. action (subview);
  627. }
  628. SetNeedsDisplay ();
  629. subview.SetNeedsDisplay ();
  630. }
  631. /// <summary>
  632. /// Brings the specified subview to the front so it is drawn on top of any other views.
  633. /// </summary>
  634. /// <param name="subview">The subview to send to the front</param>
  635. /// <remarks>
  636. /// <seealso cref="SendSubviewToBack"/>.
  637. /// </remarks>
  638. public void BringSubviewToFront (View subview)
  639. {
  640. PerformActionForSubview (subview, x => {
  641. subviews.Remove (x);
  642. subviews.Add (x);
  643. });
  644. }
  645. /// <summary>
  646. /// Sends the specified subview to the front so it is the first view drawn
  647. /// </summary>
  648. /// <param name="subview">The subview to send to the front</param>
  649. /// <remarks>
  650. /// <seealso cref="BringSubviewToFront(View)"/>.
  651. /// </remarks>
  652. public void SendSubviewToBack (View subview)
  653. {
  654. PerformActionForSubview (subview, x => {
  655. subviews.Remove (x);
  656. subviews.Insert (0, subview);
  657. });
  658. }
  659. /// <summary>
  660. /// Moves the subview backwards in the hierarchy, only one step
  661. /// </summary>
  662. /// <param name="subview">The subview to send backwards</param>
  663. /// <remarks>
  664. /// If you want to send the view all the way to the back use SendSubviewToBack.
  665. /// </remarks>
  666. public void SendSubviewBackwards (View subview)
  667. {
  668. PerformActionForSubview (subview, x => {
  669. var idx = subviews.IndexOf (x);
  670. if (idx > 0) {
  671. subviews.Remove (x);
  672. subviews.Insert (idx - 1, x);
  673. }
  674. });
  675. }
  676. /// <summary>
  677. /// Moves the subview backwards in the hierarchy, only one step
  678. /// </summary>
  679. /// <param name="subview">The subview to send backwards</param>
  680. /// <remarks>
  681. /// If you want to send the view all the way to the back use SendSubviewToBack.
  682. /// </remarks>
  683. public void BringSubviewForward (View subview)
  684. {
  685. PerformActionForSubview (subview, x => {
  686. var idx = subviews.IndexOf (x);
  687. if (idx + 1 < subviews.Count) {
  688. subviews.Remove (x);
  689. subviews.Insert (idx + 1, x);
  690. }
  691. });
  692. }
  693. /// <summary>
  694. /// Clears the view region with the current color.
  695. /// </summary>
  696. /// <remarks>
  697. /// <para>
  698. /// This clears the entire region used by this view.
  699. /// </para>
  700. /// </remarks>
  701. public void Clear ()
  702. {
  703. var h = Frame.Height;
  704. var w = Frame.Width;
  705. for (int line = 0; line < h; line++) {
  706. Move (0, line);
  707. for (int col = 0; col < w; col++)
  708. Driver.AddRune (' ');
  709. }
  710. }
  711. /// <summary>
  712. /// Clears the specified region with the current color.
  713. /// </summary>
  714. /// <remarks>
  715. /// </remarks>
  716. /// <param name="regionScreen">The screen-relative region to clear.</param>
  717. public void Clear (Rect regionScreen)
  718. {
  719. var h = regionScreen.Height;
  720. var w = regionScreen.Width;
  721. for (int line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  722. Driver.Move (regionScreen.X, line);
  723. for (int col = 0; col < w; col++)
  724. Driver.AddRune (' ');
  725. }
  726. }
  727. /// <summary>
  728. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  729. /// </summary>
  730. /// <param name="col">View-relative column.</param>
  731. /// <param name="row">View-relative row.</param>
  732. /// <param name="rcol">Absolute column; screen-relative.</param>
  733. /// <param name="rrow">Absolute row; screen-relative.</param>
  734. /// <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>
  735. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  736. {
  737. // Computes the real row, col relative to the screen.
  738. rrow = row + frame.Y;
  739. rcol = col + frame.X;
  740. var ccontainer = container;
  741. while (ccontainer != null) {
  742. rrow += ccontainer.frame.Y;
  743. rcol += ccontainer.frame.X;
  744. ccontainer = ccontainer.container;
  745. }
  746. // The following ensures that the cursor is always in the screen boundaries.
  747. if (clipped) {
  748. rrow = Math.Min (rrow, Driver.Rows - 1);
  749. rcol = Math.Min (rcol, Driver.Cols - 1);
  750. }
  751. }
  752. /// <summary>
  753. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  754. /// </summary>
  755. /// <returns>The mapped point.</returns>
  756. /// <param name="x">X screen-coordinate point.</param>
  757. /// <param name="y">Y screen-coordinate point.</param>
  758. public Point ScreenToView (int x, int y)
  759. {
  760. if (SuperView == null) {
  761. return new Point (x - Frame.X, y - frame.Y);
  762. } else {
  763. var parent = SuperView.ScreenToView (x, y);
  764. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  765. }
  766. }
  767. /// <summary>
  768. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  769. /// </summary>
  770. internal Rect ViewToScreen (Rect region)
  771. {
  772. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  773. return new Rect (x, y, region.Width, region.Height);
  774. }
  775. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  776. internal Rect ScreenClip (Rect regionScreen)
  777. {
  778. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  779. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  780. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  781. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  782. return new Rect (x, y, w, h);
  783. }
  784. /// <summary>
  785. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  786. /// </summary>
  787. /// <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>
  788. /// <remarks>
  789. /// <see cref="Bounds"/> is View-relative.
  790. /// </remarks>
  791. public Rect ClipToBounds ()
  792. {
  793. return SetClip (Bounds);
  794. }
  795. /// <summary>
  796. /// Sets the clip region to the specified view-relative region.
  797. /// </summary>
  798. /// <returns>The previous screen-relative clip region.</returns>
  799. /// <param name="region">View-relative clip region.</param>
  800. public Rect SetClip (Rect region)
  801. {
  802. var previous = Driver.Clip;
  803. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  804. return previous;
  805. }
  806. /// <summary>
  807. /// Draws a frame in the current view, clipped by the boundary of this view
  808. /// </summary>
  809. /// <param name="region">View-relative region for the frame to be drawn.</param>
  810. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  811. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  812. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  813. {
  814. var scrRect = ViewToScreen (region);
  815. var savedClip = ClipToBounds ();
  816. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  817. Driver.Clip = savedClip;
  818. }
  819. /// <summary>
  820. /// Utility function to draw strings that contain a hotkey.
  821. /// </summary>
  822. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  823. /// <param name="hotColor">Hot color.</param>
  824. /// <param name="normalColor">Normal color.</param>
  825. /// <remarks>
  826. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  827. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  828. /// </remarks>
  829. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  830. {
  831. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  832. Application.Driver.SetAttribute (normalColor);
  833. foreach (var rune in text) {
  834. if (rune == hotkeySpec) {
  835. Application.Driver.SetAttribute (hotColor);
  836. continue;
  837. }
  838. Application.Driver.AddRune (rune);
  839. Application.Driver.SetAttribute (normalColor);
  840. }
  841. }
  842. /// <summary>
  843. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  844. /// </summary>
  845. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  846. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  847. /// <param name="scheme">The color scheme to use.</param>
  848. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  849. {
  850. if (focused)
  851. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  852. else
  853. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  854. }
  855. /// <summary>
  856. /// This moves the cursor to the specified column and row in the view.
  857. /// </summary>
  858. /// <returns>The move.</returns>
  859. /// <param name="col">Col.</param>
  860. /// <param name="row">Row.</param>
  861. public void Move (int col, int row)
  862. {
  863. ViewToScreen (col, row, out var rcol, out var rrow);
  864. Driver.Move (rcol, rrow);
  865. }
  866. /// <summary>
  867. /// Positions the cursor in the right position based on the currently focused view in the chain.
  868. /// </summary>
  869. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  870. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  871. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  872. /// the last focused view. Views should make sure that they place the cursor
  873. /// in a visually sensible place.
  874. public virtual void PositionCursor ()
  875. {
  876. if (focused != null)
  877. focused.PositionCursor ();
  878. else {
  879. if (CanFocus && HasFocus) {
  880. Move (viewText.HotKeyPos == -1 ? 1 : viewText.HotKeyPos, 0);
  881. } else {
  882. Move (frame.X, frame.Y);
  883. }
  884. }
  885. }
  886. bool hasFocus;
  887. /// <inheritdoc/>
  888. public override bool HasFocus {
  889. get {
  890. return hasFocus;
  891. }
  892. }
  893. void SetHasFocus (bool value, View view)
  894. {
  895. if (hasFocus != value) {
  896. hasFocus = value;
  897. }
  898. if (value) {
  899. OnEnter (view);
  900. } else {
  901. OnLeave (view);
  902. }
  903. SetNeedsDisplay ();
  904. // Remove focus down the chain of subviews if focus is removed
  905. if (!value && focused != null) {
  906. focused.OnLeave (view);
  907. focused.SetHasFocus (false, view);
  908. focused = null;
  909. }
  910. }
  911. /// <summary>
  912. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  913. /// </summary>
  914. public class FocusEventArgs : EventArgs {
  915. /// <summary>
  916. /// Constructs.
  917. /// </summary>
  918. /// <param name="view">The view that gets or loses focus.</param>
  919. public FocusEventArgs (View view) { View = view; }
  920. /// <summary>
  921. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  922. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  923. /// </summary>
  924. public bool Handled { get; set; }
  925. /// <summary>
  926. /// Indicates the current view that gets or loses focus.
  927. /// </summary>
  928. public View View { get; set; }
  929. }
  930. /// <summary>
  931. /// Method invoked when a subview is being added to this view.
  932. /// </summary>
  933. /// <param name="view">The subview being added.</param>
  934. public virtual void OnAdded (View view)
  935. {
  936. view.Added?.Invoke (this);
  937. }
  938. /// <summary>
  939. /// Method invoked when a subview is being removed from this view.
  940. /// </summary>
  941. /// <param name="view">The subview being removed.</param>
  942. public virtual void OnRemoved (View view)
  943. {
  944. view.Removed?.Invoke (this);
  945. }
  946. /// <inheritdoc/>
  947. public override bool OnEnter (View view)
  948. {
  949. FocusEventArgs args = new FocusEventArgs (view);
  950. Enter?.Invoke (args);
  951. if (args.Handled)
  952. return true;
  953. if (base.OnEnter (view))
  954. return true;
  955. return false;
  956. }
  957. /// <inheritdoc/>
  958. public override bool OnLeave (View view)
  959. {
  960. FocusEventArgs args = new FocusEventArgs (view);
  961. Leave?.Invoke (args);
  962. if (args.Handled)
  963. return true;
  964. if (base.OnLeave (view))
  965. return true;
  966. return false;
  967. }
  968. /// <summary>
  969. /// Returns the currently focused view inside this view, or null if nothing is focused.
  970. /// </summary>
  971. /// <value>The focused.</value>
  972. public View Focused => focused;
  973. /// <summary>
  974. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  975. /// </summary>
  976. /// <value>The most focused.</value>
  977. public View MostFocused {
  978. get {
  979. if (Focused == null)
  980. return null;
  981. var most = Focused.MostFocused;
  982. if (most != null)
  983. return most;
  984. return Focused;
  985. }
  986. }
  987. /// <summary>
  988. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  989. /// color scheme.
  990. /// </summary>
  991. public ColorScheme ColorScheme {
  992. get {
  993. if (colorScheme == null)
  994. return SuperView?.ColorScheme;
  995. return colorScheme;
  996. }
  997. set {
  998. colorScheme = value;
  999. }
  1000. }
  1001. ColorScheme colorScheme;
  1002. /// <summary>
  1003. /// Displays the specified character in the specified column and row of the View.
  1004. /// </summary>
  1005. /// <param name="col">Column (view-relative).</param>
  1006. /// <param name="row">Row (view-relative).</param>
  1007. /// <param name="ch">Ch.</param>
  1008. public void AddRune (int col, int row, Rune ch)
  1009. {
  1010. if (row < 0 || col < 0)
  1011. return;
  1012. if (row > frame.Height - 1 || col > frame.Width - 1)
  1013. return;
  1014. Move (col, row);
  1015. Driver.AddRune (ch);
  1016. }
  1017. /// <summary>
  1018. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  1019. /// </summary>
  1020. protected void ClearNeedsDisplay ()
  1021. {
  1022. NeedDisplay = Rect.Empty;
  1023. childNeedsDisplay = false;
  1024. }
  1025. /// <summary>
  1026. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1027. /// </summary>
  1028. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1029. /// <remarks>
  1030. /// <para>
  1031. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1032. /// </para>
  1033. /// <para>
  1034. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1035. /// the last color that was set globaly on the driver.
  1036. /// </para>
  1037. /// <para>
  1038. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1039. /// larger than the <c>region</c> parameter.
  1040. /// </para>
  1041. /// </remarks>
  1042. public virtual void Redraw (Rect bounds)
  1043. {
  1044. var clipRect = new Rect (Point.Empty, frame.Size);
  1045. Driver.SetAttribute (HasFocus ? ColorScheme.Focus : ColorScheme.Normal);
  1046. if (!ustring.IsNullOrEmpty (Text)) {
  1047. Clear ();
  1048. // Draw any Text
  1049. viewText?.SetNeedsFormat ();
  1050. viewText?.Draw (ViewToScreen (Bounds), HasFocus ? ColorScheme.Focus : ColorScheme.Normal, HasFocus ? ColorScheme.HotFocus : ColorScheme.HotNormal);
  1051. }
  1052. // Invoke DrawContentEvent
  1053. OnDrawContent (bounds);
  1054. if (subviews != null) {
  1055. foreach (var view in subviews) {
  1056. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  1057. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1058. if (view.layoutNeeded)
  1059. view.LayoutSubviews ();
  1060. Application.CurrentView = view;
  1061. // Draw the subview
  1062. // Use the view's bounds (view-relative; Location will always be (0,0) because
  1063. view.Redraw (view.Bounds);
  1064. }
  1065. view.NeedDisplay = Rect.Empty;
  1066. view.childNeedsDisplay = false;
  1067. }
  1068. }
  1069. }
  1070. ClearNeedsDisplay ();
  1071. }
  1072. /// <summary>
  1073. /// Event invoked when the content area of the View is to be drawn.
  1074. /// </summary>
  1075. /// <remarks>
  1076. /// <para>
  1077. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1078. /// </para>
  1079. /// <para>
  1080. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1081. /// </para>
  1082. /// </remarks>
  1083. public Action<Rect> DrawContent;
  1084. /// <summary>
  1085. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1086. /// </summary>
  1087. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1088. /// <remarks>
  1089. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1090. /// </remarks>
  1091. public virtual void OnDrawContent (Rect viewport)
  1092. {
  1093. DrawContent?.Invoke (viewport);
  1094. }
  1095. /// <summary>
  1096. /// Causes the specified subview to have focus.
  1097. /// </summary>
  1098. /// <param name="view">View.</param>
  1099. public void SetFocus (View view)
  1100. {
  1101. if (view == null)
  1102. return;
  1103. //Console.WriteLine ($"Request to focus {view}");
  1104. if (!view.CanFocus)
  1105. return;
  1106. if (focused == view)
  1107. return;
  1108. // Make sure that this view is a subview
  1109. View c;
  1110. for (c = view.container; c != null; c = c.container)
  1111. if (c == this)
  1112. break;
  1113. if (c == null)
  1114. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1115. if (focused != null)
  1116. focused.SetHasFocus (false, view);
  1117. var f = focused;
  1118. focused = view;
  1119. focused.SetHasFocus (true, f);
  1120. focused.EnsureFocus ();
  1121. // Send focus upwards
  1122. SuperView?.SetFocus (this);
  1123. }
  1124. /// <summary>
  1125. /// Defines the event arguments for <see cref="KeyEvent"/>
  1126. /// </summary>
  1127. public class KeyEventEventArgs : EventArgs {
  1128. /// <summary>
  1129. /// Constructs.
  1130. /// </summary>
  1131. /// <param name="ke"></param>
  1132. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  1133. /// <summary>
  1134. /// The <see cref="KeyEvent"/> for the event.
  1135. /// </summary>
  1136. public KeyEvent KeyEvent { get; set; }
  1137. /// <summary>
  1138. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1139. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1140. /// </summary>
  1141. public bool Handled { get; set; } = false;
  1142. }
  1143. /// <summary>
  1144. /// Invoked when a character key is pressed and occurs after the key up event.
  1145. /// </summary>
  1146. public Action<KeyEventEventArgs> KeyPress;
  1147. /// <inheritdoc/>
  1148. public override bool ProcessKey (KeyEvent keyEvent)
  1149. {
  1150. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1151. KeyPress?.Invoke (args);
  1152. if (args.Handled)
  1153. return true;
  1154. if (Focused?.ProcessKey (keyEvent) == true)
  1155. return true;
  1156. return false;
  1157. }
  1158. /// <inheritdoc/>
  1159. public override bool ProcessHotKey (KeyEvent keyEvent)
  1160. {
  1161. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1162. KeyPress?.Invoke (args);
  1163. if (args.Handled)
  1164. return true;
  1165. if (subviews == null || subviews.Count == 0)
  1166. return false;
  1167. foreach (var view in subviews)
  1168. if (view.ProcessHotKey (keyEvent))
  1169. return true;
  1170. return false;
  1171. }
  1172. /// <inheritdoc/>
  1173. public override bool ProcessColdKey (KeyEvent keyEvent)
  1174. {
  1175. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1176. KeyPress?.Invoke (args);
  1177. if (args.Handled)
  1178. return true;
  1179. if (subviews == null || subviews.Count == 0)
  1180. return false;
  1181. foreach (var view in subviews)
  1182. if (view.ProcessColdKey (keyEvent))
  1183. return true;
  1184. return false;
  1185. }
  1186. /// <summary>
  1187. /// Invoked when a key is pressed
  1188. /// </summary>
  1189. public Action<KeyEventEventArgs> KeyDown;
  1190. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1191. public override bool OnKeyDown (KeyEvent keyEvent)
  1192. {
  1193. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1194. KeyDown?.Invoke (args);
  1195. if (args.Handled)
  1196. return true;
  1197. if (subviews == null || subviews.Count == 0)
  1198. return false;
  1199. foreach (var view in subviews)
  1200. if (view.HasFocus && view.OnKeyDown (keyEvent))
  1201. return true;
  1202. return false;
  1203. }
  1204. /// <summary>
  1205. /// Invoked when a key is released
  1206. /// </summary>
  1207. public Action<KeyEventEventArgs> KeyUp;
  1208. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1209. public override bool OnKeyUp (KeyEvent keyEvent)
  1210. {
  1211. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1212. KeyUp?.Invoke (args);
  1213. if (args.Handled)
  1214. return true;
  1215. if (subviews == null || subviews.Count == 0)
  1216. return false;
  1217. foreach (var view in subviews)
  1218. if (view.HasFocus && view.OnKeyUp (keyEvent))
  1219. return true;
  1220. return false;
  1221. }
  1222. /// <summary>
  1223. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1224. /// </summary>
  1225. public void EnsureFocus ()
  1226. {
  1227. if (focused == null)
  1228. if (FocusDirection == Direction.Forward)
  1229. FocusFirst ();
  1230. else
  1231. FocusLast ();
  1232. }
  1233. /// <summary>
  1234. /// Focuses the first focusable subview if one exists.
  1235. /// </summary>
  1236. public void FocusFirst ()
  1237. {
  1238. if (tabIndexes == null) {
  1239. SuperView?.SetFocus (this);
  1240. return;
  1241. }
  1242. foreach (var view in tabIndexes) {
  1243. if (view.CanFocus && view.tabStop) {
  1244. SetFocus (view);
  1245. return;
  1246. }
  1247. }
  1248. }
  1249. /// <summary>
  1250. /// Focuses the last focusable subview if one exists.
  1251. /// </summary>
  1252. public void FocusLast ()
  1253. {
  1254. if (tabIndexes == null) {
  1255. SuperView?.SetFocus (this);
  1256. return;
  1257. }
  1258. for (int i = tabIndexes.Count; i > 0;) {
  1259. i--;
  1260. View v = tabIndexes [i];
  1261. if (v.CanFocus && v.tabStop) {
  1262. SetFocus (v);
  1263. return;
  1264. }
  1265. }
  1266. }
  1267. /// <summary>
  1268. /// Focuses the previous view.
  1269. /// </summary>
  1270. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1271. public bool FocusPrev ()
  1272. {
  1273. FocusDirection = Direction.Backward;
  1274. if (tabIndexes == null || tabIndexes.Count == 0)
  1275. return false;
  1276. if (focused == null) {
  1277. FocusLast ();
  1278. return focused != null;
  1279. }
  1280. int focused_idx = -1;
  1281. for (int i = tabIndexes.Count; i > 0;) {
  1282. i--;
  1283. View w = tabIndexes [i];
  1284. if (w.HasFocus) {
  1285. if (w.FocusPrev ())
  1286. return true;
  1287. focused_idx = i;
  1288. continue;
  1289. }
  1290. if (w.CanFocus && focused_idx != -1 && w.tabStop) {
  1291. focused.SetHasFocus (false, w);
  1292. if (w != null && w.CanFocus && w.tabStop)
  1293. w.FocusLast ();
  1294. SetFocus (w);
  1295. return true;
  1296. }
  1297. }
  1298. if (focused != null) {
  1299. focused.SetHasFocus (false, this);
  1300. focused = null;
  1301. }
  1302. return false;
  1303. }
  1304. /// <summary>
  1305. /// Focuses the next view.
  1306. /// </summary>
  1307. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1308. public bool FocusNext ()
  1309. {
  1310. FocusDirection = Direction.Forward;
  1311. if (tabIndexes == null || tabIndexes.Count == 0)
  1312. return false;
  1313. if (focused == null) {
  1314. FocusFirst ();
  1315. return focused != null;
  1316. }
  1317. int n = tabIndexes.Count;
  1318. int focused_idx = -1;
  1319. for (int i = 0; i < n; i++) {
  1320. View w = tabIndexes [i];
  1321. if (w.HasFocus) {
  1322. if (w.FocusNext ())
  1323. return true;
  1324. focused_idx = i;
  1325. continue;
  1326. }
  1327. if (w.CanFocus && focused_idx != -1 && w.tabStop) {
  1328. focused.SetHasFocus (false, w);
  1329. if (w != null && w.CanFocus && w.tabStop)
  1330. w.FocusFirst ();
  1331. SetFocus (w);
  1332. return true;
  1333. }
  1334. }
  1335. if (focused != null) {
  1336. focused.SetHasFocus (false, this);
  1337. focused = null;
  1338. }
  1339. return false;
  1340. }
  1341. /// <summary>
  1342. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1343. /// </summary>
  1344. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1345. /// <remarks>
  1346. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1347. /// </remarks>
  1348. internal void SetRelativeLayout (Rect hostFrame)
  1349. {
  1350. int w, h, _x, _y;
  1351. if (x is Pos.PosCenter) {
  1352. if (width == null)
  1353. w = hostFrame.Width;
  1354. else
  1355. w = width.Anchor (hostFrame.Width);
  1356. _x = x.Anchor (hostFrame.Width - w);
  1357. } else {
  1358. if (x == null)
  1359. _x = 0;
  1360. else
  1361. _x = x.Anchor (hostFrame.Width);
  1362. if (width == null)
  1363. w = hostFrame.Width;
  1364. else if (width is Dim.DimFactor && !((Dim.DimFactor)width).IsFromRemaining ())
  1365. w = width.Anchor (hostFrame.Width);
  1366. else
  1367. w = Math.Max (width.Anchor (hostFrame.Width - _x), 0);
  1368. }
  1369. if (y is Pos.PosCenter) {
  1370. if (height == null)
  1371. h = hostFrame.Height;
  1372. else
  1373. h = height.Anchor (hostFrame.Height);
  1374. _y = y.Anchor (hostFrame.Height - h);
  1375. } else {
  1376. if (y == null)
  1377. _y = 0;
  1378. else
  1379. _y = y.Anchor (hostFrame.Height);
  1380. if (height == null)
  1381. h = hostFrame.Height;
  1382. else if (height is Dim.DimFactor && !((Dim.DimFactor)height).IsFromRemaining ())
  1383. h = height.Anchor (hostFrame.Height);
  1384. else
  1385. h = Math.Max (height.Anchor (hostFrame.Height - _y), 0);
  1386. }
  1387. Frame = new Rect (_x, _y, w, h);
  1388. }
  1389. // https://en.wikipedia.org/wiki/Topological_sorting
  1390. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1391. {
  1392. var result = new List<View> ();
  1393. // Set of all nodes with no incoming edges
  1394. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1395. while (S.Any ()) {
  1396. // remove a node n from S
  1397. var n = S.First ();
  1398. S.Remove (n);
  1399. // add n to tail of L
  1400. if (n != this?.SuperView)
  1401. result.Add (n);
  1402. // for each node m with an edge e from n to m do
  1403. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1404. var m = e.To;
  1405. // remove edge e from the graph
  1406. edges.Remove (e);
  1407. // if m has no other incoming edges then
  1408. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1409. // insert m into S
  1410. S.Add (m);
  1411. }
  1412. }
  1413. }
  1414. if (edges.Any ()) {
  1415. if (!object.ReferenceEquals (edges.First ().From, edges.First ().To)) {
  1416. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {edges.First ().From}. Did you forget to add it to {this}?");
  1417. } else {
  1418. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1419. }
  1420. } else {
  1421. // return L (a topologically sorted order)
  1422. return result;
  1423. }
  1424. }
  1425. /// <summary>
  1426. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1427. /// </summary>
  1428. public class LayoutEventArgs : EventArgs {
  1429. /// <summary>
  1430. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1431. /// </summary>
  1432. public Rect OldBounds { get; set; }
  1433. }
  1434. /// <summary>
  1435. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1436. /// </summary>
  1437. /// <remarks>
  1438. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1439. /// </remarks>
  1440. public Action<LayoutEventArgs> LayoutStarted;
  1441. /// <summary>
  1442. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  1443. /// </summary>
  1444. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  1445. {
  1446. LayoutStarted?.Invoke (args);
  1447. }
  1448. /// <summary>
  1449. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1450. /// </summary>
  1451. /// <remarks>
  1452. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1453. /// </remarks>
  1454. public Action<LayoutEventArgs> LayoutComplete;
  1455. /// <summary>
  1456. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  1457. /// </summary>
  1458. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1459. {
  1460. LayoutComplete?.Invoke (args);
  1461. }
  1462. /// <summary>
  1463. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1464. /// response to the container view or terminal resizing.
  1465. /// </summary>
  1466. /// <remarks>
  1467. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1468. /// </remarks>
  1469. public virtual void LayoutSubviews ()
  1470. {
  1471. if (!layoutNeeded) {
  1472. return;
  1473. }
  1474. Rect oldBounds = Bounds;
  1475. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  1476. viewText.Size = Bounds.Size;
  1477. // Sort out the dependencies of the X, Y, Width, Height properties
  1478. var nodes = new HashSet<View> ();
  1479. var edges = new HashSet<(View, View)> ();
  1480. foreach (var v in InternalSubviews) {
  1481. nodes.Add (v);
  1482. if (v.LayoutStyle == LayoutStyle.Computed) {
  1483. if (v.X is Pos.PosView vX)
  1484. edges.Add ((vX.Target, v));
  1485. if (v.Y is Pos.PosView vY)
  1486. edges.Add ((vY.Target, v));
  1487. if (v.Width is Dim.DimView vWidth)
  1488. edges.Add ((vWidth.Target, v));
  1489. if (v.Height is Dim.DimView vHeight)
  1490. edges.Add ((vHeight.Target, v));
  1491. }
  1492. }
  1493. var ordered = TopologicalSort (nodes, edges);
  1494. foreach (var v in ordered) {
  1495. if (v.LayoutStyle == LayoutStyle.Computed) {
  1496. v.SetRelativeLayout (Frame);
  1497. }
  1498. v.LayoutSubviews ();
  1499. v.layoutNeeded = false;
  1500. }
  1501. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1502. SetRelativeLayout (Frame);
  1503. }
  1504. layoutNeeded = false;
  1505. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1506. }
  1507. /// <summary>
  1508. /// The text displayed by the <see cref="View"/>.
  1509. /// </summary>
  1510. /// <remarks>
  1511. /// <para>
  1512. /// If provided, the text will be drawn before any subviews are drawn.
  1513. /// </para>
  1514. /// <para>
  1515. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  1516. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  1517. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  1518. /// is 1, the text will be clipped.
  1519. /// </para>
  1520. /// <para>
  1521. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  1522. /// <c>(Rune)0xffff</c>.
  1523. /// </para>
  1524. /// </remarks>
  1525. public virtual ustring Text {
  1526. get => viewText.Text;
  1527. set {
  1528. viewText.Text = value;
  1529. SetNeedsDisplay ();
  1530. }
  1531. }
  1532. /// <summary>
  1533. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  1534. /// </summary>
  1535. /// <value>The text alignment.</value>
  1536. public virtual TextAlignment TextAlignment {
  1537. get => viewText.Alignment;
  1538. set {
  1539. viewText.Alignment = value;
  1540. SetNeedsDisplay ();
  1541. }
  1542. }
  1543. /// <summary>
  1544. /// Pretty prints the View
  1545. /// </summary>
  1546. /// <returns></returns>
  1547. public override string ToString ()
  1548. {
  1549. return $"{GetType ().Name}({Id})({Frame})";
  1550. }
  1551. /// <summary>
  1552. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1553. /// </summary>
  1554. public class MouseEventArgs : EventArgs {
  1555. /// <summary>
  1556. /// Constructs.
  1557. /// </summary>
  1558. /// <param name="me"></param>
  1559. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  1560. /// <summary>
  1561. /// The <see cref="MouseEvent"/> for the event.
  1562. /// </summary>
  1563. public MouseEvent MouseEvent { get; set; }
  1564. /// <summary>
  1565. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1566. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1567. /// </summary>
  1568. public bool Handled { get; set; }
  1569. }
  1570. /// <inheritdoc/>
  1571. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1572. {
  1573. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1574. MouseEnter?.Invoke (args);
  1575. if (args.Handled)
  1576. return true;
  1577. if (base.OnMouseEnter (mouseEvent))
  1578. return true;
  1579. return false;
  1580. }
  1581. /// <inheritdoc/>
  1582. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1583. {
  1584. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1585. MouseLeave?.Invoke (args);
  1586. if (args.Handled)
  1587. return true;
  1588. if (base.OnMouseLeave (mouseEvent))
  1589. return true;
  1590. return false;
  1591. }
  1592. /// <summary>
  1593. /// Method invoked when a mouse event is generated
  1594. /// </summary>
  1595. /// <param name="mouseEvent"></param>
  1596. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1597. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1598. {
  1599. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1600. MouseClick?.Invoke (args);
  1601. if (args.Handled)
  1602. return true;
  1603. if (MouseEvent (mouseEvent))
  1604. return true;
  1605. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  1606. if (!HasFocus && SuperView != null) {
  1607. SuperView.SetFocus (this);
  1608. SetNeedsDisplay ();
  1609. }
  1610. return true;
  1611. }
  1612. return false;
  1613. }
  1614. }
  1615. }