ViewLayout.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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="prop">The property name.</param>
  429. /// <param name="oldValue"></param>
  430. /// <param name="newValue"></param>
  431. void CheckAbsolute (string prop, object oldValue, object newValue)
  432. {
  433. if (!IsInitialized || !ValidatePosDim || oldValue == null || oldValue.GetType () == newValue.GetType () || this is Toplevel) {
  434. return;
  435. }
  436. if (oldValue.GetType () != newValue.GetType () && newValue is (Pos.PosAbsolute or Dim.DimAbsolute)) {
  437. throw new ArgumentException ($@"{prop} must not be Absolute if LayoutStyle is Computed", prop);
  438. }
  439. }
  440. /// <summary>
  441. /// Called whenever the view needs to be resized. Sets <see cref="Frame"/> and
  442. /// triggers a <see cref="LayoutSubviews()"/> call.
  443. /// </summary>
  444. /// <remarks>
  445. /// Can be overridden if the view resize behavior is different than the default.
  446. /// </remarks>
  447. protected virtual void OnResizeNeeded ()
  448. {
  449. int actX = _x is Pos.PosAbsolute ? _x.Anchor (0) : _frame.X;
  450. int actY = _y is Pos.PosAbsolute ? _y.Anchor (0) : _frame.Y;
  451. if (AutoSize) {
  452. //if (TextAlignment == TextAlignment.Justified) {
  453. // throw new InvalidOperationException ("TextAlignment.Justified cannot be used with AutoSize");
  454. //}
  455. var s = GetAutoSize ();
  456. int w = _width is Dim.DimAbsolute && _width.Anchor (0) > s.Width ? _width.Anchor (0) : s.Width;
  457. int h = _height is Dim.DimAbsolute && _height.Anchor (0) > s.Height ? _height.Anchor (0) : s.Height;
  458. _frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
  459. } else {
  460. int w = _width is Dim.DimAbsolute ? _width.Anchor (0) : _frame.Width;
  461. int h = _height is Dim.DimAbsolute ? _height.Anchor (0) : _frame.Height;
  462. // BUGBUG: v2 - ? - If layoutstyle is absolute, this overwrites the current frame h/w with 0. Hmmm...
  463. // This is needed for DimAbsolute values by setting the frame before LayoutSubViews.
  464. _frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
  465. }
  466. //// BUGBUG: I think these calls are redundant or should be moved into just the AutoSize case
  467. if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
  468. SetFrameToFitText ();
  469. LayoutFrames ();
  470. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  471. SetNeedsLayout ();
  472. SetNeedsDisplay ();
  473. }
  474. if (IsInitialized
  475. && SuperView != null
  476. && LayoutStyle == LayoutStyle.Computed && (SuperView?.Height is Dim.DimAuto || SuperView?.Width is Dim.DimAuto)) {
  477. // DimAuto is in play, force a layout.
  478. // BUGBUG: This can cause LayoutSubviews to be called recursively resulting in a deadlock.
  479. // SetNeedsLayout should be sufficient, but it's not.
  480. SuperView.LayoutSubviews ();
  481. }
  482. }
  483. internal bool LayoutNeeded { get; private set; } = true;
  484. internal void SetNeedsLayout ()
  485. {
  486. if (LayoutNeeded) {
  487. return;
  488. }
  489. LayoutNeeded = true;
  490. foreach (var view in Subviews) {
  491. view.SetNeedsLayout ();
  492. }
  493. TextFormatter.NeedsFormat = true;
  494. SuperView?.SetNeedsLayout ();
  495. }
  496. /// <summary>
  497. /// Indicates that the view does not need to be laid out.
  498. /// </summary>
  499. protected void ClearLayoutNeeded () => LayoutNeeded = false;
  500. /// <summary>
  501. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means
  502. /// relative to the View's <see cref="SuperView"/>'s <see cref="Bounds"/>.
  503. /// </summary>
  504. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.</returns>
  505. /// <param name="x">Screen-relative column.</param>
  506. /// <param name="y">Screen-relative row.</param>
  507. public Point ScreenToFrame (int x, int y)
  508. {
  509. var superViewBoundsOffset = SuperView?.GetBoundsOffset () ?? Point.Empty;
  510. var ret = new Point (x - Frame.X - superViewBoundsOffset.X, y - Frame.Y - superViewBoundsOffset.Y);
  511. if (SuperView != null) {
  512. var superFrame = SuperView.ScreenToFrame (x - superViewBoundsOffset.X, y - superViewBoundsOffset.Y);
  513. ret = new Point (superFrame.X - Frame.X, superFrame.Y - Frame.Y);
  514. }
  515. return ret;
  516. }
  517. /// <summary>
  518. /// Converts a screen-relative coordinate to a bounds-relative coordinate.
  519. /// </summary>
  520. /// <returns>The coordinate relative to this view's <see cref="Bounds"/>.</returns>
  521. /// <param name="x">Screen-relative column.</param>
  522. /// <param name="y">Screen-relative row.</param>
  523. public Point ScreenToBounds (int x, int y)
  524. {
  525. var screen = ScreenToFrame (x, y);
  526. var boundsOffset = GetBoundsOffset ();
  527. return new Point (screen.X - boundsOffset.X, screen.Y - boundsOffset.Y);
  528. }
  529. /// <summary>
  530. /// Converts a <see cref="Bounds"/>-relative coordinate to a screen-relative coordinate. The output is optionally clamped to the screen dimensions.
  531. /// </summary>
  532. /// <param name="x"><see cref="Bounds"/>-relative column.</param>
  533. /// <param name="y"><see cref="Bounds"/>-relative row.</param>
  534. /// <param name="rx">Absolute column; screen-relative.</param>
  535. /// <param name="ry">Absolute row; screen-relative.</param>
  536. /// <param name="clamped">If <see langword="true"/>, <paramref name="rx"/> and <paramref name="ry"/> will be clamped to the
  537. /// screen dimensions (will never be negative and will always be less than <see cref="ConsoleDriver.Cols"/> and
  538. /// <see cref="ConsoleDriver.Rows"/>, respectively.</param>
  539. public virtual void BoundsToScreen (int x, int y, out int rx, out int ry, bool clamped = true)
  540. {
  541. var boundsOffset = GetBoundsOffset ();
  542. rx = x + Frame.X + boundsOffset.X;
  543. ry = y + Frame.Y + boundsOffset.Y;
  544. var super = SuperView;
  545. while (super != null) {
  546. boundsOffset = super.GetBoundsOffset ();
  547. rx += super.Frame.X + boundsOffset.X;
  548. ry += super.Frame.Y + boundsOffset.Y;
  549. super = super.SuperView;
  550. }
  551. // The following ensures that the cursor is always in the screen boundaries.
  552. if (clamped) {
  553. ry = Math.Min (ry, Driver.Rows - 1);
  554. rx = Math.Min (rx, Driver.Cols - 1);
  555. }
  556. }
  557. /// <summary>
  558. /// Converts a <see cref="Bounds"/>-relative region to a screen-relative region.
  559. /// </summary>
  560. public Rect BoundsToScreen (Rect region)
  561. {
  562. BoundsToScreen (region.X, region.Y, out int x, out int y, false);
  563. return new Rect (x, y, region.Width, region.Height);
  564. }
  565. /// <summary>
  566. /// Gets the <see cref="Frame"/> with a screen-relative location.
  567. /// </summary>
  568. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  569. public virtual Rect FrameToScreen ()
  570. {
  571. var ret = Frame;
  572. var super = SuperView;
  573. while (super != null) {
  574. var boundsOffset = super.GetBoundsOffset ();
  575. ret.X += super.Frame.X + boundsOffset.X;
  576. ret.Y += super.Frame.Y + boundsOffset.Y;
  577. super = super.SuperView;
  578. }
  579. return ret;
  580. }
  581. // TODO: Come up with a better name for this method. "SetRelativeLayout" lacks clarity and confuses. AdjustSizeAndPosition?
  582. /// <summary>
  583. /// Sets the View's position and dimensions (<see cref="Frame"/>) based on <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/>.
  584. /// </summary>
  585. /// <param name="superviewBounds">The rectangle describing the SuperView's Bounds (nominally the same as <c>this.SuperView.Bounds</c>).</param>
  586. internal void SetRelativeLayout (Rect superviewBounds)
  587. {
  588. int newX, newW, newY, newH;
  589. var autosize = Size.Empty;
  590. if (AutoSize) {
  591. // Note this is global to this function and used as such within the local functions defined
  592. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  593. autosize = GetAutoSize ();
  594. }
  595. // Returns the new dimension (width or height) and location (x or y) for the View given
  596. // the superview's Frame.X or Frame.Y
  597. // the superview's width or height
  598. // the current Pos (View.X or View.Y)
  599. // the current Dim (View.Width or View.Height)
  600. (int newLocation, int newDimension) GetNewLocationAndDimension (bool width, int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
  601. {
  602. int newDimension, newLocation;
  603. switch (pos) {
  604. case Pos.PosCenter:
  605. if (dim == null) {
  606. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  607. } else {
  608. newDimension = dim.Anchor (superviewDimension);
  609. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  610. }
  611. newLocation = pos.Anchor (superviewDimension - newDimension);
  612. #if false
  613. if (dim == null) {
  614. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  615. } else {
  616. newDimension = Math.Max (CalculateNewDimension (width, dim, 0, dim.Anchor (superviewDimension), autosizeDimension), 0);
  617. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  618. }
  619. newLocation = pos.Anchor (superviewDimension - newDimension);
  620. #endif
  621. break;
  622. case Pos.PosCombine combine:
  623. int left, right;
  624. (left, newDimension) = GetNewLocationAndDimension (width, superviewLocation, superviewDimension, combine._left, dim, autosizeDimension);
  625. (right, newDimension) = GetNewLocationAndDimension (width, superviewLocation, superviewDimension, combine._right, dim, autosizeDimension);
  626. if (combine._add) {
  627. newLocation = left + right;
  628. } else {
  629. newLocation = left - right;
  630. }
  631. newDimension = Math.Max (CalculateNewDimension (width, dim, newLocation, superviewDimension, autosizeDimension), 0);
  632. break;
  633. case Pos.PosAnchorEnd:
  634. case Pos.PosAbsolute:
  635. case Pos.PosFactor:
  636. case Pos.PosFunc:
  637. case Pos.PosView:
  638. default:
  639. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  640. newDimension = Math.Max (CalculateNewDimension (width, dim, newLocation, superviewDimension, autosizeDimension), 0);
  641. break;
  642. }
  643. return (newLocation, newDimension);
  644. }
  645. // Recursively calculates the new dimension (width or height) of the given Dim given:
  646. // width: true for width, false for height
  647. // location: the current location (x or y)
  648. // dimension: the current dimension (width or height)
  649. // autosize: the size to use if autosize = true
  650. int CalculateNewDimension (bool width, Dim d, int location, int dimension, int autosize)
  651. {
  652. int newDimension;
  653. switch (d) {
  654. case null:
  655. newDimension = AutoSize ? autosize : dimension;
  656. break;
  657. case Dim.DimCombine combine:
  658. int leftNewDim = CalculateNewDimension (width, combine._left, location, dimension, autosize);
  659. int rightNewDim = CalculateNewDimension (width, 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.DimAuto auto:
  672. var thickness = GetFramesThickness ();
  673. newDimension = CalculateNewDimension (width, auto._min, location, dimension, autosize);
  674. if (width) {
  675. int furthestRight = Subviews.Count == 0 ? 0 : Subviews.Max (v => v.Frame.X + v.Frame.Width);
  676. newDimension = int.Max (furthestRight + thickness.Left + thickness.Right, auto._min?.Anchor (SuperView?.Bounds.Width ?? 0) ?? 0);
  677. } else {
  678. int furthestBottom = Subviews.Count == 0 ? 0 : Subviews.Max (v => v.Frame.Y + v.Frame.Height);
  679. newDimension = int.Max (furthestBottom + thickness.Top + thickness.Bottom, auto._min?.Anchor (SuperView?.Bounds.Height ?? 0) ?? 0);
  680. }
  681. break;
  682. case Dim.DimFill:
  683. default:
  684. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  685. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  686. break;
  687. }
  688. return newDimension;
  689. }
  690. // horizontal/width
  691. (newX, newW) = GetNewLocationAndDimension (true, superviewBounds.X, superviewBounds.Width, _x, _width, autosize.Width);
  692. // vertical/height
  693. (newY, newH) = GetNewLocationAndDimension (false, superviewBounds.Y, superviewBounds.Height, _y, _height, autosize.Height);
  694. var r = new Rect (newX, newY, newW, newH);
  695. if (Frame != r) {
  696. Frame = r;
  697. // BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
  698. if (!SetFrameToFitText ()) {
  699. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  700. }
  701. }
  702. }
  703. /// <summary>
  704. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  705. /// </summary>
  706. /// <remarks>
  707. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  708. /// </remarks>
  709. public event EventHandler<LayoutEventArgs> LayoutStarted;
  710. /// <summary>
  711. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  712. /// </summary>
  713. internal virtual void OnLayoutStarted (LayoutEventArgs args) => LayoutStarted?.Invoke (this, args);
  714. /// <summary>
  715. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  716. /// </summary>
  717. /// <remarks>
  718. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  719. /// </remarks>
  720. public event EventHandler<LayoutEventArgs> LayoutComplete;
  721. /// <summary>
  722. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  723. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  724. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  725. /// </summary>
  726. public event EventHandler Initialized;
  727. /// <summary>
  728. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  729. /// </summary>
  730. internal virtual void OnLayoutComplete (LayoutEventArgs args) => LayoutComplete?.Invoke (this, args);
  731. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  732. {
  733. switch (pos) {
  734. case Pos.PosView pv:
  735. // See #2461
  736. //if (!from.InternalSubviews.Contains (pv.Target)) {
  737. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  738. //}
  739. if (pv.Target != this) {
  740. nEdges.Add ((pv.Target, from));
  741. }
  742. return;
  743. case Pos.PosCombine pc:
  744. CollectPos (pc._left, from, ref nNodes, ref nEdges);
  745. CollectPos (pc._right, from, ref nNodes, ref nEdges);
  746. break;
  747. }
  748. }
  749. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  750. {
  751. switch (dim) {
  752. case Dim.DimView dv:
  753. // See #2461
  754. //if (!from.InternalSubviews.Contains (dv.Target)) {
  755. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  756. //}
  757. if (dv.Target != this) {
  758. nEdges.Add ((dv.Target, from));
  759. }
  760. return;
  761. case Dim.DimCombine dc:
  762. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  763. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  764. break;
  765. }
  766. }
  767. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  768. {
  769. // BUGBUG: This should really only work on initialized subviews
  770. foreach (var v in from.InternalSubviews /*.Where(v => v.IsInitialized)*/) {
  771. nNodes.Add (v);
  772. if (v._layoutStyle != LayoutStyle.Computed) {
  773. continue;
  774. }
  775. CollectPos (v.X, v, ref nNodes, ref nEdges);
  776. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  777. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  778. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  779. }
  780. }
  781. // https://en.wikipedia.org/wiki/Topological_sorting
  782. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  783. {
  784. var result = new List<View> ();
  785. // Set of all nodes with no incoming edges
  786. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  787. while (noEdgeNodes.Any ()) {
  788. // remove a node n from S
  789. var n = noEdgeNodes.First ();
  790. noEdgeNodes.Remove (n);
  791. // add n to tail of L
  792. if (n != superView) {
  793. result.Add (n);
  794. }
  795. // for each node m with an edge e from n to m do
  796. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  797. var m = e.To;
  798. // remove edge e from the graph
  799. edges.Remove (e);
  800. // if m has no other incoming edges then
  801. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  802. // insert m into S
  803. noEdgeNodes.Add (m);
  804. }
  805. }
  806. }
  807. if (!edges.Any ()) {
  808. return result;
  809. }
  810. foreach ((var from, var to) in edges) {
  811. if (from == to) {
  812. // if not yet added to the result, add it and remove from edge
  813. if (result.Find (v => v == from) == null) {
  814. result.Add (from);
  815. }
  816. edges.Remove ((from, to));
  817. } else if (from.SuperView == to.SuperView) {
  818. // if 'from' is not yet added to the result, add it
  819. if (result.Find (v => v == from) == null) {
  820. result.Add (from);
  821. }
  822. // if 'to' is not yet added to the result, add it
  823. if (result.Find (v => v == to) == null) {
  824. result.Add (to);
  825. }
  826. // remove from edge
  827. edges.Remove ((from, to));
  828. } else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to)) {
  829. if (ReferenceEquals (from.SuperView, to)) {
  830. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
  831. } else {
  832. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
  833. }
  834. }
  835. }
  836. // return L (a topologically sorted order)
  837. return result;
  838. } // TopologicalSort
  839. /// <summary>
  840. /// Overriden by <see cref="Frame"/> to do nothing, as the <see cref="Frame"/> does not have frames.
  841. /// </summary>
  842. internal virtual void LayoutFrames ()
  843. {
  844. if (Margin == null) {
  845. return; // CreateFrames() has not been called yet
  846. }
  847. if (Margin.Frame.Size != Frame.Size) {
  848. Margin._frame = new Rect (Point.Empty, Frame.Size);
  849. Margin.X = 0;
  850. Margin.Y = 0;
  851. Margin.Width = Frame.Size.Width;
  852. Margin.Height = Frame.Size.Height;
  853. Margin.SetNeedsLayout ();
  854. Margin.LayoutSubviews ();
  855. Margin.SetNeedsDisplay ();
  856. }
  857. var border = Margin.Thickness.GetInside (Margin.Frame);
  858. if (border != Border.Frame) {
  859. Border._frame = new Rect (new Point (border.Location.X, border.Location.Y), border.Size);
  860. Border.X = border.Location.X;
  861. Border.Y = border.Location.Y;
  862. Border.Width = border.Size.Width;
  863. Border.Height = border.Size.Height;
  864. Border.SetNeedsLayout ();
  865. Border.LayoutSubviews ();
  866. Border.SetNeedsDisplay ();
  867. }
  868. var padding = Border.Thickness.GetInside (Border.Frame);
  869. if (padding != Padding.Frame) {
  870. Padding._frame = new Rect (new Point (padding.Location.X, padding.Location.Y), padding.Size);
  871. Padding.X = padding.Location.X;
  872. Padding.Y = padding.Location.Y;
  873. Padding.Width = padding.Size.Width;
  874. Padding.Height = padding.Size.Height;
  875. Padding.SetNeedsLayout ();
  876. Padding.LayoutSubviews ();
  877. Padding.SetNeedsDisplay ();
  878. }
  879. }
  880. /// <summary>
  881. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  882. /// response to the container view or terminal resizing.
  883. /// </summary>
  884. /// <remarks>
  885. /// Raises the <see cref="LayoutComplete"/> event) before it returns.
  886. /// </remarks>
  887. public virtual void LayoutSubviews ()
  888. {
  889. if (!IsInitialized) {
  890. Debug.WriteLine ($"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}");
  891. }
  892. if (!LayoutNeeded) {
  893. return;
  894. }
  895. CheckDimAuto ();
  896. LayoutFrames ();
  897. var oldBounds = Bounds;
  898. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  899. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  900. // Sort out the dependencies of the X, Y, Width, Height properties
  901. var nodes = new HashSet<View> ();
  902. var edges = new HashSet<(View, View)> ();
  903. CollectAll (this, ref nodes, ref edges);
  904. var ordered = TopologicalSort (SuperView, nodes, edges);
  905. foreach (var v in ordered) {
  906. if (v.Width is Dim.DimAuto || v.Height is Dim.DimAuto) {
  907. // If the view is auto-sized...
  908. var f = v.Frame;
  909. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  910. if (v.Frame != f) {
  911. // The subviews changed; do it again
  912. v.LayoutNeeded = true;
  913. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  914. }
  915. } else {
  916. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  917. }
  918. }
  919. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  920. // Use LayoutSubview with the Frame of the 'from'
  921. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded && edges.Count > 0) {
  922. foreach ((var from, var to) in edges) {
  923. LayoutSubview (to, from.Frame);
  924. }
  925. }
  926. LayoutNeeded = false;
  927. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  928. }
  929. void LayoutSubview (View v, Rect contentArea)
  930. {
  931. if (v.LayoutStyle == LayoutStyle.Computed) {
  932. v.SetRelativeLayout (contentArea);
  933. }
  934. v.LayoutSubviews ();
  935. v.LayoutNeeded = false;
  936. }
  937. bool _autoSize;
  938. /// <summary>
  939. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  940. /// within <see cref="Bounds"/>
  941. /// <para>
  942. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If <see langword="true"/> then
  943. /// <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can fit;
  944. /// if <see cref="Text"/> won't fit the view will be resized as needed.
  945. /// </para>
  946. /// <para>
  947. /// In addition, if <see cref="ValidatePosDim"/> is <see langword="true"/> the new values of <see cref="Width"/> and
  948. /// <see cref="Height"/> must be of the same types of the existing one to avoid breaking the <see cref="Dim"/> settings.
  949. /// </para>
  950. /// </summary>
  951. public virtual bool AutoSize {
  952. get => _autoSize;
  953. set {
  954. bool v = ResizeView (value);
  955. TextFormatter.AutoSize = v;
  956. if (_autoSize != v) {
  957. _autoSize = v;
  958. TextFormatter.NeedsFormat = true;
  959. UpdateTextFormatterText ();
  960. OnResizeNeeded ();
  961. }
  962. }
  963. }
  964. bool ResizeView (bool autoSize)
  965. {
  966. if (!autoSize) {
  967. return false;
  968. }
  969. bool boundsChanged = true;
  970. var newFrameSize = GetAutoSize ();
  971. if (IsInitialized && newFrameSize != Frame.Size) {
  972. if (ValidatePosDim) {
  973. // BUGBUG: This ain't right, obviously. We need to figure out how to handle this.
  974. boundsChanged = ResizeBoundsToFit (newFrameSize);
  975. } else {
  976. Height = newFrameSize.Height;
  977. Width = newFrameSize.Width;
  978. }
  979. }
  980. // BUGBUG: This call may be redundant
  981. TextFormatter.Size = GetTextFormatterSizeNeededForTextAndHotKey ();
  982. return boundsChanged;
  983. }
  984. /// <summary>
  985. /// Resizes the View to fit the specified size. Factors in the HotKey.
  986. /// </summary>
  987. /// <param name="size"></param>
  988. /// <returns>whether the Bounds was changed or not</returns>
  989. bool ResizeBoundsToFit (Size size)
  990. {
  991. bool boundsChanged = false;
  992. bool canSizeW = TrySetWidth (size.Width - GetHotKeySpecifierLength (), out int rW);
  993. bool canSizeH = TrySetHeight (size.Height - GetHotKeySpecifierLength (false), out int rH);
  994. if (canSizeW) {
  995. boundsChanged = true;
  996. _width = rW;
  997. }
  998. if (canSizeH) {
  999. boundsChanged = true;
  1000. _height = rH;
  1001. }
  1002. if (boundsChanged) {
  1003. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  1004. }
  1005. return boundsChanged;
  1006. }
  1007. /// <summary>
  1008. /// Gets the Frame dimensions required to fit <see cref="Text"/> within <see cref="Bounds"/> using the text <see cref="Direction"/> specified by the
  1009. /// <see cref="TextFormatter"/> property and accounting for any <see cref="HotKeySpecifier"/> characters.
  1010. /// </summary>
  1011. /// <returns>The <see cref="Size"/> of the view required to fit the text.</returns>
  1012. public Size GetAutoSize ()
  1013. {
  1014. int x = 0;
  1015. int y = 0;
  1016. if (IsInitialized) {
  1017. x = Bounds.X;
  1018. y = Bounds.Y;
  1019. }
  1020. var rect = TextFormatter.CalcRect (x, y, TextFormatter.Text, TextFormatter.Direction);
  1021. int newWidth = rect.Size.Width - GetHotKeySpecifierLength () + Margin.Thickness.Horizontal + Border.Thickness.Horizontal + Padding.Thickness.Horizontal;
  1022. int newHeight = rect.Size.Height - GetHotKeySpecifierLength (false) + Margin.Thickness.Vertical + Border.Thickness.Vertical + Padding.Thickness.Vertical;
  1023. return new Size (newWidth, newHeight);
  1024. }
  1025. bool IsValidAutoSize (out Size autoSize)
  1026. {
  1027. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  1028. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  1029. rect.Size.Height - GetHotKeySpecifierLength (false));
  1030. return !(ValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  1031. || _frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  1032. || _frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  1033. }
  1034. bool IsValidAutoSizeWidth (Dim width)
  1035. {
  1036. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  1037. int dimValue = width.Anchor (0);
  1038. return !(ValidatePosDim && !(width is Dim.DimAbsolute) || dimValue != rect.Size.Width
  1039. - GetHotKeySpecifierLength ());
  1040. }
  1041. bool IsValidAutoSizeHeight (Dim height)
  1042. {
  1043. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  1044. int dimValue = height.Anchor (0);
  1045. return !(ValidatePosDim && !(height is Dim.DimAbsolute) || dimValue != rect.Size.Height
  1046. - GetHotKeySpecifierLength (false));
  1047. }
  1048. /// <summary>
  1049. /// Determines if the View's <see cref="Width"/> can be set to a new value.
  1050. /// </summary>
  1051. /// <param name="desiredWidth"></param>
  1052. /// <param name="resultWidth">Contains the width that would result if <see cref="Width"/> were set to <paramref name="desiredWidth"/>"/> </param>
  1053. /// <returns><see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False otherwise.</returns>
  1054. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  1055. {
  1056. int w = desiredWidth;
  1057. bool canSetWidth;
  1058. switch (Width) {
  1059. case Dim.DimCombine _:
  1060. case Dim.DimView _:
  1061. case Dim.DimFill _:
  1062. // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  1063. w = Width.Anchor (w);
  1064. canSetWidth = !ValidatePosDim;
  1065. break;
  1066. case Dim.DimFactor factor:
  1067. // Tries to get the SuperView Width otherwise the view Width.
  1068. int sw = SuperView != null ? SuperView.Frame.Width : w;
  1069. if (factor.IsFromRemaining ()) {
  1070. sw -= Frame.X;
  1071. }
  1072. w = Width.Anchor (sw);
  1073. canSetWidth = !ValidatePosDim;
  1074. break;
  1075. default:
  1076. canSetWidth = true;
  1077. break;
  1078. }
  1079. resultWidth = w;
  1080. return canSetWidth;
  1081. }
  1082. /// <summary>
  1083. /// Determines if the View's <see cref="Height"/> can be set to a new value.
  1084. /// </summary>
  1085. /// <param name="desiredHeight"></param>
  1086. /// <param name="resultHeight">Contains the width that would result if <see cref="Height"/> were set to <paramref name="desiredHeight"/>"/> </param>
  1087. /// <returns><see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False otherwise.</returns>
  1088. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  1089. {
  1090. int h = desiredHeight;
  1091. bool canSetHeight;
  1092. switch (Height) {
  1093. case Dim.DimCombine _:
  1094. case Dim.DimView _:
  1095. case Dim.DimFill _:
  1096. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  1097. h = Height.Anchor (h);
  1098. canSetHeight = !ValidatePosDim;
  1099. break;
  1100. case Dim.DimFactor factor:
  1101. // Tries to get the SuperView height otherwise the view height.
  1102. int sh = SuperView != null ? SuperView.Frame.Height : h;
  1103. if (factor.IsFromRemaining ()) {
  1104. sh -= Frame.Y;
  1105. }
  1106. h = Height.Anchor (sh);
  1107. canSetHeight = !ValidatePosDim;
  1108. break;
  1109. default:
  1110. canSetHeight = true;
  1111. break;
  1112. }
  1113. resultHeight = h;
  1114. return canSetHeight;
  1115. }
  1116. /// <summary>
  1117. /// Finds which view that belong to the <paramref name="start"/> superview at the provided location.
  1118. /// </summary>
  1119. /// <param name="start">The superview where to look for.</param>
  1120. /// <param name="x">The column location in the superview.</param>
  1121. /// <param name="y">The row location in the superview.</param>
  1122. /// <param name="resx">The found view screen relative column location.</param>
  1123. /// <param name="resy">The found view screen relative row location.</param>
  1124. /// <returns>
  1125. /// The view that was found at the <praramref name="x"/> and <praramref name="y"/> coordinates.
  1126. /// <see langword="null"/> if no view was found.
  1127. /// </returns>
  1128. public static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1129. {
  1130. resy = resx = 0;
  1131. if (start == null || !start.Frame.Contains (x, y)) {
  1132. return null;
  1133. }
  1134. var startFrame = start.Frame;
  1135. if (start.InternalSubviews != null) {
  1136. int count = start.InternalSubviews.Count;
  1137. if (count > 0) {
  1138. var boundsOffset = start.GetBoundsOffset ();
  1139. int rx = x - (startFrame.X + boundsOffset.X);
  1140. int ry = y - (startFrame.Y + boundsOffset.Y);
  1141. for (int i = count - 1; i >= 0; i--) {
  1142. var v = start.InternalSubviews [i];
  1143. if (v.Visible && v.Frame.Contains (rx, ry)) {
  1144. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1145. if (deep == null) {
  1146. return v;
  1147. }
  1148. return deep;
  1149. }
  1150. }
  1151. }
  1152. }
  1153. resx = x - startFrame.X;
  1154. resy = y - startFrame.Y;
  1155. return start;
  1156. }
  1157. }