View.Layout.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  1. #nullable enable
  2. using System.Diagnostics;
  3. namespace Terminal.Gui.ViewBase;
  4. public partial class View // Layout APIs
  5. {
  6. #region Frame/Position/Dimension
  7. /// <summary>
  8. /// Indicates whether the specified SuperView-relative coordinates are within the View's <see cref="Frame"/>.
  9. /// </summary>
  10. /// <param name="location">SuperView-relative coordinate</param>
  11. /// <returns><see langword="true"/> if the specified SuperView-relative coordinates are within the View.</returns>
  12. public virtual bool Contains (in Point location) { return Frame.Contains (location); }
  13. private Rectangle? _frame;
  14. /// <summary>Gets or sets the absolute location and dimension of the view.</summary>
  15. /// <value>
  16. /// The rectangle describing absolute location and dimension of the view, in coordinates relative to the
  17. /// <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>.
  18. /// </value>
  19. /// <remarks>
  20. /// <para>
  21. /// See the View Layout Deep Dive for more information:
  22. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  23. /// </para>
  24. /// <para>
  25. /// Frame is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="GetContentSize ()"/>
  26. /// .
  27. /// </para>
  28. /// <para>
  29. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> to
  30. /// absolute values.
  31. /// </para>
  32. /// <para>
  33. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDraw"/> to be set,
  34. /// resulting in the
  35. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  36. /// </para>
  37. /// </remarks>
  38. public Rectangle Frame
  39. {
  40. get
  41. {
  42. if (NeedsLayout)
  43. {
  44. //Debug.WriteLine("Frame_get with _layoutNeeded");
  45. }
  46. return _frame ?? Rectangle.Empty;
  47. }
  48. set
  49. {
  50. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  51. if (SetFrame (value with { Width = Math.Max (value.Width, 0), Height = Math.Max (value.Height, 0) }))
  52. {
  53. // If Frame gets set, set all Pos/Dim to Absolute values.
  54. _x = _frame!.Value.X;
  55. _y = _frame!.Value.Y;
  56. _width = _frame!.Value.Width;
  57. _height = _frame!.Value.Height;
  58. // Explicit layout is ok here because we are setting the Frame directly.
  59. Layout ();
  60. }
  61. }
  62. }
  63. /// <summary>
  64. /// INTERNAL API - Sets _frame, calls SetsNeedsLayout, and raises OnViewportChanged/ViewportChanged
  65. /// </summary>
  66. /// <param name="frame"></param>
  67. /// <returns><see langword="true"/> if the frame was changed.</returns>
  68. private bool SetFrame (in Rectangle frame)
  69. {
  70. if (_frame == frame)
  71. {
  72. return false;
  73. }
  74. var oldViewport = Rectangle.Empty;
  75. if (IsInitialized)
  76. {
  77. oldViewport = Viewport;
  78. }
  79. // This is the only place where _frame should be set directly. Use Frame = or SetFrame instead.
  80. _frame = frame;
  81. SetAdornmentFrames ();
  82. SetNeedsDraw ();
  83. SetNeedsLayout ();
  84. // BUGBUG: When SetFrame is called from Frame_set, this event gets raised BEFORE OnResizeNeeded. Is that OK?
  85. OnFrameChanged (in frame);
  86. FrameChanged?.Invoke (this, new (in frame));
  87. if (oldViewport != Viewport)
  88. {
  89. RaiseViewportChangedEvent (oldViewport);
  90. }
  91. return true;
  92. }
  93. /// <summary>
  94. /// Called when <see cref="Frame"/> changes.
  95. /// </summary>
  96. /// <param name="frame">The new Frame.</param>
  97. protected virtual void OnFrameChanged (in Rectangle frame) { }
  98. /// <summary>
  99. /// Raised when the <see cref="Frame"/> changes. This event is raised after the <see cref="Frame"/> has been
  100. /// updated.
  101. /// </summary>
  102. public event EventHandler<EventArgs<Rectangle>>? FrameChanged;
  103. /// <summary>Gets the <see cref="Frame"/> with a screen-relative location.</summary>
  104. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  105. public virtual Rectangle FrameToScreen ()
  106. {
  107. Rectangle screen = Frame;
  108. View? current = SuperView;
  109. while (current is { })
  110. {
  111. if (current is Adornment adornment)
  112. {
  113. // Adornments don't have SuperViews; use Adornment.FrameToScreen override
  114. // which will give us the screen coordinates of the parent
  115. Rectangle parentScreen = adornment.FrameToScreen ();
  116. // Now add our Frame location
  117. parentScreen.Offset (screen.X, screen.Y);
  118. return parentScreen with { Size = Frame.Size };
  119. }
  120. Point viewportOffset = current.GetViewportOffsetFromFrame ();
  121. viewportOffset.Offset (current.Frame.X - current.Viewport.X, current.Frame.Y - current.Viewport.Y);
  122. screen.X += viewportOffset.X;
  123. screen.Y += viewportOffset.Y;
  124. current = current.SuperView;
  125. }
  126. return screen;
  127. }
  128. /// <summary>
  129. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means relative to the
  130. /// View's <see cref="SuperView"/>'s <see cref="Viewport"/>.
  131. /// </summary>
  132. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Viewport"/>.</returns>
  133. /// <param name="location">Screen-relative coordinate.</param>
  134. public virtual Point ScreenToFrame (in Point location)
  135. {
  136. if (SuperView is null)
  137. {
  138. return new (location.X - Frame.X, location.Y - Frame.Y);
  139. }
  140. Point superViewViewportOffset = SuperView.GetViewportOffsetFromFrame ();
  141. superViewViewportOffset.Offset (-SuperView.Viewport.X, -SuperView.Viewport.Y);
  142. Point frame = location;
  143. frame.Offset (-superViewViewportOffset.X, -superViewViewportOffset.Y);
  144. frame = SuperView.ScreenToFrame (frame);
  145. frame.Offset (-Frame.X, -Frame.Y);
  146. return frame;
  147. }
  148. // helper for X, Y, Width, Height setters to ensure consistency
  149. private void PosDimSet ()
  150. {
  151. SetNeedsLayout ();
  152. if (_x is PosAbsolute && _y is PosAbsolute && _width is DimAbsolute && _height is DimAbsolute)
  153. {
  154. // Implicit layout is ok here because all Pos/Dim are Absolute values.
  155. Layout ();
  156. if (SuperView is { } || this is Adornment { Parent: null })
  157. {
  158. // Ensure the next Application iteration tries to layout again
  159. SetNeedsLayout ();
  160. }
  161. }
  162. }
  163. private Pos _x = Pos.Absolute (0);
  164. /// <summary>Gets or sets the X position for the view (the column).</summary>
  165. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  166. /// <remarks>
  167. /// <para>
  168. /// See the View Layout Deep Dive for more information:
  169. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  170. /// </para>
  171. /// <para>
  172. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  173. /// <see cref="GetContentSize ()"/>.
  174. /// </para>
  175. /// <para>
  176. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  177. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  178. /// </para>
  179. /// <para>
  180. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDraw"/> to be set,
  181. /// resulting in the
  182. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  183. /// </para>
  184. /// <para>
  185. /// Changing this property will cause <see cref="Frame"/> to be updated.
  186. /// </para>
  187. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  188. /// </remarks>
  189. public Pos X
  190. {
  191. get => VerifyIsInitialized (_x, nameof (X));
  192. set
  193. {
  194. if (Equals (_x, value))
  195. {
  196. return;
  197. }
  198. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  199. PosDimSet ();
  200. }
  201. }
  202. private Pos _y = Pos.Absolute (0);
  203. /// <summary>Gets or sets the Y position for the view (the row).</summary>
  204. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  205. /// <remarks>
  206. /// <para>
  207. /// See the View Layout Deep Dive for more information:
  208. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  209. /// </para>
  210. /// <para>
  211. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by
  212. /// <see cref="GetContentSize ()"/>.
  213. /// </para>
  214. /// <para>
  215. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  216. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  217. /// </para>
  218. /// <para>
  219. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDraw"/> to be set,
  220. /// resulting in the
  221. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  222. /// </para>
  223. /// <para>
  224. /// Changing this property will cause <see cref="Frame"/> to be updated.
  225. /// </para>
  226. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  227. /// </remarks>
  228. public Pos Y
  229. {
  230. get => VerifyIsInitialized (_y, nameof (Y));
  231. set
  232. {
  233. if (Equals (_y, value))
  234. {
  235. return;
  236. }
  237. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  238. PosDimSet ();
  239. }
  240. }
  241. private Dim? _height = Dim.Absolute (0);
  242. /// <summary>Gets or sets the height dimension of the view.</summary>
  243. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  244. /// <remarks>
  245. /// <para>
  246. /// See the View Layout Deep Dive for more information:
  247. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  248. /// </para>
  249. /// <para>
  250. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  251. /// <see cref="GetContentSize ()"/> .
  252. /// </para>
  253. /// <para>
  254. /// If set to a relative value (e.g. <see cref="DimFill"/>) the value is indeterminate until the view has been
  255. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  256. /// </para>
  257. /// <para>
  258. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDraw"/> to be set,
  259. /// resulting in the
  260. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  261. /// </para>
  262. /// <para>
  263. /// Changing this property will cause <see cref="Frame"/> to be updated.
  264. /// </para>
  265. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  266. /// </remarks>
  267. public Dim? Height
  268. {
  269. get => VerifyIsInitialized (_height, nameof (Height));
  270. set
  271. {
  272. if (Equals (_height, value))
  273. {
  274. return;
  275. }
  276. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  277. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  278. TextFormatter.ConstrainToHeight = null;
  279. PosDimSet ();
  280. }
  281. }
  282. private Dim? _width = Dim.Absolute (0);
  283. /// <summary>Gets or sets the width dimension of the view.</summary>
  284. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  285. /// <remarks>
  286. /// <para>
  287. /// See the View Layout Deep Dive for more information:
  288. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  289. /// </para>
  290. /// <para>
  291. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by
  292. /// <see cref="GetContentSize ()"/>
  293. /// .
  294. /// </para>
  295. /// <para>
  296. /// If set to a relative value (e.g. <see cref="DimFill"/>) the value is indeterminate until the view has been
  297. /// laid out (e.g. <see cref="Layout(System.Drawing.Size)"/> has been called).
  298. /// </para>
  299. /// <para>
  300. /// Changing this property will result in <see cref="NeedsLayout"/> and <see cref="NeedsDraw"/> to be set,
  301. /// resulting in the
  302. /// view being laid out and redrawn as appropriate in the next iteration of the <see cref="MainLoop"/>.
  303. /// </para>
  304. /// <para>
  305. /// Changing this property will cause <see cref="Frame"/> to be updated.
  306. /// </para>
  307. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  308. /// </remarks>
  309. public Dim? Width
  310. {
  311. get => VerifyIsInitialized (_width, nameof (Width));
  312. set
  313. {
  314. if (Equals (_width, value))
  315. {
  316. return;
  317. }
  318. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  319. // Reset TextFormatter - Will be recalculated in SetTextFormatterSize
  320. TextFormatter.ConstrainToWidth = null;
  321. PosDimSet ();
  322. }
  323. }
  324. #endregion Frame/Position/Dimension
  325. #region Core Layout API
  326. /// <summary>
  327. /// INTERNAL API - Performs layout of the specified views within the specified content size. Called by the Application
  328. /// main loop.
  329. /// </summary>
  330. /// <param name="views">The views to layout.</param>
  331. /// <param name="contentSize">The size to bound the views by.</param>
  332. /// <returns><see langword="true"/>If any of the views needed to be laid out.</returns>
  333. internal static bool Layout (IEnumerable<View> views, Size contentSize)
  334. {
  335. var neededLayout = false;
  336. foreach (View v in views)
  337. {
  338. if (v.NeedsLayout)
  339. {
  340. neededLayout = true;
  341. v.Layout (contentSize);
  342. }
  343. }
  344. return neededLayout;
  345. }
  346. /// <summary>
  347. /// Performs layout of the view and its subviews within the specified content size.
  348. /// </summary>
  349. /// <remarks>
  350. /// <para>
  351. /// See the View Layout Deep Dive for more information:
  352. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  353. /// </para>
  354. /// <para>
  355. /// This method is intended to be called by the layout engine to
  356. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  357. /// </para>
  358. /// </remarks>
  359. /// <param name="contentSize"></param>
  360. /// <returns><see langword="false"/>If the view could not be laid out (typically because a dependencies was not ready). </returns>
  361. public bool Layout (Size contentSize)
  362. {
  363. if (SetRelativeLayout (contentSize))
  364. {
  365. LayoutSubViews ();
  366. // Debug.Assert(!NeedsLayout);
  367. return true;
  368. }
  369. return false;
  370. }
  371. /// <summary>
  372. /// Performs layout of the view and its subviews using the content size of either the <see cref="SuperView"/> or
  373. /// <see cref="Application.Screen"/>.
  374. /// </summary>
  375. /// <remarks>
  376. /// <para>
  377. /// See the View Layout Deep Dive for more information:
  378. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  379. /// </para>
  380. /// <para>
  381. /// This method is intended to be called by the layout engine to
  382. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  383. /// </para>
  384. /// </remarks>
  385. /// <returns><see langword="false"/>If the view could not be laid out (typically because dependency was not ready). </returns>
  386. public bool Layout () { return Layout (GetContainerSize ()); }
  387. /// <summary>
  388. /// Sets the position and size of this view, relative to the SuperView's ContentSize (nominally the same as
  389. /// <c>this.SuperView.GetContentSize ()</c>) based on the values of <see cref="X"/>, <see cref="Y"/>,
  390. /// <see cref="Width"/>,
  391. /// and <see cref="Height"/>.
  392. /// </summary>
  393. /// <remarks>
  394. /// <para>
  395. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  396. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  397. /// are left unchanged.
  398. /// </para>
  399. /// <para>
  400. /// This method does not arrange subviews or adornments. It is intended to be called by the layout engine to
  401. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  402. /// </para>
  403. /// <para>
  404. /// Some subviews may have SetRelativeLayout called on them as a side effect, particularly in DimAuto scenarios.
  405. /// </para>
  406. /// </remarks>
  407. /// <param name="superviewContentSize">
  408. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.GetContentSize ()</c>).
  409. /// </param>
  410. /// <returns><see langword="true"/> if successful. <see langword="false"/> means a dependent View still needs layout.</returns>
  411. public bool SetRelativeLayout (Size superviewContentSize)
  412. {
  413. Debug.Assert (_x is { });
  414. Debug.Assert (_y is { });
  415. Debug.Assert (_width is { });
  416. Debug.Assert (_height is { });
  417. CheckDimAuto ();
  418. // TODO: Should move to View.LayoutSubViews?
  419. SetTextFormatterSize ();
  420. int newX, newW, newY, newH;
  421. try
  422. {
  423. // Calculate the new X, Y, Width, and Height
  424. // If the Width or Height is Dim.Auto, calculate the Width or Height first. Otherwise, calculate the X or Y first.
  425. if (_width.Has<DimAuto> (out _))
  426. {
  427. newW = _width.Calculate (0, superviewContentSize.Width, this, Dimension.Width);
  428. newX = _x.Calculate (superviewContentSize.Width, newW, this, Dimension.Width);
  429. if (newW != Frame.Width)
  430. {
  431. // Pos.Calculate gave us a new position. We need to redo dimension
  432. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  433. }
  434. }
  435. else
  436. {
  437. newX = _x.Calculate (superviewContentSize.Width, _width, this, Dimension.Width);
  438. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  439. }
  440. if (_height.Has<DimAuto> (out _))
  441. {
  442. newH = _height.Calculate (0, superviewContentSize.Height, this, Dimension.Height);
  443. newY = _y.Calculate (superviewContentSize.Height, newH, this, Dimension.Height);
  444. if (newH != Frame.Height)
  445. {
  446. // Pos.Calculate gave us a new position. We need to redo dimension
  447. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  448. }
  449. }
  450. else
  451. {
  452. newY = _y.Calculate (superviewContentSize.Height, _height, this, Dimension.Height);
  453. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  454. }
  455. }
  456. catch (LayoutException)
  457. {
  458. //Debug.WriteLine ($"A Dim/PosFunc function threw (typically this is because a dependent View was not laid out)\n{le}.");
  459. return false;
  460. }
  461. Rectangle newFrame = new (newX, newY, newW, newH);
  462. if (Frame != newFrame)
  463. {
  464. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height
  465. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  466. SetFrame (newFrame);
  467. if (_x is PosAbsolute)
  468. {
  469. _x = Frame.X;
  470. }
  471. if (_y is PosAbsolute)
  472. {
  473. _y = Frame.Y;
  474. }
  475. if (_width is DimAbsolute)
  476. {
  477. _width = Frame.Width;
  478. }
  479. if (_height is DimAbsolute)
  480. {
  481. _height = Frame.Height;
  482. }
  483. if (!string.IsNullOrEmpty (Title))
  484. {
  485. SetTitleTextFormatterSize ();
  486. }
  487. if (SuperView is { })
  488. {
  489. SuperView?.SetNeedsDraw ();
  490. }
  491. else if (Application.TopLevels.Count == 1)
  492. {
  493. // If this is the only TopLevel, we need to redraw the screen
  494. Application.ClearScreenNextIteration = true;
  495. }
  496. }
  497. if (TextFormatter.ConstrainToWidth is null)
  498. {
  499. TextFormatter.ConstrainToWidth = GetContentSize ().Width;
  500. }
  501. if (TextFormatter.ConstrainToHeight is null)
  502. {
  503. TextFormatter.ConstrainToHeight = GetContentSize ().Height;
  504. }
  505. return true;
  506. }
  507. /// <summary>
  508. /// INTERNAL API - Causes the view's subviews and adornments to be laid out within the view's content areas. Assumes
  509. /// the view's relative layout has been set via <see cref="SetRelativeLayout"/>.
  510. /// </summary>
  511. /// <remarks>
  512. /// <para>
  513. /// See the View Layout Deep Dive for more information:
  514. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  515. /// </para>
  516. /// <para>
  517. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  518. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  519. /// </para>
  520. /// <para>Raises the <see cref="SubViewsLaidOut"/> event before it returns.</para>
  521. /// </remarks>
  522. internal void LayoutSubViews ()
  523. {
  524. if (!NeedsLayout)
  525. {
  526. return;
  527. }
  528. CheckDimAuto ();
  529. Size contentSize = GetContentSize ();
  530. OnSubViewLayout (new (contentSize));
  531. SubViewLayout?.Invoke (this, new (contentSize));
  532. // The Adornments already have their Frame's set by SetRelativeLayout so we call LayoutSubViews vs. Layout here.
  533. if (Margin is { SubViews.Count: > 0 })
  534. {
  535. Margin.LayoutSubViews ();
  536. }
  537. if (Border is { SubViews.Count: > 0 })
  538. {
  539. Border.LayoutSubViews ();
  540. }
  541. if (Padding is { SubViews.Count: > 0 })
  542. {
  543. Padding.LayoutSubViews ();
  544. }
  545. // Sort out the dependencies of the X, Y, Width, Height properties
  546. HashSet<View> nodes = new ();
  547. HashSet<(View, View)> edges = new ();
  548. CollectAll (this, ref nodes, ref edges);
  549. List<View> ordered = TopologicalSort (SuperView!, nodes, edges);
  550. List<View> redo = new ();
  551. foreach (View v in ordered)
  552. {
  553. if (!v.Layout (contentSize))
  554. {
  555. redo.Add (v);
  556. }
  557. }
  558. var layoutStillNeeded = false;
  559. if (redo.Count > 0)
  560. {
  561. foreach (View v in ordered)
  562. {
  563. if (!v.Layout (contentSize))
  564. {
  565. layoutStillNeeded = true;
  566. }
  567. }
  568. }
  569. // If the 'to' is rooted to 'from' it's a special-case.
  570. // Use Layout with the ContentSize of the 'from'.
  571. // See the Nested_SubViews_Ref_Topmost_SuperView unit test
  572. if (edges.Count > 0 && GetTopSuperView () is { })
  573. {
  574. foreach ((View from, View to) in edges)
  575. {
  576. // QUESTION: Do we test this with adornments well enough?
  577. to.Layout (from.GetContentSize ());
  578. }
  579. }
  580. NeedsLayout = layoutStillNeeded;
  581. OnSubViewsLaidOut (new (contentSize));
  582. SubViewsLaidOut?.Invoke (this, new (contentSize));
  583. }
  584. /// <summary>
  585. /// Called from <see cref="LayoutSubViews"/> before any subviews
  586. /// have been laid out.
  587. /// </summary>
  588. /// <remarks>
  589. /// Override to perform tasks when the layout is changing.
  590. /// </remarks>
  591. protected virtual void OnSubViewLayout (LayoutEventArgs args) { }
  592. /// <summary>
  593. /// Raised by <see cref="LayoutSubViews"/> before any subviews
  594. /// have been laid out.
  595. /// </summary>
  596. /// <remarks>
  597. /// Subscribe to this event to perform tasks when the layout is changing.
  598. /// </remarks>
  599. public event EventHandler<LayoutEventArgs>? SubViewLayout;
  600. /// <summary>
  601. /// Called from <see cref="LayoutSubViews"/> after all sub-views
  602. /// have been laid out.
  603. /// </summary>
  604. /// <remarks>
  605. /// Override to perform tasks after the <see cref="View"/> has been resized or the layout has
  606. /// otherwise changed.
  607. /// </remarks>
  608. protected virtual void OnSubViewsLaidOut (LayoutEventArgs args) { }
  609. /// <summary>Raised after all sub-views have been laid out.</summary>
  610. /// <remarks>
  611. /// Subscribe to this event to perform tasks after the <see cref="View"/> has been resized or the layout has
  612. /// otherwise changed.
  613. /// </remarks>
  614. public event EventHandler<LayoutEventArgs>? SubViewsLaidOut;
  615. #endregion Core Layout API
  616. #region NeedsLayout
  617. // We expose no setter for this to ensure that the ONLY place it's changed is in SetNeedsLayout
  618. /// <summary>
  619. /// Indicates the View's Frame or the layout of the View's subviews (including Adornments) have
  620. /// changed since the last time the View was laid out.
  621. /// </summary>
  622. /// <remarks>
  623. /// <para>
  624. /// Used to prevent <see cref="Layout()"/> from needlessly computing
  625. /// layout.
  626. /// </para>
  627. /// </remarks>
  628. /// <value>
  629. /// <see langword="true"/> if layout is needed.
  630. /// </value>
  631. public bool NeedsLayout { get; private set; } = true;
  632. /// <summary>
  633. /// Sets <see cref="NeedsLayout"/> to return <see langword="true"/>, indicating this View and all of it's subviews
  634. /// (including adornments) need to be laid out in the next Application iteration.
  635. /// </summary>
  636. /// <remarks>
  637. /// <para>
  638. /// The <see cref="MainLoop"/> will cause <see cref="Layout()"/> to be called on the next
  639. /// <see cref="Application.Iteration"/> so there is normally no reason to call see <see cref="Layout()"/>.
  640. /// </para>
  641. /// </remarks>
  642. public void SetNeedsLayout ()
  643. {
  644. NeedsLayout = true;
  645. if (Margin is { SubViews.Count: > 0 })
  646. {
  647. Margin.SetNeedsLayout ();
  648. }
  649. if (Border is { SubViews.Count: > 0 })
  650. {
  651. Border.SetNeedsLayout ();
  652. }
  653. if (Padding is { SubViews.Count: > 0 })
  654. {
  655. Padding.SetNeedsLayout ();
  656. }
  657. // TODO: Optimize this - see Setting_Thickness_Causes_Adornment_SubView_Layout
  658. // Use a stack to avoid recursion
  659. Stack<View> stack = new (SubViews);
  660. while (stack.Count > 0)
  661. {
  662. View current = stack.Pop ();
  663. if (!current.NeedsLayout)
  664. {
  665. current.NeedsLayout = true;
  666. if (current.Margin is { SubViews.Count: > 0 })
  667. {
  668. current.Margin.SetNeedsLayout ();
  669. }
  670. if (current.Border is { SubViews.Count: > 0 })
  671. {
  672. current.Border.SetNeedsLayout ();
  673. }
  674. if (current.Padding is { SubViews.Count: > 0 })
  675. {
  676. current.Padding.SetNeedsLayout ();
  677. }
  678. foreach (View subview in current.SubViews)
  679. {
  680. stack.Push (subview);
  681. }
  682. }
  683. }
  684. TextFormatter.NeedsFormat = true;
  685. if (SuperView is { NeedsLayout: false })
  686. {
  687. SuperView?.SetNeedsLayout ();
  688. }
  689. if (this is not Adornment adornment)
  690. {
  691. return;
  692. }
  693. if (adornment.Parent is { NeedsLayout: false })
  694. {
  695. adornment.Parent?.SetNeedsLayout ();
  696. }
  697. }
  698. #endregion NeedsLayout
  699. #region Topological Sort
  700. /// <summary>
  701. /// INTERNAL API - Collects all views and their dependencies from a given starting view for layout purposes. Used by
  702. /// <see cref="TopologicalSort"/> to create an ordered list of views to layout.
  703. /// </summary>
  704. /// <param name="from">The starting view from which to collect dependencies.</param>
  705. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  706. /// <param name="nEdges">
  707. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  708. /// indicating a dependency.
  709. /// </param>
  710. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  711. {
  712. foreach (View? v in from.InternalSubViews)
  713. {
  714. nNodes.Add (v);
  715. CollectPos (v.X, v, ref nNodes, ref nEdges);
  716. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  717. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  718. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  719. }
  720. }
  721. /// <summary>
  722. /// INTERNAL API - Collects dimension (where Width or Height is `DimView`) dependencies for a given view.
  723. /// </summary>
  724. /// <param name="dim">The dimension (width or height) to collect dependencies for.</param>
  725. /// <param name="from">The view for which to collect dimension dependencies.</param>
  726. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  727. /// <param name="nEdges">
  728. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  729. /// indicating a dependency.
  730. /// </param>
  731. internal void CollectDim (Dim? dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  732. {
  733. if (dim!.Has (out DimView dv))
  734. {
  735. if (dv.Target != this)
  736. {
  737. nEdges.Add ((dv.Target!, from));
  738. }
  739. }
  740. if (dim!.Has (out DimCombine dc))
  741. {
  742. CollectDim (dc.Left, from, ref nNodes, ref nEdges);
  743. CollectDim (dc.Right, from, ref nNodes, ref nEdges);
  744. }
  745. }
  746. /// <summary>
  747. /// INTERNAL API - Collects position (where X or Y is `PosView`) dependencies for a given view.
  748. /// </summary>
  749. /// <param name="pos">The position (X or Y) to collect dependencies for.</param>
  750. /// <param name="from">The view for which to collect position dependencies.</param>
  751. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  752. /// <param name="nEdges">
  753. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  754. /// indicating a dependency.
  755. /// </param>
  756. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  757. {
  758. // TODO: Use Pos.Has<T> instead.
  759. switch (pos)
  760. {
  761. case PosView pv:
  762. Debug.Assert (pv.Target is { });
  763. if (pv.Target != this)
  764. {
  765. nEdges.Add ((pv.Target!, from));
  766. }
  767. return;
  768. case PosCombine pc:
  769. CollectPos (pc.Left, from, ref nNodes, ref nEdges);
  770. CollectPos (pc.Right, from, ref nNodes, ref nEdges);
  771. break;
  772. }
  773. }
  774. // https://en.wikipedia.org/wiki/Topological_sorting
  775. internal static List<View> TopologicalSort (
  776. View superView,
  777. IEnumerable<View> nodes,
  778. ICollection<(View From, View To)> edges
  779. )
  780. {
  781. List<View> result = new ();
  782. // Set of all nodes with no incoming edges
  783. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  784. while (noEdgeNodes.Any ())
  785. {
  786. // remove a node n from S
  787. View n = noEdgeNodes.First ();
  788. noEdgeNodes.Remove (n);
  789. // add n to tail of L
  790. if (n != superView)
  791. {
  792. result.Add (n);
  793. }
  794. // for each node m with an edge e from n to m do
  795. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  796. {
  797. View m = e.To;
  798. // remove edge e from the graph
  799. edges.Remove (e);
  800. // if m has no other incoming edges then
  801. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  802. {
  803. // insert m into S
  804. noEdgeNodes.Add (m);
  805. }
  806. }
  807. }
  808. if (!edges.Any ())
  809. {
  810. return result;
  811. }
  812. foreach ((View from, View to) in edges)
  813. {
  814. if (from == to)
  815. {
  816. // if not yet added to the result, add it and remove from edge
  817. if (result.Find (v => v == from) is null)
  818. {
  819. result.Add (from);
  820. }
  821. edges.Remove ((from, to));
  822. }
  823. else if (from.SuperView == to.SuperView)
  824. {
  825. // if 'from' is not yet added to the result, add it
  826. if (result.Find (v => v == from) is null)
  827. {
  828. result.Add (from);
  829. }
  830. // if 'to' is not yet added to the result, add it
  831. if (result.Find (v => v == to) is null)
  832. {
  833. result.Add (to);
  834. }
  835. // remove from edge
  836. edges.Remove ((from, to));
  837. }
  838. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  839. {
  840. if (ReferenceEquals (from.SuperView, to))
  841. {
  842. throw new LayoutException (
  843. $"ComputedLayout for \"{superView}\": \"{to}\" "
  844. + $"references a SubView (\"{from}\")."
  845. );
  846. }
  847. throw new LayoutException (
  848. $"ComputedLayout for \"{superView}\": \"{from}\" "
  849. + $"linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  850. );
  851. }
  852. }
  853. // return L (a topologically sorted order)
  854. return result;
  855. } // TopologicalSort
  856. #endregion Topological Sort
  857. #region Utilities
  858. /// <summary>
  859. /// INTERNAL API - Gets the size of the SuperView's content (nominally the same as
  860. /// the SuperView's <see cref="GetContentSize ()"/>) or the screen size if there's no SuperView.
  861. /// </summary>
  862. /// <returns></returns>
  863. private Size GetContainerSize ()
  864. {
  865. // TODO: Get rid of refs to Top
  866. Size superViewContentSize = SuperView?.GetContentSize ()
  867. ?? (Application.Top is { } && Application.Top != this && Application.Top.IsInitialized
  868. ? Application.Top.GetContentSize ()
  869. : Application.Screen.Size);
  870. return superViewContentSize;
  871. }
  872. // BUGBUG: This method interferes with Dialog/MessageBox default min/max size.
  873. // TODO: Get rid of MenuBar coupling as part of https://github.com/gui-cs/Terminal.Gui/issues/2975
  874. // TODO: Refactor / rewrite this - It's a mess
  875. /// <summary>
  876. /// Gets a new location of the <see cref="View"/> that is within the Viewport of the <paramref name="viewToMove"/>'s
  877. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  878. /// </summary>
  879. /// <remarks>
  880. /// If <paramref name="viewToMove"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  881. /// <see cref="Application.Top"/> the position will be bound by <see cref="Application.Screen"/>.
  882. /// </remarks>
  883. /// <param name="viewToMove">The View that is to be moved.</param>
  884. /// <param name="targetX">The target x location.</param>
  885. /// <param name="targetY">The target y location.</param>
  886. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  887. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  888. /// <returns>
  889. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  890. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubViews is called on the correct View.
  891. /// </returns>
  892. internal static View? GetLocationEnsuringFullVisibility (
  893. View viewToMove,
  894. int targetX,
  895. int targetY,
  896. out int nx,
  897. out int ny
  898. )
  899. {
  900. int maxDimension;
  901. View? superView;
  902. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  903. {
  904. maxDimension = Application.Screen.Width;
  905. superView = Application.Top;
  906. }
  907. else
  908. {
  909. // Use the SuperView's Viewport, not Frame
  910. maxDimension = viewToMove!.SuperView.Viewport.Width;
  911. superView = viewToMove.SuperView;
  912. }
  913. if (superView?.Margin is { } && superView == viewToMove!.SuperView)
  914. {
  915. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  916. }
  917. if (viewToMove!.Frame.Width <= maxDimension)
  918. {
  919. nx = Math.Max (targetX, 0);
  920. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  921. //if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  922. //{
  923. // nx = Math.Max (viewToMove.Frame.Right, 0);
  924. //}
  925. }
  926. else
  927. {
  928. nx = 0; //targetX;
  929. }
  930. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  931. var menuVisible = false;
  932. var statusVisible = false;
  933. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  934. {
  935. menuVisible = Application.Top?.MenuBar?.Visible == true;
  936. }
  937. else
  938. {
  939. View? t = viewToMove!.SuperView;
  940. while (t is { } and not Toplevel)
  941. {
  942. t = t.SuperView;
  943. }
  944. if (t is Toplevel topLevel)
  945. {
  946. menuVisible = topLevel.MenuBar?.Visible == true;
  947. }
  948. }
  949. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  950. {
  951. maxDimension = menuVisible ? 1 : 0;
  952. }
  953. else
  954. {
  955. maxDimension = 0;
  956. }
  957. ny = Math.Max (targetY, maxDimension);
  958. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  959. {
  960. maxDimension = statusVisible ? Application.Screen.Height - 1 : Application.Screen.Height;
  961. }
  962. else
  963. {
  964. maxDimension = statusVisible ? viewToMove!.SuperView.Viewport.Height - 1 : viewToMove!.SuperView.Viewport.Height;
  965. }
  966. if (superView?.Margin is { } && superView == viewToMove?.SuperView)
  967. {
  968. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  969. }
  970. ny = Math.Min (ny, maxDimension);
  971. if (viewToMove?.Frame.Height <= maxDimension)
  972. {
  973. ny = ny + viewToMove.Frame.Height > maxDimension
  974. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  975. : ny;
  976. //if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  977. //{
  978. // ny = Math.Max (viewToMove.Frame.Bottom, 0);
  979. //}
  980. }
  981. else
  982. {
  983. ny = 0;
  984. }
  985. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  986. return superView!;
  987. }
  988. /// <summary>
  989. /// Gets the Views that are under <paramref name="screenLocation"/>, including Adornments. The list is ordered by depth. The
  990. /// deepest
  991. /// View is at the end of the list (the top most View is at element 0).
  992. /// </summary>
  993. /// <param name="screenLocation">Screen-relative location.</param>
  994. /// <param name="excludeViewportSettingsFlags">
  995. /// If set, excludes Views that have the <see cref="ViewportSettingsFlags.Transparent"/> or <see cref="ViewportSettingsFlags.TransparentMouse"/>
  996. /// flags set in their ViewportSettings.
  997. /// </param>
  998. public static List<View?> GetViewsUnderLocation (in Point screenLocation, ViewportSettingsFlags excludeViewportSettingsFlags)
  999. {
  1000. // PopoverHost - If visible, start with it instead of Top
  1001. if (Application.Popover?.GetActivePopover () is View { Visible: true } visiblePopover)
  1002. {
  1003. // BUGBUG: We do not traverse all visible toplevels if there's an active popover. This may be a bug.
  1004. List<View?> result = [];
  1005. result.AddRange (GetViewsUnderLocation (visiblePopover, screenLocation, excludeViewportSettingsFlags));
  1006. if (result.Count > 0)
  1007. {
  1008. return result;
  1009. }
  1010. }
  1011. var checkedTop = false;
  1012. // Traverse all visible toplevels, topmost first (reverse stack order)
  1013. if (Application.TopLevels.Count > 0)
  1014. {
  1015. foreach (Toplevel toplevel in Application.TopLevels)
  1016. {
  1017. if (toplevel.Visible && toplevel.Contains (screenLocation))
  1018. {
  1019. List<View?> result = GetViewsUnderLocation (toplevel, screenLocation, excludeViewportSettingsFlags);
  1020. // Only return if the result is not empty
  1021. if (result.Count > 0)
  1022. {
  1023. return result;
  1024. }
  1025. }
  1026. if (toplevel == Application.Top)
  1027. {
  1028. checkedTop = true;
  1029. }
  1030. }
  1031. }
  1032. // Fallback: If TopLevels is empty or Top is not in TopLevels, check Top directly (for test compatibility)
  1033. if (!checkedTop && Application.Top is { Visible: true } top)
  1034. {
  1035. // For root toplevels, allow hit-testing even if location is outside bounds (for drag/move)
  1036. List<View?> result = GetViewsUnderLocation (top, screenLocation, excludeViewportSettingsFlags);
  1037. if (result.Count > 0)
  1038. {
  1039. return result;
  1040. }
  1041. }
  1042. return [];
  1043. }
  1044. /// <summary>
  1045. /// INTERNAL: Helper for GetViewsUnderLocation that starts from a given root view.
  1046. /// Gets the Views that are under <paramref name="screenLocation"/>, including Adornments. The list is ordered by depth. The
  1047. /// deepest
  1048. /// View is at the end of the list (the topmost View is at element 0).
  1049. /// </summary>
  1050. /// <param name="root"></param>
  1051. /// <param name="screenLocation">Screen-relative location.</param>
  1052. /// <param name="excludeViewportSettingsFlags">
  1053. /// If set, excludes Views that have the <see cref="ViewportSettingsFlags.Transparent"/> or <see cref="ViewportSettingsFlags.TransparentMouse"/>
  1054. /// flags set in their ViewportSettings.
  1055. /// </param>
  1056. internal static List<View?> GetViewsUnderLocation (View root, in Point screenLocation, ViewportSettingsFlags excludeViewportSettingsFlags)
  1057. {
  1058. List<View?> viewsUnderLocation = GetViewsAtLocation (root, screenLocation);
  1059. if (!excludeViewportSettingsFlags.HasFlag (ViewportSettingsFlags.Transparent) && !excludeViewportSettingsFlags.HasFlag (ViewportSettingsFlags.TransparentMouse))
  1060. {
  1061. // Only filter views if we are excluding transparent views.
  1062. return viewsUnderLocation;
  1063. }
  1064. // Remove all views that have an adornment with ViewportSettings.TransparentMouse; they are in the list
  1065. // because the point was in their adornment, and if the adornment is transparent, they should be removed.
  1066. viewsUnderLocation.RemoveAll (
  1067. v =>
  1068. {
  1069. if (v is null or Adornment)
  1070. {
  1071. return false;
  1072. }
  1073. bool? ret = null;
  1074. if (viewsUnderLocation.Contains (v.Margin)
  1075. && v.Margin!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1076. {
  1077. ret = true;
  1078. }
  1079. if (viewsUnderLocation.Contains (v.Border)
  1080. && v.Border!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1081. {
  1082. ret = true;
  1083. }
  1084. if (viewsUnderLocation.Contains (v.Padding)
  1085. && v.Padding!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1086. {
  1087. ret = true;
  1088. }
  1089. return ret is true;
  1090. });
  1091. // Now remove all views that have ViewportSettings.TransparentMouse set
  1092. viewsUnderLocation.RemoveAll (v => v!.ViewportSettings.HasFlag (excludeViewportSettingsFlags));
  1093. return viewsUnderLocation;
  1094. }
  1095. /// <summary>
  1096. /// INTERNAL: Gets ALL Views (Subviews and Adornments) in the of <see cref="SuperView"/> hierarchcy that are at
  1097. /// <paramref name="location"/>,
  1098. /// regardless of whether they will be drawn or see mouse events or not. Views with <see cref="Visible"/> set to
  1099. /// <see langword="false"/> will not be included.
  1100. /// The list is ordered by depth. The deepest View is at the end of the list (the topmost View is at element 0).
  1101. /// </summary>
  1102. /// <param name="superView">The root view from which the search for subviews begins.</param>
  1103. /// <param name="location">The screen-relative location where the search for views is focused.</param>
  1104. /// <returns>A list of views that are located under the specified point.</returns>
  1105. internal static List<View?> GetViewsAtLocation (View? superView, in Point location)
  1106. {
  1107. if (superView is null || !superView.Visible)
  1108. {
  1109. return [];
  1110. }
  1111. List<View?> result = [];
  1112. Stack<View> viewsToProcess = new ();
  1113. // Start with the superview if it contains the location
  1114. if (superView.FrameToScreen ().Contains (location))
  1115. {
  1116. viewsToProcess.Push (superView);
  1117. }
  1118. while (viewsToProcess.Count > 0)
  1119. {
  1120. View currentView = viewsToProcess.Pop ();
  1121. // Add the current view to the result
  1122. result.Add (currentView);
  1123. // Add adornments for the current view
  1124. result.AddRange (Adornment.GetViewsAtLocation (currentView.Margin, location));
  1125. result.AddRange (Adornment.GetViewsAtLocation (currentView.Border, location));
  1126. result.AddRange (Adornment.GetViewsAtLocation (currentView.Padding, location));
  1127. // Add subviews to the stack in reverse order
  1128. // This maintains the original depth-first traversal order
  1129. for (int i = currentView.InternalSubViews.Count - 1; i >= 0; i--)
  1130. {
  1131. View subview = currentView.InternalSubViews [i];
  1132. if (subview.Visible && subview.FrameToScreen ().Contains (location))
  1133. {
  1134. viewsToProcess.Push (subview);
  1135. }
  1136. }
  1137. }
  1138. return result;
  1139. }
  1140. #endregion Utilities
  1141. #region Diagnostics and Verification
  1142. // Diagnostics to highlight when X or Y is read before the view has been initialized
  1143. private Pos VerifyIsInitialized (Pos pos, string member)
  1144. {
  1145. //#if DEBUG
  1146. // if (pos.ReferencesOtherViews () && !IsInitialized)
  1147. // {
  1148. // Debug.WriteLine (
  1149. // $"WARNING: {member} = {pos} of {this} is dependent on other views and {member} "
  1150. // + $"is being accessed before the View has been initialized. This is likely a bug."
  1151. // );
  1152. // }
  1153. //#endif // DEBUG
  1154. return pos;
  1155. }
  1156. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  1157. private Dim? VerifyIsInitialized (Dim? dim, string member)
  1158. {
  1159. //#if DEBUG
  1160. // if (dim.ReferencesOtherViews () && !IsInitialized)
  1161. // {
  1162. // Debug.WriteLine (
  1163. // $"WARNING: {member} = {dim} of {this} is dependent on other views and {member} "
  1164. // + $"is being accessed before the View has been initialized. This is likely a bug."
  1165. // );
  1166. // }
  1167. //#endif // DEBUG
  1168. return dim;
  1169. }
  1170. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  1171. /// <remarks>
  1172. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  1173. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubViews"/>. If invalid
  1174. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  1175. /// thus should only be used for debugging.
  1176. /// </remarks>
  1177. public bool ValidatePosDim { get; set; }
  1178. // TODO: Move this logic into the Pos/Dim classes
  1179. /// <summary>
  1180. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  1181. /// Views dimensions.
  1182. /// </summary>
  1183. /// <exception cref="InvalidOperationException"></exception>
  1184. private void CheckDimAuto ()
  1185. {
  1186. if (!ValidatePosDim || !IsInitialized)
  1187. {
  1188. return;
  1189. }
  1190. var widthAuto = Width as DimAuto;
  1191. var heightAuto = Height as DimAuto;
  1192. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  1193. foreach (View view in SubViews)
  1194. {
  1195. if (widthAuto is { } && widthAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  1196. {
  1197. ThrowInvalid (view, view.Width, nameof (view.Width));
  1198. ThrowInvalid (view, view.X, nameof (view.X));
  1199. }
  1200. if (heightAuto is { } && heightAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  1201. {
  1202. ThrowInvalid (view, view.Height, nameof (view.Height));
  1203. ThrowInvalid (view, view.Y, nameof (view.Y));
  1204. }
  1205. }
  1206. return;
  1207. void ThrowInvalid (View view, object? checkPosDim, string name)
  1208. {
  1209. object? bad = null;
  1210. switch (checkPosDim)
  1211. {
  1212. case Pos pos and PosAnchorEnd:
  1213. break;
  1214. case Pos pos and not PosAbsolute and not PosView and not PosCombine:
  1215. bad = pos;
  1216. break;
  1217. case Pos pos and PosCombine:
  1218. // Recursively check for not Absolute or not View
  1219. ThrowInvalid (view, (pos as PosCombine)?.Left, name);
  1220. ThrowInvalid (view, (pos as PosCombine)?.Right, name);
  1221. break;
  1222. case Dim dim and DimAuto:
  1223. break;
  1224. case Dim dim and DimFill:
  1225. break;
  1226. case Dim dim and not DimAbsolute and not DimView and not DimCombine:
  1227. bad = dim;
  1228. break;
  1229. case Dim dim and DimCombine:
  1230. // Recursively check for not Absolute or not View
  1231. ThrowInvalid (view, (dim as DimCombine)?.Left, name);
  1232. ThrowInvalid (view, (dim as DimCombine)?.Right, name);
  1233. break;
  1234. }
  1235. if (bad != null)
  1236. {
  1237. throw new LayoutException (
  1238. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  1239. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  1240. );
  1241. }
  1242. }
  1243. }
  1244. #endregion Diagnostics and Verification
  1245. }