View.Layout.cs 44 KB

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