View.Layout.cs 44 KB

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