View.Layout.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. #nullable enable
  2. using System.Diagnostics;
  3. using Microsoft.CodeAnalysis;
  4. namespace Terminal.Gui;
  5. public partial class View // Layout APIs
  6. {
  7. #region Frame/Position/Dimension
  8. /// <summary>
  9. /// Indicates whether the specified SuperView-relative coordinates are within the View's <see cref="Frame"/>.
  10. /// </summary>
  11. /// <param name="location">SuperView-relative coordinate</param>
  12. /// <returns><see langword="true"/> if the specified SuperView-relative coordinates are within the View.</returns>
  13. public virtual bool Contains (in Point location) { return Frame.Contains (location); }
  14. private Rectangle? _frame;
  15. /// <summary>Gets or sets the absolute location and dimension of the view.</summary>
  16. /// <value>
  17. /// The rectangle describing absolute location and dimension of the view, in coordinates relative to the
  18. /// <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>.
  19. /// </value>
  20. /// <remarks>
  21. /// <para>
  22. /// See the View Layout Deep Dive for more information:
  23. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  24. /// </para>
  25. /// <para>
  26. /// Frame is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>
  27. /// .
  28. /// </para>
  29. /// <para>
  30. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> to absoulte values.
  31. /// </para>
  32. /// <para>
  33. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  34. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  35. /// </para>
  36. /// </remarks>
  37. public Rectangle Frame
  38. {
  39. get
  40. {
  41. if (_needsLayout)
  42. {
  43. //Debug.WriteLine("Frame_get with _layoutNeeded");
  44. }
  45. return _frame ?? Rectangle.Empty;
  46. }
  47. set
  48. {
  49. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  50. if (SetFrame (value with { Width = Math.Max (value.Width, 0), Height = Math.Max (value.Height, 0) }))
  51. {
  52. // If Frame gets set, set all Pos/Dim to Absolute values.
  53. _x = _frame!.Value.X;
  54. _y = _frame!.Value.Y;
  55. _width = _frame!.Value.Width;
  56. _height = _frame!.Value.Height;
  57. // Implicit layout is ok here because we are setting the Frame directly.
  58. Layout ();
  59. }
  60. }
  61. }
  62. /// <summary>
  63. /// INTERNAL API - Sets _frame, calls SetsNeedsLayout, and raises OnViewportChanged/ViewportChanged
  64. /// </summary>
  65. /// <param name="frame"></param>
  66. /// <returns><see langword="true"/> if the frame was changed.</returns>
  67. private bool SetFrame (in Rectangle frame)
  68. {
  69. if (_frame == frame)
  70. {
  71. return false;
  72. }
  73. var oldViewport = Rectangle.Empty;
  74. if (IsInitialized)
  75. {
  76. oldViewport = Viewport;
  77. }
  78. // This is the only place where _frame should be set directly. Use Frame = or SetFrame instead.
  79. _frame = frame;
  80. SetAdornmentFrames ();
  81. SetNeedsDisplay ();
  82. SetNeedsLayout ();
  83. // BUGBUG: When SetFrame is called from Frame_set, this event gets raised BEFORE OnResizeNeeded. Is that OK?
  84. OnViewportChanged (new (IsInitialized ? Viewport : Rectangle.Empty, oldViewport));
  85. return true;
  86. }
  87. /// <summary>Gets the <see cref="Frame"/> with a screen-relative location.</summary>
  88. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  89. public virtual Rectangle FrameToScreen ()
  90. {
  91. Rectangle screen = Frame;
  92. View? current = SuperView;
  93. while (current is { })
  94. {
  95. if (current is Adornment adornment)
  96. {
  97. // Adornments don't have SuperViews; use Adornment.FrameToScreen override
  98. // which will give us the screen coordinates of the parent
  99. Rectangle parentScreen = adornment.FrameToScreen ();
  100. // Now add our Frame location
  101. parentScreen.Offset (screen.X, screen.Y);
  102. return parentScreen;
  103. }
  104. Point viewportOffset = current.GetViewportOffsetFromFrame ();
  105. viewportOffset.Offset (current.Frame.X - current.Viewport.X, current.Frame.Y - current.Viewport.Y);
  106. screen.X += viewportOffset.X;
  107. screen.Y += viewportOffset.Y;
  108. current = current.SuperView;
  109. }
  110. return screen;
  111. }
  112. /// <summary>
  113. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means relative to the
  114. /// View's <see cref="SuperView"/>'s <see cref="Viewport"/>.
  115. /// </summary>
  116. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Viewport"/>.</returns>
  117. /// <param name="location">Screen-relative coordinate.</param>
  118. public virtual Point ScreenToFrame (in Point location)
  119. {
  120. if (SuperView is null)
  121. {
  122. return new (location.X - Frame.X, location.Y - Frame.Y);
  123. }
  124. Point superViewViewportOffset = SuperView.GetViewportOffsetFromFrame ();
  125. superViewViewportOffset.Offset (-SuperView.Viewport.X, -SuperView.Viewport.Y);
  126. Point frame = location;
  127. frame.Offset (-superViewViewportOffset.X, -superViewViewportOffset.Y);
  128. frame = SuperView.ScreenToFrame (frame);
  129. frame.Offset (-Frame.X, -Frame.Y);
  130. return frame;
  131. }
  132. // helper for X, Y, Width, Height setters to ensure consistency
  133. private void PosDimSet ()
  134. {
  135. SetNeedsLayout ();
  136. if (_x is PosAbsolute && _y is PosAbsolute && _width is DimAbsolute && _height is DimAbsolute)
  137. {
  138. // Implicit layout is ok here because all Pos/Dim are Absolute values.
  139. Layout ();
  140. // Ensure the next Application iteration tries to layout again
  141. SetNeedsLayout ();
  142. }
  143. }
  144. private Pos _x = Pos.Absolute (0);
  145. /// <summary>Gets or sets the X position for the view (the column).</summary>
  146. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  147. /// <remarks>
  148. /// <para>
  149. /// See the View Layout Deep Dive for more information:
  150. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  151. /// </para>
  152. /// <para>
  153. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  154. /// <see cref="GetContentSize ()"/>.
  155. /// </para>
  156. /// <para>
  157. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  158. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  159. /// </para>
  160. /// <para>
  161. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  162. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  163. /// </para>
  164. /// <para>
  165. /// Changing this property will cause <see cref="Frame"/> to be updated.
  166. /// </para>
  167. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  168. /// </remarks>
  169. public Pos X
  170. {
  171. get => VerifyIsInitialized (_x, nameof (X));
  172. set
  173. {
  174. if (Equals (_x, value))
  175. {
  176. return;
  177. }
  178. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  179. PosDimSet ();
  180. }
  181. }
  182. private Pos _y = Pos.Absolute (0);
  183. /// <summary>Gets or sets the Y position for the view (the row).</summary>
  184. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  185. /// <remarks>
  186. /// <para>
  187. /// See the View Layout Deep Dive for more information:
  188. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  189. /// </para>
  190. /// <para>
  191. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  192. /// <see cref="GetContentSize ()"/>.
  193. /// </para>
  194. /// <para>
  195. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  196. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  197. /// </para>
  198. /// <para>
  199. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  200. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  201. /// </para>
  202. /// <para>
  203. /// Changing this property will cause <see cref="Frame"/> to be updated.
  204. /// </para>
  205. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  206. /// </remarks>
  207. public Pos Y
  208. {
  209. get => VerifyIsInitialized (_y, nameof (Y));
  210. set
  211. {
  212. if (Equals (_y, value))
  213. {
  214. return;
  215. }
  216. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  217. PosDimSet ();
  218. }
  219. }
  220. private Dim? _height = Dim.Absolute (0);
  221. /// <summary>Gets or sets the height dimension of the view.</summary>
  222. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  223. /// <remarks>
  224. /// <para>
  225. /// See the View Layout Deep Dive for more information:
  226. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  227. /// </para>
  228. /// <para>
  229. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  230. /// <see cref="GetContentSize ()"/> .
  231. /// </para>
  232. /// <para>
  233. /// If set to a relative value (e.g. <see cref="DimFill"/>) the value is indeterminate until the view has been
  234. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  235. /// </para>
  236. /// <para>
  237. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  238. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  239. /// </para>
  240. /// <para>
  241. /// Changing this property will cause <see cref="Frame"/> to be updated.
  242. /// </para>
  243. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  244. /// </remarks>
  245. public Dim? Height
  246. {
  247. get => VerifyIsInitialized (_height, nameof (Height));
  248. set
  249. {
  250. if (Equals (_height, value))
  251. {
  252. return;
  253. }
  254. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  255. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  256. TextFormatter.ConstrainToHeight = null;
  257. PosDimSet ();
  258. }
  259. }
  260. private Dim? _width = Dim.Absolute (0);
  261. /// <summary>Gets or sets the width dimension of the view.</summary>
  262. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  263. /// <remarks>
  264. /// <para>
  265. /// See the View Layout Deep Dive for more information:
  266. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  267. /// </para>
  268. /// <para>
  269. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  270. /// <see cref="GetContentSize ()"/>
  271. /// .
  272. /// </para>
  273. /// <para>
  274. /// If set to a relative value (e.g. <see cref="DimFill"/>) the value is indeterminate until the view has been
  275. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  276. /// </para>
  277. /// <para>
  278. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  279. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  280. /// </para>
  281. /// <para>
  282. /// Changing this property will cause <see cref="Frame"/> to be updated.
  283. /// </para>
  284. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  285. /// </remarks>
  286. public Dim? Width
  287. {
  288. get => VerifyIsInitialized (_width, nameof (Width));
  289. set
  290. {
  291. if (Equals (_width, value))
  292. {
  293. return;
  294. }
  295. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  296. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  297. TextFormatter.ConstrainToWidth = null;
  298. PosDimSet ();
  299. }
  300. }
  301. #endregion Frame/Position/Dimension
  302. #region Core Layout API
  303. /// <summary>
  304. /// Performs layout of the view and its subviews within the specified content size.
  305. /// </summary>
  306. /// <remarks>
  307. /// <para>
  308. /// See the View Layout Deep Dive for more information:
  309. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  310. /// </para>
  311. /// <para>
  312. /// This method is intended to be called by the layout engine to
  313. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  314. /// </para>
  315. /// </remarks>
  316. /// <param name="contentSize"></param>
  317. /// <returns><see langword="false"/>If the view could not be laid out (typically because a dependencies was not ready). </returns>
  318. public bool Layout (Size contentSize)
  319. {
  320. if (SetRelativeLayout (contentSize))
  321. {
  322. LayoutSubviews ();
  323. // Debug.Assert(!NeedsLayout);
  324. return true;
  325. }
  326. return false;
  327. }
  328. /// <summary>
  329. /// Performs layout of the view and its subviews using the content size of either the <see cref="SuperView"/> or <see cref="Application.Screen"/>.
  330. /// </summary>
  331. /// <remarks>
  332. /// <para>
  333. /// See the View Layout Deep Dive for more information:
  334. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  335. /// </para>
  336. /// <para>
  337. /// This method is intended to be called by the layout engine to
  338. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  339. /// </para>
  340. /// </remarks>
  341. /// <returns><see langword="false"/>If the view could not be laid out (typically because dependency was not ready). </returns>
  342. public bool Layout ()
  343. {
  344. return Layout (GetContainerSize ());
  345. }
  346. /// <summary>
  347. /// Sets the position and size of this view, relative to the SuperView's ContentSize (nominally the same as
  348. /// <c>this.SuperView.GetContentSize ()</c>) based on the values of <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>,
  349. /// and <see cref="Height"/>.
  350. /// </summary>
  351. /// <remarks>
  352. /// <para>
  353. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  354. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  355. /// are left unchanged.
  356. /// </para>
  357. /// <para>
  358. /// This method does not arrange subviews or adornments. It is intended to be called by the layout engine to
  359. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  360. /// </para>
  361. /// <para>
  362. /// Some subviews may have SetRelativeLayout called on them as a side effect, particularly in DimAuto scenarios.
  363. /// </para>
  364. /// </remarks>
  365. /// <param name="superviewContentSize">
  366. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.GetContentSize ()</c>).
  367. /// </param>
  368. /// <returns><see langword="true"/> if successful. <see langword="false"/> means a dependent View still needs layout.</returns>
  369. public bool SetRelativeLayout (Size superviewContentSize)
  370. {
  371. Debug.Assert (_x is { });
  372. Debug.Assert (_y is { });
  373. Debug.Assert (_width is { });
  374. Debug.Assert (_height is { });
  375. CheckDimAuto ();
  376. // TODO: Should move to View.LayoutSubviews?
  377. SetTextFormatterSize ();
  378. int newX, newW, newY, newH;
  379. try
  380. {
  381. // Calculate the new X, Y, Width, and Height
  382. // If the Width or Height is Dim.Auto, calculate the Width or Height first. Otherwise, calculate the X or Y first.
  383. if (_width.Has<DimAuto> (out _))
  384. {
  385. newW = _width.Calculate (0, superviewContentSize.Width, this, Dimension.Width);
  386. newX = _x.Calculate (superviewContentSize.Width, newW, this, Dimension.Width);
  387. if (newW != Frame.Width)
  388. {
  389. // Pos.Calculate gave us a new position. We need to redo dimension
  390. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  391. }
  392. }
  393. else
  394. {
  395. newX = _x.Calculate (superviewContentSize.Width, _width, this, Dimension.Width);
  396. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  397. }
  398. if (_height.Has<DimAuto> (out _))
  399. {
  400. newH = _height.Calculate (0, superviewContentSize.Height, this, Dimension.Height);
  401. newY = _y.Calculate (superviewContentSize.Height, newH, this, Dimension.Height);
  402. if (newH != Frame.Height)
  403. {
  404. // Pos.Calculate gave us a new position. We need to redo dimension
  405. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  406. }
  407. }
  408. else
  409. {
  410. newY = _y.Calculate (superviewContentSize.Height, _height, this, Dimension.Height);
  411. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  412. }
  413. }
  414. catch (LayoutException le)
  415. {
  416. //Debug.WriteLine ($"A Dim/PosFunc function threw (typically this is because a dependent View was not laid out)\n{le}.");
  417. return false;
  418. }
  419. Rectangle newFrame = new (newX, newY, newW, newH);
  420. if (Frame != newFrame)
  421. {
  422. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height
  423. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  424. SetFrame (newFrame);
  425. if (_x is PosAbsolute)
  426. {
  427. _x = Frame.X;
  428. }
  429. if (_y is PosAbsolute)
  430. {
  431. _y = Frame.Y;
  432. }
  433. if (_width is DimAbsolute)
  434. {
  435. _width = Frame.Width;
  436. }
  437. if (_height is DimAbsolute)
  438. {
  439. _height = Frame.Height;
  440. }
  441. if (!string.IsNullOrEmpty (Title))
  442. {
  443. SetTitleTextFormatterSize ();
  444. }
  445. SuperView?.SetNeedsDisplay ();
  446. }
  447. if (TextFormatter.ConstrainToWidth is null)
  448. {
  449. TextFormatter.ConstrainToWidth = GetContentSize ().Width;
  450. }
  451. if (TextFormatter.ConstrainToHeight is null)
  452. {
  453. TextFormatter.ConstrainToHeight = GetContentSize ().Height;
  454. }
  455. return true;
  456. }
  457. /// <summary>
  458. /// INTERNAL API - Causes the view's subviews and adornments to be laid out within the view's content areas. Assumes the view's relative layout has been set via <see cref="SetRelativeLayout"/>.
  459. /// </summary>
  460. /// <remarks>
  461. /// <para>
  462. /// See the View Layout Deep Dive for more information:
  463. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  464. /// </para>
  465. /// <para>
  466. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  467. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  468. /// </para>
  469. /// <para>Raises the <see cref="SubviewsLaidOut"/> event before it returns.</para>
  470. /// </remarks>
  471. internal void LayoutSubviews ()
  472. {
  473. if (!NeedsLayout)
  474. {
  475. return;
  476. }
  477. CheckDimAuto ();
  478. Size contentSize = GetContentSize ();
  479. OnSubviewLayout (new (contentSize));
  480. SubviewLayout?.Invoke(this, new (contentSize));
  481. // The Adornments already have their Frame's set by SetRelativeLayout so we call LayoutSubViews vs. Layout here.
  482. if (Margin is { Subviews.Count: > 0 })
  483. {
  484. Margin.LayoutSubviews ();
  485. }
  486. if (Border is { Subviews.Count: > 0 })
  487. {
  488. Border.LayoutSubviews ();
  489. }
  490. if (Padding is { Subviews.Count: > 0 })
  491. {
  492. Padding.LayoutSubviews ();
  493. }
  494. // Sort out the dependencies of the X, Y, Width, Height properties
  495. HashSet<View> nodes = new ();
  496. HashSet<(View, View)> edges = new ();
  497. CollectAll (this, ref nodes, ref edges);
  498. List<View> ordered = TopologicalSort (SuperView!, nodes, edges);
  499. List<View> redo = new ();
  500. foreach (View v in ordered)
  501. {
  502. if (!v.Layout (contentSize))
  503. {
  504. redo.Add (v);
  505. }
  506. }
  507. bool layoutStillNeeded = false;
  508. if (redo.Count > 0)
  509. {
  510. foreach (View v in ordered)
  511. {
  512. if (!v.Layout (contentSize))
  513. {
  514. layoutStillNeeded = true;
  515. }
  516. }
  517. }
  518. // If the 'to' is rooted to 'from' it's a special-case.
  519. // Use Layout with the ContentSize of the 'from'.
  520. // See the Nested_SubViews_Ref_Topmost_SuperView unit test
  521. if (edges.Count > 0 && GetTopSuperView () is { })
  522. {
  523. foreach ((View from, View to) in edges)
  524. {
  525. // QUESTION: Do we test this with adornments well enough?
  526. to.Layout (from.GetContentSize ());
  527. }
  528. }
  529. _needsLayout = layoutStillNeeded;
  530. OnSubviewsLaidOut (new (contentSize));
  531. SubviewsLaidOut?.Invoke (this, new (contentSize));
  532. }
  533. /// <summary>
  534. /// Called from <see cref="LayoutSubviews"/> before any subviews
  535. /// have been laid out.
  536. /// </summary>
  537. /// <remarks>
  538. /// Override to perform tasks when the layout is changing.
  539. /// </remarks>
  540. protected virtual void OnSubviewLayout (LayoutEventArgs args) { }
  541. /// <summary>Raised by <see cref="LayoutSubviews"/> before any subviews
  542. /// have been laid out.</summary>
  543. /// <remarks>
  544. /// Subscribe to this event to perform tasks when the layout is changing.
  545. /// </remarks>
  546. public event EventHandler<LayoutEventArgs>? SubviewLayout;
  547. /// <summary>
  548. /// Called from <see cref="LayoutSubviews"/> after all sub-views
  549. /// have been laid out.
  550. /// </summary>
  551. /// <remarks>
  552. /// Override to perform tasks after the <see cref="View"/> has been resized or the layout has
  553. /// otherwise changed.
  554. /// </remarks>
  555. protected virtual void OnSubviewsLaidOut (LayoutEventArgs args) { }
  556. /// <summary>Raised after all sub-views have been laid out.</summary>
  557. /// <remarks>
  558. /// Subscribe to this event to perform tasks after the <see cref="View"/> has been resized or the layout has
  559. /// otherwise changed.
  560. /// </remarks>
  561. public event EventHandler<LayoutEventArgs>? SubviewsLaidOut;
  562. #endregion Core Layout API
  563. #region NeedsLayout
  564. // We expose no setter for this to ensure that the ONLY place it's changed is in SetNeedsLayout
  565. private bool _needsLayout = true;
  566. /// <summary>
  567. /// Indicates the View's Frame or the layout of the View's subviews (including Adornments) have
  568. /// changed since the last time the View was laid out.
  569. /// </summary>
  570. /// <remarks>
  571. /// <para>Used to prevent <see cref="Layout()"/> from needlessly computing
  572. /// layout.
  573. /// </para>
  574. /// </remarks>
  575. /// <value>
  576. /// <see langword="true"/> if layout is needed.
  577. /// </value>
  578. public bool NeedsLayout => _needsLayout;
  579. /// <summary>
  580. /// Sets <see cref="NeedsLayout"/> to return <see langword="true"/>, indicating this View and all of it's subviews (including adornments) need to be laid out in the next Application iteration.
  581. /// </summary>
  582. /// <remarks>
  583. /// <para>
  584. /// The <see cref="MainLoop"/> will cause <see cref="Layout()"/> to be called on the next <see cref="Application.Iteration"/> so there is normally no reason to call see <see cref="Layout()"/>.
  585. /// </para>
  586. /// </remarks>
  587. public void SetNeedsLayout ()
  588. {
  589. _needsLayout = true;
  590. if (Margin is { Subviews.Count: > 0 })
  591. {
  592. Margin.SetNeedsLayout ();
  593. }
  594. if (Border is { Subviews.Count: > 0 })
  595. {
  596. Border.SetNeedsLayout ();
  597. }
  598. if (Padding is { Subviews.Count: > 0 })
  599. {
  600. Padding.SetNeedsLayout ();
  601. }
  602. // Use a stack to avoid recursion
  603. Stack<View> stack = new Stack<View> (Subviews);
  604. while (stack.Count > 0)
  605. {
  606. View current = stack.Pop ();
  607. if (!current.NeedsLayout)
  608. {
  609. current._needsLayout = true;
  610. if (current.Margin is { Subviews.Count: > 0 })
  611. {
  612. current.Margin.SetNeedsLayout ();
  613. }
  614. if (current.Border is { Subviews.Count: > 0 })
  615. {
  616. current.Border.SetNeedsLayout ();
  617. }
  618. if (current.Padding is { Subviews.Count: > 0 })
  619. {
  620. current.Padding.SetNeedsLayout ();
  621. }
  622. foreach (View subview in current.Subviews)
  623. {
  624. stack.Push (subview);
  625. }
  626. }
  627. }
  628. TextFormatter.NeedsFormat = true;
  629. if (SuperView is { NeedsLayout: false })
  630. {
  631. SuperView?.SetNeedsLayout ();
  632. }
  633. if (this is not Adornment adornment)
  634. {
  635. return;
  636. }
  637. if (adornment.Parent is { NeedsLayout: false })
  638. {
  639. adornment.Parent?.SetNeedsLayout ();
  640. }
  641. }
  642. #endregion NeedsLayout
  643. #region Topological Sort
  644. /// <summary>
  645. /// INTERNAL API - Collects all views and their dependencies from a given starting view for layout purposes. Used by
  646. /// <see cref="TopologicalSort"/> to create an ordered list of views to layout.
  647. /// </summary>
  648. /// <param name="from">The starting view from which to collect dependencies.</param>
  649. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  650. /// <param name="nEdges">
  651. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  652. /// indicating a dependency.
  653. /// </param>
  654. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  655. {
  656. foreach (View? v in from.InternalSubviews)
  657. {
  658. nNodes.Add (v);
  659. CollectPos (v.X, v, ref nNodes, ref nEdges);
  660. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  661. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  662. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  663. }
  664. }
  665. /// <summary>
  666. /// INTERNAL API - Collects dimension (where Width or Height is `DimView`) dependencies for a given view.
  667. /// </summary>
  668. /// <param name="dim">The dimension (width or height) to collect dependencies for.</param>
  669. /// <param name="from">The view for which to collect dimension dependencies.</param>
  670. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  671. /// <param name="nEdges">
  672. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  673. /// indicating a dependency.
  674. /// </param>
  675. internal void CollectDim (Dim? dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  676. {
  677. if (dim!.Has<DimView> (out DimView dv))
  678. {
  679. if (dv.Target != this)
  680. {
  681. nEdges.Add ((dv.Target!, from));
  682. }
  683. }
  684. if (dim!.Has<DimCombine> (out DimCombine dc))
  685. {
  686. CollectDim (dc.Left, from, ref nNodes, ref nEdges);
  687. CollectDim (dc.Right, from, ref nNodes, ref nEdges);
  688. }
  689. }
  690. /// <summary>
  691. /// INTERNAL API - Collects position (where X or Y is `PosView`) dependencies for a given view.
  692. /// </summary>
  693. /// <param name="pos">The position (X or Y) to collect dependencies for.</param>
  694. /// <param name="from">The view for which to collect position dependencies.</param>
  695. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  696. /// <param name="nEdges">
  697. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  698. /// indicating a dependency.
  699. /// </param>
  700. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  701. {
  702. // TODO: Use Pos.Has<T> instead.
  703. switch (pos)
  704. {
  705. case PosView pv:
  706. Debug.Assert (pv.Target is { });
  707. if (pv.Target != this)
  708. {
  709. nEdges.Add ((pv.Target!, from));
  710. }
  711. return;
  712. case PosCombine pc:
  713. CollectPos (pc.Left, from, ref nNodes, ref nEdges);
  714. CollectPos (pc.Right, from, ref nNodes, ref nEdges);
  715. break;
  716. }
  717. }
  718. // https://en.wikipedia.org/wiki/Topological_sorting
  719. internal static List<View> TopologicalSort (
  720. View superView,
  721. IEnumerable<View> nodes,
  722. ICollection<(View From, View To)> edges
  723. )
  724. {
  725. List<View> result = new ();
  726. // Set of all nodes with no incoming edges
  727. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  728. while (noEdgeNodes.Any ())
  729. {
  730. // remove a node n from S
  731. View n = noEdgeNodes.First ();
  732. noEdgeNodes.Remove (n);
  733. // add n to tail of L
  734. if (n != superView)
  735. {
  736. result.Add (n);
  737. }
  738. // for each node m with an edge e from n to m do
  739. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  740. {
  741. View m = e.To;
  742. // remove edge e from the graph
  743. edges.Remove (e);
  744. // if m has no other incoming edges then
  745. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  746. {
  747. // insert m into S
  748. noEdgeNodes.Add (m);
  749. }
  750. }
  751. }
  752. if (!edges.Any ())
  753. {
  754. return result;
  755. }
  756. foreach ((View from, View to) in edges)
  757. {
  758. if (from == to)
  759. {
  760. // if not yet added to the result, add it and remove from edge
  761. if (result.Find (v => v == from) is null)
  762. {
  763. result.Add (from);
  764. }
  765. edges.Remove ((from, to));
  766. }
  767. else if (from.SuperView == to.SuperView)
  768. {
  769. // if 'from' is not yet added to the result, add it
  770. if (result.Find (v => v == from) is null)
  771. {
  772. result.Add (from);
  773. }
  774. // if 'to' is not yet added to the result, add it
  775. if (result.Find (v => v == to) is null)
  776. {
  777. result.Add (to);
  778. }
  779. // remove from edge
  780. edges.Remove ((from, to));
  781. }
  782. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  783. {
  784. if (ReferenceEquals (from.SuperView, to))
  785. {
  786. throw new LayoutException (
  787. $"ComputedLayout for \"{superView}\": \"{to}\" "
  788. + $"references a SubView (\"{from}\")."
  789. );
  790. }
  791. throw new LayoutException (
  792. $"ComputedLayout for \"{superView}\": \"{from}\" "
  793. + $"linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  794. );
  795. }
  796. }
  797. // return L (a topologically sorted order)
  798. return result;
  799. } // TopologicalSort
  800. #endregion Topological Sort
  801. #region Utilities
  802. /// <summary>
  803. /// INTERNAL API - Gets the size of the SuperView's content (nominally the same as
  804. /// the SuperView's <see cref="GetContentSize ()"/>) or the screen size if there's no SuperView.
  805. /// </summary>
  806. /// <returns></returns>
  807. private Size GetContainerSize ()
  808. {
  809. // TODO: Get rid of refs to Top
  810. Size superViewContentSize = SuperView?.GetContentSize () ??
  811. (Application.Top is { } && Application.Top != this && Application.Top.IsInitialized
  812. ? Application.Top.GetContentSize ()
  813. : Application.Screen.Size);
  814. return superViewContentSize;
  815. }
  816. // BUGBUG: This method interferes with Dialog/MessageBox default min/max size.
  817. // TODO: Get rid of MenuBar coupling as part of https://github.com/gui-cs/Terminal.Gui/issues/2975
  818. /// <summary>
  819. /// Gets a new location of the <see cref="View"/> that is within the Viewport of the <paramref name="viewToMove"/>'s
  820. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  821. /// </summary>
  822. /// <remarks>
  823. /// If <paramref name="viewToMove"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  824. /// <see cref="Application.Top"/> the position will be bound by <see cref="Application.Screen"/>.
  825. /// </remarks>
  826. /// <param name="viewToMove">The View that is to be moved.</param>
  827. /// <param name="targetX">The target x location.</param>
  828. /// <param name="targetY">The target y location.</param>
  829. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  830. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  831. /// <returns>
  832. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  833. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  834. /// </returns>
  835. internal static View? GetLocationEnsuringFullVisibility (
  836. View viewToMove,
  837. int targetX,
  838. int targetY,
  839. out int nx,
  840. out int ny
  841. )
  842. {
  843. int maxDimension;
  844. View? superView;
  845. if (viewToMove is not Toplevel || viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  846. {
  847. maxDimension = Application.Screen.Width;
  848. superView = Application.Top;
  849. }
  850. else
  851. {
  852. // Use the SuperView's Viewport, not Frame
  853. maxDimension = viewToMove!.SuperView.Viewport.Width;
  854. superView = viewToMove.SuperView;
  855. }
  856. if (superView?.Margin is { } && superView == viewToMove!.SuperView)
  857. {
  858. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  859. }
  860. if (viewToMove!.Frame.Width <= maxDimension)
  861. {
  862. nx = Math.Max (targetX, 0);
  863. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  864. if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  865. {
  866. nx = Math.Max (viewToMove.Frame.Right, 0);
  867. }
  868. }
  869. else
  870. {
  871. nx = targetX;
  872. }
  873. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  874. var menuVisible = false;
  875. var statusVisible = false;
  876. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  877. {
  878. menuVisible = Application.Top?.MenuBar?.Visible == true;
  879. }
  880. else
  881. {
  882. View? t = viewToMove!.SuperView;
  883. while (t is { } and not Toplevel)
  884. {
  885. t = t.SuperView;
  886. }
  887. if (t is Toplevel topLevel)
  888. {
  889. menuVisible = topLevel.MenuBar?.Visible == true;
  890. }
  891. }
  892. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  893. {
  894. maxDimension = menuVisible ? 1 : 0;
  895. }
  896. else
  897. {
  898. maxDimension = 0;
  899. }
  900. ny = Math.Max (targetY, maxDimension);
  901. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  902. {
  903. maxDimension = statusVisible ? Application.Screen.Height - 1 : Application.Screen.Height;
  904. }
  905. else
  906. {
  907. maxDimension = statusVisible ? viewToMove!.SuperView.Viewport.Height - 1 : viewToMove!.SuperView.Viewport.Height;
  908. }
  909. if (superView?.Margin is { } && superView == viewToMove?.SuperView)
  910. {
  911. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  912. }
  913. ny = Math.Min (ny, maxDimension);
  914. if (viewToMove?.Frame.Height <= maxDimension)
  915. {
  916. ny = ny + viewToMove.Frame.Height > maxDimension
  917. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  918. : ny;
  919. if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  920. {
  921. ny = Math.Max (viewToMove.Frame.Bottom, 0);
  922. }
  923. }
  924. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  925. return superView!;
  926. }
  927. #endregion Utilities
  928. #region Diagnostics and Verification
  929. // Diagnostics to highlight when X or Y is read before the view has been initialized
  930. private Pos VerifyIsInitialized (Pos pos, string member)
  931. {
  932. //#if DEBUG
  933. // if (pos.ReferencesOtherViews () && !IsInitialized)
  934. // {
  935. // Debug.WriteLine (
  936. // $"WARNING: {member} = {pos} of {this} is dependent on other views and {member} "
  937. // + $"is being accessed before the View has been initialized. This is likely a bug."
  938. // );
  939. // }
  940. //#endif // DEBUG
  941. return pos;
  942. }
  943. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  944. private Dim? VerifyIsInitialized (Dim? dim, string member)
  945. {
  946. //#if DEBUG
  947. // if (dim.ReferencesOtherViews () && !IsInitialized)
  948. // {
  949. // Debug.WriteLine (
  950. // $"WARNING: {member} = {dim} of {this} is dependent on other views and {member} "
  951. // + $"is being accessed before the View has been initialized. This is likely a bug."
  952. // );
  953. // }
  954. //#endif // DEBUG
  955. return dim;
  956. }
  957. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  958. /// <remarks>
  959. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  960. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  961. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  962. /// thus should only be used for debugging.
  963. /// </remarks>
  964. public bool ValidatePosDim { get; set; }
  965. // TODO: Move this logic into the Pos/Dim classes
  966. /// <summary>
  967. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  968. /// Views dimensions.
  969. /// </summary>
  970. /// <exception cref="InvalidOperationException"></exception>
  971. private void CheckDimAuto ()
  972. {
  973. if (!ValidatePosDim || !IsInitialized)
  974. {
  975. return;
  976. }
  977. var widthAuto = Width as DimAuto;
  978. var heightAuto = Height as DimAuto;
  979. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  980. foreach (View view in Subviews)
  981. {
  982. if (widthAuto is { } && widthAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  983. {
  984. ThrowInvalid (view, view.Width, nameof (view.Width));
  985. ThrowInvalid (view, view.X, nameof (view.X));
  986. }
  987. if (heightAuto is { } && heightAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  988. {
  989. ThrowInvalid (view, view.Height, nameof (view.Height));
  990. ThrowInvalid (view, view.Y, nameof (view.Y));
  991. }
  992. }
  993. return;
  994. void ThrowInvalid (View view, object? checkPosDim, string name)
  995. {
  996. object? bad = null;
  997. switch (checkPosDim)
  998. {
  999. case Pos pos and PosAnchorEnd:
  1000. break;
  1001. case Pos pos and not PosAbsolute and not PosView and not PosCombine:
  1002. bad = pos;
  1003. break;
  1004. case Pos pos and PosCombine:
  1005. // Recursively check for not Absolute or not View
  1006. ThrowInvalid (view, (pos as PosCombine)?.Left, name);
  1007. ThrowInvalid (view, (pos as PosCombine)?.Right, name);
  1008. break;
  1009. case Dim dim and DimAuto:
  1010. break;
  1011. case Dim dim and DimFill:
  1012. break;
  1013. case Dim dim and not DimAbsolute and not DimView and not DimCombine:
  1014. bad = dim;
  1015. break;
  1016. case Dim dim and DimCombine:
  1017. // Recursively check for not Absolute or not View
  1018. ThrowInvalid (view, (dim as DimCombine)?.Left, name);
  1019. ThrowInvalid (view, (dim as DimCombine)?.Right, name);
  1020. break;
  1021. }
  1022. if (bad != null)
  1023. {
  1024. throw new LayoutException (
  1025. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  1026. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  1027. );
  1028. }
  1029. }
  1030. }
  1031. #endregion Diagnostics and Verification
  1032. }