ViewLayout.cs 42 KB

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