ViewLayout.cs 49 KB

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