View.Layout.cs 41 KB

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