View.Layout.cs 44 KB

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