ViewLayout.cs 65 KB

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