ViewLayout.cs 52 KB

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