ViewLayout.cs 47 KB

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