ViewLayout.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. /// Adjusts <see cref="Frame"/> given the SuperView's ContentSize (nominally the same as
  469. /// <c>this.SuperView.GetContentSize ()</c>)
  470. /// and the position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  471. /// <see cref="Height"/>).
  472. /// </summary>
  473. /// <remarks>
  474. /// <para>
  475. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  476. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  477. /// are left unchanged.
  478. /// </para>
  479. /// <para>
  480. /// If any of the view's subviews have a position or dimension dependent on either <see cref="GetContentSize"/> or other subviews, <see cref="LayoutSubview"/> on
  481. /// will be called for that subview.
  482. /// </para>
  483. /// </remarks>
  484. /// <param name="superviewContentSize">
  485. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.GetContentSize ()</c>).
  486. /// </param>
  487. internal void SetRelativeLayout (Size superviewContentSize)
  488. {
  489. Debug.Assert (_x is { });
  490. Debug.Assert (_y is { });
  491. Debug.Assert (_width is { });
  492. Debug.Assert (_height is { });
  493. CheckDimAuto ();
  494. SetTextFormatterSize ();
  495. int newX, newW, newY, newH;
  496. Rectangle oldFrame = Frame;
  497. // Calculate the new X, Y, Width, and Height
  498. // If the Width or Height is Dim.Auto, calculate the Width or Height first. Otherwise, calculate the X or Y first.
  499. if (_width is DimAuto)
  500. {
  501. newW = _width.Calculate (0, superviewContentSize.Width, this, Dimension.Width);
  502. newX = _x.Calculate (superviewContentSize.Width, newW, this, Dimension.Width);
  503. //SetFrame (oldFrame with { X = newX, Width = newW });
  504. }
  505. else
  506. {
  507. newX = _x.Calculate (superviewContentSize.Width, _width, this, Dimension.Width);
  508. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  509. }
  510. if (_height is DimAuto)
  511. {
  512. newH = _height.Calculate (0, superviewContentSize.Height, this, Dimension.Height);
  513. newY = _y.Calculate (superviewContentSize.Height, newH, this, Dimension.Height);
  514. }
  515. else
  516. {
  517. newY = _y.Calculate (superviewContentSize.Height, _height, this, Dimension.Height);
  518. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  519. }
  520. SetFrame (oldFrame);
  521. Rectangle newFrame = new (newX, newY, newW, newH);
  522. if (Frame != newFrame)
  523. {
  524. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height
  525. SetFrame (newFrame);
  526. if (_x is PosAbsolute)
  527. {
  528. _x = Frame.X;
  529. }
  530. if (_y is PosAbsolute)
  531. {
  532. _y = Frame.Y;
  533. }
  534. if (_width is DimAbsolute)
  535. {
  536. _width = Frame.Width;
  537. }
  538. if (_height is DimAbsolute)
  539. {
  540. _height = Frame.Height;
  541. }
  542. if (!string.IsNullOrEmpty (Title))
  543. {
  544. SetTitleTextFormatterSize ();
  545. }
  546. SetNeedsLayout ();
  547. SetNeedsDisplay ();
  548. }
  549. }
  550. /// <summary>
  551. /// Invoked when the dimensions of the view have changed, for example in response to the container view or terminal resizing.
  552. /// </summary>
  553. /// <remarks>
  554. /// <para>
  555. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  556. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  557. /// </para>
  558. /// <para>Raises the <see cref="LayoutComplete"/> event before it returns.</para>
  559. /// </remarks>
  560. public virtual void LayoutSubviews ()
  561. {
  562. if (!IsInitialized)
  563. {
  564. Debug.WriteLine ($"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}");
  565. }
  566. if (!LayoutNeeded)
  567. {
  568. return;
  569. }
  570. CheckDimAuto ();
  571. var contentSize = GetContentSize ();
  572. OnLayoutStarted (new (contentSize));
  573. LayoutAdornments ();
  574. SetTextFormatterSize ();
  575. // Sort out the dependencies of the X, Y, Width, Height properties
  576. HashSet<View> nodes = new ();
  577. HashSet<(View, View)> edges = new ();
  578. CollectAll (this, ref nodes, ref edges);
  579. List<View> ordered = TopologicalSort (SuperView, nodes, edges);
  580. foreach (View v in ordered)
  581. {
  582. LayoutSubview (v, contentSize);
  583. }
  584. // If the 'to' is rooted to 'from' it's a special-case.
  585. // Use LayoutSubview with the Frame of the 'from'.
  586. if (SuperView is { } && GetTopSuperView () is { } && LayoutNeeded && edges.Count > 0)
  587. {
  588. foreach ((View from, View to) in edges)
  589. {
  590. LayoutSubview (to, from.GetContentSize ());
  591. }
  592. }
  593. LayoutNeeded = false;
  594. OnLayoutComplete (new (contentSize));
  595. }
  596. private void LayoutSubview (View v, Size contentSize)
  597. {
  598. // BUGBUG: Calling SetRelativeLayout before LayoutSubviews is problematic. Need to resolve.
  599. v.SetRelativeLayout (contentSize);
  600. v.LayoutSubviews ();
  601. v.LayoutNeeded = false;
  602. }
  603. /// <summary>Indicates that the view does not need to be laid out.</summary>
  604. protected void ClearLayoutNeeded () { LayoutNeeded = false; }
  605. /// <summary>
  606. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views
  607. /// have been laid out.
  608. /// </summary>
  609. internal virtual void OnLayoutComplete (LayoutEventArgs args) { LayoutComplete?.Invoke (this, args); }
  610. // BUGBUG: We need an API/event that is called from SetRelativeLayout instead of/in addition to
  611. // BUGBUG: OnLayoutStarted which is called from LayoutSubviews.
  612. /// <summary>
  613. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews
  614. /// have been laid out.
  615. /// </summary>
  616. internal virtual void OnLayoutStarted (LayoutEventArgs args) { LayoutStarted?.Invoke (this, args); }
  617. /// <summary>
  618. /// Called whenever the view needs to be resized. This is called whenever <see cref="Frame"/>,
  619. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or <see cref="View.Height"/> changes.
  620. /// </summary>
  621. /// <remarks>
  622. /// <para>
  623. /// Determines the relative bounds of the <see cref="View"/> and its <see cref="Frame"/>s, and then calls
  624. /// <see cref="SetRelativeLayout"/> to update the view.
  625. /// </para>
  626. /// </remarks>
  627. internal void OnResizeNeeded ()
  628. {
  629. // TODO: Identify a real-world use-case where this API should be virtual.
  630. // TODO: Until then leave it `internal` and non-virtual
  631. // Determine our container's ContentSize -
  632. // First try SuperView.Viewport, then Application.Top, then Driver.Viewport.
  633. // Finally, if none of those are valid, use 2048 (for Unit tests).
  634. Size superViewContentSize = SuperView is { IsInitialized: true } ? SuperView.GetContentSize () :
  635. Application.Top is { } && Application.Top != this && Application.Top.IsInitialized ? Application.Top.GetContentSize () :
  636. Application.Screen.Size;
  637. SetTextFormatterSize ();
  638. SetRelativeLayout (superViewContentSize);
  639. if (IsInitialized)
  640. {
  641. LayoutAdornments ();
  642. }
  643. SetNeedsDisplay ();
  644. SetNeedsLayout ();
  645. }
  646. internal bool LayoutNeeded { get; private set; } = true;
  647. /// <summary>
  648. /// Sets the internal <see cref="LayoutNeeded"/> flag for this View and all of it's subviews and it's SuperView.
  649. /// The main loop will call SetRelativeLayout and LayoutSubviews for any view with <see cref="LayoutNeeded"/> set.
  650. /// </summary>
  651. internal void SetNeedsLayout ()
  652. {
  653. if (LayoutNeeded)
  654. {
  655. return;
  656. }
  657. LayoutNeeded = true;
  658. foreach (View view in Subviews)
  659. {
  660. view.SetNeedsLayout ();
  661. }
  662. TextFormatter.NeedsFormat = true;
  663. SuperView?.SetNeedsLayout ();
  664. }
  665. /// <summary>
  666. /// Collects all views and their dependencies from a given starting view for layout purposes. Used by <see cref="TopologicalSort"/> to create an ordered list of views to layout.
  667. /// </summary>
  668. /// <param name="from">The starting view from which to collect dependencies.</param>
  669. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  670. /// <param name="nEdges">A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views indicating a dependency.</param>
  671. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  672. {
  673. foreach (View? v in from.InternalSubviews)
  674. {
  675. nNodes.Add (v);
  676. CollectPos (v.X, v, ref nNodes, ref nEdges);
  677. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  678. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  679. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  680. }
  681. }
  682. /// <summary>
  683. /// Collects dimension (where Width or Height is `DimView`) dependencies for a given view.
  684. /// </summary>
  685. /// <param name="dim">The dimension (width or height) to collect dependencies for.</param>
  686. /// <param name="from">The view for which to collect dimension dependencies.</param>
  687. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  688. /// <param name="nEdges">A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views indicating a dependency.</param>
  689. internal void CollectDim (Dim? dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  690. {
  691. switch (dim)
  692. {
  693. case DimView dv:
  694. // See #2461
  695. //if (!from.InternalSubviews.Contains (dv.Target)) {
  696. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  697. //}
  698. if (dv.Target != this)
  699. {
  700. nEdges.Add ((dv.Target, from));
  701. }
  702. return;
  703. case DimCombine dc:
  704. CollectDim (dc.Left, from, ref nNodes, ref nEdges);
  705. CollectDim (dc.Right, from, ref nNodes, ref nEdges);
  706. break;
  707. }
  708. }
  709. /// <summary>
  710. /// Collects position (where X or Y is `PosView`) dependencies for a given view.
  711. /// </summary>
  712. /// <param name="pos">The position (X or Y) to collect dependencies for.</param>
  713. /// <param name="from">The view for which to collect position dependencies.</param>
  714. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  715. /// <param name="nEdges">A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views indicating a dependency.</param>
  716. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  717. {
  718. switch (pos)
  719. {
  720. case PosView pv:
  721. // See #2461
  722. //if (!from.InternalSubviews.Contains (pv.Target)) {
  723. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  724. //}
  725. if (pv.Target != this)
  726. {
  727. nEdges.Add ((pv.Target, from));
  728. }
  729. return;
  730. case PosCombine pc:
  731. CollectPos (pc.Left, from, ref nNodes, ref nEdges);
  732. CollectPos (pc.Right, from, ref nNodes, ref nEdges);
  733. break;
  734. }
  735. }
  736. // https://en.wikipedia.org/wiki/Topological_sorting
  737. internal static List<View> TopologicalSort (
  738. View superView,
  739. IEnumerable<View> nodes,
  740. ICollection<(View From, View To)> edges
  741. )
  742. {
  743. List<View> result = new ();
  744. // Set of all nodes with no incoming edges
  745. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  746. while (noEdgeNodes.Any ())
  747. {
  748. // remove a node n from S
  749. View n = noEdgeNodes.First ();
  750. noEdgeNodes.Remove (n);
  751. // add n to tail of L
  752. if (n != superView)
  753. {
  754. result.Add (n);
  755. }
  756. // for each node m with an edge e from n to m do
  757. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  758. {
  759. View m = e.To;
  760. // remove edge e from the graph
  761. edges.Remove (e);
  762. // if m has no other incoming edges then
  763. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  764. {
  765. // insert m into S
  766. noEdgeNodes.Add (m);
  767. }
  768. }
  769. }
  770. if (!edges.Any ())
  771. {
  772. return result;
  773. }
  774. foreach ((View from, View to) in edges)
  775. {
  776. if (from == to)
  777. {
  778. // if not yet added to the result, add it and remove from edge
  779. if (result.Find (v => v == from) is null)
  780. {
  781. result.Add (from);
  782. }
  783. edges.Remove ((from, to));
  784. }
  785. else if (from.SuperView == to.SuperView)
  786. {
  787. // if 'from' is not yet added to the result, add it
  788. if (result.Find (v => v == from) is null)
  789. {
  790. result.Add (from);
  791. }
  792. // if 'to' is not yet added to the result, add it
  793. if (result.Find (v => v == to) is null)
  794. {
  795. result.Add (to);
  796. }
  797. // remove from edge
  798. edges.Remove ((from, to));
  799. }
  800. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  801. {
  802. if (ReferenceEquals (from.SuperView, to))
  803. {
  804. throw new InvalidOperationException (
  805. $"ComputedLayout for \"{superView}\": \"{to}\" "
  806. + $"references a SubView (\"{from}\")."
  807. );
  808. }
  809. throw new InvalidOperationException (
  810. $"ComputedLayout for \"{superView}\": \"{from}\" "
  811. + $"linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  812. );
  813. }
  814. }
  815. // return L (a topologically sorted order)
  816. return result;
  817. } // TopologicalSort
  818. // Diagnostics to highlight when X or Y is read before the view has been initialized
  819. private Pos VerifyIsInitialized (Pos pos, string member)
  820. {
  821. //#if DEBUG
  822. // if (pos.ReferencesOtherViews () && !IsInitialized)
  823. // {
  824. // Debug.WriteLine (
  825. // $"WARNING: {member} = {pos} of {this} is dependent on other views and {member} "
  826. // + $"is being accessed before the View has been initialized. This is likely a bug."
  827. // );
  828. // }
  829. //#endif // DEBUG
  830. return pos;
  831. }
  832. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  833. private Dim? VerifyIsInitialized (Dim? dim, string member)
  834. {
  835. //#if DEBUG
  836. // if (dim.ReferencesOtherViews () && !IsInitialized)
  837. // {
  838. // Debug.WriteLine (
  839. // $"WARNING: {member} = {dim} of {this} is dependent on other views and {member} "
  840. // + $"is being accessed before the View has been initialized. This is likely a bug."
  841. // );
  842. // }
  843. //#endif // DEBUG
  844. return dim;
  845. }
  846. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  847. /// <remarks>
  848. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  849. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  850. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  851. /// thus should only be used for debugging.
  852. /// </remarks>
  853. public bool ValidatePosDim { get; set; }
  854. // TODO: Move this logic into the Pos/Dim classes
  855. /// <summary>
  856. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  857. /// Views dimensions.
  858. /// </summary>
  859. /// <exception cref="InvalidOperationException"></exception>
  860. private void CheckDimAuto ()
  861. {
  862. if (!ValidatePosDim || !IsInitialized)
  863. {
  864. return;
  865. }
  866. DimAuto? widthAuto = Width as DimAuto;
  867. DimAuto? heightAuto = Height as DimAuto;
  868. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  869. foreach (View view in Subviews)
  870. {
  871. if (widthAuto is { } && widthAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  872. {
  873. ThrowInvalid (view, view.Width, nameof (view.Width));
  874. ThrowInvalid (view, view.X, nameof (view.X));
  875. }
  876. if (heightAuto is { } && heightAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  877. {
  878. ThrowInvalid (view, view.Height, nameof (view.Height));
  879. ThrowInvalid (view, view.Y, nameof (view.Y));
  880. }
  881. }
  882. return;
  883. void ThrowInvalid (View view, object? checkPosDim, string name)
  884. {
  885. object? bad = null;
  886. switch (checkPosDim)
  887. {
  888. case Pos pos and PosAnchorEnd:
  889. break;
  890. case Pos pos and not PosAbsolute and not PosView and not PosCombine:
  891. bad = pos;
  892. break;
  893. case Pos pos and PosCombine:
  894. // Recursively check for not Absolute or not View
  895. ThrowInvalid (view, (pos as PosCombine)?.Left, name);
  896. ThrowInvalid (view, (pos as PosCombine)?.Right, name);
  897. break;
  898. case Dim dim and DimAuto:
  899. break;
  900. case Dim dim and DimFill:
  901. break;
  902. case Dim dim and not DimAbsolute and not DimView and not DimCombine:
  903. bad = dim;
  904. break;
  905. case Dim dim and DimCombine:
  906. // Recursively check for not Absolute or not View
  907. ThrowInvalid (view, (dim as DimCombine)?.Left, name);
  908. ThrowInvalid (view, (dim as DimCombine)?.Right, name);
  909. break;
  910. }
  911. if (bad != null)
  912. {
  913. throw new InvalidOperationException (
  914. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  915. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  916. );
  917. }
  918. }
  919. }
  920. }