ViewLayout.cs 49 KB

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