ViewLayout.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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. PosJustify.JustifyGroup (0, Subviews, Dim.Dimension.Width, Viewport.Width);
  586. PosJustify.JustifyGroup (0, Subviews, Dim.Dimension.Height, Viewport.Height);
  587. // Sort out the dependencies of the X, Y, Width, Height properties
  588. HashSet<View> nodes = new ();
  589. HashSet<(View, View)> edges = new ();
  590. CollectAll (this, ref nodes, ref edges);
  591. List<View> ordered = TopologicalSort (SuperView, nodes, edges);
  592. foreach (View v in ordered)
  593. {
  594. LayoutSubview (v, contentSize);
  595. }
  596. // If the 'to' is rooted to 'from' it's a special-case.
  597. // Use LayoutSubview with the Frame of the 'from'.
  598. if (SuperView is { } && GetTopSuperView () is { } && LayoutNeeded && edges.Count > 0)
  599. {
  600. foreach ((View from, View to) in edges)
  601. {
  602. LayoutSubview (to, from.ContentSize.GetValueOrDefault ());
  603. }
  604. }
  605. LayoutNeeded = false;
  606. OnLayoutComplete (new (contentSize));
  607. }
  608. private void LayoutSubview (View v, Size contentSize)
  609. {
  610. // BUGBUG: Calling SetRelativeLayout before LayoutSubviews is problematic. Need to resolve.
  611. v.SetRelativeLayout (contentSize);
  612. v.LayoutSubviews ();
  613. v.LayoutNeeded = false;
  614. }
  615. /// <summary>Indicates that the view does not need to be laid out.</summary>
  616. protected void ClearLayoutNeeded () { LayoutNeeded = false; }
  617. /// <summary>
  618. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views
  619. /// have been laid out.
  620. /// </summary>
  621. internal virtual void OnLayoutComplete (LayoutEventArgs args) { LayoutComplete?.Invoke (this, args); }
  622. // BUGBUG: We need an API/event that is called from SetRelativeLayout instead of/in addition to
  623. // BUGBUG: OnLayoutStarted which is called from LayoutSubviews.
  624. /// <summary>
  625. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews
  626. /// have been laid out.
  627. /// </summary>
  628. internal virtual void OnLayoutStarted (LayoutEventArgs args) { LayoutStarted?.Invoke (this, args); }
  629. /// <summary>
  630. /// Called whenever the view needs to be resized. This is called whenever <see cref="Frame"/>,
  631. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or <see cref="View.Height"/> changes.
  632. /// </summary>
  633. /// <remarks>
  634. /// <para>
  635. /// Determines the relative bounds of the <see cref="View"/> and its <see cref="Frame"/>s, and then calls
  636. /// <see cref="SetRelativeLayout(Size)"/> to update the view.
  637. /// </para>
  638. /// </remarks>
  639. internal void OnResizeNeeded ()
  640. {
  641. // TODO: Identify a real-world use-case where this API should be virtual.
  642. // TODO: Until then leave it `internal` and non-virtual
  643. // First try SuperView.Viewport, then Application.Top, then Driver.Viewport.
  644. // Finally, if none of those are valid, use int.MaxValue (for Unit tests).
  645. Size? contentSize = SuperView is { IsInitialized: true } ? SuperView.ContentSize :
  646. Application.Top is { } && Application.Top != this && Application.Top.IsInitialized ? Application.Top.ContentSize :
  647. Application.Driver?.Screen.Size ?? new (int.MaxValue, int.MaxValue);
  648. SetTextFormatterSize ();
  649. SetRelativeLayout (contentSize.GetValueOrDefault ());
  650. if (IsInitialized)
  651. {
  652. LayoutAdornments ();
  653. }
  654. SetNeedsDisplay ();
  655. SetNeedsLayout ();
  656. }
  657. internal bool LayoutNeeded { get; private set; } = true;
  658. /// <summary>
  659. /// Sets the internal <see cref="LayoutNeeded"/> flag for this View and all of it's subviews and it's SuperView.
  660. /// The main loop will call SetRelativeLayout and LayoutSubviews for any view with <see cref="LayoutNeeded"/> set.
  661. /// </summary>
  662. internal void SetNeedsLayout ()
  663. {
  664. if (LayoutNeeded)
  665. {
  666. return;
  667. }
  668. LayoutNeeded = true;
  669. foreach (View view in Subviews)
  670. {
  671. view.SetNeedsLayout ();
  672. }
  673. TextFormatter.NeedsFormat = true;
  674. SuperView?.SetNeedsLayout ();
  675. }
  676. /// <summary>
  677. /// Adjusts <see cref="Frame"/> given the SuperView's ContentSize (nominally the same as
  678. /// <c>this.SuperView.ContentSize</c>)
  679. /// and the position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  680. /// <see cref="Height"/>).
  681. /// </summary>
  682. /// <remarks>
  683. /// <para>
  684. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  685. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  686. /// are left unchanged.
  687. /// </para>
  688. /// </remarks>
  689. /// <param name="superviewContentSize">
  690. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.ContentSize</c>).
  691. /// </param>
  692. internal void SetRelativeLayout (Size? superviewContentSize)
  693. {
  694. Debug.Assert (_x is { });
  695. Debug.Assert (_y is { });
  696. Debug.Assert (_width is { });
  697. Debug.Assert (_height is { });
  698. if (superviewContentSize is null)
  699. {
  700. return;
  701. }
  702. CheckDimAuto ();
  703. int newX = _x.Calculate (superviewContentSize.Value.Width, _width, this, Dim.Dimension.Width);
  704. int newW = _width.Calculate (newX, superviewContentSize.Value.Width, this, Dim.Dimension.Width);
  705. int newY = _y.Calculate (superviewContentSize.Value.Height, _height, this, Dim.Dimension.Height);
  706. int newH = _height.Calculate (newY, superviewContentSize.Value.Height, this, Dim.Dimension.Height);
  707. Rectangle newFrame = new (newX, newY, newW, newH);
  708. if (Frame != newFrame)
  709. {
  710. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  711. // the view LayoutStyle.Absolute.
  712. SetFrame (newFrame);
  713. if (_x is Pos.PosAbsolute)
  714. {
  715. _x = Frame.X;
  716. }
  717. if (_y is Pos.PosAbsolute)
  718. {
  719. _y = Frame.Y;
  720. }
  721. if (_width is Dim.DimAbsolute)
  722. {
  723. _width = Frame.Width;
  724. }
  725. if (_height is Dim.DimAbsolute)
  726. {
  727. _height = Frame.Height;
  728. }
  729. if (!string.IsNullOrEmpty (Title))
  730. {
  731. SetTitleTextFormatterSize ();
  732. }
  733. SetNeedsLayout ();
  734. SetNeedsDisplay ();
  735. }
  736. }
  737. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  738. {
  739. // BUGBUG: This should really only work on initialized subviews
  740. foreach (View v in from.InternalSubviews /*.Where(v => v.IsInitialized)*/)
  741. {
  742. nNodes.Add (v);
  743. if (v.LayoutStyle != LayoutStyle.Computed)
  744. {
  745. continue;
  746. }
  747. CollectPos (v.X, v, ref nNodes, ref nEdges);
  748. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  749. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  750. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  751. }
  752. }
  753. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  754. {
  755. switch (dim)
  756. {
  757. case Dim.DimView dv:
  758. // See #2461
  759. //if (!from.InternalSubviews.Contains (dv.Target)) {
  760. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  761. //}
  762. if (dv.Target != this)
  763. {
  764. nEdges.Add ((dv.Target, from));
  765. }
  766. return;
  767. case Dim.DimCombine dc:
  768. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  769. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  770. break;
  771. }
  772. }
  773. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  774. {
  775. switch (pos)
  776. {
  777. case Pos.PosView pv:
  778. // See #2461
  779. //if (!from.InternalSubviews.Contains (pv.Target)) {
  780. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  781. //}
  782. if (pv.Target != this)
  783. {
  784. nEdges.Add ((pv.Target, from));
  785. }
  786. return;
  787. case Pos.PosCombine pc:
  788. CollectPos (pc._left, from, ref nNodes, ref nEdges);
  789. CollectPos (pc._right, from, ref nNodes, ref nEdges);
  790. break;
  791. }
  792. }
  793. // https://en.wikipedia.org/wiki/Topological_sorting
  794. internal static List<View> TopologicalSort (
  795. View superView,
  796. IEnumerable<View> nodes,
  797. ICollection<(View From, View To)> edges
  798. )
  799. {
  800. List<View> result = new ();
  801. // Set of all nodes with no incoming edges
  802. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  803. while (noEdgeNodes.Any ())
  804. {
  805. // remove a node n from S
  806. View n = noEdgeNodes.First ();
  807. noEdgeNodes.Remove (n);
  808. // add n to tail of L
  809. if (n != superView)
  810. {
  811. result.Add (n);
  812. }
  813. // for each node m with an edge e from n to m do
  814. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  815. {
  816. View m = e.To;
  817. // remove edge e from the graph
  818. edges.Remove (e);
  819. // if m has no other incoming edges then
  820. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  821. {
  822. // insert m into S
  823. noEdgeNodes.Add (m);
  824. }
  825. }
  826. }
  827. if (!edges.Any ())
  828. {
  829. return result;
  830. }
  831. foreach ((View from, View to) in edges)
  832. {
  833. if (from == to)
  834. {
  835. // if not yet added to the result, add it and remove from edge
  836. if (result.Find (v => v == from) is null)
  837. {
  838. result.Add (from);
  839. }
  840. edges.Remove ((from, to));
  841. }
  842. else if (from.SuperView == to.SuperView)
  843. {
  844. // if 'from' is not yet added to the result, add it
  845. if (result.Find (v => v == from) is null)
  846. {
  847. result.Add (from);
  848. }
  849. // if 'to' is not yet added to the result, add it
  850. if (result.Find (v => v == to) is null)
  851. {
  852. result.Add (to);
  853. }
  854. // remove from edge
  855. edges.Remove ((from, to));
  856. }
  857. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  858. {
  859. if (ReferenceEquals (from.SuperView, to))
  860. {
  861. throw new InvalidOperationException (
  862. $"ComputedLayout for \"{superView}\": \"{to}\" "
  863. + $"references a SubView (\"{from}\")."
  864. );
  865. }
  866. throw new InvalidOperationException (
  867. $"ComputedLayout for \"{superView}\": \"{from}\" "
  868. + $"linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  869. );
  870. }
  871. }
  872. // return L (a topologically sorted order)
  873. return result;
  874. } // TopologicalSort
  875. // Diagnostics to highlight when X or Y is read before the view has been initialized
  876. private Pos VerifyIsInitialized (Pos pos, string member)
  877. {
  878. #if DEBUG
  879. if ((pos.ReferencesOtherViews () || pos.ReferencesOtherViews ()) && !IsInitialized)
  880. {
  881. Debug.WriteLine (
  882. $"WARNING: The {pos} of {this} is dependent on other views and {member} "
  883. + $"is being accessed before the View has been initialized. This is likely a bug."
  884. );
  885. }
  886. #endif // DEBUG
  887. return pos;
  888. }
  889. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  890. private Dim VerifyIsInitialized (Dim dim, string member)
  891. {
  892. #if DEBUG
  893. if ((dim.ReferencesOtherViews () || dim.ReferencesOtherViews ()) && !IsInitialized)
  894. {
  895. Debug.WriteLine (
  896. $"WARNING: The {member} of {this} is dependent on other views and is "
  897. + $"is being accessed before the View has been initialized. This is likely a bug. "
  898. + $"{member} is {dim}"
  899. );
  900. }
  901. #endif // DEBUG
  902. return dim;
  903. }
  904. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  905. /// <remarks>
  906. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  907. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  908. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  909. /// thus should only be used for debugging.
  910. /// </remarks>
  911. public bool ValidatePosDim { get; set; }
  912. // TODO: Move this logic into the Pos/Dim classes
  913. /// <summary>
  914. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  915. /// Views dimensions.
  916. /// </summary>
  917. /// <exception cref="InvalidOperationException"></exception>
  918. private void CheckDimAuto ()
  919. {
  920. if (!ValidatePosDim || !IsInitialized || (Width is not Dim.DimAuto && Height is not Dim.DimAuto))
  921. {
  922. return;
  923. }
  924. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  925. foreach (View view in Subviews)
  926. {
  927. if (Width is Dim.DimAuto { _min: null })
  928. {
  929. ThrowInvalid (view, view.Width, nameof (view.Width));
  930. ThrowInvalid (view, view.X, nameof (view.X));
  931. }
  932. if (Height is Dim.DimAuto { _min: null })
  933. {
  934. ThrowInvalid (view, view.Height, nameof (view.Height));
  935. ThrowInvalid (view, view.Y, nameof (view.Y));
  936. }
  937. }
  938. return;
  939. void ThrowInvalid (View view, object checkPosDim, string name)
  940. {
  941. object bad = null;
  942. switch (checkPosDim)
  943. {
  944. case Pos pos and not Pos.PosAbsolute and not Pos.PosView and not Pos.PosCombine:
  945. bad = pos;
  946. break;
  947. case Pos pos and Pos.PosCombine:
  948. // Recursively check for not Absolute or not View
  949. ThrowInvalid (view, (pos as Pos.PosCombine)._left, name);
  950. ThrowInvalid (view, (pos as Pos.PosCombine)._right, name);
  951. break;
  952. case Dim dim and not Dim.DimAbsolute and not Dim.DimView and not Dim.DimCombine:
  953. bad = dim;
  954. break;
  955. case Dim dim and Dim.DimCombine:
  956. // Recursively check for not Absolute or not View
  957. ThrowInvalid (view, (dim as Dim.DimCombine)._left, name);
  958. ThrowInvalid (view, (dim as Dim.DimCombine)._right, name);
  959. break;
  960. }
  961. if (bad != null)
  962. {
  963. throw new InvalidOperationException (
  964. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  965. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  966. );
  967. }
  968. }
  969. }
  970. }