View.cs 61 KB

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