ViewLayout.cs 64 KB

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