ViewLayout.cs 41 KB

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