DimAuto.cs 23 KB

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