ViewLayout.cs 48 KB

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