ViewLayout.cs 42 KB

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