View.Layout.cs 41 KB

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