View.Layout.cs 42 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 the <see cref="ConsoleDriver.Cols"/> and
  21. /// <see cref="ConsoleDriver.Rows"/>.
  22. /// </remarks>
  23. /// <param name="viewToMove">The View that is to be moved.</param>
  24. /// <param name="targetX">The target x location.</param>
  25. /// <param name="targetY">The target y location.</param>
  26. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  27. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  28. /// <returns>
  29. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  30. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  31. /// </returns>
  32. internal static View? GetLocationEnsuringFullVisibility (
  33. View viewToMove,
  34. int targetX,
  35. int targetY,
  36. out int nx,
  37. out int ny
  38. //,
  39. // out StatusBar? statusBar
  40. )
  41. {
  42. int maxDimension;
  43. View? superView;
  44. //statusBar = null!;
  45. if (viewToMove is not Toplevel || viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  46. {
  47. maxDimension = Driver.Cols;
  48. superView = Application.Top;
  49. }
  50. else
  51. {
  52. // Use the SuperView's Viewport, not Frame
  53. maxDimension = viewToMove!.SuperView.Viewport.Width;
  54. superView = viewToMove.SuperView;
  55. }
  56. if (superView?.Margin is { } && superView == viewToMove!.SuperView)
  57. {
  58. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  59. }
  60. if (viewToMove!.Frame.Width <= maxDimension)
  61. {
  62. nx = Math.Max (targetX, 0);
  63. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  64. if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  65. {
  66. nx = Math.Max (viewToMove.Frame.Right, 0);
  67. }
  68. }
  69. else
  70. {
  71. nx = targetX;
  72. }
  73. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  74. var menuVisible = false;
  75. var statusVisible = false;
  76. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  77. {
  78. menuVisible = Application.Top?.MenuBar?.Visible == true;
  79. }
  80. else
  81. {
  82. View? t = viewToMove!.SuperView;
  83. while (t is { } and not Toplevel)
  84. {
  85. t = t.SuperView;
  86. }
  87. if (t is Toplevel topLevel)
  88. {
  89. menuVisible = topLevel.MenuBar?.Visible == true;
  90. }
  91. }
  92. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  93. {
  94. maxDimension = menuVisible ? 1 : 0;
  95. }
  96. else
  97. {
  98. maxDimension = 0;
  99. }
  100. ny = Math.Max (targetY, maxDimension);
  101. //if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  102. //{
  103. // statusVisible = Application.Top?.StatusBar?.Visible == true;
  104. // statusBar = Application.Top?.StatusBar!;
  105. //}
  106. //else
  107. //{
  108. // View? t = viewToMove!.SuperView;
  109. // while (t is { } and not Toplevel)
  110. // {
  111. // t = t.SuperView;
  112. // }
  113. // if (t is Toplevel topLevel)
  114. // {
  115. // statusVisible = topLevel.StatusBar?.Visible == true;
  116. // statusBar = topLevel.StatusBar!;
  117. // }
  118. //}
  119. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  120. {
  121. maxDimension = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  122. }
  123. else
  124. {
  125. maxDimension = statusVisible ? viewToMove!.SuperView.Viewport.Height - 1 : viewToMove!.SuperView.Viewport.Height;
  126. }
  127. if (superView?.Margin is { } && superView == viewToMove?.SuperView)
  128. {
  129. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  130. }
  131. ny = Math.Min (ny, maxDimension);
  132. if (viewToMove?.Frame.Height <= maxDimension)
  133. {
  134. ny = ny + viewToMove.Frame.Height > maxDimension
  135. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  136. : ny;
  137. if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  138. {
  139. ny = Math.Max (viewToMove.Frame.Bottom, 0);
  140. }
  141. }
  142. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  143. return superView!;
  144. }
  145. #region Frame
  146. private Rectangle _frame;
  147. /// <summary>Gets or sets the absolute location and dimension of the view.</summary>
  148. /// <value>
  149. /// The rectangle describing absolute location and dimension of the view, in coordinates relative to the
  150. /// <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>.
  151. /// </value>
  152. /// <remarks>
  153. /// <para>
  154. /// See the View Layout Deep Dive for more information:
  155. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  156. /// </para>
  157. /// <para>
  158. /// Frame is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>
  159. /// .
  160. /// </para>
  161. /// <para>
  162. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> to the
  163. /// values of the corresponding properties of the <paramref name="value"/> parameter.
  164. /// </para>
  165. /// <para>
  166. /// Altering the Frame will eventually (when the view hierarchy is next laid out via see
  167. /// cref="LayoutSubviews"/>) cause <see cref="Layout"/> and
  168. /// <see cref="OnDrawContent(Rectangle)"/>
  169. /// methods to be called.
  170. /// </para>
  171. /// </remarks>
  172. public Rectangle Frame
  173. {
  174. get
  175. {
  176. if (_layoutNeeded)
  177. {
  178. //Debug.WriteLine("Frame_get with _layoutNeeded");
  179. }
  180. return _frame;
  181. }
  182. set
  183. {
  184. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  185. if (SetFrame (value with { Width = Math.Max (value.Width, 0), Height = Math.Max (value.Height, 0) }))
  186. {
  187. // If Frame gets set, set all Pos/Dim to Absolute values.
  188. _x = _frame.X;
  189. _y = _frame.Y;
  190. _width = _frame.Width;
  191. _height = _frame.Height;
  192. }
  193. }
  194. }
  195. /// <summary>
  196. /// INTERNAL API - Sets _frame, calls SetsNeedsLayout, and raises OnViewportChanged/ViewportChanged
  197. /// </summary>
  198. /// <param name="frame"></param>
  199. /// <returns><see langword="true"/> if the frame was changed.</returns>
  200. private bool SetFrame (in Rectangle frame)
  201. {
  202. if (_frame == frame)
  203. {
  204. return false;
  205. }
  206. var oldViewport = Rectangle.Empty;
  207. if (IsInitialized)
  208. {
  209. oldViewport = Viewport;
  210. }
  211. // This is the only place where _frame should be set directly. Use Frame = or SetFrame instead.
  212. _frame = frame;
  213. SetAdornmentFrames ();
  214. SetLayoutNeeded ();
  215. // BUGBUG: When SetFrame is called from Frame_set, this event gets raised BEFORE OnResizeNeeded. Is that OK?
  216. OnViewportChanged (new (IsInitialized ? Viewport : Rectangle.Empty, oldViewport));
  217. return true;
  218. }
  219. /// <summary>Gets the <see cref="Frame"/> with a screen-relative location.</summary>
  220. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  221. public virtual Rectangle FrameToScreen ()
  222. {
  223. Rectangle screen = Frame;
  224. View? current = SuperView;
  225. while (current is { })
  226. {
  227. if (current is Adornment adornment)
  228. {
  229. // Adornments don't have SuperViews; use Adornment.FrameToScreen override
  230. // which will give us the screen coordinates of the parent
  231. Rectangle parentScreen = adornment.FrameToScreen ();
  232. // Now add our Frame location
  233. parentScreen.Offset (screen.X, screen.Y);
  234. return parentScreen;
  235. }
  236. Point viewportOffset = current.GetViewportOffsetFromFrame ();
  237. viewportOffset.Offset (current.Frame.X - current.Viewport.X, current.Frame.Y - current.Viewport.Y);
  238. screen.X += viewportOffset.X;
  239. screen.Y += viewportOffset.Y;
  240. current = current.SuperView;
  241. }
  242. return screen;
  243. }
  244. /// <summary>
  245. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means relative to the
  246. /// View's <see cref="SuperView"/>'s <see cref="Viewport"/>.
  247. /// </summary>
  248. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Viewport"/>.</returns>
  249. /// <param name="location">Screen-relative coordinate.</param>
  250. public virtual Point ScreenToFrame (in Point location)
  251. {
  252. if (SuperView is null)
  253. {
  254. return new (location.X - Frame.X, location.Y - Frame.Y);
  255. }
  256. Point superViewViewportOffset = SuperView.GetViewportOffsetFromFrame ();
  257. superViewViewportOffset.Offset (-SuperView.Viewport.X, -SuperView.Viewport.Y);
  258. Point frame = location;
  259. frame.Offset (-superViewViewportOffset.X, -superViewViewportOffset.Y);
  260. frame = SuperView.ScreenToFrame (frame);
  261. frame.Offset (-Frame.X, -Frame.Y);
  262. return frame;
  263. }
  264. private Pos _x = Pos.Absolute (0);
  265. /// <summary>Gets or sets the X position for the view (the column).</summary>
  266. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  267. /// <remarks>
  268. /// <para>
  269. /// See the View Layout Deep Dive for more information:
  270. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  271. /// </para>
  272. /// <para>
  273. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  274. /// <see cref="GetContentSize ()"/>.
  275. /// </para>
  276. /// <para>
  277. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  278. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  279. /// called.
  280. /// </para>
  281. /// <para>
  282. /// Changing this property will eventually (when the view is next drawn) cause the
  283. /// <see cref="Layout"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  284. /// </para>
  285. /// <para>
  286. /// Changing this property will cause <see cref="Frame"/> to be updated.
  287. /// </para>
  288. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  289. /// </remarks>
  290. public Pos X
  291. {
  292. get => VerifyIsInitialized (_x, nameof (X));
  293. set
  294. {
  295. if (Equals (_x, value))
  296. {
  297. return;
  298. }
  299. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  300. SetLayoutNeeded ();
  301. }
  302. }
  303. private Pos _y = Pos.Absolute (0);
  304. /// <summary>Gets or sets the Y position for the view (the row).</summary>
  305. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  306. /// <remarks>
  307. /// <para>
  308. /// See the View Layout Deep Dive for more information:
  309. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  310. /// </para>
  311. /// <para>
  312. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  313. /// <see cref="GetContentSize ()"/>.
  314. /// </para>
  315. /// <para>
  316. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  317. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  318. /// called.
  319. /// </para>
  320. /// <para>
  321. /// Changing this property will eventually (when the view is next drawn) cause the
  322. /// <see cref="Layout"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  323. /// </para>
  324. /// <para>
  325. /// Changing this property will cause <see cref="Frame"/> to be updated.
  326. /// </para>
  327. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  328. /// </remarks>
  329. public Pos Y
  330. {
  331. get => VerifyIsInitialized (_y, nameof (Y));
  332. set
  333. {
  334. if (Equals (_y, value))
  335. {
  336. return;
  337. }
  338. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  339. SetLayoutNeeded ();
  340. }
  341. }
  342. private Dim? _height = Dim.Absolute (0);
  343. /// <summary>Gets or sets the height dimension of the view.</summary>
  344. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  345. /// <remarks>
  346. /// <para>
  347. /// See the View Layout Deep Dive for more information:
  348. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  349. /// </para>
  350. /// <para>
  351. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  352. /// <see cref="GetContentSize ()"/>
  353. /// .
  354. /// </para>
  355. /// <para>
  356. /// If set to a relative value (e.g. <see cref="Dim.Fill(Dim)"/>) the value is indeterminate until the view has
  357. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  358. /// called.
  359. /// </para>
  360. /// <para>
  361. /// Changing this property will eventually (when the view is next drawn) cause the
  362. /// <see cref="Layout"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  363. /// </para>
  364. /// <para>
  365. /// Changing this property will cause <see cref="Frame"/> to be updated.
  366. /// </para>
  367. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  368. /// </remarks>
  369. public Dim? Height
  370. {
  371. get => VerifyIsInitialized (_height, nameof (Height));
  372. set
  373. {
  374. if (Equals (_height, value))
  375. {
  376. return;
  377. }
  378. if (_height is { } && _height.Has<DimAuto> (out _))
  379. {
  380. // Reset ContentSize to Viewport
  381. _contentSize = null;
  382. }
  383. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  384. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  385. TextFormatter.ConstrainToHeight = null;
  386. SetLayoutNeeded ();
  387. }
  388. }
  389. private Dim? _width = Dim.Absolute (0);
  390. /// <summary>Gets or sets the width dimension of the view.</summary>
  391. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  392. /// <remarks>
  393. /// <para>
  394. /// See the View Layout Deep Dive for more information:
  395. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  396. /// </para>
  397. /// <para>
  398. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  399. /// <see cref="GetContentSize ()"/>
  400. /// .
  401. /// </para>
  402. /// <para>
  403. /// If set to a relative value (e.g. <see cref="Dim.Fill(Dim)"/>) the value is indeterminate until the view has
  404. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  405. /// called.
  406. /// </para>
  407. /// <para>
  408. /// Changing this property will eventually (when the view is next drawn) cause the
  409. /// <see cref="Layout"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  410. /// </para>
  411. /// <para>
  412. /// Changing this property will cause <see cref="Frame"/> to be updated.
  413. /// </para>
  414. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  415. /// </remarks>
  416. public Dim? Width
  417. {
  418. get => VerifyIsInitialized (_width, nameof (Width));
  419. set
  420. {
  421. if (Equals (_width, value))
  422. {
  423. return;
  424. }
  425. if (_width is { } && _width.Has<DimAuto> (out _))
  426. {
  427. // Reset ContentSize to Viewport
  428. _contentSize = null;
  429. }
  430. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  431. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  432. TextFormatter.ConstrainToWidth = null;
  433. SetLayoutNeeded ();
  434. }
  435. }
  436. #endregion Frame
  437. #region Layout Engine
  438. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  439. /// <remarks>
  440. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  441. /// otherwise changed.
  442. /// </remarks>
  443. public event EventHandler<LayoutEventArgs>? LayoutComplete;
  444. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  445. /// <remarks>
  446. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  447. /// otherwise changed.
  448. /// </remarks>
  449. public event EventHandler<LayoutEventArgs>? LayoutStarted;
  450. /// <summary>
  451. /// Adjusts <see cref="Frame"/> given the SuperView's ContentSize (nominally the same as
  452. /// <c>this.SuperView.GetContentSize ()</c>)
  453. /// and the position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  454. /// <see cref="Height"/>).
  455. /// </summary>
  456. /// <remarks>
  457. /// <para>
  458. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  459. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  460. /// are left unchanged.
  461. /// </para>
  462. /// <para>
  463. /// If any of the view's subviews have a position or dimension dependent on either <see cref="GetContentSize"/> or
  464. /// other subviews, <see cref="Layout"/> on
  465. /// will be called for that subview.
  466. /// </para>
  467. /// <para>
  468. /// Some subviews may have SetRelativeLayout called on them as a side effect, particularly in DimAuto scenarios.
  469. /// </para>
  470. /// </remarks>
  471. /// <param name="superviewContentSize">
  472. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.GetContentSize ()</c>).
  473. /// </param>
  474. /// <returns><see langword="true"/> if successful. <see langword="false"/> means a dependent View still needs layout.</returns>
  475. public bool SetRelativeLayout (Size superviewContentSize)
  476. {
  477. Debug.Assert (_x is { });
  478. Debug.Assert (_y is { });
  479. Debug.Assert (_width is { });
  480. Debug.Assert (_height is { });
  481. CheckDimAuto ();
  482. SetTextFormatterSize ();
  483. int newX, newW, newY, newH;
  484. try
  485. {
  486. // Calculate the new X, Y, Width, and Height
  487. // If the Width or Height is Dim.Auto, calculate the Width or Height first. Otherwise, calculate the X or Y first.
  488. if (_width.Has<DimAuto> (out _))
  489. {
  490. newW = _width.Calculate (0, superviewContentSize.Width, this, Dimension.Width);
  491. newX = _x.Calculate (superviewContentSize.Width, newW, this, Dimension.Width);
  492. if (newW != Frame.Width)
  493. {
  494. // Pos.Calculate gave us a new position. We need to redo dimension
  495. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  496. }
  497. }
  498. else
  499. {
  500. newX = _x.Calculate (superviewContentSize.Width, _width, this, Dimension.Width);
  501. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  502. }
  503. if (_height.Has<DimAuto> (out _))
  504. {
  505. newH = _height.Calculate (0, superviewContentSize.Height, this, Dimension.Height);
  506. newY = _y.Calculate (superviewContentSize.Height, newH, this, Dimension.Height);
  507. if (newH != Frame.Height)
  508. {
  509. // Pos.Calculate gave us a new position. We need to redo dimension
  510. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  511. }
  512. }
  513. else
  514. {
  515. newY = _y.Calculate (superviewContentSize.Height, _height, this, Dimension.Height);
  516. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  517. }
  518. }
  519. catch (Exception e)
  520. {
  521. // A Dim/PosFunc threw indicating it could not calculate (typically because a dependent View was not laid out).
  522. return false;
  523. }
  524. Rectangle newFrame = new (newX, newY, newW, newH);
  525. if (Frame != newFrame)
  526. {
  527. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height
  528. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  529. SetFrame (newFrame);
  530. if (_x is PosAbsolute)
  531. {
  532. _x = Frame.X;
  533. }
  534. if (_y is PosAbsolute)
  535. {
  536. _y = Frame.Y;
  537. }
  538. if (_width is DimAbsolute)
  539. {
  540. _width = Frame.Width;
  541. }
  542. if (_height is DimAbsolute)
  543. {
  544. _height = Frame.Height;
  545. }
  546. if (!string.IsNullOrEmpty (Title))
  547. {
  548. SetTitleTextFormatterSize ();
  549. }
  550. SuperView?.SetNeedsDisplay ();
  551. }
  552. if (TextFormatter.ConstrainToWidth is null)
  553. {
  554. TextFormatter.ConstrainToWidth = GetContentSize ().Width;
  555. }
  556. if (TextFormatter.ConstrainToHeight is null)
  557. {
  558. TextFormatter.ConstrainToHeight = GetContentSize ().Height;
  559. }
  560. return true;
  561. }
  562. /// <summary>
  563. /// INTERNAL API - Causes the view's subviews and adornments to be laid out within the view's content areas. Assumes the view's relative layout has been set via <see cref="SetRelativeLayout"/>.
  564. /// </summary>
  565. /// <remarks>
  566. /// <para>
  567. /// See the View Layout Deep Dive for more information:
  568. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  569. /// </para>
  570. /// <para>
  571. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  572. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  573. /// </para>
  574. /// <para>Raises the <see cref="LayoutComplete"/> event before it returns.</para>
  575. /// </remarks>
  576. internal void LayoutSubviews ()
  577. {
  578. if (!IsInitialized)
  579. {
  580. Debug.WriteLine ($"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}");
  581. }
  582. if (!IsLayoutNeeded ())
  583. {
  584. return;
  585. }
  586. CheckDimAuto ();
  587. Size contentSize = GetContentSize ();
  588. OnLayoutStarted (new (contentSize));
  589. // The Adornments already have their Frame's set by SetRelativeLayout so we call LayoutSubViews vs. Layout here.
  590. Margin?.LayoutSubviews ();
  591. Border?.LayoutSubviews ();
  592. Padding?.LayoutSubviews ();
  593. // Sort out the dependencies of the X, Y, Width, Height properties
  594. HashSet<View> nodes = new ();
  595. HashSet<(View, View)> edges = new ();
  596. CollectAll (this, ref nodes, ref edges);
  597. List<View> ordered = TopologicalSort (SuperView!, nodes, edges);
  598. List<View> redo = new ();
  599. foreach (View v in ordered)
  600. {
  601. if (!v.Layout (contentSize))
  602. {
  603. redo.Add (v);
  604. }
  605. }
  606. bool layoutStillNeeded = false;
  607. foreach (View v in redo)
  608. {
  609. if (!v.Layout (contentSize))
  610. {
  611. layoutStillNeeded = true;
  612. }
  613. }
  614. // If the 'to' is rooted to 'from' it's a special-case.
  615. // Use LayoutSubview with the Frame of the 'from'.
  616. if (SuperView is { } && GetTopSuperView () is { } && IsLayoutNeeded () && edges.Count > 0)
  617. {
  618. foreach ((View from, View to) in edges)
  619. {
  620. Debug.Fail ("This is dead code?");
  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. if (this is Adornment adornment)
  711. {
  712. adornment.Parent?.SetLayoutNeeded ();
  713. }
  714. SuperView?.SetLayoutNeeded ();
  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. }