ViewLayout.cs 41 KB

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