PosDim.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. using System.Diagnostics;
  2. using static Terminal.Gui.Dim;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Describes the position of a <see cref="View"/> which can be an absolute value, a percentage, centered, or
  6. /// relative to the ending dimension. Integer values are implicitly convertible to an absolute <see cref="Pos"/>. These
  7. /// objects are created using the static methods Percent, AnchorEnd, and Center. The <see cref="Pos"/> objects can be
  8. /// combined with the addition and subtraction operators.
  9. /// </summary>
  10. /// <remarks>
  11. /// <para>Use the <see cref="Pos"/> objects on the X or Y properties of a view to control the position.</para>
  12. /// <para>
  13. /// These can be used to set the absolute position, when merely assigning an integer value (via the implicit
  14. /// integer to <see cref="Pos"/> conversion), and they can be combined to produce more useful layouts, like:
  15. /// Pos.Center - 3, which would shift the position of the <see cref="View"/> 3 characters to the left after
  16. /// centering for example.
  17. /// </para>
  18. /// <para>
  19. /// Reference coordinates of another view by using the methods Left(View), Right(View), Bottom(View), Top(View).
  20. /// The X(View) and Y(View) are aliases to Left(View) and Top(View) respectively.
  21. /// </para>
  22. /// <para>
  23. /// <list type="table">
  24. /// <listheader>
  25. /// <term>Pos Object</term> <description>Description</description>
  26. /// </listheader>
  27. /// <item>
  28. /// <term>
  29. /// <see cref="Pos.Function(Func{int})"/>
  30. /// </term>
  31. /// <description>
  32. /// Creates a <see cref="Pos"/> object that computes the position by executing the provided
  33. /// function. The function will be called every time the position is needed.
  34. /// </description>
  35. /// </item>
  36. /// <item>
  37. /// <term>
  38. /// <see cref="Pos.Percent(float)"/>
  39. /// </term>
  40. /// <description>
  41. /// Creates a <see cref="Pos"/> object that is a percentage of the width or height of the
  42. /// SuperView.
  43. /// </description>
  44. /// </item>
  45. /// <item>
  46. /// <term>
  47. /// <see cref="Pos.AnchorEnd()"/>
  48. /// </term>
  49. /// <description>
  50. /// Creates a <see cref="Pos"/> object that is anchored to the end (right side or bottom) of
  51. /// the dimension, useful to flush the layout from the right or bottom.
  52. /// </description>
  53. /// </item>
  54. /// <item>
  55. /// <term>
  56. /// <see cref="Pos.Center"/>
  57. /// </term>
  58. /// <description>Creates a <see cref="Pos"/> object that can be used to center the <see cref="View"/>.</description>
  59. /// </item>
  60. /// <item>
  61. /// <term>
  62. /// <see cref="Pos.At(int)"/>
  63. /// </term>
  64. /// <description>
  65. /// Creates a <see cref="Pos"/> object that is an absolute position based on the specified
  66. /// integer value.
  67. /// </description>
  68. /// </item>
  69. /// <item>
  70. /// <term>
  71. /// <see cref="Pos.Left"/>
  72. /// </term>
  73. /// <description>
  74. /// Creates a <see cref="Pos"/> object that tracks the Left (X) position of the specified
  75. /// <see cref="View"/>.
  76. /// </description>
  77. /// </item>
  78. /// <item>
  79. /// <term>
  80. /// <see cref="Pos.X(View)"/>
  81. /// </term>
  82. /// <description>
  83. /// Creates a <see cref="Pos"/> object that tracks the Left (X) position of the specified
  84. /// <see cref="View"/>.
  85. /// </description>
  86. /// </item>
  87. /// <item>
  88. /// <term>
  89. /// <see cref="Pos.Top(View)"/>
  90. /// </term>
  91. /// <description>
  92. /// Creates a <see cref="Pos"/> object that tracks the Top (Y) position of the specified
  93. /// <see cref="View"/>.
  94. /// </description>
  95. /// </item>
  96. /// <item>
  97. /// <term>
  98. /// <see cref="Pos.Y(View)"/>
  99. /// </term>
  100. /// <description>
  101. /// Creates a <see cref="Pos"/> object that tracks the Top (Y) position of the specified
  102. /// <see cref="View"/>.
  103. /// </description>
  104. /// </item>
  105. /// <item>
  106. /// <term>
  107. /// <see cref="Pos.Right(View)"/>
  108. /// </term>
  109. /// <description>
  110. /// Creates a <see cref="Pos"/> object that tracks the Right (X+Width) coordinate of the
  111. /// specified <see cref="View"/>.
  112. /// </description>
  113. /// </item>
  114. /// <item>
  115. /// <term>
  116. /// <see cref="Pos.Bottom(View)"/>
  117. /// </term>
  118. /// <description>
  119. /// Creates a <see cref="Pos"/> object that tracks the Bottom (Y+Height) coordinate of the
  120. /// specified <see cref="View"/>
  121. /// </description>
  122. /// </item>
  123. /// </list>
  124. /// </para>
  125. /// </remarks>
  126. public class Pos
  127. {
  128. /// <summary>
  129. /// Creates a <see cref="Pos"/> object that is anchored to the end (right side or
  130. /// bottom) of the SuperView, minus the respective dimension of the View. This is equivalent to using
  131. /// <see cref="Pos.AnchorEnd(int)"/>,
  132. /// with an offset equivalent to the View's respective dimension.
  133. /// </summary>
  134. /// <returns>The <see cref="Pos"/> object anchored to the end (the bottom or the right side) minus the View's dimension.</returns>
  135. /// <example>
  136. /// This sample shows how align a <see cref="Button"/> to the bottom-right the SuperView.
  137. /// <code>
  138. /// anchorButton.X = Pos.AnchorEnd ();
  139. /// anchorButton.Y = Pos.AnchorEnd ();
  140. /// </code>
  141. /// </example>
  142. public static Pos AnchorEnd () { return new PosAnchorEnd (); }
  143. /// <summary>
  144. /// Creates a <see cref="Pos"/> object that is anchored to the end (right side or bottom) of the SuperView,
  145. /// useful to flush the layout from the right or bottom. See also <see cref="Pos.AnchorEnd()"/>, which uses the view
  146. /// dimension to ensure the view is fully visible.
  147. /// </summary>
  148. /// <returns>The <see cref="Pos"/> object anchored to the end (the bottom or the right side).</returns>
  149. /// <param name="offset">The view will be shifted left or up by the amount specified.</param>
  150. /// <example>
  151. /// This sample shows how align a 10 column wide <see cref="Button"/> to the bottom-right the SuperView.
  152. /// <code>
  153. /// anchorButton.X = Pos.AnchorEnd (10);
  154. /// anchorButton.Y = 1
  155. /// </code>
  156. /// </example>
  157. public static Pos AnchorEnd (int offset)
  158. {
  159. if (offset < 0)
  160. {
  161. throw new ArgumentException (@"Must be positive", nameof (offset));
  162. }
  163. return new PosAnchorEnd (offset);
  164. }
  165. /// <summary>Creates a <see cref="Pos"/> object that is an absolute position based on the specified integer value.</summary>
  166. /// <returns>The Absolute <see cref="Pos"/>.</returns>
  167. /// <param name="n">The value to convert to the <see cref="Pos"/>.</param>
  168. public static Pos At (int n) { return new PosAbsolute (n); }
  169. /// <summary>Creates a <see cref="Pos"/> object that can be used to center the <see cref="View"/>.</summary>
  170. /// <returns>The center Pos.</returns>
  171. /// <example>
  172. /// This creates a <see cref="TextView"/> centered horizontally, is 50% of the way down, is 30% the height, and
  173. /// is 80% the width of the <see cref="View"/> it added to.
  174. /// <code>
  175. /// var textView = new TextView () {
  176. /// X = Pos.Center (),
  177. /// Y = Pos.Percent (50),
  178. /// Width = Dim.Percent (80),
  179. /// Height = Dim.Percent (30),
  180. /// };
  181. /// </code>
  182. /// </example>
  183. public static Pos Center () { return new PosCenter (); }
  184. /// <summary>Determines whether the specified object is equal to the current object.</summary>
  185. /// <param name="other">The object to compare with the current object. </param>
  186. /// <returns>
  187. /// <see langword="true"/> if the specified object is equal to the current object; otherwise,
  188. /// <see langword="false"/>.
  189. /// </returns>
  190. public override bool Equals (object other) { return other is Pos abs && abs == this; }
  191. /// <summary>
  192. /// Creates a <see cref="Pos"/> object that computes the position by executing the provided function. The function
  193. /// will be called every time the position is needed.
  194. /// </summary>
  195. /// <param name="function">The function to be executed.</param>
  196. /// <returns>The <see cref="Pos"/> returned from the function.</returns>
  197. public static Pos Function (Func<int> function) { return new PosFunc (function); }
  198. /// <summary>
  199. /// Creates a <see cref="Pos"/> object that justifies a set of views according to the specified justification.
  200. /// </summary>
  201. /// <param name="views"></param>
  202. /// <param name="justification"></param>
  203. /// <returns></returns>
  204. public static Pos Justify (Justification justification) { return new PosJustify (justification); }
  205. /// <summary>Serves as the default hash function. </summary>
  206. /// <returns>A hash code for the current object.</returns>
  207. public override int GetHashCode () { return Anchor (0).GetHashCode (); }
  208. /// <summary>Adds a <see cref="Terminal.Gui.Pos"/> to a <see cref="Terminal.Gui.Pos"/>, yielding a new <see cref="Pos"/>.</summary>
  209. /// <param name="left">The first <see cref="Terminal.Gui.Pos"/> to add.</param>
  210. /// <param name="right">The second <see cref="Terminal.Gui.Pos"/> to add.</param>
  211. /// <returns>The <see cref="Pos"/> that is the sum of the values of <c>left</c> and <c>right</c>.</returns>
  212. public static Pos operator + (Pos left, Pos right)
  213. {
  214. if (left is PosAbsolute && right is PosAbsolute)
  215. {
  216. return new PosAbsolute (left.Anchor (0) + right.Anchor (0));
  217. }
  218. var newPos = new PosCombine (true, left, right);
  219. if (left is PosView view)
  220. {
  221. view.Target.SetNeedsLayout ();
  222. }
  223. return newPos;
  224. }
  225. /// <summary>Creates an Absolute <see cref="Pos"/> from the specified integer value.</summary>
  226. /// <returns>The Absolute <see cref="Pos"/>.</returns>
  227. /// <param name="n">The value to convert to the <see cref="Pos"/> .</param>
  228. public static implicit operator Pos (int n) { return new PosAbsolute (n); }
  229. /// <summary>
  230. /// Subtracts a <see cref="Terminal.Gui.Pos"/> from a <see cref="Terminal.Gui.Pos"/>, yielding a new
  231. /// <see cref="Pos"/>.
  232. /// </summary>
  233. /// <param name="left">The <see cref="Terminal.Gui.Pos"/> to subtract from (the minuend).</param>
  234. /// <param name="right">The <see cref="Terminal.Gui.Pos"/> to subtract (the subtrahend).</param>
  235. /// <returns>The <see cref="Pos"/> that is the <c>left</c> minus <c>right</c>.</returns>
  236. public static Pos operator - (Pos left, Pos right)
  237. {
  238. if (left is PosAbsolute && right is PosAbsolute)
  239. {
  240. return new PosAbsolute (left.Anchor (0) - right.Anchor (0));
  241. }
  242. var newPos = new PosCombine (false, left, right);
  243. if (left is PosView view)
  244. {
  245. view.Target.SetNeedsLayout ();
  246. }
  247. return newPos;
  248. }
  249. /// <summary>Creates a percentage <see cref="Pos"/> object</summary>
  250. /// <returns>The percent <see cref="Pos"/> object.</returns>
  251. /// <param name="percent">A value between 0 and 100 representing the percentage.</param>
  252. /// <example>
  253. /// This creates a <see cref="TextField"/> centered horizontally, is 50% of the way down, is 30% the height, and
  254. /// is 80% the width of the <see cref="View"/> it added to.
  255. /// <code>
  256. /// var textView = new TextField {
  257. /// X = Pos.Center (),
  258. /// Y = Pos.Percent (50),
  259. /// Width = Dim.Percent (80),
  260. /// Height = Dim.Percent (30),
  261. /// };
  262. /// </code>
  263. /// </example>
  264. public static Pos Percent (float percent)
  265. {
  266. if (percent is < 0 or > 100)
  267. {
  268. throw new ArgumentException ("Percent value must be between 0 and 100.");
  269. }
  270. return new PosFactor (percent / 100);
  271. }
  272. /// <summary>Creates a <see cref="Pos"/> object that tracks the Top (Y) position of the specified <see cref="View"/>.</summary>
  273. /// <returns>The <see cref="Pos"/> that depends on the other view.</returns>
  274. /// <param name="view">The <see cref="View"/> that will be tracked.</param>
  275. public static Pos Top (View view) { return new PosView (view, Side.Top); }
  276. /// <summary>Creates a <see cref="Pos"/> object that tracks the Top (Y) position of the specified <see cref="View"/>.</summary>
  277. /// <returns>The <see cref="Pos"/> that depends on the other view.</returns>
  278. /// <param name="view">The <see cref="View"/> that will be tracked.</param>
  279. public static Pos Y (View view) { return new PosView (view, Side.Top); }
  280. /// <summary>Creates a <see cref="Pos"/> object that tracks the Left (X) position of the specified <see cref="View"/>.</summary>
  281. /// <returns>The <see cref="Pos"/> that depends on the other view.</returns>
  282. /// <param name="view">The <see cref="View"/> that will be tracked.</param>
  283. public static Pos Left (View view) { return new PosView (view, Side.Left); }
  284. /// <summary>Creates a <see cref="Pos"/> object that tracks the Left (X) position of the specified <see cref="View"/>.</summary>
  285. /// <returns>The <see cref="Pos"/> that depends on the other view.</returns>
  286. /// <param name="view">The <see cref="View"/> that will be tracked.</param>
  287. public static Pos X (View view) { return new PosView (view, Side.Left); }
  288. /// <summary>
  289. /// Creates a <see cref="Pos"/> object that tracks the Bottom (Y+Height) coordinate of the specified
  290. /// <see cref="View"/>
  291. /// </summary>
  292. /// <returns>The <see cref="Pos"/> that depends on the other view.</returns>
  293. /// <param name="view">The <see cref="View"/> that will be tracked.</param>
  294. public static Pos Bottom (View view) { return new PosView (view, Side.Bottom); }
  295. /// <summary>
  296. /// Creates a <see cref="Pos"/> object that tracks the Right (X+Width) coordinate of the specified
  297. /// <see cref="View"/>.
  298. /// </summary>
  299. /// <returns>The <see cref="Pos"/> that depends on the other view.</returns>
  300. /// <param name="view">The <see cref="View"/> that will be tracked.</param>
  301. public static Pos Right (View view) { return new PosView (view, Side.Right); }
  302. /// <summary>
  303. /// Gets a position that is anchored to a certain point in the layout. This method is typically used
  304. /// internally by the layout system to determine where a View should be positioned.
  305. /// </summary>
  306. /// <param name="width">The width of the area where the View is being positioned (Superview.ContentSize).</param>
  307. /// <returns>
  308. /// An integer representing the calculated position. The way this position is calculated depends on the specific
  309. /// subclass of Pos that is used. For example, PosAbsolute returns a fixed position, PosAnchorEnd returns a
  310. /// position that is anchored to the end of the layout, and so on.
  311. /// </returns>
  312. internal virtual int Anchor (int width) { return 0; }
  313. /// <summary>
  314. /// Calculates and returns the position of a <see cref="View"/> object. It takes into account the dimension of the
  315. /// superview and the dimension of the view itself.
  316. /// </summary>
  317. /// <param name="superviewDimension">
  318. /// The dimension of the superview. This could be the width for x-coordinate calculation or the
  319. /// height for y-coordinate calculation.
  320. /// </param>
  321. /// <param name="dim">The dimension of the View. It could be the current width or height.</param>
  322. /// <param name="us">The View that holds this Pos object.</param>
  323. /// <param name="dimension">Width or Height</param>
  324. /// <returns>
  325. /// The calculated position of the View. The way this position is calculated depends on the specific subclass of Pos
  326. /// that
  327. /// is used.
  328. /// </returns>
  329. internal virtual int Calculate (int superviewDimension, Dim dim, View us, Dim.Dimension dimension)
  330. {
  331. return Anchor (superviewDimension);
  332. }
  333. internal class PosAbsolute (int n) : Pos
  334. {
  335. private readonly int _n = n;
  336. public override bool Equals (object other) { return other is PosAbsolute abs && abs._n == _n; }
  337. public override int GetHashCode () { return _n.GetHashCode (); }
  338. public override string ToString () { return $"Absolute({_n})"; }
  339. internal override int Anchor (int width) { return _n; }
  340. }
  341. internal class PosAnchorEnd : Pos
  342. {
  343. private readonly int _offset;
  344. public PosAnchorEnd () { UseDimForOffset = true; }
  345. public PosAnchorEnd (int offset) { _offset = offset; }
  346. public override bool Equals (object other) { return other is PosAnchorEnd anchorEnd && anchorEnd._offset == _offset; }
  347. public override int GetHashCode () { return _offset.GetHashCode (); }
  348. /// <summary>
  349. /// If true, the offset is the width of the view, if false, the offset is the offset value.
  350. /// </summary>
  351. internal bool UseDimForOffset { get; set; }
  352. public override string ToString () { return UseDimForOffset ? "AnchorEnd()" : $"AnchorEnd({_offset})"; }
  353. internal override int Anchor (int width)
  354. {
  355. if (UseDimForOffset)
  356. {
  357. return width;
  358. }
  359. return width - _offset;
  360. }
  361. internal override int Calculate (int superviewDimension, Dim dim, View us, Dim.Dimension dimension)
  362. {
  363. int newLocation = Anchor (superviewDimension);
  364. if (UseDimForOffset)
  365. {
  366. newLocation -= dim.Anchor (superviewDimension);
  367. }
  368. return newLocation;
  369. }
  370. }
  371. internal class PosCenter : Pos
  372. {
  373. public override string ToString () { return "Center"; }
  374. internal override int Anchor (int width) { return width / 2; }
  375. internal override int Calculate (int superviewDimension, Dim dim, View us, Dim.Dimension dimension)
  376. {
  377. int newDimension = Math.Max (dim.Calculate (0, superviewDimension, us, dimension), 0);
  378. return Anchor (superviewDimension - newDimension);
  379. }
  380. }
  381. internal class PosCombine (bool add, Pos left, Pos right) : Pos
  382. {
  383. internal bool _add = add;
  384. internal Pos _left = left, _right = right;
  385. public override string ToString () { return $"Combine({_left}{(_add ? '+' : '-')}{_right})"; }
  386. internal override int Anchor (int width)
  387. {
  388. int la = _left.Anchor (width);
  389. int ra = _right.Anchor (width);
  390. if (_add)
  391. {
  392. return la + ra;
  393. }
  394. return la - ra;
  395. }
  396. internal override int Calculate (int superviewDimension, Dim dim, View us, Dim.Dimension dimension)
  397. {
  398. int newDimension = dim.Calculate (0, superviewDimension, us, dimension);
  399. int left = _left.Calculate (superviewDimension, dim, us, dimension);
  400. int right = _right.Calculate (superviewDimension, dim, us, dimension);
  401. if (_add)
  402. {
  403. return left + right;
  404. }
  405. return left - right;
  406. }
  407. }
  408. internal class PosFactor (float factor) : Pos
  409. {
  410. private readonly float _factor = factor;
  411. public override bool Equals (object other) { return other is PosFactor f && f._factor == _factor; }
  412. public override int GetHashCode () { return _factor.GetHashCode (); }
  413. public override string ToString () { return $"Factor({_factor})"; }
  414. internal override int Anchor (int width) { return (int)(width * _factor); }
  415. }
  416. /// <summary>
  417. /// Enables justification of a set of views.
  418. /// </summary>
  419. public class PosJustify : Pos
  420. {
  421. public Justifier Justifier { get; } = new ();
  422. public int? _location;
  423. public int GroupId { get; set; }
  424. public static void JustifyGroup (int groupId, IList<View> views, Dim.Dimension dimension, int size)
  425. {
  426. if (views is null)
  427. {
  428. return;
  429. }
  430. Justifier firstInGroup = null;
  431. List<int> dimensionsList = new ();
  432. List<View> viewsInGroup = views.Where (
  433. v =>
  434. {
  435. if (dimension == Dimension.Width && v.X is PosJustify justifyX)
  436. {
  437. return justifyX.GroupId == groupId;
  438. }
  439. if (dimension == Dimension.Height && v.Y is PosJustify justifyY)
  440. {
  441. return justifyY.GroupId == groupId;
  442. }
  443. return false;
  444. }).ToList ();
  445. if (viewsInGroup.Count == 0)
  446. {
  447. return;
  448. }
  449. foreach (var view in viewsInGroup)
  450. {
  451. var posJustify = dimension == Dimension.Width ? view.X as PosJustify : view.Y as PosJustify;
  452. if (posJustify is { })
  453. {
  454. if (firstInGroup is null)
  455. {
  456. firstInGroup = posJustify.Justifier;
  457. }
  458. dimensionsList.Add (dimension == Dimension.Width ? view.Frame.Width : view.Frame.Height);
  459. }
  460. }
  461. if (firstInGroup is null)
  462. {
  463. return;
  464. }
  465. firstInGroup.ContainerSize = size;
  466. var locations = firstInGroup.Justify (dimensionsList.ToArray ());
  467. for (var index = 0; index < viewsInGroup.Count; index++)
  468. {
  469. View view = viewsInGroup [index];
  470. PosJustify justify = dimension == Dimension.Width ? view.X as PosJustify : view.Y as PosJustify;
  471. if (justify is { })
  472. {
  473. justify._location = locations [index];
  474. }
  475. }
  476. }
  477. /// <summary>
  478. /// Enables justification of a set of views.
  479. /// </summary>
  480. /// <param name="views">The set of views to justify according to <paramref name="justification"/>.</param>
  481. /// <param name="justification"></param>
  482. public PosJustify (Justification justification)
  483. {
  484. Justifier.Justification = justification;
  485. }
  486. public override bool Equals (object other)
  487. {
  488. return other is PosJustify justify && justify.Justifier.Equals (Justifier);
  489. }
  490. public override int GetHashCode () { return Justifier.GetHashCode (); }
  491. public override string ToString ()
  492. {
  493. return $"Justify(justification={Justifier.Justification})";
  494. }
  495. internal override int Anchor (int width)
  496. {
  497. return _location ?? 0 - width;
  498. }
  499. internal override int Calculate (int superviewDimension, Dim dim, View us, Dim.Dimension dimension)
  500. {
  501. if (_location.HasValue)
  502. {
  503. return _location.Value;
  504. }
  505. return 0;
  506. }
  507. }
  508. // Helper class to provide dynamic value by the execution of a function that returns an integer.
  509. internal class PosFunc (Func<int> n) : Pos
  510. {
  511. private readonly Func<int> _function = n;
  512. public override bool Equals (object other) { return other is PosFunc f && f._function () == _function (); }
  513. public override int GetHashCode () { return _function.GetHashCode (); }
  514. public override string ToString () { return $"PosFunc({_function ()})"; }
  515. internal override int Anchor (int width) { return _function (); }
  516. }
  517. /// <summary>
  518. /// Describes which side of the view to use for the position.
  519. /// </summary>
  520. public enum Side
  521. {
  522. /// <summary>
  523. /// The left (X) side of the view.
  524. /// </summary>
  525. Left = 0,
  526. /// <summary>
  527. /// The top (Y) side of the view.
  528. /// </summary>
  529. Top = 1,
  530. /// <summary>
  531. /// The right (X + Width) side of the view.
  532. /// </summary>
  533. Right = 2,
  534. /// <summary>
  535. /// The bottom (Y + Height) side of the view.
  536. /// </summary>
  537. Bottom = 3
  538. }
  539. internal class PosView (View view, Side side) : Pos
  540. {
  541. public readonly View Target = view;
  542. public override bool Equals (object other) { return other is PosView abs && abs.Target == Target; }
  543. public override int GetHashCode () { return Target.GetHashCode (); }
  544. public override string ToString ()
  545. {
  546. string sideString = side switch
  547. {
  548. Side.Left => "left",
  549. Side.Top => "top",
  550. Side.Right => "right",
  551. Side.Bottom => "bottom",
  552. _ => "unknown"
  553. };
  554. if (Target == null)
  555. {
  556. throw new NullReferenceException (nameof (Target));
  557. }
  558. return $"View(side={sideString},target={Target})";
  559. }
  560. internal override int Anchor (int width)
  561. {
  562. return side switch
  563. {
  564. Side.Left => Target.Frame.X,
  565. Side.Top => Target.Frame.Y,
  566. Side.Right => Target.Frame.Right,
  567. Side.Bottom => Target.Frame.Bottom,
  568. _ => 0
  569. };
  570. }
  571. }
  572. }
  573. /// <summary>
  574. /// <para>
  575. /// A Dim object describes the dimensions of a <see cref="View"/>. Dim is the type of the
  576. /// <see cref="View.Width"/> and <see cref="View.Height"/> properties of <see cref="View"/>. Dim objects enable
  577. /// Computed Layout (see <see cref="LayoutStyle.Computed"/>) to automatically manage the dimensions of a view.
  578. /// </para>
  579. /// <para>
  580. /// Integer values are implicitly convertible to an absolute <see cref="Dim"/>. These objects are created using
  581. /// the static methods described below. The <see cref="Dim"/> objects can be combined with the addition and
  582. /// subtraction operators.
  583. /// </para>
  584. /// </summary>
  585. /// <remarks>
  586. /// <para>
  587. /// <list type="table">
  588. /// <listheader>
  589. /// <term>Dim Object</term> <description>Description</description>
  590. /// </listheader>
  591. /// <item>
  592. /// <term>
  593. /// <see cref="Dim.Auto"/>
  594. /// </term>
  595. /// <description>
  596. /// Creates a <see cref="Dim"/> object that automatically sizes the view to fit
  597. /// the view's SubViews.
  598. /// </description>
  599. /// </item>
  600. /// <item>
  601. /// <term>
  602. /// <see cref="Dim.Function(Func{int})"/>
  603. /// </term>
  604. /// <description>
  605. /// Creates a <see cref="Dim"/> object that computes the dimension by executing the provided
  606. /// function. The function will be called every time the dimension is needed.
  607. /// </description>
  608. /// </item>
  609. /// <item>
  610. /// <term>
  611. /// <see cref="Dim.Percent(float, bool)"/>
  612. /// </term>
  613. /// <description>
  614. /// Creates a <see cref="Dim"/> object that is a percentage of the width or height of the
  615. /// SuperView.
  616. /// </description>
  617. /// </item>
  618. /// <item>
  619. /// <term>
  620. /// <see cref="Dim.Fill(int)"/>
  621. /// </term>
  622. /// <description>
  623. /// Creates a <see cref="Dim"/> object that fills the dimension from the View's X position
  624. /// to the end of the super view's width, leaving the specified number of columns for a margin.
  625. /// </description>
  626. /// </item>
  627. /// <item>
  628. /// <term>
  629. /// <see cref="Dim.Width(View)"/>
  630. /// </term>
  631. /// <description>
  632. /// Creates a <see cref="Dim"/> object that tracks the Width of the specified
  633. /// <see cref="View"/>.
  634. /// </description>
  635. /// </item>
  636. /// <item>
  637. /// <term>
  638. /// <see cref="Dim.Height(View)"/>
  639. /// </term>
  640. /// <description>
  641. /// Creates a <see cref="Dim"/> object that tracks the Height of the specified
  642. /// <see cref="View"/>.
  643. /// </description>
  644. /// </item>
  645. /// </list>
  646. /// </para>
  647. /// <para></para>
  648. /// </remarks>
  649. public class Dim
  650. {
  651. /// <summary>
  652. /// Specifies how <see cref="DimAuto"/> will compute the dimension.
  653. /// </summary>
  654. public enum DimAutoStyle
  655. {
  656. /// <summary>
  657. /// The dimension will be computed using both the view's <see cref="View.Text"/> and
  658. /// <see cref="View.Subviews"/> (whichever is larger).
  659. /// </summary>
  660. Auto,
  661. /// <summary>
  662. /// The Subview in <see cref="View.Subviews"/> with the largest corresponding position plus dimension
  663. /// will determine the dimension.
  664. /// The corresponding dimension of the view's <see cref="View.Text"/> will be ignored.
  665. /// </summary>
  666. Subviews,
  667. /// <summary>
  668. /// The corresponding dimension of the view's <see cref="View.Text"/>, formatted using the
  669. /// <see cref="View.TextFormatter"/> settings,
  670. /// will be used to determine the dimension.
  671. /// The corresponding dimensions of the <see cref="View.Subviews"/> will be ignored.
  672. /// </summary>
  673. Text
  674. }
  675. /// <summary>
  676. ///
  677. /// </summary>
  678. public enum Dimension
  679. {
  680. /// <summary>
  681. /// No dimension specified.
  682. /// </summary>
  683. None = 0,
  684. /// <summary>
  685. /// The height dimension.
  686. /// </summary>
  687. Height = 1,
  688. /// <summary>
  689. /// The width dimension.
  690. /// </summary>
  691. Width = 2
  692. }
  693. /// <summary>
  694. /// Creates a <see cref="Dim"/> object that automatically sizes the view to fit all of the view's SubViews and/or Text.
  695. /// </summary>
  696. /// <example>
  697. /// This initializes a <see cref="View"/> with two SubViews. The view will be automatically sized to fit the two
  698. /// SubViews.
  699. /// <code>
  700. /// var button = new Button () { Text = "Click Me!", X = 1, Y = 1, Width = 10, Height = 1 };
  701. /// var textField = new TextField { Text = "Type here", X = 1, Y = 2, Width = 20, Height = 1 };
  702. /// var view = new Window () { Title = "MyWindow", X = 0, Y = 0, Width = Dim.Auto (), Height = Dim.Auto () };
  703. /// view.Add (button, textField);
  704. /// </code>
  705. /// </example>
  706. /// <returns>The <see cref="Dim"/> object.</returns>
  707. /// <param name="style">
  708. /// Specifies how <see cref="DimAuto"/> will compute the dimension. The default is <see cref="DimAutoStyle.Auto"/>.
  709. /// </param>
  710. /// <param name="min">Specifies the minimum dimension that view will be automatically sized to.</param>
  711. /// <param name="max">Specifies the maximum dimension that view will be automatically sized to. NOT CURRENTLY SUPPORTED.</param>
  712. public static Dim Auto (DimAutoStyle style = DimAutoStyle.Auto, Dim min = null, Dim max = null)
  713. {
  714. if (max != null)
  715. {
  716. throw new NotImplementedException (@"max is not implemented");
  717. }
  718. return new DimAuto (style, min, max);
  719. }
  720. /// <summary>Determines whether the specified object is equal to the current object.</summary>
  721. /// <param name="other">The object to compare with the current object. </param>
  722. /// <returns>
  723. /// <see langword="true"/> if the specified object is equal to the current object; otherwise,
  724. /// <see langword="false"/>.
  725. /// </returns>
  726. public override bool Equals (object other) { return other is Dim abs && abs == this; }
  727. /// <summary>
  728. /// Creates a <see cref="Dim"/> object that fills the dimension, leaving the specified number of columns for a
  729. /// margin.
  730. /// </summary>
  731. /// <returns>The Fill dimension.</returns>
  732. /// <param name="margin">Margin to use.</param>
  733. public static Dim Fill (int margin = 0) { return new DimFill (margin); }
  734. /// <summary>
  735. /// Creates a function <see cref="Dim"/> object that computes the dimension by executing the provided function.
  736. /// The function will be called every time the dimension is needed.
  737. /// </summary>
  738. /// <param name="function">The function to be executed.</param>
  739. /// <returns>The <see cref="Dim"/> returned from the function.</returns>
  740. public static Dim Function (Func<int> function) { return new DimFunc (function); }
  741. /// <summary>Serves as the default hash function. </summary>
  742. /// <returns>A hash code for the current object.</returns>
  743. public override int GetHashCode () { return Anchor (0).GetHashCode (); }
  744. /// <summary>Creates a <see cref="Dim"/> object that tracks the Height of the specified <see cref="View"/>.</summary>
  745. /// <returns>The height <see cref="Dim"/> of the other <see cref="View"/>.</returns>
  746. /// <param name="view">The view that will be tracked.</param>
  747. public static Dim Height (View view) { return new DimView (view, Dimension.Height); }
  748. /// <summary>Adds a <see cref="Dim"/> to a <see cref="Dim"/>, yielding a new <see cref="Dim"/>.</summary>
  749. /// <param name="left">The first <see cref="Dim"/> to add.</param>
  750. /// <param name="right">The second <see cref="Dim"/> to add.</param>
  751. /// <returns>The <see cref="Dim"/> that is the sum of the values of <c>left</c> and <c>right</c>.</returns>
  752. public static Dim operator + (Dim left, Dim right)
  753. {
  754. if (left is DimAbsolute && right is DimAbsolute)
  755. {
  756. return new DimAbsolute (left.Anchor (0) + right.Anchor (0));
  757. }
  758. var newDim = new DimCombine (true, left, right);
  759. (left as DimView)?.Target.SetNeedsLayout ();
  760. return newDim;
  761. }
  762. /// <summary>Creates an Absolute <see cref="Dim"/> from the specified integer value.</summary>
  763. /// <returns>The Absolute <see cref="Dim"/>.</returns>
  764. /// <param name="n">The value to convert to the pos.</param>
  765. public static implicit operator Dim (int n) { return new DimAbsolute (n); }
  766. /// <summary>
  767. /// Subtracts a <see cref="Dim"/> from a <see cref="Dim"/>, yielding a new
  768. /// <see cref="Dim"/>.
  769. /// </summary>
  770. /// <param name="left">The <see cref="Dim"/> to subtract from (the minuend).</param>
  771. /// <param name="right">The <see cref="Dim"/> to subtract (the subtrahend).</param>
  772. /// <returns>The <see cref="Dim"/> that is the <c>left</c> minus <c>right</c>.</returns>
  773. public static Dim operator - (Dim left, Dim right)
  774. {
  775. if (left is DimAbsolute && right is DimAbsolute)
  776. {
  777. return new DimAbsolute (left.Anchor (0) - right.Anchor (0));
  778. }
  779. var newDim = new DimCombine (false, left, right);
  780. (left as DimView)?.Target.SetNeedsLayout ();
  781. return newDim;
  782. }
  783. /// <summary>Creates a percentage <see cref="Dim"/> object that is a percentage of the width or height of the SuperView.</summary>
  784. /// <returns>The percent <see cref="Dim"/> object.</returns>
  785. /// <param name="percent">A value between 0 and 100 representing the percentage.</param>
  786. /// <param name="usePosition">
  787. /// If <see langword="true"/> the dimension is computed using the View's position (<see cref="View.X"/> or
  788. /// <see cref="View.Y"/>).
  789. /// If <see langword="false"/> the dimension is computed using the View's <see cref="View.ContentSize"/>.
  790. /// </param>
  791. /// <example>
  792. /// This initializes a <see cref="TextField"/> that will be centered horizontally, is 50% of the way down, is 30% the
  793. /// height,
  794. /// and is 80% the width of the SuperView.
  795. /// <code>
  796. /// var textView = new TextField {
  797. /// X = Pos.Center (),
  798. /// Y = Pos.Percent (50),
  799. /// Width = Dim.Percent (80),
  800. /// Height = Dim.Percent (30),
  801. /// };
  802. /// </code>
  803. /// </example>
  804. public static Dim Percent (float percent, bool usePosition = false)
  805. {
  806. if (percent is < 0 or > 100)
  807. {
  808. throw new ArgumentException ("Percent value must be between 0 and 100");
  809. }
  810. return new DimFactor (percent / 100, usePosition);
  811. }
  812. /// <summary>Creates an Absolute <see cref="Dim"/> from the specified integer value.</summary>
  813. /// <returns>The Absolute <see cref="Dim"/>.</returns>
  814. /// <param name="n">The value to convert to the <see cref="Dim"/>.</param>
  815. public static Dim Sized (int n) { return new DimAbsolute (n); }
  816. /// <summary>Creates a <see cref="Dim"/> object that tracks the Width of the specified <see cref="View"/>.</summary>
  817. /// <returns>The width <see cref="Dim"/> of the other <see cref="View"/>.</returns>
  818. /// <param name="view">The view that will be tracked.</param>
  819. public static Dim Width (View view) { return new DimView (view, Dimension.Width); }
  820. /// <summary>
  821. /// Gets a dimension that is anchored to a certain point in the layout.
  822. /// This method is typically used internally by the layout system to determine the size of a View.
  823. /// </summary>
  824. /// <param name="width">The width of the area where the View is being sized (Superview.ContentSize).</param>
  825. /// <returns>
  826. /// An integer representing the calculated dimension. The way this dimension is calculated depends on the specific
  827. /// subclass of Dim that is used. For example, DimAbsolute returns a fixed dimension, DimFactor returns a
  828. /// dimension that is a certain percentage of the super view's size, and so on.
  829. /// </returns>
  830. internal virtual int Anchor (int width) { return 0; }
  831. /// <summary>
  832. /// Calculates and returns the dimension of a <see cref="View"/> object. It takes into account the location of the
  833. /// <see cref="View"/>, it's SuperView's ContentSize, and whether it should automatically adjust its size based on its content.
  834. /// </summary>
  835. /// <param name="location">
  836. /// The starting point from where the size calculation begins. It could be the left edge for width calculation or the
  837. /// top edge for height calculation.
  838. /// </param>
  839. /// <param name="superviewContentSize">The size of the SuperView's content. It could be width or height.</param>
  840. /// <param name="us">The View that holds this Pos object.</param>
  841. /// <param name="dimension">Width or Height</param>
  842. /// <returns>
  843. /// The calculated size of the View. The way this size is calculated depends on the specific subclass of Dim that
  844. /// is used.
  845. /// </returns>
  846. internal virtual int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
  847. {
  848. return Math.Max (Anchor (superviewContentSize - location), 0);
  849. }
  850. internal class DimAbsolute (int n) : Dim
  851. {
  852. private readonly int _n = n;
  853. public override bool Equals (object other) { return other is DimAbsolute abs && abs._n == _n; }
  854. public override int GetHashCode () { return _n.GetHashCode (); }
  855. public override string ToString () { return $"Absolute({_n})"; }
  856. internal override int Anchor (int width) { return _n; }
  857. internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
  858. {
  859. // DimAbsolute.Anchor (int width) ignores width and returns n
  860. return Math.Max (Anchor (0), 0);
  861. }
  862. }
  863. internal class DimAuto (DimAutoStyle style, Dim min, Dim max) : Dim
  864. {
  865. internal readonly Dim _max = max;
  866. internal readonly Dim _min = min;
  867. internal readonly DimAutoStyle _style = style;
  868. internal int Size;
  869. public override bool Equals (object other) { return other is DimAuto auto && auto._min == _min && auto._max == _max && auto._style == _style; }
  870. public override int GetHashCode () { return HashCode.Combine (base.GetHashCode (), _min, _max, _style); }
  871. public override string ToString () { return $"Auto({_style},{_min},{_max})"; }
  872. internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
  873. {
  874. if (us == null)
  875. {
  876. return _max?.Anchor (0) ?? 0;
  877. }
  878. var textSize = 0;
  879. var subviewsSize = 0;
  880. int autoMin = _min?.Anchor (superviewContentSize) ?? 0;
  881. if (superviewContentSize < autoMin)
  882. {
  883. Debug.WriteLine ($"WARNING: DimAuto specifies a min size ({autoMin}), but the SuperView's bounds are smaller ({superviewContentSize}).");
  884. return superviewContentSize;
  885. }
  886. if (_style is Dim.DimAutoStyle.Text or Dim.DimAutoStyle.Auto)
  887. {
  888. textSize = int.Max (autoMin, dimension == Dimension.Width ? us.TextFormatter.Size.Width : us.TextFormatter.Size.Height);
  889. }
  890. if (_style is Dim.DimAutoStyle.Subviews or Dim.DimAutoStyle.Auto)
  891. {
  892. subviewsSize = us.Subviews.Count == 0
  893. ? 0
  894. : us.Subviews
  895. .Where (v => dimension == Dimension.Width ? v.X is not Pos.PosAnchorEnd : v.Y is not Pos.PosAnchorEnd)
  896. .Max (v => dimension == Dimension.Width ? v.Frame.X + v.Frame.Width : v.Frame.Y + v.Frame.Height);
  897. }
  898. int max = int.Max (textSize, subviewsSize);
  899. Thickness thickness = us.GetAdornmentsThickness ();
  900. if (dimension == Dimension.Width)
  901. {
  902. max += thickness.Horizontal;
  903. }
  904. else
  905. {
  906. max += thickness.Vertical;
  907. }
  908. max = int.Max (max, autoMin);
  909. return int.Min (max, _max?.Anchor (superviewContentSize) ?? superviewContentSize);
  910. }
  911. }
  912. internal class DimCombine (bool add, Dim left, Dim right) : Dim
  913. {
  914. internal bool _add = add;
  915. internal Dim _left = left, _right = right;
  916. public override string ToString () { return $"Combine({_left}{(_add ? '+' : '-')}{_right})"; }
  917. internal override int Anchor (int width)
  918. {
  919. int la = _left.Anchor (width);
  920. int ra = _right.Anchor (width);
  921. if (_add)
  922. {
  923. return la + ra;
  924. }
  925. return la - ra;
  926. }
  927. internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
  928. {
  929. int leftNewDim = _left.Calculate (location, superviewContentSize, us, dimension);
  930. int rightNewDim = _right.Calculate (location, superviewContentSize, us, dimension);
  931. int newDimension;
  932. if (_add)
  933. {
  934. newDimension = leftNewDim + rightNewDim;
  935. }
  936. else
  937. {
  938. newDimension = Math.Max (0, leftNewDim - rightNewDim);
  939. }
  940. return newDimension;
  941. }
  942. }
  943. internal class DimFactor (float factor, bool remaining = false) : Dim
  944. {
  945. private readonly float _factor = factor;
  946. private readonly bool _remaining = remaining;
  947. public override bool Equals (object other) { return other is DimFactor f && f._factor == _factor && f._remaining == _remaining; }
  948. public override int GetHashCode () { return _factor.GetHashCode (); }
  949. public bool IsFromRemaining () { return _remaining; }
  950. public override string ToString () { return $"Factor({_factor},{_remaining})"; }
  951. internal override int Anchor (int width) { return (int)(width * _factor); }
  952. internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
  953. {
  954. return _remaining ? Math.Max (Anchor (superviewContentSize - location), 0) : Anchor (superviewContentSize);
  955. }
  956. }
  957. internal class DimFill (int margin) : Dim
  958. {
  959. private readonly int _margin = margin;
  960. public override bool Equals (object other) { return other is DimFill fill && fill._margin == _margin; }
  961. public override int GetHashCode () { return _margin.GetHashCode (); }
  962. public override string ToString () { return $"Fill({_margin})"; }
  963. internal override int Anchor (int width) { return width - _margin; }
  964. }
  965. // Helper class to provide dynamic value by the execution of a function that returns an integer.
  966. internal class DimFunc (Func<int> n) : Dim
  967. {
  968. private readonly Func<int> _function = n;
  969. public override bool Equals (object other) { return other is DimFunc f && f._function () == _function (); }
  970. public override int GetHashCode () { return _function.GetHashCode (); }
  971. public override string ToString () { return $"DimFunc({_function ()})"; }
  972. internal override int Anchor (int width) { return _function (); }
  973. }
  974. internal class DimView : Dim
  975. {
  976. private readonly Dimension _side;
  977. internal DimView (View view, Dimension side)
  978. {
  979. Target = view;
  980. _side = side;
  981. }
  982. public View Target { get; init; }
  983. public override bool Equals (object other) { return other is DimView abs && abs.Target == Target; }
  984. public override int GetHashCode () { return Target.GetHashCode (); }
  985. public override string ToString ()
  986. {
  987. if (Target == null)
  988. {
  989. throw new NullReferenceException ();
  990. }
  991. string sideString = _side switch
  992. {
  993. Dimension.Height => "Height",
  994. Dimension.Width => "Width",
  995. _ => "unknown"
  996. };
  997. return $"View({sideString},{Target})";
  998. }
  999. internal override int Anchor (int width)
  1000. {
  1001. return _side switch
  1002. {
  1003. Dimension.Height => Target.Frame.Height,
  1004. Dimension.Width => Target.Frame.Width,
  1005. _ => 0
  1006. };
  1007. }
  1008. }
  1009. }