ViewLayout.cs 51 KB

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