ViewLayout.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. using System.Diagnostics;
  2. using Microsoft.CodeAnalysis;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// <para>Indicates the LayoutStyle for the <see cref="View"/>.</para>
  6. /// <para>
  7. /// If Absolute, the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  8. /// <see cref="View.Height"/> objects are all absolute values and are not relative. The position and size of the
  9. /// view is described by <see cref="View.Frame"/>.
  10. /// </para>
  11. /// <para>
  12. /// If Computed, one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  13. /// <see cref="View.Height"/> objects are relative to the <see cref="View.SuperView"/> and are computed at layout
  14. /// time.
  15. /// </para>
  16. /// </summary>
  17. public enum LayoutStyle
  18. {
  19. /// <summary>
  20. /// Indicates the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  21. /// <see cref="View.Height"/> objects are all absolute values and are not relative. The position and size of the view
  22. /// is described by <see cref="View.Frame"/>.
  23. /// </summary>
  24. Absolute,
  25. /// <summary>
  26. /// Indicates one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  27. /// <see cref="View.Height"/>
  28. /// objects are relative to the <see cref="View.SuperView"/> and are computed at layout time. The position and size of
  29. /// the
  30. /// view
  31. /// will be computed based on these objects at layout time. <see cref="View.Frame"/> will provide the absolute computed
  32. /// values.
  33. /// </summary>
  34. Computed
  35. }
  36. public partial class View
  37. {
  38. #region Frame
  39. private Rectangle _frame;
  40. /// <summary>Gets or sets the absolute location and dimension of the view.</summary>
  41. /// <value>
  42. /// The rectangle describing absolute location and dimension of the view, in coordinates relative to the
  43. /// <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.
  44. /// </value>
  45. /// <remarks>
  46. /// <para>Frame is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.</para>
  47. /// <para>
  48. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> to the
  49. /// values of the corresponding properties of the <paramref name="value"/> parameter.
  50. /// This causes <see cref="LayoutStyle"/> to be <see cref="LayoutStyle.Absolute"/>.
  51. /// </para>
  52. /// <para>
  53. /// Altering the Frame will eventually (when the view hierarchy is next laid out via see
  54. /// cref="LayoutSubviews"/>) cause <see cref="LayoutSubview(View, Size)"/> and
  55. /// <see cref="OnDrawContent(Rectangle)"/>
  56. /// methods to be called.
  57. /// </para>
  58. /// </remarks>
  59. public Rectangle Frame
  60. {
  61. get => _frame;
  62. set
  63. {
  64. if (_frame == value)
  65. {
  66. return;
  67. }
  68. SetFrame (value with { Width = Math.Max (value.Width, 0), Height = Math.Max (value.Height, 0) });
  69. // If Frame gets set, by definition, the View is now LayoutStyle.Absolute, so
  70. // set all Pos/Dim to Absolute values.
  71. _x = _frame.X;
  72. _y = _frame.Y;
  73. _width = _frame.Width;
  74. _height = _frame.Height;
  75. // TODO: Figure out if the below can be optimized.
  76. if (IsInitialized)
  77. {
  78. OnResizeNeeded ();
  79. }
  80. }
  81. }
  82. private void SetFrame (in Rectangle frame)
  83. {
  84. var oldViewport = Rectangle.Empty;
  85. if (IsInitialized)
  86. {
  87. oldViewport = Viewport;
  88. }
  89. // This is the only place where _frame should be set directly. Use Frame = or SetFrame instead.
  90. _frame = frame;
  91. OnViewportChanged (new (IsInitialized ? Viewport : Rectangle.Empty, oldViewport));
  92. if (!TextFormatter.AutoSize)
  93. {
  94. TextFormatter.Size = ContentSize.GetValueOrDefault ();
  95. }
  96. }
  97. /// <summary>Gets the <see cref="Frame"/> with a screen-relative location.</summary>
  98. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  99. public virtual Rectangle FrameToScreen ()
  100. {
  101. Rectangle screen = Frame;
  102. View current = SuperView;
  103. while (current is { })
  104. {
  105. if (current is Adornment adornment)
  106. {
  107. // Adornments don't have SuperViews; use Adornment.FrameToScreen override
  108. // which will give us the screen coordinates of the parent
  109. Rectangle parentScreen = adornment.FrameToScreen ();
  110. // Now add our Frame location
  111. parentScreen.Offset (screen.X, screen.Y);
  112. return parentScreen;
  113. }
  114. Point viewportOffset = current.GetViewportOffsetFromFrame ();
  115. viewportOffset.Offset (current.Frame.X - current.Viewport.X, current.Frame.Y - current.Viewport.Y);
  116. screen.X += viewportOffset.X;
  117. screen.Y += viewportOffset.Y;
  118. current = current.SuperView;
  119. }
  120. return screen;
  121. }
  122. /// <summary>
  123. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means relative to the
  124. /// View's <see cref="SuperView"/>'s <see cref="Viewport"/>.
  125. /// </summary>
  126. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Viewport"/>.</returns>
  127. /// <param name="location">Screen-relative coordinate.</param>
  128. public virtual Point ScreenToFrame (in Point location)
  129. {
  130. if (SuperView is null)
  131. {
  132. return new (location.X - Frame.X, location.Y - Frame.Y);
  133. }
  134. Point superViewViewportOffset = SuperView.GetViewportOffsetFromFrame ();
  135. superViewViewportOffset.Offset(-SuperView.Viewport.X, -SuperView.Viewport.Y);
  136. Point frame = location;
  137. frame.Offset(-superViewViewportOffset.X, -superViewViewportOffset.Y);
  138. frame = SuperView.ScreenToFrame (frame);
  139. frame.Offset (-Frame.X, -Frame.Y);
  140. return frame;
  141. }
  142. private Pos _x = Pos.At (0);
  143. /// <summary>Gets or sets the X position for the view (the column).</summary>
  144. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  145. /// <remarks>
  146. /// <para>
  147. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.
  148. /// </para>
  149. /// <para>
  150. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  151. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  152. /// called.
  153. /// </para>
  154. /// <para>
  155. /// Changing this property will eventually (when the view is next drawn) cause the
  156. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  157. /// </para>
  158. /// <para>
  159. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  160. /// <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  161. /// </para>
  162. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  163. /// </remarks>
  164. public Pos X
  165. {
  166. get => VerifyIsInitialized (_x, nameof (X));
  167. set
  168. {
  169. if (Equals (_x, value))
  170. {
  171. return;
  172. }
  173. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  174. OnResizeNeeded ();
  175. }
  176. }
  177. private Pos _y = Pos.At (0);
  178. /// <summary>Gets or sets the Y position for the view (the row).</summary>
  179. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  180. /// <remarks>
  181. /// <para>
  182. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.
  183. /// </para>
  184. /// <para>
  185. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  186. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  187. /// called.
  188. /// </para>
  189. /// <para>
  190. /// Changing this property will eventually (when the view is next drawn) cause the
  191. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  192. /// </para>
  193. /// <para>
  194. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  195. /// <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  196. /// </para>
  197. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  198. /// </remarks>
  199. public Pos Y
  200. {
  201. get => VerifyIsInitialized (_y, nameof (Y));
  202. set
  203. {
  204. if (Equals (_y, value))
  205. {
  206. return;
  207. }
  208. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  209. OnResizeNeeded ();
  210. }
  211. }
  212. private Dim _height = Dim.Sized (0);
  213. /// <summary>Gets or sets the height dimension of the view.</summary>
  214. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  215. /// <remarks>
  216. /// <para>
  217. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>
  218. /// .
  219. /// </para>
  220. /// <para>
  221. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the view has
  222. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  223. /// called.
  224. /// </para>
  225. /// <para>
  226. /// Changing this property will eventually (when the view is next drawn) cause the
  227. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  228. /// </para>
  229. /// <para>
  230. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  231. /// <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  232. /// </para>
  233. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  234. /// </remarks>
  235. public Dim Height
  236. {
  237. get => VerifyIsInitialized (_height, nameof (Height));
  238. set
  239. {
  240. if (Equals (_height, value))
  241. {
  242. return;
  243. }
  244. if (_height is Dim.DimAuto)
  245. {
  246. // Reset ContentSize to Viewport
  247. _contentSize = null;
  248. }
  249. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  250. OnResizeNeeded ();
  251. }
  252. }
  253. private Dim _width = Dim.Sized (0);
  254. /// <summary>Gets or sets the width dimension of the view.</summary>
  255. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  256. /// <remarks>
  257. /// <para>
  258. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>
  259. /// .
  260. /// </para>
  261. /// <para>
  262. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the view has
  263. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout"/> has been
  264. /// called.
  265. /// </para>
  266. /// <para>
  267. /// Changing this property will eventually (when the view is next drawn) cause the
  268. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  269. /// </para>
  270. /// <para>
  271. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  272. /// <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  273. /// </para>
  274. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  275. /// </remarks>
  276. public Dim Width
  277. {
  278. get => VerifyIsInitialized (_width, nameof (Width));
  279. set
  280. {
  281. if (Equals (_width, value))
  282. {
  283. return;
  284. }
  285. if (_width is Dim.DimAuto)
  286. {
  287. // Reset ContentSize to Viewport
  288. _contentSize = null;
  289. }
  290. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  291. OnResizeNeeded ();
  292. }
  293. }
  294. #endregion Frame
  295. #region Layout Engine
  296. // @tig Notes on layout flow. Ignore for now.
  297. // BeginLayout
  298. // If !LayoutNeeded return
  299. // If !SizeNeeded return
  300. // Call OnLayoutStarted
  301. // Views and subviews can update things
  302. //
  303. // EndLayout
  304. /// <summary>
  305. /// Controls how the View's <see cref="Frame"/> is computed during <see cref="LayoutSubviews"/>. If the style is
  306. /// set to <see cref="LayoutStyle.Absolute"/>, LayoutSubviews does not change the <see cref="Frame"/>. If the style is
  307. /// <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using the <see cref="X"/>, <see cref="Y"/>,
  308. /// <see cref="Width"/>, and <see cref="Height"/> properties.
  309. /// </summary>
  310. /// <remarks>
  311. /// <para>
  312. /// Setting this property to <see cref="LayoutStyle.Absolute"/> will cause <see cref="Frame"/> to determine the
  313. /// size and position of the view. <see cref="X"/> and <see cref="Y"/> will be set to <see cref="Dim.DimAbsolute"/>
  314. /// using <see cref="Frame"/>.
  315. /// </para>
  316. /// <para>
  317. /// Setting this property to <see cref="LayoutStyle.Computed"/> will cause the view to use the
  318. /// <see cref="LayoutSubviews"/> method to size and position of the view. If either of the <see cref="X"/> and
  319. /// <see cref="Y"/> properties are `null` they will be set to <see cref="Pos.PosAbsolute"/> using the current value
  320. /// of <see cref="Frame"/>. If either of the <see cref="Width"/> and <see cref="Height"/> properties are `null`
  321. /// they will be set to <see cref="Dim.DimAbsolute"/> using <see cref="Frame"/>.
  322. /// </para>
  323. /// </remarks>
  324. /// <value>The layout style.</value>
  325. public LayoutStyle LayoutStyle
  326. {
  327. get
  328. {
  329. if (_x is Pos.PosAbsolute
  330. && _y is Pos.PosAbsolute
  331. && _width is Dim.DimAbsolute
  332. && _height is Dim.DimAbsolute)
  333. {
  334. return LayoutStyle.Absolute;
  335. }
  336. return LayoutStyle.Computed;
  337. }
  338. }
  339. #endregion Layout Engine
  340. /// <summary>
  341. /// Indicates whether the specified SuperView-relative coordinates are within the View's <see cref="Frame"/>.
  342. /// </summary>
  343. /// <param name="location">SuperView-relative coordinate</param>
  344. /// <returns><see langword="true"/> if the specified SuperView-relative coordinates are within the View.</returns>
  345. public virtual bool Contains (in Point location) { return Frame.Contains (location); }
  346. #nullable enable
  347. /// <summary>Finds the first Subview of <paramref name="start"/> that is visible at the provided location.</summary>
  348. /// <remarks>
  349. /// <para>
  350. /// Used to determine what view the mouse is over.
  351. /// </para>
  352. /// </remarks>
  353. /// <param name="start">The view to scope the search by.</param>
  354. /// <param name="location"><paramref name="start"/>.SuperView-relative coordinate.</param>
  355. /// <returns>
  356. /// The view that was found at the <paramref name="location"/> coordinate.
  357. /// <see langword="null"/> if no view was found.
  358. /// </returns>
  359. // CONCURRENCY: This method is not thread-safe. Undefined behavior and likely program crashes are exposed by unsynchronized access to InternalSubviews.
  360. internal static View? FindDeepestView (View? start, in Point location)
  361. {
  362. Point currentLocation = location;
  363. while (start is { Visible: true } && start.Contains (currentLocation))
  364. {
  365. Adornment? found = null;
  366. if (start.Margin.Contains (currentLocation))
  367. {
  368. found = start.Margin;
  369. }
  370. else if (start.Border.Contains (currentLocation))
  371. {
  372. found = start.Border;
  373. }
  374. else if (start.Padding.Contains (currentLocation))
  375. {
  376. found = start.Padding;
  377. }
  378. Point viewportOffset = start.GetViewportOffsetFromFrame ();
  379. if (found is { })
  380. {
  381. start = found;
  382. viewportOffset = found.Parent.Frame.Location;
  383. }
  384. int startOffsetX = currentLocation.X - (start.Frame.X + viewportOffset.X);
  385. int startOffsetY = currentLocation.Y - (start.Frame.Y + viewportOffset.Y);
  386. View? subview = null;
  387. for (int i = start.InternalSubviews.Count - 1; i >= 0; i--)
  388. {
  389. if (start.InternalSubviews [i].Visible
  390. && start.InternalSubviews [i].Contains (new (startOffsetX + start.Viewport.X, startOffsetY + start.Viewport.Y)))
  391. {
  392. subview = start.InternalSubviews [i];
  393. currentLocation.X = startOffsetX + start.Viewport.X;
  394. currentLocation.Y = startOffsetY + start.Viewport.Y;
  395. // start is the deepest subview under the mouse; stop searching the subviews
  396. break;
  397. }
  398. }
  399. if (subview is null)
  400. {
  401. // No subview was found that's under the mouse, so we're done
  402. return start;
  403. }
  404. // We found a subview of start that's under the mouse, continue...
  405. start = subview;
  406. }
  407. return null;
  408. }
  409. #nullable restore
  410. /// <summary>
  411. /// Gets a new location of the <see cref="View"/> that is within the Viewport of the <paramref name="viewToMove"/>'s
  412. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  413. /// </summary>
  414. /// <remarks>
  415. /// If <paramref name="viewToMove"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  416. /// <see cref="Application.Top"/> the position will be bound by the <see cref="ConsoleDriver.Cols"/> and
  417. /// <see cref="ConsoleDriver.Rows"/>.
  418. /// </remarks>
  419. /// <param name="viewToMove">The View that is to be moved.</param>
  420. /// <param name="targetX">The target x location.</param>
  421. /// <param name="targetY">The target y location.</param>
  422. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  423. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  424. /// <param name="statusBar">The new top most statusBar</param>
  425. /// <returns>
  426. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  427. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  428. /// </returns>
  429. internal static View GetLocationEnsuringFullVisibility (
  430. View viewToMove,
  431. int targetX,
  432. int targetY,
  433. out int nx,
  434. out int ny,
  435. out StatusBar statusBar
  436. )
  437. {
  438. int maxDimension;
  439. View superView;
  440. statusBar = null;
  441. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  442. {
  443. maxDimension = Driver.Cols;
  444. superView = Application.Top;
  445. }
  446. else
  447. {
  448. // Use the SuperView's Viewport, not Frame
  449. maxDimension = viewToMove.SuperView.Viewport.Width;
  450. superView = viewToMove.SuperView;
  451. }
  452. if (superView?.Margin is { } && superView == viewToMove.SuperView)
  453. {
  454. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  455. }
  456. if (viewToMove!.Frame.Width <= maxDimension)
  457. {
  458. nx = Math.Max (targetX, 0);
  459. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  460. if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  461. {
  462. nx = Math.Max (viewToMove.Frame.Right, 0);
  463. }
  464. }
  465. else
  466. {
  467. nx = targetX;
  468. }
  469. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  470. var menuVisible = false;
  471. var statusVisible = false;
  472. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  473. {
  474. menuVisible = Application.Top?.MenuBar?.Visible == true;
  475. }
  476. else
  477. {
  478. View t = viewToMove.SuperView;
  479. while (t is { } and not Toplevel)
  480. {
  481. t = t.SuperView;
  482. }
  483. if (t is Toplevel topLevel)
  484. {
  485. menuVisible = topLevel.MenuBar?.Visible == true;
  486. }
  487. }
  488. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  489. {
  490. maxDimension = menuVisible ? 1 : 0;
  491. }
  492. else
  493. {
  494. maxDimension = 0;
  495. }
  496. ny = Math.Max (targetY, maxDimension);
  497. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  498. {
  499. statusVisible = Application.Top?.StatusBar?.Visible == true;
  500. statusBar = Application.Top?.StatusBar;
  501. }
  502. else
  503. {
  504. View t = viewToMove.SuperView;
  505. while (t is { } and not Toplevel)
  506. {
  507. t = t.SuperView;
  508. }
  509. if (t is Toplevel toplevel)
  510. {
  511. statusVisible = toplevel.StatusBar?.Visible == true;
  512. statusBar = toplevel.StatusBar;
  513. }
  514. }
  515. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  516. {
  517. maxDimension = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  518. }
  519. else
  520. {
  521. maxDimension = statusVisible ? viewToMove.SuperView.Viewport.Height - 1 : viewToMove.SuperView.Viewport.Height;
  522. }
  523. if (superView?.Margin is { } && superView == viewToMove?.SuperView)
  524. {
  525. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  526. }
  527. ny = Math.Min (ny, maxDimension);
  528. if (viewToMove?.Frame.Height <= maxDimension)
  529. {
  530. ny = ny + viewToMove.Frame.Height > maxDimension
  531. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  532. : ny;
  533. if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  534. {
  535. ny = Math.Max (viewToMove.Frame.Bottom, 0);
  536. }
  537. }
  538. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  539. return superView;
  540. }
  541. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  542. /// <remarks>
  543. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  544. /// otherwise changed.
  545. /// </remarks>
  546. public event EventHandler<LayoutEventArgs> LayoutComplete;
  547. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  548. /// <remarks>
  549. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  550. /// otherwise changed.
  551. /// </remarks>
  552. public event EventHandler<LayoutEventArgs> LayoutStarted;
  553. /// <summary>
  554. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in response to
  555. /// the container view or terminal resizing.
  556. /// </summary>
  557. /// <remarks>
  558. /// <para>
  559. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  560. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  561. /// </para>
  562. /// <para>Raises the <see cref="LayoutComplete"/> event) before it returns.</para>
  563. /// </remarks>
  564. public virtual void LayoutSubviews ()
  565. {
  566. if (!IsInitialized)
  567. {
  568. Debug.WriteLine ($"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}");
  569. }
  570. if (!LayoutNeeded)
  571. {
  572. return;
  573. }
  574. CheckDimAuto ();
  575. var contentSize = ContentSize.GetValueOrDefault ();
  576. OnLayoutStarted (new (contentSize));
  577. LayoutAdornments ();
  578. SetTextFormatterSize ();
  579. // Sort out the dependencies of the X, Y, Width, Height properties
  580. HashSet<View> nodes = new ();
  581. HashSet<(View, View)> edges = new ();
  582. CollectAll (this, ref nodes, ref edges);
  583. List<View> ordered = TopologicalSort (SuperView, nodes, edges);
  584. foreach (View v in ordered)
  585. {
  586. LayoutSubview (v, contentSize);
  587. }
  588. // If the 'to' is rooted to 'from' it's a special-case.
  589. // Use LayoutSubview with the Frame of the 'from'.
  590. if (SuperView is { } && GetTopSuperView () is { } && LayoutNeeded && edges.Count > 0)
  591. {
  592. foreach ((View from, View to) in edges)
  593. {
  594. LayoutSubview (to, from.ContentSize.GetValueOrDefault ());
  595. }
  596. }
  597. LayoutNeeded = false;
  598. OnLayoutComplete (new (contentSize));
  599. }
  600. private void LayoutSubview (View v, Size contentSize)
  601. {
  602. // BUGBUG: Calling SetRelativeLayout before LayoutSubviews is problematic. Need to resolve.
  603. v.SetRelativeLayout (contentSize);
  604. v.LayoutSubviews ();
  605. v.LayoutNeeded = false;
  606. }
  607. /// <summary>Indicates that the view does not need to be laid out.</summary>
  608. protected void ClearLayoutNeeded () { LayoutNeeded = false; }
  609. /// <summary>
  610. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views
  611. /// have been laid out.
  612. /// </summary>
  613. internal virtual void OnLayoutComplete (LayoutEventArgs args) { LayoutComplete?.Invoke (this, args); }
  614. // BUGBUG: We need an API/event that is called from SetRelativeLayout instead of/in addition to
  615. // BUGBUG: OnLayoutStarted which is called from LayoutSubviews.
  616. /// <summary>
  617. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews
  618. /// have been laid out.
  619. /// </summary>
  620. internal virtual void OnLayoutStarted (LayoutEventArgs args) { LayoutStarted?.Invoke (this, args); }
  621. /// <summary>
  622. /// Called whenever the view needs to be resized. This is called whenever <see cref="Frame"/>,
  623. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or <see cref="View.Height"/> changes.
  624. /// </summary>
  625. /// <remarks>
  626. /// <para>
  627. /// Determines the relative bounds of the <see cref="View"/> and its <see cref="Frame"/>s, and then calls
  628. /// <see cref="SetRelativeLayout"/> to update the view.
  629. /// </para>
  630. /// </remarks>
  631. internal void OnResizeNeeded ()
  632. {
  633. // TODO: Identify a real-world use-case where this API should be virtual.
  634. // TODO: Until then leave it `internal` and non-virtual
  635. // First try SuperView.Viewport, then Application.Top, then Driver.Viewport.
  636. // Finally, if none of those are valid, use int.MaxValue (for Unit tests).
  637. Size? contentSize = SuperView is { IsInitialized: true } ? SuperView.ContentSize :
  638. Application.Top is { } && Application.Top != this && Application.Top.IsInitialized ? Application.Top.ContentSize :
  639. Application.Driver?.Screen.Size ?? new (int.MaxValue, int.MaxValue);
  640. SetTextFormatterSize ();
  641. SetRelativeLayout (contentSize.GetValueOrDefault ());
  642. if (IsInitialized)
  643. {
  644. LayoutAdornments ();
  645. }
  646. SetNeedsDisplay ();
  647. SetNeedsLayout ();
  648. }
  649. internal bool LayoutNeeded { get; private set; } = true;
  650. /// <summary>
  651. /// Sets the internal <see cref="LayoutNeeded"/> flag for this View and all of it's subviews and it's SuperView.
  652. /// The main loop will call SetRelativeLayout and LayoutSubviews for any view with <see cref="LayoutNeeded"/> set.
  653. /// </summary>
  654. internal void SetNeedsLayout ()
  655. {
  656. if (LayoutNeeded)
  657. {
  658. return;
  659. }
  660. LayoutNeeded = true;
  661. foreach (View view in Subviews)
  662. {
  663. view.SetNeedsLayout ();
  664. }
  665. TextFormatter.NeedsFormat = true;
  666. SuperView?.SetNeedsLayout ();
  667. }
  668. /// <summary>
  669. /// Adjusts <see cref="Frame"/> given the SuperView's ContentSize (nominally the same as
  670. /// <c>this.SuperView.ContentSize</c>)
  671. /// and the position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  672. /// <see cref="Height"/>).
  673. /// </summary>
  674. /// <remarks>
  675. /// <para>
  676. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  677. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  678. /// are left unchanged.
  679. /// </para>
  680. /// </remarks>
  681. /// <param name="superviewContentSize">
  682. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.ContentSize</c>).
  683. /// </param>
  684. internal void SetRelativeLayout (Size? superviewContentSize)
  685. {
  686. Debug.Assert (_x is { });
  687. Debug.Assert (_y is { });
  688. Debug.Assert (_width is { });
  689. Debug.Assert (_height is { });
  690. if (superviewContentSize is null)
  691. {
  692. return;
  693. }
  694. CheckDimAuto ();
  695. int newX = _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.LeftPos, from, ref nNodes, ref nEdges);
  781. CollectPos (pc.RightPos, 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).LeftPos, name);
  942. ThrowInvalid (view, (pos as Pos.PosCombine).RightPos, 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. }