ViewLayout.cs 42 KB

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