ViewLayout.cs 42 KB

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