DimAuto.cs 22 KB

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