2
0

ViewLayout.cs 53 KB

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