ViewLayout.cs 42 KB

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