ViewLayout.cs 53 KB

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