View.cs 52 KB

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