DimAuto.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Drawing;
  4. namespace Terminal.Gui;
  5. /// <summary>
  6. /// Represents a dimension that automatically sizes the view to fit all the view's Content, SubViews, and/or Text.
  7. /// </summary>
  8. /// <remarks>
  9. /// <para>
  10. /// See <see cref="DimAutoStyle"/>.
  11. /// </para>
  12. /// <para>
  13. /// This is a low-level API that is typically used internally by the layout system. Use the various static
  14. /// methods on the <see cref="Dim"/> class to create <see cref="Dim"/> objects instead.
  15. /// </para>
  16. /// </remarks>
  17. public class DimAuto () : Dim
  18. {
  19. private readonly Dim? _maximumContentDim;
  20. /// <summary>
  21. /// Gets the maximum dimension the View's ContentSize will be fit to. NOT CURRENTLY SUPPORTED.
  22. /// </summary>
  23. // ReSharper disable once ConvertToAutoProperty
  24. public required Dim? MaximumContentDim
  25. {
  26. get => _maximumContentDim;
  27. init => _maximumContentDim = value;
  28. }
  29. private readonly Dim? _minimumContentDim;
  30. /// <summary>
  31. /// Gets the minimum dimension the View's ContentSize will be constrained to.
  32. /// </summary>
  33. // ReSharper disable once ConvertToAutoProperty
  34. public required Dim? MinimumContentDim
  35. {
  36. get => _minimumContentDim;
  37. init => _minimumContentDim = value;
  38. }
  39. private readonly DimAutoStyle _style;
  40. /// <summary>
  41. /// Gets the style of the DimAuto.
  42. /// </summary>
  43. // ReSharper disable once ConvertToAutoProperty
  44. public required DimAutoStyle Style
  45. {
  46. get => _style;
  47. init => _style = value;
  48. }
  49. /// <inheritdoc/>
  50. public override string ToString () { return $"Auto({Style},{MinimumContentDim},{MaximumContentDim})"; }
  51. internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
  52. {
  53. var textSize = 0;
  54. var maxCalculatedSize = 0;
  55. int autoMin = MinimumContentDim?.GetAnchor (superviewContentSize) ?? 0;
  56. int screen = dimension == Dimension.Width ? Application.Screen.Width * 4 : Application.Screen.Height * 4;
  57. int autoMax = MaximumContentDim?.GetAnchor (superviewContentSize) ?? screen;
  58. Debug.Assert (autoMin <= autoMax, "MinimumContentDim must be less than or equal to MaximumContentDim.");
  59. if (Style.FastHasFlags (DimAutoStyle.Text))
  60. {
  61. if (dimension == Dimension.Width)
  62. {
  63. if (us.TextFormatter.Width is null)
  64. {
  65. us.TextFormatter.Size = us.TextFormatter.FormatAndGetSize (new (int.Max (autoMax, superviewContentSize), screen));
  66. }
  67. // else
  68. {
  69. textSize = us.TextFormatter.Width.Value;
  70. }
  71. }
  72. else
  73. {
  74. if (us.TextFormatter.Height is null)
  75. {
  76. textSize = us.TextFormatter.FormatAndGetSize (new (us.TextFormatter.Width ?? screen, int.Max (autoMax, superviewContentSize))).Height;
  77. us.TextFormatter.Height = textSize;
  78. }
  79. else
  80. {
  81. textSize = us.TextFormatter.Height.Value;
  82. }
  83. //if (us.Width.Has (typeof(DimAuto), out var widthDim))
  84. //{
  85. // DimAuto widthDimAuto = (DimAuto)widthDim;
  86. // textSize = us.TextFormatter.FormatAndGetSize (us.GetContentSize ()).Height;
  87. //}
  88. //else
  89. //{
  90. // textSize = us.TextFormatter.FormatAndGetSize ().Height;
  91. //}
  92. //us.TextFormatter.Size = us.TextFormatter.Size with { Height = textSize };
  93. }
  94. }
  95. List<View> viewsNeedingLayout = new List<View> ();
  96. if (Style.FastHasFlags (DimAutoStyle.Content))
  97. {
  98. if (!us.ContentSizeTracksViewport)
  99. {
  100. // ContentSize was explicitly set. Use `us.ContentSize` to determine size.
  101. maxCalculatedSize = dimension == Dimension.Width ? us.GetContentSize ().Width : us.GetContentSize ().Height;
  102. }
  103. else
  104. {
  105. maxCalculatedSize = textSize;
  106. // ContentSize was NOT explicitly set. Use `us.Subviews` to determine size.
  107. List<View> includedSubviews = us.Subviews.ToList ();
  108. // If [x] it can cause `us.ContentSize` to change.
  109. // If [ ] it doesn't need special processing for us to determine `us.ContentSize`.
  110. // -------------------- Pos types that are dependent on `us.Subviews`
  111. // [ ] PosAlign - Position is dependent on other views with `GroupId` AND `us.ContentSize`
  112. // [x] PosView - Position is dependent on `subview.Target` - it can cause a change in `us.ContentSize`
  113. // [x] PosCombine - Position is dependent if `Pos.Has [one of the above]` - it can cause a change in `us.ContentSize`
  114. // -------------------- Pos types that are dependent on `us.ContentSize`
  115. // [ ] PosAlign - Position is dependent on other views with `GroupId` AND `us.ContentSize`
  116. // [x] PosAnchorEnd - Position is dependent on `us.ContentSize` AND `subview.Frame` - it can cause a change in `us.ContentSize`
  117. // [ ] PosCenter - Position is dependent `us.ContentSize` AND `subview.Frame` -
  118. // [ ] PosPercent - Position is dependent `us.ContentSize` - Will always be 0 if there is no other content that makes the superview have a size.
  119. // [x] PosCombine - Position is dependent if `Pos.Has [one of the above]` - it can cause a change in `us.ContentSize`
  120. // -------------------- Pos types that are not dependent on either `us.Subviews` or `us.ContentSize`
  121. // [ ] PosAbsolute - Position is fixed.
  122. // [ ] PosFunc - Position is internally calculated.
  123. // -------------------- Dim types that are dependent on `us.Subviews`
  124. // [x] DimView - Dimension is dependent on `subview.Target`
  125. // [x] DimCombine - Dimension is dependent if `Dim.Has [one of the above]` - it can cause a change in `us.ContentSize`
  126. // -------------------- Dim types that are dependent on `us.ContentSize`
  127. // [ ] DimFill - Dimension is dependent on `us.ContentSize` - Will always be 0 if there is no other content that makes the superview have a size.
  128. // [ ] DimPercent - Dimension is dependent on `us.ContentSize` - Will always be 0 if there is no other content that makes the superview have a size.
  129. // [ ] DimCombine - Dimension is dependent if `Dim.Has [one of the above]`
  130. // -------------------- Dim types that are not dependent on either `us.Subviews` or `us.ContentSize`
  131. // [ ] DimAuto - Dimension is internally calculated
  132. // [ ] DimAbsolute - Dimension is fixed
  133. // [ ] DimFunc - Dimension is internally calculated
  134. // ======================================================
  135. // Do the easy stuff first - subviews whose position and size are not dependent on other views or content size
  136. // ======================================================
  137. // [ ] PosAbsolute - Position is fixed.
  138. // [ ] PosFunc - Position is internally calculated
  139. // [ ] DimAuto - Dimension is internally calculated
  140. // [ ] DimAbsolute - Dimension is fixed
  141. // [ ] DimFunc - Dimension is internally calculated
  142. List<View> notDependentSubViews;
  143. if (dimension == Dimension.Width)
  144. {
  145. notDependentSubViews = includedSubviews.Where (v => v.Width is { }
  146. && (v.X is PosAbsolute or PosFunc || v.Width is DimAuto or DimAbsolute or DimFunc)
  147. && !v.X.Has (typeof (PosAnchorEnd), out _)
  148. && !v.X.Has (typeof (PosAlign), out _)
  149. && !v.X.Has (typeof (PosView), out _)
  150. && !v.X.Has (typeof (PosCenter), out _)
  151. && !v.Width.Has (typeof (DimView), out _)
  152. && !v.Width.Has (typeof (DimFill), out _)
  153. && !v.Width.Has (typeof (DimPercent), out _)
  154. ).ToList ();
  155. }
  156. else
  157. {
  158. notDependentSubViews = includedSubviews.Where (v => v.Height is { }
  159. && (v.Y is PosAbsolute or PosFunc || v.Height is DimAuto or DimAbsolute or DimFunc)
  160. && !v.Y.Has (typeof (PosAnchorEnd), out _)
  161. && !v.Y.Has (typeof (PosAlign), out _)
  162. && !v.Y.Has (typeof (PosView), out _)
  163. && !v.Y.Has (typeof (PosCenter), out _)
  164. && !v.Height.Has (typeof (DimView), out _)
  165. && !v.Height.Has (typeof (DimFill), out _)
  166. && !v.Height.Has (typeof (DimPercent), out _)
  167. ).ToList ();
  168. }
  169. for (var i = 0; i < notDependentSubViews.Count; i++)
  170. {
  171. View v = notDependentSubViews [i];
  172. int size = 0;
  173. if (dimension == Dimension.Width)
  174. {
  175. int width = v.Width!.Calculate (0, superviewContentSize, v, dimension);
  176. size = v.X.GetAnchor (0) + width;
  177. }
  178. else
  179. {
  180. int height = v.Height!.Calculate (0, superviewContentSize, v, dimension);
  181. size = v.Y.GetAnchor (0) + height;
  182. }
  183. if (size > maxCalculatedSize)
  184. {
  185. maxCalculatedSize = size;
  186. }
  187. }
  188. // ************** We now have some idea of `us.ContentSize` ***************
  189. #region Centered
  190. // [ ] PosCenter - Position is dependent `us.ContentSize` AND `subview.Frame`
  191. List<View> centeredSubViews;
  192. if (dimension == Dimension.Width)
  193. {
  194. centeredSubViews = us.Subviews.Where (v => v.X.Has (typeof (PosCenter), out _)).ToList ();
  195. }
  196. else
  197. {
  198. centeredSubViews = us.Subviews.Where (v => v.Y.Has (typeof (PosCenter), out _)).ToList ();
  199. }
  200. viewsNeedingLayout.AddRange (centeredSubViews);
  201. int maxCentered = 0;
  202. for (var i = 0; i < centeredSubViews.Count; i++)
  203. {
  204. View v = centeredSubViews [i];
  205. if (dimension == Dimension.Width)
  206. {
  207. int width = v.Width!.Calculate (0, screen, v, dimension);
  208. maxCentered = (v.X.GetAnchor (0) + width);
  209. }
  210. else
  211. {
  212. int height = v.Height!.Calculate (0, screen, v, dimension);
  213. maxCentered = (v.Y.GetAnchor (0) + height);
  214. }
  215. }
  216. maxCalculatedSize = int.Max (maxCalculatedSize, maxCentered);
  217. #endregion Centered
  218. #region Percent
  219. //// [ ] DimPercent - Dimension is dependent on `us.ContentSize`
  220. //// - DimPercent will always be 0 if there is no other content that makes the superview have a size.
  221. //List<View> dimPercentSubViews;
  222. //if (dimension == Dimension.Width)
  223. //{
  224. // dimPercentSubViews = us.Subviews.Where (v => v.Width.Has (typeof (DimPercent), out _)).ToList ();
  225. //}
  226. //else
  227. //{
  228. // dimPercentSubViews = us.Subviews.Where (v => v.Height.Has (typeof (DimPercent), out _)).ToList ();
  229. //}
  230. //viewsNeedingLayout.AddRange (dimPercentSubViews);
  231. //int maxDimPercent = 0;
  232. //for (var i = 0; i < dimPercentSubViews.Count; i++)
  233. //{
  234. // View v = dimPercentSubViews [i];
  235. // if (dimension == Dimension.Width)
  236. // {
  237. // int width = v.Width!.Calculate (0, superviewContentSize, null, dimension);
  238. // maxDimPercent = (v.X.GetAnchor (0) + width);
  239. // }
  240. // else
  241. // {
  242. // int height = v.Height!.Calculate (0, superviewContentSize, null, dimension);
  243. // maxDimPercent = (v.Y.GetAnchor (0) + height);
  244. // }
  245. //}
  246. //maxCalculatedSize = int.Max (maxCalculatedSize, maxDimPercent);
  247. #endregion Percent
  248. #region Aligned
  249. // [ ] PosAlign - Position is dependent on other views with `GroupId` AND `us.ContentSize`
  250. int maxAlign = 0;
  251. // Use Linq to get a list of distinct GroupIds from the subviews
  252. List<int> groupIds = includedSubviews.Select (
  253. v =>
  254. {
  255. if (dimension == Dimension.Width)
  256. {
  257. if (v.X.Has (typeof (PosAlign), out Pos posAlign))
  258. {
  259. return ((PosAlign)posAlign).GroupId;
  260. }
  261. }
  262. else
  263. {
  264. if (v.Y.Has (typeof (PosAlign), out Pos posAlign))
  265. {
  266. return ((PosAlign)posAlign).GroupId;
  267. }
  268. }
  269. return -1;
  270. }).Distinct ().ToList ();
  271. foreach (var groupId in groupIds.Where (g => g != -1))
  272. {
  273. // PERF: If this proves a perf issue, consider caching a ref to this list in each item
  274. List<PosAlign?> posAlignsInGroup = includedSubviews.Where (
  275. v =>
  276. {
  277. return dimension switch
  278. {
  279. Dimension.Width when v.X is PosAlign alignX => alignX.GroupId == groupId,
  280. Dimension.Height when v.Y is PosAlign alignY => alignY.GroupId == groupId,
  281. _ => false
  282. };
  283. })
  284. .Select (v => dimension == Dimension.Width ? v.X as PosAlign : v.Y as PosAlign)
  285. .ToList ();
  286. if (posAlignsInGroup.Count == 0)
  287. {
  288. continue;
  289. }
  290. maxAlign = PosAlign.CalculateMinDimension (groupId, includedSubviews, dimension);
  291. }
  292. maxCalculatedSize = int.Max (maxCalculatedSize, maxAlign);
  293. #endregion Aligned
  294. #region Anchored
  295. // [x] PosAnchorEnd - Position is dependent on `us.ContentSize` AND `subview.Frame`
  296. List<View> anchoredSubViews;
  297. if (dimension == Dimension.Width)
  298. {
  299. anchoredSubViews = includedSubviews.Where (v => v.X.Has (typeof (PosAnchorEnd), out _)).ToList ();
  300. }
  301. else
  302. {
  303. anchoredSubViews = includedSubviews.Where (v => v.Y.Has (typeof (PosAnchorEnd), out _)).ToList ();
  304. }
  305. viewsNeedingLayout.AddRange (anchoredSubViews);
  306. int maxAnchorEnd = 0;
  307. for (var i = 0; i < anchoredSubViews.Count; i++)
  308. {
  309. View v = anchoredSubViews [i];
  310. // Need to set the relative layout for PosAnchorEnd subviews to calculate the size
  311. if (dimension == Dimension.Width)
  312. {
  313. v.SetRelativeLayout (new Size (maxCalculatedSize, screen));
  314. }
  315. else
  316. {
  317. v.SetRelativeLayout (new Size (screen, maxCalculatedSize));
  318. }
  319. maxAnchorEnd = dimension == Dimension.Width ? v.X.GetAnchor (maxCalculatedSize + v.Frame.Width) : v.Y.GetAnchor (maxCalculatedSize + v.Frame.Height);
  320. }
  321. maxCalculatedSize = Math.Max (maxCalculatedSize, maxAnchorEnd);
  322. #endregion Anchored
  323. #region PosView
  324. // [x] PosView - Position is dependent on `subview.Target` - it can cause a change in `us.ContentSize`
  325. List<View> posViewSubViews;
  326. if (dimension == Dimension.Width)
  327. {
  328. posViewSubViews = includedSubviews.Where (v => v.X.Has (typeof (PosView), out _)).ToList ();
  329. }
  330. else
  331. {
  332. posViewSubViews = includedSubviews.Where (v => v.Y.Has (typeof (PosView), out _)).ToList ();
  333. }
  334. for (var i = 0; i < posViewSubViews.Count; i++)
  335. {
  336. View v = posViewSubViews [i];
  337. // BUGBUG: The order may not be correct. May need to call TopologicalSort?
  338. if (dimension == Dimension.Width)
  339. {
  340. v.SetRelativeLayout (new Size (maxCalculatedSize, 0));
  341. }
  342. else
  343. {
  344. v.SetRelativeLayout (new Size (0, maxCalculatedSize));
  345. }
  346. int maxPosView = dimension == Dimension.Width ? v.Frame.X + v.Frame.Width : v.Frame.Y + v.Frame.Height;
  347. if (maxPosView > maxCalculatedSize)
  348. {
  349. maxCalculatedSize = maxPosView;
  350. }
  351. }
  352. #endregion PosView
  353. // [x] PosCombine - Position is dependent if `Pos.Has ([one of the above]` - it can cause a change in `us.ContentSize`
  354. #region DimView
  355. // [x] DimView - Dimension is dependent on `subview.Target` - it can cause a change in `us.ContentSize`
  356. List<View> dimViewSubViews;
  357. if (dimension == Dimension.Width)
  358. {
  359. dimViewSubViews = includedSubviews.Where (v => v.Width is { } && v.Width.Has (typeof (DimView), out _)).ToList ();
  360. }
  361. else
  362. {
  363. dimViewSubViews = includedSubviews.Where (v => v.Height is { } && v.Height.Has (typeof (DimView), out _)).ToList ();
  364. }
  365. for (var i = 0; i < dimViewSubViews.Count; i++)
  366. {
  367. View v = dimViewSubViews [i];
  368. // BUGBUG: The order may not be correct. May need to call TopologicalSort?
  369. if (dimension == Dimension.Width)
  370. {
  371. v.SetRelativeLayout (new Size (maxCalculatedSize, 0));
  372. }
  373. else
  374. {
  375. v.SetRelativeLayout (new Size (0, maxCalculatedSize));
  376. }
  377. int maxDimView = dimension == Dimension.Width ? v.Frame.X + v.Frame.Width : v.Frame.Y + v.Frame.Height;
  378. if (maxDimView > maxCalculatedSize)
  379. {
  380. maxCalculatedSize = maxDimView;
  381. }
  382. }
  383. #endregion DimView
  384. }
  385. }
  386. // All sizes here are content-relative; ignoring adornments.
  387. // We take the largest of text and content.
  388. int max = int.Max (textSize, maxCalculatedSize);
  389. // And, if min: is set, it wins if larger
  390. max = int.Max (max, autoMin);
  391. // And, if max: is set, it wins if smaller
  392. max = int.Min (max, autoMax);
  393. // ************** We now definitively know `us.ContentSize` ***************
  394. int oppositeScreen = dimension == Dimension.Width ? Application.Screen.Height * 4 : Application.Screen.Width * 4;
  395. foreach (var v in viewsNeedingLayout)
  396. {
  397. if (dimension == Dimension.Width)
  398. {
  399. v.SetRelativeLayout (new Size (max, oppositeScreen));
  400. }
  401. else
  402. {
  403. v.SetRelativeLayout (new Size (oppositeScreen, max));
  404. }
  405. }
  406. // Factor in adornments
  407. Thickness thickness = us.GetAdornmentsThickness ();
  408. var adornmentThickness = dimension switch
  409. {
  410. Dimension.Width => thickness.Horizontal,
  411. Dimension.Height => thickness.Vertical,
  412. Dimension.None => 0,
  413. _ => throw new ArgumentOutOfRangeException (nameof (dimension), dimension, null)
  414. };
  415. max += adornmentThickness;
  416. return max;
  417. }
  418. internal override bool ReferencesOtherViews ()
  419. {
  420. // BUGBUG: This is not correct. _contentSize may be null.
  421. return false; //_style.HasFlag (DimAutoStyle.Content);
  422. }
  423. /// <inheritdoc/>
  424. public override bool Equals (object? other)
  425. {
  426. if (other is not DimAuto auto)
  427. {
  428. return false;
  429. }
  430. return auto.MinimumContentDim == MinimumContentDim &&
  431. auto.MaximumContentDim == MaximumContentDim &&
  432. auto.Style == Style;
  433. }
  434. /// <inheritdoc/>
  435. public override int GetHashCode ()
  436. {
  437. return HashCode.Combine (MinimumContentDim, MaximumContentDim, Style);
  438. }
  439. }