View.Layout.cs 44 KB

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