ViewLayout.cs 51 KB

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