ViewLayout.cs 65 KB

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