View.cs 53 KB

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