ViewLayout.cs 48 KB

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