ViewLayout.cs 49 KB

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