View.Layout.cs 45 KB

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