View.Layout.cs 43 KB

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