ViewLayout.cs 51 KB

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