ViewLayout.cs 47 KB

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