ViewLayout.cs 41 KB

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