PosDim.cs 47 KB

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