ViewLayout.cs 38 KB

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