ViewLayout.cs 48 KB

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