ViewLayout.cs 46 KB

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