View.Layout.cs 41 KB

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