View.Layout.cs 38 KB

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