View.Layout.cs 44 KB

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