ViewLayout.cs 55 KB

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