ViewLayout.cs 58 KB

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