View.Layout.cs 43 KB

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