ViewLayout.cs 40 KB

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