View.cs 62 KB

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