View.Layout.cs 44 KB

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