View.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  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 base.HasFocus;
  820. }
  821. internal set {
  822. if (base.HasFocus != value)
  823. if (value)
  824. OnEnter ();
  825. else
  826. OnLeave ();
  827. SetNeedsDisplay ();
  828. base.HasFocus = value;
  829. // Remove focus down the chain of subviews if focus is removed
  830. if (!value && focused != null) {
  831. focused.OnLeave ();
  832. focused.HasFocus = false;
  833. focused = null;
  834. }
  835. }
  836. }
  837. /// <summary>
  838. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  839. /// </summary>
  840. public class FocusEventArgs : EventArgs {
  841. /// <summary>
  842. /// Constructs.
  843. /// </summary>
  844. public FocusEventArgs () { }
  845. /// <summary>
  846. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  847. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  848. /// </summary>
  849. public bool Handled { get; set; }
  850. }
  851. /// <inheritdoc/>
  852. public override bool OnEnter ()
  853. {
  854. FocusEventArgs args = new FocusEventArgs ();
  855. Enter?.Invoke (args);
  856. if (args.Handled)
  857. return true;
  858. if (base.OnEnter ())
  859. return true;
  860. return false;
  861. }
  862. /// <inheritdoc/>
  863. public override bool OnLeave ()
  864. {
  865. FocusEventArgs args = new FocusEventArgs ();
  866. Leave?.Invoke (args);
  867. if (args.Handled)
  868. return true;
  869. if (base.OnLeave ())
  870. return true;
  871. return false;
  872. }
  873. /// <summary>
  874. /// Returns the currently focused view inside this view, or null if nothing is focused.
  875. /// </summary>
  876. /// <value>The focused.</value>
  877. public View Focused => focused;
  878. /// <summary>
  879. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  880. /// </summary>
  881. /// <value>The most focused.</value>
  882. public View MostFocused {
  883. get {
  884. if (Focused == null)
  885. return null;
  886. var most = Focused.MostFocused;
  887. if (most != null)
  888. return most;
  889. return Focused;
  890. }
  891. }
  892. /// <summary>
  893. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  894. /// color scheme.
  895. /// </summary>
  896. public ColorScheme ColorScheme {
  897. get {
  898. if (colorScheme == null)
  899. return SuperView?.ColorScheme;
  900. return colorScheme;
  901. }
  902. set {
  903. colorScheme = value;
  904. }
  905. }
  906. ColorScheme colorScheme;
  907. /// <summary>
  908. /// Displays the specified character in the specified column and row of the View.
  909. /// </summary>
  910. /// <param name="col">Column (view-relative).</param>
  911. /// <param name="row">Row (view-relative).</param>
  912. /// <param name="ch">Ch.</param>
  913. public void AddRune (int col, int row, Rune ch)
  914. {
  915. if (row < 0 || col < 0)
  916. return;
  917. if (row > frame.Height - 1 || col > frame.Width - 1)
  918. return;
  919. Move (col, row);
  920. Driver.AddRune (ch);
  921. }
  922. /// <summary>
  923. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  924. /// </summary>
  925. protected void ClearNeedsDisplay ()
  926. {
  927. NeedDisplay = Rect.Empty;
  928. childNeedsDisplay = false;
  929. }
  930. /// <summary>
  931. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  932. /// </summary>
  933. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  934. /// <remarks>
  935. /// <para>
  936. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  937. /// </para>
  938. /// <para>
  939. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  940. /// the last color that was set globaly on the driver.
  941. /// </para>
  942. /// <para>
  943. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  944. /// larger than the <c>region</c> parameter.
  945. /// </para>
  946. /// </remarks>
  947. public virtual void Redraw (Rect bounds)
  948. {
  949. var clipRect = new Rect (Point.Empty, frame.Size);
  950. Driver.SetAttribute (HasFocus ? ColorScheme.Focus : ColorScheme.Normal);
  951. if (!ustring.IsNullOrEmpty (Text)) {
  952. Clear ();
  953. // Draw any Text
  954. viewText?.SetNeedsFormat ();
  955. viewText?.Draw (ViewToScreen (Bounds), HasFocus ? ColorScheme.Focus : ColorScheme.Normal, HasFocus ? ColorScheme.HotFocus : ColorScheme.HotNormal);
  956. }
  957. // Invoke DrawContentEvent
  958. OnDrawContent (bounds);
  959. if (subviews != null) {
  960. foreach (var view in subviews) {
  961. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  962. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  963. if (view.layoutNeeded)
  964. view.LayoutSubviews ();
  965. Application.CurrentView = view;
  966. // Draw the subview
  967. // Use the view's bounds (view-relative; Location will always be (0,0) because
  968. view.Redraw (view.Bounds);
  969. }
  970. view.NeedDisplay = Rect.Empty;
  971. view.childNeedsDisplay = false;
  972. }
  973. }
  974. }
  975. ClearNeedsDisplay ();
  976. }
  977. /// <summary>
  978. /// Event invoked when the content area of the View is to be drawn.
  979. /// </summary>
  980. /// <remarks>
  981. /// <para>
  982. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  983. /// </para>
  984. /// <para>
  985. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  986. /// </para>
  987. /// </remarks>
  988. public Action<Rect> DrawContent;
  989. /// <summary>
  990. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  991. /// </summary>
  992. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  993. /// <remarks>
  994. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  995. /// </remarks>
  996. public virtual void OnDrawContent (Rect viewport)
  997. {
  998. DrawContent?.Invoke (viewport);
  999. }
  1000. /// <summary>
  1001. /// Causes the specified subview to have focus.
  1002. /// </summary>
  1003. /// <param name="view">View.</param>
  1004. public void SetFocus (View view)
  1005. {
  1006. if (view == null)
  1007. return;
  1008. //Console.WriteLine ($"Request to focus {view}");
  1009. if (!view.CanFocus)
  1010. return;
  1011. if (focused == view)
  1012. return;
  1013. // Make sure that this view is a subview
  1014. View c;
  1015. for (c = view.container; c != null; c = c.container)
  1016. if (c == this)
  1017. break;
  1018. if (c == null)
  1019. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1020. if (focused != null)
  1021. focused.HasFocus = false;
  1022. focused = view;
  1023. focused.HasFocus = true;
  1024. focused.EnsureFocus ();
  1025. // Send focus upwards
  1026. SuperView?.SetFocus (this);
  1027. }
  1028. /// <summary>
  1029. /// Defines the event arguments for <see cref="KeyEvent"/>
  1030. /// </summary>
  1031. public class KeyEventEventArgs : EventArgs {
  1032. /// <summary>
  1033. /// Constructs.
  1034. /// </summary>
  1035. /// <param name="ke"></param>
  1036. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  1037. /// <summary>
  1038. /// The <see cref="KeyEvent"/> for the event.
  1039. /// </summary>
  1040. public KeyEvent KeyEvent { get; set; }
  1041. /// <summary>
  1042. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1043. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1044. /// </summary>
  1045. public bool Handled { get; set; } = false;
  1046. }
  1047. /// <summary>
  1048. /// Invoked when a character key is pressed and occurs after the key up event.
  1049. /// </summary>
  1050. public Action<KeyEventEventArgs> KeyPress;
  1051. /// <inheritdoc/>
  1052. public override bool ProcessKey (KeyEvent keyEvent)
  1053. {
  1054. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1055. KeyPress?.Invoke (args);
  1056. if (args.Handled)
  1057. return true;
  1058. if (Focused?.ProcessKey (keyEvent) == true)
  1059. return true;
  1060. return false;
  1061. }
  1062. /// <inheritdoc/>
  1063. public override bool ProcessHotKey (KeyEvent keyEvent)
  1064. {
  1065. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1066. KeyPress?.Invoke (args);
  1067. if (args.Handled)
  1068. return true;
  1069. if (subviews == null || subviews.Count == 0)
  1070. return false;
  1071. foreach (var view in subviews)
  1072. if (view.SuperView.IsCurrentTop && view.ProcessHotKey (keyEvent))
  1073. return true;
  1074. return false;
  1075. }
  1076. /// <inheritdoc/>
  1077. public override bool ProcessColdKey (KeyEvent keyEvent)
  1078. {
  1079. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1080. KeyPress?.Invoke (args);
  1081. if (args.Handled)
  1082. return true;
  1083. if (subviews == null || subviews.Count == 0)
  1084. return false;
  1085. foreach (var view in subviews)
  1086. if (view.SuperView.IsCurrentTop && view.ProcessColdKey (keyEvent))
  1087. return true;
  1088. return false;
  1089. }
  1090. /// <summary>
  1091. /// Invoked when a key is pressed
  1092. /// </summary>
  1093. public Action<KeyEventEventArgs> KeyDown;
  1094. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1095. public override bool OnKeyDown (KeyEvent keyEvent)
  1096. {
  1097. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1098. KeyDown?.Invoke (args);
  1099. if (args.Handled)
  1100. return true;
  1101. if (subviews == null || subviews.Count == 0)
  1102. return false;
  1103. foreach (var view in subviews)
  1104. if (view.SuperView.IsCurrentTop && view.OnKeyDown (keyEvent))
  1105. return true;
  1106. return false;
  1107. }
  1108. /// <summary>
  1109. /// Invoked when a key is released
  1110. /// </summary>
  1111. public Action<KeyEventEventArgs> KeyUp;
  1112. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1113. public override bool OnKeyUp (KeyEvent keyEvent)
  1114. {
  1115. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1116. KeyUp?.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.SuperView.IsCurrentTop && view.OnKeyUp (keyEvent))
  1123. return true;
  1124. return false;
  1125. }
  1126. /// <summary>
  1127. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1128. /// </summary>
  1129. public void EnsureFocus ()
  1130. {
  1131. if (focused == null)
  1132. if (FocusDirection == Direction.Forward)
  1133. FocusFirst ();
  1134. else
  1135. FocusLast ();
  1136. }
  1137. /// <summary>
  1138. /// Focuses the first focusable subview if one exists.
  1139. /// </summary>
  1140. public void FocusFirst ()
  1141. {
  1142. if (subviews == null) {
  1143. SuperView?.SetFocus (this);
  1144. return;
  1145. }
  1146. foreach (var view in subviews) {
  1147. if (view.CanFocus) {
  1148. SetFocus (view);
  1149. return;
  1150. }
  1151. }
  1152. }
  1153. /// <summary>
  1154. /// Focuses the last focusable subview if one exists.
  1155. /// </summary>
  1156. public void FocusLast ()
  1157. {
  1158. if (subviews == null) {
  1159. SuperView?.SetFocus (this);
  1160. return;
  1161. }
  1162. for (int i = subviews.Count; i > 0;) {
  1163. i--;
  1164. View v = subviews [i];
  1165. if (v.CanFocus) {
  1166. SetFocus (v);
  1167. return;
  1168. }
  1169. }
  1170. }
  1171. /// <summary>
  1172. /// Focuses the previous view.
  1173. /// </summary>
  1174. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1175. public bool FocusPrev ()
  1176. {
  1177. FocusDirection = Direction.Backward;
  1178. if (subviews == null || subviews.Count == 0)
  1179. return false;
  1180. if (focused == null) {
  1181. FocusLast ();
  1182. return focused != null;
  1183. }
  1184. int focused_idx = -1;
  1185. for (int i = subviews.Count; i > 0;) {
  1186. i--;
  1187. View w = subviews [i];
  1188. if (w.HasFocus) {
  1189. if (w.FocusPrev ())
  1190. return true;
  1191. focused_idx = i;
  1192. continue;
  1193. }
  1194. if (w.CanFocus && focused_idx != -1) {
  1195. focused.HasFocus = false;
  1196. if (w != null && w.CanFocus)
  1197. w.FocusLast ();
  1198. SetFocus (w);
  1199. return true;
  1200. }
  1201. }
  1202. if (focused != null) {
  1203. focused.HasFocus = false;
  1204. focused = null;
  1205. }
  1206. return false;
  1207. }
  1208. /// <summary>
  1209. /// Focuses the next view.
  1210. /// </summary>
  1211. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1212. public bool FocusNext ()
  1213. {
  1214. FocusDirection = Direction.Forward;
  1215. if (subviews == null || subviews.Count == 0)
  1216. return false;
  1217. if (focused == null) {
  1218. FocusFirst ();
  1219. return focused != null;
  1220. }
  1221. int n = subviews.Count;
  1222. int focused_idx = -1;
  1223. for (int i = 0; i < n; i++) {
  1224. View w = subviews [i];
  1225. if (w.HasFocus) {
  1226. if (w.FocusNext ())
  1227. return true;
  1228. focused_idx = i;
  1229. continue;
  1230. }
  1231. if (w.CanFocus && focused_idx != -1) {
  1232. focused.HasFocus = false;
  1233. if (w != null && w.CanFocus)
  1234. w.FocusFirst ();
  1235. SetFocus (w);
  1236. return true;
  1237. }
  1238. }
  1239. if (focused != null) {
  1240. focused.HasFocus = false;
  1241. focused = null;
  1242. }
  1243. return false;
  1244. }
  1245. /// <summary>
  1246. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1247. /// </summary>
  1248. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1249. /// <remarks>
  1250. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1251. /// </remarks>
  1252. internal void SetRelativeLayout (Rect hostFrame)
  1253. {
  1254. int w, h, _x, _y;
  1255. if (x is Pos.PosCenter) {
  1256. if (width == null)
  1257. w = hostFrame.Width;
  1258. else
  1259. w = width.Anchor (hostFrame.Width);
  1260. _x = x.Anchor (hostFrame.Width - w);
  1261. } else {
  1262. if (x == null)
  1263. _x = 0;
  1264. else
  1265. _x = x.Anchor (hostFrame.Width);
  1266. if (width == null)
  1267. w = hostFrame.Width;
  1268. else if (width is Dim.DimFactor && !((Dim.DimFactor)width).IsFromRemaining ())
  1269. w = width.Anchor (hostFrame.Width);
  1270. else
  1271. w = Math.Max (width.Anchor (hostFrame.Width - _x), 0);
  1272. }
  1273. if (y is Pos.PosCenter) {
  1274. if (height == null)
  1275. h = hostFrame.Height;
  1276. else
  1277. h = height.Anchor (hostFrame.Height);
  1278. _y = y.Anchor (hostFrame.Height - h);
  1279. } else {
  1280. if (y == null)
  1281. _y = 0;
  1282. else
  1283. _y = y.Anchor (hostFrame.Height);
  1284. if (height == null)
  1285. h = hostFrame.Height;
  1286. else if (height is Dim.DimFactor && !((Dim.DimFactor)height).IsFromRemaining ())
  1287. h = height.Anchor (hostFrame.Height);
  1288. else
  1289. h = Math.Max (height.Anchor (hostFrame.Height - _y), 0);
  1290. }
  1291. Frame = new Rect (_x, _y, w, h);
  1292. }
  1293. // https://en.wikipedia.org/wiki/Topological_sorting
  1294. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1295. {
  1296. var result = new List<View> ();
  1297. // Set of all nodes with no incoming edges
  1298. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1299. while (S.Any ()) {
  1300. // remove a node n from S
  1301. var n = S.First ();
  1302. S.Remove (n);
  1303. // add n to tail of L
  1304. if (n != this?.SuperView)
  1305. result.Add (n);
  1306. // for each node m with an edge e from n to m do
  1307. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1308. var m = e.To;
  1309. // remove edge e from the graph
  1310. edges.Remove (e);
  1311. // if m has no other incoming edges then
  1312. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1313. // insert m into S
  1314. S.Add (m);
  1315. }
  1316. }
  1317. }
  1318. if (edges.Any ()) {
  1319. if (!object.ReferenceEquals (edges.First ().From, edges.First ().To)) {
  1320. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {edges.First ().From}. Did you forget to add it to {this}?");
  1321. } else {
  1322. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1323. }
  1324. } else {
  1325. // return L (a topologically sorted order)
  1326. return result;
  1327. }
  1328. }
  1329. /// <summary>
  1330. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1331. /// </summary>
  1332. public class LayoutEventArgs : EventArgs {
  1333. /// <summary>
  1334. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1335. /// </summary>
  1336. public Rect OldBounds { get; set; }
  1337. }
  1338. /// <summary>
  1339. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1340. /// </summary>
  1341. /// <remarks>
  1342. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1343. /// </remarks>
  1344. public Action<LayoutEventArgs> LayoutStarted;
  1345. /// <summary>
  1346. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  1347. /// </summary>
  1348. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  1349. {
  1350. LayoutStarted?.Invoke (args);
  1351. }
  1352. /// <summary>
  1353. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1354. /// </summary>
  1355. /// <remarks>
  1356. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1357. /// </remarks>
  1358. public Action<LayoutEventArgs> LayoutComplete;
  1359. /// <summary>
  1360. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  1361. /// </summary>
  1362. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1363. {
  1364. LayoutComplete?.Invoke (args);
  1365. }
  1366. /// <summary>
  1367. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1368. /// response to the container view or terminal resizing.
  1369. /// </summary>
  1370. /// <remarks>
  1371. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1372. /// </remarks>
  1373. public virtual void LayoutSubviews ()
  1374. {
  1375. if (!layoutNeeded) {
  1376. return;
  1377. }
  1378. Rect oldBounds = Bounds;
  1379. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  1380. viewText.Size = Bounds.Size;
  1381. // Sort out the dependencies of the X, Y, Width, Height properties
  1382. var nodes = new HashSet<View> ();
  1383. var edges = new HashSet<(View, View)> ();
  1384. foreach (var v in InternalSubviews) {
  1385. nodes.Add (v);
  1386. if (v.LayoutStyle == LayoutStyle.Computed) {
  1387. if (v.X is Pos.PosView vX)
  1388. edges.Add ((vX.Target, v));
  1389. if (v.Y is Pos.PosView vY)
  1390. edges.Add ((vY.Target, v));
  1391. if (v.Width is Dim.DimView vWidth)
  1392. edges.Add ((vWidth.Target, v));
  1393. if (v.Height is Dim.DimView vHeight)
  1394. edges.Add ((vHeight.Target, v));
  1395. }
  1396. }
  1397. var ordered = TopologicalSort (nodes, edges);
  1398. foreach (var v in ordered) {
  1399. if (v.LayoutStyle == LayoutStyle.Computed) {
  1400. v.SetRelativeLayout (Frame);
  1401. }
  1402. v.LayoutSubviews ();
  1403. v.layoutNeeded = false;
  1404. }
  1405. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1406. SetRelativeLayout (Frame);
  1407. }
  1408. layoutNeeded = false;
  1409. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1410. }
  1411. /// <summary>
  1412. /// The text displayed by the <see cref="View"/>.
  1413. /// </summary>
  1414. /// <remarks>
  1415. /// <para>
  1416. /// If provided, the text will be drawn before any subviews are drawn.
  1417. /// </para>
  1418. /// <para>
  1419. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  1420. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  1421. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  1422. /// is 1, the text will be clipped.
  1423. /// </para>
  1424. /// <para>
  1425. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  1426. /// <c>(Rune)0xffff</c>.
  1427. /// </para>
  1428. /// </remarks>
  1429. public virtual ustring Text {
  1430. get => viewText.Text;
  1431. set {
  1432. viewText.Text = value;
  1433. SetNeedsDisplay ();
  1434. }
  1435. }
  1436. /// <summary>
  1437. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  1438. /// </summary>
  1439. /// <value>The text alignment.</value>
  1440. public virtual TextAlignment TextAlignment {
  1441. get => viewText.Alignment;
  1442. set {
  1443. viewText.Alignment = value;
  1444. SetNeedsDisplay ();
  1445. }
  1446. }
  1447. /// <summary>
  1448. /// Pretty prints the View
  1449. /// </summary>
  1450. /// <returns></returns>
  1451. public override string ToString ()
  1452. {
  1453. return $"{GetType ().Name}({Id})({Frame})";
  1454. }
  1455. /// <summary>
  1456. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1457. /// </summary>
  1458. public class MouseEventArgs : EventArgs {
  1459. /// <summary>
  1460. /// Constructs.
  1461. /// </summary>
  1462. /// <param name="me"></param>
  1463. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  1464. /// <summary>
  1465. /// The <see cref="MouseEvent"/> for the event.
  1466. /// </summary>
  1467. public MouseEvent MouseEvent { get; set; }
  1468. /// <summary>
  1469. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1470. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1471. /// </summary>
  1472. public bool Handled { get; set; }
  1473. }
  1474. /// <inheritdoc/>
  1475. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1476. {
  1477. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1478. MouseEnter?.Invoke (args);
  1479. if (args.Handled)
  1480. return true;
  1481. if (base.OnMouseEnter (mouseEvent))
  1482. return true;
  1483. return false;
  1484. }
  1485. /// <inheritdoc/>
  1486. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1487. {
  1488. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1489. MouseLeave?.Invoke (args);
  1490. if (args.Handled)
  1491. return true;
  1492. if (base.OnMouseLeave (mouseEvent))
  1493. return true;
  1494. return false;
  1495. }
  1496. /// <summary>
  1497. /// Method invoked when a mouse event is generated
  1498. /// </summary>
  1499. /// <param name="mouseEvent"></param>
  1500. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1501. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1502. {
  1503. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1504. MouseClick?.Invoke (args);
  1505. if (args.Handled)
  1506. return true;
  1507. if (MouseEvent (mouseEvent))
  1508. return true;
  1509. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  1510. if (!HasFocus && SuperView != null) {
  1511. SuperView.SetFocus (this);
  1512. SetNeedsDisplay ();
  1513. }
  1514. return true;
  1515. }
  1516. return false;
  1517. }
  1518. }
  1519. }