View.Layout.cs 40 KB

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