ViewLayout.cs 42 KB

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