View.Layout.cs 42 KB

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