View.cs 53 KB

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