View.cs 54 KB

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