View.cs 53 KB

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