DimAuto.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 screen = dimension == Dimension.Width ? Application.Screen.Width * 4 : Application.Screen.Height * 4;
  57. int autoMax = MaximumContentDim?.GetAnchor (superviewContentSize) ?? screen;
  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. //us.TextFormatter.Size = new (superviewContentSize, 2048);
  64. textSize = us.TextFormatter.FormatAndGetSize ().Width;
  65. //us.TextFormatter.Size = new Size (textSize, 2048);
  66. }
  67. else
  68. {
  69. //if (us.TextFormatter.Size.Width == 0)
  70. //{
  71. // us.TextFormatter.Size = us.TextFormatter.GetAutoSize ();
  72. //}
  73. textSize = us.TextFormatter.FormatAndGetSize ().Height;
  74. //us.TextFormatter.Size = us.TextFormatter.Size with { Height = textSize };
  75. }
  76. }
  77. List<View> viewsNeedingLayout = new List<View> ();
  78. if (Style.FastHasFlags (DimAutoStyle.Content))
  79. {
  80. if (!us.ContentSizeTracksViewport)
  81. {
  82. // ContentSize was explicitly set. Use `us.ContentSize` to determine size.
  83. maxCalculatedSize = dimension == Dimension.Width ? us.GetContentSize ().Width : us.GetContentSize ().Height;
  84. }
  85. else
  86. {
  87. maxCalculatedSize = textSize;
  88. // ContentSize was NOT explicitly set. Use `us.Subviews` to determine size.
  89. List<View> includedSubviews = us.Subviews.ToList ();
  90. // If [x] it can cause `us.ContentSize` to change.
  91. // If [ ] it doesn't need special processing for us to determine `us.ContentSize`.
  92. // -------------------- Pos types that are dependent on `us.Subviews`
  93. // [ ] PosAlign - Position is dependent on other views with `GroupId` AND `us.ContentSize`
  94. // [x] PosView - Position is dependent on `subview.Target` - it can cause a change in `us.ContentSize`
  95. // [x] PosCombine - Position is dependent if `Pos.Has [one of the above]` - it can cause a change in `us.ContentSize`
  96. // -------------------- Pos types that are dependent on `us.ContentSize`
  97. // [ ] PosAlign - Position is dependent on other views with `GroupId` AND `us.ContentSize`
  98. // [x] PosAnchorEnd - Position is dependent on `us.ContentSize` AND `subview.Frame` - it can cause a change in `us.ContentSize`
  99. // [ ] PosCenter - Position is dependent `us.ContentSize` AND `subview.Frame` -
  100. // [ ] PosPercent - Position is dependent `us.ContentSize` - Will always be 0 if there is no other content that makes the superview have a size.
  101. // [x] PosCombine - Position is dependent if `Pos.Has [one of the above]` - it can cause a change in `us.ContentSize`
  102. // -------------------- Pos types that are not dependent on either `us.Subviews` or `us.ContentSize`
  103. // [ ] PosAbsolute - Position is fixed.
  104. // [ ] PosFunc - Position is internally calculated.
  105. // -------------------- Dim types that are dependent on `us.Subviews`
  106. // [x] DimView - Dimension is dependent on `subview.Target`
  107. // [x] DimCombine - Dimension is dependent if `Dim.Has [one of the above]` - it can cause a change in `us.ContentSize`
  108. // -------------------- Dim types that are dependent on `us.ContentSize`
  109. // [ ] DimFill - Dimension is dependent on `us.ContentSize` - Will always be 0 if there is no other content that makes the superview have a size.
  110. // [ ] DimPercent - Dimension is dependent on `us.ContentSize` - Will always be 0 if there is no other content that makes the superview have a size.
  111. // [ ] DimCombine - Dimension is dependent if `Dim.Has [one of the above]`
  112. // -------------------- Dim types that are not dependent on either `us.Subviews` or `us.ContentSize`
  113. // [ ] DimAuto - Dimension is internally calculated
  114. // [ ] DimAbsolute - Dimension is fixed
  115. // [ ] DimFunc - Dimension is internally calculated
  116. // ======================================================
  117. // Do the easy stuff first - subviews whose position and size are not dependent on other views or content size
  118. // ======================================================
  119. // [ ] PosAbsolute - Position is fixed.
  120. // [ ] PosFunc - Position is internally calculated
  121. // [ ] DimAuto - Dimension is internally calculated
  122. // [ ] DimAbsolute - Dimension is fixed
  123. // [ ] DimFunc - Dimension is internally calculated
  124. List<View> notDependentSubViews;
  125. if (dimension == Dimension.Width)
  126. {
  127. notDependentSubViews = includedSubviews.Where (v => v.Width is { }
  128. && (v.X is PosAbsolute or PosFunc || v.Width is DimAuto or DimAbsolute or DimFunc)
  129. && !v.X.Has (typeof (PosAnchorEnd), out _)
  130. && !v.X.Has (typeof (PosAlign), out _)
  131. && !v.X.Has (typeof (PosView), out _)
  132. && !v.X.Has (typeof (PosCenter), out _)
  133. && !v.Width.Has (typeof (DimView), out _)
  134. && !v.Width.Has (typeof (DimFill), out _)
  135. && !v.Width.Has (typeof (DimPercent), out _)
  136. ).ToList ();
  137. }
  138. else
  139. {
  140. notDependentSubViews = includedSubviews.Where (v => v.Height is { }
  141. && (v.Y is PosAbsolute or PosFunc || v.Height is DimAuto or DimAbsolute or DimFunc)
  142. && !v.Y.Has (typeof (PosAnchorEnd), out _)
  143. && !v.Y.Has (typeof (PosAlign), out _)
  144. && !v.Y.Has (typeof (PosView), out _)
  145. && !v.Y.Has (typeof (PosCenter), out _)
  146. && !v.Height.Has (typeof (DimView), out _)
  147. && !v.Height.Has (typeof (DimFill), out _)
  148. && !v.Height.Has (typeof (DimPercent), out _)
  149. ).ToList ();
  150. }
  151. for (var i = 0; i < notDependentSubViews.Count; i++)
  152. {
  153. View v = notDependentSubViews [i];
  154. int size = 0;
  155. if (dimension == Dimension.Width)
  156. {
  157. int width = v.Width!.Calculate (0, superviewContentSize, v, dimension);
  158. size = v.X.GetAnchor (0) + width;
  159. }
  160. else
  161. {
  162. int height = v.Height!.Calculate (0, superviewContentSize, v, dimension);
  163. size = v.Y.GetAnchor (0) + height;
  164. }
  165. if (size > maxCalculatedSize)
  166. {
  167. maxCalculatedSize = size;
  168. }
  169. }
  170. // ************** We now have some idea of `us.ContentSize` ***************
  171. #region Centered
  172. // [ ] PosCenter - Position is dependent `us.ContentSize` AND `subview.Frame`
  173. List<View> centeredSubViews;
  174. if (dimension == Dimension.Width)
  175. {
  176. centeredSubViews = us.Subviews.Where (v => v.X.Has (typeof (PosCenter), out _)).ToList ();
  177. }
  178. else
  179. {
  180. centeredSubViews = us.Subviews.Where (v => v.Y.Has (typeof (PosCenter), out _)).ToList ();
  181. }
  182. viewsNeedingLayout.AddRange (centeredSubViews);
  183. int maxCentered = 0;
  184. for (var i = 0; i < centeredSubViews.Count; i++)
  185. {
  186. View v = centeredSubViews [i];
  187. if (dimension == Dimension.Width)
  188. {
  189. int width = v.Width!.Calculate (0, screen, v, dimension);
  190. maxCentered = (v.X.GetAnchor (0) + width);
  191. }
  192. else
  193. {
  194. int height = v.Height!.Calculate (0, screen, v, dimension);
  195. maxCentered = (v.Y.GetAnchor (0) + height);
  196. }
  197. }
  198. maxCalculatedSize = int.Max (maxCalculatedSize, maxCentered);
  199. #endregion Centered
  200. #region Percent
  201. //// [ ] DimPercent - Dimension is dependent on `us.ContentSize`
  202. //// - DimPercent will always be 0 if there is no other content that makes the superview have a size.
  203. //List<View> dimPercentSubViews;
  204. //if (dimension == Dimension.Width)
  205. //{
  206. // dimPercentSubViews = us.Subviews.Where (v => v.Width.Has (typeof (DimPercent), out _)).ToList ();
  207. //}
  208. //else
  209. //{
  210. // dimPercentSubViews = us.Subviews.Where (v => v.Height.Has (typeof (DimPercent), out _)).ToList ();
  211. //}
  212. //viewsNeedingLayout.AddRange (dimPercentSubViews);
  213. //int maxDimPercent = 0;
  214. //for (var i = 0; i < dimPercentSubViews.Count; i++)
  215. //{
  216. // View v = dimPercentSubViews [i];
  217. // if (dimension == Dimension.Width)
  218. // {
  219. // int width = v.Width!.Calculate (0, superviewContentSize, null, dimension);
  220. // maxDimPercent = (v.X.GetAnchor (0) + width);
  221. // }
  222. // else
  223. // {
  224. // int height = v.Height!.Calculate (0, superviewContentSize, null, dimension);
  225. // maxDimPercent = (v.Y.GetAnchor (0) + height);
  226. // }
  227. //}
  228. //maxCalculatedSize = int.Max (maxCalculatedSize, maxDimPercent);
  229. #endregion Percent
  230. #region Aligned
  231. // [ ] PosAlign - Position is dependent on other views with `GroupId` AND `us.ContentSize`
  232. int maxAlign = 0;
  233. // Use Linq to get a list of distinct GroupIds from the subviews
  234. List<int> groupIds = includedSubviews.Select (
  235. v =>
  236. {
  237. if (dimension == Dimension.Width)
  238. {
  239. if (v.X.Has (typeof (PosAlign), out Pos posAlign))
  240. {
  241. return ((PosAlign)posAlign).GroupId;
  242. }
  243. }
  244. else
  245. {
  246. if (v.Y.Has (typeof (PosAlign), out Pos posAlign))
  247. {
  248. return ((PosAlign)posAlign).GroupId;
  249. }
  250. }
  251. return -1;
  252. }).Distinct ().ToList ();
  253. foreach (var groupId in groupIds.Where (g => g != -1))
  254. {
  255. // PERF: If this proves a perf issue, consider caching a ref to this list in each item
  256. List<PosAlign?> posAlignsInGroup = includedSubviews.Where (
  257. v =>
  258. {
  259. return dimension switch
  260. {
  261. Dimension.Width when v.X is PosAlign alignX => alignX.GroupId == groupId,
  262. Dimension.Height when v.Y is PosAlign alignY => alignY.GroupId == groupId,
  263. _ => false
  264. };
  265. })
  266. .Select (v => dimension == Dimension.Width ? v.X as PosAlign : v.Y as PosAlign)
  267. .ToList ();
  268. if (posAlignsInGroup.Count == 0)
  269. {
  270. continue;
  271. }
  272. maxAlign = PosAlign.CalculateMinDimension (groupId, includedSubviews, dimension);
  273. }
  274. maxCalculatedSize = int.Max (maxCalculatedSize, maxAlign);
  275. #endregion Aligned
  276. #region Anchored
  277. // [x] PosAnchorEnd - Position is dependent on `us.ContentSize` AND `subview.Frame`
  278. List<View> anchoredSubViews;
  279. if (dimension == Dimension.Width)
  280. {
  281. anchoredSubViews = includedSubviews.Where (v => v.X.Has (typeof (PosAnchorEnd), out _)).ToList ();
  282. }
  283. else
  284. {
  285. anchoredSubViews = includedSubviews.Where (v => v.Y.Has (typeof (PosAnchorEnd), out _)).ToList ();
  286. }
  287. viewsNeedingLayout.AddRange (anchoredSubViews);
  288. int maxAnchorEnd = 0;
  289. for (var i = 0; i < anchoredSubViews.Count; i++)
  290. {
  291. View v = anchoredSubViews [i];
  292. // Need to set the relative layout for PosAnchorEnd subviews to calculate the size
  293. if (dimension == Dimension.Width)
  294. {
  295. v.SetRelativeLayout (new Size (maxCalculatedSize, screen));
  296. }
  297. else
  298. {
  299. v.SetRelativeLayout (new Size (screen, maxCalculatedSize));
  300. }
  301. maxAnchorEnd = dimension == Dimension.Width ? v.X.GetAnchor (maxCalculatedSize + v.Frame.Width) : v.Y.GetAnchor (maxCalculatedSize + v.Frame.Height);
  302. }
  303. maxCalculatedSize = Math.Max (maxCalculatedSize, maxAnchorEnd);
  304. #endregion Anchored
  305. #region PosView
  306. // [x] PosView - Position is dependent on `subview.Target` - it can cause a change in `us.ContentSize`
  307. List<View> posViewSubViews;
  308. if (dimension == Dimension.Width)
  309. {
  310. posViewSubViews = includedSubviews.Where (v => v.X.Has (typeof (PosView), out _)).ToList ();
  311. }
  312. else
  313. {
  314. posViewSubViews = includedSubviews.Where (v => v.Y.Has (typeof (PosView), out _)).ToList ();
  315. }
  316. for (var i = 0; i < posViewSubViews.Count; i++)
  317. {
  318. View v = posViewSubViews [i];
  319. // BUGBUG: The order may not be correct. May need to call TopologicalSort?
  320. if (dimension == Dimension.Width)
  321. {
  322. v.SetRelativeLayout (new Size (maxCalculatedSize, 0));
  323. }
  324. else
  325. {
  326. v.SetRelativeLayout (new Size (0, maxCalculatedSize));
  327. }
  328. int maxPosView = dimension == Dimension.Width ? v.Frame.X + v.Frame.Width : v.Frame.Y + v.Frame.Height;
  329. if (maxPosView > maxCalculatedSize)
  330. {
  331. maxCalculatedSize = maxPosView;
  332. }
  333. }
  334. #endregion PosView
  335. // [x] PosCombine - Position is dependent if `Pos.Has ([one of the above]` - it can cause a change in `us.ContentSize`
  336. #region DimView
  337. // [x] DimView - Dimension is dependent on `subview.Target` - it can cause a change in `us.ContentSize`
  338. List<View> dimViewSubViews;
  339. if (dimension == Dimension.Width)
  340. {
  341. dimViewSubViews = includedSubviews.Where (v => v.Width is { } && v.Width.Has (typeof (DimView), out _)).ToList ();
  342. }
  343. else
  344. {
  345. dimViewSubViews = includedSubviews.Where (v => v.Height is { } && v.Height.Has (typeof (DimView), out _)).ToList ();
  346. }
  347. for (var i = 0; i < dimViewSubViews.Count; i++)
  348. {
  349. View v = dimViewSubViews [i];
  350. // BUGBUG: The order may not be correct. May need to call TopologicalSort?
  351. if (dimension == Dimension.Width)
  352. {
  353. v.SetRelativeLayout (new Size (maxCalculatedSize, 0));
  354. }
  355. else
  356. {
  357. v.SetRelativeLayout (new Size (0, maxCalculatedSize));
  358. }
  359. int maxDimView = dimension == Dimension.Width ? v.Frame.X + v.Frame.Width : v.Frame.Y + v.Frame.Height;
  360. if (maxDimView > maxCalculatedSize)
  361. {
  362. maxCalculatedSize = maxDimView;
  363. }
  364. }
  365. #endregion DimView
  366. }
  367. }
  368. // All sizes here are content-relative; ignoring adornments.
  369. // We take the largest of text and content.
  370. int max = int.Max (textSize, maxCalculatedSize);
  371. // And, if min: is set, it wins if larger
  372. max = int.Max (max, autoMin);
  373. // And, if max: is set, it wins if smaller
  374. max = int.Min (max, autoMax);
  375. // ************** We now definitively know `us.ContentSize` ***************
  376. int oppositeScreen = dimension == Dimension.Width ? Application.Screen.Height * 4 : Application.Screen.Width * 4;
  377. foreach (var v in viewsNeedingLayout)
  378. {
  379. if (dimension == Dimension.Width)
  380. {
  381. v.SetRelativeLayout (new Size (max, oppositeScreen));
  382. }
  383. else
  384. {
  385. v.SetRelativeLayout (new Size (oppositeScreen, max));
  386. }
  387. }
  388. // Factor in adornments
  389. Thickness thickness = us.GetAdornmentsThickness ();
  390. var adornmentThickness = dimension switch
  391. {
  392. Dimension.Width => thickness.Horizontal,
  393. Dimension.Height => thickness.Vertical,
  394. Dimension.None => 0,
  395. _ => throw new ArgumentOutOfRangeException (nameof (dimension), dimension, null)
  396. };
  397. max += adornmentThickness;
  398. return max;
  399. }
  400. internal override bool ReferencesOtherViews ()
  401. {
  402. // BUGBUG: This is not correct. _contentSize may be null.
  403. return false; //_style.HasFlag (DimAutoStyle.Content);
  404. }
  405. /// <inheritdoc/>
  406. public override bool Equals (object? other)
  407. {
  408. if (other is not DimAuto auto)
  409. {
  410. return false;
  411. }
  412. return auto.MinimumContentDim == MinimumContentDim &&
  413. auto.MaximumContentDim == MaximumContentDim &&
  414. auto.Style == Style;
  415. }
  416. /// <inheritdoc/>
  417. public override int GetHashCode ()
  418. {
  419. return HashCode.Combine (MinimumContentDim, MaximumContentDim, Style);
  420. }
  421. }