ViewLayout.cs 49 KB

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