View.cs 62 KB

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