ViewLayout.cs 42 KB

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