ViewLayout.cs 50 KB

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