ViewLayout.cs 42 KB

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