ViewLayout.cs 55 KB

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