View.Layout.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. #nullable enable
  2. using System.Diagnostics;
  3. using Microsoft.CodeAnalysis;
  4. namespace Terminal.Gui;
  5. public partial class View // Layout APIs
  6. {
  7. #region Frame/Position/Dimension
  8. /// <summary>
  9. /// Indicates whether the specified SuperView-relative coordinates are within the View's <see cref="Frame"/>.
  10. /// </summary>
  11. /// <param name="location">SuperView-relative coordinate</param>
  12. /// <returns><see langword="true"/> if the specified SuperView-relative coordinates are within the View.</returns>
  13. public virtual bool Contains (in Point location) { return Frame.Contains (location); }
  14. private Rectangle? _frame;
  15. /// <summary>Gets or sets the absolute location and dimension of the view.</summary>
  16. /// <value>
  17. /// The rectangle describing absolute location and dimension of the view, in coordinates relative to the
  18. /// <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>.
  19. /// </value>
  20. /// <remarks>
  21. /// <para>
  22. /// See the View Layout Deep Dive for more information:
  23. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  24. /// </para>
  25. /// <para>
  26. /// Frame is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>
  27. /// .
  28. /// </para>
  29. /// <para>
  30. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> to absoulte values.
  31. /// </para>
  32. /// <para>
  33. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  34. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  35. /// </para>
  36. /// </remarks>
  37. public Rectangle Frame
  38. {
  39. get
  40. {
  41. if (_needsLayout)
  42. {
  43. //Debug.WriteLine("Frame_get with _layoutNeeded");
  44. }
  45. return _frame ?? Rectangle.Empty;
  46. }
  47. set
  48. {
  49. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  50. if (SetFrame (value with { Width = Math.Max (value.Width, 0), Height = Math.Max (value.Height, 0) }))
  51. {
  52. // If Frame gets set, set all Pos/Dim to Absolute values.
  53. _x = _frame!.Value.X;
  54. _y = _frame!.Value.Y;
  55. _width = _frame!.Value.Width;
  56. _height = _frame!.Value.Height;
  57. // Implicit layout is ok here because we are setting the Frame directly.
  58. Layout ();
  59. }
  60. }
  61. }
  62. /// <summary>
  63. /// INTERNAL API - Sets _frame, calls SetsNeedsLayout, and raises OnViewportChanged/ViewportChanged
  64. /// </summary>
  65. /// <param name="frame"></param>
  66. /// <returns><see langword="true"/> if the frame was changed.</returns>
  67. private bool SetFrame (in Rectangle frame)
  68. {
  69. if (_frame == frame)
  70. {
  71. return false;
  72. }
  73. var oldViewport = Rectangle.Empty;
  74. if (IsInitialized)
  75. {
  76. oldViewport = Viewport;
  77. }
  78. // This is the only place where _frame should be set directly. Use Frame = or SetFrame instead.
  79. _frame = frame;
  80. SetAdornmentFrames ();
  81. SetNeedsDisplay ();
  82. SetNeedsLayout ();
  83. // BUGBUG: When SetFrame is called from Frame_set, this event gets raised BEFORE OnResizeNeeded. Is that OK?
  84. OnViewportChanged (new (IsInitialized ? Viewport : Rectangle.Empty, oldViewport));
  85. return true;
  86. }
  87. /// <summary>Gets the <see cref="Frame"/> with a screen-relative location.</summary>
  88. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  89. public virtual Rectangle FrameToScreen ()
  90. {
  91. Rectangle screen = Frame;
  92. View? current = SuperView;
  93. while (current is { })
  94. {
  95. if (current is Adornment adornment)
  96. {
  97. // Adornments don't have SuperViews; use Adornment.FrameToScreen override
  98. // which will give us the screen coordinates of the parent
  99. Rectangle parentScreen = adornment.FrameToScreen ();
  100. // Now add our Frame location
  101. parentScreen.Offset (screen.X, screen.Y);
  102. return parentScreen;
  103. }
  104. Point viewportOffset = current.GetViewportOffsetFromFrame ();
  105. viewportOffset.Offset (current.Frame.X - current.Viewport.X, current.Frame.Y - current.Viewport.Y);
  106. screen.X += viewportOffset.X;
  107. screen.Y += viewportOffset.Y;
  108. current = current.SuperView;
  109. }
  110. return screen;
  111. }
  112. /// <summary>
  113. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means relative to the
  114. /// View's <see cref="SuperView"/>'s <see cref="Viewport"/>.
  115. /// </summary>
  116. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Viewport"/>.</returns>
  117. /// <param name="location">Screen-relative coordinate.</param>
  118. public virtual Point ScreenToFrame (in Point location)
  119. {
  120. if (SuperView is null)
  121. {
  122. return new (location.X - Frame.X, location.Y - Frame.Y);
  123. }
  124. Point superViewViewportOffset = SuperView.GetViewportOffsetFromFrame ();
  125. superViewViewportOffset.Offset (-SuperView.Viewport.X, -SuperView.Viewport.Y);
  126. Point frame = location;
  127. frame.Offset (-superViewViewportOffset.X, -superViewViewportOffset.Y);
  128. frame = SuperView.ScreenToFrame (frame);
  129. frame.Offset (-Frame.X, -Frame.Y);
  130. return frame;
  131. }
  132. // helper for X, Y, Width, Height setters to ensure consistency
  133. private void PosDimSet ()
  134. {
  135. SetNeedsLayout ();
  136. if (_x is PosAbsolute && _y is PosAbsolute && _width is DimAbsolute && _height is DimAbsolute)
  137. {
  138. // Implicit layout is ok here because all Pos/Dim are Absolute values.
  139. Layout ();
  140. }
  141. }
  142. private Pos _x = Pos.Absolute (0);
  143. /// <summary>Gets or sets the X position for the view (the column).</summary>
  144. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  145. /// <remarks>
  146. /// <para>
  147. /// See the View Layout Deep Dive for more information:
  148. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  149. /// </para>
  150. /// <para>
  151. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  152. /// <see cref="GetContentSize ()"/>.
  153. /// </para>
  154. /// <para>
  155. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  156. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  157. /// </para>
  158. /// <para>
  159. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  160. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  161. /// </para>
  162. /// <para>
  163. /// Changing this property will cause <see cref="Frame"/> to be updated.
  164. /// </para>
  165. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  166. /// </remarks>
  167. public Pos X
  168. {
  169. get => VerifyIsInitialized (_x, nameof (X));
  170. set
  171. {
  172. if (Equals (_x, value))
  173. {
  174. return;
  175. }
  176. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  177. PosDimSet ();
  178. }
  179. }
  180. private Pos _y = Pos.Absolute (0);
  181. /// <summary>Gets or sets the Y position for the view (the row).</summary>
  182. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  183. /// <remarks>
  184. /// <para>
  185. /// See the View Layout Deep Dive for more information:
  186. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  187. /// </para>
  188. /// <para>
  189. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  190. /// <see cref="GetContentSize ()"/>.
  191. /// </para>
  192. /// <para>
  193. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  194. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  195. /// </para>
  196. /// <para>
  197. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  198. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  199. /// </para>
  200. /// <para>
  201. /// Changing this property will cause <see cref="Frame"/> to be updated.
  202. /// </para>
  203. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  204. /// </remarks>
  205. public Pos Y
  206. {
  207. get => VerifyIsInitialized (_y, nameof (Y));
  208. set
  209. {
  210. if (Equals (_y, value))
  211. {
  212. return;
  213. }
  214. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  215. PosDimSet ();
  216. }
  217. }
  218. private Dim? _height = Dim.Absolute (0);
  219. /// <summary>Gets or sets the height dimension of the view.</summary>
  220. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  221. /// <remarks>
  222. /// <para>
  223. /// See the View Layout Deep Dive for more information:
  224. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  225. /// </para>
  226. /// <para>
  227. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  228. /// <see cref="GetContentSize ()"/> .
  229. /// </para>
  230. /// <para>
  231. /// If set to a relative value (e.g. <see cref="DimFill"/>) the value is indeterminate until the view has been
  232. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  233. /// </para>
  234. /// <para>
  235. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  236. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  237. /// </para>
  238. /// <para>
  239. /// Changing this property will cause <see cref="Frame"/> to be updated.
  240. /// </para>
  241. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  242. /// </remarks>
  243. public Dim? Height
  244. {
  245. get => VerifyIsInitialized (_height, nameof (Height));
  246. set
  247. {
  248. if (Equals (_height, value))
  249. {
  250. return;
  251. }
  252. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  253. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  254. TextFormatter.ConstrainToHeight = null;
  255. PosDimSet ();
  256. }
  257. }
  258. private Dim? _width = Dim.Absolute (0);
  259. /// <summary>Gets or sets the width dimension of the view.</summary>
  260. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  261. /// <remarks>
  262. /// <para>
  263. /// See the View Layout Deep Dive for more information:
  264. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  265. /// </para>
  266. /// <para>
  267. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  268. /// <see cref="GetContentSize ()"/>
  269. /// .
  270. /// </para>
  271. /// <para>
  272. /// If set to a relative value (e.g. <see cref="DimFill"/>) the value is indeterminate until the view has been
  273. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  274. /// </para>
  275. /// <para>
  276. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDisplay"/> to be set, resulting in the
  277. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  278. /// </para>
  279. /// <para>
  280. /// Changing this property will cause <see cref="Frame"/> to be updated.
  281. /// </para>
  282. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  283. /// </remarks>
  284. public Dim? Width
  285. {
  286. get => VerifyIsInitialized (_width, nameof (Width));
  287. set
  288. {
  289. if (Equals (_width, value))
  290. {
  291. return;
  292. }
  293. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  294. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  295. TextFormatter.ConstrainToWidth = null;
  296. PosDimSet ();
  297. }
  298. }
  299. #endregion Frame/Position/Dimension
  300. #region Core Layout API
  301. /// <summary>
  302. /// Performs layout of the view and its subviews within the specified content size.
  303. /// </summary>
  304. /// <remarks>
  305. /// <para>
  306. /// See the View Layout Deep Dive for more information:
  307. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  308. /// </para>
  309. /// <para>
  310. /// This method is intended to be called by the layout engine to
  311. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  312. /// </para>
  313. /// </remarks>
  314. /// <param name="contentSize"></param>
  315. /// <returns><see langword="false"/>If the view could not be laid out (typically because a dependencies was not ready). </returns>
  316. public bool Layout (Size contentSize)
  317. {
  318. if (SetRelativeLayout (contentSize))
  319. {
  320. LayoutSubviews ();
  321. // Debug.Assert(!NeedsLayout);
  322. return true;
  323. }
  324. return false;
  325. }
  326. /// <summary>
  327. /// Performs layout of the view and its subviews using the content size of either the <see cref="SuperView"/> or <see cref="Application.Screen"/>.
  328. /// </summary>
  329. /// <remarks>
  330. /// <para>
  331. /// See the View Layout Deep Dive for more information:
  332. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  333. /// </para>
  334. /// <para>
  335. /// This method is intended to be called by the layout engine to
  336. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  337. /// </para>
  338. /// </remarks>
  339. /// <returns><see langword="false"/>If the view could not be laid out (typically because dependency was not ready). </returns>
  340. public bool Layout ()
  341. {
  342. return Layout (GetContainerSize ());
  343. }
  344. /// <summary>
  345. /// Sets the position and size of this view, relative to the SuperView's ContentSize (nominally the same as
  346. /// <c>this.SuperView.GetContentSize ()</c>) based on the values of <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>,
  347. /// and <see cref="Height"/>.
  348. /// </summary>
  349. /// <remarks>
  350. /// <para>
  351. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  352. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  353. /// are left unchanged.
  354. /// </para>
  355. /// <para>
  356. /// This method does not arrange subviews or adornments. It is intended to be called by the layout engine to
  357. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  358. /// </para>
  359. /// <para>
  360. /// Some subviews may have SetRelativeLayout called on them as a side effect, particularly in DimAuto scenarios.
  361. /// </para>
  362. /// </remarks>
  363. /// <param name="superviewContentSize">
  364. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.GetContentSize ()</c>).
  365. /// </param>
  366. /// <returns><see langword="true"/> if successful. <see langword="false"/> means a dependent View still needs layout.</returns>
  367. public bool SetRelativeLayout (Size superviewContentSize)
  368. {
  369. Debug.Assert (_x is { });
  370. Debug.Assert (_y is { });
  371. Debug.Assert (_width is { });
  372. Debug.Assert (_height is { });
  373. CheckDimAuto ();
  374. // TODO: Should move to View.LayoutSubviews?
  375. SetTextFormatterSize ();
  376. int newX, newW, newY, newH;
  377. try
  378. {
  379. // Calculate the new X, Y, Width, and Height
  380. // If the Width or Height is Dim.Auto, calculate the Width or Height first. Otherwise, calculate the X or Y first.
  381. if (_width.Has<DimAuto> (out _))
  382. {
  383. newW = _width.Calculate (0, superviewContentSize.Width, this, Dimension.Width);
  384. newX = _x.Calculate (superviewContentSize.Width, newW, this, Dimension.Width);
  385. if (newW != Frame.Width)
  386. {
  387. // Pos.Calculate gave us a new position. We need to redo dimension
  388. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  389. }
  390. }
  391. else
  392. {
  393. newX = _x.Calculate (superviewContentSize.Width, _width, this, Dimension.Width);
  394. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  395. }
  396. if (_height.Has<DimAuto> (out _))
  397. {
  398. newH = _height.Calculate (0, superviewContentSize.Height, this, Dimension.Height);
  399. newY = _y.Calculate (superviewContentSize.Height, newH, this, Dimension.Height);
  400. if (newH != Frame.Height)
  401. {
  402. // Pos.Calculate gave us a new position. We need to redo dimension
  403. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  404. }
  405. }
  406. else
  407. {
  408. newY = _y.Calculate (superviewContentSize.Height, _height, this, Dimension.Height);
  409. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  410. }
  411. }
  412. catch (LayoutException le)
  413. {
  414. //Debug.WriteLine ($"A Dim/PosFunc function threw (typically this is because a dependent View was not laid out)\n{le}.");
  415. return false;
  416. }
  417. Rectangle newFrame = new (newX, newY, newW, newH);
  418. if (Frame != newFrame)
  419. {
  420. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height
  421. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  422. SetFrame (newFrame);
  423. if (_x is PosAbsolute)
  424. {
  425. _x = Frame.X;
  426. }
  427. if (_y is PosAbsolute)
  428. {
  429. _y = Frame.Y;
  430. }
  431. if (_width is DimAbsolute)
  432. {
  433. _width = Frame.Width;
  434. }
  435. if (_height is DimAbsolute)
  436. {
  437. _height = Frame.Height;
  438. }
  439. if (!string.IsNullOrEmpty (Title))
  440. {
  441. SetTitleTextFormatterSize ();
  442. }
  443. SuperView?.SetNeedsDisplay ();
  444. }
  445. if (TextFormatter.ConstrainToWidth is null)
  446. {
  447. TextFormatter.ConstrainToWidth = GetContentSize ().Width;
  448. }
  449. if (TextFormatter.ConstrainToHeight is null)
  450. {
  451. TextFormatter.ConstrainToHeight = GetContentSize ().Height;
  452. }
  453. return true;
  454. }
  455. /// <summary>
  456. /// 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"/>.
  457. /// </summary>
  458. /// <remarks>
  459. /// <para>
  460. /// See the View Layout Deep Dive for more information:
  461. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/layout.html"/>
  462. /// </para>
  463. /// <para>
  464. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  465. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  466. /// </para>
  467. /// <para>Raises the <see cref="SubviewsLaidOut"/> event before it returns.</para>
  468. /// </remarks>
  469. internal void LayoutSubviews ()
  470. {
  471. if (!NeedsLayout)
  472. {
  473. return;
  474. }
  475. CheckDimAuto ();
  476. Size contentSize = GetContentSize ();
  477. OnSubviewLayout (new (contentSize));
  478. SubviewLayout?.Invoke(this, new (contentSize));
  479. // The Adornments already have their Frame's set by SetRelativeLayout so we call LayoutSubViews vs. Layout here.
  480. if (Margin is { Subviews.Count: > 0 })
  481. {
  482. Margin.LayoutSubviews ();
  483. }
  484. if (Border is { Subviews.Count: > 0 })
  485. {
  486. Border.LayoutSubviews ();
  487. }
  488. if (Padding is { Subviews.Count: > 0 })
  489. {
  490. Padding.LayoutSubviews ();
  491. }
  492. // Sort out the dependencies of the X, Y, Width, Height properties
  493. HashSet<View> nodes = new ();
  494. HashSet<(View, View)> edges = new ();
  495. CollectAll (this, ref nodes, ref edges);
  496. List<View> ordered = TopologicalSort (SuperView!, nodes, edges);
  497. List<View> redo = new ();
  498. foreach (View v in ordered)
  499. {
  500. if (!v.Layout (contentSize))
  501. {
  502. redo.Add (v);
  503. }
  504. }
  505. bool layoutStillNeeded = false;
  506. if (redo.Count > 0)
  507. {
  508. foreach (View v in ordered)
  509. {
  510. if (!v.Layout (contentSize))
  511. {
  512. layoutStillNeeded = true;
  513. }
  514. }
  515. }
  516. // If the 'to' is rooted to 'from' it's a special-case.
  517. // Use Layout with the ContentSize of the 'from'.
  518. // See the Nested_SubViews_Ref_Topmost_SuperView unit test
  519. if (edges.Count > 0 && GetTopSuperView () is { })
  520. {
  521. foreach ((View from, View to) in edges)
  522. {
  523. // QUESTION: Do we test this with adornments well enough?
  524. to.Layout (from.GetContentSize ());
  525. }
  526. }
  527. _needsLayout = layoutStillNeeded;
  528. OnSubviewsLaidOut (new (contentSize));
  529. SubviewsLaidOut?.Invoke (this, new (contentSize));
  530. }
  531. /// <summary>
  532. /// Called from <see cref="LayoutSubviews"/> before any subviews
  533. /// have been laid out.
  534. /// </summary>
  535. /// <remarks>
  536. /// Override to perform tasks when the layout is changing.
  537. /// </remarks>
  538. protected virtual void OnSubviewLayout (LayoutEventArgs args) { }
  539. /// <summary>Raised by <see cref="LayoutSubviews"/> before any subviews
  540. /// have been laid out.</summary>
  541. /// <remarks>
  542. /// Subscribe to this event to perform tasks when the layout is changing.
  543. /// </remarks>
  544. public event EventHandler<LayoutEventArgs>? SubviewLayout;
  545. /// <summary>
  546. /// Called from <see cref="LayoutSubviews"/> after all sub-views
  547. /// have been laid out.
  548. /// </summary>
  549. /// <remarks>
  550. /// Override to perform tasks after the <see cref="View"/> has been resized or the layout has
  551. /// otherwise changed.
  552. /// </remarks>
  553. protected virtual void OnSubviewsLaidOut (LayoutEventArgs args) { }
  554. /// <summary>Raised after all sub-views have been laid out.</summary>
  555. /// <remarks>
  556. /// Subscribe to this event to perform tasks after the <see cref="View"/> has been resized or the layout has
  557. /// otherwise changed.
  558. /// </remarks>
  559. public event EventHandler<LayoutEventArgs>? SubviewsLaidOut;
  560. #endregion Core Layout API
  561. #region NeedsLayout
  562. // We expose no setter for this to ensure that the ONLY place it's changed is in SetNeedsLayout
  563. private bool _needsLayout = true;
  564. /// <summary>
  565. /// Indicates the View's Frame or the layout of the View's subviews (including Adornments) have
  566. /// changed since the last time the View was laid out.
  567. /// </summary>
  568. /// <remarks>
  569. /// <para>Used to prevent <see cref="Layout()"/> from needlessly computing
  570. /// layout.
  571. /// </para>
  572. /// </remarks>
  573. /// <value>
  574. /// <see langword="true"/> if layout is needed.
  575. /// </value>
  576. public bool NeedsLayout => _needsLayout;
  577. /// <summary>
  578. /// Sets <see cref="NeedsLayout"/> to return <see langword="true"/>, indicating this View and all of it's subviews (including adornments) need to be laid out in the next Application iteration.
  579. /// </summary>
  580. /// <remarks>
  581. /// <para>
  582. /// 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()"/>.
  583. /// </para>
  584. /// </remarks>
  585. public void SetNeedsLayout ()
  586. {
  587. _needsLayout = true;
  588. if (Margin is { Subviews.Count: > 0 })
  589. {
  590. Margin.SetNeedsLayout ();
  591. }
  592. if (Border is { Subviews.Count: > 0 })
  593. {
  594. Border.SetNeedsLayout ();
  595. }
  596. if (Padding is { Subviews.Count: > 0 })
  597. {
  598. Padding.SetNeedsLayout ();
  599. }
  600. // Use a stack to avoid recursion
  601. Stack<View> stack = new Stack<View> (Subviews);
  602. while (stack.Count > 0)
  603. {
  604. View current = stack.Pop ();
  605. if (!current.NeedsLayout)
  606. {
  607. current._needsLayout = true;
  608. if (current.Margin is { Subviews.Count: > 0 })
  609. {
  610. current.Margin.SetNeedsLayout ();
  611. }
  612. if (current.Border is { Subviews.Count: > 0 })
  613. {
  614. current.Border.SetNeedsLayout ();
  615. }
  616. if (current.Padding is { Subviews.Count: > 0 })
  617. {
  618. current.Padding.SetNeedsLayout ();
  619. }
  620. foreach (View subview in current.Subviews)
  621. {
  622. stack.Push (subview);
  623. }
  624. }
  625. }
  626. TextFormatter.NeedsFormat = true;
  627. if (SuperView is { NeedsLayout: false })
  628. {
  629. SuperView?.SetNeedsLayout ();
  630. }
  631. if (this is not Adornment adornment)
  632. {
  633. return;
  634. }
  635. if (adornment.Parent is { NeedsLayout: false })
  636. {
  637. adornment.Parent?.SetNeedsLayout ();
  638. }
  639. }
  640. #endregion NeedsLayout
  641. #region Topological Sort
  642. /// <summary>
  643. /// INTERNAL API - Collects all views and their dependencies from a given starting view for layout purposes. Used by
  644. /// <see cref="TopologicalSort"/> to create an ordered list of views to layout.
  645. /// </summary>
  646. /// <param name="from">The starting view from which to collect dependencies.</param>
  647. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  648. /// <param name="nEdges">
  649. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  650. /// indicating a dependency.
  651. /// </param>
  652. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  653. {
  654. foreach (View? v in from.InternalSubviews)
  655. {
  656. nNodes.Add (v);
  657. CollectPos (v.X, v, ref nNodes, ref nEdges);
  658. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  659. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  660. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  661. }
  662. }
  663. /// <summary>
  664. /// INTERNAL API - Collects dimension (where Width or Height is `DimView`) dependencies for a given view.
  665. /// </summary>
  666. /// <param name="dim">The dimension (width or height) to collect dependencies for.</param>
  667. /// <param name="from">The view for which to collect dimension dependencies.</param>
  668. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  669. /// <param name="nEdges">
  670. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  671. /// indicating a dependency.
  672. /// </param>
  673. internal void CollectDim (Dim? dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  674. {
  675. if (dim!.Has<DimView> (out DimView dv))
  676. {
  677. if (dv.Target != this)
  678. {
  679. nEdges.Add ((dv.Target!, from));
  680. }
  681. }
  682. if (dim!.Has<DimCombine> (out DimCombine dc))
  683. {
  684. CollectDim (dc.Left, from, ref nNodes, ref nEdges);
  685. CollectDim (dc.Right, from, ref nNodes, ref nEdges);
  686. }
  687. }
  688. /// <summary>
  689. /// INTERNAL API - Collects position (where X or Y is `PosView`) dependencies for a given view.
  690. /// </summary>
  691. /// <param name="pos">The position (X or Y) to collect dependencies for.</param>
  692. /// <param name="from">The view for which to collect position dependencies.</param>
  693. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  694. /// <param name="nEdges">
  695. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  696. /// indicating a dependency.
  697. /// </param>
  698. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  699. {
  700. // TODO: Use Pos.Has<T> instead.
  701. switch (pos)
  702. {
  703. case PosView pv:
  704. Debug.Assert (pv.Target is { });
  705. if (pv.Target != this)
  706. {
  707. nEdges.Add ((pv.Target!, from));
  708. }
  709. return;
  710. case PosCombine pc:
  711. CollectPos (pc.Left, from, ref nNodes, ref nEdges);
  712. CollectPos (pc.Right, from, ref nNodes, ref nEdges);
  713. break;
  714. }
  715. }
  716. // https://en.wikipedia.org/wiki/Topological_sorting
  717. internal static List<View> TopologicalSort (
  718. View superView,
  719. IEnumerable<View> nodes,
  720. ICollection<(View From, View To)> edges
  721. )
  722. {
  723. List<View> result = new ();
  724. // Set of all nodes with no incoming edges
  725. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  726. while (noEdgeNodes.Any ())
  727. {
  728. // remove a node n from S
  729. View n = noEdgeNodes.First ();
  730. noEdgeNodes.Remove (n);
  731. // add n to tail of L
  732. if (n != superView)
  733. {
  734. result.Add (n);
  735. }
  736. // for each node m with an edge e from n to m do
  737. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  738. {
  739. View m = e.To;
  740. // remove edge e from the graph
  741. edges.Remove (e);
  742. // if m has no other incoming edges then
  743. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  744. {
  745. // insert m into S
  746. noEdgeNodes.Add (m);
  747. }
  748. }
  749. }
  750. if (!edges.Any ())
  751. {
  752. return result;
  753. }
  754. foreach ((View from, View to) in edges)
  755. {
  756. if (from == to)
  757. {
  758. // if not yet added to the result, add it and remove from edge
  759. if (result.Find (v => v == from) is null)
  760. {
  761. result.Add (from);
  762. }
  763. edges.Remove ((from, to));
  764. }
  765. else if (from.SuperView == to.SuperView)
  766. {
  767. // if 'from' is not yet added to the result, add it
  768. if (result.Find (v => v == from) is null)
  769. {
  770. result.Add (from);
  771. }
  772. // if 'to' is not yet added to the result, add it
  773. if (result.Find (v => v == to) is null)
  774. {
  775. result.Add (to);
  776. }
  777. // remove from edge
  778. edges.Remove ((from, to));
  779. }
  780. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  781. {
  782. if (ReferenceEquals (from.SuperView, to))
  783. {
  784. throw new LayoutException (
  785. $"ComputedLayout for \"{superView}\": \"{to}\" "
  786. + $"references a SubView (\"{from}\")."
  787. );
  788. }
  789. throw new LayoutException (
  790. $"ComputedLayout for \"{superView}\": \"{from}\" "
  791. + $"linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  792. );
  793. }
  794. }
  795. // return L (a topologically sorted order)
  796. return result;
  797. } // TopologicalSort
  798. #endregion Topological Sort
  799. #region Utilities
  800. /// <summary>
  801. /// INTERNAL API - Gets the size of the SuperView's content (nominally the same as
  802. /// the SuperView's <see cref="GetContentSize ()"/>) or the screen size if there's no SuperView.
  803. /// </summary>
  804. /// <returns></returns>
  805. private Size GetContainerSize ()
  806. {
  807. // TODO: Get rid of refs to Top
  808. Size superViewContentSize = SuperView?.GetContentSize () ??
  809. (Application.Top is { } && Application.Top != this && Application.Top.IsInitialized
  810. ? Application.Top.GetContentSize ()
  811. : Application.Screen.Size);
  812. return superViewContentSize;
  813. }
  814. // BUGBUG: This method interferes with Dialog/MessageBox default min/max size.
  815. // TODO: Get rid of MenuBar coupling as part of https://github.com/gui-cs/Terminal.Gui/issues/2975
  816. /// <summary>
  817. /// Gets a new location of the <see cref="View"/> that is within the Viewport of the <paramref name="viewToMove"/>'s
  818. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  819. /// </summary>
  820. /// <remarks>
  821. /// If <paramref name="viewToMove"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  822. /// <see cref="Application.Top"/> the position will be bound by <see cref="Application.Screen"/>.
  823. /// </remarks>
  824. /// <param name="viewToMove">The View that is to be moved.</param>
  825. /// <param name="targetX">The target x location.</param>
  826. /// <param name="targetY">The target y location.</param>
  827. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  828. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  829. /// <returns>
  830. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  831. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  832. /// </returns>
  833. internal static View? GetLocationEnsuringFullVisibility (
  834. View viewToMove,
  835. int targetX,
  836. int targetY,
  837. out int nx,
  838. out int ny
  839. )
  840. {
  841. int maxDimension;
  842. View? superView;
  843. if (viewToMove is not Toplevel || viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  844. {
  845. maxDimension = Application.Screen.Width;
  846. superView = Application.Top;
  847. }
  848. else
  849. {
  850. // Use the SuperView's Viewport, not Frame
  851. maxDimension = viewToMove!.SuperView.Viewport.Width;
  852. superView = viewToMove.SuperView;
  853. }
  854. if (superView?.Margin is { } && superView == viewToMove!.SuperView)
  855. {
  856. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  857. }
  858. if (viewToMove!.Frame.Width <= maxDimension)
  859. {
  860. nx = Math.Max (targetX, 0);
  861. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  862. if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  863. {
  864. nx = Math.Max (viewToMove.Frame.Right, 0);
  865. }
  866. }
  867. else
  868. {
  869. nx = targetX;
  870. }
  871. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  872. var menuVisible = false;
  873. var statusVisible = false;
  874. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  875. {
  876. menuVisible = Application.Top?.MenuBar?.Visible == true;
  877. }
  878. else
  879. {
  880. View? t = viewToMove!.SuperView;
  881. while (t is { } and not Toplevel)
  882. {
  883. t = t.SuperView;
  884. }
  885. if (t is Toplevel topLevel)
  886. {
  887. menuVisible = topLevel.MenuBar?.Visible == true;
  888. }
  889. }
  890. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  891. {
  892. maxDimension = menuVisible ? 1 : 0;
  893. }
  894. else
  895. {
  896. maxDimension = 0;
  897. }
  898. ny = Math.Max (targetY, maxDimension);
  899. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  900. {
  901. maxDimension = statusVisible ? Application.Screen.Height - 1 : Application.Screen.Height;
  902. }
  903. else
  904. {
  905. maxDimension = statusVisible ? viewToMove!.SuperView.Viewport.Height - 1 : viewToMove!.SuperView.Viewport.Height;
  906. }
  907. if (superView?.Margin is { } && superView == viewToMove?.SuperView)
  908. {
  909. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  910. }
  911. ny = Math.Min (ny, maxDimension);
  912. if (viewToMove?.Frame.Height <= maxDimension)
  913. {
  914. ny = ny + viewToMove.Frame.Height > maxDimension
  915. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  916. : ny;
  917. if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  918. {
  919. ny = Math.Max (viewToMove.Frame.Bottom, 0);
  920. }
  921. }
  922. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  923. return superView!;
  924. }
  925. #endregion Utilities
  926. #region Diagnostics and Verification
  927. // Diagnostics to highlight when X or Y is read before the view has been initialized
  928. private Pos VerifyIsInitialized (Pos pos, string member)
  929. {
  930. //#if DEBUG
  931. // if (pos.ReferencesOtherViews () && !IsInitialized)
  932. // {
  933. // Debug.WriteLine (
  934. // $"WARNING: {member} = {pos} of {this} is dependent on other views and {member} "
  935. // + $"is being accessed before the View has been initialized. This is likely a bug."
  936. // );
  937. // }
  938. //#endif // DEBUG
  939. return pos;
  940. }
  941. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  942. private Dim? VerifyIsInitialized (Dim? dim, string member)
  943. {
  944. //#if DEBUG
  945. // if (dim.ReferencesOtherViews () && !IsInitialized)
  946. // {
  947. // Debug.WriteLine (
  948. // $"WARNING: {member} = {dim} of {this} is dependent on other views and {member} "
  949. // + $"is being accessed before the View has been initialized. This is likely a bug."
  950. // );
  951. // }
  952. //#endif // DEBUG
  953. return dim;
  954. }
  955. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  956. /// <remarks>
  957. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  958. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  959. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  960. /// thus should only be used for debugging.
  961. /// </remarks>
  962. public bool ValidatePosDim { get; set; }
  963. // TODO: Move this logic into the Pos/Dim classes
  964. /// <summary>
  965. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  966. /// Views dimensions.
  967. /// </summary>
  968. /// <exception cref="InvalidOperationException"></exception>
  969. private void CheckDimAuto ()
  970. {
  971. if (!ValidatePosDim || !IsInitialized)
  972. {
  973. return;
  974. }
  975. var widthAuto = Width as DimAuto;
  976. var heightAuto = Height as DimAuto;
  977. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  978. foreach (View view in Subviews)
  979. {
  980. if (widthAuto is { } && widthAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  981. {
  982. ThrowInvalid (view, view.Width, nameof (view.Width));
  983. ThrowInvalid (view, view.X, nameof (view.X));
  984. }
  985. if (heightAuto is { } && heightAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  986. {
  987. ThrowInvalid (view, view.Height, nameof (view.Height));
  988. ThrowInvalid (view, view.Y, nameof (view.Y));
  989. }
  990. }
  991. return;
  992. void ThrowInvalid (View view, object? checkPosDim, string name)
  993. {
  994. object? bad = null;
  995. switch (checkPosDim)
  996. {
  997. case Pos pos and PosAnchorEnd:
  998. break;
  999. case Pos pos and not PosAbsolute and not PosView and not PosCombine:
  1000. bad = pos;
  1001. break;
  1002. case Pos pos and PosCombine:
  1003. // Recursively check for not Absolute or not View
  1004. ThrowInvalid (view, (pos as PosCombine)?.Left, name);
  1005. ThrowInvalid (view, (pos as PosCombine)?.Right, name);
  1006. break;
  1007. case Dim dim and DimAuto:
  1008. break;
  1009. case Dim dim and DimFill:
  1010. break;
  1011. case Dim dim and not DimAbsolute and not DimView and not DimCombine:
  1012. bad = dim;
  1013. break;
  1014. case Dim dim and DimCombine:
  1015. // Recursively check for not Absolute or not View
  1016. ThrowInvalid (view, (dim as DimCombine)?.Left, name);
  1017. ThrowInvalid (view, (dim as DimCombine)?.Right, name);
  1018. break;
  1019. }
  1020. if (bad != null)
  1021. {
  1022. throw new LayoutException (
  1023. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  1024. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  1025. );
  1026. }
  1027. }
  1028. }
  1029. #endregion Diagnostics and Verification
  1030. }