View.cs 55 KB

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