ViewLayout.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. namespace Terminal.Gui {
  9. /// <summary>
  10. /// Determines the LayoutStyle for a <see cref="View"/>, if Absolute, during <see cref="View.LayoutSubviews"/>, the
  11. /// value from the <see cref="View.Frame"/> will be used, if the value is Computed, then <see cref="View.Frame"/>
  12. /// will be updated from the X, Y <see cref="Pos"/> objects and the Width and Height <see cref="Dim"/> objects.
  13. /// </summary>
  14. public enum LayoutStyle {
  15. /// <summary>
  16. /// The position and size of the view are based <see cref="View.Frame"/>.
  17. /// </summary>
  18. Absolute,
  19. /// <summary>
  20. /// The position and size of the view will be computed based on
  21. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and <see cref="View.Height"/>. <see cref="View.Frame"/> will
  22. /// provide the absolute computed values.
  23. /// </summary>
  24. Computed
  25. }
  26. public partial class View {
  27. // The frame for the object. Relative to the SuperView's Bounds.
  28. Rect _frame;
  29. /// <summary>
  30. /// Gets or sets the frame for the view. The frame is relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.
  31. /// </summary>
  32. /// <value>The frame.</value>
  33. /// <remarks>
  34. /// <para>
  35. /// Change the Frame when using the <see cref="Terminal.Gui.LayoutStyle.Absolute"/> layout style to move or resize views.
  36. /// </para>
  37. /// <para>
  38. /// Altering the Frame of a view will trigger the redrawing of the
  39. /// view as well as the redrawing of the affected regions of the <see cref="SuperView"/>.
  40. /// </para>
  41. /// </remarks>
  42. public virtual Rect Frame {
  43. get => _frame;
  44. set {
  45. _frame = new Rect (value.X, value.Y, Math.Max (value.Width, 0), Math.Max (value.Height, 0));
  46. if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
  47. LayoutFrames ();
  48. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  49. SetNeedsLayout ();
  50. SetNeedsDisplay ();
  51. }
  52. }
  53. }
  54. /// <summary>
  55. /// The frame (specified as a <see cref="Thickness"/>) that separates a View from other SubViews of the same SuperView.
  56. /// The margin offsets the <see cref="Bounds"/> from the <see cref="Frame"/>.
  57. /// </summary>
  58. /// <remarks>
  59. /// <para>
  60. /// The frames (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the View's content
  61. /// and are not clipped by the View's Clip Area.
  62. /// </para>
  63. /// <para>
  64. /// Changing the size of a frame (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>)
  65. /// will change the size of the <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout of the
  66. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  67. /// </para>
  68. /// </remarks>
  69. public Frame Margin { get; private set; }
  70. /// <summary>
  71. /// The frame (specified as a <see cref="Thickness"/>) inside of the view that offsets the <see cref="Bounds"/> from the <see cref="Margin"/>.
  72. /// The Border provides the space for a visual border (drawn using line-drawing glyphs) and the Title.
  73. /// The Border expands inward; in other words if `Border.Thickness.Top == 2` the border and
  74. /// title will take up the first row and the second row will be filled with spaces.
  75. /// </summary>
  76. /// <remarks>
  77. /// <para>
  78. /// <see cref="BorderStyle"/> provides a simple helper for turning a simple border frame on or off.
  79. /// </para>
  80. /// <para>
  81. /// The frames (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the View's content
  82. /// and are not clipped by the View's Clip Area.
  83. /// </para>
  84. /// <para>
  85. /// Changing the size of a frame (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>)
  86. /// will change the size of the <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout of the
  87. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  88. /// </para>
  89. /// </remarks>
  90. public Frame Border { get; private set; }
  91. /// <summary>
  92. /// Gets or sets whether the view has a one row/col thick border.
  93. /// </summary>
  94. /// <remarks>
  95. /// <para>
  96. /// This is a helper for manipulating the view's <see cref="Border"/>. Setting this property to any value other than
  97. /// <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s <see cref="Frame.Thickness"/>
  98. /// to `1` and <see cref="BorderStyle"/> to the value.
  99. /// </para>
  100. /// <para>
  101. /// Setting this property to <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s <see cref="Frame.Thickness"/>
  102. /// to `0` and <see cref="BorderStyle"/> to <see cref="LineStyle.None"/>.
  103. /// </para>
  104. /// <para>
  105. /// For more advanced customization of the view's border, manipulate see <see cref="Border"/> directly.
  106. /// </para>
  107. /// </remarks>
  108. public LineStyle BorderStyle {
  109. get {
  110. return Border?.BorderStyle ?? LineStyle.None;
  111. }
  112. set {
  113. if (Border == null) {
  114. throw new InvalidOperationException ("Border is null; this is likely a bug.");
  115. }
  116. if (value != LineStyle.None) {
  117. Border.Thickness = new Thickness (1);
  118. } else {
  119. Border.Thickness = new Thickness (0);
  120. }
  121. Border.BorderStyle = value;
  122. LayoutFrames ();
  123. SetNeedsLayout ();
  124. }
  125. }
  126. /// <summary>
  127. /// The frame (specified as a <see cref="Thickness"/>) inside of the view that offsets the <see cref="Bounds"/> from the <see cref="Border"/>.
  128. /// </summary>
  129. /// <remarks>
  130. /// <para>
  131. /// The frames (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the View's content
  132. /// and are not clipped by the View's Clip Area.
  133. /// </para>
  134. /// <para>
  135. /// Changing the size of a frame (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>)
  136. /// will change the size of the <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout of the
  137. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  138. /// </para>
  139. /// </remarks>
  140. public Frame Padding { get; private set; }
  141. /// <summary>
  142. /// Helper to get the total thickness of the <see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>.
  143. /// </summary>
  144. /// <returns>A thickness that describes the sum of the Frames' thicknesses.</returns>
  145. public Thickness GetFramesThickness ()
  146. {
  147. var left = Margin.Thickness.Left + Border.Thickness.Left + Padding.Thickness.Left;
  148. var top = Margin.Thickness.Top + Border.Thickness.Top + Padding.Thickness.Top;
  149. var right = Margin.Thickness.Right + Border.Thickness.Right + Padding.Thickness.Right;
  150. var bottom = Margin.Thickness.Bottom + Border.Thickness.Bottom + Padding.Thickness.Bottom;
  151. return new Thickness (left, top, right, bottom);
  152. }
  153. /// <summary>
  154. /// Helper to get the X and Y offset of the Bounds from the Frame. This is the sum of the Left and Top properties of
  155. /// <see cref="Margin"/>, <see cref="Border"/> and <see cref="Padding"/>.
  156. /// </summary>
  157. public Point GetBoundsOffset () => new Point (Padding?.Thickness.GetInside (Padding.Frame).X ?? 0, Padding?.Thickness.GetInside (Padding.Frame).Y ?? 0);
  158. /// <summary>
  159. /// Creates the view's <see cref="Frame"/> objects. This internal method is overridden by Frame to do nothing
  160. /// to prevent recursion during View construction.
  161. /// </summary>
  162. internal virtual void CreateFrames ()
  163. {
  164. void ThicknessChangedHandler (object sender, EventArgs e)
  165. {
  166. LayoutFrames ();
  167. SetNeedsLayout ();
  168. SetNeedsDisplay ();
  169. }
  170. if (Margin != null) {
  171. Margin.ThicknessChanged -= ThicknessChangedHandler;
  172. Margin.Dispose ();
  173. }
  174. Margin = new Frame () { Id = "Margin", Thickness = new Thickness (0) };
  175. Margin.ThicknessChanged += ThicknessChangedHandler;
  176. Margin.Parent = this;
  177. if (Border != null) {
  178. Border.ThicknessChanged -= ThicknessChangedHandler;
  179. Border.Dispose ();
  180. }
  181. Border = new Frame () { Id = "Border", Thickness = new Thickness (0) };
  182. Border.ThicknessChanged += ThicknessChangedHandler;
  183. Border.Parent = this;
  184. // TODO: Create View.AddAdornment
  185. if (Padding != null) {
  186. Padding.ThicknessChanged -= ThicknessChangedHandler;
  187. Padding.Dispose ();
  188. }
  189. Padding = new Frame () { Id = "Padding", Thickness = new Thickness (0) };
  190. Padding.ThicknessChanged += ThicknessChangedHandler;
  191. Padding.Parent = this;
  192. }
  193. LayoutStyle _layoutStyle;
  194. /// <summary>
  195. /// Controls how the View's <see cref="Frame"/> is computed during <see cref="LayoutSubviews"/>. If the style is set to
  196. /// <see cref="LayoutStyle.Absolute"/>,
  197. /// LayoutSubviews does not change the <see cref="Frame"/>. If the style is <see cref="LayoutStyle.Computed"/>
  198. /// the <see cref="Frame"/> is updated using
  199. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  200. /// </summary>
  201. /// <value>The layout style.</value>
  202. public LayoutStyle LayoutStyle {
  203. get => _layoutStyle;
  204. set {
  205. _layoutStyle = value;
  206. SetNeedsLayout ();
  207. }
  208. }
  209. /// <summary>
  210. /// The view's content area.
  211. /// <para>
  212. /// SubViews are positioned relative to Bounds.
  213. /// </para>
  214. /// <para>
  215. /// Drawing is clipped to Bounds (<see cref="Draw()"/> clips drawing to Bounds.<see cref="Rect.Size">Size</see>).
  216. /// </para>
  217. /// <para>
  218. /// Mouse events are reported relative to Bounds.
  219. /// </para>
  220. /// </summary>
  221. /// <value>The view's content area.</value>
  222. /// <remarks>
  223. /// <para>
  224. /// The <see cref="Rect.Location"/> of Bounds is always (0, 0). To obtain the offset of the Bounds from the Frame use
  225. /// <see cref="GetBoundsOffset"/>.
  226. /// </para>
  227. /// <para>
  228. /// When using <see cref="LayoutStyle.Computed"/>, Bounds is not valid until after the view has been initialized (after <see cref="EndInit"/> has been called and <see cref="Initialized"/>
  229. /// has fired). Accessing this property before the view is initialized is considered an error./>
  230. /// </para>
  231. /// </remarks>
  232. public virtual Rect Bounds {
  233. get {
  234. #if DEBUG
  235. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized) {
  236. Debug.WriteLine ($"WARNING: Bounds is being accessed before the View has been initialized. This is likely a bug in {this}");
  237. Debug.WriteLine ($"The Frame is set before the View has been initialized. So it isn't a bug.Is by design.");
  238. }
  239. #endif // DEBUG
  240. //var frameRelativeBounds = Padding?.Thickness.GetInside (Padding.Frame) ?? new Rect (default, Frame.Size);
  241. var frameRelativeBounds = FrameGetInsideBounds ();
  242. return new Rect (default, frameRelativeBounds.Size);
  243. }
  244. set {
  245. // BUGBUG: Margin etc.. can be null (if typeof(Frame))
  246. Frame = new Rect (Frame.Location,
  247. new Size (
  248. value.Size.Width + Margin.Thickness.Horizontal + Border.Thickness.Horizontal + Padding.Thickness.Horizontal,
  249. value.Size.Height + Margin.Thickness.Vertical + Border.Thickness.Vertical + Padding.Thickness.Vertical
  250. )
  251. );
  252. }
  253. }
  254. private Rect FrameGetInsideBounds ()
  255. {
  256. if (Margin == null || Border == null || Padding == null) {
  257. return new Rect (default, Frame.Size);
  258. }
  259. var width = Math.Max (0, Frame.Size.Width - Margin.Thickness.Horizontal - Border.Thickness.Horizontal - Padding.Thickness.Horizontal);
  260. var height = Math.Max (0, Frame.Size.Height - Margin.Thickness.Vertical - Border.Thickness.Vertical - Padding.Thickness.Vertical);
  261. return new Rect (Point.Empty, new Size (width, height));
  262. }
  263. Pos _x, _y;
  264. /// <summary>
  265. /// Gets or sets the X position for the view (the column). Only used if the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  266. /// </summary>
  267. /// <value>The X Position.</value>
  268. /// <remarks>
  269. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  270. /// </remarks>
  271. public Pos X {
  272. get => VerifyIsInitialized (_x);
  273. set {
  274. if (ValidatePosDim && LayoutStyle == LayoutStyle.Computed) {
  275. CheckAbsolute (nameof (X), _x, value);
  276. }
  277. _x = value;
  278. OnResizeNeeded ();
  279. }
  280. }
  281. /// <summary>
  282. /// Gets or sets the Y position for the view (the row). Only used if the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  283. /// </summary>
  284. /// <value>The y position (line).</value>
  285. /// <remarks>
  286. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  287. /// </remarks>
  288. public Pos Y {
  289. get => VerifyIsInitialized (_y);
  290. set {
  291. if (ValidatePosDim && LayoutStyle == LayoutStyle.Computed) {
  292. CheckAbsolute (nameof (Y), _y, value);
  293. }
  294. _y = value;
  295. OnResizeNeeded ();
  296. }
  297. }
  298. Dim _width, _height;
  299. /// <summary>
  300. /// Gets or sets the width of the view. Only used the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  301. /// </summary>
  302. /// <value>The width.</value>
  303. /// <remarks>
  304. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  305. /// </remarks>
  306. public Dim Width {
  307. get => VerifyIsInitialized (_width);
  308. set {
  309. if (ValidatePosDim && LayoutStyle == LayoutStyle.Computed) {
  310. CheckAbsolute (nameof (Width), _width, value);
  311. }
  312. _width = value;
  313. if (ValidatePosDim) {
  314. var isValidNewAutSize = AutoSize && IsValidAutoSizeWidth (_width);
  315. if (IsAdded && AutoSize && !isValidNewAutSize) {
  316. throw new InvalidOperationException ("Must set AutoSize to false before set the Width.");
  317. }
  318. }
  319. OnResizeNeeded ();
  320. }
  321. }
  322. /// <summary>
  323. /// Gets or sets the height of the view. Only used the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  324. /// </summary>
  325. /// <value>The height.</value>
  326. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  327. public Dim Height {
  328. get => VerifyIsInitialized (_height);
  329. set {
  330. if (ValidatePosDim) {
  331. if (value is Dim.DimAuto) {
  332. CheckDimAuto ();
  333. }
  334. if (LayoutStyle == LayoutStyle.Computed) {
  335. CheckAbsolute (nameof (Height), _height, value);
  336. }
  337. }
  338. _height = value;
  339. if (ValidatePosDim) {
  340. var isValidNewAutSize = AutoSize && IsValidAutoSizeHeight (_height);
  341. if (IsAdded && AutoSize && !isValidNewAutSize) {
  342. throw new InvalidOperationException ("Must set AutoSize to false before setting the Height.");
  343. }
  344. }
  345. OnResizeNeeded ();
  346. }
  347. }
  348. // Diagnostics to highlight when X or Y is read before the view has been initialized
  349. Pos VerifyIsInitialized (Pos pos)
  350. {
  351. #if DEBUG
  352. if (LayoutStyle == LayoutStyle.Computed && (!IsInitialized)) {
  353. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; position is indeterminate {pos}. This is likely a bug.");
  354. }
  355. #endif // DEBUG
  356. return pos;
  357. }
  358. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  359. Dim VerifyIsInitialized (Dim dim)
  360. {
  361. #if DEBUG
  362. if (LayoutStyle == LayoutStyle.Computed && (!IsInitialized)) {
  363. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; dimension is indeterminate: {dim}. This is likely a bug.");
  364. }
  365. #endif // DEBUG
  366. return dim;
  367. }
  368. /// <summary>
  369. /// Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.
  370. /// </summary>
  371. /// <remarks>
  372. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/>
  373. /// during set operations and in <see cref="LayoutSubviews"/>.If invalid settings are discovered exceptions will be thrown indicating the error.
  374. /// This will impose a performance penalty and thus should only be used for debugging.
  375. /// </remarks>
  376. public bool ValidatePosDim { get; set; }
  377. /// <summary>
  378. /// Throws an <see cref="InvalidOperationException"/> if any of the SubViews are using Dim objects that depend on this Views dimensions.
  379. /// </summary>
  380. /// <exception cref="InvalidOperationException"></exception>
  381. void CheckDimAuto ()
  382. {
  383. if (!ValidatePosDim) {
  384. return;
  385. }
  386. void ThrowInvalid (View view, object checkPosDim, string name)
  387. {
  388. object bad = null;
  389. switch (checkPosDim) {
  390. case Pos pos and not Pos.PosAbsolute and not Pos.PosView:
  391. bad = pos;
  392. break;
  393. case Dim dim and not Dim.DimAbsolute and not Dim.DimView:
  394. bad = dim;
  395. break;
  396. }
  397. if (bad != null) {
  398. throw new InvalidOperationException (@$"{view.GetType().Name}.{name} = {bad.GetType ().Name} which depends on the SuperView's dimensions and the SuperView uses Dim.Auto.");
  399. }
  400. }
  401. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  402. foreach (var view in Subviews) {
  403. ThrowInvalid (view, view.Width, nameof(view.Width));
  404. ThrowInvalid (view, view.Height, nameof(view.Height));
  405. ThrowInvalid (view, view.X, nameof (view.X));
  406. ThrowInvalid (view, view.Y, nameof (view.Y));
  407. }
  408. }
  409. /// <summary>
  410. /// Throws an <see cref="ArgumentException"/> if <paramref name="newValue"/> is <see cref="Pos.PosAbsolute"/> or <see cref="Dim.DimAbsolute"/>.
  411. /// Used when <see cref="ValidatePosDim"/> is turned on to verify correct <see cref="LayoutStyle.Computed"/> behavior.
  412. /// </summary>
  413. /// <remarks>
  414. /// Does not verify if this view is Toplevel (WHY??!?).
  415. /// </remarks>
  416. /// <param name="oldValue"></param>
  417. /// <param name="newValue"></param>
  418. void CheckAbsolute (string prop, object oldValue, object newValue)
  419. {
  420. if (!IsInitialized || !ValidatePosDim || oldValue == null || oldValue.GetType () == newValue.GetType () || this is Toplevel) {
  421. return;
  422. }
  423. if (oldValue.GetType () != newValue.GetType () && newValue is (Pos.PosAbsolute or Dim.DimAbsolute)) {
  424. throw new ArgumentException ($@"{prop} must not be Absolute if LayoutStyle is Computed", prop);
  425. }
  426. }
  427. // BUGBUG: This API is broken - should not assume Frame.Height == Bounds.Height
  428. // BUGBUG: this function does not belong in ViewLayout.cs - it should be in ViewText.cs
  429. /// <summary>
  430. /// Gets the minimum dimensions required to fit the View's <see cref="Text"/>, factoring in <see cref="TextDirection"/>.
  431. /// </summary>
  432. /// <param name="size">The minimum dimensions required.</param>
  433. /// <returns><see langword="true"/> if the dimensions fit within the View's <see cref="Bounds"/>, <see langword="false"/> otherwise.</returns>
  434. /// <remarks>
  435. /// Always returns <see langword="false"/> if <see cref="AutoSize"/> is <see langword="true"/> or
  436. /// if <see cref="Height"/> (Horizontal) or <see cref="Width"/> (Vertical) are not not set or zero.
  437. /// Does not take into account word wrapping.
  438. /// </remarks>
  439. bool GetMinimumBoundsForFrame (out Size size)
  440. {
  441. if (!IsInitialized) {
  442. size = new Size (0, 0);
  443. return false;
  444. }
  445. size = Bounds.Size;
  446. if (!AutoSize && !string.IsNullOrEmpty (TextFormatter.Text)) {
  447. switch (TextFormatter.IsVerticalDirection (TextDirection)) {
  448. case true:
  449. var colWidth = TextFormatter.GetSumMaxCharWidth (new List<string> { TextFormatter.Text }, 0, 1);
  450. // TODO: v2 - This uses frame.Width; it should only use Bounds
  451. if (_frame.Width < colWidth &&
  452. (Width == null ||
  453. (Bounds.Width >= 0 &&
  454. Width is Dim.DimAbsolute &&
  455. Width.Anchor (0) >= 0 &&
  456. Width.Anchor (0) < colWidth))) {
  457. size = new Size (colWidth, Bounds.Height);
  458. return true;
  459. }
  460. break;
  461. default:
  462. if (_frame.Height < 1 &&
  463. (Height == null ||
  464. (Height is Dim.DimAbsolute &&
  465. Height.Anchor (0) == 0))) {
  466. size = new Size (Bounds.Width, 1);
  467. return true;
  468. }
  469. break;
  470. }
  471. }
  472. return false;
  473. }
  474. // BUGBUG: this function does not belong in ViewLayout.cs - it should be in ViewText.cs
  475. /// <summary>
  476. /// Sets the size of the View to the minimum width or height required to fit <see cref="Text"/> (see <see cref="GetMinimumBoundsForFrame"/>.
  477. /// </summary>
  478. /// <returns><see langword="true"/> if the size was changed, <see langword="false"/> if <see cref="Text"/>
  479. /// will not fit.</returns>
  480. bool SetBoundsToFitFrame ()
  481. {
  482. if (GetMinimumBoundsForFrame (out Size size)) {
  483. _frame = new Rect (_frame.Location, size);
  484. return true;
  485. }
  486. return false;
  487. }
  488. /// <summary>
  489. /// Called whenever the view needs to be resized. Sets <see cref="Frame"/> and
  490. /// triggers a <see cref="LayoutSubviews()"/> call.
  491. /// </summary>
  492. /// <remarks>
  493. /// Can be overridden if the view resize behavior is different than the default.
  494. /// </remarks>
  495. protected virtual void OnResizeNeeded ()
  496. {
  497. var actX = _x is Pos.PosAbsolute ? _x.Anchor (0) : _frame.X;
  498. var actY = _y is Pos.PosAbsolute ? _y.Anchor (0) : _frame.Y;
  499. if (AutoSize) {
  500. //if (TextAlignment == TextAlignment.Justified) {
  501. // throw new InvalidOperationException ("TextAlignment.Justified cannot be used with AutoSize");
  502. //}
  503. var s = GetAutoSize ();
  504. var w = _width is Dim.DimAbsolute && _width.Anchor (0) > s.Width ? _width.Anchor (0) : s.Width;
  505. var h = _height is Dim.DimAbsolute && _height.Anchor (0) > s.Height ? _height.Anchor (0) : s.Height;
  506. _frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
  507. } else {
  508. var w = _width is Dim.DimAbsolute ? _width.Anchor (0) : _frame.Width;
  509. var h = _height is Dim.DimAbsolute ? _height.Anchor (0) : _frame.Height;
  510. // BUGBUG: v2 - ? - If layoutstyle is absolute, this overwrites the current frame h/w with 0. Hmmm...
  511. // This is needed for DimAbsolute values by setting the frame before LayoutSubViews.
  512. _frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
  513. }
  514. //// BUGBUG: I think these calls are redundant or should be moved into just the AutoSize case
  515. if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
  516. SetBoundsToFitFrame ();
  517. LayoutFrames ();
  518. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  519. SetNeedsLayout ();
  520. SetNeedsDisplay ();
  521. }
  522. }
  523. internal bool LayoutNeeded { get; private set; } = true;
  524. internal void SetNeedsLayout ()
  525. {
  526. if (LayoutNeeded) {
  527. return;
  528. }
  529. LayoutNeeded = true;
  530. foreach (var view in Subviews) {
  531. view.SetNeedsLayout ();
  532. }
  533. TextFormatter.NeedsFormat = true;
  534. SuperView?.SetNeedsLayout ();
  535. }
  536. /// <summary>
  537. /// Indicates that the view does not need to be laid out.
  538. /// </summary>
  539. protected void ClearLayoutNeeded ()
  540. {
  541. LayoutNeeded = false;
  542. }
  543. /// <summary>
  544. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means
  545. /// relative to the View's <see cref="SuperView"/>'s <see cref="Bounds"/>.
  546. /// </summary>
  547. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.</returns>
  548. /// <param name="x">Screen-relative column.</param>
  549. /// <param name="y">Screen-relative row.</param>
  550. public Point ScreenToFrame (int x, int y)
  551. {
  552. Point superViewBoundsOffset = SuperView?.GetBoundsOffset () ?? Point.Empty;
  553. var ret = new Point (x - Frame.X - superViewBoundsOffset.X, y - Frame.Y - superViewBoundsOffset.Y);
  554. if (SuperView != null) {
  555. var superFrame = SuperView.ScreenToFrame (x - superViewBoundsOffset.X, y - superViewBoundsOffset.Y);
  556. ret = new Point (superFrame.X - Frame.X, superFrame.Y - Frame.Y);
  557. }
  558. return ret;
  559. }
  560. /// <summary>
  561. /// Converts a screen-relative coordinate to a bounds-relative coordinate.
  562. /// </summary>
  563. /// <returns>The coordinate relative to this view's <see cref="Bounds"/>.</returns>
  564. /// <param name="x">Screen-relative column.</param>
  565. /// <param name="y">Screen-relative row.</param>
  566. public Point ScreenToBounds (int x, int y)
  567. {
  568. var screen = ScreenToFrame (x, y);
  569. var boundsOffset = GetBoundsOffset ();
  570. return new Point (screen.X - boundsOffset.X, screen.Y - boundsOffset.Y);
  571. }
  572. /// <summary>
  573. /// Converts a <see cref="Bounds"/>-relative coordinate to a screen-relative coordinate. The output is optionally clamped to the screen dimensions.
  574. /// </summary>
  575. /// <param name="x"><see cref="Bounds"/>-relative column.</param>
  576. /// <param name="y"><see cref="Bounds"/>-relative row.</param>
  577. /// <param name="rx">Absolute column; screen-relative.</param>
  578. /// <param name="ry">Absolute row; screen-relative.</param>
  579. /// <param name="clamped">If <see langword="true"/>, <paramref name="rx"/> and <paramref name="ry"/> will be clamped to the
  580. /// screen dimensions (will never be negative and will always be less than <see cref="ConsoleDriver.Cols"/> and
  581. /// <see cref="ConsoleDriver.Rows"/>, respectively.</param>
  582. public virtual void BoundsToScreen (int x, int y, out int rx, out int ry, bool clamped = true)
  583. {
  584. var boundsOffset = GetBoundsOffset ();
  585. rx = x + Frame.X + boundsOffset.X;
  586. ry = y + Frame.Y + boundsOffset.Y;
  587. var super = SuperView;
  588. while (super != null) {
  589. boundsOffset = super.GetBoundsOffset ();
  590. rx += super.Frame.X + boundsOffset.X;
  591. ry += super.Frame.Y + boundsOffset.Y;
  592. super = super.SuperView;
  593. }
  594. // The following ensures that the cursor is always in the screen boundaries.
  595. if (clamped) {
  596. ry = Math.Min (ry, Driver.Rows - 1);
  597. rx = Math.Min (rx, Driver.Cols - 1);
  598. }
  599. }
  600. /// <summary>
  601. /// Converts a <see cref="Bounds"/>-relative region to a screen-relative region.
  602. /// </summary>
  603. public Rect BoundsToScreen (Rect region)
  604. {
  605. BoundsToScreen (region.X, region.Y, out var x, out var y, clamped: false);
  606. return new Rect (x, y, region.Width, region.Height);
  607. }
  608. /// <summary>
  609. /// Gets the <see cref="Frame"/> with a screen-relative location.
  610. /// </summary>
  611. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  612. public virtual Rect FrameToScreen ()
  613. {
  614. var ret = Frame;
  615. var super = SuperView;
  616. while (super != null) {
  617. var boundsOffset = super.GetBoundsOffset ();
  618. ret.X += super.Frame.X + boundsOffset.X;
  619. ret.Y += super.Frame.Y + boundsOffset.Y;
  620. super = super.SuperView;
  621. }
  622. return ret;
  623. }
  624. /// <summary>
  625. /// Sets the View's <see cref="Frame"/> to the frame-relative coordinates if its container. The
  626. /// container size and location are specified by <paramref name="superviewFrame"/> and are relative to the
  627. /// View's superview.
  628. /// </summary>
  629. /// <param name="superviewFrame">The SuperView-relative rectangle describing View's container (nominally the
  630. /// same as <c>this.SuperView.Frame</c>).</param>
  631. internal void SetRelativeLayout (Rect superviewFrame)
  632. {
  633. int newX, newW, newY, newH;
  634. var autosize = Size.Empty;
  635. if (AutoSize) {
  636. // Note this is global to this function and used as such within the local functions defined
  637. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  638. autosize = GetAutoSize ();
  639. }
  640. // Returns the new dimension (width or height) and location (x or y) for the View given
  641. // the superview's Frame.X or Frame.Y
  642. // the superview's width or height
  643. // the current Pos (View.X or View.Y)
  644. // the current Dim (View.Width or View.Height)
  645. (int newLocation, int newDimension) GetNewLocationAndDimension (bool width, int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
  646. {
  647. int newDimension, newLocation;
  648. switch (pos) {
  649. case Pos.PosCenter:
  650. if (dim == null) {
  651. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  652. } else {
  653. newDimension = dim.Anchor (superviewDimension);
  654. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  655. }
  656. newLocation = pos.Anchor (superviewDimension - newDimension);
  657. break;
  658. case Pos.PosCombine combine:
  659. int left, right;
  660. (left, newDimension) = GetNewLocationAndDimension (width, superviewLocation, superviewDimension, combine.left, dim, autosizeDimension);
  661. (right, newDimension) = GetNewLocationAndDimension (width, superviewLocation, superviewDimension, combine.right, dim, autosizeDimension);
  662. if (combine.add) {
  663. newLocation = left + right;
  664. } else {
  665. newLocation = left - right;
  666. }
  667. newDimension = Math.Max (CalculateNewDimension (width, dim, newLocation, superviewDimension, autosizeDimension), 0);
  668. break;
  669. case Pos.PosAbsolute:
  670. case Pos.PosAnchorEnd:
  671. case Pos.PosFactor:
  672. case Pos.PosFunc:
  673. case Pos.PosView:
  674. default:
  675. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  676. newDimension = Math.Max (CalculateNewDimension (width, dim, newLocation, superviewDimension, autosizeDimension), 0);
  677. break;
  678. }
  679. return (newLocation, newDimension);
  680. }
  681. // Recursively calculates the new dimension (width or height) of the given Dim given:
  682. // the current location (x or y)
  683. // the current dimension (width or height)
  684. int CalculateNewDimension (bool width, Dim d, int location, int dimension, int autosize)
  685. {
  686. int newDimension;
  687. switch (d) {
  688. case null:
  689. newDimension = AutoSize ? autosize : dimension;
  690. break;
  691. case Dim.DimCombine combine:
  692. int leftNewDim = CalculateNewDimension (width, combine._left, location, dimension, autosize);
  693. int rightNewDim = CalculateNewDimension (width, combine._right, location, dimension, autosize);
  694. if (combine._add) {
  695. newDimension = leftNewDim + rightNewDim;
  696. } else {
  697. newDimension = leftNewDim - rightNewDim;
  698. }
  699. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  700. break;
  701. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  702. newDimension = d.Anchor (dimension);
  703. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  704. break;
  705. case Dim.DimAuto:
  706. var thickness = GetFramesThickness ();
  707. if (width) {
  708. var furthestRight = Subviews.Max (v => v.Frame.X + v.Frame.Width);
  709. newDimension = furthestRight + thickness.Left + thickness.Right;
  710. } else {
  711. var furthestBottom = Subviews.Max (v => v.Frame.Y + v.Frame.Height);
  712. newDimension = furthestBottom + thickness.Top + thickness.Bottom;
  713. }
  714. break;
  715. case Dim.DimFill:
  716. default:
  717. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  718. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  719. break;
  720. }
  721. return newDimension;
  722. }
  723. // horizontal width
  724. (newX, newW) = GetNewLocationAndDimension (true, superviewFrame.X, superviewFrame.Width, _x, _width, autosize.Width);
  725. // vertical height
  726. (newY, newH) = GetNewLocationAndDimension (false, superviewFrame.Y, superviewFrame.Height, _y, _height, autosize.Height);
  727. var r = new Rect (newX, newY, newW, newH);
  728. if (Frame != r) {
  729. Frame = r;
  730. // BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
  731. if (!SetBoundsToFitFrame ()) {
  732. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  733. }
  734. }
  735. }
  736. /// <summary>
  737. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  738. /// </summary>
  739. /// <remarks>
  740. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  741. /// </remarks>
  742. public event EventHandler<LayoutEventArgs> LayoutStarted;
  743. /// <summary>
  744. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  745. /// </summary>
  746. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  747. {
  748. LayoutStarted?.Invoke (this, args);
  749. }
  750. /// <summary>
  751. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  752. /// </summary>
  753. /// <remarks>
  754. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  755. /// </remarks>
  756. public event EventHandler<LayoutEventArgs> LayoutComplete;
  757. /// <summary>
  758. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  759. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  760. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  761. /// </summary>
  762. public event EventHandler Initialized;
  763. /// <summary>
  764. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  765. /// </summary>
  766. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  767. {
  768. LayoutComplete?.Invoke (this, args);
  769. }
  770. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  771. {
  772. switch (pos) {
  773. case Pos.PosView pv:
  774. // See #2461
  775. //if (!from.InternalSubviews.Contains (pv.Target)) {
  776. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  777. //}
  778. if (pv.Target != this) {
  779. nEdges.Add ((pv.Target, from));
  780. }
  781. return;
  782. case Pos.PosCombine pc:
  783. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  784. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  785. break;
  786. }
  787. }
  788. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  789. {
  790. switch (dim) {
  791. case Dim.DimView dv:
  792. // See #2461
  793. //if (!from.InternalSubviews.Contains (dv.Target)) {
  794. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  795. //}
  796. if (dv.Target != this) {
  797. nEdges.Add ((dv.Target, from));
  798. }
  799. return;
  800. case Dim.DimCombine dc:
  801. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  802. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  803. break;
  804. }
  805. }
  806. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  807. {
  808. foreach (var v in from.InternalSubviews) {
  809. nNodes.Add (v);
  810. if (v._layoutStyle != LayoutStyle.Computed) {
  811. continue;
  812. }
  813. CollectPos (v.X, v, ref nNodes, ref nEdges);
  814. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  815. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  816. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  817. }
  818. }
  819. // https://en.wikipedia.org/wiki/Topological_sorting
  820. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  821. {
  822. var result = new List<View> ();
  823. // Set of all nodes with no incoming edges
  824. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  825. while (noEdgeNodes.Any ()) {
  826. // remove a node n from S
  827. var n = noEdgeNodes.First ();
  828. noEdgeNodes.Remove (n);
  829. // add n to tail of L
  830. if (n != superView)
  831. result.Add (n);
  832. // for each node m with an edge e from n to m do
  833. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  834. var m = e.To;
  835. // remove edge e from the graph
  836. edges.Remove (e);
  837. // if m has no other incoming edges then
  838. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  839. // insert m into S
  840. noEdgeNodes.Add (m);
  841. }
  842. }
  843. }
  844. if (edges.Any ()) {
  845. foreach ((var from, var to) in edges) {
  846. if (from == to) {
  847. // if not yet added to the result, add it and remove from edge
  848. if (result.Find (v => v == from) == null) {
  849. result.Add (from);
  850. }
  851. edges.Remove ((from, to));
  852. } else if (from.SuperView == to.SuperView) {
  853. // if 'from' is not yet added to the result, add it
  854. if (result.Find (v => v == from) == null) {
  855. result.Add (from);
  856. }
  857. // if 'to' is not yet added to the result, add it
  858. if (result.Find (v => v == to) == null) {
  859. result.Add (to);
  860. }
  861. // remove from edge
  862. edges.Remove ((from, to));
  863. } else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to)) {
  864. if (ReferenceEquals (from.SuperView, to)) {
  865. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
  866. } else {
  867. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
  868. }
  869. }
  870. }
  871. }
  872. // return L (a topologically sorted order)
  873. return result;
  874. } // TopologicalSort
  875. /// <summary>
  876. /// Overriden by <see cref="Frame"/> to do nothing, as the <see cref="Frame"/> does not have frames.
  877. /// </summary>
  878. internal virtual void LayoutFrames ()
  879. {
  880. if (Margin == null) return; // CreateFrames() has not been called yet
  881. if (Margin.Frame.Size != Frame.Size) {
  882. Margin._frame = new Rect (Point.Empty, Frame.Size);
  883. Margin.X = 0;
  884. Margin.Y = 0;
  885. Margin.Width = Frame.Size.Width;
  886. Margin.Height = Frame.Size.Height;
  887. Margin.SetNeedsLayout ();
  888. Margin.LayoutSubviews ();
  889. Margin.SetNeedsDisplay ();
  890. }
  891. var border = Margin.Thickness.GetInside (Margin.Frame);
  892. if (border != Border.Frame) {
  893. Border._frame = new Rect (new Point (border.Location.X, border.Location.Y), border.Size);
  894. Border.X = border.Location.X;
  895. Border.Y = border.Location.Y;
  896. Border.Width = border.Size.Width;
  897. Border.Height = border.Size.Height;
  898. Border.SetNeedsLayout ();
  899. Border.LayoutSubviews ();
  900. Border.SetNeedsDisplay ();
  901. }
  902. var padding = Border.Thickness.GetInside (Border.Frame);
  903. if (padding != Padding.Frame) {
  904. Padding._frame = new Rect (new Point (padding.Location.X, padding.Location.Y), padding.Size);
  905. Padding.X = padding.Location.X;
  906. Padding.Y = padding.Location.Y;
  907. Padding.Width = padding.Size.Width;
  908. Padding.Height = padding.Size.Height;
  909. Padding.SetNeedsLayout ();
  910. Padding.LayoutSubviews ();
  911. Padding.SetNeedsDisplay ();
  912. }
  913. }
  914. /// <summary>
  915. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  916. /// response to the container view or terminal resizing.
  917. /// </summary>
  918. /// <remarks>
  919. /// Raises the <see cref="LayoutComplete"/> event) before it returns.
  920. /// </remarks>
  921. public virtual void LayoutSubviews ()
  922. {
  923. if (!LayoutNeeded) {
  924. return;
  925. }
  926. CheckDimAuto ();
  927. LayoutFrames ();
  928. var oldBounds = Bounds;
  929. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  930. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  931. // Sort out the dependencies of the X, Y, Width, Height properties
  932. var nodes = new HashSet<View> ();
  933. var edges = new HashSet<(View, View)> ();
  934. CollectAll (this, ref nodes, ref edges);
  935. var ordered = View.TopologicalSort (SuperView, nodes, edges);
  936. foreach (var v in ordered) {
  937. if (v.Width is Dim.DimAuto || v.Height is Dim.DimAuto) {
  938. // If the view is auto-sized...
  939. var f = v.Frame;
  940. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  941. if (v.Frame != f) {
  942. // The subviews changed; do it again
  943. v.LayoutNeeded = true;
  944. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  945. }
  946. } else {
  947. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  948. }
  949. }
  950. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  951. // Use LayoutSubview with the Frame of the 'from'
  952. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded && edges.Count > 0) {
  953. foreach ((var from, var to) in edges) {
  954. LayoutSubview (to, from.Frame);
  955. }
  956. }
  957. LayoutNeeded = false;
  958. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  959. }
  960. private void LayoutSubview (View v, Rect contentArea)
  961. {
  962. if (v.LayoutStyle == LayoutStyle.Computed) {
  963. v.SetRelativeLayout (contentArea);
  964. }
  965. v.LayoutSubviews ();
  966. v.LayoutNeeded = false;
  967. }
  968. bool _autoSize;
  969. /// <summary>
  970. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  971. /// within <see cref="Bounds"/>
  972. /// <para>
  973. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If <see langword="true"/> then
  974. /// <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can fit;
  975. /// if <see cref="Text"/> won't fit the view will be resized as needed.
  976. /// </para>
  977. /// <para>
  978. /// In addition, if <see cref="ValidatePosDim"/> is <see langword="true"/> the new values of <see cref="Width"/> and
  979. /// <see cref="Height"/> must be of the same types of the existing one to avoid breaking the <see cref="Dim"/> settings.
  980. /// </para>
  981. /// </summary>
  982. public virtual bool AutoSize {
  983. get => _autoSize;
  984. set {
  985. var v = ResizeView (value);
  986. TextFormatter.AutoSize = v;
  987. if (_autoSize != v) {
  988. _autoSize = v;
  989. TextFormatter.NeedsFormat = true;
  990. UpdateTextFormatterText ();
  991. OnResizeNeeded ();
  992. }
  993. }
  994. }
  995. bool ResizeView (bool autoSize)
  996. {
  997. if (!autoSize) {
  998. return false;
  999. }
  1000. var boundsChanged = true;
  1001. var newFrameSize = GetAutoSize ();
  1002. if (IsInitialized && newFrameSize != Frame.Size) {
  1003. if (ValidatePosDim) {
  1004. // BUGBUG: This ain't right, obviously. We need to figure out how to handle this.
  1005. boundsChanged = ResizeBoundsToFit (newFrameSize);
  1006. } else {
  1007. Height = newFrameSize.Height;
  1008. Width = newFrameSize.Width;
  1009. }
  1010. }
  1011. // BUGBUG: This call may be redundant
  1012. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  1013. return boundsChanged;
  1014. }
  1015. /// <summary>
  1016. /// Resizes the View to fit the specified size. Factors in the HotKey.
  1017. /// </summary>
  1018. /// <param name="size"></param>
  1019. /// <returns>whether the Bounds was changed or not</returns>
  1020. bool ResizeBoundsToFit (Size size)
  1021. {
  1022. var boundsChanged = false;
  1023. var canSizeW = TrySetWidth (size.Width - GetHotKeySpecifierLength (), out var rW);
  1024. var canSizeH = TrySetHeight (size.Height - GetHotKeySpecifierLength (false), out var rH);
  1025. if (canSizeW) {
  1026. boundsChanged = true;
  1027. _width = rW;
  1028. }
  1029. if (canSizeH) {
  1030. boundsChanged = true;
  1031. _height = rH;
  1032. }
  1033. if (boundsChanged) {
  1034. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  1035. }
  1036. return boundsChanged;
  1037. }
  1038. /// <summary>
  1039. /// Gets the Frame dimensions required to fit <see cref="Text"/> within <see cref="Bounds"/> using the text <see cref="Direction"/> specified by the
  1040. /// <see cref="TextFormatter"/> property and accounting for any <see cref="HotKeySpecifier"/> characters.
  1041. /// </summary>
  1042. /// <returns>The <see cref="Size"/> of the view required to fit the text.</returns>
  1043. public Size GetAutoSize ()
  1044. {
  1045. int x = 0;
  1046. int y = 0;
  1047. if (IsInitialized) {
  1048. x = Bounds.X;
  1049. y = Bounds.Y;
  1050. }
  1051. var rect = TextFormatter.CalcRect (x, y, TextFormatter.Text, TextFormatter.Direction);
  1052. var newWidth = rect.Size.Width - GetHotKeySpecifierLength () + Margin.Thickness.Horizontal + Border.Thickness.Horizontal + Padding.Thickness.Horizontal;
  1053. var newHeight = rect.Size.Height - GetHotKeySpecifierLength (false) + Margin.Thickness.Vertical + Border.Thickness.Vertical + Padding.Thickness.Vertical;
  1054. return new Size (newWidth, newHeight);
  1055. }
  1056. bool IsValidAutoSize (out Size autoSize)
  1057. {
  1058. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  1059. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  1060. rect.Size.Height - GetHotKeySpecifierLength (false));
  1061. return !(ValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  1062. || _frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  1063. || _frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  1064. }
  1065. bool IsValidAutoSizeWidth (Dim width)
  1066. {
  1067. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  1068. var dimValue = width.Anchor (0);
  1069. return !(ValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
  1070. - GetHotKeySpecifierLength ());
  1071. }
  1072. bool IsValidAutoSizeHeight (Dim height)
  1073. {
  1074. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  1075. var dimValue = height.Anchor (0);
  1076. return !(ValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
  1077. - GetHotKeySpecifierLength (false));
  1078. }
  1079. /// <summary>
  1080. /// Determines if the View's <see cref="Width"/> can be set to a new value.
  1081. /// </summary>
  1082. /// <param name="desiredWidth"></param>
  1083. /// <param name="resultWidth">Contains the width that would result if <see cref="Width"/> were set to <paramref name="desiredWidth"/>"/> </param>
  1084. /// <returns><see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False otherwise.</returns>
  1085. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  1086. {
  1087. var w = desiredWidth;
  1088. bool canSetWidth;
  1089. switch (Width) {
  1090. case Dim.DimCombine _:
  1091. case Dim.DimView _:
  1092. case Dim.DimFill _:
  1093. // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  1094. w = Width.Anchor (w);
  1095. canSetWidth = !ValidatePosDim;
  1096. break;
  1097. case Dim.DimFactor factor:
  1098. // Tries to get the SuperView Width otherwise the view Width.
  1099. var sw = SuperView != null ? SuperView.Frame.Width : w;
  1100. if (factor.IsFromRemaining ()) {
  1101. sw -= Frame.X;
  1102. }
  1103. w = Width.Anchor (sw);
  1104. canSetWidth = !ValidatePosDim;
  1105. break;
  1106. default:
  1107. canSetWidth = true;
  1108. break;
  1109. }
  1110. resultWidth = w;
  1111. return canSetWidth;
  1112. }
  1113. /// <summary>
  1114. /// Determines if the View's <see cref="Height"/> can be set to a new value.
  1115. /// </summary>
  1116. /// <param name="desiredHeight"></param>
  1117. /// <param name="resultHeight">Contains the width that would result if <see cref="Height"/> were set to <paramref name="desiredHeight"/>"/> </param>
  1118. /// <returns><see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False otherwise.</returns>
  1119. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  1120. {
  1121. var h = desiredHeight;
  1122. bool canSetHeight;
  1123. switch (Height) {
  1124. case Dim.DimCombine _:
  1125. case Dim.DimView _:
  1126. case Dim.DimFill _:
  1127. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  1128. h = Height.Anchor (h);
  1129. canSetHeight = !ValidatePosDim;
  1130. break;
  1131. case Dim.DimFactor factor:
  1132. // Tries to get the SuperView height otherwise the view height.
  1133. var sh = SuperView != null ? SuperView.Frame.Height : h;
  1134. if (factor.IsFromRemaining ()) {
  1135. sh -= Frame.Y;
  1136. }
  1137. h = Height.Anchor (sh);
  1138. canSetHeight = !ValidatePosDim;
  1139. break;
  1140. default:
  1141. canSetHeight = true;
  1142. break;
  1143. }
  1144. resultHeight = h;
  1145. return canSetHeight;
  1146. }
  1147. /// <summary>
  1148. /// Finds which view that belong to the <paramref name="start"/> superview at the provided location.
  1149. /// </summary>
  1150. /// <param name="start">The superview where to look for.</param>
  1151. /// <param name="x">The column location in the superview.</param>
  1152. /// <param name="y">The row location in the superview.</param>
  1153. /// <param name="resx">The found view screen relative column location.</param>
  1154. /// <param name="resy">The found view screen relative row location.</param>
  1155. /// <returns>
  1156. /// The view that was found at the <praramref name="x"/> and <praramref name="y"/> coordinates.
  1157. /// <see langword="null"/> if no view was found.
  1158. /// </returns>
  1159. public static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1160. {
  1161. resy = resx = 0;
  1162. if (start == null || !start.Frame.Contains (x, y)) {
  1163. return null;
  1164. }
  1165. var startFrame = start.Frame;
  1166. if (start.InternalSubviews != null) {
  1167. int count = start.InternalSubviews.Count;
  1168. if (count > 0) {
  1169. var boundsOffset = start.GetBoundsOffset ();
  1170. var rx = x - (startFrame.X + boundsOffset.X);
  1171. var ry = y - (startFrame.Y + boundsOffset.Y);
  1172. for (int i = count - 1; i >= 0; i--) {
  1173. View v = start.InternalSubviews [i];
  1174. if (v.Visible && v.Frame.Contains (rx, ry)) {
  1175. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1176. if (deep == null)
  1177. return v;
  1178. return deep;
  1179. }
  1180. }
  1181. }
  1182. }
  1183. resx = x - startFrame.X;
  1184. resy = y - startFrame.Y;
  1185. return start;
  1186. }
  1187. }
  1188. }