View.Layout.cs 44 KB

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