ViewLayout.cs 40 KB

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