ViewLayout.cs 42 KB

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