DimAuto.cs 23 KB

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