DimAuto.cs 22 KB

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