View.cs 64 KB

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