DimAuto.cs 22 KB

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