ViewLayout.cs 40 KB

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