View.Layout.cs 39 KB

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