ViewLayout.cs 59 KB

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