2
0

View.cs 54 KB

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