ViewLayout.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. namespace Terminal.Gui;
  7. /// <summary>
  8. /// <para>
  9. /// Indicates the LayoutStyle for the <see cref="View"/>.
  10. /// </para>
  11. /// <para>
  12. /// If Absolute, the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  13. /// <see cref="View.Height"/>
  14. /// objects are all absolute values and are not relative. The position and size of the view is described by
  15. /// <see cref="View.Frame"/>.
  16. /// </para>
  17. /// <para>
  18. /// If Computed, one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  19. /// <see cref="View.Height"/>
  20. /// objects are relative to the <see cref="View.SuperView"/> and are computed at layout time.
  21. /// </para>
  22. /// <para>
  23. /// Indicates the LayoutStyle for the <see cref="View"/>.
  24. /// </para>
  25. /// <para>
  26. /// If Absolute, the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  27. /// <see cref="View.Height"/>
  28. /// objects are all absolute values and are not relative. The position and size of the view is described by
  29. /// <see cref="View.Frame"/>.
  30. /// </para>
  31. /// <para>
  32. /// If Computed, one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  33. /// <see cref="View.Height"/>
  34. /// objects are relative to the <see cref="View.SuperView"/> and are computed at layout time.
  35. /// </para>
  36. /// </summary>
  37. public enum LayoutStyle {
  38. /// <summary>
  39. /// Indicates the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and <see cref="View.Height"/>
  40. /// objects are all absolute values and are not relative. The position and size of the view is described by
  41. /// <see cref="View.Frame"/>.
  42. /// </summary>
  43. Absolute,
  44. /// <summary>
  45. /// Indicates one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  46. /// <see cref="View.Height"/>
  47. /// objects are relative to the <see cref="View.SuperView"/> and are computed at layout time. The position and size of the
  48. /// view
  49. /// will be computed based on these objects at layout time. <see cref="View.Frame"/> will provide the absolute computed
  50. /// values.
  51. /// </summary>
  52. Computed
  53. }
  54. public partial class View {
  55. bool _autoSize;
  56. Rect _frame;
  57. Dim _height = Dim.Sized (0);
  58. Dim _width = Dim.Sized (0);
  59. Pos _x = Pos.At (0);
  60. Pos _y = Pos.At (0);
  61. /// <summary>
  62. /// Gets or sets the absolute location and dimension of the view.
  63. /// </summary>
  64. /// <value>
  65. /// The rectangle describing absolute location and dimension of the view,
  66. /// in coordinates relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.
  67. /// </value>
  68. /// <remarks>
  69. /// <para>
  70. /// Frame is relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.
  71. /// </para>
  72. /// <para>
  73. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/>
  74. /// to the values of the corresponding properties of the <paramref name="value"/> parameter.
  75. /// </para>
  76. /// <para>
  77. /// This causes <see cref="LayoutStyle"/> to be <see cref="LayoutStyle.Absolute"/>.
  78. /// </para>
  79. /// <para>
  80. /// Altering the Frame will eventually (when the view hierarchy is next laid out via see cref="LayoutSubviews"/>)
  81. /// cause <see cref="LayoutSubview(View, Rect)"/> and <see cref="OnDrawContent(Rect)"/> methods to be called.
  82. /// </para>
  83. /// </remarks>
  84. public Rect Frame {
  85. get => _frame;
  86. set {
  87. _frame = new Rect (value.X, value.Y, Math.Max (value.Width, 0), Math.Max (value.Height, 0));
  88. // If Frame gets set, by definition, the View is now LayoutStyle.Absolute, so
  89. // set all Pos/Dim to Absolute values.
  90. _x = _frame.X;
  91. _y = _frame.Y;
  92. _width = _frame.Width;
  93. _height = _frame.Height;
  94. // TODO: Figure out if the below can be optimized.
  95. if (IsInitialized /*|| LayoutStyle == LayoutStyle.Absolute*/) {
  96. LayoutAdornments ();
  97. SetTextFormatterSize ();
  98. SetNeedsLayout ();
  99. SetNeedsDisplay ();
  100. }
  101. }
  102. }
  103. /// <summary>
  104. /// The frame (specified as a <see cref="Thickness"/>) that separates a View from other SubViews of the same SuperView.
  105. /// The margin offsets the <see cref="Bounds"/> from the <see cref="Frame"/>.
  106. /// </summary>
  107. /// <remarks>
  108. /// <para>
  109. /// The adornments (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the View's
  110. /// content and are not clipped by the View's Clip Area.
  111. /// </para>
  112. /// <para>
  113. /// Changing the size of an adornment (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>)
  114. /// will change the size of <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout
  115. /// of the <see cref="SuperView"/> and its <see cref="Subviews"/>.
  116. /// </para>
  117. /// </remarks>
  118. public Margin Margin { get; private set; }
  119. /// <summary>
  120. /// The adornment (specified as a <see cref="Thickness"/>) inside of the view that offsets the <see cref="Bounds"/> from the
  121. /// <see cref="Margin"/>.
  122. /// The Border provides the space for a visual border (drawn using line-drawing glyphs) and the Title.
  123. /// The Border expands inward; in other words if `Border.Thickness.Top == 2` the border and
  124. /// title will take up the first row and the second row will be filled with spaces.
  125. /// </summary>
  126. /// <remarks>
  127. /// <para>
  128. /// <see cref="BorderStyle"/> provides a simple helper for turning a simple border frame on or off.
  129. /// </para>
  130. /// <para>
  131. /// The adornments (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the View's
  132. /// content and are not clipped by the View's Clip Area.
  133. /// </para>
  134. /// <para>
  135. /// Changing the size of a frame (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>)
  136. /// will change the size of the <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout
  137. /// of the
  138. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  139. /// </para>
  140. /// </remarks>
  141. public Border Border { get; private set; }
  142. /// <summary>
  143. /// Gets or sets whether the view has a one row/col thick border.
  144. /// </summary>
  145. /// <remarks>
  146. /// <para>
  147. /// This is a helper for manipulating the view's <see cref="Border"/>. Setting this property to any value other
  148. /// than
  149. /// <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s <see cref="Adornment.Thickness"/>
  150. /// to `1` and <see cref="BorderStyle"/> to the value.
  151. /// </para>
  152. /// <para>
  153. /// Setting this property to <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s
  154. /// <see cref="Adornment.Thickness"/>
  155. /// to `0` and <see cref="BorderStyle"/> to <see cref="LineStyle.None"/>.
  156. /// </para>
  157. /// <para>
  158. /// For more advanced customization of the view's border, manipulate see <see cref="Border"/> directly.
  159. /// </para>
  160. /// </remarks>
  161. public LineStyle BorderStyle {
  162. get => Border.LineStyle;
  163. set {
  164. if (value != LineStyle.None) {
  165. Border.Thickness = new Thickness (1);
  166. } else {
  167. Border.Thickness = new Thickness (0);
  168. }
  169. Border.LineStyle = value;
  170. LayoutAdornments ();
  171. SetNeedsLayout ();
  172. }
  173. }
  174. /// <summary>
  175. /// The frame (specified as a <see cref="Thickness"/>) inside of the view that offsets the <see cref="Bounds"/> from the
  176. /// <see cref="Border"/>.
  177. /// </summary>
  178. /// <remarks>
  179. /// <para>
  180. /// The adornments (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the View's
  181. /// content and are not clipped by the View's Clip Area.
  182. /// </para>
  183. /// <para>
  184. /// Changing the size of a frame (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>)
  185. /// will change the size of the <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout
  186. /// of the
  187. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  188. /// </para>
  189. /// </remarks>
  190. public Padding Padding { get; private set; }
  191. /// <summary>
  192. /// <para>
  193. /// Gets the thickness describing the sum of the Adornments' thicknesses.
  194. /// </para>
  195. /// </summary>
  196. /// <returns>A thickness that describes the sum of the Adornments' thicknesses.</returns>
  197. public Thickness GetAdornmentsThickness ()
  198. {
  199. int left = Margin.Thickness.Left + Border.Thickness.Left + Padding.Thickness.Left;
  200. int top = Margin.Thickness.Top + Border.Thickness.Top + Padding.Thickness.Top;
  201. int right = Margin.Thickness.Right + Border.Thickness.Right + Padding.Thickness.Right;
  202. int bottom = Margin.Thickness.Bottom + Border.Thickness.Bottom + Padding.Thickness.Bottom;
  203. return new Thickness (left, top, right, bottom);
  204. }
  205. /// <summary>
  206. /// Helper to get the X and Y offset of the Bounds from the Frame. This is the sum of the Left and Top properties of
  207. /// <see cref="Margin"/>, <see cref="Border"/> and <see cref="Padding"/>.
  208. /// </summary>
  209. public Point GetBoundsOffset () => new (Padding?.Thickness.GetInside (Padding.Frame).X ?? 0, Padding?.Thickness.GetInside (Padding.Frame).Y ?? 0);
  210. /// <summary>
  211. /// This internal method is overridden by Adornment to do nothing to prevent recursion during View construction.
  212. /// And, because Adornments don't have Adornments. It's internal to support unit tests.
  213. /// </summary>
  214. /// <param name="adornmentType"></param>
  215. /// <exception cref="ArgumentNullException"></exception>
  216. /// <exception cref="ArgumentException"></exception>
  217. internal virtual Adornment CreateAdornment (Type adornmentType)
  218. {
  219. void ThicknessChangedHandler (object sender, EventArgs e)
  220. {
  221. if (IsInitialized) {
  222. LayoutAdornments ();
  223. }
  224. SetNeedsLayout ();
  225. SetNeedsDisplay ();
  226. }
  227. Adornment adornment;
  228. adornment = Activator.CreateInstance (adornmentType, this) as Adornment;
  229. adornment.ThicknessChanged += ThicknessChangedHandler;
  230. return adornment;
  231. }
  232. /// <summary>
  233. /// Controls how the View's <see cref="Frame"/> is computed during <see cref="LayoutSubviews"/>. If the style is set to
  234. /// <see cref="LayoutStyle.Absolute"/>, LayoutSubviews does not change the <see cref="Frame"/>.
  235. /// If the style is <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using
  236. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  237. /// </summary>
  238. /// <remarks>
  239. /// <para>
  240. /// Setting this property to <see cref="LayoutStyle.Absolute"/> will cause <see cref="Frame"/> to determine the
  241. /// size and position of the view. <see cref="X"/> and <see cref="Y"/> will be set to <see cref="Dim.DimAbsolute"/> using <see cref="Frame"/>.
  242. /// </para>
  243. /// <para>
  244. /// Setting this property to <see cref="LayoutStyle.Computed"/> will cause the view to use the <see cref="LayoutSubviews"/> method to
  245. /// size and position of the view. If either of the <see cref="X"/> and <see cref="Y"/> properties are `null` they will be set to <see cref="Pos.PosAbsolute"/> using
  246. /// the current value of <see cref="Frame"/>.
  247. /// If either of the <see cref="Width"/> and <see cref="Height"/> properties are `null` they will be set to <see cref="Dim.DimAbsolute"/> using <see cref="Frame"/>.
  248. /// </para>
  249. /// </remarks>
  250. /// <value>The layout style.</value>
  251. public LayoutStyle LayoutStyle {
  252. get {
  253. if (_x is Pos.PosAbsolute && _y is Pos.PosAbsolute && _width is Dim.DimAbsolute && _height is Dim.DimAbsolute) {
  254. return LayoutStyle.Absolute;
  255. }
  256. return LayoutStyle.Computed;
  257. }
  258. }
  259. /// <summary>
  260. /// The bounds represent the View-relative rectangle used for this view; the area inside of the view where subviews and
  261. /// content are presented.
  262. /// </summary>
  263. /// <value>The rectangle describing the location and size of the area where the views' subviews and content are drawn.</value>
  264. /// <remarks>
  265. /// <para>
  266. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/> the value of Bounds is indeterminate until
  267. /// the view has been initialized (<see cref="IsInitialized"/> is true) and <see cref="LayoutSubviews"/> has been
  268. /// called.
  269. /// </para>
  270. /// <para>
  271. /// Updates to the Bounds updates <see cref="Frame"/>, and has the same effect as updating the
  272. /// <see cref="Frame"/>.
  273. /// </para>
  274. /// <para>
  275. /// Altering the Bounds will eventually (when the view is next laid out) cause the
  276. /// <see cref="LayoutSubview(View, Rect)"/>
  277. /// and <see cref="OnDrawContent(Rect)"/> methods to be called.
  278. /// </para>
  279. /// <para>
  280. /// Because <see cref="Bounds"/> coordinates are relative to the upper-left corner of the <see cref="View"/>,
  281. /// the coordinates of the upper-left corner of the rectangle returned by this property are (0,0).
  282. /// Use this property to obtain the size of the area of the view for tasks such as drawing the view's contents.
  283. /// </para>
  284. /// </remarks>
  285. public virtual Rect Bounds {
  286. get {
  287. #if DEBUG
  288. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized) {
  289. Debug.WriteLine ($"WARNING: Bounds is being accessed before the View has been initialized. This is likely a bug in {this}");
  290. }
  291. #endif // DEBUG
  292. // BUGBUG: I think there's a bug here. This should be && not ||
  293. if (Margin == null || Border == null || Padding == null) {
  294. return new Rect (default, Frame.Size);
  295. }
  296. var width = Math.Max (0, Frame.Size.Width - Margin.Thickness.Horizontal - Border.Thickness.Horizontal - Padding.Thickness.Horizontal);
  297. var height = Math.Max (0, Frame.Size.Height - Margin.Thickness.Vertical - Border.Thickness.Vertical - Padding.Thickness.Vertical);
  298. return new Rect (Point.Empty, new Size (width, height));
  299. }
  300. set {
  301. // TODO: Should we enforce Bounds.X/Y == 0? The code currently ignores value.X/Y which is
  302. // TODO: correct behavior, but is silent. Perhaps an exception?
  303. #if DEBUG
  304. if (value.Location != Point.Empty) {
  305. Debug.WriteLine ($"WARNING: Bounds.Location must always be 0,0. Location ({value.Location}) is ignored. {this}");
  306. }
  307. #endif // DEBUG
  308. Frame = new Rect (Frame.Location,
  309. new Size (
  310. value.Size.Width + Margin.Thickness.Horizontal + Border.Thickness.Horizontal + Padding.Thickness.Horizontal,
  311. value.Size.Height + Margin.Thickness.Vertical + Border.Thickness.Vertical + Padding.Thickness.Vertical
  312. )
  313. );
  314. }
  315. }
  316. /// <summary>
  317. /// Gets or sets the X position for the view (the column).
  318. /// </summary>
  319. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  320. /// <remarks>
  321. /// <para>
  322. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the
  323. /// view has been initialized (<see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rect)"/> has been
  324. /// called.
  325. /// </para>
  326. /// <para>
  327. /// Changing this property will eventually (when the view is next drawn) cause the
  328. /// <see cref="LayoutSubview(View, Rect)"/> and
  329. /// <see cref="OnDrawContent(Rect)"/> methods to be called.
  330. /// </para>
  331. /// <para>
  332. /// Changing this property will cause <see cref="Frame"/> to be updated. If
  333. /// the new value is not of type <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to
  334. /// <see cref="LayoutStyle.Computed"/>.
  335. /// </para>
  336. /// <para>
  337. /// The default value is <c>Pos.At (0)</c>.
  338. /// </para>
  339. /// </remarks>
  340. public Pos X {
  341. get => VerifyIsInitialized (_x, nameof (X));
  342. set {
  343. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  344. OnResizeNeeded ();
  345. }
  346. }
  347. /// <summary>
  348. /// Gets or sets the Y position for the view (the row).
  349. /// </summary>
  350. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  351. /// <remarks>
  352. /// <para>
  353. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the
  354. /// view has been initialized (<see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rect)"/> has been
  355. /// called.
  356. /// </para>
  357. /// <para>
  358. /// Changing this property will eventually (when the view is next drawn) cause the
  359. /// <see cref="LayoutSubview(View, Rect)"/> and
  360. /// <see cref="OnDrawContent(Rect)"/> methods to be called.
  361. /// </para>
  362. /// <para>
  363. /// Changing this property will cause <see cref="Frame"/> to be updated. If
  364. /// the new value is not of type <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to
  365. /// <see cref="LayoutStyle.Computed"/>.
  366. /// </para>
  367. /// <para>
  368. /// The default value is <c>Pos.At (0)</c>.
  369. /// </para>
  370. /// </remarks>
  371. public Pos Y {
  372. get => VerifyIsInitialized (_y, nameof (Y));
  373. set {
  374. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  375. OnResizeNeeded ();
  376. }
  377. }
  378. /// <summary>
  379. /// Gets or sets the width dimension of the view.
  380. /// </summary>
  381. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  382. /// <remarks>
  383. /// <para>
  384. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the
  385. /// view has been initialized (<see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rect)"/> has been
  386. /// called.
  387. /// </para>
  388. /// <para>
  389. /// Changing this property will eventually (when the view is next drawn) cause the
  390. /// <see cref="LayoutSubview(View, Rect)"/>
  391. /// and <see cref="OnDrawContent(Rect)"/> methods to be called.
  392. /// </para>
  393. /// <para>
  394. /// Changing this property will cause <see cref="Frame"/> to be updated. If
  395. /// the new value is not of type <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to
  396. /// <see cref="LayoutStyle.Computed"/>.
  397. /// </para>
  398. /// <para>
  399. /// The default value is <c>Dim.Sized (0)</c>.
  400. /// </para>
  401. /// </remarks>
  402. public Dim Width {
  403. get => VerifyIsInitialized (_width, nameof (Width));
  404. set {
  405. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  406. if (ValidatePosDim) {
  407. CheckDimAuto ();
  408. var isValidNewAutSize = AutoSize && IsValidAutoSizeWidth (_width);
  409. if (IsAdded && AutoSize && !isValidNewAutSize) {
  410. throw new InvalidOperationException ("Must set AutoSize to false before set the Width.");
  411. }
  412. }
  413. OnResizeNeeded ();
  414. }
  415. }
  416. /// <summary>
  417. /// Gets or sets the height dimension of the view.
  418. /// Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.
  419. /// </summary>
  420. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  421. /// <remarks>
  422. /// <para>
  423. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the
  424. /// view has been initialized (<see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rect)"/> has been
  425. /// called.
  426. /// </para>
  427. /// <para>
  428. /// Changing this property will eventually (when the view is next drawn) cause the
  429. /// <see cref="LayoutSubview(View, Rect)"/>
  430. /// and <see cref="OnDrawContent(Rect)"/> methods to be called.
  431. /// </para>
  432. /// <para>
  433. /// Changing this property will cause <see cref="Frame"/> to be updated. If
  434. /// the new value is not of type <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to
  435. /// <see cref="LayoutStyle.Computed"/>.
  436. /// </para>
  437. /// <para>
  438. /// The default value is <c>Dim.Sized (0)</c>.
  439. /// </para>
  440. /// </remarks>
  441. public Dim Height {
  442. get => VerifyIsInitialized (_height, nameof (Height));
  443. set {
  444. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  445. if (ValidatePosDim) {
  446. CheckDimAuto ();
  447. var isValidNewAutSize = AutoSize && IsValidAutoSizeHeight (_height);
  448. if (IsAdded && AutoSize && !isValidNewAutSize) {
  449. throw new InvalidOperationException ("Must set AutoSize to false before setting the Height.");
  450. }
  451. }
  452. OnResizeNeeded ();
  453. }
  454. }
  455. /// <summary>
  456. /// Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.
  457. /// </summary>
  458. /// <remarks>
  459. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>,
  460. /// and <see cref="Height"/>
  461. /// during set operations and in <see cref="LayoutSubviews"/>. If invalid settings are discovered exceptions will be thrown
  462. /// indicating the error.
  463. /// This will impose a performance penalty and thus should only be used for debugging.
  464. /// </remarks>
  465. public bool ValidatePosDim { get; set; }
  466. /// <summary>
  467. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  468. /// Views dimensions.
  469. /// </summary>
  470. /// <exception cref="InvalidOperationException"></exception>
  471. void CheckDimAuto ()
  472. {
  473. if (!ValidatePosDim || !IsInitialized || (Width is not Dim.DimAuto && Height is not Dim.DimAuto)) {
  474. return;
  475. }
  476. void ThrowInvalid (View view, object checkPosDim, string name)
  477. {
  478. // TODO: Figure out how to make CheckDimAuto deal with PosCombine
  479. object bad = null;
  480. switch (checkPosDim) {
  481. case Pos pos and not Pos.PosAbsolute and not Pos.PosView and not Pos.PosCombine:
  482. bad = pos;
  483. break;
  484. case Pos pos and Pos.PosCombine:
  485. // Recursively check for not Absolute or not View
  486. ThrowInvalid (view, (pos as Pos.PosCombine)._left, name);
  487. ThrowInvalid (view, (pos as Pos.PosCombine)._right, name);
  488. break;
  489. case Dim dim and not Dim.DimAbsolute and not Dim.DimView and not Dim.DimCombine:
  490. bad = dim;
  491. break;
  492. case Dim dim and Dim.DimCombine:
  493. // Recursively check for not Absolute or not View
  494. ThrowInvalid (view, (dim as Dim.DimCombine)._left, name);
  495. ThrowInvalid (view, (dim as Dim.DimCombine)._right, name);
  496. break;
  497. }
  498. if (bad != null) {
  499. throw new InvalidOperationException (
  500. @$"{view.GetType ().Name}.{name} = {bad.GetType ().Name} which depends on the SuperView's dimensions and the SuperView uses Dim.Auto.");
  501. }
  502. }
  503. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  504. foreach (var view in Subviews) {
  505. if (Width is Dim.DimAuto { _min: null }) {
  506. ThrowInvalid (view, view.Width, nameof (view.Width));
  507. ThrowInvalid (view, view.X, nameof (view.X));
  508. }
  509. if (Height is Dim.DimAuto { _min: null }) {
  510. ThrowInvalid (view, view.Height, nameof (view.Height));
  511. ThrowInvalid (view, view.Y, nameof (view.Y));
  512. }
  513. }
  514. }
  515. internal bool LayoutNeeded { get; private set; } = true;
  516. /// <summary>
  517. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  518. /// within <see cref="Bounds"/>.
  519. /// <para>
  520. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If <see langword="true"/>
  521. /// then
  522. /// <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can fit;
  523. /// if <see cref="Text"/> won't fit the view will be resized as needed.
  524. /// </para>
  525. /// <para>
  526. /// If <see cref="AutoSize"/> is set to <see langword="true"/> then <see cref="Width"/> and <see cref="Height"/>
  527. /// will be changed to <see cref="Dim.DimAbsolute"/> if they are not already.
  528. /// </para>
  529. /// <para>
  530. /// If <see cref="AutoSize"/> is set to <see langword="false"/> then <see cref="Width"/> and <see cref="Height"/>
  531. /// will left unchanged.
  532. /// </para>
  533. /// </summary>
  534. public virtual bool AutoSize {
  535. get => _autoSize;
  536. set {
  537. var v = ResizeView (value);
  538. TextFormatter.AutoSize = v;
  539. if (_autoSize != v) {
  540. _autoSize = v;
  541. TextFormatter.NeedsFormat = true;
  542. UpdateTextFormatterText ();
  543. OnResizeNeeded ();
  544. }
  545. }
  546. }
  547. /// <summary>
  548. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  549. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  550. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being
  551. /// initialized.
  552. /// </summary>
  553. public event EventHandler Initialized;
  554. // Diagnostics to highlight when X or Y is read before the view has been initialized
  555. Pos VerifyIsInitialized (Pos pos, string member)
  556. {
  557. #if DEBUG
  558. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized) {
  559. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; {member} is indeterminate {pos}. This is potentially a bug.");
  560. }
  561. #endif // DEBUG
  562. return pos;
  563. }
  564. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  565. Dim VerifyIsInitialized (Dim dim, string member)
  566. {
  567. #if DEBUG
  568. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized) {
  569. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; {member} is indeterminate: {dim}. This is potentially a bug.");
  570. }
  571. #endif // DEBUG
  572. return dim;
  573. }
  574. /// <summary>
  575. /// Called whenever the view needs to be resized. This is called whenever <see cref="Frame"/>,
  576. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or <see cref="View.Height"/> changes.
  577. /// </summary>
  578. /// <remarks>
  579. /// <para>
  580. /// Determines the relative bounds of the <see cref="View"/> and its <see cref="Frame"/>s, and then calls
  581. /// <see cref="SetRelativeLayout(Rect)"/> to update the view.
  582. /// </para>
  583. /// </remarks>
  584. internal void OnResizeNeeded ()
  585. {
  586. // TODO: Identify a real-world use-case where this API should be virtual.
  587. // TODO: Until then leave it `internal` and non-virtual
  588. // First try SuperView.Bounds, then Application.Top, then Driver.Bounds.
  589. // Finally, if none of those are valid, use int.MaxValue (for Unit tests).
  590. var relativeBounds = SuperView is { IsInitialized: true } ? SuperView.Bounds :
  591. Application.Top != null && Application.Top.IsInitialized ? Application.Top.Bounds :
  592. Application.Driver?.Bounds ??
  593. new Rect (0, 0, int.MaxValue, int.MaxValue);
  594. SetRelativeLayout (relativeBounds);
  595. // TODO: Determine what, if any of the below is actually needed here.
  596. if (IsInitialized) {
  597. SetFrameToFitText ();
  598. LayoutAdornments ();
  599. SetTextFormatterSize ();
  600. SetNeedsLayout ();
  601. SetNeedsDisplay ();
  602. }
  603. }
  604. /// <summary>
  605. /// Sets the internal <see cref="LayoutNeeded"/> flag for this View and all of it's
  606. /// subviews and it's SuperView. The main loop will call SetRelativeLayout and LayoutSubviews
  607. /// for any view with <see cref="LayoutNeeded"/> set.
  608. /// </summary>
  609. internal void SetNeedsLayout ()
  610. {
  611. if (LayoutNeeded) {
  612. return;
  613. }
  614. LayoutNeeded = true;
  615. foreach (var view in Subviews) {
  616. view.SetNeedsLayout ();
  617. }
  618. TextFormatter.NeedsFormat = true;
  619. SuperView?.SetNeedsLayout ();
  620. }
  621. /// <summary>
  622. /// Indicates that the view does not need to be laid out.
  623. /// </summary>
  624. protected void ClearLayoutNeeded () => LayoutNeeded = false;
  625. /// <summary>
  626. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means
  627. /// relative to the View's <see cref="SuperView"/>'s <see cref="Bounds"/>.
  628. /// </summary>
  629. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.</returns>
  630. /// <param name="x">Screen-relative column.</param>
  631. /// <param name="y">Screen-relative row.</param>
  632. public Point ScreenToFrame (int x, int y)
  633. {
  634. var superViewBoundsOffset = SuperView?.GetBoundsOffset () ?? Point.Empty;
  635. var ret = new Point (x - Frame.X - superViewBoundsOffset.X, y - Frame.Y - superViewBoundsOffset.Y);
  636. if (SuperView != null) {
  637. var superFrame = SuperView.ScreenToFrame (x - superViewBoundsOffset.X, y - superViewBoundsOffset.Y);
  638. ret = new Point (superFrame.X - Frame.X, superFrame.Y - Frame.Y);
  639. }
  640. return ret;
  641. }
  642. /// <summary>
  643. /// Converts a screen-relative coordinate to a bounds-relative coordinate.
  644. /// </summary>
  645. /// <returns>The coordinate relative to this view's <see cref="Bounds"/>.</returns>
  646. /// <param name="x">Screen-relative column.</param>
  647. /// <param name="y">Screen-relative row.</param>
  648. public Point ScreenToBounds (int x, int y)
  649. {
  650. var screen = ScreenToFrame (x, y);
  651. var boundsOffset = GetBoundsOffset ();
  652. return new Point (screen.X - boundsOffset.X, screen.Y - boundsOffset.Y);
  653. }
  654. /// <summary>
  655. /// Converts a <see cref="Bounds"/>-relative coordinate to a screen-relative coordinate. The output is optionally clamped
  656. /// to the screen dimensions.
  657. /// </summary>
  658. /// <param name="x"><see cref="Bounds"/>-relative column.</param>
  659. /// <param name="y"><see cref="Bounds"/>-relative row.</param>
  660. /// <param name="rx">Absolute column; screen-relative.</param>
  661. /// <param name="ry">Absolute row; screen-relative.</param>
  662. /// <param name="clamped">
  663. /// If <see langword="true"/>, <paramref name="rx"/> and <paramref name="ry"/> will be clamped to the
  664. /// screen dimensions (will never be negative and will always be less than <see cref="ConsoleDriver.Cols"/> and
  665. /// <see cref="ConsoleDriver.Rows"/>, respectively.
  666. /// </param>
  667. public virtual void BoundsToScreen (int x, int y, out int rx, out int ry, bool clamped = true)
  668. {
  669. var boundsOffset = GetBoundsOffset ();
  670. rx = x + Frame.X + boundsOffset.X;
  671. ry = y + Frame.Y + boundsOffset.Y;
  672. var super = SuperView;
  673. while (super != null) {
  674. boundsOffset = super.GetBoundsOffset ();
  675. rx += super.Frame.X + boundsOffset.X;
  676. ry += super.Frame.Y + boundsOffset.Y;
  677. super = super.SuperView;
  678. }
  679. // The following ensures that the cursor is always in the screen boundaries.
  680. if (clamped) {
  681. ry = Math.Min (ry, Driver.Rows - 1);
  682. rx = Math.Min (rx, Driver.Cols - 1);
  683. }
  684. }
  685. /// <summary>
  686. /// Converts a <see cref="Bounds"/>-relative region to a screen-relative region.
  687. /// </summary>
  688. public Rect BoundsToScreen (Rect region)
  689. {
  690. BoundsToScreen (region.X, region.Y, out var x, out var y, false);
  691. return new Rect (x, y, region.Width, region.Height);
  692. }
  693. /// <summary>
  694. /// Gets the <see cref="Frame"/> with a screen-relative location.
  695. /// </summary>
  696. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  697. public virtual Rect FrameToScreen ()
  698. {
  699. var ret = Frame;
  700. var super = SuperView;
  701. while (super != null) {
  702. var boundsOffset = super.GetBoundsOffset ();
  703. ret.X += super.Frame.X + boundsOffset.X;
  704. ret.Y += super.Frame.Y + boundsOffset.Y;
  705. super = super.SuperView;
  706. }
  707. return ret;
  708. }
  709. /// <summary>
  710. /// Applies the view's position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  711. /// <see cref="Height"/>) to
  712. /// <see cref="Frame"/>, given a rectangle describing the SuperView's Bounds (nominally the same as
  713. /// <c>this.SuperView.Bounds</c>).
  714. /// </summary>
  715. /// <param name="superviewBounds">
  716. /// The rectangle describing the SuperView's Bounds (nominally the same as
  717. /// <c>this.SuperView.Bounds</c>).
  718. /// </param>
  719. internal void SetRelativeLayout (Rect superviewBounds)
  720. {
  721. Debug.Assert (_x != null);
  722. Debug.Assert (_y != null);
  723. Debug.Assert (_width != null);
  724. Debug.Assert (_height != null);
  725. CheckDimAuto ();
  726. int newX, newW, newY, newH;
  727. var autosize = Size.Empty;
  728. if (AutoSize) {
  729. // Note this is global to this function and used as such within the local functions defined
  730. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  731. autosize = GetTextAutoSize ();
  732. }
  733. // TODO: Since GetNewLocationAndDimension does not depend on View, it can be moved into PosDim.cs
  734. // TODO: to make architecture more clean. Do this after DimAuto is implemented and the
  735. // TODO: View.AutoSize stuff is removed.
  736. // Returns the new dimension (width or height) and location (x or y) for the View given
  737. // the superview's Bounds
  738. // the current Pos (View.X or View.Y)
  739. // the current Dim (View.Width or View.Height)
  740. // This method is called recursively if pos is Pos.PosCombine
  741. (int newLocation, int newDimension) GetNewLocationAndDimension (bool width, Rect superviewBounds, Pos pos, Dim dim, int autosizeDimension)
  742. {
  743. // Gets the new dimension (width or height, dependent on `width`) of the given Dim given:
  744. // location: the current location (x or y)
  745. // dimension: the new dimension (width or height) (if relevant for Dim type)
  746. // autosize: the size to use if autosize = true
  747. // This method is recursive if d is Dim.DimCombine
  748. int GetNewDimension (Dim d, int location, int dimension, int autosize)
  749. {
  750. int newDimension;
  751. switch (d) {
  752. case Dim.DimCombine combine:
  753. // TODO: Move combine logic into DimCombine?
  754. var leftNewDim = GetNewDimension (combine._left, location, dimension, autosize);
  755. var rightNewDim = GetNewDimension (combine._right, location, dimension, autosize);
  756. if (combine._add) {
  757. newDimension = leftNewDim + rightNewDim;
  758. } else {
  759. newDimension = leftNewDim - rightNewDim;
  760. }
  761. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  762. break;
  763. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  764. newDimension = d.Anchor (dimension);
  765. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  766. break;
  767. case Dim.DimAuto auto:
  768. var thickness = GetAdornmentsThickness ();
  769. var text = 0;
  770. var subviews = 0;
  771. if (auto._style is Dim.DimAutoStyle.Text or Dim.DimAutoStyle.Auto) {
  772. if (Id == "vlabel") {
  773. }
  774. text = int.Max (width ? TextFormatter.Size.Width : TextFormatter.Size.Height,
  775. auto._min?.Anchor (width ? superviewBounds.Width : superviewBounds.Height) ?? 0);
  776. }
  777. if (auto._style is Dim.DimAutoStyle.Subviews or Dim.DimAutoStyle.Auto) {
  778. subviews = Subviews.Count == 0 ? 0 : Subviews
  779. .Where (v => width ? v.X is not Pos.PosAnchorEnd : v.Y is not Pos.PosAnchorEnd)
  780. .Max (v => width ? v.Frame.X + v.Frame.Width : v.Frame.Y + v.Frame.Height);
  781. }
  782. var max = int.Max (text, subviews);
  783. newDimension = int.Max (width ? max + thickness.Left + thickness.Right : max + thickness.Top + thickness.Bottom,
  784. auto._min?.Anchor (width ? superviewBounds.Width : superviewBounds.Height) ?? 0);
  785. break;
  786. case Dim.DimAbsolute:
  787. // DimAbsoulte.Anchor (int width) ignores width and returns n
  788. newDimension = Math.Max (d.Anchor (0), 0);
  789. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  790. break;
  791. case Dim.DimFill:
  792. default:
  793. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  794. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  795. break;
  796. }
  797. return newDimension;
  798. }
  799. int newDimension, newLocation;
  800. var superviewDimension = width ? superviewBounds.Width : superviewBounds.Height;
  801. // Determine new location
  802. switch (pos) {
  803. case Pos.PosCenter posCenter:
  804. // For Center, the dimension is dependent on location, but we need to force getting the dimension first
  805. // using a location of 0
  806. newDimension = Math.Max (GetNewDimension (dim, 0, superviewDimension, autosizeDimension), 0);
  807. newLocation = posCenter.Anchor (superviewDimension - newDimension);
  808. newDimension = Math.Max (GetNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  809. break;
  810. case Pos.PosCombine combine:
  811. // TODO: Move combine logic into PosCombine?
  812. // TODO: Move combine logic into PosCombine?
  813. int left, right;
  814. (left, newDimension) = GetNewLocationAndDimension (width, superviewBounds, combine._left, dim, autosizeDimension);
  815. (right, newDimension) = GetNewLocationAndDimension (width, superviewBounds, combine._right, dim, autosizeDimension);
  816. if (combine._add) {
  817. newLocation = left + right;
  818. } else {
  819. newLocation = left - right;
  820. }
  821. newDimension = Math.Max (GetNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  822. break;
  823. case Pos.PosAnchorEnd:
  824. case Pos.PosAbsolute:
  825. case Pos.PosFactor:
  826. case Pos.PosFunc:
  827. case Pos.PosView:
  828. default:
  829. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  830. newDimension = Math.Max (GetNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  831. break;
  832. }
  833. return (newLocation, newDimension);
  834. }
  835. // horizontal/width
  836. (newX, newW) = GetNewLocationAndDimension (true, superviewBounds, _x, _width, autosize.Width);
  837. // vertical/height
  838. (newY, newH) = GetNewLocationAndDimension (false, superviewBounds, _y, _height, autosize.Height);
  839. var r = new Rect (newX, newY, newW, newH);
  840. if (Frame != r) {
  841. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  842. // the view LayoutStyle.Absolute.
  843. _frame = r;
  844. if (_x is Pos.PosAbsolute) {
  845. _x = Frame.X;
  846. }
  847. if (_y is Pos.PosAbsolute) {
  848. _y = Frame.Y;
  849. }
  850. if (_width is Dim.DimAbsolute) {
  851. _width = Frame.Width;
  852. }
  853. if (_height is Dim.DimAbsolute) {
  854. _height = Frame.Height;
  855. }
  856. if (IsInitialized) {
  857. // TODO: Figure out what really is needed here. All unit tests (except AutoSize) pass as-is
  858. SetTextFormatterSize ();
  859. SetNeedsLayout ();
  860. }
  861. // BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
  862. if (!SetFrameToFitText ()) {
  863. SetTextFormatterSize ();
  864. }
  865. }
  866. }
  867. /// <summary>
  868. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  869. /// </summary>
  870. /// <remarks>
  871. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise
  872. /// changed.
  873. /// </remarks>
  874. public event EventHandler<LayoutEventArgs> LayoutStarted;
  875. /// <summary>
  876. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been
  877. /// laid out.
  878. /// </summary>
  879. internal virtual void OnLayoutStarted (LayoutEventArgs args) => LayoutStarted?.Invoke (this, args);
  880. /// <summary>
  881. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  882. /// </summary>
  883. /// <remarks>
  884. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise
  885. /// changed.
  886. /// </remarks>
  887. public event EventHandler<LayoutEventArgs> LayoutComplete;
  888. /// <summary>
  889. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been
  890. /// laid out.
  891. /// </summary>
  892. internal virtual void OnLayoutComplete (LayoutEventArgs args) => LayoutComplete?.Invoke (this, args);
  893. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  894. {
  895. switch (pos) {
  896. case Pos.PosView pv:
  897. // See #2461
  898. //if (!from.InternalSubviews.Contains (pv.Target)) {
  899. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  900. //}
  901. if (pv.Target != this) {
  902. nEdges.Add ((pv.Target, from));
  903. }
  904. return;
  905. case Pos.PosCombine pc:
  906. CollectPos (pc._left, from, ref nNodes, ref nEdges);
  907. CollectPos (pc._right, from, ref nNodes, ref nEdges);
  908. break;
  909. }
  910. }
  911. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  912. {
  913. switch (dim) {
  914. case Dim.DimView dv:
  915. // See #2461
  916. //if (!from.InternalSubviews.Contains (dv.Target)) {
  917. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  918. //}
  919. if (dv.Target != this) {
  920. nEdges.Add ((dv.Target, from));
  921. }
  922. return;
  923. case Dim.DimCombine dc:
  924. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  925. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  926. break;
  927. }
  928. }
  929. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  930. {
  931. // BUGBUG: This should really only work on initialized subviews
  932. foreach (var v in from.InternalSubviews /*.Where(v => v.IsInitialized)*/) {
  933. nNodes.Add (v);
  934. if (v.LayoutStyle != LayoutStyle.Computed) {
  935. continue;
  936. }
  937. CollectPos (v.X, v, ref nNodes, ref nEdges);
  938. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  939. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  940. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  941. }
  942. }
  943. // https://en.wikipedia.org/wiki/Topological_sorting
  944. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  945. {
  946. var result = new List<View> ();
  947. // Set of all nodes with no incoming edges
  948. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  949. while (noEdgeNodes.Any ()) {
  950. // remove a node n from S
  951. var n = noEdgeNodes.First ();
  952. noEdgeNodes.Remove (n);
  953. // add n to tail of L
  954. if (n != superView) {
  955. result.Add (n);
  956. }
  957. // for each node m with an edge e from n to m do
  958. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  959. var m = e.To;
  960. // remove edge e from the graph
  961. edges.Remove (e);
  962. // if m has no other incoming edges then
  963. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  964. // insert m into S
  965. noEdgeNodes.Add (m);
  966. }
  967. }
  968. }
  969. if (!edges.Any ()) {
  970. return result;
  971. }
  972. foreach ((var from, var to) in edges) {
  973. if (from == to) {
  974. // if not yet added to the result, add it and remove from edge
  975. if (result.Find (v => v == from) == null) {
  976. result.Add (from);
  977. }
  978. edges.Remove ((from, to));
  979. } else if (from.SuperView == to.SuperView) {
  980. // if 'from' is not yet added to the result, add it
  981. if (result.Find (v => v == from) == null) {
  982. result.Add (from);
  983. }
  984. // if 'to' is not yet added to the result, add it
  985. if (result.Find (v => v == to) == null) {
  986. result.Add (to);
  987. }
  988. // remove from edge
  989. edges.Remove ((from, to));
  990. } else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to)) {
  991. if (ReferenceEquals (from.SuperView, to)) {
  992. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
  993. }
  994. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
  995. }
  996. }
  997. // return L (a topologically sorted order)
  998. return result;
  999. } // TopologicalSort
  1000. /// <summary>
  1001. /// Overriden by <see cref="Adornment"/> to do nothing, as the <see cref="Adornment"/> does not have adornments.
  1002. /// </summary>
  1003. internal virtual void LayoutAdornments ()
  1004. {
  1005. if (Margin == null) {
  1006. return; // CreateAdornments () has not been called yet
  1007. }
  1008. if (Margin.Frame.Size != Frame.Size) {
  1009. Margin._frame = new Rect (Point.Empty, Frame.Size);
  1010. Margin.X = 0;
  1011. Margin.Y = 0;
  1012. Margin.Width = Frame.Size.Width;
  1013. Margin.Height = Frame.Size.Height;
  1014. Margin.SetNeedsLayout ();
  1015. Margin.SetNeedsDisplay ();
  1016. }
  1017. var border = Margin.Thickness.GetInside (Margin.Frame);
  1018. if (border != Border.Frame) {
  1019. Border._frame = new Rect (new Point (border.Location.X, border.Location.Y), border.Size);
  1020. Border.X = border.Location.X;
  1021. Border.Y = border.Location.Y;
  1022. Border.Width = border.Size.Width;
  1023. Border.Height = border.Size.Height;
  1024. Border.SetNeedsLayout ();
  1025. Border.SetNeedsDisplay ();
  1026. }
  1027. var padding = Border.Thickness.GetInside (Border.Frame);
  1028. if (padding != Padding.Frame) {
  1029. Padding._frame = new Rect (new Point (padding.Location.X, padding.Location.Y), padding.Size);
  1030. Padding.X = padding.Location.X;
  1031. Padding.Y = padding.Location.Y;
  1032. Padding.Width = padding.Size.Width;
  1033. Padding.Height = padding.Size.Height;
  1034. Padding.SetNeedsLayout ();
  1035. Padding.SetNeedsDisplay ();
  1036. }
  1037. }
  1038. /// <summary>
  1039. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1040. /// response to the container view or terminal resizing.
  1041. /// </summary>
  1042. /// <remarks>
  1043. /// <para>
  1044. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore,
  1045. /// the behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  1046. /// </para>
  1047. /// <para>
  1048. /// Raises the <see cref="LayoutComplete"/> event) before it returns.
  1049. /// </para>
  1050. /// </remarks>
  1051. public virtual void LayoutSubviews ()
  1052. {
  1053. if (!IsInitialized) {
  1054. Debug.WriteLine ($"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}");
  1055. }
  1056. if (!LayoutNeeded) {
  1057. return;
  1058. }
  1059. CheckDimAuto ();
  1060. LayoutAdornments ();
  1061. var oldBounds = Bounds;
  1062. OnLayoutStarted (new LayoutEventArgs { OldBounds = oldBounds });
  1063. SetTextFormatterSize ();
  1064. // Sort out the dependencies of the X, Y, Width, Height properties
  1065. var nodes = new HashSet<View> ();
  1066. var edges = new HashSet<(View, View)> ();
  1067. CollectAll (this, ref nodes, ref edges);
  1068. var ordered = TopologicalSort (SuperView, nodes, edges);
  1069. foreach (var v in ordered) {
  1070. if (v.Width is Dim.DimAuto || v.Height is Dim.DimAuto) {
  1071. // If the view is auto-sized...
  1072. var f = v.Frame;
  1073. v._frame = new Rect (v.Frame.X, v.Frame.Y, 0, 0);
  1074. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  1075. if (v.Frame != f) {
  1076. // The subviews changed; do it again
  1077. v.LayoutNeeded = true;
  1078. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  1079. }
  1080. } else {
  1081. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  1082. }
  1083. }
  1084. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  1085. // Use LayoutSubview with the Frame of the 'from'
  1086. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded && edges.Count > 0) {
  1087. foreach ((var from, var to) in edges) {
  1088. LayoutSubview (to, from.Frame);
  1089. }
  1090. }
  1091. LayoutNeeded = false;
  1092. OnLayoutComplete (new LayoutEventArgs { OldBounds = oldBounds });
  1093. }
  1094. void LayoutSubview (View v, Rect contentArea)
  1095. {
  1096. //if (v.LayoutStyle == LayoutStyle.Computed) {
  1097. v.SetRelativeLayout (contentArea);
  1098. //}
  1099. v.LayoutSubviews ();
  1100. v.LayoutNeeded = false;
  1101. }
  1102. bool ResizeView (bool autoSize)
  1103. {
  1104. if (!autoSize) {
  1105. return false;
  1106. }
  1107. var boundsChanged = true;
  1108. var newFrameSize = GetTextAutoSize ();
  1109. if (IsInitialized && newFrameSize != Frame.Size) {
  1110. if (ValidatePosDim) {
  1111. // BUGBUG: This ain't right, obviously. We need to figure out how to handle this.
  1112. boundsChanged = ResizeBoundsToFit (newFrameSize);
  1113. } else {
  1114. Height = newFrameSize.Height;
  1115. Width = newFrameSize.Width;
  1116. }
  1117. }
  1118. return boundsChanged;
  1119. }
  1120. /// <summary>
  1121. /// Resizes the View to fit the specified size. Factors in the HotKey.
  1122. /// </summary>
  1123. /// <param name="size"></param>
  1124. /// <returns>whether the Bounds was changed or not</returns>
  1125. bool ResizeBoundsToFit (Size size)
  1126. {
  1127. var boundsChanged = false;
  1128. var canSizeW = TrySetWidth (size.Width - GetHotKeySpecifierLength (), out var rW);
  1129. var canSizeH = TrySetHeight (size.Height - GetHotKeySpecifierLength (false), out var rH);
  1130. if (canSizeW) {
  1131. boundsChanged = true;
  1132. _width = rW;
  1133. }
  1134. if (canSizeH) {
  1135. boundsChanged = true;
  1136. _height = rH;
  1137. }
  1138. if (boundsChanged) {
  1139. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  1140. }
  1141. return boundsChanged;
  1142. }
  1143. /// <summary>
  1144. /// Determines if the View's <see cref="Width"/> can be set to a new value.
  1145. /// </summary>
  1146. /// <param name="desiredWidth"></param>
  1147. /// <param name="resultWidth">
  1148. /// Contains the width that would result if <see cref="Width"/> were set to
  1149. /// <paramref name="desiredWidth"/>"/>
  1150. /// </param>
  1151. /// <returns>
  1152. /// <see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False
  1153. /// otherwise.
  1154. /// </returns>
  1155. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  1156. {
  1157. var w = desiredWidth;
  1158. bool canSetWidth;
  1159. switch (Width) {
  1160. case Dim.DimCombine _:
  1161. case Dim.DimView _:
  1162. case Dim.DimFill _:
  1163. // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  1164. w = Width.Anchor (w);
  1165. canSetWidth = !ValidatePosDim;
  1166. break;
  1167. case Dim.DimFactor factor:
  1168. // Tries to get the SuperView Width otherwise the view Width.
  1169. var sw = SuperView != null ? SuperView.Frame.Width : w;
  1170. if (factor.IsFromRemaining ()) {
  1171. sw -= Frame.X;
  1172. }
  1173. w = Width.Anchor (sw);
  1174. canSetWidth = !ValidatePosDim;
  1175. break;
  1176. default:
  1177. canSetWidth = true;
  1178. break;
  1179. }
  1180. resultWidth = w;
  1181. return canSetWidth;
  1182. }
  1183. /// <summary>
  1184. /// Determines if the View's <see cref="Height"/> can be set to a new value.
  1185. /// </summary>
  1186. /// <param name="desiredHeight"></param>
  1187. /// <param name="resultHeight">
  1188. /// Contains the width that would result if <see cref="Height"/> were set to
  1189. /// <paramref name="desiredHeight"/>"/>
  1190. /// </param>
  1191. /// <returns>
  1192. /// <see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False
  1193. /// otherwise.
  1194. /// </returns>
  1195. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  1196. {
  1197. var h = desiredHeight;
  1198. bool canSetHeight;
  1199. switch (Height) {
  1200. case Dim.DimCombine _:
  1201. case Dim.DimView _:
  1202. case Dim.DimFill _:
  1203. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  1204. h = Height.Anchor (h);
  1205. canSetHeight = !ValidatePosDim;
  1206. break;
  1207. case Dim.DimFactor factor:
  1208. // Tries to get the SuperView height otherwise the view height.
  1209. var sh = SuperView != null ? SuperView.Frame.Height : h;
  1210. if (factor.IsFromRemaining ()) {
  1211. sh -= Frame.Y;
  1212. }
  1213. h = Height.Anchor (sh);
  1214. canSetHeight = !ValidatePosDim;
  1215. break;
  1216. default:
  1217. canSetHeight = true;
  1218. break;
  1219. }
  1220. resultHeight = h;
  1221. return canSetHeight;
  1222. }
  1223. /// <summary>
  1224. /// Finds which view that belong to the <paramref name="start"/> superview at the provided location.
  1225. /// </summary>
  1226. /// <param name="start">The superview where to look for.</param>
  1227. /// <param name="x">The column location in the superview.</param>
  1228. /// <param name="y">The row location in the superview.</param>
  1229. /// <param name="resx">The found view screen relative column location.</param>
  1230. /// <param name="resy">The found view screen relative row location.</param>
  1231. /// <returns>
  1232. /// The view that was found at the <praramref name="x"/> and <praramref name="y"/> coordinates.
  1233. /// <see langword="null"/> if no view was found.
  1234. /// </returns>
  1235. public static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1236. {
  1237. resy = resx = 0;
  1238. if (start == null || !start.Frame.Contains (x, y)) {
  1239. return null;
  1240. }
  1241. var startFrame = start.Frame;
  1242. if (start.InternalSubviews != null) {
  1243. var count = start.InternalSubviews.Count;
  1244. if (count > 0) {
  1245. var boundsOffset = start.GetBoundsOffset ();
  1246. var rx = x - (startFrame.X + boundsOffset.X);
  1247. var ry = y - (startFrame.Y + boundsOffset.Y);
  1248. for (var i = count - 1; i >= 0; i--) {
  1249. var v = start.InternalSubviews [i];
  1250. if (v.Visible && v.Frame.Contains (rx, ry)) {
  1251. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1252. if (deep == null) {
  1253. return v;
  1254. }
  1255. return deep;
  1256. }
  1257. }
  1258. }
  1259. }
  1260. resx = x - startFrame.X;
  1261. resy = y - startFrame.Y;
  1262. return start;
  1263. }
  1264. }