View.Layout.cs 43 KB

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