ViewLayout.cs 57 KB

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