ViewLayout.cs 47 KB

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