ViewLayout.cs 55 KB

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