ViewLayout.cs 55 KB

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