View.Layout.cs 40 KB

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