ViewLayout.cs 57 KB

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