ViewLayout.cs 55 KB

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