View.Layout.cs 42 KB

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