ViewLayout.cs 56 KB

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