View.cs 53 KB

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