View.Layout.cs 44 KB

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