ViewLayout.cs 52 KB

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