ViewLayout.cs 51 KB

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