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