View.Layout.cs 41 KB

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