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