DimAuto.cs 22 KB

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