DimAuto.cs 23 KB

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