ViewLayout.cs 44 KB

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