ViewLayout.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. foreach (View v in from.InternalSubviews)
  743. {
  744. nNodes.Add (v);
  745. if (v.LayoutStyle != LayoutStyle.Computed)
  746. {
  747. continue;
  748. }
  749. CollectPos (v.X, v, ref nNodes, ref nEdges);
  750. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  751. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  752. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  753. }
  754. }
  755. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  756. {
  757. switch (dim)
  758. {
  759. case DimView dv:
  760. // See #2461
  761. //if (!from.InternalSubviews.Contains (dv.Target)) {
  762. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  763. //}
  764. if (dv.Target != this)
  765. {
  766. nEdges.Add ((dv.Target, from));
  767. }
  768. return;
  769. case DimCombine dc:
  770. CollectDim (dc.Left, from, ref nNodes, ref nEdges);
  771. CollectDim (dc.Right, from, ref nNodes, ref nEdges);
  772. break;
  773. }
  774. }
  775. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  776. {
  777. switch (pos)
  778. {
  779. case PosView pv:
  780. // See #2461
  781. //if (!from.InternalSubviews.Contains (pv.Target)) {
  782. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  783. //}
  784. if (pv.Target != this)
  785. {
  786. nEdges.Add ((pv.Target, from));
  787. }
  788. return;
  789. case PosCombine pc:
  790. CollectPos (pc.Left, from, ref nNodes, ref nEdges);
  791. CollectPos (pc.Right, from, ref nNodes, ref nEdges);
  792. break;
  793. }
  794. }
  795. // https://en.wikipedia.org/wiki/Topological_sorting
  796. internal static List<View> TopologicalSort (
  797. View superView,
  798. IEnumerable<View> nodes,
  799. ICollection<(View From, View To)> edges
  800. )
  801. {
  802. List<View> result = new ();
  803. // Set of all nodes with no incoming edges
  804. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  805. while (noEdgeNodes.Any ())
  806. {
  807. // remove a node n from S
  808. View n = noEdgeNodes.First ();
  809. noEdgeNodes.Remove (n);
  810. // add n to tail of L
  811. if (n != superView)
  812. {
  813. result.Add (n);
  814. }
  815. // for each node m with an edge e from n to m do
  816. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  817. {
  818. View m = e.To;
  819. // remove edge e from the graph
  820. edges.Remove (e);
  821. // if m has no other incoming edges then
  822. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  823. {
  824. // insert m into S
  825. noEdgeNodes.Add (m);
  826. }
  827. }
  828. }
  829. if (!edges.Any ())
  830. {
  831. return result;
  832. }
  833. foreach ((View from, View to) in edges)
  834. {
  835. if (from == to)
  836. {
  837. // if not yet added to the result, add it and remove from edge
  838. if (result.Find (v => v == from) is null)
  839. {
  840. result.Add (from);
  841. }
  842. edges.Remove ((from, to));
  843. }
  844. else if (from.SuperView == to.SuperView)
  845. {
  846. // if 'from' is not yet added to the result, add it
  847. if (result.Find (v => v == from) is null)
  848. {
  849. result.Add (from);
  850. }
  851. // if 'to' is not yet added to the result, add it
  852. if (result.Find (v => v == to) is null)
  853. {
  854. result.Add (to);
  855. }
  856. // remove from edge
  857. edges.Remove ((from, to));
  858. }
  859. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  860. {
  861. if (ReferenceEquals (from.SuperView, to))
  862. {
  863. throw new InvalidOperationException (
  864. $"ComputedLayout for \"{superView}\": \"{to}\" "
  865. + $"references a SubView (\"{from}\")."
  866. );
  867. }
  868. throw new InvalidOperationException (
  869. $"ComputedLayout for \"{superView}\": \"{from}\" "
  870. + $"linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  871. );
  872. }
  873. }
  874. // return L (a topologically sorted order)
  875. return result;
  876. } // TopologicalSort
  877. // Diagnostics to highlight when X or Y is read before the view has been initialized
  878. private Pos VerifyIsInitialized (Pos pos, string member)
  879. {
  880. //#if DEBUG
  881. // if (pos.ReferencesOtherViews () && !IsInitialized)
  882. // {
  883. // Debug.WriteLine (
  884. // $"WARNING: {member} = {pos} of {this} is dependent on other views and {member} "
  885. // + $"is being accessed before the View has been initialized. This is likely a bug."
  886. // );
  887. // }
  888. //#endif // DEBUG
  889. return pos;
  890. }
  891. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  892. private Dim VerifyIsInitialized (Dim dim, string member)
  893. {
  894. //#if DEBUG
  895. // if (dim.ReferencesOtherViews () && !IsInitialized)
  896. // {
  897. // Debug.WriteLine (
  898. // $"WARNING: {member} = {dim} of {this} is dependent on other views and {member} "
  899. // + $"is being accessed before the View has been initialized. This is likely a bug."
  900. // );
  901. // }
  902. //#endif // DEBUG
  903. return dim;
  904. }
  905. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  906. /// <remarks>
  907. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  908. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  909. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  910. /// thus should only be used for debugging.
  911. /// </remarks>
  912. public bool ValidatePosDim { get; set; }
  913. // TODO: Move this logic into the Pos/Dim classes
  914. /// <summary>
  915. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  916. /// Views dimensions.
  917. /// </summary>
  918. /// <exception cref="InvalidOperationException"></exception>
  919. private void CheckDimAuto ()
  920. {
  921. if (!ValidatePosDim || !IsInitialized)
  922. {
  923. return;
  924. }
  925. DimAuto? widthAuto = Width as DimAuto;
  926. DimAuto? heightAuto = Height as DimAuto;
  927. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  928. foreach (View view in Subviews)
  929. {
  930. if (widthAuto is { } && widthAuto.Style.HasFlag (DimAutoStyle.Content) && _contentSize is null)
  931. {
  932. ThrowInvalid (view, view.Width, nameof (view.Width));
  933. ThrowInvalid (view, view.X, nameof (view.X));
  934. }
  935. if (heightAuto is { } && heightAuto.Style.HasFlag (DimAutoStyle.Content) && _contentSize is null)
  936. {
  937. ThrowInvalid (view, view.Height, nameof (view.Height));
  938. ThrowInvalid (view, view.Y, nameof (view.Y));
  939. }
  940. }
  941. return;
  942. void ThrowInvalid (View view, object checkPosDim, string name)
  943. {
  944. object bad = null;
  945. switch (checkPosDim)
  946. {
  947. case Pos pos and PosAnchorEnd:
  948. break;
  949. case Pos pos and not PosAbsolute and not PosView and not PosCombine:
  950. bad = pos;
  951. break;
  952. case Pos pos and PosCombine:
  953. // Recursively check for not Absolute or not View
  954. ThrowInvalid (view, (pos as PosCombine).Left, name);
  955. ThrowInvalid (view, (pos as PosCombine).Right, name);
  956. break;
  957. case Dim dim and DimAuto:
  958. break;
  959. case Dim dim and DimFill:
  960. break;
  961. case Dim dim and not DimAbsolute and not DimView and not DimCombine:
  962. bad = dim;
  963. break;
  964. case Dim dim and DimCombine:
  965. // Recursively check for not Absolute or not View
  966. ThrowInvalid (view, (dim as DimCombine).Left, name);
  967. ThrowInvalid (view, (dim as DimCombine).Right, name);
  968. break;
  969. }
  970. if (bad != null)
  971. {
  972. throw new InvalidOperationException (
  973. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  974. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  975. );
  976. }
  977. }
  978. }
  979. }